问:
Class template in header
I have a class in which there are structures declared using template. Can't figure out how to describe class structure in the header file

.cpp file

```<code>#include <map>
#include <numeric>

class Statistics {
    private:
        std::map<int, int> *data;

        struct add_first {
            template<class Pair>
            int operator()(int value, const Pair& pair) const {
                return value + pair.first;
            }
        };

        struct add_second {
            template<class Pair>
            int operator()(int value, const Pair& pair) const {
                return value + pair.second;
            }
        };

        struct add_expectation {
            template<class Pair>
            int operator()(int value, const Pair& pair) const {
                return value + (pair.first * pair.second);
            }
        };

    public:
        Statistics(std::map<int, int> *load_data) {
            data = load_data;
        }

        double get_mean() {
            return std::accumulate((*data).begin(), (*data).end(), 0.0, add_first()) / (*data).size();
        }

        double get_expectation() {
            return std::accumulate((*data).begin(), (*data).end(), 0.0, add_expectation()) / std::accumulate((*data).begin(), (*data).end(), 0.0, add_second());
        }
};
</code>```

In the header file I'm trying to write the following code
.h file

```<code>#ifndef STATISTICS_H
#define STATISTICS_H

#include <map>

class Statistics {
    private:
        std::map<int, int> *data;
        struct add_first {
            template<class Pair>;
            int operator()(int value, const Pair& pair) const;
        };
        struct add_second {
            template<class Pair>;
            int operator()(int value, const Pair& pair) const;
        };
        struct add_expectation{
            template<class Pair>;
            int operator()(int value, const Pair& pair) const;
        };
    public:
        Statistics(std::map<int, int> *load_data);
        double get_mean();
        double get_expectation();
};

#endif
</code>```

But under this definition, compiler generates an error that the identifier Pair is not defined. What's wrong?

答:
After taking all suggentions by @Angew, there should be no error.

remove extra colon.

define class only in header files.

Title: Class template in header

Body:
I have a class in which there are structures declared using template. Can't figure out how to describe class structure in the header file

.cpp file

#include <map>
#include <numeric>

class Statistics {
    private:
        std::map<int, int> *data;

        struct add_first {
            template<class Pair>
            int operator()(int value, const Pair& pair) const {
                return value + pair.first;
            }
        };

        struct add_second {
            template<class Pair>
            int operator()(int value, const Pair& pair) const {
                return value + pair.second;
            }
        };

        struct add_expectation {
            template<class Pair>
            int operator()(int value, const Pair& pair) const {
                return value + (pair.first * pair.second);
            }
        };

    public:
        Statistics(std::map<int, int> *load_data) {
            data = load_data;
        }

        double get_mean() {
            return std::accumulate((*data).begin(), (*data).end(), 0.0, add_first()) / (*data).size();
        }

        double get_expectation() {
            return std::accumulate((*data).begin(), (*data).end(), 0.0, add_expectation()) / std::accumulate((*data).begin(), (*data).end(), 0.0, add_second());
        }
};

In the header file I'm trying to write the following code
.h file

#ifndef STATISTICS_H
#define STATISTICS_H

#include <map>

class Statistics {
    private:
        std::map<int, int> *data;
        struct add_first {
            template<class Pair>;
            int operator()(int value, const Pair& pair) const;
        };
        struct add_second {
            template<class Pair>;
            int operator()(int value, const Pair& pair) const;
        };
        struct add_expectation{
            template<class Pair>;
            int operator()(int value, const Pair& pair) const;
        };
    public:
        Statistics(std::map<int, int> *load_data);
        double get_mean();
        double get_expectation();
};

#endif

But under this definition, compiler generates an error that the identifier Pair is not defined. What's wrong?


来源: stackexchange

问:
CSS: div with background image not displaying
At this site, there is a div.social below the Online Bookings at top right of the screen.

http://imgur.com/a/QhlIL

Note: I've not been able to upload images to SO for months - always says the image is too large (> 2MB) when it is 140 KB.

For some reason .social is not displaying, nor its sub-elements:

```<code><div class="social">

  <a title="Trip Advisor" href="#" target="_blank">
  <div class="tripAdvisor"></div>
  </a>

  <a title="Facebook" href="#" target="_blank">
  <div class="facebook"></div>
  </a>

  <a title="Instagram" target="_blank" href="#">
  <div class="instagram"></div>
  </a>

  <a title="YouTube" target="_blank" href="#">
  <div class="youtube"></div>
  </a>

</div>

<style>
.headRight .tripAdvisor {
    background: url(../images/social/tripadvisor.png) no-repeat;
    width: 28px;
    height: 22px;
}
</style>
</code>```

.social is set to display: block; and there is enough room to fit the icons in.

Help appreciated.

答:
Just checked the bug on your website.

You must apply the style to the child divs of .social

```<code>.social div {
    display: inline-block;
    margin-right: 15px;
    display: inline;   // remove this line
    zoom: 1;
}
</code>```

remove the

```<code>"display: inline"
</code>```

Just keep

```<code>.social div {
    display: inline-block;
    margin-right: 15px;
    zoom: 1;
}
</code>```

from that class. Will work perfectly.

ContentLicense: CC BY-SA 3.0

Body:
At this site, there is a div.social below the Online Bookings at top right of the screen.

http://imgur.com/a/QhlIL

Note: I've not been able to upload images to SO for months - always says the image is too large (> 2MB) when it is 140 KB.

For some reason .social is not displaying, nor its sub-elements:

.social is set to display: block; and there is enough room to fit the icons in.

Help appreciated.

Body:
Just checked the bug on your website.

You must apply the style to the child divs of .social

.social div {
    display: inline-block;
    margin-right: 15px;
    display: inline;   // remove this line
    zoom: 1;
}

remove the

"display: inline"

Just keep

.social div {
    display: inline-block;
    margin-right: 15px;
    zoom: 1;
}

from that class. Will work perfectly.


问:
Control disappear when move its style to Window.Resources
So i have this Gauge control:

Gauge.xaml

```<code><Style TargetType="controlsGauge:Gauge">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="controlsGauge:Gauge">
                <Viewbox>
                    <Grid Height="200"
                          Width="200">
                        <!-- Ticks -->
                        <Line x:Name="TicksProxy"
                              Visibility="Collapsed"
                              Fill="{TemplateBinding TickBrush}" />
                        <ItemsControl ItemsSource="{TemplateBinding Ticks}"
                                      VerticalAlignment="Center"
                                      HorizontalAlignment="Center">
                            <ItemsControl.ItemsPanel>
                                <ItemsPanelTemplate>
                                    <Canvas />
                                </ItemsPanelTemplate>
                            </ItemsControl.ItemsPanel>
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <Rectangle Height="15"
                                               Width="4"
                                               Fill="{Binding Fill, ElementName=TicksProxy}">
                                        <Rectangle.RenderTransform>
                                            <TransformGroup>
                                                <TranslateTransform X="-2.5"
                                                                    Y="-95" />
                                                <RotateTransform Angle="{Binding}" />
                                            </TransformGroup>
                                        </Rectangle.RenderTransform>
                                    </Rectangle>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>

                        <!-- Scale -->
                        <Path Name="PART_Scale"
                              Stroke="{TemplateBinding ScaleBrush}"
                              StrokeThickness="{TemplateBinding ScaleWidth}" />

                        <!-- Trail -->
                        <Path Name="PART_Trail"
                              Stroke="{TemplateBinding TrailBrush}"
                              StrokeThickness="{TemplateBinding ScaleWidth}" />
                        <!-- Scale Ticks -->
                        <Line x:Name="ScaleTicksProxy"
                              Visibility="Collapsed"
                              Fill="{TemplateBinding ScaleTickBrush}"
                              X1="{TemplateBinding ScaleWidth}" />
                        <ItemsControl ItemsSource="{TemplateBinding Ticks}"
                                      VerticalAlignment="Center"
                                      HorizontalAlignment="Center">
                            <ItemsControl.ItemsPanel>
                                <ItemsPanelTemplate>
                                    <Canvas />
                                </ItemsPanelTemplate>
                            </ItemsControl.ItemsPanel>
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <Rectangle Height="{Binding X1, ElementName=ScaleTicksProxy}"
                                               Width="2"
                                               Fill="{Binding Fill, ElementName=ScaleTicksProxy}">
                                        <Rectangle.RenderTransform>
                                            <TransformGroup>
                                                <TranslateTransform X="-0.5"
                                                                    Y="-77" />
                                                <RotateTransform Angle="{Binding}" />
                                            </TransformGroup>
                                        </Rectangle.RenderTransform>
                                    </Rectangle>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>

                        <!-- Value and Unit -->
                        <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0,145,0,0">
                            <StackPanel.RenderTransform>
                                <RotateTransform Angle="0.5"/>
                            </StackPanel.RenderTransform>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Name="PART_ValueText"
                                       Foreground="Orange"
                                       FontSize="16"
                                       FontFamily="Comic Sans MS"
                                       FontWeight="SemiBold"
                                       Text="{TemplateBinding Value}"
                                       TextAlignment="Center"
                                       Margin="0 0 0 0" />
                                <TextBlock Foreground="Orange"
                                       FontSize="16"
                                       FontFamily="Comic Sans MS"
                                       FontWeight="SemiBold"
                                       Text="%"
                                       Margin="0 0 0 0" />
                            </StackPanel>
                            <TextBlock Foreground="{TemplateBinding UnitBrush}"
                                       FontSize="16"
                                       TextAlignment="Center"
                                       Text="{TemplateBinding Unit}"
                                       Margin="0" />
                        </StackPanel>

                        <!-- Needle -->
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="*" />
                                <RowDefinition Height="*" />
                            </Grid.RowDefinitions>

                            <!-- The RenderTransform is in code behind. -->
                            <Path Name="PART_Needle"
                                  Stretch="Uniform"
                                  HorizontalAlignment="Center"
                                  Fill="{TemplateBinding NeedleBrush}"
                                  Data="M 0,0 l 0,100 l 5,0 l 0,-100 l -5,0"
                                  RenderTransformOrigin="0.5,1">
                            </Path>
                        </Grid>
                    </Grid>
                </Viewbox>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

```<code>Gauge.cs

[TemplatePart(Name = NeedlePartName, Type = typeof(Path))]
[TemplatePart(Name = ScalePartName, Type = typeof(Path))]
[TemplatePart(Name = TrailPartName, Type = typeof(Path))]
[TemplatePart(Name = ValueTextPartName, Type = typeof(TextBlock))]
public class Gauge : UserControl
{
    #region Constants

    private const string NeedlePartName = "PART_Needle";

    private const string ScalePartName = "PART_Scale";

    private const string TrailPartName = "PART_Trail";

    private const string ValueTextPartName = "PART_ValueText";

