问:
Why is a parameter pack allowed after default arguments?
Maybe I'm missing something obvious, but the following compiles and runs, and I'm not sure why. I am aware of this, but in the example below the position of the parameter pack and the default argument are reversed. Doesn't it violate the rule that default arguments have to appear last? The parameter pack cannot have a default value.

```<code>#include <iostream>
#include <string>
#include <tuple>

template<typename ... Ts>
struct Test
{
    int i;
    std::string str;

    Test(int _i = 0, Ts&& ... _ts)
        :
          i(_i),
          str(std::get<0>(std::forward_as_tuple(std::forward<Ts>(_ts)...)))
    {}
};

int main()
{
    Test<std::string> t(1, "huh??");
    std::cout << "t.i = " << t.i << ", t.str = " << t.str << "\n";

    return 0;
}
</code>```

This produces

```<code>t.i = 1, t.str = huh??
</code>```

答:
From 8.3.6 ([dcl.fct.default])/4:

For non-template functions, default arguments can be added in later
  declarations of a function in the same scope. Declarations in
  different scopes have completely distinct sets of default arguments.
  That is, declarations in inner scopes do not acquire default arguments
  from declarations in outer scopes, and vice versa. In a given function
  declaration, each parameter subsequent to a parameter with a default
  argument shall have a default argument supplied in this or a previous
  declaration or shall be a function parameter pack. A default argument
  shall not be redefined by a later declaration (not even to the same
  value).
   [ Example:

```<code>void g(int = 0, ...); // OK, ellipsis is not a parameter. So it can follow a parameter with a default argument
</code>```

Body:
Maybe I'm missing something obvious, but the following compiles and runs, and I'm not sure why. I am aware of this, but in the example below the position of the parameter pack and the default argument are reversed. Doesn't it violate the rule that default arguments have to appear last? The parameter pack cannot have a default value.

#include <iostream>
#include <string>
#include <tuple>

template<typename ... Ts>
struct Test
{
    int i;
    std::string str;

    Test(int _i = 0, Ts&& ... _ts)
        :
          i(_i),
          str(std::get<0>(std::forward_as_tuple(std::forward<Ts>(_ts)...)))
    {}
};

int main()
{
    Test<std::string> t(1, "huh??");
    std::cout << "t.i = " << t.i << ", t.str = " << t.str << "\n";

    return 0;
}

This produces

t.i = 1, t.str = huh??

Body:
From 8.3.6 ([dcl.fct.default])/4:

For non-template functions, default arguments can be added in later
  declarations of a function in the same scope. Declarations in
  different scopes have completely distinct sets of default arguments.
  That is, declarations in inner scopes do not acquire default arguments
  from declarations in outer scopes, and vice versa. In a given function
  declaration, each parameter subsequent to a parameter with a default
  argument shall have a default argument supplied in this or a previous
  declaration or shall be a function parameter pack. A default argument
  shall not be redefined by a later declaration (not even to the same
  value).
   [ Example:

void g(int = 0, ...); // OK, ellipsis is not a parameter. So it can follow a parameter with a default argument


来源: stackexchange

问:
how to resize image in wordpress plugin developmennt
I am developing a wordpress plugin, and use custom metabox of an image, how can i resize image dynamically to display on front.
i am using this function but it not works</p>

```<code>add_image_size( 'photos', 100, 100, true );
</code>```

答:
You can use wp_get_image_editor()

```<code>$image = wp_get_image_editor( 'cool_image.jpg' );
if ( ! is_wp_error( $image ) ) {
    $image->resize( 300, 300, true );
    $image->save( 'new_image.jpg' );
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am developing a wordpress plugin, and use custom metabox of an image, how can i resize image dynamically to display on front.
i am using this function but it not works

add_image_size( 'photos', 100, 100, true );

Body:
You can use wp_get_image_editor()

$image = wp_get_image_editor( 'cool_image.jpg' );
if ( ! is_wp_error( $image ) ) {
    $image->resize( 300, 300, true );
    $image->save( 'new_image.jpg' );
}


问:
how to watermark a rendered PDF (on context) without repeating the image
I'm rendering a PDF file on my iPad using a graphics PDF context. The PDFs vary in size but may be up to 90 pages. I need a background image on each page but if I simply draw it the PDF file size will be way larger. Is there a way to kinda only add it once and 'share' it somehow across pages?

Thanks

答: The PDF format specification enables you to re-use objects "by reference". You can re-use any object multiple times that is defined only once. Usually that happens with fonts, logos, background images, watermarks, ICC profiles, ....</p>

ContentLicense: CC BY-SA 2.5


问:
How to find the "href" of a
 a particular frame?
Image here I am trying to get the "href" of a particular frame which you can find in the image , i tried as much as i can but i am not able to get the "href"

```<code>List<WebElement> list=d.findElements(By.xpath(".//*[@id='collegeFilter']/div/div/div/div/div/div[13]/div"));
                   for(WebElement e : list){
                       String link = e.getAttribute("href");
                       System.out.println(link);
</code>```

I tried the above code , i took the Xpath of that frame and tried to get the href of that frame . Link: http://freevideolectures.com/Subject/Business-Management  [image]

答:
Your xpath is pointing to top element which doesn't have href property. you can try with following it may help you.</p>

```<code>List<WebElement> list=d.findElements(By.xpath(".//*[@id='collegeFilter']/div/div/div/div/div/div/div/div/figure/a"));
for(WebElement e : list){
       String link = e.getAttribute("href");
       System.out.println(link);
 }
</code>```

Title: How to find the "href" of a <ul> a particular frame?

Body:
Image here I am trying to get the "href" of a particular frame which you can find in the image , i tried as much as i can but i am not able to get the "href"

List<WebElement> list=d.findElements(By.xpath(".//*[@id='collegeFilter']/div/div/div/div/div/div[13]/div"));
                   for(WebElement e : list){
                       String link = e.getAttribute("href");
                       System.out.println(link);

I tried the above code , i took the Xpath of that frame and tried to get the href of that frame . Link: http://freevideolectures.com/Subject/Business-Management  [image]

Body:
Your xpath is pointing to top element which doesn't have href property. you can try with following it may help you.

List<WebElement> list=d.findElements(By.xpath(".//*[@id='collegeFilter']/div/div/div/div/div/div/div/div/figure/a"));
for(WebElement e : list){
       String link = e.getAttribute("href");
       System.out.println(link);
 }


问:
How do I write 'this' less often?
Using ES6 classes is great and all, but I find myself using this.variable everywhere, and it is always referring to my class. Is there a way to have implied globals within my class be implied this.variable instead? So if I write 'width' it will be defaulted to this.width instead of an implied global?

Or if there are some best practices that I might not be aware of to cut down on my 'this' addiction I'd love to read that too. In the file I'm currently working on there are about half as many this keywords as there are lines of code...

答:
I know this isn't a recommended practice, but a with statement is sortof what OP asks for.

with allows parsing an object, using the attributes as variables within the statement:

var MyClass = /** @class */ (function() {
  function MyClass(name, age) {
    this.name = name;
    this.age = age;
  }
  MyClass.prototype.whoami = function() {
    with(this) {
      console.log(name, age);
    }
  };
  return MyClass;
}());
var c = new MyClass("bob", 123);
c.whoami();```

There is the issue that with is disabled in strict mode though, meaning that there are some contexts where it simply won't work.

ES6 classes is one such context, so if OP want's to use ES6 classes, then with is out.

Title: How do I write 'this' less often?

Body:
I know this isn't a recommended practice, but a with statement is sortof what OP asks for.

with allows parsing an object, using the attributes as variables within the statement:

var MyClass = /** @class */ (function() {
  function MyClass(name, age) {
    this.name = name;
    this.age = age;
  }
  MyClass.prototype.whoami = function() {
    with(this) {
      console.log(name, age);
    }
  };
  return MyClass;
}());
var c = new MyClass("bob", 123);
c.whoami();

There is the issue that with is disabled in strict mode though, meaning that there are some contexts where it simply won't work.

ES6 classes is one such context, so if OP want's to use ES6 classes, then with is out.


问:
Implement dilation filter for SVG Morphology filter
I am trying to implement dilation filter for SVG Morphology filter.

The documentation says dilation (or erosion) kernel is a rectangle with a width of 2*x-radius and a height of 2*y-radius. In dilation, the output pixel is the individual component-wise maximum of the corresponding R,G,B,A values in the input image's kernel rectangle.

https://www.w3.org/TR/SVG/filters.html#feMorphologyElement

I couldn't really find out what should be the kernel in this case. Can you please give some pointers?

Is it really equivalent to finding local maxima of below region for each pixel in input image?

```<code>  int startX = std::max( pixelCordX - radiusX,  0 );
  int endX = std::min( pixelCordX + radiusX,  width - 1 );
  int = std::max( pixelCordY - radiusY,  0 );
  int endY = std::min( pixelCordY + radiusY,  height - 1 );

  outputPixel( pixelCordX , pixelCordY  ) = ComputeMaxMin( image[][], startX, endX, startY, endY );
</code>```

答: Loop through all pixels in the rectangle, keeping track of the maximum value for each of R,G,B and A.  Combine the maximum value of each component into a single colour value, and make that the centre pixel colour.</p>

Body:
I am trying to implement dilation filter for SVG Morphology filter.

The documentation says dilation (or erosion) kernel is a rectangle with a width of 2*x-radius and a height of 2*y-radius. In dilation, the output pixel is the individual component-wise maximum of the corresponding R,G,B,A values in the input image's kernel rectangle.

https://www.w3.org/TR/SVG/filters.html#feMorphologyElement

I couldn't really find out what should be the kernel in this case. Can you please give some pointers?

Is it really equivalent to finding local maxima of below region for each pixel in input image?

  int startX = std::max( pixelCordX - radiusX,  0 );
  int endX = std::min( pixelCordX + radiusX,  width - 1 );
  int = std::max( pixelCordY - radiusY,  0 );
  int endY = std::min( pixelCordY + radiusY,  height - 1 );

  outputPixel( pixelCordX , pixelCordY  ) = ComputeMaxMin( image[][], startX, endX, startY, endY );


问:
NameError: global name 'styles' is not defined
This part of my code Paragraph('Road',style["Normal"], bulletText=None) gives me this NameError: global name 'styles' is not defined.
The module that I have importeded is :

```<code>from reportlab.lib.styles import ParagraphStyle
</code>```

答:
First make sure you have defined styles like this :

```<code>from reportlab.lib.styles import getSampleStyleSheet

styles = getSampleStyleSheet()
</code>```

Also you can add other styles like "Justify"

You can do it this way (exemple with "Justify"):

```<code>from reportlab.lib.enums import TA_JUSTIFY

styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
text = "Hello World !"
story.append(Paragraph(text, style["Justify"]))
</code>```

Then use it this way :

```<code># create pdf
pdf = SimpleDocTemplate("your_doc.pdf")
# write in it
story = []
story.append(Paragraph(text, style["Justify"]))
# save it
pdf.build(story)
# return
return (frame)
</code>```

And Here it is you have your pdf with styles !

Body:
This part of my code Paragraph('Road',style["Normal"], bulletText=None) gives me this NameError: global name 'styles' is not defined.
The module that I have importeded is :

from reportlab.lib.styles import ParagraphStyle

Body:
First make sure you have defined styles like this :

from reportlab.lib.styles import getSampleStyleSheet

styles = getSampleStyleSheet()

Also you can add other styles like "Justify"

You can do it this way (exemple with "Justify"):

from reportlab.lib.enums import TA_JUSTIFY

styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
text = "Hello World !"
story.append(Paragraph(text, style["Justify"]))

Then use it this way :

# create pdf
pdf = SimpleDocTemplate("your_doc.pdf")
# write in it
story = []
story.append(Paragraph(text, style["Justify"]))
# save it
pdf.build(story)
# return
return (frame)

And Here it is you have your pdf with styles !


问:
How to perform segue from inside UIView
How can a prepare a segue properly from inside a UIView NOT UIViewController

My UIViewController has a container view and inside that container view has a button.

```<code>class myInnerView: UIView {
    ...
    func myButton(gesture: UIGestureRecognizer){
        //calling a perform segue from another UIViewController does not recognize the SegueID
        //ViewController().self.showProfile(self.id) -- DOES NOT WORK
    }
}

class ViewController: UIViewController {
    ...
    func showProfile(id: String){
        ...
        self.performSegueWithIdentifier("toViewProfile", sender: self)
    }
}
</code>```

答:
One of the solution is to add UITapGestureRecognizer to your button but from inside the UIViewController :

```<code>class ViewController: UIViewController {

    var myInnerView = myInnerView()

    override func viewDidLoad() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.handleTapGesture))
        self.myInnerView.myButton.addGestureRecognizer(tap)
    }

    @objc func handleTapGesture(){
        performSegue(withIdentifier: "toViewProfile", sender: nil)
    }
}

class myInnerView: UIView {
    // make outlet of your button so you can add the tapGestureRecognizer from your ViewController and thats all
    @IBOutlet public weak var myButton: UIButton!
}
</code>```

Title: How to perform segue from inside UIView

Body:
How can a prepare a segue properly from inside a UIView NOT UIViewController

My UIViewController has a container view and inside that container view has a button.

class myInnerView: UIView {
    ...
    func myButton(gesture: UIGestureRecognizer){
        //calling a perform segue from another UIViewController does not recognize the SegueID
        //ViewController().self.showProfile(self.id) -- DOES NOT WORK
    }
}

class ViewController: UIViewController {
    ...
    func showProfile(id: String){
        ...
        self.performSegueWithIdentifier("toViewProfile", sender: self)
    }
}

Body:
One of the solution is to add UITapGestureRecognizer to your button but from inside the UIViewController :

class ViewController: UIViewController {

    var myInnerView = myInnerView()

    override func viewDidLoad() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.handleTapGesture))
        self.myInnerView.myButton.addGestureRecognizer(tap)
    }

    @objc func handleTapGesture(){
        performSegue(withIdentifier: "toViewProfile", sender: nil)
    }
}

