问:
I've customized my Toolkit pie chart but now all slices are same color
I've implemented a resource dictionary so that I could customize my tooltip on a pie chart. But now the series returns a pie chart where the slices are all the same color. How do I get it to act like it did before I applied the resource dictionary? PieDataPoint.xaml is the file I copied into my project to use as a reesource dictionary.</p>

答:
I was able to solve my issue. Below is my resource dictionary. I had to manually define my colors as a style near the bottom.

```<code><ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:datavis="clr-namespace:System.Windows.Controls.DataVisualization;assembly=System.Windows.Controls.DataVisualization.Toolkit"
xmlns:charting="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"
>

<!--http://silverlight.codeplex.com/SourceControl/changeset/view/18791#507651-->
<ControlTemplate
        x:Key="MyPieDataPointTemplate"
        TargetType="charting:PieDataPoint">
    <Grid
            x:Name="Root"
            Opacity="0">
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
                <VisualStateGroup.Transitions>
                    <VisualTransition GeneratedDuration="0:0:0.1"/>
                </VisualStateGroup.Transitions>
                <VisualState x:Name="Normal"/>
                <VisualState x:Name="MouseOver">
                    <Storyboard>
                        <DoubleAnimation
                                Storyboard.TargetName="MouseOverHighlight"
                                Storyboard.TargetProperty="Opacity"
                                To="0.6"
                                Duration="0"/>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
            <VisualStateGroup x:Name="SelectionStates">
                <VisualStateGroup.Transitions>
                    <VisualTransition GeneratedDuration="0:0:0.1"/>
                </VisualStateGroup.Transitions>
                <VisualState x:Name="Unselected"/>
                <VisualState x:Name="Selected">
                    <Storyboard>
                        <DoubleAnimation
                                Storyboard.TargetName="SelectionHighlight"
                                Storyboard.TargetProperty="Opacity"
                                To="0.6"
                                Duration="0"/>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
            <VisualStateGroup x:Name="RevealStates">
                <VisualStateGroup.Transitions>
                    <VisualTransition GeneratedDuration="0:0:0.5"/>
                </VisualStateGroup.Transitions>
                <VisualState x:Name="Shown">
                    <Storyboard>
                        <DoubleAnimation
                                Storyboard.TargetName="Root"
                                Storyboard.TargetProperty="Opacity"
                                To="1"
                                Duration="0"/>
                    </Storyboard>
                </VisualState>
                <VisualState x:Name="Hidden">
                    <Storyboard>
                        <DoubleAnimation
                                Storyboard.TargetName="Root"
                                Storyboard.TargetProperty="Opacity"
                                To="0"
                                Duration="0"/>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
        <Path
                x:Name="Slice"
                Data="{TemplateBinding Geometry}"
                Fill="{TemplateBinding Background}"
                Stroke="{TemplateBinding BorderBrush}"
                StrokeMiterLimit="1">
            <ToolTipService.ToolTip>
                <StackPanel>
                    <ContentControl
                            Content="{TemplateBinding FormattedIndependentValue}"
                            FontWeight="Bold"/>
                    <ContentControl
                            Content="{TemplateBinding FormattedDependentValue}"/>
                    <ContentControl
                            Content="{TemplateBinding FormattedRatio}"/>
                </StackPanel>
            </ToolTipService.ToolTip>
        </Path>
        <Path
                x:Name="SelectionHighlight"
                Data="{TemplateBinding GeometrySelection}"
                Fill="Red"
                StrokeMiterLimit="1"
                IsHitTestVisible="False"
                Opacity="0"/>
        <Path
                x:Name="MouseOverHighlight"
                Data="{TemplateBinding GeometryHighlight}"
                Fill="White"
                StrokeMiterLimit="1"
                IsHitTestVisible="False"
                Opacity="0"/>
    </Grid>
</ControlTemplate>

<!--http://silverlight.codeplex.com/SourceControl/changeset/view/18791#507636-->
<datavis:ResourceDictionaryCollection x:Key="MyPalette">
    <!-- Blue -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FFB9D6F7"/>
            <GradientStop Color="#FF284B70" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Red -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FFFBB7B5"/>
            <GradientStop Color="#FF702828" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Light Green -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FFB8C0AC"/>
            <GradientStop Color="#FF5F7143" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Yellow -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FFFDE79C"/>
            <GradientStop Color="#FFF6BC0C" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Indigo -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FFA9A3BD"/>
            <GradientStop Color="#FF382C6C" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Magenta -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FFB1A1B1"/>
            <GradientStop Color="#FF50224F" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Dark Green -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FF9DC2B3"/>
            <GradientStop Color="#FF1D7554" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Gray Shade -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FFB5B5B5"/>
            <GradientStop Color="#FF4C4C4C" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Blue -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FF98C1DC"/>
            <GradientStop Color="#FF0271AE" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Brown -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FFC1C0AE"/>
            <GradientStop Color="#FF706E41" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Cyan -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FFADBDC0"/>
            <GradientStop Color="#FF446A73" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Special Blue -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FF2F8CE2"/>
            <GradientStop Color="#FF0C3E69" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Gray Shade 2 -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FFDCDCDC"/>
            <GradientStop Color="#FF757575" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Gray Shade 3 -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FFF4F4F4"/>
            <GradientStop Color="#FFB7B7B7" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Gray Shade 4 -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FFF4F4F4"/>
            <GradientStop Color="#FFA3A3A3" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
</datavis:ResourceDictionaryCollection>
</code>```

Body:
I was able to solve my issue. Below is my resource dictionary. I had to manually define my colors as a style near the bottom.

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:datavis="clr-namespace:System.Windows.Controls.DataVisualization;assembly=System.Windows.Controls.DataVisualization.Toolkit"
xmlns:charting="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"
>

<!--http://silverlight.codeplex.com/SourceControl/changeset/view/18791#507651-->
<ControlTemplate
        x:Key="MyPieDataPointTemplate"
        TargetType="charting:PieDataPoint">
    <Grid
            x:Name="Root"
            Opacity="0">
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
                <VisualStateGroup.Transitions>
                    <VisualTransition GeneratedDuration="0:0:0.1"/>
                </VisualStateGroup.Transitions>
                <VisualState x:Name="Normal"/>
                <VisualState x:Name="MouseOver">
                    <Storyboard>
                        <DoubleAnimation
                                Storyboard.TargetName="MouseOverHighlight"
                                Storyboard.TargetProperty="Opacity"
                                To="0.6"
                                Duration="0"/>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
            <VisualStateGroup x:Name="SelectionStates">
                <VisualStateGroup.Transitions>
                    <VisualTransition GeneratedDuration="0:0:0.1"/>
                </VisualStateGroup.Transitions>
                <VisualState x:Name="Unselected"/>
                <VisualState x:Name="Selected">
                    <Storyboard>
                        <DoubleAnimation
                                Storyboard.TargetName="SelectionHighlight"
                                Storyboard.TargetProperty="Opacity"
                                To="0.6"
                                Duration="0"/>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
            <VisualStateGroup x:Name="RevealStates">
                <VisualStateGroup.Transitions>
                    <VisualTransition GeneratedDuration="0:0:0.5"/>
                </VisualStateGroup.Transitions>
                <VisualState x:Name="Shown">
                    <Storyboard>
                        <DoubleAnimation
                                Storyboard.TargetName="Root"
                                Storyboard.TargetProperty="Opacity"
                                To="1"
                                Duration="0"/>
                    </Storyboard>
                </VisualState>
                <VisualState x:Name="Hidden">
                    <Storyboard>
                        <DoubleAnimation
                                Storyboard.TargetName="Root"
                                Storyboard.TargetProperty="Opacity"
                                To="0"
                                Duration="0"/>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
        <Path
                x:Name="Slice"
                Data="{TemplateBinding Geometry}"
                Fill="{TemplateBinding Background}"
                Stroke="{TemplateBinding BorderBrush}"
                StrokeMiterLimit="1">
            <ToolTipService.ToolTip>
                <StackPanel>
                    <ContentControl
                            Content="{TemplateBinding FormattedIndependentValue}"
                            FontWeight="Bold"/>
                    <ContentControl
                            Content="{TemplateBinding FormattedDependentValue}"/>
                    <ContentControl
                            Content="{TemplateBinding FormattedRatio}"/>
                </StackPanel>
            </ToolTipService.ToolTip>
        </Path>
        <Path
                x:Name="SelectionHighlight"
                Data="{TemplateBinding GeometrySelection}"
                Fill="Red"
                StrokeMiterLimit="1"
                IsHitTestVisible="False"
                Opacity="0"/>
        <Path
                x:Name="MouseOverHighlight"
                Data="{TemplateBinding GeometryHighlight}"
                Fill="White"
                StrokeMiterLimit="1"
                IsHitTestVisible="False"
                Opacity="0"/>
    </Grid>
</ControlTemplate>