    private const double Degrees2Radians = Math.PI / 180;

    #endregion Constants

    #region Dependency Property Registrations

    public static readonly DependencyProperty MinimumProperty =
        DependencyProperty.Register("Minimum", typeof(double), typeof(Gauge), new PropertyMetadata(0.0));

    public static readonly DependencyProperty MaximumProperty =
        DependencyProperty.Register("Maximum", typeof(double), typeof(Gauge), new PropertyMetadata(100.0));

    public static readonly DependencyProperty ScaleWidthProperty =
        DependencyProperty.Register("ScaleWidth", typeof(Double), typeof(Gauge), new PropertyMetadata(26.0));

    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register("Value", typeof(double), typeof(Gauge), new PropertyMetadata(0.0, OnValueChanged));

    public static readonly DependencyProperty UnitProperty =
        DependencyProperty.Register("Unit", typeof(string), typeof(Gauge), new PropertyMetadata(string.Empty));

    public static readonly DependencyProperty NeedleBrushProperty =
        DependencyProperty.Register("NeedleBrush", typeof(Brush), typeof(Gauge), new PropertyMetadata(new SolidColorBrush(Colors.OrangeRed)));

    public static readonly DependencyProperty ScaleBrushProperty =
        DependencyProperty.Register("ScaleBrush", typeof(Brush), typeof(Gauge), new PropertyMetadata(new SolidColorBrush(Colors.LightGray)));

    public static readonly DependencyProperty TickBrushProperty =
        DependencyProperty.Register("TickBrush", typeof(Brush), typeof(Gauge), new PropertyMetadata(new SolidColorBrush(Colors.DimGray)));

    public static readonly DependencyProperty TrailBrushProperty =
        DependencyProperty.Register("TrailBrush", typeof(Brush), typeof(Gauge), new PropertyMetadata(new SolidColorBrush(Colors.Orange)));

    public static readonly DependencyProperty ValueBrushProperty =
        DependencyProperty.Register("ValueBrush", typeof(Brush), typeof(Gauge), new PropertyMetadata(new SolidColorBrush(Colors.DimGray)));

    public static readonly DependencyProperty ScaleTickBrushProperty =
        DependencyProperty.Register("ScaleTickBrush", typeof(Brush), typeof(Gauge), new PropertyMetadata(new SolidColorBrush(Colors.White)));

    public static readonly DependencyProperty UnitBrushProperty =
        DependencyProperty.Register("UnitBrush", typeof(Brush), typeof(Gauge), new PropertyMetadata(new SolidColorBrush(Colors.DimGray)));

    public static readonly DependencyProperty ValueStringFormatProperty =
        DependencyProperty.Register("ValueStringFormat", typeof(string), typeof(Gauge), new PropertyMetadata("N0"));

    protected static readonly DependencyProperty ValueAngleProperty =
        DependencyProperty.Register("ValueAngle", typeof(double), typeof(Gauge), new PropertyMetadata(null));

    public static readonly DependencyProperty TicksProperty =
        DependencyProperty.Register("Ticks", typeof(IEnumerable<double>), typeof(Gauge), new PropertyMetadata(null));

    #endregion Dependency Property Registrations

    #region Constructors

    public Gauge()
    {
        this.DefaultStyleKey = typeof(Gauge);
        this.Ticks = this.getTicks();
    }

    #endregion Constructors

    #region Properties

    public double Minimum
    {
        get { return (double)GetValue(MinimumProperty); }
        set { SetValue(MinimumProperty, value); }
    }

    public double Maximum
    {
        get { return (double)GetValue(MaximumProperty); }
        set { SetValue(MaximumProperty, value); }
    }

    public Double ScaleWidth
    {
        get { return (Double)GetValue(ScaleWidthProperty); }
        set { SetValue(ScaleWidthProperty, value); }
    }

    public double Value
    {
        get { return (double)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }

    public string Unit
    {
        get { return (string)GetValue(UnitProperty); }
        set { SetValue(UnitProperty, value); }
    }

    public Brush NeedleBrush
    {
        get { return (Brush)GetValue(NeedleBrushProperty); }
        set { SetValue(NeedleBrushProperty, value); }
    }

    public Brush TrailBrush
    {
        get { return (Brush)GetValue(TrailBrushProperty); }
        set { SetValue(TrailBrushProperty, value); }
    }

    public Brush ScaleBrush
    {
        get { return (Brush)GetValue(ScaleBrushProperty); }
        set { SetValue(ScaleBrushProperty, value); }
    }

    public Brush ScaleTickBrush
    {
        get { return (Brush)GetValue(ScaleTickBrushProperty); }
        set { SetValue(ScaleTickBrushProperty, value); }
    }

    public Brush TickBrush
    {
        get { return (Brush)GetValue(TickBrushProperty); }
        set { SetValue(TickBrushProperty, value); }
    }

    public Brush ValueBrush
    {
        get { return (Brush)GetValue(ValueBrushProperty); }
        set { SetValue(ValueBrushProperty, value); }
    }

    public Brush UnitBrush
    {
        get { return (Brush)GetValue(UnitBrushProperty); }
        set { SetValue(UnitBrushProperty, value); }
    }

    public string ValueStringFormat
    {
        get { return (string)GetValue(ValueStringFormatProperty); }
        set { SetValue(ValueStringFormatProperty, value); }
    }

    public double ValueAngle
    {
        get { return (double)GetValue(ValueAngleProperty); }
        set { SetValue(ValueAngleProperty, value); }
    }

    public IEnumerable<double> Ticks
    {
        get { return (IEnumerable<double>)GetValue(TicksProperty); }
        set { SetValue(TicksProperty, value); }
    }

    #endregion Properties

    public override void OnApplyTemplate()
    {
        // Draw Scale
        var scale = this.GetTemplateChild(ScalePartName) as Path;
        if (scale != null)
        {
            var pg = new PathGeometry();
            var pf = new PathFigure();
            pf.IsClosed = false;
            var middleOfScale = 77 - this.ScaleWidth / 2;
            pf.StartPoint = this.ScalePoint(-150, middleOfScale);
            var seg = new ArcSegment();
            seg.SweepDirection = SweepDirection.Clockwise;
            seg.IsLargeArc = true;
            seg.Size = new Size(middleOfScale, middleOfScale);
            seg.Point = this.ScalePoint(150, middleOfScale);
            pf.Segments.Add(seg);
            pg.Figures.Add(pf);
            scale.Data = pg;
        }

        OnValueChanged(this, new DependencyPropertyChangedEventArgs());
        base.OnApplyTemplate();
    }

    private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        Gauge c = (Gauge)d;
        if (!Double.IsNaN(c.Value))
        {
            var middleOfScale = 77 - c.ScaleWidth / 2;
            var needle = c.GetTemplateChild(NeedlePartName) as Path;
            var valueText = c.GetTemplateChild(ValueTextPartName) as TextBlock;
            c.ValueAngle = c.ValueToAngle(c.Value);

            // Needle
            if (needle != null)
            {
                needle.RenderTransform = new RotateTransform() { Angle = c.ValueAngle };
            }

            // Trail
            var trail = c.GetTemplateChild(TrailPartName) as Path;
            if (trail != null)
            {
                if (c.ValueAngle > -146)
                {
                    trail.Visibility = Visibility.Visible;
                    var pg = new PathGeometry();
                    var pf = new PathFigure();
                    pf.IsClosed = false;
                    pf.StartPoint = c.ScalePoint(-150, middleOfScale);
                    var seg = new ArcSegment();
                    seg.SweepDirection = SweepDirection.Clockwise;
                    // We start from -150, so +30 becomes a large arc.
                    seg.IsLargeArc = c.ValueAngle > 30;
                    seg.Size = new Size(middleOfScale, middleOfScale);
                    seg.Point = c.ScalePoint(c.ValueAngle, middleOfScale);
                    pf.Segments.Add(seg);
                    pg.Figures.Add(pf);
                    trail.Data = pg;
                }
                else
                {
                    trail.Visibility = Visibility.Collapsed;
                }
            }

            // Value Text
            if (valueText != null)
            {
                valueText.Text = c.Value.ToString(c.ValueStringFormat);
            }
        }
    }

    private Point ScalePoint(double angle, double middleOfScale)
    {
        return new Point(100 + Math.Sin(Degrees2Radians * angle) * middleOfScale, 100 - Math.Cos(Degrees2Radians * angle) * middleOfScale);
    }

    private double ValueToAngle(double value)
    {
        double minAngle = -150;
        double maxAngle = 150;

        // Off-scale to the left
        if (value < this.Minimum)
        {
            return minAngle - 7.5;
        }

        // Off-scale to the right
        if (value > this.Maximum)
        {
            return maxAngle + 7.5;
        }

        double angularRange = maxAngle - minAngle;

        return (value - this.Minimum) / (this.Maximum - this.Minimum) * angularRange + minAngle;
    }

    private IEnumerable<double> getTicks()
    {
        double tickSpacing = (this.Maximum - this.Minimum) / 10;
        for (double tick = this.Minimum; tick <= this.Maximum; tick += tickSpacing)
        {
            yield return ValueToAngle(tick);
        }
    }
}
</code>```

Main XAML:

```<code>xmlns:Controllers="clr-namespace:MyApplication.Controllers"
</code>```

My controls:

```<code><Controllers:Gauge
    x:Name="gauge"
    Minimum="0"
    Maximum="100"
    NeedleBrush="Transparent"
    ScaleTickBrush="White"
    ScaleBrush="White"
    ScaleWidth="20"
    TickBrush="White"
    TrailBrush="SeaGreen"
    ValueBrush="Orange"
    ValueStringFormat="N1">
</code>```

So i want to create several styles so create this inside my Window.Resources:

```<code><Style x:Key="GaugesStyle1" TargetType="{x:Type Controllers:Gauge}">
    <Setter Property="NeedleBrush" Value="Transparent"/>
    <Setter Property="ScaleTickBrush" Value="White"/>
    <Setter Property="ScaleBrush" Value="White"/>
    <Setter Property="ScaleWidth" Value="20"/>
    <Setter Property="TickBrush" Value="White"/>
    <Setter Property="TrailBrush" Value="SeaGreen"/>
    <Setter Property="ValueBrush" Value="Orange"/>
    <Setter Property="ValueStringFormat" Value="N1"/>
    <Setter Property="VerticalAlignment" Value="Center"/>
    <Setter Property="HorizontalAlignment" Value="Center"/>
</Style>
</code>```

And changed my control:

```<code><Controllers:Gauge
    x:Name="gauge"
    Minimum="0"
    Maximum="100"
    Style="{StaticResource GaugesStyle1}">