class myInnerView: UIView {
    // make outlet of your button so you can add the tapGestureRecognizer from your ViewController and thats all
    @IBOutlet public weak var myButton: UIButton!
}


问:
.htaccess issue in wordpress 4.8.2
I am having images issue in my Wordpress version 4.8.2.

There is an .htaccess file in wp-content folder public_html/wp-content/.htaccess. When I rename or delete this file images work fine but the site breaks down

.htaccess

```<code> # BEGIN WordPress
  <IfModule mod_rewrite.c>
     RewriteEngine On
     RewriteBase /
     RewriteRule ^index\.php$ - [L]
     RewriteCond %{REQUEST_FILENAME} !-f
     RewriteCond %{REQUEST_FILENAME} !-d
     RewriteRule . /index.php [L]
  </IfModule>
# END WordPress

php_value upload_max_filesize 128M
php_value post_max_size 128M
php_value max_execution_time 300
php_value max_input_time 300
php_value memory_limit 256M
</code>```

答: You have to place this .htaccess file in root folder(public_html/.htaccess). Don't upload that file in wp-content folder. I hope it will make sense.</p>

Title: .htaccess issue in wordpress 4.8.2

Body:
I am having images issue in my Wordpress version 4.8.2.

There is an .htaccess file in wp-content folder public_html/wp-content/.htaccess. When I rename or delete this file images work fine but the site breaks down

.htaccess

 # BEGIN WordPress
  <IfModule mod_rewrite.c>
     RewriteEngine On
     RewriteBase /
     RewriteRule ^index\.php$ - [L]
     RewriteCond %{REQUEST_FILENAME} !-f
     RewriteCond %{REQUEST_FILENAME} !-d
     RewriteRule . /index.php [L]
  </IfModule>
# END WordPress

php_value upload_max_filesize 128M
php_value post_max_size 128M
php_value max_execution_time 300
php_value max_input_time 300
php_value memory_limit 256M


问:
Implement IDataErrorInfo on button click event
I'm trying to achieve validation on button click for a textbox using binding. Basically when I click Submit my textbox is not turning red and giving me the "Required" error, it is when I add text to it.

I'm new at validation and been looking at this for almost a week on and off in frustration. I think my answer may have something to-do with propertychangedevent? but I'm not sure and resorting to asking the professionals.

All and any help with this will be must appreciated.

Here is my Model class:

```<code> public class sForms : INotifyPropertyChanged, IDataErrorInfo

{
    private string name;
    public string NAME { get { return name; } set { if (name != value) name = value.Trim(); OnPropertyChanged("NAME"); } }

    public string this[string columnName]
    {
        get
        {
            return ValidationError(columnName);
        }

    }

    public string Error { get { return null; } }

    private string ValidationError(string columnName)
    {
        string error = null;
        switch (columnName)
        {
            case "NAME":
                error = IsNameValid();
                break;
        }
        return
            error;
    }

    static readonly string[] ValidatedProperties = { "NAME" };

    public bool IsValid
    {
        get
        {
            foreach (string property in ValidatedProperties)
            {
                if (ValidationError(property) != null)
                {
                    return
                        false;
                }
            }
            return
                true;
        }
    }

    public string IsNameValid()
    {
        if (string.IsNullOrWhiteSpace(NAME) || string.IsNullOrEmpty(NAME))
            return "Required";
        else
            return
                null;
    }

    #region Property Changed
    private void OnPropertyChanged(string propertyName)
    {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    public event PropertyChangedEventHandler PropertyChanged;
    #endregion
}
</code>```

Here is my XAML for my button + Text Box;

```<code>        <TextBox Controls:TextBoxHelper.UseFloatingWatermark="True"
                     Controls:TextBoxHelper.Watermark="Name *"
                     Grid.Column="1" Grid.Row="1"
                     Margin="0 0 2 0"
                     Text="{Binding Path=NAME, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"
                     >
        <Button Content="Submit"
                Style="{DynamicResource SquareButtonStyle}"
                VerticalAlignment="Bottom" HorizontalAlignment="Right"
                Margin="0 0 10 0"
                Click="Submit_Click"
                />
</code>```

Here is my code behind;

```<code>        public v_subsForm()
    {
        InitializeComponent();
        this.DataContext = subs;
    }

    sForms subs = new sForms();
    #region PropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

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

    private void Submit_Click(object sender, RoutedEventArgs e)
    {
        if (subs.IsValid)
            MessageBox.Show("True");
        else
            MessageBox.Show("False");
    }
</code>```

答:
First, your code works as it should, assuming you included all MahApps.Metro resources that are required. Also, you don't need to implement INotifyPropertyChanged in your code-behind (that's your MainWindow I guess).

I'm trying to achieve validation on button click for a textbox using binding.

That is not how IDataErrorInfo works. IDataErrorInfo defines an API that the binding can query for errors on the object that it's bound to. So, when your NAME property is changed, the binding will query the indexer on your sForms object: subs["NAME"]. If it gets an error, error template is applied. This is usually paired with a submit button whose Command property is bound to a command whose CanExecute checks for errors and if there are errors the button is disabled (so you can not submit if there are errors, button is disabled).

If you want to do your validation on button click, you don't need to implement IDataErrorInfo. System.Windows.Controls.Validation class has attached properties that drive presentation of errors: HasError, Errors, ErrorTemplate. But you can't just set Validation.HasError to true (there is no accessible setter) like you can set Validation.ErrorTemplate. To set Validation.HasError in code-behind, you can use Validation.MarkInvalid method, but this is not how these things are usually done. Here is a quick example, for this to work you need to set Name property on your TextBox to MyTextBox:

```<code>private void Submit_Click(object sender, RoutedEventArgs e)
{
    if (!string.IsNullOrEmpty(MyTextBox.Text)) return;

    BindingExpression bindingExpression =
        BindingOperations.GetBindingExpression(MyTextBox, TextBox.TextProperty);

    BindingExpressionBase bindingExpressionBase =
        BindingOperations.GetBindingExpressionBase(MyTextBox, TextBox.TextProperty);

    ValidationError validationError =
        new ValidationError(new ExceptionValidationRule(), bindingExpression);

    validationError.ErrorContent = "My error message.";

    Validation.MarkInvalid(bindingExpressionBase, validationError);
}
</code>```

So if MyTextBox.Text is empty, it will be considered invalid.

Body:
I'm trying to achieve validation on button click for a textbox using binding. Basically when I click Submit my textbox is not turning red and giving me the "Required" error, it is when I add text to it.

I'm new at validation and been looking at this for almost a week on and off in frustration. I think my answer may have something to-do with propertychangedevent? but I'm not sure and resorting to asking the professionals.

All and any help with this will be must appreciated.

Here is my Model class:

 public class sForms : INotifyPropertyChanged, IDataErrorInfo

{
    private string name;
    public string NAME { get { return name; } set { if (name != value) name = value.Trim(); OnPropertyChanged("NAME"); } }

    public string this[string columnName]
    {
        get
        {
            return ValidationError(columnName);
        }

    }

    public string Error { get { return null; } }

    private string ValidationError(string columnName)
    {
        string error = null;
        switch (columnName)
        {
            case "NAME":
                error = IsNameValid();
                break;
        }
        return
            error;
    }

    static readonly string[] ValidatedProperties = { "NAME" };

    public bool IsValid
    {
        get
        {
            foreach (string property in ValidatedProperties)
            {
                if (ValidationError(property) != null)
                {
                    return
                        false;
                }
            }
            return
                true;
        }
    }

    public string IsNameValid()
    {
        if (string.IsNullOrWhiteSpace(NAME) || string.IsNullOrEmpty(NAME))
            return "Required";
        else
            return
                null;
    }

    #region Property Changed
    private void OnPropertyChanged(string propertyName)
    {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    public event PropertyChangedEventHandler PropertyChanged;
    #endregion
}

Here is my XAML for my button + Text Box;

        <TextBox Controls:TextBoxHelper.UseFloatingWatermark="True"
                     Controls:TextBoxHelper.Watermark="Name *"
                     Grid.Column="1" Grid.Row="1"
                     Margin="0 0 2 0"
                     Text="{Binding Path=NAME, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"
                     >
        <Button Content="Submit"
                Style="{DynamicResource SquareButtonStyle}"
                VerticalAlignment="Bottom" HorizontalAlignment="Right"
                Margin="0 0 10 0"
                Click="Submit_Click"
                />

Here is my code behind;

        public v_subsForm()
    {
        InitializeComponent();
        this.DataContext = subs;
    }

    sForms subs = new sForms();
    #region PropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

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

    private void Submit_Click(object sender, RoutedEventArgs e)
    {
        if (subs.IsValid)
            MessageBox.Show("True");
        else
            MessageBox.Show("False");
    }

Body:
First, your code works as it should, assuming you included all MahApps.Metro resources that are required. Also, you don't need to implement INotifyPropertyChanged in your code-behind (that's your MainWindow I guess).

I'm trying to achieve validation on button click for a textbox using binding.

That is not how IDataErrorInfo works. IDataErrorInfo defines an API that the binding can query for errors on the object that it's bound to. So, when your NAME property is changed, the binding will query the indexer on your sForms object: subs["NAME"]. If it gets an error, error template is applied. This is usually paired with a submit button whose Command property is bound to a command whose CanExecute checks for errors and if there are errors the button is disabled (so you can not submit if there are errors, button is disabled).

If you want to do your validation on button click, you don't need to implement IDataErrorInfo. System.Windows.Controls.Validation class has attached properties that drive presentation of errors: HasError, Errors, ErrorTemplate. But you can't just set Validation.HasError to true (there is no accessible setter) like you can set Validation.ErrorTemplate. To set Validation.HasError in code-behind, you can use Validation.MarkInvalid method, but this is not how these things are usually done. Here is a quick example, for this to work you need to set Name property on your TextBox to MyTextBox:

private void Submit_Click(object sender, RoutedEventArgs e)
{
    if (!string.IsNullOrEmpty(MyTextBox.Text)) return;

    BindingExpression bindingExpression =
        BindingOperations.GetBindingExpression(MyTextBox, TextBox.TextProperty);

    BindingExpressionBase bindingExpressionBase =
        BindingOperations.GetBindingExpressionBase(MyTextBox, TextBox.TextProperty);

    ValidationError validationError =
        new ValidationError(new ExceptionValidationRule(), bindingExpression);

    validationError.ErrorContent = "My error message.";

    Validation.MarkInvalid(bindingExpressionBase, validationError);
}

So if MyTextBox.Text is empty, it will be considered invalid.


问:
Get the number of lines of code in a R script
I would like to know if there is a way to count the number of lines in a R script.

Ignoring lines of comment.

I didn't find a solution on the Internet. But maybe I missed something.

答:
You could try this :</p>

```<code>library(magrittr)
library(stringr)
library(readr)

number_of_lines_of_code <- function(file_path){
 file <- readr::read_file(file_path)
 file_lines <- file %>% stringr::str_split("\n")
 first_character_of_lines <- file_lines %>%
  lapply(function(line)stringr::str_replace_all(line," ",""))  %>%
  lapply(function(line)stringr::str_sub(line,1,1)) %>%
  unlist
 sum(first_character_of_lines != "#" & first_character_of_lines != "\r")
}

number_of_lines_of_code("your/file/path.R")
</code>```

Body:
You could try this :

library(magrittr)
library(stringr)
library(readr)

number_of_lines_of_code <- function(file_path){
 file <- readr::read_file(file_path)
 file_lines <- file %>% stringr::str_split("\n")
 first_character_of_lines <- file_lines %>%
  lapply(function(line)stringr::str_replace_all(line," ",""))  %>%
  lapply(function(line)stringr::str_sub(line,1,1)) %>%
  unlist
 sum(first_character_of_lines != "#" & first_character_of_lines != "\r")
}

number_of_lines_of_code("your/file/path.R")


问:
How to filter out the elements of the List so that the List only contains elements of distinct A.getId()?
I have a List that contains some objects A with the attribute id. What I need is the list to contain only one object for an id.

```<code>public List<A> findAllA() {
    List<A> aList; // fetches the elements from db

    HashMap<Long, A> aMap = new HashMap<>();
    for (A a: aList) {
        aMap.put(a.getId(), a);
    }

    return new ArrayList<>(aMap.values());
}
</code>```

So I put my list elements in a HashMap, because a HashMap holds distinct keys. Then a new ArrayList with the values of the map is returned. This does work fine, but is there a more efficient way to achieve the result? Or at least a shorter one?

答:
If you are looking for less characters/lines of codes, you can use Streams:

```<code>return aList.stream().distinct().collect(Collectors.toList());
</code>```

This is assuming your A class overrides equals and two instances of A are equals if and only if they have the same ID.

Of course, if that's the case, you can also use a HashSet to eliminate the duplicates:

```<code>return new ArrayList<A>(new HashSet<A>(alist));
</code>```

If your A class doesn't override equals (or equals doesn't behave as mentioned above) using a HashMap as you did is an efficient linear time solution. You can't do better in terms of average running time.

Title: How to filter out the elements of the List<A> so that the List<A> only contains elements of distinct A.getId()?

Body:
I have a List that contains some objects A with the attribute id. What I need is the list to contain only one object for an id.

public List findAllA() {
    List aList; // fetches the elements from db

    HashMap<Long, A> aMap = new HashMap<>();
    for (A a: aList) {
        aMap.put(a.getId(), a);
    }

    return new ArrayList<>(aMap.values());
}

So I put my list elements in a HashMap, because a HashMap holds distinct keys. Then a new ArrayList with the values of the map is returned. This does work fine, but is there a more efficient way to achieve the result? Or at least a shorter one?

Body:
If you are looking for less characters/lines of codes, you can use Streams:

return aList.stream().distinct().collect(Collectors.toList());

This is assuming your A class overrides equals and two instances of A are equals if and only if they have the same ID.

Of course, if that's the case, you can also use a HashSet to eliminate the duplicates:

return new ArrayList<A>(new HashSet<A>(alist));

If your A class doesn't override equals (or equals doesn't behave as mentioned above) using a HashMap as you did is an efficient linear time solution. You can't do better in terms of average running time.


问:
Cron Job - why does my php script select not only one day (as I want it to work) which is 7 days forwads from right now but it selects
```<code>ID  | Client  |    Data    | Hosting   | Price |
    |         |            |           |       |
    |         | 2017-11-23 | Heineken  | 500   |
    |         | 2017-11-22 | Hestia    | 200   |
    |         | 2017-11-21 | Bravo     | 200   |
    |         | 0000-00-00 |           |       |
    |         | 0000-00-00 |           |       |
</code>```

Why when I want the PHP code to select only the record with date 23-11-2017 which is 7 days from right now (16-11-2017) my scirpt somehow selects EACH SINGLE DAY from now (16-11-2017) up to 23-22-2017, namely 2017-11-22 and 2017-11-21...(above is my MySql table from which I select mentioned records)

This is my cronejob.php code:

```<code><?php

    use PHPMailer\PHPMailer\PHPMailer;
    include_once "PHPMailer/PHPMailer.php";
    include_once "PHPMailer/Exception.php";

    $mysqli = new mysqli('localhost', 'stdeja_genek', 'haslo', 'stdeja_genek');

    $tbl_2 = $mysqli->query( "SELECT * FROM klienci WHERE date(Data) BETWEEN CURTIME() AND DATE_ADD(CURTIME(), INTERVAL 7 DAY);");

    if($tbl_2->num_rows == 1) {
        $mail = new PHPMailer();
        foreach($tbl_2 as $email => $details) {
            $fullname = $details['Klient'] . ' ' . $details['Data'];

            $mail->addAddress('piterdeja@gmail.com');
            $mail->setFrom('system_przypomnien_hosting@powiadomienia.pl');
            $mail->Subject = "Hosting - system przypomnień";
            $mail->isHTML(true);
            $mail->Body = "W dniu {$details['Data']} kończy się hosting klientowi {$details['Klient']} na KWOTĘ {$details['Cena']}, hosting to {$details['Hosting']}";

            if ($mail->send())
                echo "Formularz został wysłany. Postaramy się odpowiedzieć jak najszybciej.";
            else
                echo 'Mailer Error: ' . $mail->ErrorInfo;
        }
    }
?>
</code>```

答: Wait... you want it to select one day 7 days from now, but you’re using BETWEEN. Why not just use =?

Body:
ID  | Client  |    Data    | Hosting   | Price |
    |         |            |           |       |
    |         | 2017-11-23 | Heineken  | 500   |
    |         | 2017-11-22 | Hestia    | 200   |
    |         | 2017-11-21 | Bravo     | 200   |
    |         | 0000-00-00 |           |       |
    |         | 0000-00-00 |           |       |

Why when I want the PHP code to select only the record with date 23-11-2017 which is 7 days from right now (16-11-2017) my scirpt somehow selects EACH SINGLE DAY from now (16-11-2017) up to 23-22-2017, namely 2017-11-22 and 2017-11-21...(above is my MySql table from which I select mentioned records)

This is my cronejob.php code:

<?php

    use PHPMailer\PHPMailer\PHPMailer;
    include_once "PHPMailer/PHPMailer.php";
    include_once "PHPMailer/Exception.php";

    $mysqli = new mysqli('localhost', 'stdeja_genek', 'haslo', 'stdeja_genek');

    $tbl_2 = $mysqli->query( "SELECT * FROM klienci WHERE date(Data) BETWEEN CURTIME() AND DATE_ADD(CURTIME(), INTERVAL 7 DAY);");

    if($tbl_2->num_rows == 1) {
        $mail = new PHPMailer();
        foreach($tbl_2 as $email => $details) {
            $fullname = $details['Klient'] . ' ' . $details['Data'];

            $mail->addAddress('piterdeja@gmail.com');
            $mail->setFrom('system_przypomnien_hosting@powiadomienia.pl');
            $mail->Subject = "Hosting - system przypomnień";
            $mail->isHTML(true);
            $mail->Body = "W dniu {$details['Data']} kończy się hosting klientowi {$details['Klient']} na KWOTĘ {$details['Cena']}, hosting to {$details['Hosting']}";

            if ($mail->send())
                echo "Formularz został wysłany. Postaramy się odpowiedzieć jak najszybciej.";
            else
                echo 'Mailer Error: ' . $mail->ErrorInfo;
        }
    }
?>


问:
ERROR: ' No module named 'django.core.urlresolvers'
I am trying to create web services using the Django REST Framework. While running the server, when I try to access the admin page, I get the following error:

```<code>Invalid template library specified.
ImportError raised when trying to load
'rest_framework.templatetags.rest_framework': No module named 'django.core.urlresolvers'
</code>```

Note: I have added the rest_framework in the settings.

答:
Since Django 1.10 the module django.core.urlresolvers is deprecated. See the official documentation.

In order to resolve the issue you have to use compatible third-party packages. You didn't mention which version of Django REST Framework you're using, but I'd assume it's not DRF 3.x.x

Check the installed version of Django REST Framework and update it to the 3.7.x series (Stand: 2017-11-17).

Body:
I am trying to create web services using the Django REST Framework. While running the server, when I try to access the admin page, I get the following error:

Invalid template library specified.
ImportError raised when trying to load
'rest_framework.templatetags.rest_framework': No module named 'django.core.urlresolvers'

Note: I have added the rest_framework in the settings.


答:
Using Java 8 stream :</p>

```<code>List<A> aList; // fetches the elements from db

Collection<A> original= aList.stream()
   .<Map<Integer, A>> collect(HashMap::new,(m,e)->m.put(e.getId(), e), Map::putAll).values();
</code>```

Body:
Using Java 8 stream :

List<A> aList; // fetches the elements from db

Collection<A> original= aList.stream()
   .<Map<Integer, A>> collect(HashMap::new,(m,e)->m.put(e.getId(), e), Map::putAll).values();


问:
How to do Typing Replay in JavaScript?
I am wondering how typeracer is doing this kinda words reply with also mistakes made while typing I am confused and I have no Idea how to do this in JavaScript

答:
Take a look at typed.js and pass your saved strings to it.

Link:

http://www.mattboldt.com/demos/typed-js/

Title: How to do Typing Replay in JavaScript?


问:
^a-zA-Z0-9 excluding spaces?
I am trying to find everything in a paragraph that is not abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 and not space / /gi

```<code>/[^a-zA-Z0-9]|[^ ]/gi
</code>```

the above doesn't work!

答:
You can use this for
 am trying to find everything in a paragraph that is not abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 and not space / /gi</p>

```<code>replaceAll("[^A-Za-z0-9\\s]", "")
</code>```

Title: ^a-zA-Z0-9 excluding spaces?

Body:
I am trying to find everything in a paragraph that is not abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 and not space / /gi

/[^a-zA-Z0-9]|[^ ]/gi

the above doesn't work!

Body:
You can use this for
 am trying to find everything in a paragraph that is not abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 and not space / /gi

replaceAll("[^A-Za-z0-9\\s]", "")

ContentLicense: CC BY-SA 4.0


问:
Confused behavior with async pipe (Angular)
I will try use async pipe for show/hide some waiting message.

app.component.html

```<code><ng-template #isWait>
    <h1>Please wait</h1>
</ng-template>

<div *ngIf="wait | async; else isWait">
    <hello name="{{ name }}"></hello>

    <p>
        Start editing to see some magic happen :)
    </p>

</div>

<button (click)="toggle()">Toggle</button>

<!-- Doesn't change -->
<div style="margin:1rem;">
    Doesn't change here
    <span style="color:red;">Value is {{wait | async}}</span>
  (AppComponent)
</div>
</code>```

app.component.ts

```<code>@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name: string = 'Angular 5';
  wait: Observable<boolean>;

  constructor(public waitService: WaitService) {
    this.wait = this.waitService.wait;
  }

  toggle() {
    this.waitService.toggle();
  }
}
</code>```

wait.service.ts

```<code>export class WaitService {
  wait: Observable<boolean>;
  private _wait: boolean = false;
  private _onChange: EventEmitter<boolean> = new EventEmitter();

  constructor() {
    this.wait = Observable.create((obs: any) => {
      obs.next(this._wait);
      this._onChange.subscribe((w: boolean) => {
        if (this._wait !== w) {
          this._wait = w;
          obs.next(this._wait);
        }
      });
    });
  }

  toggle() {
    this._onChange.emit(!this._wait);
  }
}
</code>```

I have WaitService with wait property and method toggle for switching wait.
When I try toggle wait, it works in one case, but doesn't work for each others (as I expected).

So, It confused me.
I will try figure out, why it happens.

Example: https://stackblitz.com/edit/angular-fwghfj

If you click on Toggle button nothing happen with wait message, but subscription in Wait2Component will be emitted and and will be write to console output each time when you clicked on toggle.

But after commented line with subscription, show and hide wait message will be work ok, but in other places wait still have no change.

Sure I can change wait to boolean and don't care about this situation with async, but this unexpected behavior for me.

答:
app.component.ts

```<code>@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name: string = 'Angular 5';
  wait: Observable<boolean>;

  constructor(public waitService: WaitService) {
    this.wait = this.waitService.waitingStatus();
  }

  toggle() {
    this.waitService.toggle();
  }
}
</code>```

Your service

```<code>@Injectable()
export class WaitService {
  private currentWaitingStatus: boolean = false;
  private waitingStatus$: Subject<boolean> = new BehaviorSubject<boolean>(this.currentWaitingStatus)

  waitingStatus(): Observable<boolean> {
     return this.waitingStatus$
  }

  toggle() {
     this.currentWaitingStatus= !this.currentWaitingStatus
     this.waitingStatus$.next(this.currentWaitingStatus)
  }
}
</code>```

I prefer to have a method which return my property than to put it public.

Because, your component must not know how is the inside of your service. If your service is use by n clients, tomorrow you want to change the name of your property you must change it everywhere

Otherwise, if you abstract this behind a method you change juste at one place in your service

Body:
I will try use async pipe for show/hide some waiting message.

app.component.html

<ng-template #isWait>

Please wait

</ng-template>

    <hello name="{{ name }}"></hello>

        Start editing to see some magic happen :)

<button (click)="toggle()">Toggle</button>

    Doesn't change here
    Value is {{wait | async}}
  (AppComponent)

app.component.ts

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name: string = 'Angular 5';
  wait: Observable<boolean>;

  constructor(public waitService: WaitService) {
    this.wait = this.waitService.wait;
  }

  toggle() {
    this.waitService.toggle();
  }
}

wait.service.ts

export class WaitService {
  wait: Observable<boolean>;
  private _wait: boolean = false;
  private _onChange: EventEmitter<boolean> = new EventEmitter();

  constructor() {
    this.wait = Observable.create((obs: any) => {
      obs.next(this._wait);
      this._onChange.subscribe((w: boolean) => {
        if (this._wait !== w) {
          this._wait = w;
          obs.next(this._wait);
        }
      });
    });
  }

  toggle() {
    this._onChange.emit(!this._wait);
  }
}

I have WaitService with wait property and method toggle for switching wait.
When I try toggle wait, it works in one case, but doesn't work for each others (as I expected).

So, It confused me.
I will try figure out, why it happens.

Example: https://stackblitz.com/edit/angular-fwghfj

If you click on Toggle button nothing happen with wait message, but subscription in Wait2Component will be emitted and and will be write to console output each time when you clicked on toggle.