<!--http://silverlight.codeplex.com/SourceControl/changeset/view/18791#507636-->
<datavis:ResourceDictionaryCollection x:Key="MyPalette">
    <!-- Blue -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FFB9D6F7"/>
            <GradientStop Color="#FF284B70" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Red -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FFFBB7B5"/>
            <GradientStop Color="#FF702828" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Light Green -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FFB8C0AC"/>
            <GradientStop Color="#FF5F7143" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Yellow -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FFFDE79C"/>
            <GradientStop Color="#FFF6BC0C" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Indigo -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FFA9A3BD"/>
            <GradientStop Color="#FF382C6C" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Magenta -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FFB1A1B1"/>
            <GradientStop Color="#FF50224F" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Dark Green -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FF9DC2B3"/>
            <GradientStop Color="#FF1D7554" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Gray Shade -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FFB5B5B5"/>
            <GradientStop Color="#FF4C4C4C" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Blue -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FF98C1DC"/>
            <GradientStop Color="#FF0271AE" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Brown -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FFC1C0AE"/>
            <GradientStop Color="#FF706E41" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Cyan -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FFADBDC0"/>
            <GradientStop Color="#FF446A73" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Special Blue -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FF2F8CE2"/>
            <GradientStop Color="#FF0C3E69" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Gray Shade 2 -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FFDCDCDC"/>
            <GradientStop Color="#FF757575" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Gray Shade 3 -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FFF4F4F4"/>
            <GradientStop Color="#FFB7B7B7" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
    <!-- Gray Shade 4 -->
    <ResourceDictionary>
        <RadialGradientBrush x:Key="Background" GradientOrigin="-0.1,-0.1" Center="0.075,0.015" RadiusX="1.05" RadiusY="0.9">
            <GradientStop Color="#FFF4F4F4"/>
            <GradientStop Color="#FFA3A3A3" Offset="1"/>
        </RadialGradientBrush>
        <Style x:Key="DataPointStyle" TargetType="Control">
            <Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}"/>
            <Setter Property="Background" Value="{StaticResource Background}"/>
        </Style>
    </ResourceDictionary>
</datavis:ResourceDictionaryCollection>


来源: stackexchange

问:
Copying a schedule without overlap in SQL Server
I have a simple table in SQL Server that is used to schedule room bookings. It has only three columns: roomid, fromdate, todate.

I need to enable copying existing bookings of one week (Sun-Sat) to another week, but only so long as there is no overlap with existing appointments.

For example, if in the source week I have

```<code>1/1/2017 10:00-11:00
1/2/2017 11:00-12:00
1/3/2017 12:00-13:00
</code>```

and in the destination week I have

```<code>1/2/2017 09:00-11:30
</code>```

The only the bookings for 1/1 and 1/3 would be copied. 1/2/2017 11:00 would not be copied because there would be an overlap with an existing booking in the source week.

PLEASE NOTE:
I know how to check for if one booking overlaps another booking. However, There are multiple bookings in the source date range and multiple bookings in the target date range and the question is whether there is a smart way to check the source range against the target range WITHOUT checking every booking in the source range against every booking in the target range (for example by linking the table onto itself).

答:
This is a prototype query that should get you want you want.

Note: it works for comparing one week of source data against one week of target data

```<code>SELECT *
FROM
        -- Current week appointments with +1 week dates
        ( SELECT roomid, DATEADD( week, 1, fromdate ) AS FutureFrom, DATEADD( week, 1, todate ) AS FutureTo
        FROM data
        WHERE [current week filter] ) AS CurrentWeek
    LEFT JOIN
            -- Next week appointments
            ( SELECT roomid, fromdate, todate
            FROM data
            WHERE [next week filter] ) AS NextWeek
        ON (FutureFrom < todate)  and  (FutureTo > fromdate) AND CurrentWeek.roomid = NextWeek.roomid
-- Only return CurrentWeek appointments where appointment date range does not overlap with next week's one
WHERE NextWeek.roomid IS NULL
</code>```

Note that date range overlap logic is obtained from: Determine Whether Two Date Ranges Overlap

This query should help your get the start of week filters working:

```<code>-- Start of the current week
SELECT DATEADD(DD, 1 - DATEPART(DW, CONVERT( DATE, GETDATE())), CONVERT( DATE, GETDATE())) AS StartOfTheWeek
</code>```

Reference: Get first day of week in SQL Server

Note: If you want a working sample you need to provide a full DDL script with more sample data.

ContentLicense: CC BY-SA 3.0

Body:
I have a simple table in SQL Server that is used to schedule room bookings. It has only three columns: roomid, fromdate, todate.

I need to enable copying existing bookings of one week (Sun-Sat) to another week, but only so long as there is no overlap with existing appointments.

For example, if in the source week I have

1/1/2017 10:00-11:00
1/2/2017 11:00-12:00
1/3/2017 12:00-13:00

and in the destination week I have

1/2/2017 09:00-11:30

The only the bookings for 1/1 and 1/3 would be copied. 1/2/2017 11:00 would not be copied because there would be an overlap with an existing booking in the source week.

PLEASE NOTE:
I know how to check for if one booking overlaps another booking. However, There are multiple bookings in the source date range and multiple bookings in the target date range and the question is whether there is a smart way to check the source range against the target range WITHOUT checking every booking in the source range against every booking in the target range (for example by linking the table onto itself).

Body:
This is a prototype query that should get you want you want.

Note: it works for comparing one week of source data against one week of target data

SELECT *
FROM
        -- Current week appointments with +1 week dates
        ( SELECT roomid, DATEADD( week, 1, fromdate ) AS FutureFrom, DATEADD( week, 1, todate ) AS FutureTo
        FROM data
        WHERE [current week filter] ) AS CurrentWeek
    LEFT JOIN
            -- Next week appointments
            ( SELECT roomid, fromdate, todate
            FROM data
            WHERE [next week filter] ) AS NextWeek
        ON (FutureFrom < todate)  and  (FutureTo > fromdate) AND CurrentWeek.roomid = NextWeek.roomid
-- Only return CurrentWeek appointments where appointment date range does not overlap with next week's one
WHERE NextWeek.roomid IS NULL

Note that date range overlap logic is obtained from: Determine Whether Two Date Ranges Overlap

This query should help your get the start of week filters working:

-- Start of the current week
SELECT DATEADD(DD, 1 - DATEPART(DW, CONVERT( DATE, GETDATE())), CONVERT( DATE, GETDATE())) AS StartOfTheWeek

Reference: Get first day of week in SQL Server

Note: If you want a working sample you need to provide a full DDL script with more sample data.


问:
Peek ahead when iterating an array of arrays in PHP
I have a mysql query object result which I want to parse through. Let's say the array looks like this.

```<code>$superheroes = array(
    [0] => array(
        "name" => "Peter Parker",
        "email" => "peterparker@mail.com",
        "age"=>"33",
        "sex"=>"male",
    ),
    [1] => array(
        "name" => "jLaw",
        "email" => "jlaw@mail.com",
        "age"=>"22",
        "sex"=>"female",
    ),
    [2] => array(
        "name" => "Clark Kent",
        "email" => "clarkkent@mail.com",
        "age"=>"36",
        "sex"=>"male",
    ),
    [3] => array(
        "name" => "Gal Gadot",
        "email" => "gal@mail.com",
        "age"=>"22",
        "sex"=>"female",
    )
);
</code>```

I want to iterate through this array, and while I am at each array, I want to look ahead in the next array, and find out the age difference between current male hero and next immediate female in the list. I found a lot of posts that talk about
1. array_keys
2. caching iterators,
3. prev, next, etc.

But all of them are talking about one dimensional arrays. Here Is what I tried

```<code>foreach ($superheroes as $key => $list){
if($list['sex']=="male"){
    $currentHerosAge=$list['age'];
    while($next=next($superheroes)){
        if($next['sex']=="female"){
            $diff=$currentHerosAge -$next['age'];
            echo "Age diff: ".$diff;
            break;
        }
    }
}
</code>```

}

But when I try this, for array[0], next misses the array[1], and picks up array[3]. Not sure how to work this out.

答:
Normally, you don't use a "lookahead", when iterating over the array. The common way would be to store the item of the last iteration and do the comparison on this element

```<code>$last_hero = false;
foreach ($superheroes as $hero) {
    if ($last_hero) {
        // do some stuff..
    }
    $last_hero = $hero;
}
</code>```

If you really need a lookahead of more than one item, you wouldn't use a foreach loop.

```<code>for ($i = 0; $i < count($superheroes); $i++) {
    // do sth. with $superheroes[$i]
    if (...) {
        for ($j = $i + 1; $j < count($superheroes); $j++) {
            // do sth. with $superheroes[$j]
        }
    }
}
</code>```

Body:
I have a mysql query object result which I want to parse through. Let's say the array looks like this.

$superheroes = array(
    [0] => array(
        "name" => "Peter Parker",
        "email" => "peterparker@mail.com",
        "age"=>"33",
        "sex"=>"male",
    ),
    [1] => array(
        "name" => "jLaw",
        "email" => "jlaw@mail.com",
        "age"=>"22",
        "sex"=>"female",
    ),
    [2] => array(
        "name" => "Clark Kent",
        "email" => "clarkkent@mail.com",
        "age"=>"36",
        "sex"=>"male",
    ),
    [3] => array(
        "name" => "Gal Gadot",
        "email" => "gal@mail.com",
        "age"=>"22",
        "sex"=>"female",
    )
);

I want to iterate through this array, and while I am at each array, I want to look ahead in the next array, and find out the age difference between current male hero and next immediate female in the list. I found a lot of posts that talk about
1. array_keys
2. caching iterators,
3. prev, next, etc.

But all of them are talking about one dimensional arrays. Here Is what I tried

foreach ($superheroes as $key => $list){
if($list['sex']=="male"){
    $currentHerosAge=$list['age'];
    while($next=next($superheroes)){
        if($next['sex']=="female"){
            $diff=$currentHerosAge -$next['age'];
            echo "Age diff: ".$diff;
            break;
        }
    }
}

}

But when I try this, for array[0], next misses the array[1], and picks up array[3]. Not sure how to work this out.