</code>```

And now i cannot see my Gauge, it just disappear.
Any suggestions why ?

答:
Your UserControl doesn't have any default style so you need to base the Style you have defined in the window on the first Style where the template is defined.

This means that you should define the first Style in some global resource Dictionary (for example App.xaml) and give it an x:Key. You can then base the second style on the first one:

```<code><Style x:Key="GaugesStyle1" TargetType="{x:Type Controllers:Gauge}" BasedOn="{StaticResource theKeyOfTheFirstStyle}">
...
</code>```

The other option would be to re-define the entire template in GaugesStyle1 or create a custom control that actually has a default style.

Derive your Gauge class from Control and put the default Style in a ResourceDictionary called Generic.xaml in a folder called Themes at the root of your project.

Body:
So i have this Gauge control:

Gauge.xaml

Gauge.cs

[TemplatePart(Name = NeedlePartName, Type = typeof(Path))]
[TemplatePart(Name = ScalePartName, Type = typeof(Path))]
[TemplatePart(Name = TrailPartName, Type = typeof(Path))]
[TemplatePart(Name = ValueTextPartName, Type = typeof(TextBlock))]
public class Gauge : UserControl
{
    #region Constants

    private const string NeedlePartName = "PART_Needle";

    private const string ScalePartName = "PART_Scale";

    private const string TrailPartName = "PART_Trail";

    private const string ValueTextPartName = "PART_ValueText";

    private const double Degrees2Radians = Math.PI / 180;

    #endregion Constants

    #region Dependency Property Registrations

    public static readonly DependencyProperty MinimumProperty =
        DependencyProperty.Register("Minimum", typeof(double), typeof(Gauge), new PropertyMetadata(0.0));

    public static readonly DependencyProperty MaximumProperty =
        DependencyProperty.Register("Maximum", typeof(double), typeof(Gauge), new PropertyMetadata(100.0));

    public static readonly DependencyProperty ScaleWidthProperty =
        DependencyProperty.Register("ScaleWidth", typeof(Double), typeof(Gauge), new PropertyMetadata(26.0));

    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register("Value", typeof(double), typeof(Gauge), new PropertyMetadata(0.0, OnValueChanged));

    public static readonly DependencyProperty UnitProperty =
        DependencyProperty.Register("Unit", typeof(string), typeof(Gauge), new PropertyMetadata(string.Empty));

    public static readonly DependencyProperty NeedleBrushProperty =
        DependencyProperty.Register("NeedleBrush", typeof(Brush), typeof(Gauge), new PropertyMetadata(new SolidColorBrush(Colors.OrangeRed)));

    public static readonly DependencyProperty ScaleBrushProperty =
        DependencyProperty.Register("ScaleBrush", typeof(Brush), typeof(Gauge), new PropertyMetadata(new SolidColorBrush(Colors.LightGray)));

    public static readonly DependencyProperty TickBrushProperty =
        DependencyProperty.Register("TickBrush", typeof(Brush), typeof(Gauge), new PropertyMetadata(new SolidColorBrush(Colors.DimGray)));

    public static readonly DependencyProperty TrailBrushProperty =
        DependencyProperty.Register("TrailBrush", typeof(Brush), typeof(Gauge), new PropertyMetadata(new SolidColorBrush(Colors.Orange)));

    public static readonly DependencyProperty ValueBrushProperty =
        DependencyProperty.Register("ValueBrush", typeof(Brush), typeof(Gauge), new PropertyMetadata(new SolidColorBrush(Colors.DimGray)));

    public static readonly DependencyProperty ScaleTickBrushProperty =
        DependencyProperty.Register("ScaleTickBrush", typeof(Brush), typeof(Gauge), new PropertyMetadata(new SolidColorBrush(Colors.White)));

    public static readonly DependencyProperty UnitBrushProperty =
        DependencyProperty.Register("UnitBrush", typeof(Brush), typeof(Gauge), new PropertyMetadata(new SolidColorBrush(Colors.DimGray)));

    public static readonly DependencyProperty ValueStringFormatProperty =
        DependencyProperty.Register("ValueStringFormat", typeof(string), typeof(Gauge), new PropertyMetadata("N0"));

    protected static readonly DependencyProperty ValueAngleProperty =
        DependencyProperty.Register("ValueAngle", typeof(double), typeof(Gauge), new PropertyMetadata(null));

    public static readonly DependencyProperty TicksProperty =
        DependencyProperty.Register("Ticks", typeof(IEnumerable<double>), typeof(Gauge), new PropertyMetadata(null));

    #endregion Dependency Property Registrations

    #region Constructors

    public Gauge()
    {
        this.DefaultStyleKey = typeof(Gauge);
        this.Ticks = this.getTicks();
    }

    #endregion Constructors

    #region Properties

    public double Minimum
    {
        get { return (double)GetValue(MinimumProperty); }
        set { SetValue(MinimumProperty, value); }
    }

    public double Maximum
    {
        get { return (double)GetValue(MaximumProperty); }
        set { SetValue(MaximumProperty, value); }
    }

    public Double ScaleWidth
    {
        get { return (Double)GetValue(ScaleWidthProperty); }
        set { SetValue(ScaleWidthProperty, value); }
    }

    public double Value
    {
        get { return (double)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }

    public string Unit
    {
        get { return (string)GetValue(UnitProperty); }
        set { SetValue(UnitProperty, value); }
    }

    public Brush NeedleBrush
    {
        get { return (Brush)GetValue(NeedleBrushProperty); }
        set { SetValue(NeedleBrushProperty, value); }
    }

    public Brush TrailBrush
    {
        get { return (Brush)GetValue(TrailBrushProperty); }
        set { SetValue(TrailBrushProperty, value); }
    }

    public Brush ScaleBrush
    {
        get { return (Brush)GetValue(ScaleBrushProperty); }
        set { SetValue(ScaleBrushProperty, value); }
    }

    public Brush ScaleTickBrush
    {
        get { return (Brush)GetValue(ScaleTickBrushProperty); }
        set { SetValue(ScaleTickBrushProperty, value); }
    }

    public Brush TickBrush
    {
        get { return (Brush)GetValue(TickBrushProperty); }
        set { SetValue(TickBrushProperty, value); }
    }

    public Brush ValueBrush
    {
        get { return (Brush)GetValue(ValueBrushProperty); }
        set { SetValue(ValueBrushProperty, value); }
    }

    public Brush UnitBrush
    {
        get { return (Brush)GetValue(UnitBrushProperty); }
        set { SetValue(UnitBrushProperty, value); }
    }

    public string ValueStringFormat
    {
        get { return (string)GetValue(ValueStringFormatProperty); }
        set { SetValue(ValueStringFormatProperty, value); }
    }

    public double ValueAngle
    {
        get { return (double)GetValue(ValueAngleProperty); }
        set { SetValue(ValueAngleProperty, value); }
    }

    public IEnumerable<double> Ticks
    {
        get { return (IEnumerable<double>)GetValue(TicksProperty); }
        set { SetValue(TicksProperty, value); }
    }

    #endregion Properties

    public override void OnApplyTemplate()
    {
        // Draw Scale
        var scale = this.GetTemplateChild(ScalePartName) as Path;
        if (scale != null)
        {
            var pg = new PathGeometry();
            var pf = new PathFigure();
            pf.IsClosed = false;
            var middleOfScale = 77 - this.ScaleWidth / 2;
            pf.StartPoint = this.ScalePoint(-150, middleOfScale);
            var seg = new ArcSegment();
            seg.SweepDirection = SweepDirection.Clockwise;
            seg.IsLargeArc = true;
            seg.Size = new Size(middleOfScale, middleOfScale);
            seg.Point = this.ScalePoint(150, middleOfScale);
            pf.Segments.Add(seg);
            pg.Figures.Add(pf);
            scale.Data = pg;
        }

        OnValueChanged(this, new DependencyPropertyChangedEventArgs());
        base.OnApplyTemplate();
    }

    private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        Gauge c = (Gauge)d;
        if (!Double.IsNaN(c.Value))
        {
            var middleOfScale = 77 - c.ScaleWidth / 2;
            var needle = c.GetTemplateChild(NeedlePartName) as Path;
            var valueText = c.GetTemplateChild(ValueTextPartName) as TextBlock;
            c.ValueAngle = c.ValueToAngle(c.Value);

            // Needle
            if (needle != null)
            {
                needle.RenderTransform = new RotateTransform() { Angle = c.ValueAngle };
            }

            // Trail
            var trail = c.GetTemplateChild(TrailPartName) as Path;
            if (trail != null)
            {
                if (c.ValueAngle > -146)
                {
                    trail.Visibility = Visibility.Visible;
                    var pg = new PathGeometry();
                    var pf = new PathFigure();
                    pf.IsClosed = false;
                    pf.StartPoint = c.ScalePoint(-150, middleOfScale);
                    var seg = new ArcSegment();
                    seg.SweepDirection = SweepDirection.Clockwise;
                    // We start from -150, so +30 becomes a large arc.
                    seg.IsLargeArc = c.ValueAngle > 30;
                    seg.Size = new Size(middleOfScale, middleOfScale);
                    seg.Point = c.ScalePoint(c.ValueAngle, middleOfScale);
                    pf.Segments.Add(seg);
                    pg.Figures.Add(pf);
                    trail.Data = pg;
                }
                else
                {
                    trail.Visibility = Visibility.Collapsed;
                }
            }

            // Value Text
            if (valueText != null)
            {
                valueText.Text = c.Value.ToString(c.ValueStringFormat);
            }
        }
    }

    private Point ScalePoint(double angle, double middleOfScale)
    {
        return new Point(100 + Math.Sin(Degrees2Radians * angle) * middleOfScale, 100 - Math.Cos(Degrees2Radians * angle) * middleOfScale);
    }

    private double ValueToAngle(double value)
    {
        double minAngle = -150;
        double maxAngle = 150;

        // Off-scale to the left
        if (value < this.Minimum)
        {
            return minAngle - 7.5;
        }

        // Off-scale to the right
        if (value > this.Maximum)
        {
            return maxAngle + 7.5;
        }

        double angularRange = maxAngle - minAngle;

        return (value - this.Minimum) / (this.Maximum - this.Minimum) * angularRange + minAngle;
    }

    private IEnumerable<double> getTicks()
    {
        double tickSpacing = (this.Maximum - this.Minimum) / 10;
        for (double tick = this.Minimum; tick <= this.Maximum; tick += tickSpacing)
        {
            yield return ValueToAngle(tick);
        }
    }
}

Main XAML:

xmlns:Controllers="clr-namespace:MyApplication.Controllers"

My controls:

<Controllers:Gauge
    x:Name="gauge"
    Minimum="0"
    Maximum="100"
    NeedleBrush="Transparent"
    ScaleTickBrush="White"
    ScaleBrush="White"
    ScaleWidth="20"
    TickBrush="White"
    TrailBrush="SeaGreen"
    ValueBrush="Orange"
    ValueStringFormat="N1">

So i want to create several styles so create this inside my Window.Resources:

And changed my control:

<Controllers:Gauge
    x:Name="gauge"
    Minimum="0"
    Maximum="100"
    Style="{StaticResource GaugesStyle1}">

And now i cannot see my Gauge, it just disappear.
Any suggestions why ?

Body:
Your UserControl doesn't have any default style so you need to base the Style you have defined in the window on the first Style where the template is defined.

This means that you should define the first Style in some global resource Dictionary (for example App.xaml) and give it an x:Key. You can then base the second style on the first one:

<Style x:Key="GaugesStyle1" TargetType="{x:Type Controllers:Gauge}" BasedOn="{StaticResource theKeyOfTheFirstStyle}">
...

The other option would be to re-define the entire template in GaugesStyle1 or create a custom control that actually has a default style.

Derive your Gauge class from Control and put the default Style in a ResourceDictionary called Generic.xaml in a folder called Themes at the root of your project.


问:
Displaying HTML String from Model in MVC Razor View
I have a Model filed that returns an HTML string with line break BR tag, but How do I display that HTML on the browser ? The problem ins instead putting the line break, the Tag itself displaying on the UI

I tried to put the model within Html.Raw(modelItem => item.Speaking), but it never works as it expecting a string inside, and Cannot convert lambda expression to type 'string' because it is not a delegate type

Below is the code and comments what I've tried.

```<code><div>
  @{
     string strTest = "<br/>Line 1 <br/> Line 2<br>";
     @Html.Raw(strTest); //This works and display as expected
     @MvcHtmlString.Create(strTest); //This works and display as expected

     @Html.Raw(Html.DisplayFor(modelItem => item.Speaking)); //This doesn't work, its show the <br />  on the screen
     @MvcHtmlString.Create(Html.DisplayFor(modelItem => item.Speaking).ToString());   //This doent work, its show the <br />  on the screen
     @Html.Raw(modelItem => item.Speaking) //This throw error Cannot convert lambda expression to type string
    }

 </div>