But after commented line with subscription, show and hide wait message will be work ok, but in other places wait still have no change.

Sure I can change wait to boolean and don't care about this situation with async, but this unexpected behavior for me.

Body:
app.component.ts

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name: string = 'Angular 5';
  wait: Observable<boolean>;

  constructor(public waitService: WaitService) {
    this.wait = this.waitService.waitingStatus();
  }

  toggle() {
    this.waitService.toggle();
  }
}

Your service

@Injectable()
export class WaitService {
  private currentWaitingStatus: boolean = false;
  private waitingStatus$: Subject<boolean> = new BehaviorSubject<boolean>(this.currentWaitingStatus)

  waitingStatus(): Observable<boolean> {
     return this.waitingStatus$
  }

  toggle() {
     this.currentWaitingStatus= !this.currentWaitingStatus
     this.waitingStatus$.next(this.currentWaitingStatus)
  }
}

I prefer to have a method which return my property than to put it public.

Because, your component must not know how is the inside of your service. If your service is use by n clients, tomorrow you want to change the name of your property you must change it everywhere

Otherwise, if you abstract this behind a method you change juste at one place in your service


问:
Scala dynamic String interpolation - Read from properties file
I tried to get the log message from message.properties and did string interpolation with that log message.In this time,The log message is not interpolated with original message.

I am not able to get string interpolated result and am getting the output as log message what i have specified in properties file

Here I dont want to hard code any log message in scala file,Instead of this,I want to get all message from properties file and redirected into application log after interpolating string value.

```<code>import com.typesafe.config.ConfigFactory
import grizzled.slf4j.Logging
object Test extends Logging {
  def main(args: Array[String]){
    val subjectArea="Member"
    val  messageProp = ConfigFactory.load("message.properties")
    val log=messageProp.getString("log.subject.area")
    debug(s"$log")
  }
}

message.properties
log.subject.area=The Subject Area : $subjectArea
</code>```

Console Output: The Subject Area : $subjectArea
i want this output : The Subject Area : Member

Thanks in advance!!!
Test.scala
message.propeties

答:
String interpolation only works with constants. To do what you want dynamically, you need to write some explicit processing yoruself (or use a template engine library). Something like this, perhaps?</p>

```<code> val substPattern = """\$\{(.+?)\}""".r
 import java.util.regex.Matcher.{ quoteReplacement => qq }
 def processSubstitutions(
   input: String,
   vars: Map[String, String]
 ) = substPattern.replaceAllIn(
     input, { m =>
       val ref = m.group(1)
       qq(vars.getOrElse(ref, ref)
     }
 )

 val vars = Map("subjectArea" -> "Member")
 val  messageProp = ConfigFactory.load("message.properties")
 val log=processSubstitutions(
    messageProp.getString("log.subject.area"),
    vars
 )
</code>```

Body:
I tried to get the log message from message.properties and did string interpolation with that log message.In this time,The log message is not interpolated with original message.

I am not able to get string interpolated result and am getting the output as log message what i have specified in properties file

Here I dont want to hard code any log message in scala file,Instead of this,I want to get all message from properties file and redirected into application log after interpolating string value.

import com.typesafe.config.ConfigFactory
import grizzled.slf4j.Logging
object Test extends Logging {
  def main(args: Array[String]){
    val subjectArea="Member"
    val  messageProp = ConfigFactory.load("message.properties")
    val log=messageProp.getString("log.subject.area")
    debug(s"$log")
  }
}

message.properties
log.subject.area=The Subject Area : $subjectArea

Console Output: The Subject Area : $subjectArea
i want this output : The Subject Area : Member

Thanks in advance!!!
Test.scala
message.propeties

Body:
String interpolation only works with constants. To do what you want dynamically, you need to write some explicit processing yoruself (or use a template engine library). Something like this, perhaps?

 val substPattern = """\$\{(.+?)\}""".r
 import java.util.regex.Matcher.{ quoteReplacement => qq }
 def processSubstitutions(
   input: String,
   vars: Map[String, String]
 ) = substPattern.replaceAllIn(
     input, { m =>
       val ref = m.group(1)
       qq(vars.getOrElse(ref, ref)
     }
 )

 val vars = Map("subjectArea" -> "Member")
 val  messageProp = ConfigFactory.load("message.properties")
 val log=processSubstitutions(
    messageProp.getString("log.subject.area"),
    vars
 )


答:
If the equals()/hashCode() methods rely on the id , you could simply create a Set from the List :

```<code>Set<A> set = new HashSet<>(aList);
</code>```

Set removes duplicate elements equals in terms of equals().

If the Set type doesn't suit, you may still transform it into a List :

```<code>List<A> newList = new ArrayList<A>(new HashSet<A>(alist));
</code>```

Body:
If the equals()/hashCode() methods rely on the id , you could simply create a Set from the List :

Set<A> set = new HashSet<>(aList);

Set removes duplicate elements equals in terms of equals().

If the Set type doesn't suit, you may still transform it into a List :

List<A> newList = new ArrayList<A>(new HashSet<A>(alist));


问:
Alpha isn't changing UINavigationBar's barTintColor
I want to set the color of UINavigationBar to black with alpha 0.6 to see my interface. But if i use this code:

```<code>self.navigationController?.navigationBar.barTintColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.6)
self.navigationController?.navigationBar.translucent = true
</code>```

It still looks like with alpha 1.0:

How can I have it transparent with black transparent color?

Thanks

答:
You would have to get the image from Color as there is some problem with lower iOS version.Use this method to convert your UIColor to a background Image.

Xmarin.iOS

```<code>private static UIImage GetImageFromColor(UIColor color, CGSize size)
            {
                var rect = new CGRect(0, 0, size.Width, size.Height);
                UIGraphics.BeginImageContextWithOptions(size, false, 0);
                color.SetFill();
                UIGraphics.RectFill(rect);
                var image = UIGraphics.GetImageFromCurrentImageContext();
                UIGraphics.EndImageContext();
                return image;
            }
</code>```

call this method

var bgImage = GetImageFromColor(UIColor.FromRGBA(r, g, b, alpha), new CGSize(viewWidth, viewHeight));

Body:
I want to set the color of UINavigationBar to black with alpha 0.6 to see my interface. But if i use this code:

self.navigationController?.navigationBar.barTintColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.6)
self.navigationController?.navigationBar.translucent = true

It still looks like with alpha 1.0:

How can I have it transparent with black transparent color?

Thanks

Body:
You would have to get the image from Color as there is some problem with lower iOS version.Use this method to convert your UIColor to a background Image.

Xmarin.iOS

private static UIImage GetImageFromColor(UIColor color, CGSize size)
            {
                var rect = new CGRect(0, 0, size.Width, size.Height);
                UIGraphics.BeginImageContextWithOptions(size, false, 0);
                color.SetFill();
                UIGraphics.RectFill(rect);
                var image = UIGraphics.GetImageFromCurrentImageContext();
                UIGraphics.EndImageContext();
                return image;
            }

call this method

var bgImage = GetImageFromColor(UIColor.FromRGBA(r, g, b, alpha), new CGSize(viewWidth, viewHeight));


问:
DES encoding with security key C#
I know It's a probably common question but I cannot find answer anywhere. So I have byte array key and byte array value and I need to produce new 8 byte array that has been encrypted with DES in C#</p>

答:
This is what I was looking for :D:D...thank you :D</p>

```<code>   private static byte[] Encrypt(byte[] value, byte[] key)
    {
        DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider
                                                      {
                                                          Mode = CipherMode.ECB,
                                                          Padding = PaddingMode.None
                                                      };

        MemoryStream memoryStream = new MemoryStream();

        CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(key, key), CryptoStreamMode.Write);

        cryptoStream.Write(value, 0, value.Length);
        cryptoStream.Close();

        return memoryStream.ToArray();
    }
</code>```

Title: DES encoding with security key C#

Body:
This is what I was looking for :D:D...thank you :D

   private static byte[] Encrypt(byte[] value, byte[] key)
    {
        DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider
                                                      {
                                                          Mode = CipherMode.ECB,
                                                          Padding = PaddingMode.None
                                                      };

        MemoryStream memoryStream = new MemoryStream();

        CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(key, key), CryptoStreamMode.Write);

        cryptoStream.Write(value, 0, value.Length);
        cryptoStream.Close();

        return memoryStream.ToArray();
    }


问:
Custom Elements data attributes not working
I am trying to make a custom html element and pass along with its instantiation some custom data tags.  The problem is its dataset is always empty, and I can't figure out what I am doing wrong.  I'm following the example from MDN on custom elements.. and this example does work in my browsers.. Additionally, I can successfully pass custom data tags when I add a standard img on my page, but not when I use my custom html element.

Below are my js file (defined in MyImage.js) and my html file.  Along side these is an image called small.jpg.

class MyImage extends HTMLElement {
  constructor() {
    // Always call super first in constructor
    super();

    // Create a dom shadow root
    var domShadow = this.attachShadow({mode: 'open'});

    // Create a standard img element and set its attributes.
    var img = document.createElement('img');
    img.alt = this.dataset.name;
    img.src = this.dataset.img;

    // Add the image to the shadow root.
    domShadow.appendChild(img);
  }
}

// Define the new element
customElements.define('my-image', MyImage);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
    <head>
        <title>myimage</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="MyImage.js"></script>
    </head>
    <body>
        <my-image data-name="My special image name" data-img="small.jpg"></my-image>

    </body>