Body:
Normally, you don't use a "lookahead", when iterating over the array. The common way would be to store the item of the last iteration and do the comparison on this element

$last_hero = false;
foreach ($superheroes as $hero) {
    if ($last_hero) {
        // do some stuff..
    }
    $last_hero = $hero;
}

If you really need a lookahead of more than one item, you wouldn't use a foreach loop.

for ($i = 0; $i < count($superheroes); $i++) {
    // do sth. with $superheroes[$i]
    if (...) {
        for ($j = $i + 1; $j < count($superheroes); $j++) {
            // do sth. with $superheroes[$j]
        }
    }
}


问:
Angular model doesn't update after ng-click
the ng-repeat model doesn't update after a user clicks submit, it will only show on refresh, i reviewed a similar problem, but i couldn't connect the dots. A user recommended i do a ng-init, but i don't think im doing it right.

with ng-init it shows no data, without ng-init and removing the angular function it shows posts but doesn't update the model after click.

note:the angular brackets are replaced because laravel blade doesn't like it

html

```<code>    <div id="mypost" class="col-md-8 panel-default" ng-init="getPosts()" ng-repeat="post in myposts">
        <div id="eli-style-heading" class="panel-heading"><% post.title %></div>
            <div class="panel-body panel">
                <figure>
                    <p> <% post.body %></p>

                </figure>
            </div>

    </div>
</code>```

Main.js

```<code>// this doens't show posts when i use ng-init
$scope.getPosts = function(){

    $http.get('/auth/posts').then(function(data){
        $scope.myposts = data.data;
    });

};

// this shows posts without ng-init but doesn't update when a user adds data

$http.get('/auth/posts').then(function(data){
    $scope.myposts = data.data;
});
</code>```

Updated Again

network error

PostController.php

```<code>public function storePost(Request $request)
{
    $data = request()->validate([
     'title' => 'required|max:120',
     'body' => 'required|max:1000'
    ]);

    $data['user_id'] = auth()->user()->id;

    $post = Post::create($data);

    // return redirect('/home')->withMessage('A new post was created.');

    return Response::json(array('success' => true));
}
</code>```

答:
With the help of another @Sorikairo we were able to solve the problem, i didn't want to post the answer because i was lazy, but i need to help the people who ever encounter a very similar problem when using laravel. Here is the updated code.

Main.js

```<code>var app = angular.module('eli', []);

app.config(function($interpolateProvider) {
    $interpolateProvider.startSymbol('<%');
    $interpolateProvider.endSymbol('%>');
});

app.controller('mainCtrl', ['$scope', '$http', function($scope, $http){

    $scope.posts = {};

    $scope.addPost = function(){

        $http.post('/auth/post', {
            title: $scope.post.title,
            body: $scope.post.body

        }).then(function(data, status, headers, config){
            console.log(data);
            $scope.myposts.push(data.data);

        });

        $scope.post.title = '';
        $scope.post.body = '';

    };

    $scope.getPosts = function(){

        $http.get('/auth/posts').then(function(data){
            $scope.myposts = data.data;
        }).then(function(data, status, header, config){
        });

    };

    $scope.getPosts();

}]);
</code>```

i needed to add

the response class to my php file

```<code><?php

namespace App\Http\Controllers;

use App\Post;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function storePost(Request $request)
    {
        $data = request()->validate([
         'title' => 'required|max:120',
         'body' => 'required|max:1000'
        ]);

        $data['user_id'] = auth()->user()->id;

        $post = Post::create($data);

        $response = new Response(json_encode($data));
        $response->headers->set('Content-Type', 'application/json');

        // return redirect('/home')->withMessage('A new post was created.');

        return $response;
    }
</code>```

it works now thank you everyone

Body:
the ng-repeat model doesn't update after a user clicks submit, it will only show on refresh, i reviewed a similar problem, but i couldn't connect the dots. A user recommended i do a ng-init, but i don't think im doing it right.

with ng-init it shows no data, without ng-init and removing the angular function it shows posts but doesn't update the model after click.

note:the angular brackets are replaced because laravel blade doesn't like it

html

<% post.title %>

 <% post.body %>

Main.js

// this doens't show posts when i use ng-init
$scope.getPosts = function(){

    $http.get('/auth/posts').then(function(data){
        $scope.myposts = data.data;
    });

};

// this shows posts without ng-init but doesn't update when a user adds data

$http.get('/auth/posts').then(function(data){
    $scope.myposts = data.data;
});

Updated Again

network error

PostController.php

public function storePost(Request $request)
{
    $data = request()->validate([
     'title' => 'required|max:120',
     'body' => 'required|max:1000'
    ]);

    $data['user_id'] = auth()->user()->id;

    $post = Post::create($data);

    // return redirect('/home')->withMessage('A new post was created.');

    return Response::json(array('success' => true));
}

Body:
With the help of another @Sorikairo we were able to solve the problem, i didn't want to post the answer because i was lazy, but i need to help the people who ever encounter a very similar problem when using laravel. Here is the updated code.

Main.js

var app = angular.module('eli', []);

app.config(function($interpolateProvider) {
    $interpolateProvider.startSymbol('<%');
    $interpolateProvider.endSymbol('%>');
});

app.controller('mainCtrl', ['$scope', '$http', function($scope, $http){

    $scope.posts = {};

    $scope.addPost = function(){

        $http.post('/auth/post', {
            title: $scope.post.title,
            body: $scope.post.body

        }).then(function(data, status, headers, config){
            console.log(data);
            $scope.myposts.push(data.data);

        });

        $scope.post.title = '';
        $scope.post.body = '';

    };

    $scope.getPosts = function(){

        $http.get('/auth/posts').then(function(data){
            $scope.myposts = data.data;
        }).then(function(data, status, header, config){
        });

    };

    $scope.getPosts();

}]);

i needed to add

the response class to my php file

<?php

namespace App\Http\Controllers;

use App\Post;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function storePost(Request $request)
    {
        $data = request()->validate([
         'title' => 'required|max:120',
         'body' => 'required|max:1000'
        ]);

        $data['user_id'] = auth()->user()->id;

        $post = Post::create($data);

        $response = new Response(json_encode($data));
        $response->headers->set('Content-Type', 'application/json');

        // return redirect('/home')->withMessage('A new post was created.');

        return $response;
    }

it works now thank you everyone


问:
In moment.js, is it possible to have a date-time string and keep the date but change the time?
I'm using moment.js and want to update a date-time string with a new user-entered time. The date has not changed, only the time. There is no timezone change, just that the hour and minute values have possibly been altered.

How would I take a string like this and convert it such that the time is different?

This is would I'd expect:

```<code>const dateTimeString = '2017-11-14T16:04:54.0086709-06:00'
const newDateTimeString = (
    moment(dateTimeString)
    .changeTime('05:20 PM')
    .format()
)
// newDateTimeString === '2017-11-14T17:20:00.0086709-06:00'
</code>```

答:
If the user-entered time is formatted as such 13:00 you could do :

```<code>   const dateTimeString = '2017-11-14T16:04:54.0086709-06:00'
var userInput = "13:20"
    const newDateTimeString = (
        moment(dateTimeString)
        .hours(userInput.split(":")[0])
        .minutes(userInput.split(":")[1])
        .format()
    )
</code>```

Using https://momentjs.com/docs/#/get-set/hour/ and https://momentjs.com/docs/#/get-set/minute/

If it's formatted with PM and AM system, you could to the same, but with a little bit more of parsing, to know if it's 5.00 AM or PM.

Body:
I'm using moment.js and want to update a date-time string with a new user-entered time. The date has not changed, only the time. There is no timezone change, just that the hour and minute values have possibly been altered.

How would I take a string like this and convert it such that the time is different?

This is would I'd expect:

const dateTimeString = '2017-11-14T16:04:54.0086709-06:00'
const newDateTimeString = (
    moment(dateTimeString)
    .changeTime('05:20 PM')
    .format()
)
// newDateTimeString === '2017-11-14T17:20:00.0086709-06:00'

Body:
If the user-entered time is formatted as such 13:00 you could do :

   const dateTimeString = '2017-11-14T16:04:54.0086709-06:00'
var userInput = "13:20"
    const newDateTimeString = (
        moment(dateTimeString)
        .hours(userInput.split(":")[0])
        .minutes(userInput.split(":")[1])
        .format()
    )

Using https://momentjs.com/docs/#/get-set/hour/ and https://momentjs.com/docs/#/get-set/minute/

If it's formatted with PM and AM system, you could to the same, but with a little bit more of parsing, to know if it's 5.00 AM or PM.


问:
how to create a multi dimensional array out of dynamically created fields and variables
here is my url: http://iadprint.com/products?product=business%20card

the fields that you see on this page are all dynamically created on the backend. i decided to use the fieldnames created as variables to display the price as you can see in the js below. I have two problems one being that when the page refreshes the pricing div values cleans out and the selections do not stay and the second one is i cant figure out how to add all items selected into an array for the cart page.

for the first problem i figured it was best to place each selection into a cookie in an array form and on refresh pull out the data and select the needed fields. unless there is another way.

this is what im guessing the array would look like

```<code>$products = array("product" => "business_card", array("ProdID" => "1"), ("ProdID" => "2") ..and so on)
</code>```

basically i would add only the fields who have a length of greater than zero so that i know it was selected. what my question is would that be the correct way to format the array? and is there a way i can do array_push in javascript to push in new elements each time a selection change is occurred?

as for problem two im hopefully guessing it will be easy once the cookie is created with its correct data.