</code>```

Appreciate any help or suggestions. thanks in advance!

答:
In MVC4

Instead of using  @Html.Raw(modelItem => item.Speaking)

You can use
@Html.Raw(@Model.Speaking.ToString())

It works for me and I hope this help someone else too

Body:
I have a Model filed that returns an HTML string with line break BR tag, but How do I display that HTML on the browser ? The problem ins instead putting the line break, the Tag itself displaying on the UI

I tried to put the model within Html.Raw(modelItem => item.Speaking), but it never works as it expecting a string inside, and Cannot convert lambda expression to type 'string' because it is not a delegate type

Below is the code and comments what I've tried.

  @{
     string strTest = "
Line 1
 Line 2
";
     @Html.Raw(strTest); //This works and display as expected
     @MvcHtmlString.Create(strTest); //This works and display as expected

     @Html.Raw(Html.DisplayFor(modelItem => item.Speaking)); //This doesn't work, its show the
  on the screen
     @MvcHtmlString.Create(Html.DisplayFor(modelItem => item.Speaking).ToString());   //This doent work, its show the
  on the screen
     @Html.Raw(modelItem => item.Speaking) //This throw error Cannot convert lambda expression to type string
    }

Appreciate any help or suggestions. thanks in advance!


问:
Oracle SQL: Missing identifier error in Select with Xmlagg
I am new to Oracle and hope someone here can help me with this.

I have a Select that returns the following without row aggregation:

current output

My problem here is that I can have multiple rows for certain IDs in the first column whereas I need just one row per ID, like this:

required output

Select Distinct is not an option in my case and Listag doesn't allow enough characters for the second column.

After some research I think Xmlagg is exactly what I need here but I cannot get this to work and always get an error here so I think I am writing it wrong.

Latest error:

```<code>ORA-00931: missing identifier
</code>```

Can someone show me how to write this properly ?

My query (shortened):

```<code>ALTER SESSION ENABLE PARALLEL QUERY;
SELECT
    a.Id
    , RTRIM(XMLAGG(XMLELEMENT("Details",
        (
            b.title || ' -' || c.item || ' -' || b.quantity) ORDER BY b.title)
        ).EXTRACT('//text()'), ' --- ') AS Details
    , TO_CHAR(c.total, 'FM9,990.00') AS Sum
FROM
    table1 d
/* joins */
WHERE
/* ... */
GROUP BY
    a.Id
    , b.title
    , c.item
    , b.quantity
ORDER BY
    a.Id
</code>```

Many thanks in advance.

Mike

答:
Just a few things need to be moved here and there.</p>

```<code>SELECT a.Id ,
    RTRIM(XMLAGG(XMLELEMENT("Details", b.title
    || ' -'
    || c.item
    || ' -'
    || b.quantity ,' --- ' ).EXTRACT('//text()')
ORDER BY b.title),
    ' --- ')
AS
    Details , TO_CHAR(c.total, 'FM9,990.00')
AS
    SUM FROM table1 d
    /* joins */
    WHERE
* ... */
GROUP BY
    a.Id
    , b.title
    , c.item
    , b.quantity
ORDER BY
    a.Id
</code>```

Body:
I am new to Oracle and hope someone here can help me with this.

I have a Select that returns the following without row aggregation:

current output

My problem here is that I can have multiple rows for certain IDs in the first column whereas I need just one row per ID, like this:

required output

Select Distinct is not an option in my case and Listag doesn't allow enough characters for the second column.

After some research I think Xmlagg is exactly what I need here but I cannot get this to work and always get an error here so I think I am writing it wrong.

Latest error:

ORA-00931: missing identifier

Can someone show me how to write this properly ?

My query (shortened):

ALTER SESSION ENABLE PARALLEL QUERY;
SELECT
    a.Id
    , RTRIM(XMLAGG(XMLELEMENT("Details",
        (
            b.title || ' -' || c.item || ' -' || b.quantity) ORDER BY b.title)
        ).EXTRACT('//text()'), ' --- ') AS Details
    , TO_CHAR(c.total, 'FM9,990.00') AS Sum
FROM
    table1 d
/* joins */
WHERE
/* ... */
GROUP BY
    a.Id
    , b.title
    , c.item
    , b.quantity
ORDER BY
    a.Id

Many thanks in advance.

Mike

Body:
Just a few things need to be moved here and there.

SELECT a.Id ,
    RTRIM(XMLAGG(XMLELEMENT("Details", b.title
    || ' -'
    || c.item
    || ' -'
    || b.quantity ,' --- ' ).EXTRACT('//text()')
ORDER BY b.title),
    ' --- ')
AS
    Details , TO_CHAR(c.total, 'FM9,990.00')
AS
    SUM FROM table1 d
    /* joins */
    WHERE
* ... */
GROUP BY
    a.Id
    , b.title
    , c.item
    , b.quantity
ORDER BY
    a.Id


问:
How to reset the bootstrap modal when it gets closed and open it fresh again?
I have a list box in the bootstrap modal and a button.
When the button is clicked a new button gets rendered inside a div in the modal.
When I close the modal and reopen it, the last operation performed on the modal like the button rendered earlier is still present in the modal.

How do reset the modal so that when the modal is opened again, the button is not present and user can again select the option from the list box and click on the button to render a new button and so on.

```<code><!-- Modal -->
<div
  class="modal fade"
  id="myModal"
  tabindex="-1"
  role="dialog"
  aria-labelledby="myModalLabel"
  aria-hidden="true"
>
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">
          <span aria-hidden="true">×</span
          ><span class="sr-only">Close</span>
        </button>
        <h4 class="modal-title" id="myModalLabel">Select Language</h4>
      </div>
      <div class="modal-body">
        <button type="button" class="btn" data-dismiss="modal">Close</button>
        <button type="button" class="btn" id="submit_form">Submit</button>

        <div class="modal-body1">
          <div id="placeholder-div1"></div>
        </div>
      </div>

      <div class="modal-footer">
        <script>
          $("#submit_form").on("click", function () {
            $(".modal-body1").html("<h3>test</h3>");
          });
        </script>

        <script>
          $(function () {
            $(".modal-footer").click(function () {
              $(".modal").modal("hide");
            });
          });
        </script>
      </div>
    </div>
  </div>
</div>
</code>```

-- Update ---

Why doesn't this work?

```<code><script type="text/javascript">
  $(function () {
    $("#myModal").on("hidden.bs.modal", function (e) {
      console.log("Modal hidden");
      $("#placeholder-div1").html("");
    });
  });
</script>
</code>```

答:
Sample code:</p>

```<code> $(document).on('hide.bs.modal', '#basicModal', function (e) {
        $('#basicModal').empty();
    });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a list box in the bootstrap modal and a button.
When the button is clicked a new button gets rendered inside a div in the modal.
When I close the modal and reopen it, the last operation performed on the modal like the button rendered earlier is still present in the modal.

How do reset the modal so that when the modal is opened again, the button is not present and user can again select the option from the list box and click on the button to render a new button and so on.

        <button type="button" class="close" data-dismiss="modal">
          ×Close
        </button>

Select Language

        <button type="button" class="btn" data-dismiss="modal">Close</button>
        <button type="button" class="btn" id="submit_form">Submit</button>

-- Update ---

Why doesn't this work?

Body:
Sample code:

 $(document).on('hide.bs.modal', '#basicModal', function (e) {
        $('#basicModal').empty();
    });


问:
locating jar file in $PATH environment variable for java -jar command
I want to run a simple executable jar like this:

```<code>java -jar /path/to/my/jar/myjar.jar
</code>```

However, i have to put that absolute path every time I want to run it. Is there a way to tell the OS to look for the jar in $PATH environment variable?

答:
You can also copy your jar file to /usr/bin folder, then it will work with just $ myjar.jar

Make sure your jar file has the executable bit (chmod +x myjar.jar) and copy it to /usr/bin (sudo cp myjar.jar /usr/bin/myjar.jar)

Body:
I want to run a simple executable jar like this:

java -jar /path/to/my/jar/myjar.jar

However, i have to put that absolute path every time I want to run it. Is there a way to tell the OS to look for the jar in $PATH environment variable?

ContentLicense: CC BY-SA 2.5


问:
how to select multiple columns with only one distinct column from joining two tables with all id's are UNIQUEIDENTIFIER using Nhibernate
Following is my table structure:

```<code>create table Department(
    deptid [UNIQUEIDENTIFIER] ROWGUIDCOL DEFAULT NEWSEQUENTIALID() NOT NULL CONSTRAINT Department_P_KEY PRIMARY KEY,
    departmentname varchar(100)
    )

create table Employee(
    empid [UNIQUEIDENTIFIER] ROWGUIDCOL DEFAULT NEWSEQUENTIALID() NOT NULL CONSTRAINT Employee_P_KEY PRIMARY KEY,
    name varchar(50),
    city varchar(50),
    deptid UNIQUEIDENTIFIER NOT NULL,
    foreign key(deptid) references Department(deptid) ON DELETE CASCADE ON UPDATE CASCADE
    )
</code>```