</html></code>```

答:
Update your code to get properties as below from DOM instantiation    </p>

```<code>img.alt = this.getAttribute('data-name');
img.src = this.getAttribute('data-img');
</code>```

Body:
I am trying to make a custom html element and pass along with its instantiation some custom data tags.  The problem is its dataset is always empty, and I can't figure out what I am doing wrong.  I'm following the example from MDN on custom elements.. and this example does work in my browsers.. Additionally, I can successfully pass custom data tags when I add a standard img on my page, but not when I use my custom html element.

Below are my js file (defined in MyImage.js) and my html file.  Along side these is an image called small.jpg.

class MyImage extends HTMLElement {
  constructor() {
    // Always call super first in constructor
    super();

    // Create a dom shadow root
    var domShadow = this.attachShadow({mode: 'open'});

    // Create a standard img element and set its attributes.
    var img = document.createElement('img');
    img.alt = this.dataset.name;
    img.src = this.dataset.img;

    // Add the image to the shadow root.
    domShadow.appendChild(img);
  }
}

// Define the new element
customElements.define('my-image', MyImage);

        <title>myimage</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <my-image data-name="My special image name" data-img="small.jpg"></my-image>

Body:
Update your code to get properties as below from DOM instantiation

img.alt = this.getAttribute('data-name');
img.src = this.getAttribute('data-img');


问:
Need parser in Java from XML(SOAP) to JSON
i'm looking for a parser or SOAP client in Java to convert XML(WSDL) from Magento SOAP v1 API to JSON Object.

Magento SOAP v1 API returns a XML which looks like this:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="urn:Magento"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                   xmlns:ns2="http://xml.apache.org/xml-soap" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
                   SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
    <ns1:callResponse>
        <callReturn xsi:type="ns2:Map">
            <item>
                <key xsi:type="xsd:string">store_id</key>
                <value xsi:type="xsd:string">1</value>
            </item>
            <item>
                <key xsi:type="xsd:string">created_at</key>
                <value xsi:type="xsd:string">2013-03-05 05:56:35</value>
            </item>
            <item>
                <key xsi:type="xsd:string">updated_at</key>
                <value xsi:type="xsd:string">2017-11-09 15:37:05</value>
            </item>
            <item>
                    <key xsi:type="xsd:string">shipping_address</key>
                    <value xsi:type="ns2:Map">
                        <item>
                            <key xsi:type="xsd:string">address_id</key>
                            <value xsi:type="xsd:string">1</value>
                        </item>
                        <item>
                            <key xsi:type="xsd:string">created_at</key>
                            <value xsi:type="xsd:string">2013-01-31 11:37:38</value>
                        </item>
                        <item>
                            <key xsi:type="xsd:string">updated_at</key>
                            <value xsi:type="xsd:string">2017-11-09 15:37:05</value>
                        </item>
                    </value>
           </item>
        </callReturn>
    </ns1:callResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>```
</div>
</div>
</p>

<p>and i would like to received a simple JSON Object like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>{
  "store_id": "1",
  "created_at": "2013-03-05 05:56:35",
  "updated_at": "2017-11-09 15:37:05",
  "shipping_address": {
    "address_id": "1",
    "created_at": "2013-01-31 11:37:38",
    "updated_at": "2017-11-09 15:37:05"
  }
}</code>```

答:
If you are using Java 8 or later, you should check out my open source library: unXml. unXml basically maps from Xpaths to Json-attributes.

It's available on Maven Central.

Example

```<code>import com.fasterxml.jackson.databind.node.ObjectNode;
import com.nerdforge.unxml.factory.ParsingFactory;
import com.nerdforge.unxml.parsers.Parser;
import org.w3c.dom.Document;

public class Parser {
  public ObjectNode parseXml(String xml){
    Parsing parsing = ParsingFactory.getInstance().create();
    Document document = parsing.xml().document(xml);

    Parser<ObjectNode> parser = parsing.obj()
      .attribute("store_id", "//item[key/text() = 'store_id']/value")
      .attribute("created_at", "//item[key/text() = 'created_at']/value")
      .attribute("updated_at", "//item[key/text() = 'updated_at']/value")
      .attribute("shipping_address", parsing.obj("//item[key/text() = 'shipping_address']")
          .attribute("address_id", "value/item[key/text() = 'address_id']/value")
          .attribute("created_at", "value/item[key/text() = 'created_at']/value")
          .attribute("updated_at", "value/item[key/text() = 'updated_at']/value")
      )
      .build();

    ObjectNode result = parser.apply(document);
    return result;
  }
}
</code>```

It will return a Jackson ObjectNode, with the following json:

```<code>{
  "created_at": "2013-03-05 05:56:35",
  "shipping_address": {
    "created_at": "2013-01-31 11:37:38",
    "address_id": "1",
    "updated_at": "2017-11-09 15:37:05"
  },
  "store_id": "1",
  "updated_at": "2017-11-09 15:37:05"
}
</code>```

Body:
i'm looking for a parser or SOAP client in Java to convert XML(WSDL) from Magento SOAP v1 API to JSON Object.

Magento SOAP v1 API returns a XML which looks like this:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="urn:Magento"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                   xmlns:ns2="http://xml.apache.org/xml-soap" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
                   SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
    <ns1:callResponse>
        <callReturn xsi:type="ns2:Map">
            <item>
                <key xsi:type="xsd:string">store_id</key>
                <value xsi:type="xsd:string">1</value>
            </item>
            <item>
                <key xsi:type="xsd:string">created_at</key>
                <value xsi:type="xsd:string">2013-03-05 05:56:35</value>
            </item>
            <item>
                <key xsi:type="xsd:string">updated_at</key>
                <value xsi:type="xsd:string">2017-11-09 15:37:05</value>
            </item>
            <item>
                    <key xsi:type="xsd:string">shipping_address</key>
                    <value xsi:type="ns2:Map">
                        <item>
                            <key xsi:type="xsd:string">address_id</key>
                            <value xsi:type="xsd:string">1</value>
                        </item>
                        <item>
                            <key xsi:type="xsd:string">created_at</key>
                            <value xsi:type="xsd:string">2013-01-31 11:37:38</value>
                        </item>
                        <item>
                            <key xsi:type="xsd:string">updated_at</key>
                            <value xsi:type="xsd:string">2017-11-09 15:37:05</value>
                        </item>
                    </value>
           </item>
        </callReturn>
    </ns1:callResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

and i would like to received a simple JSON Object like this:

{
  "store_id": "1",
  "created_at": "2013-03-05 05:56:35",
  "updated_at": "2017-11-09 15:37:05",
  "shipping_address": {
    "address_id": "1",
    "created_at": "2013-01-31 11:37:38",
    "updated_at": "2017-11-09 15:37:05"
  }
}

Body:
If you are using Java 8 or later, you should check out my open source library: unXml. unXml basically maps from Xpaths to Json-attributes.

It's available on Maven Central.

Example

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.nerdforge.unxml.factory.ParsingFactory;
import com.nerdforge.unxml.parsers.Parser;
import org.w3c.dom.Document;

public class Parser {
  public ObjectNode parseXml(String xml){
    Parsing parsing = ParsingFactory.getInstance().create();
    Document document = parsing.xml().document(xml);

    Parser<ObjectNode> parser = parsing.obj()
      .attribute("store_id", "//item[key/text() = 'store_id']/value")
      .attribute("created_at", "//item[key/text() = 'created_at']/value")
      .attribute("updated_at", "//item[key/text() = 'updated_at']/value")
      .attribute("shipping_address", parsing.obj("//item[key/text() = 'shipping_address']")
          .attribute("address_id", "value/item[key/text() = 'address_id']/value")
          .attribute("created_at", "value/item[key/text() = 'created_at']/value")
          .attribute("updated_at", "value/item[key/text() = 'updated_at']/value")
      )
      .build();

    ObjectNode result = parser.apply(document);
    return result;
  }
}

It will return a Jackson ObjectNode, with the following json:

{
  "created_at": "2013-03-05 05:56:35",
  "shipping_address": {
    "created_at": "2013-01-31 11:37:38",
    "address_id": "1",
    "updated_at": "2017-11-09 15:37:05"
  },
  "store_id": "1",
  "updated_at": "2017-11-09 15:37:05"
}


问:
Which architecture should be used while developing iOS Application?
I am going to start a new application in iOS and there are multiple architectures available in iOS i.e Viper,MVVM,MVP and MVC.

I have search google but didn't find any specific use of these architectures.

Can anyone please guide me that when and which architecture should be used and which is more beneficial?

答:
I will try to put my answer in short:

MVC: This is the basic architecture you will find most of the people use. Without knowing this, don't go forward as it's wasting time doing so. But this architecture no one is interested in the current market as it has few drawbacks. When comes to unit testing people find it difficult. So they started moving on. One good thing about this architecture is your development is super fast.

VIPER: which became very popular these days for its separation of data, design, controller logic. For unit testing, it will be very nice. But understanding and putting efforts in this are more. If you fully understand this one, I advise you to go.

MVP: People who understand MVC, can easily go with this MVP. As there are not many changes involved in this from MVC. Presentation logic will be separated out. If you want to build good architecture, not the basic one go for this.

MVVM: It also requires good efforts from you. Don't go until you understood. Again very good separation of model, View, ViewModel.

Now it's your choice to get onboard. As all of us know, how important an architecture is for an app, don't take fast decisions here. Take your own time and conclude based on the time you have in your hands, the need for proper architecture.


问:
How to add hidden field in form element in masterpage
I want to add hidden field to every view i have through jquery or javascript. But i want that code to be in MasterPage.Master so i write code at one place and it adds on every view i have. Can i do this if yes then how? Im using asp.net mvc 2</p>

答:
Not sure about MVC but in the master page Page_PreRender method you can have such code:

```<code>HiddenField field = new HiddenField();
field.ID = "HiddenField1";
field.Value = "SomeValue";
(this.Page.FindControl("form1") as HtmlForm).Controls.Add(field);
</code>```

This will push the hidden field to the form regardless of what page is using the master page.

Body:
Not sure about MVC but in the master page Page_PreRender method you can have such code:

HiddenField field = new HiddenField();
field.ID = "HiddenField1";
field.Value = "SomeValue";
(this.Page.FindControl("form1") as HtmlForm).Controls.Add(field);

This will push the hidden field to the form regardless of what page is using the master page.


问:
Android Studio layout design view shows overlay after upgrade to v3.0
After upgrading to Android Studio v3.0 the design view for all my layouts look like below, i.e. ActionBarOverlayLayout covers the whole design surface, and the app does not even use the actionbar.

In the manifest the application element is:

```<code><application
    android:name=".MyAppName"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