答:
The best way, imo to handle selection in javascript is by using an object on the form

```<code>{<id1>: true, <id2>:true, etc.}
</code>```

The reason for this is that it is incredibly fast to check if something is selected, and it is very easy to convert it to an array if needed (just extract the keys).

Keeping track of a selection using an array means you have to loop over that array everytime you need to check if something is selected.

ContentLicense: CC BY-SA 2.5

Body:
here is my url: http://iadprint.com/products?product=business%20card

the fields that you see on this page are all dynamically created on the backend. i decided to use the fieldnames created as variables to display the price as you can see in the js below. I have two problems one being that when the page refreshes the pricing div values cleans out and the selections do not stay and the second one is i cant figure out how to add all items selected into an array for the cart page.

for the first problem i figured it was best to place each selection into a cookie in an array form and on refresh pull out the data and select the needed fields. unless there is another way.

this is what im guessing the array would look like

$products = array("product" => "business_card", array("ProdID" => "1"), ("ProdID" => "2") ..and so on)

basically i would add only the fields who have a length of greater than zero so that i know it was selected. what my question is would that be the correct way to format the array? and is there a way i can do array_push in javascript to push in new elements each time a selection change is occurred?

as for problem two im hopefully guessing it will be easy once the cookie is created with its correct data.

Body:
The best way, imo to handle selection in javascript is by using an object on the form

{<id1>: true, <id2>:true, etc.}

The reason for this is that it is incredibly fast to check if something is selected, and it is very easy to convert it to an array if needed (just extract the keys).

Keeping track of a selection using an array means you have to loop over that array everytime you need to check if something is selected.


问:
Tyring to pivot based on Date field
I have 2 fields that I want to pull into a query, plus a deal_balance (Decimal), and AsOfDate (Date).  I tried two different ways; neither worked but I think both are close.  The only catch is that the AsOfDate is the last working day of each month.  I'm not sure how to convert that into an Integer (1,2,etc) or an abbreviated month's name (Jan,Feb,etc.)

```<code>select Contact_ID, TB_Line,
  sum(case when [AsOfDate] = 1 then [DEAL_BALANCE] else 0 end) MonthJan,
  sum(case when [AsOfDate] = 2 then [DEAL_BALANCE] else 0 end) MonthFeb,
  sum(case when [AsOfDate] = 3 then [DEAL_BALANCE] else 0 end) MonthMar,
  sum(case when [AsOfDate] = 4 then [DEAL_BALANCE] else 0 end) MonthApr,
  sum(case when [AsOfDate] = 5 then [DEAL_BALANCE] else 0 end) MonthMay,
  sum(case when [AsOfDate] = 6 then [DEAL_BALANCE] else 0 end) MonthJun,
  sum(case when [AsOfDate] = 7 then [DEAL_BALANCE] else 0 end) MonthJul,
  sum(case when [AsOfDate] = 8 then [DEAL_BALANCE] else 0 end) MonthAug,
  sum(case when [AsOfDate] = 9 then [DEAL_BALANCE] else 0 end) MonthSep,
  sum(case when [AsOfDate] = 10 then [DEAL_BALANCE] else 0 end) MonthOct,
  sum(case when [AsOfDate] = 11 then [DEAL_BALANCE] else 0 end) MonthNov,
  sum(case when [AsOfDate] = 12 then [DEAL_BALANCE] else 0 end) MonthDec
from [TBL_HIST]
group by Contact_ID, TB_Line;

SELECT *
FROM
(
  SELECT Contact_ID, TB_Line, AsOfDate, Deal_Balance
  FROM [TBL_HIST]
) src
pivot
(
  SUM(DEAL_BALANCE)
  for AsOfDate in (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec)
) piv;
</code>```

I am using SQL Server 2008.

答:
I just got the other version working!!</p>

```<code>SELECT *
FROM
(
  SELECT Contact_ID, TB_Line, Deal_Balance, DATENAME(Month,[AsOfDate]) AS TheDate
  FROM [TBL_HIST]
) AS P
PIVOT
(
  SUM(DEAL_BALANCE) for TheDate in (January, February, March, April, May, June, July, August, September, October, November, December)
) AS PV;
</code>```

Title: Tyring to pivot based on Date field

Body:
I have 2 fields that I want to pull into a query, plus a deal_balance (Decimal), and AsOfDate (Date).  I tried two different ways; neither worked but I think both are close.  The only catch is that the AsOfDate is the last working day of each month.  I'm not sure how to convert that into an Integer (1,2,etc) or an abbreviated month's name (Jan,Feb,etc.)

select Contact_ID, TB_Line,
  sum(case when [AsOfDate] = 1 then [DEAL_BALANCE] else 0 end) MonthJan,
  sum(case when [AsOfDate] = 2 then [DEAL_BALANCE] else 0 end) MonthFeb,
  sum(case when [AsOfDate] = 3 then [DEAL_BALANCE] else 0 end) MonthMar,
  sum(case when [AsOfDate] = 4 then [DEAL_BALANCE] else 0 end) MonthApr,
  sum(case when [AsOfDate] = 5 then [DEAL_BALANCE] else 0 end) MonthMay,
  sum(case when [AsOfDate] = 6 then [DEAL_BALANCE] else 0 end) MonthJun,
  sum(case when [AsOfDate] = 7 then [DEAL_BALANCE] else 0 end) MonthJul,
  sum(case when [AsOfDate] = 8 then [DEAL_BALANCE] else 0 end) MonthAug,
  sum(case when [AsOfDate] = 9 then [DEAL_BALANCE] else 0 end) MonthSep,
  sum(case when [AsOfDate] = 10 then [DEAL_BALANCE] else 0 end) MonthOct,
  sum(case when [AsOfDate] = 11 then [DEAL_BALANCE] else 0 end) MonthNov,
  sum(case when [AsOfDate] = 12 then [DEAL_BALANCE] else 0 end) MonthDec
from [TBL_HIST]
group by Contact_ID, TB_Line;

SELECT *
FROM
(
  SELECT Contact_ID, TB_Line, AsOfDate, Deal_Balance
  FROM [TBL_HIST]
) src
pivot
(
  SUM(DEAL_BALANCE)
  for AsOfDate in (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec)
) piv;

I am using SQL Server 2008.

Body:
I just got the other version working!!

SELECT *
FROM
(
  SELECT Contact_ID, TB_Line, Deal_Balance, DATENAME(Month,[AsOfDate]) AS TheDate
  FROM [TBL_HIST]
) AS P
PIVOT
(
  SUM(DEAL_BALANCE) for TheDate in (January, February, March, April, May, June, July, August, September, October, November, December)
) AS PV;


问:
HTTP Basic: Access denied fatal: Authentication failed
I use GitLab Community Edition 9.1.3 2e4e522 on Windows 10 Pro x64. With Git client.

Error

```<code>Cloning into 'project_name'...
remote: HTTP Basic: Access denied
fatal: Authentication failed for 'http://my_user_name@example.com/my_user_name/project_name.git/'
</code>```

How to fix it?

答: A simple git fetch/pull command will throw a authentication failed message. But do the same git fetch/pull command second time, and it should prompt a window asking for credential(username/password). Enter your Id and new password and it should save and move on.</p>

Body:
I use GitLab Community Edition 9.1.3 2e4e522 on Windows 10 Pro x64. With Git client.

Error

Cloning into 'project_name'...
remote: HTTP Basic: Access denied
fatal: Authentication failed for 'http://my_user_name@example.com/my_user_name/project_name.git/'

How to fix it?


问:
Function type mismatch
I have a function with function type :

```<code>newtonRootSequence' :: Double -> Double -> [Double]
</code>```

and function definition:

```<code>newtonRootSequence' xn d = [(xn + (d * (1/xn))) div 2] ++ newtonRootSequence' ((xn + (d * (1/xn))) div 2) d
</code>```

upon receiving two values xn and d it should calculate the results for the given function

```<code>[(xn + (d * (1/xn))) div 2]
</code>```

But for some reason on launch the compilator is not accepting the function with an error:

Couldnt match expected type '(Integer->Integer->Integer->) ->Integer
  ->Double with actual type double the function (xn + (d * (1/xn))) div 2) is applied to two arguments

This error occurs to the part where I try to send the result of the equation into the recursive step

```<code>++ newtonRootSequence' ((xn + (d * (1/xn))) div 2) d
</code>```

答:
As already mentioned in the comments:

if you want to use div as an infix function, you have to enclose it in backticks

div is for integral division with truncation towards negative infinity, not for dividing Double

These two points are the cause for your error message.

To divide Doubles, use the / operator like you already did in your expression 1/xn.

With this your code should work. For clarity it could be transformed:

Extract the duplicated expression to compute the next xn in the sequence into a where clause. The expression can also be slightly simplified. Adding a single element in front of a list can simply be done with the cons operator (:):

```<code>newtonRootSequence' xn d = xn' : newtonRootSequence' xn' d
    where xn' = (xn + (d / xn)) / 2
</code>```

You could use iterate :: (a -> a) -> a -> [a] from the Prelude to separate the computation for a single step from the generation of the list of intermediate steps (note the flipped arguments):

```<code>sequenceStep :: Double -> Double -> Double
sequenceStep s xn = (xn + (s / xn)) / 2

newtonRootSequence' :: Double -> Double -> [Double]
newtonRootSequence' s x0 = iterate (sequenceStep s) x0
</code>```

Title: Function type mismatch

Body:
I have a function with function type :

newtonRootSequence' :: Double -> Double -> [Double]