My issue is that when I select mutliple columns and apply DISTINCT on one column with all primary keys and foreign keys are UNIQUEIDENTIFIER then that time query gives error message. my query and error as follows:

```<code>select distinct(Department.deptid),min(Employee.empid) as empid
from Employee
inner join Department on Department.deptid = Employee.deptid
group by Department.deptid
</code>```

and Error message is :

Msg 8117, Level 16, State 1, Line 2 Operand data type uniqueidentifier is invalid for min operator.

But if Primary key and foreign key was int then above query will execute successfully because min function support to integer but how can I select distinct record using uniqueidentifier key.

And Following is my Nhibernate query:-

```<code>EmployeeEntity employeeEntity = new EmployeeEntity();
            employeeEntity.DepartmentMaster = new DepartmentEntity();
            ProjectionList projectionList = Projections.ProjectionList();
            projectionList.Add(Projections.Distinct(Projections.Property<EmployeeEntity>(x => x.DepartmentMaster)).WithAlias(() => employeeEntity.DepartmentMaster));
            projectionList.Add(Projections.Property<EmployeeEntity>(x => x.empid).WithAlias(() => employeeEntity.empid));

            IList<EmployeeEntity> query = null;
            query = NHSession.QueryOver<EmployeeEntity>()
            .Select(projectionList)
            .TransformUsing(Transformers.AliasToBean<EmployeeEntity>()).List<EmployeeEntity>();
</code>```

How can I execute distinct query in sql first as per above sql query?.

答:
Just convert the UniqueIdentifier to a string</p>

```<code>select distinct(Department.deptid),min(CAST(Employee.empid AS NVARCHAR(36))) as empid
from Employee
inner join Department on Department.deptid = Employee.deptid
group by Department.deptid
</code>```

Body:
Following is my table structure:

create table Department(
    deptid [UNIQUEIDENTIFIER] ROWGUIDCOL DEFAULT NEWSEQUENTIALID() NOT NULL CONSTRAINT Department_P_KEY PRIMARY KEY,
    departmentname varchar(100)
    )

create table Employee(
    empid [UNIQUEIDENTIFIER] ROWGUIDCOL DEFAULT NEWSEQUENTIALID() NOT NULL CONSTRAINT Employee_P_KEY PRIMARY KEY,
    name varchar(50),
    city varchar(50),
    deptid UNIQUEIDENTIFIER NOT NULL,
    foreign key(deptid) references Department(deptid) ON DELETE CASCADE ON UPDATE CASCADE
    )

My issue is that when I select mutliple columns and apply DISTINCT on one column with all primary keys and foreign keys are UNIQUEIDENTIFIER then that time query gives error message. my query and error as follows:

select distinct(Department.deptid),min(Employee.empid) as empid
from Employee
inner join Department on Department.deptid = Employee.deptid
group by Department.deptid

and Error message is :

Msg 8117, Level 16, State 1, Line 2 Operand data type uniqueidentifier is invalid for min operator.

But if Primary key and foreign key was int then above query will execute successfully because min function support to integer but how can I select distinct record using uniqueidentifier key.

And Following is my Nhibernate query:-

EmployeeEntity employeeEntity = new EmployeeEntity();
            employeeEntity.DepartmentMaster = new DepartmentEntity();
            ProjectionList projectionList = Projections.ProjectionList();
            projectionList.Add(Projections.Distinct(Projections.Property<EmployeeEntity>(x => x.DepartmentMaster)).WithAlias(() => employeeEntity.DepartmentMaster));
            projectionList.Add(Projections.Property<EmployeeEntity>(x => x.empid).WithAlias(() => employeeEntity.empid));

            IList<EmployeeEntity> query = null;
            query = NHSession.QueryOver<EmployeeEntity>()
            .Select(projectionList)
            .TransformUsing(Transformers.AliasToBean<EmployeeEntity>()).List<EmployeeEntity>();

How can I execute distinct query in sql first as per above sql query?.

Body:
Just convert the UniqueIdentifier to a string

select distinct(Department.deptid),min(CAST(Employee.empid AS NVARCHAR(36))) as empid
from Employee
inner join Department on Department.deptid = Employee.deptid
group by Department.deptid


问:
How can I configure a Flask API to allow for token-protected user-specific responses?
If I have a server end point that say does a simple task like initializes an API with a token that I generate client side, and then print the users account info.

Can I initialize() the API globally so the user can do other tasks after printing account info?

and

How does that affect other users initializing() and printing info if they do it at the same time?

I don't understand how this server works and any help would be great. Thank you!

答:
If I'm understanding you correctly, it sounds like the easiest way to accomplish what you're trying to do is to use the flask-login module.

You will want to create an endpoint / Flask route (for example, '/login') that the user will send a POST request to with a username (and usually also a password). When the login is successful, the user's browser will have a cookie set with a token that will allow them to access Flask routes that have a @login_required decorator attached.

In your Python code for those routes, you will be able to access the "current_user", which will allow you to tailor your response to the particular user sending the request.

This way of doing things will allow you to deal with your first question, which seems to be about saving a user's identity across requests, and it will also allow you to deal with your second question, which seems to be about the problem of having different users accessing the same endpoint while expecting different responses.


问:
Print D-Bus introspection tree
How can I print out a tree of all the available information on D-Bus?</p>

```<code>*Bus Name
    * Interface
        *Method
            *Signature
    * Interface
        *Method
            *Signature
        *Method
            *Signature
*Bus Name
    * Interface
        *Method
            *Signature
</code>```

答:
As well as D-Feet (mentioned in an earlier answer), the gdbus command line tool will allow introspection of a particular object path on a given unique or well-known bus name:

```<code>$ gdbus introspect --session --dest org.gnome.Contacts --object-path /org/gnome/Contacts
node /org/gnome/Contacts {
  interface org.freedesktop.DBus.Properties {
    methods:
      Get(in  s interface_name,
          in  s property_name,
          out v value);
      …
    signals:
      PropertiesChanged(s interface_name,
                        a{sv} changed_properties,
                        as invalidated_properties);
    properties:
  };
  …
}
</code>```

Title: Print D-Bus introspection tree

Body:
How can I print out a tree of all the available information on D-Bus?

*Bus Name
    * Interface
        *Method
            *Signature
    * Interface
        *Method
            *Signature
        *Method
            *Signature
*Bus Name
    * Interface
        *Method
            *Signature

Body:
As well as D-Feet (mentioned in an earlier answer), the gdbus command line tool will allow introspection of a particular object path on a given unique or well-known bus name:

$ gdbus introspect --session --dest org.gnome.Contacts --object-path /org/gnome/Contacts
node /org/gnome/Contacts {
  interface org.freedesktop.DBus.Properties {
    methods:
      Get(in  s interface_name,
          in  s property_name,
          out v value);
      …
    signals:
      PropertiesChanged(s interface_name,
                        a{sv} changed_properties,
                        as invalidated_properties);
    properties:
  };
  …
}


问:
CSS Hover on a div to show another div not working
I'm trying to change the opacity of a div when I hover on another div, but it isn't working at all. Here's the HTML:

.chatdate {
  padding-top: 10px;
  opacity: 0.5;
  transition: opacity 1s ease-in-out;
}