</code>```

And AppTheme is defined in styles.xml like

```<code><style name="AppTheme" parent="Theme.AppCompat">
    <item name="android:colorBackground">?attr/colorPrimaryDark</item>
    <item name="android:textColor">@color/colorWhite</item>
    <item name="android:itemBackground">@color/colorControlActivated</item>

</style>
</code>```

答:
Change parent style of Apptheme

From:

```<code><style name="AppTheme" parent="Theme.AppCompat">
</code>```

To:

```<code><style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
</code>```

I hope it will help.

Body:
After upgrading to Android Studio v3.0 the design view for all my layouts look like below, i.e. ActionBarOverlayLayout covers the whole design surface, and the app does not even use the actionbar.

In the manifest the application element is:

<application
    android:name=".MyAppName"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

And AppTheme is defined in styles.xml like

Body:
Change parent style of Apptheme

From:

<style name="AppTheme" parent="Theme.AppCompat">

To:

<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">

I hope it will help.


答:
The difficulty here comes from the way the problem is specified with the r vector, and it would be possible to modify Milan's answer to better match the expected result.

```<code>r <- c(
  "A==A[i] & B==B[i]",
  "A==A[i] & C==C[i]",
  "B==B[i] & C==C[i]",
  "A==A[i] & B==B[i] & C==C[i]"
)
</code>```

Instead of that, I'll take another route, given that in each element of r, you only need to identify the names of the columns. For example, on the first case, you only need A and B.

```<code>library(purrr)
library(glue)
library(rlang)
names <- c("A", "B")
DF <- data.frame(
  A = c(11, 11, 2, 3),
  B = c(22, 22, 30, 30),
  C = c(88, 47, 21, 21)
)

map( names, ~{
  glue( "{name} == {values}", name = ., values = DF[[.]] )
})
#> [[1]]
#> A == 11
#> A == 11
#> A == 2
#> A == 3
#>
#> [[2]]
#> B == 22
#> B == 22
#> B == 30
#> B == 30
</code>```

you can then reduce it to only get one string per line of your data frame:

```<code>map( names, ~{
  glue( "{name} == {values}", name = ., values = DF[[.]] )
}) %>%
  reduce( paste, sep = " & ")