and function definition:

newtonRootSequence' xn d = [(xn + (d * (1/xn))) div 2] ++ newtonRootSequence' ((xn + (d * (1/xn))) div 2) d

upon receiving two values xn and d it should calculate the results for the given function

[(xn + (d * (1/xn))) div 2]

But for some reason on launch the compilator is not accepting the function with an error:

Couldnt match expected type '(Integer->Integer->Integer->) ->Integer
  ->Double with actual type double the function (xn + (d * (1/xn))) div 2) is applied to two arguments

This error occurs to the part where I try to send the result of the equation into the recursive step

++ newtonRootSequence' ((xn + (d * (1/xn))) div 2) d

Body:
As already mentioned in the comments:

if you want to use div as an infix function, you have to enclose it in backticks

div is for integral division with truncation towards negative infinity, not for dividing Double

These two points are the cause for your error message.

To divide Doubles, use the / operator like you already did in your expression 1/xn.

With this your code should work. For clarity it could be transformed:

Extract the duplicated expression to compute the next xn in the sequence into a where clause. The expression can also be slightly simplified. Adding a single element in front of a list can simply be done with the cons operator (:):

newtonRootSequence' xn d = xn' : newtonRootSequence' xn' d
    where xn' = (xn + (d / xn)) / 2

You could use iterate :: (a -> a) -> a -> [a] from the Prelude to separate the computation for a single step from the generation of the list of intermediate steps (note the flipped arguments):

sequenceStep :: Double -> Double -> Double
sequenceStep s xn = (xn + (s / xn)) / 2

newtonRootSequence' :: Double -> Double -> [Double]
newtonRootSequence' s x0 = iterate (sequenceStep s) x0


问:
adjusting python autoviv to take "+=1" increments
I am using some common python autovivification code build dictionaries:

```<code>class autoviv(dict):
    """Implementation of perl's autovivification feature."""

    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value
</code>```

One thing I'd love to be able to is to increment values in the case where no key currently exists at the specified dictionary nesting level, using += notation like so:

```<code>d['a']+=1
</code>```

Doing so will return the error:

```<code>TypeError: unsupported operand type(s) for +=: 'autoviv' and 'int'
</code>```

To get around this I've built a step that checks whether the key exists before incrementing it, but I'd love to do away with that step if I could.

How should I modify the above autoviv() code to get this enhancement?  I've googled and tried different approaches for a few hours but no joy.

Thanks for any advice!

答:
Autovivication is already in Python, inside of collections' defaultdict.

```<code>from collections import defaultdict

#Let's say we want to count every character
#  that occurs
text = "Let's implement autovivication!"
di = defaultdict(int)
for char in text:
    di[char] += 1
print(di)

#Another way of doing this is using a defualt string
#  (or default int, or whatever you want)
currentDict = {'bob':'password','mike':'12345'}
di = defaultdict(lambda:'unknown user', currentDict)
print(di['bob'])
print(di['sheryl'])
</code>```

However, if you're trying to implement your own.  You should assign your item and then get the reference to it.

```<code>def __getitem__(self, item):
    try:
        return dict.__getitem__(self, item)
    except KeyError:
        value = self[item] = type(self)()
        return dict.__getitem__(self, item)
</code>```

Body:
I am using some common python autovivification code build dictionaries:

class autoviv(dict):
    """Implementation of perl's autovivification feature."""

    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value

One thing I'd love to be able to is to increment values in the case where no key currently exists at the specified dictionary nesting level, using += notation like so:

d['a']+=1

Doing so will return the error:

TypeError: unsupported operand type(s) for +=: 'autoviv' and 'int'

To get around this I've built a step that checks whether the key exists before incrementing it, but I'd love to do away with that step if I could.

How should I modify the above autoviv() code to get this enhancement?  I've googled and tried different approaches for a few hours but no joy.

Thanks for any advice!

Body:
Autovivication is already in Python, inside of collections' defaultdict.

from collections import defaultdict

#Let's say we want to count every character
#  that occurs
text = "Let's implement autovivication!"
di = defaultdict(int)
for char in text:
    di[char] += 1
print(di)

#Another way of doing this is using a defualt string
#  (or default int, or whatever you want)
currentDict = {'bob':'password','mike':'12345'}
di = defaultdict(lambda:'unknown user', currentDict)
print(di['bob'])
print(di['sheryl'])

However, if you're trying to implement your own.  You should assign your item and then get the reference to it.

def __getitem__(self, item):
    try:
        return dict.__getitem__(self, item)
    except KeyError:
        value = self[item] = type(self)()
        return dict.__getitem__(self, item)


问:
Installing a package (conda) results in ImportError: Library not loaded
I installed seaborn package through conda:

```<code>~user: conda install seaborn

The following NEW packages will be INSTALLED:
seaborn:     0.8-py27_0
The following packages will be UPDATED:
conda:       4.3.8-py27_0     --> 4.3.30-py27h407ed3a_0
matplotlib:  1.4.3-np19py27_2 --> 1.5.3-np111py27_1
statsmodels: 0.6.1-np19py27_0 --> 0.8.0-np111py27_0
</code>```

And it messed up my matplotlib installation, now when I run my python script, it raises an error when importing matplotlib:

```<code>ImportError: dlopen(/Users/.../anaconda/lib/python2.7/site-packages/matplotlib/_png.so, 2): Library not loaded: @rpath/libpng16.16.dylib
Referenced from: /Users/.../anaconda/lib/python2.7/site-packages/matplotlib/_png.so
Reason: Incompatible library version: _png.so requires version 39.0.0 or later, but libpng16.16.dylib provides version 34.0.0
</code>```

答:
This error can be caused by old version of conda. You need to first update conda and then try again. </p>

```<code>conda update conda
</code>```

Body:
I installed seaborn package through conda:

~user: conda install seaborn

The following NEW packages will be INSTALLED:
seaborn:     0.8-py27_0
The following packages will be UPDATED:
conda:       4.3.8-py27_0     --> 4.3.30-py27h407ed3a_0
matplotlib:  1.4.3-np19py27_2 --> 1.5.3-np111py27_1
statsmodels: 0.6.1-np19py27_0 --> 0.8.0-np111py27_0

And it messed up my matplotlib installation, now when I run my python script, it raises an error when importing matplotlib:

ImportError: dlopen(/Users/.../anaconda/lib/python2.7/site-packages/matplotlib/_png.so, 2): Library not loaded: @rpath/libpng16.16.dylib
Referenced from: /Users/.../anaconda/lib/python2.7/site-packages/matplotlib/_png.so
Reason: Incompatible library version: _png.so requires version 39.0.0 or later, but libpng16.16.dylib provides version 34.0.0

Body:
This error can be caused by old version of conda. You need to first update conda and then try again.

conda update conda


问:
Extract type from subexpression in template
Given the following templated function:

```<code>template <typename T>
void f(std::function <void (T)>) {}
</code>```

Can I extract T without having to explicitly mention it when calling f?

f<int>([](int){}); works fine but I'd like T to be deduced and f([](int){}); to just work. The latter errors out with "no matching function for call to".

答:
You can deduce T if the object passed into the function actually has type std::function<void(T)>. If the type you pass in is a lambda, then you'll have to deduce it from the type of the lambda's function call operator, like so:

```<code>template <class Callable, class Arg, class T>
void f_helper(Callable callable, Ret (Callable::*)(T)) {
    // do something with T
}

template <class Callable>
void f(Callable callable) {
    f_helper(callable, &callable::operator());
}
</code>```

Actually, in reality it is a bit more annoying than this, because you need at least two overloads for f_helper, according to whether the lambda is declared mutable (which determines whether operator() is const), and in C++17 you also need to double the number of overloads again according to whether the lambda is noexcept.

The standard library sidesteps issues like this by not attempting to extract the argument type from the callables you pass to algorithms such as std::sort. It just accepts an arbitrary callable type and then tries to call it.

Body:
Given the following templated function:

template <typename T>
void f(std::function <void (T)>) {}

Can I extract T without having to explicitly mention it when calling f?

f<int>([](int){}); works fine but I'd like T to be deduced and f([](int){}); to just work. The latter errors out with "no matching function for call to".

Body:
You can deduce T if the object passed into the function actually has type std::function<void(T)>. If the type you pass in is a lambda, then you'll have to deduce it from the type of the lambda's function call operator, like so:

template <class Callable, class Arg, class T>
void f_helper(Callable callable, Ret (Callable::*)(T)) {
    // do something with T
}

template <class Callable>
void f(Callable callable) {
    f_helper(callable, &callable::operator());
}

Actually, in reality it is a bit more annoying than this, because you need at least two overloads for f_helper, according to whether the lambda is declared mutable (which determines whether operator() is const), and in C++17 you also need to double the number of overloads again according to whether the lambda is noexcept.

The standard library sidesteps issues like this by not attempting to extract the argument type from the callables you pass to algorithms such as std::sort. It just accepts an arbitrary callable type and then tries to call it.


答:
One possible way is to use moment to grab the date and then combine it with your custom time value in another moment() call like so:

```<code>const newDateTimeString = (
    moment(`${moment(dateTimeString).format('YYYY-MM-DD')} 05:20 PM`)
    .format()
)
</code>```

Title: In moment.js, is it possible to have a date-time string and keep the date but change the time?

Body:
One possible way is to use moment to grab the date and then combine it with your custom time value in another moment() call like so:

const newDateTimeString = (
    moment(`${moment(dateTimeString).format('YYYY-MM-DD')} 05:20 PM`)
    .format()
)


