问:
Bootstrap accordion with arrow glyphs Changing bg color and arrow color after click
I have my accordion and I would like to:

after click in the arrow:

change the bg color of the panel from grey to red.
change the color of the arrow from grey to blue.

if not clicked  the panel the colour should back to the normal one: grey.

jsfiddle: https://jsfiddle.net/4x7y14wj/1/

css:

```<code>.panel-heading .accordion-toggle:after {
    /* symbol for "opening" panels */
    font-family: 'Glyphicons Halflings';  /* essential for enabling glyphicon */
    content: "\e114";    /* adjust as needed, taken from bootstrap.css */
    float: right;        /* adjust as needed */
    color: grey;         /* adjust as needed */
}
.panel-heading .accordion-toggle.collapsed:after {
    /* symbol for "collapsed" panels */
    content: "\e080";    /* adjust as needed, taken from bootstrap.css */
}
</code>```

html:

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

  <div class="panel-group" id="accordion">
    <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="panel-title">
        <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
          Collapsible Group Item #1
        </a>
      </h4>
      </div>
      <div id="collapseOne" class="panel-collapse collapse in">
        <div class="panel-body">
          Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
          on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
          raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
        </div>
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="panel-title">
        <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">
          Collapsible Group Item #2
        </a>
      </h4>
      </div>
      <div id="collapseTwo" class="panel-collapse collapse">
        <div class="panel-body">
          Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
          on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
          raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
        </div>
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="panel-title">
        <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapseThree">
          Collapsible Group Item #3
        </a>
      </h4>
      </div>
      <div id="collapseThree" class="panel-collapse collapse">
        <div class="panel-body">
          Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
          on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
          raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
        </div>
      </div>
    </div>
  </div>

</div>
<!-- end container -->

<!-- Latest compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
</code>```

答:
Think this is what you're looking for: https://jsfiddle.net/dennispreston/4x7y14wj/4/

EDIT

While this works, Chandra Shekhar's answer is a million times better!

HTML

```<code><div class="container">
  <div class="panel-group" id="accordion">
    <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="panel-title">
        <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
          Collapsible Group Item #1
        </a>
      </h4>
      </div>
      <div id="collapseOne" class="panel-collapse collapse in">
        <div class="panel-body">
          Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
          on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
          raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
        </div>
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="panel-title">
        <a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">
          Collapsible Group Item #2
        </a>
      </h4>
      </div>
      <div id="collapseTwo" class="panel-collapse collapse">
        <div class="panel-body">
          Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
          on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
          raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
        </div>
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="panel-title">
        <a id="toggle" class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseThree">
          Collapsible Group Item #3
        </a>
      </h4>
      </div>
      <div id="collapseThree" class="panel-collapse collapse">
        <div class="panel-body">
          Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
          on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
          raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
        </div>
      </div>
    </div>
  </div>

</div>
<!-- end container -->

<!-- Latest compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
</code>```

CSS

```<code> .panel-heading .accordion-toggle:after {
  /* symbol for "opening" panels */
  font-family: 'Glyphicons Halflings';
  /* essential for enabling glyphicon */
  content: "\e114";
  /* adjust as needed, taken from bootstrap.css */
  float: right;
  /* adjust as needed */
  color: blue;
  /* adjust as needed */
}

.panel-heading .accordion-toggle.collapsed:after {
  /* symbol for "collapsed" panels */
  content: "\e080";
  /* adjust as needed, taken from bootstrap.css */
  color: grey;
}

.panel-heading {
  background: red!important;
}

.panel-heading.grey {
  background: #f5f5f5!important;
}
</code>```

jQuery

If the panel heading has a child element with the .collapsed class, add .grey class to the panel heading. If not, remove it. Called on load and on click of toggle with delay so the .collapsed class is added before the script is run. This is a bit messy, I made it in a rush so any useful comments will be listened to and I will edit it with a tidier script.

```<code>$('.panel-heading:has(.collapsed)').addClass('grey');
$('.panel-heading:not(:has(.collapsed))').removeClass('grey');

$(".accordion-toggle").click(function() {
  setTimeout(
    function() {
      $('.panel-heading:has(.collapsed)').addClass('grey');
      $('.panel-heading:not(:has(.collapsed))').removeClass('grey');
    },
    10);
});
</code>```

Body:
I have my accordion and I would like to:

after click in the arrow:

change the bg color of the panel from grey to red.
change the color of the arrow from grey to blue.

if not clicked  the panel the colour should back to the normal one: grey.

jsfiddle: https://jsfiddle.net/4x7y14wj/1/

css:

.panel-heading .accordion-toggle:after {
    /* symbol for "opening" panels */
    font-family: 'Glyphicons Halflings';  /* essential for enabling glyphicon */
    content: "\e114";    /* adjust as needed, taken from bootstrap.css */
    float: right;        /* adjust as needed */
    color: grey;         /* adjust as needed */
}
.panel-heading .accordion-toggle.collapsed:after {
    /* symbol for "collapsed" panels */
    content: "\e080";    /* adjust as needed, taken from bootstrap.css */
}

html:

          Collapsible Group Item #1

          Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
          on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
          raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

          Collapsible Group Item #2

          Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
          on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
          raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

          Collapsible Group Item #3

          Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
          on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
          raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

Body:
Think this is what you're looking for: https://jsfiddle.net/dennispreston/4x7y14wj/4/

EDIT

While this works, Chandra Shekhar's answer is a million times better!

HTML

<div class="container">
  <div class="panel-group" id="accordion">
    <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="panel-title">
        <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
          Collapsible Group Item #1
        </a>
      </h4>
      </div>
      <div id="collapseOne" class="panel-collapse collapse in">
        <div class="panel-body">
          Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
          on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
          raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
        </div>
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="panel-title">
        <a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">
          Collapsible Group Item #2
        </a>
      </h4>
      </div>
      <div id="collapseTwo" class="panel-collapse collapse">
        <div class="panel-body">
          Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
          on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
          raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
        </div>
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="panel-title">
        <a id="toggle" class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseThree">
          Collapsible Group Item #3
        </a>
      </h4>
      </div>
      <div id="collapseThree" class="panel-collapse collapse">
        <div class="panel-body">
          Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
          on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
          raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
        </div>
      </div>
    </div>
  </div>

</div>
<!-- end container -->

<!-- Latest compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

CSS

 .panel-heading .accordion-toggle:after {
  /* symbol for "opening" panels */
  font-family: 'Glyphicons Halflings';
  /* essential for enabling glyphicon */
  content: "\e114";
  /* adjust as needed, taken from bootstrap.css */
  float: right;
  /* adjust as needed */
  color: blue;
  /* adjust as needed */
}

.panel-heading .accordion-toggle.collapsed:after {
  /* symbol for "collapsed" panels */
  content: "\e080";
  /* adjust as needed, taken from bootstrap.css */
  color: grey;
}

.panel-heading {
  background: red!important;
}

.panel-heading.grey {
  background: #f5f5f5!important;
}

jQuery

If the panel heading has a child element with the .collapsed class, add .grey class to the panel heading. If not, remove it. Called on load and on click of toggle with delay so the .collapsed class is added before the script is run. This is a bit messy, I made it in a rush so any useful comments will be listened to and I will edit it with a tidier script.

$('.panel-heading:has(.collapsed)').addClass('grey');
$('.panel-heading:not(:has(.collapsed))').removeClass('grey');

$(".accordion-toggle").click(function() {
  setTimeout(
    function() {
      $('.panel-heading:has(.collapsed)').addClass('grey');
      $('.panel-heading:not(:has(.collapsed))').removeClass('grey');
    },
    10);
});


来源: stackexchange

问:
WPF: User Control access Style via Dependency Property
I have created a Style for a Button with an Image:

```<code>    <Style x:Key="StyleButtonBase" TargetType="Button">
    <Style.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="../Sizes/Sizes.xaml" />
                <ResourceDictionary Source="../Colors/Brushes.xaml" />
                <ResourceDictionary Source="../Fonts/Fonts.xaml" />
                <ResourceDictionary Source="../Images/Images.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Style.Resources>
    <Setter Property="Background" Value="{StaticResource BrushButtonActive}" />
    <Setter Property="Foreground" Value="{StaticResource BrushForegroundLight}" />
    <Setter Property="FontFamily" Value="{StaticResource FontFamilyDefault}" />
    <Setter Property="FontSize" Value="{StaticResource DoubleFontSizeStandard}" />
    <Setter Property="Cursor" Value="Hand" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border
                    Background="{TemplateBinding Background}"
                    BorderBrush="{StaticResource BrushBorder}"
                    BorderThickness="{StaticResource ThicknessBorder}"
                    CornerRadius="{StaticResource CornerRadius}">
                    <Image Source="{StaticResource IconIcon}" Stretch="None" />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsPressed" Value="True">
            <Setter Property="Background" Value="{StaticResource BrushButtonPressed}" />
        </Trigger>
    </Style.Triggers>