#> [1] "A == 11 & B == 22" "A == 11 & B == 22" "A == 2 & B == 30"
#> [4] "A == 3 & B == 30"
</code>```

Wrapping it all up into a function that uses tidy eval to get the names to begin with:

```<code>tests <- function(data, ...){
  names <- map_chr(quos(...), f_name)

  map( names, ~{
    glue( "{name} == {values}", name = ., values = data[[.]] )
  }) %>%
    reduce(paste, sep = " & " )

}
</code>```

So that you can get the results by calling tests 4 times:

```<code>c(
  tests( DF, A, B),
  tests( DF, A, C),
  tests( DF, B, C),
  tests( DF, A, B, C)
)
#>  [1] "A == 11 & B == 22"           "A == 11 & B == 22"
#>  [3] "A == 2 & B == 30"            "A == 3 & B == 30"
#>  [5] "A == 11 & C == 88"           "A == 11 & C == 47"
#>  [7] "A == 2 & C == 21"            "A == 3 & C == 21"
#>  [9] "B == 22 & C == 88"           "B == 22 & C == 47"
#> [11] "B == 30 & C == 21"           "B == 30 & C == 21"
#> [13] "A == 11 & B == 22 & C == 88" "A == 11 & B == 22 & C == 47"
#> [15] "A == 2 & B == 30 & C == 21"  "A == 3 & B == 30 & C == 21"
</code>```

Title: Loop within string in r to output expressions with vectorized values

Body:
Example data:

> DF
   A  B  C
1 11 22 88
2 11 22 47
3  2 30 21
4  3 30 21

> r
[1] "A==A[i] & B==B[i] "           "A==A[i] & C==C[i] "
[3] "B==B[i] & C==C[i] "           "A==A[i] & B==B[i] & C==C[i] "

Executed code:

> output=list()
> for (j in r){
+   for (i in 1:nrow(DF)){
+
+     output[[j]][i]=j
+   }
+ }
> output
$`A==A[i] & B==B[i] `
[1] "A==A[i] & B==B[i] " "A==A[i] & B==B[i] " "A==A[i] & B==B[i] "
[4] "A==A[i] & B==B[i] "

$`A==A[i] & C==C[i] `
[1] "A==A[i] & C==C[i] " "A==A[i] & C==C[i] " "A==A[i] & C==C[i] "
[4] "A==A[i] & C==C[i] "

$`B==B[i] & C==C[i] `
[1] "B==B[i] & C==C[i] " "B==B[i] & C==C[i] " "B==B[i] & C==C[i] "
[4] "B==B[i] & C==C[i] "

$`A==A[i] & B==B[i] & C==C[i] `
[1] "A==A[i] & B==B[i] & C==C[i] " "A==A[i] & B==B[i] & C==C[i] "
[3] "A==A[i] & B==B[i] & C==C[i] " "A==A[i] & B==B[i] & C==C[i] "

> output=purrr::flatten_chr(output)
> output
 [1] "A==A[i] & B==B[i] "           "A==A[i] & B==B[i] "
 [3] "A==A[i] & B==B[i] "           "A==A[i] & B==B[i] "
 [5] "A==A[i] & C==C[i] "           "A==A[i] & C==C[i] "
 [7] "A==A[i] & C==C[i] "           "A==A[i] & C==C[i] "
 [9] "B==B[i] & C==C[i] "           "B==B[i] & C==C[i] "
[11] "B==B[i] & C==C[i] "           "B==B[i] & C==C[i] "
[13] "A==A[i] & B==B[i] & C==C[i] " "A==A[i] & B==B[i] & C==C[i] "
[15] "A==A[i] & B==B[i] & C==C[i] " "A==A[i] & B==B[i] & C==C[i] "

My target was to get the same output with the specific values A[i], B[i] and C[i] from DF, i.e., the final output would be the following:

> output
[1] "A==11 & B==22 "            "A==11 & B==22 "
[3] "A==2 & B==30 "             "A==3 & B==30 "
[5] "A==11 & C==88 "            "A==11 & C==47 "
[7] "A==2 & C==21 "             "A==3 & C==21 "
[9] "B==22 & C==88 "            "B==22 & C==47 "
[11] "B==30 & C==21 "           "B==30 & C==21 "
[13] "A==11 & B==22 & C==88 "   "A==11 & B==22 & C==47 "
[15] "A==2 & B==30 & C==21 "    "A==3 & B==30 & C==21 "

I would be grateful if someone could help me with this matter.

Body:
The difficulty here comes from the way the problem is specified with the r vector, and it would be possible to modify Milan's answer to better match the expected result.

r <- c(
  "A==A[i] & B==B[i]",
  "A==A[i] & C==C[i]",
  "B==B[i] & C==C[i]",
  "A==A[i] & B==B[i] & C==C[i]"
)

Instead of that, I'll take another route, given that in each element of r, you only need to identify the names of the columns. For example, on the first case, you only need A and B.

library(purrr)
library(glue)
library(rlang)
names <- c("A", "B")
DF <- data.frame(
  A = c(11, 11, 2, 3),
  B = c(22, 22, 30, 30),
  C = c(88, 47, 21, 21)
)

map( names, ~{
  glue( "{name} == {values}", name = ., values = DF[[.]] )
})
#> [[1]]
#> A == 11
#> A == 11
#> A == 2
#> A == 3
#>
#> [[2]]
#> B == 22
#> B == 22
#> B == 30
#> B == 30

you can then reduce it to only get one string per line of your data frame:

map( names, ~{
  glue( "{name} == {values}", name = ., values = DF[[.]] )
}) %>%
  reduce( paste, sep = " & ")
#> [1] "A == 11 & B == 22" "A == 11 & B == 22" "A == 2 & B == 30"
#> [4] "A == 3 & B == 30"

Wrapping it all up into a function that uses tidy eval to get the names to begin with:

tests <- function(data, ...){
  names <- map_chr(quos(...), f_name)

  map( names, ~{
    glue( "{name} == {values}", name = ., values = data[[.]] )
  }) %>%
    reduce(paste, sep = " & " )

}

So that you can get the results by calling tests 4 times:

c(
  tests( DF, A, B),
  tests( DF, A, C),
  tests( DF, B, C),
  tests( DF, A, B, C)
)
#>  [1] "A == 11 & B == 22"           "A == 11 & B == 22"
#>  [3] "A == 2 & B == 30"            "A == 3 & B == 30"
#>  [5] "A == 11 & C == 88"           "A == 11 & C == 47"
#>  [7] "A == 2 & C == 21"            "A == 3 & C == 21"
#>  [9] "B == 22 & C == 88"           "B == 22 & C == 47"
#> [11] "B == 30 & C == 21"           "B == 30 & C == 21"
#> [13] "A == 11 & B == 22 & C == 88" "A == 11 & B == 22 & C == 47"
#> [15] "A == 2 & B == 30 & C == 21"  "A == 3 & B == 30 & C == 21"


问:
Multiple Pivots on Diff Columns in PySpark Frames
I have a py-spark dataframe , with 8 columns.

DataFrame has columns:

```<code>Columns  L ,  W , PN , PV , CP , CH , RP , RH
Row1     L1,  W1, PN1, PV1, CP1, CH1, RP1, RH1
Row2     L2,  W2, PN2, PV2, CP2, CH2, RP2, RH2
</code>```

Columns L, W form the key for the dataset.

I want to pivot the DataSet to the form:

```<code>Columns L ,  W , PN1 , PN2 , CP1 , CP2 , RP1 , RP2
Row1    L1,  W1, PV1 ,  -  , CH1 ,  -  , RH1 , -
Row2    L2,  W2,  -  , PV2 ,  -  , CH2 ,  -  , RH2
</code>```

Fundamentally I have to pivot 3 diff columns, with 3 different statistics( e.g.: Min, max, Mean).

What is the best possible way to pivot this dataset in pyspark?

Thanks,
P Ved

Body:
I have a py-spark dataframe , with 8 columns.

DataFrame has columns:

Columns  L ,  W , PN , PV , CP , CH , RP , RH
Row1     L1,  W1, PN1, PV1, CP1, CH1, RP1, RH1
Row2     L2,  W2, PN2, PV2, CP2, CH2, RP2, RH2

Columns L, W form the key for the dataset.

I want to pivot the DataSet to the form:

Columns L ,  W , PN1 , PN2 , CP1 , CP2 , RP1 , RP2
Row1    L1,  W1, PV1 ,  -  , CH1 ,  -  , RH1 , -
Row2    L2,  W2,  -  , PV2 ,  -  , CH2 ,  -  , RH2

Fundamentally I have to pivot 3 diff columns, with 3 different statistics( e.g.: Min, max, Mean).

What is the best possible way to pivot this dataset in pyspark?

Thanks,
P Ved

Body:
You can only pivot on one column at a time, but you can group by multiple columns and compute multiple aggregations:

Let's start with a sample dataframe:

import numpy as np
df = spark.createDataFrame([np.random.randint(0, 10, 8).tolist() for _ in range(10)], ["L", "W", "PN", "PV", "CP", "CH", "RP", "RH"])
df.show()

    +---+---+---+---+---+---+---+---+
    |  L|  W| PN| PV| CP| CH| RP| RH|
    +---+---+---+---+---+---+---+---+
    |  9|  2|  9|  7|  1|  5|  2|  7|
    |  4|  1|  1|  7|  5|  0|  2|  3|
    |  6|  2|  0|  3|  3|  6|  0|  0|
    |  9|  8|  9|  8|  8|  5|  5|  1|
    |  8|  2|  2|  3|  9|  1|  1|  7|
    |  2|  7|  7|  3|  8|  6|  1|  4|
    |  9|  7|  4|  8|  1|  7|  6|  1|
    |  8|  1|  9|  2|  2|  2|  9|  9|
    |  8|  9|  9|  0|  4|  4|  9|  7|
    |  4|  4|  2|  2|  0|  6|  1|  0|
    +---+---+---+---+---+---+---+---+

Let's group by column L, pivot on column W and compute min, max, mean for all the other columns:

import pyspark.sql.functions as psf
from itertools import chain
df.groupBy("L").pivot("W").agg(*list(chain(*[[psf.min(c), psf.max(c), psf.mean(c)] for c in df.columns if c not in ["L", "W"]]))).show()

    +---+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+
    |  L|1_min(PN)|1_max(PN)|1_avg(PN)|1_min(PV)|1_max(PV)|1_avg(PV)|1_min(CP)|1_max(CP)|1_avg(CP)|1_min(CH)|1_max(CH)|1_avg(CH)|1_min(RP)|1_max(RP)|1_avg(RP)|1_min(RH)|1_max(RH)|1_avg(RH)|2_min(PN)|2_max(PN)|2_avg(PN)|2_min(PV)|2_max(PV)|2_avg(PV)|2_min(CP)|2_max(CP)|2_avg(CP)|2_min(CH)|2_max(CH)|2_avg(CH)|2_min(RP)|2_max(RP)|2_avg(RP)|2_min(RH)|2_max(RH)|2_avg(RH)|4_min(PN)|4_max(PN)|4_avg(PN)|4_min(PV)|4_max(PV)|4_avg(PV)|4_min(CP)|4_max(CP)|4_avg(CP)|4_min(CH)|4_max(CH)|4_avg(CH)|4_min(RP)|4_max(RP)|4_avg(RP)|4_min(RH)|4_max(RH)|4_avg(RH)|7_min(PN)|7_max(PN)|7_avg(PN)|7_min(PV)|7_max(PV)|7_avg(PV)|7_min(CP)|7_max(CP)|7_avg(CP)|7_min(CH)|7_max(CH)|7_avg(CH)|7_min(RP)|7_max(RP)|7_avg(RP)|7_min(RH)|7_max(RH)|7_avg(RH)|8_min(PN)|8_max(PN)|8_avg(PN)|8_min(PV)|8_max(PV)|8_avg(PV)|8_min(CP)|8_max(CP)|8_avg(CP)|8_min(CH)|8_max(CH)|8_avg(CH)|8_min(RP)|8_max(RP)|8_avg(RP)|8_min(RH)|8_max(RH)|8_avg(RH)|9_min(PN)|9_max(PN)|9_avg(PN)|9_min(PV)|9_max(PV)|9_avg(PV)|9_min(CP)|9_max(CP)|9_avg(CP)|9_min(CH)|9_max(CH)|9_avg(CH)|9_min(RP)|9_max(RP)|9_avg(RP)|9_min(RH)|9_max(RH)|9_avg(RH)|
    +---+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+
    |  6|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|        0|        0|      0.0|        3|        3|      3.0|        3|        3|      3.0|        6|        6|      6.0|        0|        0|      0.0|        0|        0|      0.0|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|
    |  9|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|        9|        9|      9.0|        7|        7|      7.0|        1|        1|      1.0|        5|        5|      5.0|        2|        2|      2.0|        7|        7|      7.0|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|        4|        4|      4.0|        8|        8|      8.0|        1|        1|      1.0|        7|        7|      7.0|        6|        6|      6.0|        1|        1|      1.0|        9|        9|      9.0|        8|        8|      8.0|        8|        8|      8.0|        5|        5|      5.0|        5|        5|      5.0|        1|        1|      1.0|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|
    |  8|        9|        9|      9.0|        2|        2|      2.0|        2|        2|      2.0|        2|        2|      2.0|        9|        9|      9.0|        9|        9|      9.0|        2|        2|      2.0|        3|        3|      3.0|        9|        9|      9.0|        1|        1|      1.0|        1|        1|      1.0|        7|        7|      7.0|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|        9|        9|      9.0|        0|        0|      0.0|        4|        4|      4.0|        4|        4|      4.0|        9|        9|      9.0|        7|        7|      7.0|
    |  2|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|        7|        7|      7.0|        3|        3|      3.0|        8|        8|      8.0|        6|        6|      6.0|        1|        1|      1.0|        4|        4|      4.0|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|
    |  4|        1|        1|      1.0|        7|        7|      7.0|        5|        5|      5.0|        0|        0|      0.0|        2|        2|      2.0|        3|        3|      3.0|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|        2|        2|      2.0|        2|        2|      2.0|        0|        0|      0.0|        6|        6|      6.0|        1|        1|      1.0|        0|        0|      0.0|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|     null|
    +---+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+

If there are three aggregating columns you can put 2 of them in the groupBy:

df.groupBy("L", "W").pivot("PN").agg(psf.max("PV")).show()

    +---+---+----+----+----+----+----+----+
    |  L|  W|   0|   1|   2|   4|   7|   9|
    +---+---+----+----+----+----+----+----+
    |  8|  9|null|null|null|null|null|   0|
    |  8|  1|null|null|null|null|null|   2|
    |  4|  4|null|null|   2|null|null|null|
    |  9|  8|null|null|null|null|null|   8|
    |  2|  7|null|null|null|null|   3|null|
    |  4|  1|null|   7|null|null|null|null|
    |  8|  2|null|null|   3|null|null|null|
    |  6|  2|   3|null|null|null|null|null|
    |  9|  2|null|null|null|null|null|   7|
    |  9|  7|null|null|null|   8|null|null|
    +---+---+----+----+----+----+----+----+


问:
Words in a list with consecutively repeated letters
Right now I have a list of for example

```<code>data = ['dog','cat','a','aa','aac','bbb','bcca','ffffff']
</code>```

I want to remove the words with the repeated letters, in which I want to remove the words

```<code>'aa','aac','bbb','bcca','ffffff'
</code>```

Maybe import re?

答:
Here's a way to check if there are consecutive repeated characters:

```<code>def has_consecutive_repeated_letters(word):
    return any(c1 == c2 for c1, c2 in zip(word, word[1:]))
</code>```

You can then use a list comprehension to filter your list:

```<code>words = ['dog','cat','a','aa','aac','bbb','bcca','ffffff', 'abab', 'wow']
[word for word in words if not has_consecutive_repeated_letters(word)]
# ['dog', 'cat', 'a', 'abab', 'wow']
</code>```

Body:
Right now I have a list of for example

data = ['dog','cat','a','aa','aac','bbb','bcca','ffffff']

I want to remove the words with the repeated letters, in which I want to remove the words

'aa','aac','bbb','bcca','ffffff'

Maybe import re?

Body:
Here's a way to check if there are consecutive repeated characters:

def has_consecutive_repeated_letters(word):
    return any(c1 == c2 for c1, c2 in zip(word, word[1:]))

You can then use a list comprehension to filter your list:

words = ['dog','cat','a','aa','aac','bbb','bcca','ffffff', 'abab', 'wow']
[word for word in words if not has_consecutive_repeated_letters(word)]
# ['dog', 'cat', 'a', 'abab', 'wow']


问:
Git Status hangs using Cygwin
On my Windows machine, I have a repository that works nicely with msysgit. But when I try running git status on cygwin, it just hangs, without printing anything until I press Ctrl-C.

How can I investigate this to find out the reason for such behaviour?

答:
The reason for this was the difference in core.autocrlf setting. When install git for windows, I set it to automatically convert line endings in both directions, so the files in the filesystem were actually different from the files saved in git history - but windows git always hid these differences.

Meanwhile, cygwin git was working extremely slow because it detected differences in every line of thousands of text files in my repository.

Title: Git Status hangs using Cygwin