问:
Java - quidditch program using arraylists
I am supposed to create a quidditch program using arraylists but I am kinda confused and my teacher isn't helpful whatsoever. I know how to create the array list and add them, remove, the basic uses of array list. The way he has the directions worded confuse me, any help about where to start would be great.

I can do most of the work for this program,
the main confusion for me is part a, how to pair the teams to go against each other and how to do the multiple rounds.

Im not asking for anyone to do this program, I'm just asking for some help, explanation and pointers on where to start. Thanks a lot guys.

Directions:

Create an ArrayList of Strings containing the names of your 8 ‘teams’.  Use humorous names for your teams (Dwarves, Wizards, Dinosaurs, etc.)

Code a method public void playGame(int teamA, int teamB, ArryList teams)

a.  teamA and teamB are the indices (sic. Indexes) of the teams that are playing the current game.  You will use these to retrieve the String name of the team.
For our purposes a Quiddich game has four quarters:

b.  Each team randomly scores 0 to 4 goals worth 10 points each per quarter (0 – 40 points per quarter.
c.  Each quarter, there is a 15% chance that a team will capture the Golden snitch. If that happens the game ends immediately and that team wins.
(First determine if a team got the snitch, then if one did randomize which one wins with even probability.)

d.  The method should display the results for each quarter that is played and indicate the final score or if the teams won by capturing the snitch.

e.  There are no ties. Play additional sudden death quarters until one team wins.

f.  Your method should remove the loosing team from the ArrayList and print a msg that that team (using the String name) has been eliminated from the Tourney.

Code your main program to display the list of teams. Then run the tournament.  For each round pit every other team against one another.
a.  First round: 4 games reduces teams to 4 remaining.
b.  Second round: 2 games reduces teams to final 2
c.  Final round: 1 game determines the tournament winner.

Each time show the list of remaining teams and use your method to run the games for that round. (Hint: just use even/odd indices for the pairings: Team index 0 plays team index 1, team index 2 plays team index 3, etc.)

答:
I think the answer is in the last point - the teams shouldn't play in a "league" way (one vs all others) but in a "cup" way (the one that loses won't play anymore). The teams should be divided like this: even vs odd. I believe the simplest way to do this would be:

```<code>for(int i = 0; i < teams.size(); i = i + 2) {
    playGame(i, i + 1, teams);
}
</code>```

Assuming, that there will be even number of all teams of course.

Body:
I think the answer is in the last point - the teams shouldn't play in a "league" way (one vs all others) but in a "cup" way (the one that loses won't play anymore). The teams should be divided like this: even vs odd. I believe the simplest way to do this would be:

for(int i = 0; i < teams.size(); i = i + 2) {
    playGame(i, i + 1, teams);
}

Assuming, that there will be even number of all teams of course.


问:
Converting UNIX TimeStamp in Android API versions LESS than 24
I am developing an app which I want specifically to work Android API 23. I need to convert a UNIX timestamp into an actual time/date.

I have seen this solution which mentions SimpleDateFormat;

Convert unix time stamp to date in java

However, this is only supported in API 24 and higher. Any ideas on how to achieve this in API 23?

答:
I think you may be using android.icu.text.SimpleDateFormat instead of java.text.SimpleDateFormat.

The former one was added in API level 24, the later one should work fine for all API levels.


问:
Create pipe for angular2 for iterating JSON to array
I'm trying to use the following JSON data and convert it into an array, so I can run *ngFor='let item of items' and display data in terms of item.name etc...

I tried the following:

```<code>var out = [];
for(var key1 in object) {
    out[key1] = key1;
  for(var key2 in object[key1]) {
    for(var key3 in object[key2]) {
        out[key1][key2] = key3;
        }
  }
  console.log(out);
}
</code>```

But Im just getting the title as key and value.

```<code>var object = {
  "compressorClutch": {
    "name": "compressorClutch",
    "param": "Y",
    "register": "64",
    "type": "b"
  },
  "batteryLive": {
    "name": "batteryLive",
    "param": "Y",
    "register": "53",
    "type": "b"
  },
  "batteryGround": {
    "name": "batteryGround",
    "param": "Y",
    "register": "85",
    "type": "b"
  },
  "mainsCable": {
    "name": "mainsCable",
    "param": "N",
    "register": "",
    "type": "b"
  },
  "kcb": {
    "name": "kcb",
    "param": "13",
    "register": "337",
    "type": "i"
  },
  "config": "LorA-F"
}
</code>```

答:
If you want to use a JSONArray it should be formatted like so:

```<code>  object = [
    {
      'name': 'compressorClutch',
      'param': 'Y',
      'register': '64',
      'type': 'b'
    },
    {
      'name': 'batteryLive',
      'param': 'Y',
      'register': '53',
      'type': 'b'
    },
    {
      'name': 'batteryGround',
      'param': 'Y',
      'register': '85',
      'type': 'b'
    },
    {
      'name': 'mainsCable',
      'param': 'N',
      'register': '',
      'type': 'b'
    },
    {
      'name': 'kcb',
      'param': '13',
      'register': '337',
      'type': 'i'
    }
  ];
</code>```

That is capable of being used in an *ngFor easily to display the data. The object keys as names are redundant as you also have a 'name' field in the JSONObject. To find the right object that matches maybe a search query such as 'mainCables' you could just filter the array based on one of the object values. I hope this can be of some help for what you are trying to do.

Body:
I'm trying to use the following JSON data and convert it into an array, so I can run *ngFor='let item of items' and display data in terms of item.name etc...

I tried the following:

var out = [];
for(var key1 in object) {
    out[key1] = key1;
  for(var key2 in object[key1]) {
    for(var key3 in object[key2]) {
        out[key1][key2] = key3;
        }
  }
  console.log(out);
}

But Im just getting the title as key and value.

var object = {
  "compressorClutch": {
    "name": "compressorClutch",
    "param": "Y",
    "register": "64",
    "type": "b"
  },
  "batteryLive": {
    "name": "batteryLive",
    "param": "Y",
    "register": "53",
    "type": "b"
  },
  "batteryGround": {
    "name": "batteryGround",
    "param": "Y",
    "register": "85",
    "type": "b"
  },
  "mainsCable": {
    "name": "mainsCable",
    "param": "N",
    "register": "",
    "type": "b"
  },
  "kcb": {
    "name": "kcb",
    "param": "13",
    "register": "337",
    "type": "i"
  },
  "config": "LorA-F"
}

Body:
If you want to use a JSONArray it should be formatted like so:

  object = [
    {
      'name': 'compressorClutch',
      'param': 'Y',
      'register': '64',
      'type': 'b'
    },
    {
      'name': 'batteryLive',
      'param': 'Y',
      'register': '53',
      'type': 'b'
    },
    {
      'name': 'batteryGround',
      'param': 'Y',
      'register': '85',
      'type': 'b'
    },
    {
      'name': 'mainsCable',
      'param': 'N',
      'register': '',
      'type': 'b'
    },
    {
      'name': 'kcb',
      'param': '13',
      'register': '337',
      'type': 'i'
    }
  ];

That is capable of being used in an *ngFor easily to display the data. The object keys as names are redundant as you also have a 'name' field in the JSONObject. To find the right object that matches maybe a search query such as 'mainCables' you could just filter the array based on one of the object values. I hope this can be of some help for what you are trying to do.


问:
Canadian data and iOS push notiifcations
I've inherited an application that works with data for Canadian schools.  One aspect of this application is that we have a feature that lets us push notifications to parents using iOS push notifications.  We have a legal requirement that none of the personally identifying information we work with leaves Canada.

From what I've read, iOS push notifications go through api.push.apple.com, which I'd assume resides in the US.  Is there a Canadian server that we can use instead?

答:
You should design your application such that no sensitive/private data should not be sent through push notifications. It should contain generic statements such as "Important information available regarding Mathematics exam of student." or "Results available for examination held last week !!"

You should download specific data once parent opens the app


问:
Share an Inline Message link with User Conversation via Telegram Bot
I'm using node-telegram-bot-api and I Have an inline Keyboard, How Can I Share a link When a user click on that Inline Link?
I need to Choose an Conversation and
after that paste this link in that Conversation:  </p>

<p>(telegram.me/my_bot?start)</p>

```<code>    const iopts = {
        reply_markup: {
            inline_keyboard: [
                [{
                    text: `Share This Bot to Your Friends`,
                    url: `telegram.me/my_bot?start`
                }]
            ]
        }
    };
</code>```

答: You can use switch_inline_query instead of url, see following example:

Body:
I'm using node-telegram-bot-api and I Have an inline Keyboard, How Can I Share a link When a user click on that Inline Link?
I need to Choose an Conversation and
after that paste this link in that Conversation:

(telegram.me/my_bot?start)

    const iopts = {
        reply_markup: {
            inline_keyboard: [
                [{
                    text: `Share This Bot to Your Friends`,
                    url: `telegram.me/my_bot?start`
                }]
            ]
        }
    };


问:
Access a JS variable inside an html or ejs page
I have a js file with JSON object like-
say main.js

```<code>const person = {};
person.AGE = '17';
person.GENDER = 'Male';
</code>```

The file is loaded in .ejs file like:

```<code><script type="text/javascript" charset="utf-8" src="main.js"></script>
</code>```

Is there any way I can directly access this person variable in HTML or EJS page, say

```<code><li></li>
</code>```

I want to write person.GENDER inside li tag.

I know I can have a JS and can use innerHTML and all but is there any way to access directly specifically in .ejs page?