</Style>
</code>```

Now I Want to create a User-Control which only consists of a Button with this style and a Dependency Property to set the Button Image. The XAML part of my user control looks like this:

```<code><UserControl
x:Class="HH.HMI.ToolSuite.ResourceLib.Controls.ButtonSmall">

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="../Styles/Buttons.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>

<Button Style="{StaticResource StyleButtonBase}" Width="{StaticResource DoubleWidthButtonSmall}" Height="{StaticResource DoubleHeightControls}">
</Button></UserControl>
</code>```

The code behind of my user-control looks like this:

```<code>public partial class ButtonSmall : UserControl, INotifyPropertyChanged
{
    public ButtonSmall()
    {
        InitializeComponent();
    }

    public static readonly DependencyProperty ButtonImageProperty
        = DependencyProperty.Register("ButtonImage", typeof(ImageSource), typeof(TextOutput), new PropertyMetadata(null, OnButtonImagePropertyChanged));

    private static void OnButtonImagePropertyChanged(DependencyObject dependencyObject,
           DependencyPropertyChangedEventArgs e)
    {
        ButtonSmall temp = dependencyObject as ButtonSmall;
        temp.OnPropertyChanged("ButtonImage");
        temp.OnButtonImagePropertyChanged(e);
    }

    private void OnButtonImagePropertyChanged(DependencyPropertyChangedEventArgs e)
    {
        ButtonSmallImage.Source = ButtonImageSource;
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public ImageSource ButtonImageSource
    {
        get { return (ImageSource)GetValue(ButtonImageProperty); }
        set { SetValue(ButtonImageProperty, value); }
    }
}
</code>```

In my other user-controls i usually access an element in the user control itself like:

```<code>xamlname.text = text
</code>```

Now i haven't a named element in my xaml code of the user-control. Instead i have the named element in the style, which i reference in the user control. How can access this throug my code behind?

答:
If the Style is defined in Application.Resources in App.xaml, or in a resource dictionary that's merged into Application.Resources in App.xaml, you can just reference it in the user control via StaticResource. If it's in another resource dictionary, you'll have to merge that one into UserControl.Resources.

Or you can put it directly in UserControl.Resources as TernaryTopiary suggests, if it won't be needed elsewhere.

As for the image source property, you could write a Button subclass as Ternary suggests, or you could write an attached property (see below). In XAML, when you customize controls, first you try to do it with regular attributes; then you try to restyle the thing. Then you escalate to replacing the control template, and that won't quite do the job, you consider attached properties/behaviors. Only if all else fails to do you resort to subclassing. You should know how to do it, but you should also learn the other ways of doing things.

In this case, there's a somewhat quick and dirty way to do it that's consistent with the correct XAML way of doing things: The Content property of the button is going unused, and its declared type is Object, so we can just use that. Since we're using a binding to pass in the image source, you can get rid of that PropertyChanged handler on ButtonImageSource.

```<code><UserControl
    ...>
    <!-- ... -->

    <Button
        Content="{Binding ButtonImageSource, RelativeSource={RelativeSource AncestorType=UserControl}}"
        Style="{StaticResource StyleButtonBase}"
        Width="{StaticResource DoubleWidthButtonSmall}"
        Height="{StaticResource DoubleHeightControls}"
        />
</code>```

And make the following change in the control template in StyleButtonBase:

```<code>        <ControlTemplate TargetType="Button">
            <Border
                Background="{TemplateBinding Background}"
                BorderBrush="{StaticResource BrushBorder}"
                BorderThickness="{StaticResource ThicknessBorder}"
                CornerRadius="{StaticResource CornerRadius}"
                >
                <!-- Now we'll find the image source in the button's Content --->
                <Image
                    Source="{TemplateBinding Content}"
                    Stretch="None"
                    />
            </Border>
        </ControlTemplate>
</code>```

Attached Property

Using Content for this is a very mild abuse of WPF: You shouldn't really be repurposing properties. Content is universally understood in WPF to mean "any arbitrary content", not "any ImageSource".

So it's a little more "correct" to use an attached property, and it's not a lot more work. Here's how that would look.

We'll define the attached property in a separate static class, because I can't think of a good name for it other than ButtonImageSource, which you're already using in SmallButton:

```<code>public static class ButtonHelper
{
    #region ButtonHelper.ButtonImageSource Attached Property
    public static ImageSource GetButtonImageSource(Button obj)
    {
        return (ImageSource)obj.GetValue(ButtonImageSourceProperty);
    }

    public static void SetButtonImageSource(Button obj, ImageSource value)
    {
        obj.SetValue(ButtonImageSourceProperty, value);
    }

    public static readonly DependencyProperty ButtonImageSourceProperty =
        DependencyProperty.RegisterAttached("ButtonImageSource", typeof(ImageSource), typeof(ButtonHelper),
            new PropertyMetadata(null));
    #endregion ButtonHelper.ButtonImageSource Attached Property
}
</code>```

In the XAML, the user control uses this attached property instead of Content:

```<code><Button
    Style="{StaticResource StyleButtonBase}"
    local:ButtonHelper.ButtonImageSource="{Binding ButtonImageSource, RelativeSource={RelativeSource AncestorType=UserControl}}"
    />
</code>```

And the control template does likewise:

```<code><ControlTemplate TargetType="Button">
    <Border
        Background="{TemplateBinding Background}"
        BorderBrush="{TemplateBinding BorderBrush}"
        BorderThickness="{TemplateBinding BorderThickness}"
        CornerRadius="4"
        >
        <Image
            Source="{TemplateBinding local:ButtonHelper.ButtonImageSource}"
            Stretch="None"
            />
    </Border>
</ControlTemplate>
</code>```

All the attached property does is give us a property that isn't named Content, and which is strongly typed as ImageSource, which we can use to pass in that image source.

Another thing: Maybe this was an error that crept in when you simplified your code for the question, but you're passing typeof(TextOutput) to DependencyProperty.Register() where you should be passing typeof(ButtonSmall). More importantly, you've got two names for what should be a single property: ButtonImage and ButtonImageSource.

```<code>public static readonly DependencyProperty ButtonImageSourceProperty
    = DependencyProperty.Register(
        "ButtonImageSource",
        typeof(ImageSource),
        //  Should be ButtonSmall, not TextOutput
        typeof(ButtonSmall),
        new PropertyMetadata(null));

public ImageSource ButtonImageSource
{
    get { return (ImageSource)GetValue(ButtonImageSourceProperty); }
    set { SetValue(ButtonImageSourceProperty, value); }
}
</code>```

Incidentally, in your Style, it would be better practice to use TemplateBinding for BorderBrush and BorderThickness, and set the defaults in Style setters, the way you did with Background.

ContentLicense: CC BY-SA 3.0

Body:
I have created a Style for a Button with an Image:

    <Setter Property="Background" Value="{StaticResource BrushButtonActive}" />
    <Setter Property="Foreground" Value="{StaticResource BrushForegroundLight}" />
    <Setter Property="FontFamily" Value="{StaticResource FontFamilyDefault}" />
    <Setter Property="FontSize" Value="{StaticResource DoubleFontSizeStandard}" />
    <Setter Property="Cursor" Value="Hand" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border
                    Background="{TemplateBinding Background}"
                    BorderBrush="{StaticResource BrushBorder}"
                    BorderThickness="{StaticResource ThicknessBorder}"
                    CornerRadius="{StaticResource CornerRadius}">
                    <Image Source="{StaticResource IconIcon}" Stretch="None" />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>

</Style>

Now I Want to create a User-Control which only consists of a Button with this style and a Dependency Property to set the Button Image. The XAML part of my user control looks like this:

<UserControl
x:Class="HH.HMI.ToolSuite.ResourceLib.Controls.ButtonSmall">

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="../Styles/Buttons.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>

<Button Style="{StaticResource StyleButtonBase}" Width="{StaticResource DoubleWidthButtonSmall}" Height="{StaticResource DoubleHeightControls}">
</Button></UserControl>

The code behind of my user-control looks like this:

public partial class ButtonSmall : UserControl, INotifyPropertyChanged
{
    public ButtonSmall()
    {
        InitializeComponent();
    }

    public static readonly DependencyProperty ButtonImageProperty
        = DependencyProperty.Register("ButtonImage", typeof(ImageSource), typeof(TextOutput), new PropertyMetadata(null, OnButtonImagePropertyChanged));

    private static void OnButtonImagePropertyChanged(DependencyObject dependencyObject,
           DependencyPropertyChangedEventArgs e)
    {
        ButtonSmall temp = dependencyObject as ButtonSmall;
        temp.OnPropertyChanged("ButtonImage");
        temp.OnButtonImagePropertyChanged(e);
    }

    private void OnButtonImagePropertyChanged(DependencyPropertyChangedEventArgs e)
    {
        ButtonSmallImage.Source = ButtonImageSource;
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public ImageSource ButtonImageSource
    {
        get { return (ImageSource)GetValue(ButtonImageProperty); }
        set { SetValue(ButtonImageProperty, value); }
    }
}

In my other user-controls i usually access an element in the user control itself like:

xamlname.text = text

Now i haven't a named element in my xaml code of the user-control. Instead i have the named element in the style, which i reference in the user control. How can access this throug my code behind?

Body:
If the Style is defined in Application.Resources in App.xaml, or in a resource dictionary that's merged into Application.Resources in App.xaml, you can just reference it in the user control via StaticResource. If it's in another resource dictionary, you'll have to merge that one into UserControl.Resources.

Or you can put it directly in UserControl.Resources as TernaryTopiary suggests, if it won't be needed elsewhere.

As for the image source property, you could write a Button subclass as Ternary suggests, or you could write an attached property (see below). In XAML, when you customize controls, first you try to do it with regular attributes; then you try to restyle the thing. Then you escalate to replacing the control template, and that won't quite do the job, you consider attached properties/behaviors. Only if all else fails to do you resort to subclassing. You should know how to do it, but you should also learn the other ways of doing things.

In this case, there's a somewhat quick and dirty way to do it that's consistent with the correct XAML way of doing things: The Content property of the button is going unused, and its declared type is Object, so we can just use that. Since we're using a binding to pass in the image source, you can get rid of that PropertyChanged handler on ButtonImageSource.

<UserControl
    ...>
    <!-- ... -->

    <Button
        Content="{Binding ButtonImageSource, RelativeSource={RelativeSource AncestorType=UserControl}}"
        Style="{StaticResource StyleButtonBase}"
        Width="{StaticResource DoubleWidthButtonSmall}"
        Height="{StaticResource DoubleHeightControls}"
        />

And make the following change in the control template in StyleButtonBase:

        <ControlTemplate TargetType="Button">
            <Border
                Background="{TemplateBinding Background}"
                BorderBrush="{StaticResource BrushBorder}"
                BorderThickness="{StaticResource ThicknessBorder}"
                CornerRadius="{StaticResource CornerRadius}"
                >
                <!-- Now we'll find the image source in the button's Content --->
                <Image
                    Source="{TemplateBinding Content}"
                    Stretch="None"
                    />
            </Border>
        </ControlTemplate>

Attached Property

Using Content for this is a very mild abuse of WPF: You shouldn't really be repurposing properties. Content is universally understood in WPF to mean "any arbitrary content", not "any ImageSource".

So it's a little more "correct" to use an attached property, and it's not a lot more work. Here's how that would look.

We'll define the attached property in a separate static class, because I can't think of a good name for it other than ButtonImageSource, which you're already using in SmallButton:

public static class ButtonHelper
{
    #region ButtonHelper.ButtonImageSource Attached Property
    public static ImageSource GetButtonImageSource(Button obj)
    {
        return (ImageSource)obj.GetValue(ButtonImageSourceProperty);
    }

    public static void SetButtonImageSource(Button obj, ImageSource value)
    {
        obj.SetValue(ButtonImageSourceProperty, value);
    }

    public static readonly DependencyProperty ButtonImageSourceProperty =
        DependencyProperty.RegisterAttached("ButtonImageSource", typeof(ImageSource), typeof(ButtonHelper),
            new PropertyMetadata(null));
    #endregion ButtonHelper.ButtonImageSource Attached Property
}

In the XAML, the user control uses this attached property instead of Content:

<Button
    Style="{StaticResource StyleButtonBase}"
    local:ButtonHelper.ButtonImageSource="{Binding ButtonImageSource, RelativeSource={RelativeSource AncestorType=UserControl}}"
    />

And the control template does likewise:

<ControlTemplate TargetType="Button">
    <Border
        Background="{TemplateBinding Background}"
        BorderBrush="{TemplateBinding BorderBrush}"
        BorderThickness="{TemplateBinding BorderThickness}"
        CornerRadius="4"
        >
        <Image
            Source="{TemplateBinding local:ButtonHelper.ButtonImageSource}"
            Stretch="None"
            />
    </Border>
</ControlTemplate>

All the attached property does is give us a property that isn't named Content, and which is strongly typed as ImageSource, which we can use to pass in that image source.

Another thing: Maybe this was an error that crept in when you simplified your code for the question, but you're passing typeof(TextOutput) to DependencyProperty.Register() where you should be passing typeof(ButtonSmall). More importantly, you've got two names for what should be a single property: ButtonImage and ButtonImageSource.

public static readonly DependencyProperty ButtonImageSourceProperty
    = DependencyProperty.Register(
        "ButtonImageSource",
        typeof(ImageSource),
        //  Should be ButtonSmall, not TextOutput
        typeof(ButtonSmall),
        new PropertyMetadata(null));

public ImageSource ButtonImageSource
{
    get { return (ImageSource)GetValue(ButtonImageSourceProperty); }
    set { SetValue(ButtonImageSourceProperty, value); }
}

Incidentally, in your Style, it would be better practice to use TemplateBinding for BorderBrush and BorderThickness, and set the defaults in Style setters, the way you did with Background.


问:
Unit test angular form to ensure form cannot be submitted unless required fields are provided
Using the test below, I'm seeing that my code coverage sees this:

```<code>public onSubmit() { this.submitted = true; }
</code>```

as being executed, even though I have not input data into the title textfield .. why is that?

How can I test this kind of logic?

dummy.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'my-selector',
  templateUrl: './dummy.component.html'
})
export class DummyComponent {

  public submitted = false;
  public onSubmit() { this.submitted = true; }
}
</code>```

dummy.component.html

```<code><div class="container">
  <div [hidden]="submitted">
    <h1>New Page Form</h1>
    <form (ngSubmit)="onSubmit()" #pageForm="ngForm">
      <div>
        <label for="title">Title</label>
        <input type="text" id="title" required [(ngModel)]="model.title" name="title" #title="ngModel">
        <div [hidden]="title.valid || title.pristine">
          Title is required
        </div>
      </div>

      <button id="submitNewPage" type="submit" [disabled]="!pageForm.form.valid">Finish</button>
    </form>
  </div>

  <div [hidden]="!submitted">
    <h2>New page details:</h2>
    <div>
      <div>Title: {{ model.title }}</div>
    </div>
    <br>
    <button (click)="submitted=false">Edit</button>
  </div>
</div>
</code>```

dummy.component.spec.ts

```<code>it('should create an instance of PageFormComponent', () => {
  fixture.debugElement.nativeElement.querySelector('#submitNewPage').click();
});
</code>```

答:
Are you sure that is even firing the event in the proper way with that click()? Because as far as i know should be something</p>

```<code>  describe('your block', () => {
     let submitB;
    beforeEach(() => {
       submitB = fixture.debugElement.nativeElement.query(By.css('#submitNewPage'));
       submitB.dispatchEvent(new Event('click'))
     });

    it('your expectation' () => {})
   })
</code>```

Body:
Using the test below, I'm seeing that my code coverage sees this:

public onSubmit() { this.submitted = true; }

as being executed, even though I have not input data into the title textfield .. why is that?

How can I test this kind of logic?

dummy.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-selector',
  templateUrl: './dummy.component.html'
})
export class DummyComponent {