.workstream-comment:hover .chatdate {
  background: red;
  opacity: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-lg-12">
  <div class="row">
    <div class="col-lg-10">
      <div class="workstream-comment">
        ...
      </div>
    </div>
    <div class="col-lg-2">
      <div class="chatdate text-center">
        <h6>15/07/2017</h6>
        <br>
        <h1>11:07</h1>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-lg-10">
      <div class="workstream-comment">
        ...
      </div>
    </div>
    <div class="col-lg-2">
      <div class="chatdate text-center">
        <h6>15/07/2017</h6>
        <br>
        <h1>11:07</h1>
      </div>
    </div>
  </div>
</div></code>```

Can anyone tell me what I'm doing wrong?
Thanks

答:
You can achieve it via jquery

Check this code. Hope it will helps You. :)

$('.workstream-comment').mouseover(function(){
  $(this).parent().next().find(".chatdate").css("opacity","1");
});
$('.workstream-comment').mouseout(function(){
  $(this).parent().next().find(".chatdate").css("opacity","0.5");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.chatdate {
    padding-top: 10px;
    opacity: 0.5;
    transition: opacity 1s ease-in-out;
}

.workstream-comment:hover .chatdate {
    background: red;
    opacity: 1;
}</code>```

                            ...

15/07/2017

11:07

                            ...

15/07/2017

11:07

```

Body:
I'm trying to change the opacity of a div when I hover on another div, but it isn't working at all. Here's the HTML:

.chatdate {
  padding-top: 10px;
  opacity: 0.5;
  transition: opacity 1s ease-in-out;
}

.workstream-comment:hover .chatdate {
  background: red;
  opacity: 1;
}

        ...

15/07/2017

11:07

        ...

15/07/2017

11:07

Can anyone tell me what I'm doing wrong?
Thanks

Body:
You can achieve it via jquery

Check this code. Hope it will helps You. :)

$('.workstream-comment').mouseover(function(){
  $(this).parent().next().find(".chatdate").css("opacity","1");
});
$('.workstream-comment').mouseout(function(){
  $(this).parent().next().find(".chatdate").css("opacity","0.5");
});

.chatdate {
    padding-top: 10px;
    opacity: 0.5;
    transition: opacity 1s ease-in-out;
}

.workstream-comment:hover .chatdate {
    background: red;
    opacity: 1;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-lg-12">
                <div class="row">
                    <div class="col-lg-10">
                        <div class="workstream-comment">
                            ...
                        </div>
                    </div>
                    <div class="col-lg-2">
                        <div class="chatdate text-center">
                            <h6>15/07/2017</h6>
                            <br>
                            <h1>11:07</h1>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-lg-10">
                        <div class="workstream-comment">
                            ...
                        </div>
                    </div>
                    <div class="col-lg-2">
                        <div class="chatdate text-center">
                            <h6>15/07/2017</h6>
                            <br>
                            <h1>11:07</h1>
                        </div>
                    </div>
                </div>
            </div>


问:
React Router - Stay at the same page after refresh
I'm learning React. I have page with 4 subpages and i use React Router to go through those pages. Everything works fine except for reloading page. When i go from page "home" to "about" or other it's ok, but when i refresh page then it render again page "about" for a second and then it change page to home (home is default/first page).I want it to stay at that page which is currently rendered, not go back to home after every refresh.
There is my code in index.js file where i render whole app and use router:

```<code><Provider store={store}>
    <Router path="/" history={browserHistory}>
        <Route path="/home" component={App}>
            <Route path="/" component={Home}/>
            <Route path="/allhotels" component={AllHotels}/>
            <Route path="/addhotel" component={AddHotel} />
            <Route path="/about" component={About} />
        </Route>
        <Route path="/signin" component={SignIn} />
        <Route path="/signup" component={SignUp} />
    </Router>
</Provider>, document.getElementById('root')
</code>```

In "App" i have Navigation and there i render rest of conent from Home, AllHotels etc.

There is code from App.jsx

```<code>class App extends Component {

render() {
    return (
        <div className="app-comp">
            <Navigation />
            <div> {this.props.children}</div>
        </div>
    )
  }
}
</code>```

I also attach gif which shows my problem.

https://gifyu.com/image/boMp

In backend i use Firebase if it's important.

Thanks in advance.

答:
I found the reason of my problem. I use also Firebase in my project and it causes the problem.
Thanks guys for help.

EDIT ======================================================================

Mabye I will write how I've fixed my problem and what was the reason of it.
So i was checking if user is logged in or not in auth method. And there if user was authorized I was pushing / to browserHistory.
It was mistake because every refresh method was executing and then also redirection was called as well.
Solution is just to check if during executing auth method I'm on Signin page or not. If it is Signin page then I'm pushing / to browserHistory but if not then just don't push anything.

```<code>    firebaseApp.auth().onAuthStateChanged(user => {
     if (user) {
        let currentPathname = browserHistory.getCurrentLocation().pathname;
        if( currentPathname === "/" || currentPathname === "/signin"){
          browserHistory.push('/');
        }
        const { email } = user;
        store.dispatch(logUser(email));
     }
     else {
        browserHistory.replace('/signin');
     }
    })
</code>```

I know that it's not pretty solution but it works and it was only home project which was created to learn react. (btw this project is using old react router 3.0 so probalby now using browserHistory is deprecated)

Body:
I'm learning React. I have page with 4 subpages and i use React Router to go through those pages. Everything works fine except for reloading page. When i go from page "home" to "about" or other it's ok, but when i refresh page then it render again page "about" for a second and then it change page to home (home is default/first page).I want it to stay at that page which is currently rendered, not go back to home after every refresh.
There is my code in index.js file where i render whole app and use router:

<Provider store={store}>
    <Router path="/" history={browserHistory}>
        <Route path="/home" component={App}>
            <Route path="/" component={Home}/>
            <Route path="/allhotels" component={AllHotels}/>
            <Route path="/addhotel" component={AddHotel} />
            <Route path="/about" component={About} />
        </Route>
        <Route path="/signin" component={SignIn} />
        <Route path="/signup" component={SignUp} />
    </Router>
</Provider>, document.getElementById('root')

In "App" i have Navigation and there i render rest of conent from Home, AllHotels etc.

There is code from App.jsx

class App extends Component {

render() {
    return (

            <Navigation />

 {this.props.children}

    )
  }
}

I also attach gif which shows my problem.

https://gifyu.com/image/boMp

In backend i use Firebase if it's important.

Thanks in advance.

Body:
I found the reason of my problem. I use also Firebase in my project and it causes the problem.
Thanks guys for help.

EDIT ======================================================================

Mabye I will write how I've fixed my problem and what was the reason of it.
So i was checking if user is logged in or not in auth method. And there if user was authorized I was pushing / to browserHistory.
It was mistake because every refresh method was executing and then also redirection was called as well.
Solution is just to check if during executing auth method I'm on Signin page or not. If it is Signin page then I'm pushing / to browserHistory but if not then just don't push anything.

    firebaseApp.auth().onAuthStateChanged(user => {
     if (user) {
        let currentPathname = browserHistory.getCurrentLocation().pathname;
        if( currentPathname === "/" || currentPathname === "/signin"){
          browserHistory.push('/');
        }
        const { email } = user;
        store.dispatch(logUser(email));
     }
     else {
        browserHistory.replace('/signin');
     }
    })

I know that it's not pretty solution but it works and it was only home project which was created to learn react. (btw this project is using old react router 3.0 so probalby now using browserHistory is deprecated)


问:
Extract a function name inside a macro
In C, we often have to run such code

```<code>if (! somefun(x, y, z)) {
    perror("somefun")
}
</code>```

Is it possible to create a macro which, used as follows:

```<code>#define chkerr ...
chkerr(somefun(x, y, z));
</code>```

would compile to the above?

I already know I can use __VA_ARGS__ macro, but this would require me to call it like

```<code>chkerr(somefun, x, y, z)
</code>```

答:
Yes it is possible with an ugly, unsafe variadic macro:

```<code>#define chkerr(func, ...) \
if(!func(__VA_ARGS__))    \
{                         \
  perror(#func);          \
}

...
chkerr(somefunc, 1, 2, 3);
</code>```

But it is a very bad idea.

Call for sanity:

If there was just the original code with the plain if statement, the reader would think "Here they call a function and do some basic error control. Okay, basic stuff. Moving on...". But after the changes, anyone who reads the code will instead freeze and think "WTF is this???".

You can never write a macro that is clearer than the if statement - which makes the if statement superior to the macro.

Some rules to follow:

Function-like macros are dangerous and unreadable. They should only be used as the very last resort.

Avoid inventing your own secret macro language with function-like macros. C programmers who read your code know C. They don't know your secret macro language.

"To avoid typing" is often a poor rationale for program design decisions. Avoiding code repetition is a good rationale, but taking it to the extremes will affect code readability. If you avoid code repetition and make the code more readable at the same time, it is a good thing. If you do it but the code turns less readable, it is hard to justify.

Title: Extract a function name inside a macro

Body:
In C, we often have to run such code

if (! somefun(x, y, z)) {
    perror("somefun")
}

Is it possible to create a macro which, used as follows:

#define chkerr ...
chkerr(somefun(x, y, z));

would compile to the above?

I already know I can use __VA_ARGS__ macro, but this would require me to call it like

chkerr(somefun, x, y, z)

Body:
Yes it is possible with an ugly, unsafe variadic macro:

#define chkerr(func, ...) \
if(!func(__VA_ARGS__))    \
{                         \
  perror(#func);          \
}

...
chkerr(somefunc, 1, 2, 3);

But it is a very bad idea.

Call for sanity:

If there was just the original code with the plain if statement, the reader would think "Here they call a function and do some basic error control. Okay, basic stuff. Moving on...". But after the changes, anyone who reads the code will instead freeze and think "WTF is this???".

You can never write a macro that is clearer than the if statement - which makes the if statement superior to the macro.

Some rules to follow:

Function-like macros are dangerous and unreadable. They should only be used as the very last resort.

Avoid inventing your own secret macro language with function-like macros. C programmers who read your code know C. They don't know your secret macro language.

"To avoid typing" is often a poor rationale for program design decisions. Avoiding code repetition is a good rationale, but taking it to the extremes will affect code readability. If you avoid code repetition and make the code more readable at the same time, it is a good thing. If you do it but the code turns less readable, it is hard to justify.


问:
Send an array with objects to php
i tried here a lot of options to send data from jQuery to php but without success, i'm trying to send an array of objects like here:

```<code>$.ajax({
            type: "POST",
            contentType: 'application/json',
            url: "sendCartDetails.php",
            data: {
                'details': prod
            }
    });
</code>```

where prod has this structure:

```<code>prod: [{name: 'Some Name'}, {name: 'Other Name'}]
</code>```

and my php file:

```<code>$data = json_decode($_POST['details']);

$to = "email@email.com";
$subject = "New Order";
$headers = "From: Some ";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
$message .= "<tr style='background: #eee;'><td><strong>Name:</strong> </td><td>" . $data . "</td></tr>"
$message .= "</table>";
$message .= "</body></html>";

mail($to,$subject,$message,$headers);
</code>```

and data here it's undefined also had the 500 (Internal Server Error) when trying to send it. How to get the data correctly here? Thanks a lot

答: try prod:[{"name": "Some Name"}, {"name": "Other Name"}]</p>

Title: Send an array with objects to php

Body:
i tried here a lot of options to send data from jQuery to php but without success, i'm trying to send an array of objects like here:

$.ajax({
            type: "POST",
            contentType: 'application/json',
            url: "sendCartDetails.php",
            data: {
                'details': prod
            }
    });

where prod has this structure:

prod: [{name: 'Some Name'}, {name: 'Other Name'}]

and my php file:

$data = json_decode($_POST['details']);

$to = "email@email.com";
$subject = "New Order";
$headers = "From: Some ";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '';
$message .= '
';
$message .= "
Name: 	" . $data . "
"
$message .= "
";
$message .= "";

mail($to,$subject,$message,$headers);

and data here it's undefined also had the 500 (Internal Server Error) when trying to send it. How to get the data correctly here? Thanks a lot


问:
How to get to the public directory
I use angular-cli in my project, and I want to use a global image - my website logo image.

As I understand the public directory at the root of the project (which angular-cli created) is for public assets - which seems like a good place to put my image (please correct me if I'm wrong).

But, when I try to get to that image in my  tag, I get 404. The reason is, of course, my project root is the src directory and not the project root directory.

So, how should I get to that directory? Or should I place my image in another directory?

My project tree (i remove the unnecessary suff):

```<code>.
├── angular-cli-build.js
├── angular-cli.json
├── package.json
├── public
│   ├── book4u-logo.svg
│   └── hero-image-default.jpg
├── src
│   ├── app
│   │   ├── bfy.component.html
│   │   ├── bfy.component.scss
│   │   ├── bfy.component.ts
│   │   ├── environment.ts
│   ├── favicon.ico
│   ├── index.html
│   ├── main.ts
│   ├── system-config.ts
│   ├── tsconfig.json
│   └── typings.d.ts
├── tslint.json
└── typings.json
</code>```

The img tag is at /src/app/bfy.component.html and the image itself is at /public/book4u-logo.svg.

Title: How to get to the public directory

Body:
I use angular-cli in my project, and I want to use a global image - my website logo image.

As I understand the public directory at the root of the project (which angular-cli created) is for public assets - which seems like a good place to put my image (please correct me if I'm wrong).

But, when I try to get to that image in my  tag, I get 404. The reason is, of course, my project root is the src directory and not the project root directory.

So, how should I get to that directory? Or should I place my image in another directory?

My project tree (i remove the unnecessary suff):

.
├── angular-cli-build.js
├── angular-cli.json
├── package.json
├── public
│   ├── book4u-logo.svg
│   └── hero-image-default.jpg
├── src
│   ├── app
│   │   ├── bfy.component.html
│   │   ├── bfy.component.scss
│   │   ├── bfy.component.ts
│   │   ├── environment.ts
│   ├── favicon.ico
│   ├── index.html
│   ├── main.ts
│   ├── system-config.ts
│   ├── tsconfig.json
│   └── typings.d.ts
├── tslint.json
└── typings.json

The img tag is at /src/app/bfy.component.html and the image itself is at /public/book4u-logo.svg.

Body:
I solved a similar problem in Angular 4 (I had a css file that was in public folder and I put it in assets folder).
The answer would be:

file path: ./src/assets/book4u-logo.svg

<img src="./assets/book4u-logo.svg>


答:
You can not send emails from localhost(your local system), unless you are using 3rd party email solution
This Line :
mail($to,$subject,$message,$headers);
will work on server but on local machine, it will result a 500 server error</p>

Title: Send an array with objects to php


问:
Java Void to Scala Unit
I have a java library method requiring a class of Void as a parameter. for example, in com.mongodb.async.client.MongoCollection:

```<code>void insertOne(TDocument document, SingleResultCallback<Void> callback);
</code>```

I'm accessing this method from scala. Scala uses the type Unit as equivalent of Void (correct me if I'm wrong please)

How can I pass a SingleResultCallback[Unit] (instead of SingleResultCallback[Void]) to this method? The compiler is not allowing this. Shouldn't it be picking this up?

答:
Try javatoscala

It returned:

```<code>def insertOne(document: TDocument,
                callback: SingleResultCallback[Void]): Unit
</code>```

Title: Java Void to Scala Unit

Body:
I have a java library method requiring a class of Void as a parameter. for example, in com.mongodb.async.client.MongoCollection:

void insertOne(TDocument document, SingleResultCallback<Void> callback);

I'm accessing this method from scala. Scala uses the type Unit as equivalent of Void (correct me if I'm wrong please)

How can I pass a SingleResultCallback[Unit] (instead of SingleResultCallback[Void]) to this method? The compiler is not allowing this. Shouldn't it be picking this up?

Body:
Try javatoscala

It returned:

def insertOne(document: TDocument,
                callback: SingleResultCallback[Void]): Unit


问:
Spring MVC home page
I have HomeController class:

```<code>@Controller
public class HomeController {

    @RequestMapping("/")
    public String showPage() {
        return "main-menu";
    }
}
</code>```

My project structure:

Spring version: 4.3.9
web.xml:

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.form</url-pattern>
    </servlet-mapping>
</web-app>
</code>```

dispatcher-servlet.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>
</code>```

It always shows index.jsp, never main-menu.jsp
I want a main-menu my Home Page. What should i do?

答:
i've used an approach to solve this problem in my project.
i'm sharing it with you below

Keep only below content in your index.jsp

```<code>index.jsp

<meta http-equiv="refresh" content="0;url=welcome" />
</code>```

In your controller java program the RequestMapping must hold the value specified in the url attribute of <meta> tag specified in index.jsp file.

In this example, the url attribute has value welcome

```<code>@Controller
public class HomeController {

    @RequestMapping("/welcome")
    public String welcome() {
        return "main-menu";
    }
}
</code>```

This worked for me

Updated #1:

```<code>    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
</code>```

Updated #2:

```<code><context:annotation-config />
<context:component-scan base-package="add your base folder here" />
</code>```

Title: Spring MVC home page

Body:
I have HomeController class:

@Controller
public class HomeController {

    @RequestMapping("/")
    public String showPage() {
        return "main-menu";
    }
}

My project structure:

Spring version: 4.3.9
web.xml:

    <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.form</url-pattern>
    </servlet-mapping>
</web-app>

dispatcher-servlet.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>

It always shows index.jsp, never main-menu.jsp
I want a main-menu my Home Page. What should i do?

Body:
i've used an approach to solve this problem in my project.
i'm sharing it with you below

Keep only below content in your index.jsp

index.jsp

<meta http-equiv="refresh" content="0;url=welcome" />

In your controller java program the RequestMapping must hold the value specified in the url attribute of <meta> tag specified in index.jsp file.

In this example, the url attribute has value welcome

@Controller
public class HomeController {

    @RequestMapping("/welcome")
    public String welcome() {
        return "main-menu";
    }
}

This worked for me

Updated #1:

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

Updated #2:

<context:annotation-config />
<context:component-scan base-package="add your base folder here" />


问:
Airport ticker effect in Adobe trials
When you run an Adobe product in a trial, a window appears each time asking if you have have a serial number yet or if you would like to continue with the trial. Next to that is a lovely 'number ticker', like the ones they used to have at airports (see image).

Does anyone know where I can get one of these, preferably gratis, to use as a component in a flex application?

答:
There are a few decent components available for close to free that I've found at activeden.net.  They generally include source code so you can change them to meet your exact need.  Here's a good example of what you can find there: http://activeden.net/item/flip-numbers/104628

Hope that helps.

Title: Airport ticker effect in Adobe trials


问:
Object of class DateTime could not be converted
I can see that there are many questions along these lines but I am very confused as to why the following does not work, taken straight from the PHP docs:

```<code>$tempDate = DateTime::createFromFormat('j-M-Y', '15-Feb-2009');
echo $tempDate;
</code>```

The error:

PHP Catchable fatal error:  Object of class DateTime could not be converted to string.

In fact every example in the docs gives me this error. Any ideas?

答:
You can't echo the DateTime object directly. You have to use the format method to get the date and / or time part:

```<code>$tempDate = DateTime::createFromFormat('j-M-Y', '15-Feb-2009');
echo $tempDate->format('Y-m-d H:i:s');
// NOT echo $tempDate!!!
</code>```

demo: http://ideone.com/IyqRWj

If you want to see the details of the object (for debug) you can use var_dump:

```<code>$tempDate = DateTime::createFromFormat('j-M-Y', '15-Feb-2009');
var_dump($tempDate);
</code>```

Body:
I can see that there are many questions along these lines but I am very confused as to why the following does not work, taken straight from the PHP docs:

$tempDate = DateTime::createFromFormat('j-M-Y', '15-Feb-2009');
echo $tempDate;

The error:

PHP Catchable fatal error:  Object of class DateTime could not be converted to string.

In fact every example in the docs gives me this error. Any ideas?

Body:
You can't echo the DateTime object directly. You have to use the format method to get the date and / or time part:

$tempDate = DateTime::createFromFormat('j-M-Y', '15-Feb-2009');
echo $tempDate->format('Y-m-d H:i:s');
// NOT echo $tempDate!!!

demo: http://ideone.com/IyqRWj

If you want to see the details of the object (for debug) you can use var_dump:

$tempDate = DateTime::createFromFormat('j-M-Y', '15-Feb-2009');
var_dump($tempDate);


问:
Python PIL 0.5 opacity, transparency, alpha
Is there any way to make an image half transparent?

the pseudo code is something like this:

```<code>from PIL import Image
image = Image.open('image.png')
image = alpha(image, 0.5)
</code>```

I googled it for a couple of hours but I can't find anything useful.

答:
I just did this by myself...even though my code maybe a little bit weird...But it works fine. So I share it here. Hopes it could help anybody. =)

The idea: To transparent a pic means lower alpha which is the 4th element in the tuple.

my frame code:

```<code>from PIL import Image
img=open(image)
img=img.convert('RGBA')  #you can make sure your pic is in the right mode by check img.mode
data=img.getdata()  #you'll get a list of tuples
newData=[]
for a in data:
    a=a[:3] #you'll get your tuple shorten to RGB
    a=a+(100,) #change the 100 to any transparency number you like between (0,255)
    newData.append(a)
img.putdata(newData) #you'll get your new img ready
img.save(filename.filetype)
</code>```

I didn't find the right command to fulfil this job automatically, so I write this by myself. Hopes it'll help again. XD

Body:
Is there any way to make an image half transparent?

the pseudo code is something like this:

from PIL import Image
image = Image.open('image.png')
image = alpha(image, 0.5)

I googled it for a couple of hours but I can't find anything useful.

Body:
I just did this by myself...even though my code maybe a little bit weird...But it works fine. So I share it here. Hopes it could help anybody. =)

The idea: To transparent a pic means lower alpha which is the 4th element in the tuple.

my frame code:

from PIL import Image
img=open(image)
img=img.convert('RGBA')  #you can make sure your pic is in the right mode by check img.mode
data=img.getdata()  #you'll get a list of tuples
newData=[]
for a in data:
    a=a[:3] #you'll get your tuple shorten to RGB
    a=a+(100,) #change the 100 to any transparency number you like between (0,255)
    newData.append(a)
img.putdata(newData) #you'll get your new img ready
img.save(filename.filetype)

I didn't find the right command to fulfil this job automatically, so I write this by myself. Hopes it'll help again. XD


问:
how to create task takening in account build flavors
```<code>task wsUpload(type: Exec) {
  commandLine '../scripts/ws_upload.sh'
  args = [rootProject.ext.VERSION_CODE]

  crashlyticsUploadDistributionMinAPI16ProdRelease
}
</code>```

wsUpload is defined outside and block at the bottom of app/build.gradle file
I want it to execute ws_upload.sh script and then upload apk to fabric beta.

In android block i have several  productFlavors

```<code>flavorDimensions "api", "mode"
  productFlavors {
    // Define separate dev and prod product flavors.
    dev {
    }
    prod {
    }
    minAPI21 {
    }
    minAPI16 {
    }
  }
</code>```

However when I try to sync I am getting Error:(150, 0) Could not get unknown property 'crashlyticsUploadDistributionMinAPI16ProdRelease' for task ':app:wsUpload' of type org.gradle.api.tasks.Exec.

答:
Exec Task doesn't know what is crashlyticsUploadDistributionMinAPI16ProdRelease

The properties that Exec task handles are here

If you want to create a Custom task, you can do so please refer to docs

Body:
task wsUpload(type: Exec) {
  commandLine '../scripts/ws_upload.sh'
  args = [rootProject.ext.VERSION_CODE]

  crashlyticsUploadDistributionMinAPI16ProdRelease
}

wsUpload is defined outside and block at the bottom of app/build.gradle file
I want it to execute ws_upload.sh script and then upload apk to fabric beta.

In android block i have several  productFlavors

flavorDimensions "api", "mode"
  productFlavors {
    // Define separate dev and prod product flavors.
    dev {
    }
    prod {
    }
    minAPI21 {
    }
    minAPI16 {
    }
  }

However when I try to sync I am getting Error:(150, 0) Could not get unknown property 'crashlyticsUploadDistributionMinAPI16ProdRelease' for task ':app:wsUpload' of type org.gradle.api.tasks.Exec.


问:
Ordering sub-collections in an EF/LINQ query
I am having trouble figuring out how (and where) to order a subcollection in a LINQ/EF query.

Basically I have a collection of SubscriptionTypes, each having its own collection of Subscriptions. I would like each Subscription in the collection to be ordered by NumberOfMonths.

Here is my current query:

```<code>    public IQueryable<SubscriptionType> SubscriptionTypesByProperty(string propertyCode)
{
    return from a in db.SubscriptionTypes.Include("Subscriptions")
           where a.Subscriptions.Any(x => x.PropertyCode == propertyCode)
           select a;
}
</code>```

I would like the Subscriptions to be ordered by NumberOfMonths. I tried this:

```<code>    public IQueryable<SubscriptionType> SubscriptionTypesByProperty(string propertyCode)
    {
        return from a in db.SubscriptionTypes.Include("Subscriptions")
               where a.Subscriptions.OrderBy(q => q.NumberOfMonths).Any(x => x.PropertyCode == propertyCode)
               select a;
    }
</code>```

.. but that did not order the subscriptions correctly.

Does anybody know of an easy way to do this?

UPDATE: SubscriptionType and Subscription are types generated by the EF designer.

Thanks,
Adam

答:
You can change your existing query to this, and it should do what you're looking for.

```<code>public IQueryable<SubscriptionType> SubscriptionTypesByProperty(string propertyCode)
{
    return from a in db.SubscriptionTypes.Include("Subscriptions")
           where a.Subscriptions.Any(x => x.PropertyCode == propertyCode)
           order by a.NumberOfMonths descending
           select a;
}
</code>```

Obviously, descending could be ascending if that's what you want.

Body:
I am having trouble figuring out how (and where) to order a subcollection in a LINQ/EF query.

Basically I have a collection of SubscriptionTypes, each having its own collection of Subscriptions. I would like each Subscription in the collection to be ordered by NumberOfMonths.

Here is my current query:

    public IQueryable<SubscriptionType> SubscriptionTypesByProperty(string propertyCode)
{
    return from a in db.SubscriptionTypes.Include("Subscriptions")
           where a.Subscriptions.Any(x => x.PropertyCode == propertyCode)
           select a;
}

I would like the Subscriptions to be ordered by NumberOfMonths. I tried this:

    public IQueryable<SubscriptionType> SubscriptionTypesByProperty(string propertyCode)
    {
        return from a in db.SubscriptionTypes.Include("Subscriptions")
               where a.Subscriptions.OrderBy(q => q.NumberOfMonths).Any(x => x.PropertyCode == propertyCode)
               select a;
    }

.. but that did not order the subscriptions correctly.

Does anybody know of an easy way to do this?

UPDATE: SubscriptionType and Subscription are types generated by the EF designer.

Thanks,
Adam

Body:
You can change your existing query to this, and it should do what you're looking for.

public IQueryable<SubscriptionType> SubscriptionTypesByProperty(string propertyCode)
{
    return from a in db.SubscriptionTypes.Include("Subscriptions")
           where a.Subscriptions.Any(x => x.PropertyCode == propertyCode)
           order by a.NumberOfMonths descending
           select a;
}

Obviously, descending could be ascending if that's what you want.


问:
converting a tuple consisting of floats and text to one single string
I'm trying to convert a tuple consisting of 2 floats and 3 parts of text to one string so I can use it in file.write() because it is not accepting tuples.

```<code>testr = 'you went' ,speed ,'mph and stopped in' ,stop ,'meters'
test = open('testresults.txt' ,'w')
test.write(testr)
test.close()
</code>```

whenever I try to run the program it gives me this

```<code>    test.write(testr)
TypeError: must be str, not tuple
</code>```

答:
Use format:

```<code>testr = 'you went {} mph and stopped in {} meters'.format(speed, stop)
</code>```

Body:
I'm trying to convert a tuple consisting of 2 floats and 3 parts of text to one string so I can use it in file.write() because it is not accepting tuples.

testr = 'you went' ,speed ,'mph and stopped in' ,stop ,'meters'
test = open('testresults.txt' ,'w')
test.write(testr)
test.close()

whenever I try to run the program it gives me this

    test.write(testr)
TypeError: must be str, not tuple

Body:
Use format:

testr = 'you went {} mph and stopped in {} meters'.format(speed, stop)


答:
Convert it to a String

```<code>test.write(str(testr))
</code>```

Title: converting a tuple consisting of floats and text to one single string

Body:
Convert it to a String

test.write(str(testr))


问:
Converting the result of Func<T, IConvertible> to int in a lambda expression
I am abstracting a bit of code, and ran into an issue with casting the result of a Func to an integer for comparison.

I have a function:

```<code>public static IConvertible GetIllnessRateByParity(IEnumerable<ILLNESS_OBJECT> pItems, int pParity, Func<ILLNESS_OBJECT, IConvertible> pSelector)
    {
        var filtered = pItems.Where(a => a.Parity == pParity);
        return Math.Round(filtered.Count(a => Convert.ToInt32(pSelector(a)) == 1) / (double)GetBirthCountByParity(pItems, pParity), 2);
    }

public class ILLNESS_OBJECT
{
    public int ID { get; set; }
    public DateTime Day { get; set; }
    public int Parity { get; set; }
    public int Afterbirth { get; set; }
    public int OvaryInfection { get; set; }
    etc...
}
</code>```

Which calculates the rate of a specific illness within a set of data. The illness to be analysed is input through a selector, which selects an IConvertible value from the ILLNESS_OBJECT object.

I call the method like this:

```<code>GetIllnessRateByParity(data, 1, a => a.AfterBirth)
</code>```

data is an IEnumerable with non-null values.

The method throws an InvalidCastException at the Convert.ToInt32(pSelector(a)) part without clear indication of why this cast fails, could anyone explain it to me? I am under the impression that pSelector(a) returns an IConvertible value which is cast-compatible with int, right? Any help would be greatly appreciated!

EDIT: Exception message:
An exception of type 'System.InvalidCastException' occurred in CONFIDENTIAL.CLASS.dll but was not handled in user code

Message: Specified cast is not valid.

答:
Check this</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var data = new List<ILLNESS_OBJECT>{
                new ILLNESS_OBJECT{ ID = 1, Parity = 1, Day = DateTime.Now, SomeString = "1", Long = 2L},
                new ILLNESS_OBJECT{ ID = 2, Parity = 2, Day = DateTime.Now, SomeString = "1", Long = 2L},
                new ILLNESS_OBJECT{ ID = 3, Parity = 1, Day = DateTime.Now, SomeString = "2", Long = 1L},
                new ILLNESS_OBJECT{ ID = 4, Parity = 1, Day = DateTime.Now, SomeString = "3", Long = 3L},
        };
        Console.WriteLine(GetIllnessRateByParity(data, 1, x => x.ID));
        Console.WriteLine(GetIllnessRateByParity(data, 1, x => int.Parse(x.SomeString)));
        Console.WriteLine(GetIllnessRateByParity(data, 1, x => (DateTime.Now - x.Day).Days + 1));
        Console.WriteLine(GetIllnessRateByParity(data, 1, x => (int)x.Long));
    }

    public static IConvertible GetIllnessRateByParity(IEnumerable<ILLNESS_OBJECT> pItems, int pParity, Func<ILLNESS_OBJECT, int> pSelector)
    {
        var filtered = pItems.Where(a => a.Parity == pParity);
        return Math.Round(filtered.Count(a => pSelector(a) == 1)/(double)1, 2);
    }

}

public class ILLNESS_OBJECT
{
    public int ID { get; set; }
    public DateTime Day { get; set; }
    public int Parity { get; set; }
    public int Afterbirth { get; set; }
    public string SomeString { get; set; }
    public long Long { get; set; }
}
</code>```

Body:
I am abstracting a bit of code, and ran into an issue with casting the result of a Func to an integer for comparison.

I have a function:

public static IConvertible GetIllnessRateByParity(IEnumerable<ILLNESS_OBJECT> pItems, int pParity, Func<ILLNESS_OBJECT, IConvertible> pSelector)
    {
        var filtered = pItems.Where(a => a.Parity == pParity);
        return Math.Round(filtered.Count(a => Convert.ToInt32(pSelector(a)) == 1) / (double)GetBirthCountByParity(pItems, pParity), 2);
    }

public class ILLNESS_OBJECT
{
    public int ID { get; set; }
    public DateTime Day { get; set; }
    public int Parity { get; set; }
    public int Afterbirth { get; set; }
    public int OvaryInfection { get; set; }
    etc...
}

Which calculates the rate of a specific illness within a set of data. The illness to be analysed is input through a selector, which selects an IConvertible value from the ILLNESS_OBJECT object.

I call the method like this:

GetIllnessRateByParity(data, 1, a => a.AfterBirth)

data is an IEnumerable with non-null values.

The method throws an InvalidCastException at the Convert.ToInt32(pSelector(a)) part without clear indication of why this cast fails, could anyone explain it to me? I am under the impression that pSelector(a) returns an IConvertible value which is cast-compatible with int, right? Any help would be greatly appreciated!

EDIT: Exception message:
An exception of type 'System.InvalidCastException' occurred in CONFIDENTIAL.CLASS.dll but was not handled in user code

Message: Specified cast is not valid.

Body:
Check this

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var data = new List<ILLNESS_OBJECT>{
                new ILLNESS_OBJECT{ ID = 1, Parity = 1, Day = DateTime.Now, SomeString = "1", Long = 2L},
                new ILLNESS_OBJECT{ ID = 2, Parity = 2, Day = DateTime.Now, SomeString = "1", Long = 2L},
                new ILLNESS_OBJECT{ ID = 3, Parity = 1, Day = DateTime.Now, SomeString = "2", Long = 1L},
                new ILLNESS_OBJECT{ ID = 4, Parity = 1, Day = DateTime.Now, SomeString = "3", Long = 3L},
        };
        Console.WriteLine(GetIllnessRateByParity(data, 1, x => x.ID));
        Console.WriteLine(GetIllnessRateByParity(data, 1, x => int.Parse(x.SomeString)));
        Console.WriteLine(GetIllnessRateByParity(data, 1, x => (DateTime.Now - x.Day).Days + 1));
        Console.WriteLine(GetIllnessRateByParity(data, 1, x => (int)x.Long));
    }

    public static IConvertible GetIllnessRateByParity(IEnumerable<ILLNESS_OBJECT> pItems, int pParity, Func<ILLNESS_OBJECT, int> pSelector)
    {
        var filtered = pItems.Where(a => a.Parity == pParity);
        return Math.Round(filtered.Count(a => pSelector(a) == 1)/(double)1, 2);
    }

}

public class ILLNESS_OBJECT
{
    public int ID { get; set; }
    public DateTime Day { get; set; }
    public int Parity { get; set; }
    public int Afterbirth { get; set; }
    public string SomeString { get; set; }
    public long Long { get; set; }
}