Also, is there a way that I can load my scripts dynamically. Say I have two scripts: ScriptA and ScriptB

Checking some conditions I want to load a particular script. Any idea for doing that?

答:
Also, is there a way that I can load my scripts dynamically. Say I have two scripts: ScriptA and ScriptB.
  Checking some conditions I want to load a particular script. Any idea for doing that?

Do, what EJS was made for:

```<code><html>
<head>
<!-- head -->
    <% if(condictionA) { %>
    <script type="text/javascript" charset="utf-8" src="main.js"></script>
    <% }
    if (conditionB) { %>
    <script type="text/javascript" charset="utf-8" src="main2.js"></script>
    <% } %>
<!-- head -->
</head>
....
</code>```

Body:
I have a js file with JSON object like-
say main.js

const person = {};
person.AGE = '17';
person.GENDER = 'Male';

The file is loaded in .ejs file like:

Is there any way I can directly access this person variable in HTML or EJS page, say

I want to write person.GENDER inside li tag.

I know I can have a JS and can use innerHTML and all but is there any way to access directly specifically in .ejs page?

Also, is there a way that I can load my scripts dynamically. Say I have two scripts: ScriptA and ScriptB

Checking some conditions I want to load a particular script. Any idea for doing that?

Body:
Also, is there a way that I can load my scripts dynamically. Say I have two scripts: ScriptA and ScriptB.
  Checking some conditions I want to load a particular script. Any idea for doing that?

Do, what EJS was made for:

<html>
<head>
<!-- head -->
    <% if(condictionA) { %>
    <script type="text/javascript" charset="utf-8" src="main.js"></script>
    <% }
    if (conditionB) { %>
    <script type="text/javascript" charset="utf-8" src="main2.js"></script>
    <% } %>
<!-- head -->
</head>
....


问:
How do I place an image at the right margin?
I'm trying to place an image against the right-hand margin of a google doc using scripts. I've got this calculation for the left offset:

```<code>body.getPageWidth()-body.getMarginRight()-body.getMarginLeft()-myImage.imageWidth
</code>```

This consistently places the image 5/8 of an inch inside the margin. I thought maybe this might be something to do with the automatic margin around a wrapped image? I can't find a way to control that in the PositionedImage documentation though.

Is there an extra element I'm missing in my calculation for the left offset? Something else I'm failing to allow for? Is there another method I can use to place the image?

答:
Is the image already a PositionedImage - was it moved to a PositionedImage? or is there a choice? If it is an InlineImage; Then you can getParent() and setAttributes() LEFT_TO_RIGHT. It will re-position against the right margin.

```<code>function imgRight() {
  var doc = DocumentApp.getActiveDocument()
  var body = doc.getBody()
  // Get the first inline image in the doc.body
  var img_container = body.getImages()[0].getParent()

  // Set the ContainerElement to right_to_left
  img_container.setAttributes({LEFT_TO_RIGHT:false})
}
</code>```

edit and update: The issue with the calculation for PositionedImage.LeftOffset is that the image.getWidth() returns the width in pixels and the margins and page size in points. Convert the img pixels to points and the offset calculation would look something like:

```<code>var body = DocumentApp.getActiveDocument().getBody();
var body_attributes = body.getAttributes();

var img = body.getParagraphs()[0].getPositionedImages()[0];
var img_width = img.getWidth();
var img_in_points = img_width * 72/96;
var current_img_offset = img.getLeftOffset();

var offset = body_attributes.PAGE_WIDTH - body_attributes.MARGIN_RIGHT - body_attributes.MARGIN_LEFT  - img_in_points + current_img_offset;
</code>```

Body:
I'm trying to place an image against the right-hand margin of a google doc using scripts. I've got this calculation for the left offset:

body.getPageWidth()-body.getMarginRight()-body.getMarginLeft()-myImage.imageWidth

This consistently places the image 5/8 of an inch inside the margin. I thought maybe this might be something to do with the automatic margin around a wrapped image? I can't find a way to control that in the PositionedImage documentation though.

Is there an extra element I'm missing in my calculation for the left offset? Something else I'm failing to allow for? Is there another method I can use to place the image?

Body:
Is the image already a PositionedImage - was it moved to a PositionedImage? or is there a choice? If it is an InlineImage; Then you can getParent() and setAttributes() LEFT_TO_RIGHT. It will re-position against the right margin.

function imgRight() {
  var doc = DocumentApp.getActiveDocument()
  var body = doc.getBody()
  // Get the first inline image in the doc.body
  var img_container = body.getImages()[0].getParent()

  // Set the ContainerElement to right_to_left
  img_container.setAttributes({LEFT_TO_RIGHT:false})
}

edit and update: The issue with the calculation for PositionedImage.LeftOffset is that the image.getWidth() returns the width in pixels and the margins and page size in points. Convert the img pixels to points and the offset calculation would look something like:

var body = DocumentApp.getActiveDocument().getBody();
var body_attributes = body.getAttributes();

var img = body.getParagraphs()[0].getPositionedImages()[0];
var img_width = img.getWidth();
var img_in_points = img_width * 72/96;
var current_img_offset = img.getLeftOffset();

var offset = body_attributes.PAGE_WIDTH - body_attributes.MARGIN_RIGHT - body_attributes.MARGIN_LEFT  - img_in_points + current_img_offset;


问:
center button and glyphicon on different lines
As part of a small jQuery project, I'm trying to have a Bootstrap glyphicon and button centered and with a line break between them. Right now the glyphicon stays centered, but the button shifts a bit left/right depending on the container's size (at its smallest, it appears off to the left).

How can I make both elements be centered on different lines within their parent
?

The html below shows two glyphicons, but I'm using jquery to unhide one of them upon clicking the correct button.

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');

#questionmark {
    font-size: 15px;
    color: purple;
    border-bottom: 2px solid purple;
    padding: 0 10px 2px 10px;
}

.btn {
    font-family: Geneva, "Helvetica Neue", Helvetica, Arial, sans-serif;
}

p {
    font-family: "Courier New", Courier, "Lucida Sans Typewriter", "Lucida Typewriter", monospace;
}

.valign{
    line-height:46px;
    vertical-align:middle;
}

.glyphicon-ok-sign {
    font-size: 40px;
    color: green;
}

.glyphicon-warning-sign {
    font-size: 40px;
    color: red;
}

.hide {
    display: none;
}

#display-sentence {
    display: none;
}