  public submitted = false;
  public onSubmit() { this.submitted = true; }
}

dummy.component.html

New Page Form

    <form (ngSubmit)="onSubmit()" #pageForm="ngForm">

        Title
        <input type="text" id="title" required [(ngModel)]="model.title" name="title" #title="ngModel">

          Title is required

      <button id="submitNewPage" type="submit" [disabled]="!pageForm.form.valid">Finish</button>
    </form>

New page details:

Title: {{ model.title }}

    <button (click)="submitted=false">Edit</button>

dummy.component.spec.ts

it('should create an instance of PageFormComponent', () => {
  fixture.debugElement.nativeElement.querySelector('#submitNewPage').click();
});

Body:
Are you sure that is even firing the event in the proper way with that click()? Because as far as i know should be something

  describe('your block', () => {
     let submitB;
    beforeEach(() => {
       submitB = fixture.debugElement.nativeElement.query(By.css('#submitNewPage'));
       submitB.dispatchEvent(new Event('click'))
     });

    it('your expectation' () => {})
   })


问:
Determining if a user input field is empty
I've looked at some of the answers here but for some reason, I can't get this to work. I want the user to grade something and if they input nothing in the required field and press "Grade", I want for it to alert something.

function Script() {
  var G = document.getElementById("gradevalue").value
  if (G == null || G == undefined) {
    window.alert("Please input a grade");
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label id="grade">|Please grade on a scale from 1 to 10 (10 is the best!)
    <input id="gradevalue" type="text"; size="2"; maxlength="2">
    </label>
<input type="button" value="GRADE!" id="nota" onclick="Script()"></code>```

I'm very new at this, so please don't be too harsh.

答:
Checking !G || G == 0 seems to do the job:

function Script() {
    var G = document.getElementById("gradevalue").value
    if(!G || G == 0) {
        window.alert("Please input a grade");
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label id="grade">|Please grade on a scale from 1 to 10 (10 is the best!)
    <input id="gradevalue" type="text"; size="2"; maxlength="2">
</label>
<input type="button" value="GRADE!" id="nota" onclick="Script()"></code>```

Note that you may also want to check for > 11 values:

```<code>if (!G) {
    window.alert("Please input a grade");
} else if(G == 0 || G > 10) {
    window.alert("Please input a grade between 1 and 10");
}
</code>```

Body:
I've looked at some of the answers here but for some reason, I can't get this to work. I want the user to grade something and if they input nothing in the required field and press "Grade", I want for it to alert something.

function Script() {
  var G = document.getElementById("gradevalue").value
  if (G == null || G == undefined) {
    window.alert("Please input a grade");
  }
}

|Please grade on a scale from 1 to 10 (10 is the best!)
    <input id="gradevalue" type="text"; size="2"; maxlength="2">

<input type="button" value="GRADE!" id="nota" onclick="Script()">

I'm very new at this, so please don't be too harsh.

Body:
Checking !G || G == 0 seems to do the job:

function Script() {
    var G = document.getElementById("gradevalue").value
    if(!G || G == 0) {
        window.alert("Please input a grade");
    }
}

<label id="grade">|Please grade on a scale from 1 to 10 (10 is the best!)
    <input id="gradevalue" type="text"; size="2"; maxlength="2">
</label>
<input type="button" value="GRADE!" id="nota" onclick="Script()">

Note that you may also want to check for > 11 values:

if (!G) {
    window.alert("Please input a grade");
} else if(G == 0 || G > 10) {
    window.alert("Please input a grade between 1 and 10");
}


问:
Rails Authentication and Authorization without guarantee of browser sessions?
Right now, I am using the RESTful Authentication framework for authorizations with my rails application.  This is all well and good (though from my understanding, a little dated?), but now I need to authenticate a user who might not have an http session (such as from a application (not a browser) that is hitting my rails routes).

Specifically, I now have to support an iPhone application, that hits some of my restful routes to populate itself. However, this app needs to be authenticated, and just passing in a user name and password as parameters doesn't seem very secure. Not only is it not secure, it's not very clean (I would have to change all my calls referencing the current_user (stored in session) to manually setting the current user, as hits to my app without a browser doesn't seem to have session vars (or am I wrong about this?))

Any advice? Can RESTful Authentication do this? Is their an alternative framework (such as Authlogic, or OAuth or whatever) that can help me?

答:
Devise appears able to do token-based authentication.

For security, only permit SSL connections. Redirect any non-SSL HTTP requests to the SSL version of the site. You can use the Rack middleware rack-ssl for this.

ContentLicense: CC BY-SA 2.5


问:
How to find if button is in active state in ionic app
In my ionic app, I have a screen which has 2 buttons. On pressing each of those buttons, I call a function which does some intensive network task. Everything is working well.

Normally when I press one of those button, it calls the function. But if I press that button again, it again calls that function and does same work. I dont want it do call function again if I had pressed before. Only if I press another button and then press this button again, it should call the function.

So, can I get to know the active state of my button before calling the function?

I am new to Ionic, so would appreciate any help on this.

Button code :

```<code><div class="button-bar button-bar-full bar-light"
             ng-if="activityLog.enabledChecked && !activityLog.disabledToggle">
            <a class="button" ng-class="{'button-active': activityLog.isUnblockedFiltered}"
               ng-click="switchFilter(true)">{{ 'main.activity-log-blocked-report' | i18n }}</a>
            <a class="button" ng-class="{'button-active': !activityLog.isUnblockedFiltered}"
               ng-click="switchFilter(false)">{{ 'main.activity-log-full-report' | i18n }}</a>
        </div>
</code>```

PS: I can apply some flags and can make this work but want to know if I can get to know the state of button by some api.

Thanks

答:
You can check whether the button is disabled or not by using the following method</p>

```<code>var target = angular.element(document.getElementById("#buttonId"));
if (target.prop('disabled')) {
    // Button is disabled
    //Do something
}
</code>```

Body:
In my ionic app, I have a screen which has 2 buttons. On pressing each of those buttons, I call a function which does some intensive network task. Everything is working well.

Normally when I press one of those button, it calls the function. But if I press that button again, it again calls that function and does same work. I dont want it do call function again if I had pressed before. Only if I press another button and then press this button again, it should call the function.

So, can I get to know the active state of my button before calling the function?

I am new to Ionic, so would appreciate any help on this.

Button code :

            {{ 'main.activity-log-blocked-report' | i18n }}
            {{ 'main.activity-log-full-report' | i18n }}

PS: I can apply some flags and can make this work but want to know if I can get to know the state of button by some api.

Thanks

Body:
You can check whether the button is disabled or not by using the following method

var target = angular.element(document.getElementById("#buttonId"));
if (target.prop('disabled')) {
    // Button is disabled
    //Do something
}


问:
Exception: java.lang.Exception: When running with master 'yarn' either HADOOP_CONF_DIR or YARN_CONF_DIR must be set in the environment. in spark
I am new apache-spark. I have tested some application in spark standalone mode.but I want to run application yarn mode.I am running apache-spark 2.1.0 in windows.Here is My code

```<code>c:\spark>spark-submit2 --master yarn --deploy-mode client --executor-cores 4 --jars C:\DependencyJars\spark-streaming-eventhubs_2.11-2.0.3.jar,C:\DependencyJars\scalaj-http_2.11-2.3.0.jar,C:\DependencyJars\config-1.3.1.jar,C:\DependencyJars\commons-lang3-3.3.2.jar --conf spark.driver.userClasspathFirst=true --conf spark.executor.extraClassPath=C:\DependencyJars\commons-lang3-3.3.2.jar --conf spark.executor.userClasspathFirst=true --class "GeoLogConsumerRT" C:\sbtazure\target\scala-2.11\azuregeologproject_2.11-1.0.jar
</code>```

EXCEPTION: When running with master 'yarn' either HADOOP_CONF_DIR or YARN_CONF_DIR must be set in the environment. in spark

so from searching website. I have created a folder name Hadoop_CONF_DIR and place hive site.xml in it and pointed as environment variable, after that i have run spark-submit then I have got

connection refused exception
I think i could not configure yarn mode set up properly.Could anyone help me for solving this issue? do I need to install Hadoop and yarn separately?I want to run my application in pseudo distributed mode.Kindly help me to configure yarn mode in windows thanks

答:
You need to export two variables HADOOP_CONF_DIR and YARN_CONF_DIR to make your configurations file visible to yarn. Use below code  in .bashrc file if you are using linux.

```<code>export HADOOP_CONF_DIR=$HADOOP_HOME/etc/hadoop
export YARN_CONF_DIR=$HADOOP_HOME/etc/hadoop
</code>```

In windows you need to set environment variable.

Hope this helps!

Body:
I am new apache-spark. I have tested some application in spark standalone mode.but I want to run application yarn mode.I am running apache-spark 2.1.0 in windows.Here is My code

c:\spark>spark-submit2 --master yarn --deploy-mode client --executor-cores 4 --jars C:\DependencyJars\spark-streaming-eventhubs_2.11-2.0.3.jar,C:\DependencyJars\scalaj-http_2.11-2.3.0.jar,C:\DependencyJars\config-1.3.1.jar,C:\DependencyJars\commons-lang3-3.3.2.jar --conf spark.driver.userClasspathFirst=true --conf spark.executor.extraClassPath=C:\DependencyJars\commons-lang3-3.3.2.jar --conf spark.executor.userClasspathFirst=true --class "GeoLogConsumerRT" C:\sbtazure\target\scala-2.11\azuregeologproject_2.11-1.0.jar

EXCEPTION: When running with master 'yarn' either HADOOP_CONF_DIR or YARN_CONF_DIR must be set in the environment. in spark

so from searching website. I have created a folder name Hadoop_CONF_DIR and place hive site.xml in it and pointed as environment variable, after that i have run spark-submit then I have got

connection refused exception
I think i could not configure yarn mode set up properly.Could anyone help me for solving this issue? do I need to install Hadoop and yarn separately?I want to run my application in pseudo distributed mode.Kindly help me to configure yarn mode in windows thanks

Body:
You need to export two variables HADOOP_CONF_DIR and YARN_CONF_DIR to make your configurations file visible to yarn. Use below code  in .bashrc file if you are using linux.

export HADOOP_CONF_DIR=$HADOOP_HOME/etc/hadoop
export YARN_CONF_DIR=$HADOOP_HOME/etc/hadoop

In windows you need to set environment variable.

Hope this helps!


问:
System.ObjectModel Warning Xamarin does not run on Android
We are running the 'Welcome to Xamarin` example on Visual Studio Enterprise, using the latest Xamarin, in a Windows 8.1 environment.

We are managing to build and run on both Windows and Apple, but we are facing problems with Android.

Error:
The referenced component System.ObjectModel could not be found.

The errors can be seen in the screen shot below:

See screenshot

We've already tried searching online for solutions, we found some, which we tried, but to no avail.

On the other hand, is Xamarin compatible with Windows 8.1? Perhaps some Android requirement actually needs a Windows 10 environment.

Any help would be appreciated.

答:
In the Package manager console type: (Select the Android project)

```<code>update-package -reinstall
</code>```

Is slower but is the correct method and always works

Body:
In the Package manager console type: (Select the Android project)

update-package -reinstall

Is slower but is the correct method and always works


问:
Adjust vertical grid in ggplot (R) to match desired values
Second post in StackOverflow so my apologies for not been clear enoguh.

I need to modify the vertical  grid in ggplot to match  the beginning and the end of certain repetitive period (each dar or each 24h). I have been looking but I cannot find anything similar. I attach a code to run the problem:

```<code>mydate <- seq(ISOdate(2016,1,1), ISOdate(2016,2,1), by = "hour") # or "3 months"
mysample <- runif(n = length(mydate), min = 1, max = 10)
mydf <- data.frame(mydate,mysample)
mygraph <- ggplot(data = mydf, aes (x = mydate)) +
              geom_line(aes(y = mysample, colour = "red")) +
              ggtitle("MyTry") +
              labs(x="Day of the Month", y= "MyValue") +
              theme(panel.grid.minor = element_line(colour = "gray50", size = 0.1),
                    panel.grid.major = element_line(colour = "gray50", size = 0.5),
                    panel.grid.major.x = element_blank(),
                    panel.background = element_blank(),
                    axis.text.y = element_text(colour="gray", size = 10),
                    axis.text.x = element_text(vjust = 5, size = 9),
                    plot.title = element_text(hjust = 0.5, size = 20, vjust = 1))
mygraph
</code>```

Whichs gives:

Random values for each hour of a month

I would appreciate if anybody could help me out with any of these two questions:

1-. Is it posible to modify the vertical grid (in my plot there are just 5)  in such a way so it matches every beginning of a day (i.e the 00:00:00 time) or should I create data and plot it to "simulate" a grid (anyidea on this would be aprreciated also)

2-. Instead of "ene04" , "ene 11", "ene 18"... in te X axis, is there a way to put all de days (not the hours)? So it apperas "ene 01" "ene 02" etc?

I hope I have make it clear enough so someone can help me!

Thank you!!

答:
You can control ticks with scale_x_timedate alson with some adjustments in axis.text.x and axis.ticks.x, you can get the result pasted below.

```<code>library(ggplot2)
library(lubridate)
library(scales)
mydate <- seq(ISOdate(2016,1,1), ISOdate(2016,2,1), by = "hour") # or "3 months"
mysample <- runif(n = length(mydate), min = 1, max = 10)
mydf <- data.frame(mydate,mysample)
mygraph <- ggplot(data = mydf, aes (x = mydate)) +
  geom_line(aes(y = mysample, colour = "red")) +
  ggtitle("MyTry") +
  labs(x="Day of the Month", y= "MyValue") +
  scale_x_datetime(labels = date_format("%b-%d"), breaks=pretty_breaks(n = 32)(as_datetime(c("2016-01-01", "2016-02-01")))) +
  theme(panel.grid.minor = element_line(colour = "gray50", size = 0.1),
        panel.grid.major = element_line(colour = "gray50", size = 0.5),
        panel.grid.major.x = element_blank(),
        panel.background = element_blank(),
        axis.text.y = element_text(colour="gray", size = 10),
          axis.text.x = element_text(size = 9, angle = 270, vjust = -.5),
        axis.ticks.x=element_blank(),
        plot.title = element_text(hjust = 0.5, size = 20, vjust = 1),)
mygraph
</code>```

Body:
Second post in StackOverflow so my apologies for not been clear enoguh.

I need to modify the vertical  grid in ggplot to match  the beginning and the end of certain repetitive period (each dar or each 24h). I have been looking but I cannot find anything similar. I attach a code to run the problem:

mydate <- seq(ISOdate(2016,1,1), ISOdate(2016,2,1), by = "hour") # or "3 months"
mysample <- runif(n = length(mydate), min = 1, max = 10)
mydf <- data.frame(mydate,mysample)
mygraph <- ggplot(data = mydf, aes (x = mydate)) +
              geom_line(aes(y = mysample, colour = "red")) +
              ggtitle("MyTry") +
              labs(x="Day of the Month", y= "MyValue") +
              theme(panel.grid.minor = element_line(colour = "gray50", size = 0.1),
                    panel.grid.major = element_line(colour = "gray50", size = 0.5),
                    panel.grid.major.x = element_blank(),
                    panel.background = element_blank(),
                    axis.text.y = element_text(colour="gray", size = 10),
                    axis.text.x = element_text(vjust = 5, size = 9),
                    plot.title = element_text(hjust = 0.5, size = 20, vjust = 1))
mygraph

Whichs gives:

Random values for each hour of a month

I would appreciate if anybody could help me out with any of these two questions:

1-. Is it posible to modify the vertical grid (in my plot there are just 5)  in such a way so it matches every beginning of a day (i.e the 00:00:00 time) or should I create data and plot it to "simulate" a grid (anyidea on this would be aprreciated also)

2-. Instead of "ene04" , "ene 11", "ene 18"... in te X axis, is there a way to put all de days (not the hours)? So it apperas "ene 01" "ene 02" etc?

I hope I have make it clear enough so someone can help me!

Thank you!!

Body:
You can control ticks with scale_x_timedate alson with some adjustments in axis.text.x and axis.ticks.x, you can get the result pasted below.

library(ggplot2)
library(lubridate)
library(scales)
mydate <- seq(ISOdate(2016,1,1), ISOdate(2016,2,1), by = "hour") # or "3 months"
mysample <- runif(n = length(mydate), min = 1, max = 10)
mydf <- data.frame(mydate,mysample)
mygraph <- ggplot(data = mydf, aes (x = mydate)) +
  geom_line(aes(y = mysample, colour = "red")) +
  ggtitle("MyTry") +
  labs(x="Day of the Month", y= "MyValue") +
  scale_x_datetime(labels = date_format("%b-%d"), breaks=pretty_breaks(n = 32)(as_datetime(c("2016-01-01", "2016-02-01")))) +
  theme(panel.grid.minor = element_line(colour = "gray50", size = 0.1),
        panel.grid.major = element_line(colour = "gray50", size = 0.5),
        panel.grid.major.x = element_blank(),
        panel.background = element_blank(),
        axis.text.y = element_text(colour="gray", size = 10),
          axis.text.x = element_text(size = 9, angle = 270, vjust = -.5),
        axis.ticks.x=element_blank(),
        plot.title = element_text(hjust = 0.5, size = 20, vjust = 1),)
mygraph


问:
Can i call a server side script from a hyper link in system generated email?
I am developing an application that creates an event in an other employee's google calendar when the Manager approves a vacation request.
I am able to create events in the calendar I own, but not in the Calendar owned by a colleague. Is there a way to create a special account that can update all calendars in an organization?
If I am not able to make it part of the workflow, I would like to have a hyper link in the email i send to the colleague saying the vacation has been approved and click here to add it to your calendar. I am able to achieve this by creating a page for create event in calendar, is there a way by which i can call the serve side function directly from the hyper link?

Thanks,

答:
There is a documentation https://web.archive.org/web/20120313011336/http://www.google.com/googlecalendar/event_publisher_guide.html
It will help you create link, that will fill Google calendar create event screen.

So user will click link and will see Google calendar create event screen with filled data, he will need just click "save" button

By this link http://useroffline.blogspot.com/2009/06/making-google-calendar-link.html you will find short version of documentation and link sample.


问:
ng-disabled within angular directive
I have an angular directive:

```<code>angular.module("app").directive("myButtons", function () {
    return {
        restrict: "E",
        scope: {
            bdisabled: '='
        },
        templateUrl: "buttons.html"
    }
});
</code>```

template:

```<code><input type="submit" value="Update" ng-disabled="{{bdisabled}}" />
</code>```

html:

```<code><my-buttons bdisabled="!form.$valid"></my-buttons>
</code>```

I'm trying to set the disabled state of the button in my template. The above code almost works.

The form loads and is valid, the html is rendered as follows:

```<code><input type="submit" ng-click="bdisabled()" value="Save" ng-disabled="false" disabled="disabled">
</code>```

When I make the form invalid ng-disabled changes to true but disabled="disabled" stays no matter what.

What am I doing wrong?

答:
You can use the variable itself inside the ng-disabled likeng-disabled='disabled'
No need of interpolation operator since it is a native angular directive

Title: ng-disabled within angular directive

Body:
I have an angular directive:

angular.module("app").directive("myButtons", function () {
    return {
        restrict: "E",
        scope: {
            bdisabled: '='
        },
        templateUrl: "buttons.html"
    }
});

template:

<input type="submit" value="Update" ng-disabled="{{bdisabled}}" />

html:

<my-buttons bdisabled="!form.$valid"></my-buttons>

I'm trying to set the disabled state of the button in my template. The above code almost works.

The form loads and is valid, the html is rendered as follows:

<input type="submit" ng-click="bdisabled()" value="Save" ng-disabled="false" disabled="disabled">

When I make the form invalid ng-disabled changes to true but disabled="disabled" stays no matter what.

What am I doing wrong?


问:
Parse HTML string in Angular 2 and extract and update values
I just started working on an Angular project but am a bit stuck. I have a component that receives an HTML string from a (trusted) external source. I want to extract and update values from this string, and dispay it in my component.

Now displaying the string is easily done with the following code:

```<code><div [innerHTML]="displayString"></div>
</code>```

My input string has some  elements with the data-card-text element attached as identifier. Is it possible to extract this value, and update it whenever my component wants?

Example:
let displayString:string = "<svg><text data-card-text>Value I want to update</text></svg>"

Are operations like these even possible in Angular 2?

答:
So, if I understand correctly, you want to update the string value in the <text data-card-text/> element?

If so, you need to use regular expressions in order to extract the string inside the element. The output needs to be saved in a variable (i.e. displayString).

The variable can be added to the template in the following way:

{{displayString}}

Body:
I just started working on an Angular project but am a bit stuck. I have a component that receives an HTML string from a (trusted) external source. I want to extract and update values from this string, and dispay it in my component.

Now displaying the string is easily done with the following code:

My input string has some  elements with the data-card-text element attached as identifier. Is it possible to extract this value, and update it whenever my component wants?

Example:
let displayString:string = "<svg><text data-card-text>Value I want to update</text></svg>"

Are operations like these even possible in Angular 2?

Body:
So, if I understand correctly, you want to update the string value in the <text data-card-text/> element?

If so, you need to use regular expressions in order to extract the string inside the element. The output needs to be saved in a variable (i.e. displayString).

The variable can be added to the template in the following way:
<div>{{displayString}}</div>


问:
How to encode a JSON string that includes HTML characters?
I have an ASP.NET MVC view model that I need to pass to a JavaScript function when the page loads, and I'm currently doing that like so:

```<code><script type="text/javascript">
    $(window).on("load", function () {
        myFunction(@Html.Raw(JsonConvert.SerializeObject(Model)));
    });
</script>
</code>```

In other words, I'm using JSON.NET to serialize the model to JSON, and inserting that (un-encoded) into my
```

<p>That works, up to a point. But when my model contains a string property that whose text includes HTML tags *, these confuse the browser into thinking that the <code></code> tag.</li>
</ul>

<p>For example:</p>

```<script type="text/javascript">
    $(window).on("load", function () {
        myFunction({"myProperty": "<script>...</script>"});
    });
</script>
```

How can I solve this?

答:
This is a know problem. PHP's json_encode function encodes / as \/ to avoid exactly this problem.

A straightforward solution is to write your own JSON encode wrapper-function that replaces </script> by <\/script> after JSON encoding.

Maybe there is a better solution though, I'm not familiar with asp.net.

Body:
I have an ASP.NET MVC view model that I need to pass to a JavaScript function when the page loads, and I'm currently doing that like so:

In other words, I'm using JSON.NET to serialize the model to JSON, and inserting that (un-encoded) into my

That works, up to a point. But when my model contains a string property that whose text includes HTML tags *, these confuse the browser into thinking that the  tag.

For example:

"});
    });
</script>

How can I solve this?


问:
creating a literal for a Point - C++
I am trying to do a simple library where the object is a point on the xy-axis.

I want to be able to use literals like this:

Point a = (3,4);

where (3,4) is a point literal.

I read about user defined literals, but (as I understood) this seems to be impossible.

May be "(3,4)"_P is possible as I understand it.

However, I found on this page interesting use of user defined literals as follows:

```<code>#include <iostream>
#include <complex>

int main()
{
    using namespace std::complex_literals;
    std::complex<double> c = 1.0 + 1i;
    std::cout << "abs" << c << " = " << abs(c) << '\n';
}
</code>```

I can under stand the part 1i as a user defined literal, but not the whole thing 1.0 + 1i.

What I am missing, and what is the nearest possible way of getting a literal similar to (x,y) without using ".

答:
You can't make up literals on your own, only create suffixes for literals. Like the shown 1i or the standard language f as in 1.0f. (See e.g. this user-defined literal reference for more information.)

What you can to is to use uniform initialization doing something like

```<code>Point a = { 3, 4 };  // note the use of curly-braces
</code>```

Depending on what Point is you might need to add a suitable constructor to make it work.

Title: creating a literal for a Point - C++

Body:
I am trying to do a simple library where the object is a point on the xy-axis.

I want to be able to use literals like this:

Point a = (3,4);

where (3,4) is a point literal.

I read about user defined literals, but (as I understood) this seems to be impossible.

May be "(3,4)"_P is possible as I understand it.

However, I found on this page interesting use of user defined literals as follows:

#include <iostream>
#include <complex>

int main()
{
    using namespace std::complex_literals;
    std::complex<double> c = 1.0 + 1i;
    std::cout << "abs" << c << " = " << abs(c) << '\n';
}

I can under stand the part 1i as a user defined literal, but not the whole thing 1.0 + 1i.

What I am missing, and what is the nearest possible way of getting a literal similar to (x,y) without using ".

Body:
You can't make up literals on your own, only create suffixes for literals. Like the shown 1i or the standard language f as in 1.0f. (See e.g. this user-defined literal reference for more information.)

What you can to is to use uniform initialization doing something like

Point a = { 3, 4 };  // note the use of curly-braces

Depending on what Point is you might need to add a suitable constructor to make it work.


问:
jQuery AutoComplete Fill Array
I'm attempting to use jQuery's autocomplete feature, and after reading several posts I still have two questions:

1)  I've gotten autocomplete to work with the code posted at the bottom, however I need the array titled "data" to be filled from our database.  I've been trying to use different methods to fill this via AJAX.  I tried using $.get and $.ajax.  What is the correct syntax to accomplish this?

2)  This array will be big, I will have 60,000 plus values if I just fill the array once.  I was wondering if it's possible to perform an AJAX request to fill the array every-time the user enters a new letter?  Is this better to do, or just fill the array with all values at once?  By better, which taxes the system less?

```<code>//This code works
<script type="text/javascript">
  $(document).ready(function(){
  var data = "Facebook Gowalla Foursquare".split(" ");
  $("#search_company").autocomplete(data);
  });
</script>

//display company live search
echo('<form id="form" method="post" action="competitor_unlink.php" onsubmit="return">');
echo('Company: <input id="search_company"/>');
echo('<br/>');
echo('<button type="submit" value="Submit">Submit</button>');
echo('</form>');
</code>```

答:
Here's an example of how to specify a URL that will return the results from the database as JSON using the jQuery UI autocomplete plugin.

```<code>$("#search_company").autocomplete({
    source: "/Search", // <-- URL of the page you want to do the processing server-side
    minLength: 4 // <-- don't try to run the search until the user enters at least 4 chars
});
</code>```

Autocomplete will automatically append a querystring parameter named "term" to the URL so your search page will need to expect that.  Not sure what server technology you're using but since I'm a .NET developer here's an example in ASP.NET MVC :)

```<code>public ActionResult Search(string term) {
    var results = db.Search(term); // <-- this is where you query your DB
    var jqItems = new List<jQueryUIAutoCompleteItem>();
    foreach (var item in results) {
        jqItems.Add(new jQueryUIAutoCompleteItem() {
            value = item.CompanyId.ToString(),
            id = item.CompanyId.ToString(),
            label = item.CompanyName
        });
    }
    return Json(jqItems.ToArray(), JsonRequestBehavior.AllowGet);
}
</code>```

jQueryUIAutoCompleteItem is just a data container that represents the JSON format that the autocomplete plugin expects.

```<code>public class jQueryUIAutoCompleteItem {
    public string value { get; set; }
    public string label { get; set; }
    public string id { get; set; }
}
</code>```

Title: jQuery AutoComplete Fill Array

Body:
I'm attempting to use jQuery's autocomplete feature, and after reading several posts I still have two questions:

1)  I've gotten autocomplete to work with the code posted at the bottom, however I need the array titled "data" to be filled from our database.  I've been trying to use different methods to fill this via AJAX.  I tried using $.get and $.ajax.  What is the correct syntax to accomplish this?

2)  This array will be big, I will have 60,000 plus values if I just fill the array once.  I was wondering if it's possible to perform an AJAX request to fill the array every-time the user enters a new letter?  Is this better to do, or just fill the array with all values at once?  By better, which taxes the system less?

//This code works

//display company live search
echo('<form id="form" method="post" action="competitor_unlink.php" onsubmit="return">');
echo('Company: <input id="search_company"/>');
echo('
');
echo('<button type="submit" value="Submit">Submit</button>');
echo('</form>');

Body:
Here's an example of how to specify a URL that will return the results from the database as JSON using the jQuery UI autocomplete plugin.

$("#search_company").autocomplete({
    source: "/Search", // <-- URL of the page you want to do the processing server-side
    minLength: 4 // <-- don't try to run the search until the user enters at least 4 chars
});

Autocomplete will automatically append a querystring parameter named "term" to the URL so your search page will need to expect that.  Not sure what server technology you're using but since I'm a .NET developer here's an example in ASP.NET MVC :)

public ActionResult Search(string term) {
    var results = db.Search(term); // <-- this is where you query your DB
    var jqItems = new List<jQueryUIAutoCompleteItem>();
    foreach (var item in results) {
        jqItems.Add(new jQueryUIAutoCompleteItem() {
            value = item.CompanyId.ToString(),
            id = item.CompanyId.ToString(),
            label = item.CompanyName
        });
    }
    return Json(jqItems.ToArray(), JsonRequestBehavior.AllowGet);
}

jQueryUIAutoCompleteItem is just a data container that represents the JSON format that the autocomplete plugin expects.

public class jQueryUIAutoCompleteItem {
    public string value { get; set; }
    public string label { get; set; }
    public string id { get; set; }
}


问:
What is the equivalent of CultureInfo.GetCultures is .NET Core
Straight forward question really, What is the equivalent of CultureInfo.GetCultures is .NET Core?

Just trying to find a way to enumerate available cultures.

Just to clarify, this isn't the same as GetCultureInfo as that only gets a specified culture, (i.e. does not enumerate it)

答: There isn't a good way to enumerate all supported cultures in .NET Core < 2.0. In .NET Core 2.0 the respective queries to the underlying localisation systems have been implemented for windows and *nix, making this API available.</p>


问:
List of list with variable size of element with no brackets and apostrophes
I want to make list of list, like in 1 element of new list should be variable size of elements of another list.

For exmaple:

```<code>Input buffor[]:

> "0,70"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,70"
>
> ...
>
> ,"n"
</code>```

variable size, for example = 14 => list[0] = 14 elements of another list

```<code>(list[0] - list[13]) with no [] or ' between elements

Output list[]:

> list[0] = "0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0"
>
> ...
>
> list[n] = ...
</code>```

I got this line:

```<code>values = [values[i:i + size] for i in range(0, len(values), size)]
</code>```

, but it is producing something like this:

```<code>> ['"val1"', ',"val2"', ... ,',"val13"']
</code>```

答:
If someone is looking for solution

1 Simple While Loop

```<code>oper = 0
tmp = []
while (oper < len(values)):
    if ( (oper % size) == 0 ):
        temp = ''.join(map(str, values[oper:(size + oper)]))
        tmp.append(temp)
        oper += size
</code>```

2 - using List comprehension:

```<code>values = [''.join(map(str, values[i:i + size])) for i in range(0, len(values), size)]
</code>```

Body:
I want to make list of list, like in 1 element of new list should be variable size of elements of another list.

For exmaple:

Input buffor[]:

> "0,70"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,0"
>
> ,"0,70"
>
> ...
>
> ,"n"

variable size, for example = 14 => list[0] = 14 elements of another list

(list[0] - list[13]) with no [] or ' between elements

Output list[]:

> list[0] = "0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0"
>
> ...
>
> list[n] = ...

I got this line:

values = [values[i:i + size] for i in range(0, len(values), size)]

, but it is producing something like this:

> ['"val1"', ',"val2"', ... ,',"val13"']

Body:
If someone is looking for solution

1 Simple While Loop

oper = 0
tmp = []
while (oper < len(values)):
    if ( (oper % size) == 0 ):
        temp = ''.join(map(str, values[oper:(size + oper)]))
        tmp.append(temp)
        oper += size

2 - using List comprehension:

values = [''.join(map(str, values[i:i + size])) for i in range(0, len(values), size)]


问:
What kind of drive is "NoRootDirectory " (System.IO.DriveType.NoRootDirectory)?
In C# System.IO.DriveInfo has the property DriveType.

System.IO.DriveType is an enum:

```<code>public enum DriveType
{
    Unknown = 0,
    //
    // Summary:
    //     The drive does not have a root directory.
    NoRootDirectory = 1,
    Removable = 2,
    Fixed = 3,
    Network = 4,
    CDRom = 5,
    Ram = 6,
}
</code>```

I suspect that this is a volume without a drive letter. But using:

```<code>System.IO.DriveInfo.GetDrives();
</code>```

doesn't list my volume without drive letter.

Is NoRootDirectory used for any other type of volumes / drives or does System.IO.DriveInfo.GetDrives() just not show them?

答:
```<code>//Check fixed local drive
string path= "C\MyFolder\myfile.txt";
string root = Path.GetPathRoot(path);

if (DriveInfo.GetDrives().FirstOrDefault(d => d.Name == root).DriveType == DriveType.Fixed)
{
    MessageBox.Show(root);
}
</code>```

Body:
In C# System.IO.DriveInfo has the property DriveType.

System.IO.DriveType is an enum:

public enum DriveType
{
    Unknown = 0,
    //
    // Summary:
    //     The drive does not have a root directory.
    NoRootDirectory = 1,
    Removable = 2,
    Fixed = 3,
    Network = 4,
    CDRom = 5,
    Ram = 6,
}

I suspect that this is a volume without a drive letter. But using:

System.IO.DriveInfo.GetDrives();

doesn't list my volume without drive letter.

Is NoRootDirectory used for any other type of volumes / drives or does System.IO.DriveInfo.GetDrives() just not show them?


问:
PhpStorm Live Template ENUM not showing suggestions
I have a live template for todos and I would like a dropdown list when I create them that give me the options of "todo", "fixme" and "note". I understand that I can use enum for this but I can't seem to get it working properly. Here is a screenshot of my live template:

And here is a GIF of the use of that live template:

What am I doing wrong?

答:
Here's what I've came up with. You have to surround strings with quote signs there, please see:

and


问:
sort the list of links by the name of the link
I have list of links

```<code>links = [
  '<a href="http://127.0.0.1:5000/project/24/portfolio/">Packaging Only Demo</a>',
  '<a href="http://127.0.0.1:5000/project/38/portfolio/">QA Source</a>',
  '<a href="http://127.0.0.1:5000/project/44/portfolio/">Complete Demo</a>'
]
</code>```

And I need to sort the list by the name of the link.

I tried to sort it with a regular expression but it lasted too long. The list consists of a multitude of references

```<code>import re
def sorted(x):
  return re.search(r'\>(.*)<', x).group(1)

links = sorted(links, key=sorted)
print(links)
</code>```

答: Create a function that extracts the name from a given string; then pass this function as key argument to sort or sorted.

Body:
I have list of links

links = [
  'Packaging Only Demo',
  'QA Source',
  'Complete Demo'
]

And I need to sort the list by the name of the link.

I tried to sort it with a regular expression but it lasted too long. The list consists of a multitude of references

import re
def sorted(x):
  return re.search(r'\>(.*)<', x).group(1)

links = sorted(links, key=sorted)
print(links)


问:
How do i configure fiddler to show the parameters included in a url
I am having problems with our .net openID authorisation

I am trying to use fiddler to view to flow of addresses and data, but fiddler isn't showing the url parameters in the return to localhost

so i tested this by typing

```<code>https://localhost:8080/#id=2
</code>```

into IE and seeing what showed up in fiddler, it  was

```<code>1281    502 HTTP    Tunnel to   localhost:8080  512 no-cache, must-revalidate   text/html; charset=UTF-8    iexplore:19884
</code>```

i tried looking at fiddler help for configuration it suggested not using localhost but using your machine name, I tried this is wasn't any different.

Thank you in advance.

This is the pre-question to get all the information I will need for the next question about the openid problem :)

答: I wanted to be looking at the response of the line above for the information I needed. This question is closed thanks</p>

Body:
I am having problems with our .net openID authorisation

I am trying to use fiddler to view to flow of addresses and data, but fiddler isn't showing the url parameters in the return to localhost

so i tested this by typing

https://localhost:8080/#id=2

into IE and seeing what showed up in fiddler, it  was

1281    502 HTTP    Tunnel to   localhost:8080  512 no-cache, must-revalidate   text/html; charset=UTF-8    iexplore:19884

i tried looking at fiddler help for configuration it suggested not using localhost but using your machine name, I tried this is wasn't any different.

Thank you in advance.

This is the pre-question to get all the information I will need for the next question about the openid problem :)


问:
How to serialize a Marshmallow field under a different name
I want a Marshmallow Schema  with the following output json -

```<code>{
  "_id": "aae216334c3611e78a3e06148752fd79",
  "_time": 20.79606056213379,
  "more_data" : {...}
}
</code>```

Marshmallow doesn't serialize private members so this is as close as I can get -

```<code>class ApiSchema(Schema):
    class Meta:
        strict = True

    time = fields.Number()
    id = fields.String()
</code>```

But I do need the underscores in the output json.

Is there a way to tell Marshmallow to serialize the fields using different names?

答:
You can override the dump method to prepend underscores to selected fields before returning the serialised object:

```<code>class ApiSchema(Schema):
    class Meta:
        strict = True

    time = fields.Number()
    id = fields.String()

    def dump(self, *args, **kwargs):
        special = kwargs.pop('special', None)
        _partial = super(ApiSchema, self).dump(*args, **kwargs)
        if special is not None and all(f in _partial for f in special):
            for field in special:
                _partial['_{}'.format(field)] = _partial.pop(field)
        return _partial
</code>```

```<code>api_schema = ApiSchema(...)
result = api_schema.dump(obj, special=('id', 'time'))
</code>```

You can also use the post_dump decorator on a separate custom method without having to override dump, but then, you may have to hardcode the fields to-be-modified as part of the class, which may be inflexible depending on your use case.

Body:
I want a Marshmallow Schema  with the following output json -

{
  "_id": "aae216334c3611e78a3e06148752fd79",
  "_time": 20.79606056213379,
  "more_data" : {...}
}

Marshmallow doesn't serialize private members so this is as close as I can get -

class ApiSchema(Schema):
    class Meta:
        strict = True

    time = fields.Number()
    id = fields.String()

But I do need the underscores in the output json.

Is there a way to tell Marshmallow to serialize the fields using different names?

Body:
You can override the dump method to prepend underscores to selected fields before returning the serialised object:

class ApiSchema(Schema):
    class Meta:
        strict = True

    time = fields.Number()
    id = fields.String()

    def dump(self, *args, **kwargs):
        special = kwargs.pop('special', None)
        _partial = super(ApiSchema, self).dump(*args, **kwargs)
        if special is not None and all(f in _partial for f in special):
            for field in special:
                _partial['_{}'.format(field)] = _partial.pop(field)
        return _partial

api_schema = ApiSchema(...)
result = api_schema.dump(obj, special=('id', 'time'))

You can also use the post_dump decorator on a separate custom method without having to override dump, but then, you may have to hardcode the fields to-be-modified as part of the class, which may be inflexible depending on your use case.


问:
Why is Scala promoting List[Any] to List[Long]?
In the following code:

```<code>def test(list: List[Any]): Unit = {
  list.foreach {
    v =>
    v match {
      case r: AnyRef => println(r + ": " + r.getClass.getName)
      case d: Double => println(d + ": Double")
      case f: Float=> println(f + ": Float")
      case b: Byte => println(b + ": Byte")
      case c: Char => println(c + ": Char")
      case s: Short => println(s + ": Short")
      case i: Int => println(i + ": Int")
      case l: Long=> println(l + ": Long")
      case b: Boolean => println(b + ": Boolean")
      case _ => throw new IllegalArgumentException("Unknown type: " + v)
    }
  }
}

test(List(0L, 1.asInstanceOf[Int], 2.asInstanceOf[Short]))
</code>```

here is the output (Scala 2.8.1):

```<code>0: java.lang.Long
1: java.lang.Long
2: java.lang.Long
</code>```

Why are the numbers being promoted to java.lang.Long? How can I do this so that they either keep their AnyVal types or get "boxed" to the equivalent AnyRef type?

答:
Here is why (building on the answer by pst):

```<code>scala> val x = List(0L, 1.asInstanceOf[Int], 2.asInstanceOf[Short])
x: List[Long] = List(0, 1, 2)
</code>```

It seems Scala tries to define the type of the list to be of the biggest object that can contain all the elements. For instance,

```<code>scala> val x = List(0.asInstanceOf[Short], 1.asInstanceOf[Int], 2.asInstanceOf[Short])
x: List[Int] = List(0, 1, 2)
</code>```

So the workaround suggested by pst is the answer.

Body:
In the following code:

def test(list: List[Any]): Unit = {
  list.foreach {
    v =>
    v match {
      case r: AnyRef => println(r + ": " + r.getClass.getName)
      case d: Double => println(d + ": Double")
      case f: Float=> println(f + ": Float")
      case b: Byte => println(b + ": Byte")
      case c: Char => println(c + ": Char")
      case s: Short => println(s + ": Short")
      case i: Int => println(i + ": Int")
      case l: Long=> println(l + ": Long")
      case b: Boolean => println(b + ": Boolean")
      case _ => throw new IllegalArgumentException("Unknown type: " + v)
    }
  }
}

test(List(0L, 1.asInstanceOf[Int], 2.asInstanceOf[Short]))

here is the output (Scala 2.8.1):

0: java.lang.Long
1: java.lang.Long
2: java.lang.Long

Why are the numbers being promoted to java.lang.Long? How can I do this so that they either keep their AnyVal types or get "boxed" to the equivalent AnyRef type?

Body:
Here is why (building on the answer by pst):

scala> val x = List(0L, 1.asInstanceOf[Int], 2.asInstanceOf[Short])
x: List[Long] = List(0, 1, 2)

It seems Scala tries to define the type of the list to be of the biggest object that can contain all the elements. For instance,

scala> val x = List(0.asInstanceOf[Short], 1.asInstanceOf[Int], 2.asInstanceOf[Short])
x: List[Int] = List(0, 1, 2)

So the workaround suggested by pst is the answer.


问:
Random position of nodes in hierarchical tree with alternate paths
I'm struggling with directed graph hierarchy tree visualization (distributed network in this case). Using graphviz: dot I have this tree:

```<code>digraph G {
    node[width=0.14, height=0.14];
    edge[weight=3, color = "0.000 0.000 0.0"];
    1 -> 2;
    1 -> 3;
    edge[weight=2, color = "0.000 0.000 0.175"];
    2 -> 4;
    2 -> 5;
    3 -> 6;
    3 -> 7;
    edge[weight=1, color = "0.000 0.000 0.825"];
    3 -> 4;
    3 -> 5;
    2 -> 6;
    2 -> 7;
}
</code>```

Resulting in:

You can see that the primary paths (edges with higher weights) are crossed. The goal is to have the preferred path nodes as close as possible. I can do it by changing the order of nodes randomly so the output looks like this:

However I don't want to think about the ordering algorithm as I want to automate this on hundreds of nodes.

From documentation:

The weight of an edge provides another way to keep edges straight. An edge’s weight suggests some measure of an edge’s importance; thus, the heavier the weight, the closer together its nodes should be. dot causes edges with heavier weights to be drawn shorter and straighter.

But this is not the case as the nodes are drawn in random order. What am I doing wrong?

答:
Probably not the answer you were looking for, but since dot doesn't seem to work with edge weights in this case:

You may just use constraint=false for the lightgray edges.

ContentLicense: CC BY-SA 4.0

Body:
I'm struggling with directed graph hierarchy tree visualization (distributed network in this case). Using graphviz: dot I have this tree:

digraph G {
    node[width=0.14, height=0.14];
    edge[weight=3, color = "0.000 0.000 0.0"];
    1 -> 2;
    1 -> 3;
    edge[weight=2, color = "0.000 0.000 0.175"];
    2 -> 4;
    2 -> 5;
    3 -> 6;
    3 -> 7;
    edge[weight=1, color = "0.000 0.000 0.825"];
    3 -> 4;
    3 -> 5;
    2 -> 6;
    2 -> 7;
}

Resulting in:

You can see that the primary paths (edges with higher weights) are crossed. The goal is to have the preferred path nodes as close as possible. I can do it by changing the order of nodes randomly so the output looks like this:

However I don't want to think about the ordering algorithm as I want to automate this on hundreds of nodes.

From documentation:

The weight of an edge provides another way to keep edges straight. An edge’s weight suggests some measure of an edge’s importance; thus, the heavier the weight, the closer together its nodes should be. dot causes edges with heavier weights to be drawn shorter and straighter.

But this is not the case as the nodes are drawn in random order. What am I doing wrong?


问:
Iterating through a vector and using that value as column of dataframe
I am using this for loop to standardize the data in my columns. Here m_sel_cols is a vector with column names.

```<code>for(i in m_sel_cols)
    {
        cal <- work_data1$i
        cal <- ((cal-mean(cal))/sd(cal))
    }
</code>```

Suppose if my column name is "A" then is you do :

```<code>  ...
        cal <- work_data1$A
  ...
</code>```

The number of columns in my dataset is huge and I want to convert it back to data frame, I know cbind() can be used but how within the for loop?

答:
You can "loop" through columns using sapply.

```<code>xy <- data.frame(a = 1:3, b = 4:6, c = 7:9)
sapply(xy, FUN = function(x) (x - mean(x))/sd(x))

      a  b  c
[1,] -1 -1 -1
[2,]  0  0  0
[3,]  1  1  1
</code>```

or

```<code>> scale(xy)
      a  b  c
[1,] -1 -1 -1
[2,]  0  0  0
[3,]  1  1  1
attr(,"scaled:center")
a b c
2 5 8
attr(,"scaled:scale")
a b c
1 1 1
</code>```

Body:
I am using this for loop to standardize the data in my columns. Here m_sel_cols is a vector with column names.

for(i in m_sel_cols)
    {
        cal <- work_data1$i
        cal <- ((cal-mean(cal))/sd(cal))
    }

Suppose if my column name is "A" then is you do :

  ...
        cal <- work_data1$A
  ...

The number of columns in my dataset is huge and I want to convert it back to data frame, I know cbind() can be used but how within the for loop?

Body:
You can "loop" through columns using sapply.

xy <- data.frame(a = 1:3, b = 4:6, c = 7:9)
sapply(xy, FUN = function(x) (x - mean(x))/sd(x))

      a  b  c
[1,] -1 -1 -1
[2,]  0  0  0
[3,]  1  1  1

or

> scale(xy)
      a  b  c
[1,] -1 -1 -1
[2,]  0  0  0
[3,]  1  1  1
attr(,"scaled:center")
a b c
2 5 8
attr(,"scaled:scale")
a b c
1 1 1