.highlight {
    background-color: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <h1 class="text-center text-primary">¿POR O PARA?</h1>
    <br>
    <div class="jumbotron">
        <br>
        <p><span id="test-sentence"></span></p>
    </div>
    <div class="col-xs-10 col-xs-offset-1">
        <div class="row">
            <div class="col-xs-4">
                <button type="button" class="btn test-btn btn-primary btn-lg" id="por-btn">por</button>
            </div>
            <div class="col-xs-4 text-center valign">
                <p class="text-center">
                    <!-- I'm trying to center the following, only one glyphicon will be desplayed at a time, along with the #reload-btn -->
                    <span class="glyphicon glyphicon-ok-sign hide"></span>
                    <span class="glyphicon glyphicon-warning-sign hide"></span>
                    <br>
                    <button type="button" class="btn btn-success pull-right btn-lg hide" id="reload-btn">¡OTRA!</button>
                </p>
            </div>
            <div class="col-xs-4">
                <button type="button" class="btn test-btn btn-primary pull-right btn-lg" id="para-btn">para</button>
            </div>
        </div>
    </div>
</div></code>```

答:
You can keep the glyphicons centered by setting relative position to parent element, the paragraph with "text-center" class in this case. The glyphicons are centered then. Hope this helps and answers your question.</p>

```<code>.glyphicon-ok-sign {
  position: absolute;
  font-size: 40px;
  color: green;
}

.glyphicon-warning-sign {
  position: absolute;
  font-size: 40px;
  color: red;
}

p.text-center {
    position: relative;
}
</code>```

Body:
As part of a small jQuery project, I'm trying to have a Bootstrap glyphicon and button centered and with a line break between them. Right now the glyphicon stays centered, but the button shifts a bit left/right depending on the container's size (at its smallest, it appears off to the left).

How can I make both elements be centered on different lines within their parent
?

The html below shows two glyphicons, but I'm using jquery to unhide one of them upon clicking the correct button.

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');

#questionmark {
    font-size: 15px;
    color: purple;
    border-bottom: 2px solid purple;
    padding: 0 10px 2px 10px;
}

.btn {
    font-family: Geneva, "Helvetica Neue", Helvetica, Arial, sans-serif;
}

p {
    font-family: "Courier New", Courier, "Lucida Sans Typewriter", "Lucida Typewriter", monospace;
}

.valign{
    line-height:46px;
    vertical-align:middle;
}

.glyphicon-ok-sign {
    font-size: 40px;
    color: green;
}

.glyphicon-warning-sign {
    font-size: 40px;
    color: red;
}

.hide {
    display: none;
}

#display-sentence {
    display: none;
}

.highlight {
    background-color: yellow;
}

¿POR O PARA?

                <button type="button" class="btn test-btn btn-primary btn-lg" id="por-btn">por</button>

                    <button type="button" class="btn btn-success pull-right btn-lg hide" id="reload-btn">¡OTRA!</button>

                <button type="button" class="btn test-btn btn-primary pull-right btn-lg" id="para-btn">para</button>

Body:
You can keep the glyphicons centered by setting relative position to parent element, the paragraph with "text-center" class in this case. The glyphicons are centered then. Hope this helps and answers your question.

.glyphicon-ok-sign {
  position: absolute;
  font-size: 40px;
  color: green;
}

.glyphicon-warning-sign {
  position: absolute;
  font-size: 40px;
  color: red;
}

p.text-center {
    position: relative;
}


问:
sqlalchemy: Passign a form input to a filter does not return any results
```<code>db = create_engine('mysql://usr:passwd@localhost/DB',
isolation_level="READ UNCOMMITTED")
metadata = MetaData(db)
Session = sessionmaker(bind=db)
session = Session()
server = Table('server', metadata, autoload=True)

if (model is not None):
  # The below == works and returns results
  #s = session.query(server).filter(server.c.product == model)
  #This returns nothing
  s = session.query(server).filter(server.c.product.like("%model%")).all()
</code>```

model is passed as a form parameter

```<code>@app.route('/serverHandleList', methods=['POST'])
def serverHandleList():
model = request.form['inputModelName']
serverItems = getModel(model)

return render_template('some.html', items=serverItems, name=model)
</code>```

What am I doing wrong? Any help much appreciated. Thanks!

答:
You are currently searching for the word "model" instead of what's being passed in the variable model.

Change to this instead:

```<code>  s = session.query(server).filter(server.c.product.like("%{}%".format(model))).all()
</code>```

Body:
db = create_engine('mysql://usr:passwd@localhost/DB',
isolation_level="READ UNCOMMITTED")
metadata = MetaData(db)
Session = sessionmaker(bind=db)
session = Session()
server = Table('server', metadata, autoload=True)

if (model is not None):
  # The below == works and returns results
  #s = session.query(server).filter(server.c.product == model)
  #This returns nothing
  s = session.query(server).filter(server.c.product.like("%model%")).all()

model is passed as a form parameter

@app.route('/serverHandleList', methods=['POST'])
def serverHandleList():
model = request.form['inputModelName']
serverItems = getModel(model)

return render_template('some.html', items=serverItems, name=model)

What am I doing wrong? Any help much appreciated. Thanks!

Body:
You are currently searching for the word "model" instead of what's being passed in the variable model.

Change to this instead:

  s = session.query(server).filter(server.c.product.like("%{}%".format(model))).all()


问:
Build DLL error
First I still embrace the concept of a dll and now I'm trying to make one for myself but i get this when i try to build:

```<code>error C2059: syntax error: '__declspec(dllimport)'
error C2238: unexpected token(s) preceding ';'
error C2059: syntax error: '__declspec(dllimport)'
error C2238: unexpected token(s) preceding ';'
</code>```

Vec2.h:

```<code>#pragma once

#ifdef VECTORLIB_EXPORTS
#define VECTORLIB_API __declspec(dllexport)
#else
#define VECTORLIB_API __declspec(dllimport)
#endif

class Vec2
{
public:
    Vec2() = default;
    VECTORLIB_API Vec2(double x, double y);
    Vec2 VECTORLIB_API operator+(Vec2& rhs);
    Vec2 VECTORLIB_API operator*(double& rhs);
    Vec2& VECTORLIB_API operator+=(Vec2& rhs);
    Vec2& VECTORLIB_API operator*=(double& rhs);

public:
    //public vars///////
    double x, y;
    ////////////////////
};
</code>```

stdafx.h:

```<code>// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//

#pragma once

#include "targetver.h"

#define WIN32_LEAN_AND_MEAN// Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>

#include "Vec2.h"

// TODO: reference additional headers your program requires here
</code>```

Vector2.cpp:

```<code>// Vector2.cpp : Defines the exported functions for the DLL application.
//

#include "stdafx.h"

Vec2::Vec2(double x, double y) : x(x), y(y) {}

Vec2 Vec2::operator+(Vec2& rhs)
{
    return Vec2( x + rhs.x, y + rhs.y );
}

Vec2 Vec2::operator*(double& rhs)
{
    return Vec2( x * rhs, y * rhs );
}

Vec2& Vec2::operator+=(Vec2& rhs)
{
    return ( *this = *this + rhs );
}

Vec2& Vec2::operator*=(double& rhs)
{
    return ( *this = *this * rhs);
}
</code>```

The dll is a start of a vector2d class for me to use later.
I understand that the code is probably not in the way it is supposed to be but i'm just starting to hang on these concepts so any tips are more than welcome.

答:
Place the VECTORLIB_API before the return type.  See here

```<code>VECTORLIB_API Vec2 operator+(Vec2& rhs);
</code>```

You can also just add it to the class. See here

```<code>class VECTORLIB_API Vec2 {
  ...
};
</code>```

Title: Build DLL error

Body:
First I still embrace the concept of a dll and now I'm trying to make one for myself but i get this when i try to build:

error C2059: syntax error: '__declspec(dllimport)'
error C2238: unexpected token(s) preceding ';'
error C2059: syntax error: '__declspec(dllimport)'
error C2238: unexpected token(s) preceding ';'

Vec2.h:

#pragma once

#ifdef VECTORLIB_EXPORTS
#define VECTORLIB_API __declspec(dllexport)
#else
#define VECTORLIB_API __declspec(dllimport)
#endif

class Vec2
{
public:
    Vec2() = default;
    VECTORLIB_API Vec2(double x, double y);
    Vec2 VECTORLIB_API operator+(Vec2& rhs);
    Vec2 VECTORLIB_API operator*(double& rhs);
    Vec2& VECTORLIB_API operator+=(Vec2& rhs);
    Vec2& VECTORLIB_API operator*=(double& rhs);

public:
    //public vars///////
    double x, y;
    ////////////////////
};

stdafx.h:

// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//

#pragma once

#include "targetver.h"

#define WIN32_LEAN_AND_MEAN// Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>

#include "Vec2.h"

// TODO: reference additional headers your program requires here

Vector2.cpp:

// Vector2.cpp : Defines the exported functions for the DLL application.
//

#include "stdafx.h"

Vec2::Vec2(double x, double y) : x(x), y(y) {}

Vec2 Vec2::operator+(Vec2& rhs)
{
    return Vec2( x + rhs.x, y + rhs.y );
}

Vec2 Vec2::operator*(double& rhs)
{
    return Vec2( x * rhs, y * rhs );
}

Vec2& Vec2::operator+=(Vec2& rhs)
{
    return ( *this = *this + rhs );
}

Vec2& Vec2::operator*=(double& rhs)
{
    return ( *this = *this * rhs);
}

The dll is a start of a vector2d class for me to use later.
I understand that the code is probably not in the way it is supposed to be but i'm just starting to hang on these concepts so any tips are more than welcome.

Body:
Place the VECTORLIB_API before the return type.  See here

VECTORLIB_API Vec2 operator+(Vec2& rhs);

You can also just add it to the class. See here

class VECTORLIB_API Vec2 {
  ...
};


问:
Condense Repeated Excel Formula Cell References into one Cell Reference
Is there a way to condense Excel Formula references into one reference while keeping the formula contained to one cell?

For reference the formula I am using is

```<code>=VALUE(SUBSTITUTE(RIGHT(G4,LEN(G4)-
 MIN(FIND({0,1,2,3,4,5,6,7,8,9},G4&"0123456789"))+1),"-","."))
</code>```

Which References G4 multiple times, I would like someway to make it so I or another user only has to change G4 in one place should the change be required.

Perhaps something like this (Not real excel formula:)

```<code>=MULTIPLEX(VALUE(SUBSTITUTE(RIGHT(#1,LEN(#1)-
 MIN(FIND({0,1,2,3,4,5,6,7,8,9},#1&"0123456789"))+1),"-",".")),#1,G4)
</code>```

So that the #1 does not need to be changed and the G4 being changed once updates the whole formula.

I was trying to avoid VBA so that it is a user friendly formula, I will not be the only one using it.

Side note an implementation of my theoretical multiplex formula would allow for multiple references to be made. Syntax would be like MULTIPLEX([formula],[ref1],[cell1],[ref2],[cell2],...)

Side Side note the Formula is meant to extract the number from an item identifier for sorting purposes. ABC1234-1 becomes 1234.1 so we can sort by number ascending.

答:
Assuming the numeric part is at most 9 characters (including the "-") then you can use this formula to extract, which only references G4 once

=LOOKUP(10^10,SUBSTITUTE(RIGHT(G4,{1,2,3,4,5,6,7,8,9}),"-",".")+0)

Body:
Is there a way to condense Excel Formula references into one reference while keeping the formula contained to one cell?

For reference the formula I am using is

=VALUE(SUBSTITUTE(RIGHT(G4,LEN(G4)-
 MIN(FIND({0,1,2,3,4,5,6,7,8,9},G4&"0123456789"))+1),"-","."))

Which References G4 multiple times, I would like someway to make it so I or another user only has to change G4 in one place should the change be required.

Perhaps something like this (Not real excel formula:)

=MULTIPLEX(VALUE(SUBSTITUTE(RIGHT(#1,LEN(#1)-
 MIN(FIND({0,1,2,3,4,5,6,7,8,9},#1&"0123456789"))+1),"-",".")),#1,G4)

So that the #1 does not need to be changed and the G4 being changed once updates the whole formula.

I was trying to avoid VBA so that it is a user friendly formula, I will not be the only one using it.

Side note an implementation of my theoretical multiplex formula would allow for multiple references to be made. Syntax would be like MULTIPLEX([formula],[ref1],[cell1],[ref2],[cell2],...)

Side Side note the Formula is meant to extract the number from an item identifier for sorting purposes. ABC1234-1 becomes 1234.1 so we can sort by number ascending.