问:
border-bottom not working when dealing with background-color overlay
When clicking the Menu and it opens, the overlay background effect doesn't work for border-bottom under the h2 tag.

How do I tackle this issue?

How do I go about it?

function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
    document.getElementById("main").style.marginLeft = "250px";
    document.body.style.backgroundColor = "rgba(0,0,0,0.4)";
}

function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
    document.getElementById("main").style.marginLeft= "0";
    document.body.style.backgroundColor = "white";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>h2 {
 border-bottom: 1px solid #eee;
}
.sidenav {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: #111;
    overflow-x: hidden;
    transition: 0.5s;
    padding-top: 60px;
}

.sidenav a {
    padding: 8px 8px 8px 32px;
    text-decoration: none;
    font-size: 25px;
    color: #818181;
    display: block;
    transition: 0.3s;
}

.sidenav a:hover {
    color: #f1f1f1;
}

.sidenav .closebtn {
    position: absolute;
    top: 0;
    right: 25px;
    font-size: 36px;
    margin-left: 50px;
}

#main {
    transition: margin-left .5s;
    padding: 16px;
}

@media screen and (max-height: 450px) {
  .sidenav {padding-top: 15px;}
  .sidenav a {font-size: 18px;}
}</code>```

  ×
  About
  Services
  Clients
  Contact

  ×
  About
  Services
  Clients
  Contact

Sidenav Push Example

Click on the element below to open the side navigation menu, and push this content to the right. Notice that we add a black see-through background-color to body when the sidenav is opened.

  ☰ open

```

答:
Changing the background-color of document.body is not overlaying. It is just painting the background into another color. That is why the border-color of h2 is not affected at all.

To do an overlay, you must create a separate element that serves as an overlay.

function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
    document.getElementById("main").style.marginLeft = "250px";
    //document.body.style.backgroundColor = "rgba(0,0,0,0.4)";

    /* ADD THIS */
    document.getElementById('overlay').style.display = 'block';
}

function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
    document.getElementById("main").style.marginLeft= "0";
    //document.body.style.backgroundColor = "white";

    /* ADD THIS */
    document.getElementById('overlay').style.display = 'none';
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>h2 {
 border-bottom: 1px solid #eee;
}
.sidenav {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: #111;
    overflow-x: hidden;
    transition: 0.5s;
    padding-top: 60px;
}

.sidenav a {
    padding: 8px 8px 8px 32px;
    text-decoration: none;
    font-size: 25px;
    color: #818181;
    display: block;
    transition: 0.3s;
}

.sidenav a:hover {
    color: #f1f1f1;
}

.sidenav .closebtn {
    position: absolute;
    top: 0;
    right: 25px;
    font-size: 36px;
    margin-left: 50px;
}

#main {
    transition: margin-left .5s;
    padding: 16px;
    box-sizing: border-box;
}

/* ADD THIS */
#overlay {
  background-color: rgba(0, 0, 0, 0.4);
  position: absolute;
  top: 0;
  left: 0;
  display: none;
  height: 100%;
  width: 100%;
}

@media screen and (max-height: 450px) {
  .sidenav {padding-top: 15px;}
  .sidenav a {font-size: 18px;}
}</code>```

  ×
  About
  Services
  Clients
  Contact

Sidenav Push Example

Click on the element below to open the side navigation menu, and push this content to the right. Notice that we add a black see-through background-color to body when the sidenav is opened.

  ☰ open

```

You can adjust the width and height of the overlay yourself.

Body:
When clicking the Menu and it opens, the overlay background effect doesn't work for border-bottom under the h2 tag.

How do I tackle this issue?

How do I go about it?

function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
    document.getElementById("main").style.marginLeft = "250px";
    document.body.style.backgroundColor = "rgba(0,0,0,0.4)";
}

function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
    document.getElementById("main").style.marginLeft= "0";
    document.body.style.backgroundColor = "white";
}

h2 {
 border-bottom: 1px solid #eee;
}
.sidenav {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: #111;
    overflow-x: hidden;
    transition: 0.5s;
    padding-top: 60px;
}

.sidenav a {
    padding: 8px 8px 8px 32px;
    text-decoration: none;
    font-size: 25px;
    color: #818181;
    display: block;
    transition: 0.3s;
}

.sidenav a:hover {
    color: #f1f1f1;
}

.sidenav .closebtn {
    position: absolute;
    top: 0;
    right: 25px;
    font-size: 36px;
    margin-left: 50px;
}

#main {
    transition: margin-left .5s;
    padding: 16px;
}

@media screen and (max-height: 450px) {
  .sidenav {padding-top: 15px;}
  .sidenav a {font-size: 18px;}
}

  ×
  About
  Services
  Clients
  Contact

  ×
  About
  Services
  Clients
  Contact

Sidenav Push Example

Click on the element below to open the side navigation menu, and push this content to the right. Notice that we add a black see-through background-color to body when the sidenav is opened.

  ☰ open

Body:
Changing the background-color of document.body is not overlaying. It is just painting the background into another color. That is why the border-color of h2 is not affected at all.

To do an overlay, you must create a separate element that serves as an overlay.

function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
    document.getElementById("main").style.marginLeft = "250px";
    //document.body.style.backgroundColor = "rgba(0,0,0,0.4)";

    /* ADD THIS */
    document.getElementById('overlay').style.display = 'block';
}

function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
    document.getElementById("main").style.marginLeft= "0";
    //document.body.style.backgroundColor = "white";

    /* ADD THIS */
    document.getElementById('overlay').style.display = 'none';
}

h2 {
 border-bottom: 1px solid #eee;
}
.sidenav {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: #111;
    overflow-x: hidden;
    transition: 0.5s;
    padding-top: 60px;
}

.sidenav a {
    padding: 8px 8px 8px 32px;
    text-decoration: none;
    font-size: 25px;
    color: #818181;
    display: block;
    transition: 0.3s;
}

.sidenav a:hover {
    color: #f1f1f1;
}

.sidenav .closebtn {
    position: absolute;
    top: 0;
    right: 25px;
    font-size: 36px;
    margin-left: 50px;
}

#main {
    transition: margin-left .5s;
    padding: 16px;
    box-sizing: border-box;
}

/* ADD THIS */
#overlay {
  background-color: rgba(0, 0, 0, 0.4);
  position: absolute;
  top: 0;
  left: 0;
  display: none;
  height: 100%;
  width: 100%;
}

@media screen and (max-height: 450px) {
  .sidenav {padding-top: 15px;}
  .sidenav a {font-size: 18px;}
}

<div id="mySidenav" class="sidenav">
  <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
  <a href="#">About</a>
  <a href="#">Services</a>
  <a href="#">Clients</a>
  <a href="#">Contact</a>
</div>

<div id="main">

  <!-- ADD THIS -->
  <div id="overlay"></div>

  <h2>Sidenav Push Example</h2>
  <img src="https://i.stack.imgur.com/cpi0Y.jpg">
  <p>Click on the element below to open the side navigation menu, and push this content to the right. Notice that we add a black see-through background-color to body when the sidenav is opened.</p>
  <span style="font-size:30px;cursor:pointer" onclick="openNav()">&#9776; open</span>
</div>

You can adjust the width and height of the overlay yourself.


来源: stackexchange

问:
cannot remove searchController when switching between childViewControllers
I have a container viewController with two childViewControllers.  Both childViewControllers are tableViewControllers.  I want only one of the child viewControllers to be able to use a searchController.

I define and setup the searchController in the viewDidLoad of the parent containerViewController as such:

```<code>let searchController = UISearchController(searchResultsController: nil)
searchController.delegate = self.childOneTableViewController
searchController.searchResultsUpdater = self.childOneTableViewController
searchController.dimsBackgroundDuringPresentation = false
self.navigationItem.searchController = searchController
self.definesPresentationContext = true
</code>```

I am using a segmented control to switch between the two childViewControllers.

What I want to do is hide the searchBar for the second childViewController but so far I can only achieve that by setting the searchController to nil which is not something I want to do.

I have read many posts that highlight what to do when segueing but this is a slightly different scenario.

I thought the obvious thing was: searchController.isActive = false when adding the secondChildViewController:

```<code>@IBAction func segmentedControlValueChanged(_ sender: UISegmentedControl) {
        if segmentedControl.selectedSegmentIndex == 0 {
            remove(asChildViewController: childOneTableViewController)
            add(asChildViewController: childTwoTableViewController)
            navigationItem.searchController!.isActive = true
        } else {
            remove(asChildViewController: childOneTableViewController)
            add(asChildViewController: childTwoTableViewController)
            navigationItem.searchController!.isActive = false
        }
    }
</code>```

however this is having no effect and the searchController remains visible in both childViewControllers

答:
The search bar will remain visible on both child view controllers because you set it to be the navigation item of the parent controller. To hide the search bar for the second child controller you can do the following in your else statement: searchController.searchBar.hidden = true

Activating the search controller doesn't show or hide the search bar, it affects whether or not the search results view controller is presented. More on that here.

ContentLicense: CC BY-SA 3.0

Body:
I have a container viewController with two childViewControllers.  Both childViewControllers are tableViewControllers.  I want only one of the child viewControllers to be able to use a searchController.

I define and setup the searchController in the viewDidLoad of the parent containerViewController as such:

let searchController = UISearchController(searchResultsController: nil)
searchController.delegate = self.childOneTableViewController
searchController.searchResultsUpdater = self.childOneTableViewController
searchController.dimsBackgroundDuringPresentation = false
self.navigationItem.searchController = searchController
self.definesPresentationContext = true

I am using a segmented control to switch between the two childViewControllers.

What I want to do is hide the searchBar for the second childViewController but so far I can only achieve that by setting the searchController to nil which is not something I want to do.

I have read many posts that highlight what to do when segueing but this is a slightly different scenario.

I thought the obvious thing was: searchController.isActive = false when adding the secondChildViewController:

@IBAction func segmentedControlValueChanged(_ sender: UISegmentedControl) {
        if segmentedControl.selectedSegmentIndex == 0 {
            remove(asChildViewController: childOneTableViewController)
            add(asChildViewController: childTwoTableViewController)
            navigationItem.searchController!.isActive = true
        } else {
            remove(asChildViewController: childOneTableViewController)
            add(asChildViewController: childTwoTableViewController)
            navigationItem.searchController!.isActive = false
        }
    }

however this is having no effect and the searchController remains visible in both childViewControllers


问:
can somebody explain what exactly is going on with python functions?
what i know in python is i can write something like this  </p>

```<code>blabla = Classname().somefunctions()
</code>```

<p>but in this case both the "np.arange" and "reshape" are functions and it confuses me because  "np.arange" is a function and is treated like a class.   the question is how is this possible??  </p>

```<code>import numpy as np
a = np.arange(15).reshape(3, 5)
print(a)
</code>```

答:
This happens because np.arange(15) returns an instance of a class. Actually everything in python are classes. That's why you can for example do "HELLO WORLD".lower()

In this case what the code does is to evaluate np.(arange) and after reshape(3, 5)

So this will be the equivalent:

```<code>import numpy as np
a = np.arange(15)
a = a.reshape(3, 5)
print(a)
</code>```

Body:
what i know in python is i can write something like this

blabla = Classname().somefunctions()

but in this case both the "np.arange" and "reshape" are functions and it confuses me because  "np.arange" is a function and is treated like a class.   the question is how is this possible??

import numpy as np
a = np.arange(15).reshape(3, 5)
print(a)

Body:
This happens because np.arange(15) returns an instance of a class. Actually everything in python are classes. That's why you can for example do "HELLO WORLD".lower()

In this case what the code does is to evaluate np.(arange) and after reshape(3, 5)

So this will be the equivalent:

import numpy as np
a = np.arange(15)
a = a.reshape(3, 5)
print(a)


问:
How to make two buttons on the same row in eclipse programmatically?
```<code>LinearLayout table = (LinearLayout)findViewById(R.id.linearlayout);

btnControl = new Button(this);
    btnControl.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    btnControl.setPadding(0,40,0,40);//x,y,w,h
    btnControl.setBackgroundColor(Color.parseColor("#1C344E"));
    btnControl.setTextColor(Color.WHITE);
    setMargins(btnControl, 50, 50, 50, 50);

btnLogs = new Button(this);
        btnLogs.setLayoutParams(new LayoutParams(380, LayoutParams.WRAP_CONTENT));
        btnLogs.setPadding(0,40,0,40);//x,y,w,h
        btnLogs.setBackgroundColor(Color.parseColor("#1C344E"));
        btnLogs.setTextColor(Color.WHITE);
        setMargins(btnLogs, 50, 50, 50, 50);
        btnLogs.setId(5);
        btnLogs.setOnClickListener(this);

        btnTermLogs = new Button(this);
        btnTermLogs.setLayoutParams(new LayoutParams(380, LayoutParams.WRAP_CONTENT));
        btnTermLogs.setPadding(0,40,0,40);//x,y,w,h
        btnTermLogs.setBackgroundColor(Color.parseColor("#CC6675"));
        btnTermLogs.setTextColor(Color.WHITE);
        setMargins(btnLogs, 50, 50, 50, 50);
        btnTermLogs.setId(6);
        btnTermLogs.setOnClickListener(this);

btnLogout = new Button(this);
    btnLogout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    btnLogout.setPadding(0,40,0,40);//x,y,w,h
    btnLogout.setBackgroundColor(Color.parseColor("#CC6675"));
    btnLogout.setTextColor(Color.WHITE);

    table.addView(btnLogs);
        table.addView(btnTermLogs);
</code>```

I want the two buttons to be aligned together horizontally. However it just align themselves vertically which i dont want.

My buttons look like this:

what i want is to look like this:

答:
Try this below function. It will help

```<code>public void addButtons(){
    LinearLayout table = (LinearLayout)findViewById(R.id.linearlayout);

    LinearLayout linearLayout1 = new LinearLayout(this);
    linearLayout1.setOrientation(LinearLayout.VERTICAL);
    LinearLayout.LayoutParams LayoutParamsview = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

    Button button1 = new Button(this);
    button1.setText("Btn 1");
    button1.setLayoutParams(LayoutParamsview);

    linearLayout1.addView(button1);
    table.addView(linearLayout1);

    //
    LinearLayout linearLayout2 = new LinearLayout(this);
    linearLayout2.setOrientation(LinearLayout.HORIZONTAL);

    Button button2 = new Button(this);
    button2.setText("Btn 2");
    button2.setLayoutParams(LayoutParamsview);

    Button button3 = new Button(this);
    button3.setText("Btn 3");
    button3.setLayoutParams(LayoutParamsview);

    linearLayout2.addView(button2);
    linearLayout2.addView(button3);
    table.addView(linearLayout2);

    //
    LinearLayout linearLayout3 = new LinearLayout(this);
    linearLayout3.setOrientation(LinearLayout.VERTICAL);

    Button button4 = new Button(this);
    button4.setText("Btn 4");
    button4.setLayoutParams(LayoutParamsview);

    linearLayout3.addView(button4);
    table.addView(linearLayout3);

}
</code>```

Body:
LinearLayout table = (LinearLayout)findViewById(R.id.linearlayout);

btnControl = new Button(this);
    btnControl.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    btnControl.setPadding(0,40,0,40);//x,y,w,h
    btnControl.setBackgroundColor(Color.parseColor("#1C344E"));
    btnControl.setTextColor(Color.WHITE);
    setMargins(btnControl, 50, 50, 50, 50);

btnLogs = new Button(this);
        btnLogs.setLayoutParams(new LayoutParams(380, LayoutParams.WRAP_CONTENT));
        btnLogs.setPadding(0,40,0,40);//x,y,w,h
        btnLogs.setBackgroundColor(Color.parseColor("#1C344E"));
        btnLogs.setTextColor(Color.WHITE);
        setMargins(btnLogs, 50, 50, 50, 50);
        btnLogs.setId(5);
        btnLogs.setOnClickListener(this);

        btnTermLogs = new Button(this);
        btnTermLogs.setLayoutParams(new LayoutParams(380, LayoutParams.WRAP_CONTENT));
        btnTermLogs.setPadding(0,40,0,40);//x,y,w,h
        btnTermLogs.setBackgroundColor(Color.parseColor("#CC6675"));
        btnTermLogs.setTextColor(Color.WHITE);
        setMargins(btnLogs, 50, 50, 50, 50);
        btnTermLogs.setId(6);
        btnTermLogs.setOnClickListener(this);

btnLogout = new Button(this);
    btnLogout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    btnLogout.setPadding(0,40,0,40);//x,y,w,h
    btnLogout.setBackgroundColor(Color.parseColor("#CC6675"));
    btnLogout.setTextColor(Color.WHITE);

    table.addView(btnLogs);
        table.addView(btnTermLogs);

I want the two buttons to be aligned together horizontally. However it just align themselves vertically which i dont want.

My buttons look like this:

what i want is to look like this:

Body:
Try this below function. It will help

public void addButtons(){
    LinearLayout table = (LinearLayout)findViewById(R.id.linearlayout);

    LinearLayout linearLayout1 = new LinearLayout(this);
    linearLayout1.setOrientation(LinearLayout.VERTICAL);
    LinearLayout.LayoutParams LayoutParamsview = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

    Button button1 = new Button(this);
    button1.setText("Btn 1");
    button1.setLayoutParams(LayoutParamsview);

    linearLayout1.addView(button1);
    table.addView(linearLayout1);

    //
    LinearLayout linearLayout2 = new LinearLayout(this);
    linearLayout2.setOrientation(LinearLayout.HORIZONTAL);

    Button button2 = new Button(this);
    button2.setText("Btn 2");
    button2.setLayoutParams(LayoutParamsview);

    Button button3 = new Button(this);
    button3.setText("Btn 3");
    button3.setLayoutParams(LayoutParamsview);

    linearLayout2.addView(button2);
    linearLayout2.addView(button3);
    table.addView(linearLayout2);

    //
    LinearLayout linearLayout3 = new LinearLayout(this);
    linearLayout3.setOrientation(LinearLayout.VERTICAL);

    Button button4 = new Button(this);
    button4.setText("Btn 4");
    button4.setLayoutParams(LayoutParamsview);

    linearLayout3.addView(button4);
    table.addView(linearLayout3);

}


问:
How to solve this SQL query
There are 3 tables: item, grp and grp_rel.

item table:

```<code>item_id     title
</code>```

grp table:

```<code>grp_id      title
</code>```

grp_rel table:

```<code>grp_id      item_id
</code>```

Data in table (item table): item title is varchar(255), not unique

```<code>1       item-a
2       item-b
3       title-c
4       item-d
5       title-c
6       value-e
7       value-e
</code>```

Data in table (grp table): grp title is varchar(255), not unique.

```<code>1   title
2   value
</code>```

Data in table (grp_rel table):

```<code>1   3
1   5
2   6
2   7
</code>```

Expected sql result is (order by item title):

```<code>item_id     grp_id  title       grp_title
1           NULL    item-a      NULL
2           NULL    item-b      NULL
3           1       title-c     title
4           NULL    item-d      NULL
6           2       value-e     value
</code>```

答:
You can use this code,</p>

```<code>SELECT MIN(it.item_id) as item_id,MIN(gr.grp_id) as grp_id,it.title,gr.title
FROM item it
left join  grp_rel gl on it.item_id=gl.item_id
left join grp gr on gl.grp_id=gr.grp_id
GROUP BY it.title,gr.title
ORDER BY it.title
</code>```

Title: How to solve this SQL query

Body:
There are 3 tables: item, grp and grp_rel.

item table:

item_id     title

grp table:

grp_id      title

grp_rel table:

grp_id      item_id

Data in table (item table): item title is varchar(255), not unique

1       item-a
2       item-b
3       title-c
4       item-d
5       title-c
6       value-e
7       value-e

Data in table (grp table): grp title is varchar(255), not unique.

1   title
2   value

Data in table (grp_rel table):

1   3
1   5
2   6
2   7

Expected sql result is (order by item title):

item_id     grp_id  title       grp_title
1           NULL    item-a      NULL
2           NULL    item-b      NULL
3           1       title-c     title
4           NULL    item-d      NULL
6           2       value-e     value

Body:
You can use this code,

SELECT MIN(it.item_id) as item_id,MIN(gr.grp_id) as grp_id,it.title,gr.title
FROM item it
left join  grp_rel gl on it.item_id=gl.item_id
left join grp gr on gl.grp_id=gr.grp_id
GROUP BY it.title,gr.title
ORDER BY it.title


问:
.net core Avoid repeating ModelState in controller/action
Im working in a .net core 2.x project.
I write below code in each action to validate my modelstate.

```<code>        if (ModelState.IsValid)
        {
            // Do something
        }
        else
        {
            // Return Modelstate Error
        }
</code>```

I want to know what is the best practice to avoid repeating the condition in each action.
I want to validate modelstate before reaching the action and return the appropriate error message if modelstate is not valid.

Update

Note. My actions are simple Api action and I just want to return errors ( which are in my Model)in the HttpContext Body in the form of array of string.

Eg of Model Property.

```<code>    [Required(ErrorMessage = "Fill the name Please !!!")]
    public string FirstName { get; set; }
</code>```

Eg of Action.

```<code>    [HttpPost]
    public void Create([FromBody]MyModel model)
    {
        if (ModelState.IsValid)
        {
            // Do something
        }
        else
        {
            // Return Modelstate Error
        }
    }
</code>```

答:
Try somethink like this

```<code> public class ModelStateValidationFilter : ActionFilterAttribute
    {
        public string ErrorPage;

        public override void OnActionExecuting(ActionExecutingContext context)
        {

 if (!context.ModelState.IsValid)
        {
            //return error result
            List<string> list = (from modelState in context.ModelState.Values from error in modelState.Errors select error.ErrorMessage).ToList();
            context.Result = new BadRequestObjectResult(list);

            //or redirect to some result
            context.Result = new RedirectToRouteResult(ErrorPage);

            //or do whatever you need
        }

        base.OnActionExecuting(context);
    }
}
</code>```

and add it like this

on controller

```<code>[ModelStateValidationFilter(ErrorPage = "somepage")]
    public class SomeController : Controller
</code>```

on action

```<code>[ModelStateValidationFilter(ErrorPage = "somepage")]
public IActionResult SomeAction(somemodel model)
</code>```

or add to all via startup

Body:
Im working in a .net core 2.x project.
I write below code in each action to validate my modelstate.

        if (ModelState.IsValid)
        {
            // Do something
        }
        else
        {
            // Return Modelstate Error
        }

I want to know what is the best practice to avoid repeating the condition in each action.
I want to validate modelstate before reaching the action and return the appropriate error message if modelstate is not valid.

Update

Note. My actions are simple Api action and I just want to return errors ( which are in my Model)in the HttpContext Body in the form of array of string.

Eg of Model Property.

    [Required(ErrorMessage = "Fill the name Please !!!")]
    public string FirstName { get; set; }

Eg of Action.

    [HttpPost]
    public void Create([FromBody]MyModel model)
    {
        if (ModelState.IsValid)
        {
            // Do something
        }
        else
        {
            // Return Modelstate Error
        }
    }

Body:
Try somethink like this

 public class ModelStateValidationFilter : ActionFilterAttribute
    {
        public string ErrorPage;

        public override void OnActionExecuting(ActionExecutingContext context)
        {

 if (!context.ModelState.IsValid)
        {
            //return error result
            List<string> list = (from modelState in context.ModelState.Values from error in modelState.Errors select error.ErrorMessage).ToList();
            context.Result = new BadRequestObjectResult(list);

            //or redirect to some result
            context.Result = new RedirectToRouteResult(ErrorPage);

            //or do whatever you need
        }

        base.OnActionExecuting(context);
    }
}

and add it like this

on controller

[ModelStateValidationFilter(ErrorPage = "somepage")]
    public class SomeController : Controller

on action

[ModelStateValidationFilter(ErrorPage = "somepage")]
public IActionResult SomeAction(somemodel model)

or add to all via startup


问:
calculating ASPECT, SLOPE in python3.x (matlab gradientm function)
gradientm is a matlab function that Calculate gradient, slope, and aspect of data grid

Syntax

[ASPECT, SLOPE, gradN, gradE] = gradientm(Z, R)

Description

[ASPECT, SLOPE, gradN, gradE] = gradientm(Z, R) computes the slope, aspect, and north and east components of the gradient for a regular data grid Z with respect to reference R. If the grid contains elevations in meters, the resulting aspect and slope are in units of degrees clockwise from north and up from the horizontal. The north and east gradient components are the change in the map variable per meter of distance in the north and east directions. The computation uses finite differences for the map variable on the default earth ellipsoid.

Problem

I want something equivalent in python.
I have founded this python library PyDEM but it is for python 2.x but I am working with python 3.x

this is The way of Use the DEMProcessor to compute slope and aspect for the DEM files by PyDEM:

```<code># needs to match above command
filename = 'Shasta-30m-DEM.tif'

# instantiate a processor object
processor = DEMProcessor(filename)

# get magnitude of slope and aspect
mag, aspect = processor.calc_slopes_directions()
</code>```

答:
step1: install GDAL

step2: install rasterio

step3: easy as py:

```<code>from osgeo import gdal
import numpy as np
import rasterio

def calculate_slope(DEM):
    gdal.DEMProcessing('slope.tif', DEM, 'slope')
    with rasterio.open('slope.tif') as dataset:
        slope=dataset.read(1)
    return slope

def calculate_aspect(DEM):
    gdal.DEMProcessing('aspect.tif', DEM, 'aspect')
    with rasterio.open('aspect.tif') as dataset:
        aspect=dataset.read(1)
    return aspect

slope=calculate_slope('DEM.tif')
aspect=calculate_aspect('DEM.tif')

print(type(slope))
print(slope.dtype)
print(slope.shape)
</code>```

Body:
gradientm is a matlab function that Calculate gradient, slope, and aspect of data grid

Syntax

[ASPECT, SLOPE, gradN, gradE] = gradientm(Z, R)

Description

[ASPECT, SLOPE, gradN, gradE] = gradientm(Z, R) computes the slope, aspect, and north and east components of the gradient for a regular data grid Z with respect to reference R. If the grid contains elevations in meters, the resulting aspect and slope are in units of degrees clockwise from north and up from the horizontal. The north and east gradient components are the change in the map variable per meter of distance in the north and east directions. The computation uses finite differences for the map variable on the default earth ellipsoid.

Problem

I want something equivalent in python.
I have founded this python library PyDEM but it is for python 2.x but I am working with python 3.x

this is The way of Use the DEMProcessor to compute slope and aspect for the DEM files by PyDEM:

# needs to match above command
filename = 'Shasta-30m-DEM.tif'

# instantiate a processor object
processor = DEMProcessor(filename)

# get magnitude of slope and aspect
mag, aspect = processor.calc_slopes_directions()

Body:
step1: install GDAL

step2: install rasterio

step3: easy as py:

from osgeo import gdal
import numpy as np
import rasterio

def calculate_slope(DEM):
    gdal.DEMProcessing('slope.tif', DEM, 'slope')
    with rasterio.open('slope.tif') as dataset:
        slope=dataset.read(1)
    return slope

def calculate_aspect(DEM):
    gdal.DEMProcessing('aspect.tif', DEM, 'aspect')
    with rasterio.open('aspect.tif') as dataset:
        aspect=dataset.read(1)
    return aspect

slope=calculate_slope('DEM.tif')
aspect=calculate_aspect('DEM.tif')

print(type(slope))
print(slope.dtype)
print(slope.shape)


问:
State of react app is not current with what I have in my database?
I am working on a small grocery list application. Whenever I submit a form, I perform an axios request to add the item to the database and update my "items" state to contain the new grocery item.

The issue is, unless I refresh the page, my state still shows an empty "items" array. The "items" array's initial state is pulled from the database, this works through using componentDidMount and setting the state of "items" in there.

Also, in my state, I have currentUser which is also pulled from the database. If I attempt to log this.state.currentUser.shoppingList after adding my first item, it will show an empty array even though I can see the server side log stating the array is not empty.

Here is my code:

```<code>**App Component**
import React from 'react';
import ListForm from './ListForm';
import * as helpers from '../helpers';

class App extends React.Component{
  state = {
    currentUser: {},
    items: []
  }

  componentDidMount() {
    console.log('Hello!');
    helpers.fetchUser()
      .then(data => {
        this.setState({
          currentUser: data,
          items: data.shoppingList
        }, () => {
          console.log(this.state)
        });
      });
  }

  // Handle adding new items
  onSubmit = (id, item) => {
    this.setState({items: this.state.items.concat([item])});
    helpers.addItem(id, item);
    console.log(this.state);
  }

  // Handle deletion of items
  onDelete = (id, deleteItem) => {
    var shoppingList = this.state.currentUser.shoppingList;
    var index = shoppingList.findIndex(x => x.name === deleteItem);

    console.log(shoppingList);
    helpers.removeItem(id, deleteItem);
  }

  render() {
    return (
      <div className="container row offset-4">
        <div className="jumbotron col-sm-6">
          <ListForm
            currentUser={this.state.currentUser}
            items={this.state.items}
            onSubmit={this.onSubmit}
            onDelete={this.onDelete}
          />
        </div>
      </div>
    );
  }
};

export default App;
</code>```

Helpers.js

```<code>import axios from 'axios';

export const fetchUser = async () => {
  const resp = await axios.get('/api/current_user');

  return resp.data;
}

export const addItem =  (id, newItem) => {
  const resp = axios.post("/api/" + id + "/addItem", newItem);

  return resp.data;
}

export const removeItem = (id, deleteItem) => {
  const resp = axios.delete("/api/" + id + "/removeItem", {data: {item: deleteItem}});

  return resp.data;
}
</code>```

ListForm Component

```<code>import React from 'react';
import ListItem from './ListItem';

class ListForm extends React.Component {
  state = {
    value: ''
  }

  // Render content based on whether or not currentUser has been returned from
  // our API request.
  renderContent = () => {
    const shoppingList = this.props.currentUser.shoppingList;
    if(shoppingList === null || shoppingList === undefined) {
      return (<h5>Loading List</h5>);
    } else {
        return (
          <div>
            {this.props.items.map((item, index) =>
              <ListItem
                {...item}
                key={index}
                id={index}
                currentUser={this.props.currentUser}
                onDelete={this.props.onDelete}
              />
            )}
          </div>
        );
    }
  }

  // Handle the submission of a new item to database and state.
  handleSubmit = e => {
    e.preventDefault();

    this.props.onSubmit(this.props.currentUser._id, {name: this.state.value});
    this.setState(prevState => ({value: ''}));
  }

  // Handle any changes within the input.
  onChange = e => {
    this.setState({value: e.target.value});
  }

  render() {
    return (
      <div className="col-xs-9">
          <h3>Grocery List</h3>
        <form className="form-control" onSubmit={this.handleSubmit}>
          <input style={{display: "inline", width: "60%", height: "2em"}} className="form-control" type="text"
            value={this.state.value}
            onChange={this.onChange}
          />
          <button className="btn btn-success btn-sm float-right">Add item</button>
        </form>
        <div style={{marginTop: "10%"}}>
          {this.renderContent()}
        </div>
      </div>
    );
  }
}

export default ListForm;
</code>```

ListItem Component

```<code>import React from 'react';

const ListItem = props => {

  // Handle delete item requests
  const handleClick = event => {
    var delItem = document.getElementById("btn" + props.id).textContent;

    props.onDelete(props.currentUser._id, delItem);
  }

  return (
    <div>
      <li
        style={{display: "inline"}} id={"btn" + props.id} key={props.id}>{props.name}
      </li>
      <button
        style={{display: "inline"}} onClick={e => handleClick(e)} className="btn btn-danger btn-sm float-right">
          Remove
      </button>
      <hr />
    </div>
  );
}

export default ListItem;
</code>```

答:
Instead of this:

```<code>onSubmit = (id, item) => {
    this.setState({items: this.state.items.concat([item])});
    helpers.addItem(id, item);
    console.log(this.state);
  }
</code>```

Try this:

```<code>onSubmit = (id, item) => {
    this.setState({items: [...this.state.items,item]});
    helpers.addItem(id, item);
    console.log(this.state);
  }
</code>```

Body:
I am working on a small grocery list application. Whenever I submit a form, I perform an axios request to add the item to the database and update my "items" state to contain the new grocery item.

The issue is, unless I refresh the page, my state still shows an empty "items" array. The "items" array's initial state is pulled from the database, this works through using componentDidMount and setting the state of "items" in there.

Also, in my state, I have currentUser which is also pulled from the database. If I attempt to log this.state.currentUser.shoppingList after adding my first item, it will show an empty array even though I can see the server side log stating the array is not empty.

Here is my code:

**App Component**
import React from 'react';
import ListForm from './ListForm';
import * as helpers from '../helpers';

class App extends React.Component{
  state = {
    currentUser: {},
    items: []
  }

  componentDidMount() {
    console.log('Hello!');
    helpers.fetchUser()
      .then(data => {
        this.setState({
          currentUser: data,
          items: data.shoppingList
        }, () => {
          console.log(this.state)
        });
      });
  }

  // Handle adding new items
  onSubmit = (id, item) => {
    this.setState({items: this.state.items.concat([item])});
    helpers.addItem(id, item);
    console.log(this.state);
  }

  // Handle deletion of items
  onDelete = (id, deleteItem) => {
    var shoppingList = this.state.currentUser.shoppingList;
    var index = shoppingList.findIndex(x => x.name === deleteItem);

    console.log(shoppingList);
    helpers.removeItem(id, deleteItem);
  }

  render() {
    return (

          <ListForm
            currentUser={this.state.currentUser}
            items={this.state.items}
            onSubmit={this.onSubmit}
            onDelete={this.onDelete}
          />

    );
  }
};

export default App;

Helpers.js

import axios from 'axios';

export const fetchUser = async () => {
  const resp = await axios.get('/api/current_user');

  return resp.data;
}

export const addItem =  (id, newItem) => {
  const resp = axios.post("/api/" + id + "/addItem", newItem);

  return resp.data;
}

export const removeItem = (id, deleteItem) => {
  const resp = axios.delete("/api/" + id + "/removeItem", {data: {item: deleteItem}});

  return resp.data;
}

ListForm Component

import React from 'react';
import ListItem from './ListItem';

class ListForm extends React.Component {
  state = {
    value: ''
  }

  // Render content based on whether or not currentUser has been returned from
  // our API request.
  renderContent = () => {
    const shoppingList = this.props.currentUser.shoppingList;
    if(shoppingList === null || shoppingList === undefined) {
      return (
Loading List
);
    } else {
        return (

            {this.props.items.map((item, index) =>
              <ListItem
                {...item}
                key={index}
                id={index}
                currentUser={this.props.currentUser}
                onDelete={this.props.onDelete}
              />
            )}

        );
    }
  }

  // Handle the submission of a new item to database and state.
  handleSubmit = e => {
    e.preventDefault();

    this.props.onSubmit(this.props.currentUser._id, {name: this.state.value});
    this.setState(prevState => ({value: ''}));
  }

  // Handle any changes within the input.
  onChange = e => {
    this.setState({value: e.target.value});
  }

  render() {
    return (

Grocery List

        <form className="form-control" onSubmit={this.handleSubmit}>
          <input style={{display: "inline", width: "60%", height: "2em"}} className="form-control" type="text"
            value={this.state.value}
            onChange={this.onChange}
          />
          <button className="btn btn-success btn-sm float-right">Add item</button>
        </form>

          {this.renderContent()}

    );
  }
}

export default ListForm;

ListItem Component

import React from 'react';

const ListItem = props => {

  // Handle delete item requests
  const handleClick = event => {
    var delItem = document.getElementById("btn" + props.id).textContent;

    props.onDelete(props.currentUser._id, delItem);
  }

  return (

{props.name}

      <button
        style={{display: "inline"}} onClick={e => handleClick(e)} className="btn btn-danger btn-sm float-right">
          Remove
      </button>

  );
}

export default ListItem;

Body:
Instead of this:

onSubmit = (id, item) => {
    this.setState({items: this.state.items.concat([item])});
    helpers.addItem(id, item);
    console.log(this.state);
  }

Try this:

onSubmit = (id, item) => {
    this.setState({items: [...this.state.items,item]});
    helpers.addItem(id, item);
    console.log(this.state);
  }


问:
How to create an array column using the Spark Dataset API (Java)
I have a Dataset called outLinks which has two columns, a string column and an array column. It looks like below:

```<code>+-------+---------------------+
|    url|collect_set(outlinks)|
+-------+---------------------+
| link91|   [link620, link761]|
|link297| [link999, link942...|
|link246| [link623, link605...|
...
</code>```

I am trying to append several more rows to this table, where each new row contains a string and an empty list. diff is a Dataset with one string column.

```<code>outLinks = outLinks.union(
        diff.map(r ->
                 new Tuple2<>(r.getString(0), DataTypes.createArrayType(DataTypes.StringType)),
                 Encoders.tuple(Encoders.STRING(), Encoders.bean(ArrayType.class))).toDF());
</code>```

I've tried to define an empty array/list in every way I can imagine. When I do it like above (where I use the ArrayType class), I get the following exception:

```<code>Exception in thread "main" java.util.NoSuchElementException: head of empty list
    at scala.collection.immutable.Nil$.head(List.scala:420)
    at scala.collection.immutable.Nil$.head(List.scala:417)
    at org.apache.spark.sql.catalyst.encoders.ExpressionEncoder$$anonfun$5.apply(ExpressionEncoder.scala:121)
    at org.apache.spark.sql.catalyst.encoders.ExpressionEncoder$$anonfun$5.apply(ExpressionEncoder.scala:120)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
    at scala.collection.immutable.List.foreach(List.scala:381)
    at scala.collection.TraversableLike$class.map(TraversableLike.scala:234)
    at scala.collection.immutable.List.map(List.scala:285)
    at org.apache.spark.sql.catalyst.encoders.ExpressionEncoder$.tuple(ExpressionEncoder.scala:120)
    at org.apache.spark.sql.catalyst.encoders.ExpressionEncoder$.tuple(ExpressionEncoder.scala:186)
    at org.apache.spark.sql.Encoders$.tuple(Encoders.scala:228)
    at org.apache.spark.sql.Encoders.tuple(Encoders.scala)
    at edu.upenn.cis455.pagerank.PageRankTask.run(PageRankTask.java:96)
    at edu.upenn.cis455.pagerank.PageRankTask.main(PageRankTask.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:755)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:180)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:205)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:119)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
</code>```

And when I use regular Java collections:

```<code>outLinks = outLinks.union(
        diff.map(r ->
                 new Tuple2<>(r.getString(0), Collections.emptyList),
                 Encoders.tuple(Encoders.STRING(), Encoders.javaSerialization(List.class))).toDF());
</code>```

I get the following exception:

```<code>Exception in thread "main" org.apache.spark.sql.AnalysisException: Union can only be performed on tables with the compatible column types. binary <> array<string> at the second column of the second table;;
'Union
:- Aggregate [url#18], [url#18, collect_set(outlinks#1, 0, 0) AS collect_set(outlinks)#99]
:  +- Deduplicate [url#18, outlinks#1], false
:     +- TypedFilter edu.upenn.cis455.pagerank.PageRankTask$$Lambda$15/603456365@713e49c3, interface org.apache.spark.sql.Row, [StructField(url,StringType,true), StructField(outlinks,StringType,true)], createexternalrow(url#18.toString, outlinks#1.toString, StructField(url,StringType,true), StructField(outlinks,StringType,true))
:        +- Project [url#18, outlinks#1]
:           +- Join Inner, (id#15 = storagepage_id#0)
:              :- Relation[id#15,body#16,lastaccessed#17L,url#18] JDBCRelation(pages) [numPartitions=1]
:              +- Relation[storagepage_id#0,outlinks#1] JDBCRelation(storagepage_outlinks) [numPartitions=1]
+- SerializeFromObject [staticinvoke(class org.apache.spark.unsafe.types.UTF8String, StringType, fromString, input[0, scala.Tuple2, true]._1, true) AS value#1771, encodeusingserializer(input[0, scala.Tuple2, true]._2, false) AS _2#1772]
   +- MapElements edu.upenn.cis455.pagerank.PageRankTask$$Lambda$17/2054286321@4bf89d3d, interface org.apache.spark.sql.Row, [StructField(url,StringType,true)], obj#1770: scala.Tuple2
      +- DeserializeToObject createexternalrow(url#18.toString, StructField(url,StringType,true)), obj#1769: org.apache.spark.sql.Row
         +- Except
            :- Project [url#18]
            :  +- Relation[id#15,body#16,lastaccessed#17L,url#18] JDBCRelation(pages) [numPartitions=1]
            +- Project [url#152]
               +- Aggregate [url#152], [url#152, collect_set(outlinks#1, 0, 0) AS collect_set(outlinks)#99]
                  +- Deduplicate [url#152, outlinks#1], false
                     +- TypedFilter edu.upenn.cis455.pagerank.PageRankTask$$Lambda$15/603456365@713e49c3, interface org.apache.spark.sql.Row, [StructField(url,StringType,true), StructField(outlinks,StringType,true)], createexternalrow(url#152.toString, outlinks#1.toString, StructField(url,StringType,true), StructField(outlinks,StringType,true))
                        +- Project [url#152, outlinks#1]
                           +- Join Inner, (id#149 = storagepage_id#0)
                              :- Relation[id#149,body#150,lastaccessed#151L,url#152] JDBCRelation(pages) [numPartitions=1]
                              +- Relation[storagepage_id#0,outlinks#1] JDBCRelation(storagepage_outlinks) [numPartitions=1]

    at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$class.failAnalysis(CheckAnalysis.scala:39)
    at org.apache.spark.sql.catalyst.analysis.Analyzer.failAnalysis(Analyzer.scala:91)
    at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1$$anonfun$apply$13$$anonfun$apply$14.apply(CheckAnalysis.scala:329)
    at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1$$anonfun$apply$13$$anonfun$apply$14.apply(CheckAnalysis.scala:326)
    at scala.collection.immutable.List.foreach(List.scala:381)
    at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1$$anonfun$apply$13.apply(CheckAnalysis.scala:326)
    at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1$$anonfun$apply$13.apply(CheckAnalysis.scala:315)
    at scala.collection.immutable.List.foreach(List.scala:381)
    at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1.apply(CheckAnalysis.scala:315)
    at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1.apply(CheckAnalysis.scala:78)
    at org.apache.spark.sql.catalyst.trees.TreeNode.foreachUp(TreeNode.scala:127)
    at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$class.checkAnalysis(CheckAnalysis.scala:78)
    at org.apache.spark.sql.catalyst.analysis.Analyzer.checkAnalysis(Analyzer.scala:91)
    at org.apache.spark.sql.execution.QueryExecution.assertAnalyzed(QueryExecution.scala:52)
    at org.apache.spark.sql.Dataset$.ofRows(Dataset.scala:66)
    at org.apache.spark.sql.Dataset.withSetOperator(Dataset.scala:2884)
    at org.apache.spark.sql.Dataset.union(Dataset.scala:1656)
    at edu.upenn.cis455.pagerank.PageRankTask.run(PageRankTask.java:95)
    at edu.upenn.cis455.pagerank.PageRankTask.main(PageRankTask.java:29)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:755)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:180)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:205)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:119)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
</code>```

答:
You can use spark.implicits().newStringArrayEncoder() for String array. Here is the sample.

```<code>public class SparkSample {
    public static void main(String[] args) {
        SparkSession spark = SparkSession
                .builder()
                .appName("SparkSample")
                .master("local[*]")
                .getOrCreate();

        List<Tuple2<String,String[]>> inputList = new ArrayList<Tuple2<String,String[]>>();
        inputList.add(new Tuple2<String,String[]>("link91",new String[]{"link620","link761"}));
        inputList.add(new Tuple2<String,String[]>("link297",new String[]{"link999","link942"}));
        Dataset<Row> dataset = spark.createDataset(inputList, Encoders.tuple(Encoders.STRING(), spark.implicits().newStringArrayEncoder())).toDF();
        dataset.show(false);
    }
}
</code>```

Body:
I have a Dataset called outLinks which has two columns, a string column and an array column. It looks like below:

+-------+---------------------+
|    url|collect_set(outlinks)|
+-------+---------------------+
| link91|   [link620, link761]|
|link297| [link999, link942...|
|link246| [link623, link605...|
...

I am trying to append several more rows to this table, where each new row contains a string and an empty list. diff is a Dataset with one string column.

outLinks = outLinks.union(
        diff.map(r ->
                 new Tuple2<>(r.getString(0), DataTypes.createArrayType(DataTypes.StringType)),
                 Encoders.tuple(Encoders.STRING(), Encoders.bean(ArrayType.class))).toDF());

I've tried to define an empty array/list in every way I can imagine. When I do it like above (where I use the ArrayType class), I get the following exception:

Exception in thread "main" java.util.NoSuchElementException: head of empty list
    at scala.collection.immutable.Nil$.head(List.scala:420)
    at scala.collection.immutable.Nil$.head(List.scala:417)
    at org.apache.spark.sql.catalyst.encoders.ExpressionEncoder$$anonfun$5.apply(ExpressionEncoder.scala:121)
    at org.apache.spark.sql.catalyst.encoders.ExpressionEncoder$$anonfun$5.apply(ExpressionEncoder.scala:120)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
    at scala.collection.immutable.List.foreach(List.scala:381)
    at scala.collection.TraversableLike$class.map(TraversableLike.scala:234)
    at scala.collection.immutable.List.map(List.scala:285)
    at org.apache.spark.sql.catalyst.encoders.ExpressionEncoder$.tuple(ExpressionEncoder.scala:120)
    at org.apache.spark.sql.catalyst.encoders.ExpressionEncoder$.tuple(ExpressionEncoder.scala:186)
    at org.apache.spark.sql.Encoders$.tuple(Encoders.scala:228)
    at org.apache.spark.sql.Encoders.tuple(Encoders.scala)
    at edu.upenn.cis455.pagerank.PageRankTask.run(PageRankTask.java:96)
    at edu.upenn.cis455.pagerank.PageRankTask.main(PageRankTask.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:755)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:180)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:205)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:119)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

And when I use regular Java collections:

outLinks = outLinks.union(
        diff.map(r ->
                 new Tuple2<>(r.getString(0), Collections.emptyList),
                 Encoders.tuple(Encoders.STRING(), Encoders.javaSerialization(List.class))).toDF());

I get the following exception:

Exception in thread "main" org.apache.spark.sql.AnalysisException: Union can only be performed on tables with the compatible column types. binary <> array<string> at the second column of the second table;;
'Union
:- Aggregate [url#18], [url#18, collect_set(outlinks#1, 0, 0) AS collect_set(outlinks)#99]
:  +- Deduplicate [url#18, outlinks#1], false
:     +- TypedFilter edu.upenn.cis455.pagerank.PageRankTask$$Lambda$15/603456365@713e49c3, interface org.apache.spark.sql.Row, [StructField(url,StringType,true), StructField(outlinks,StringType,true)], createexternalrow(url#18.toString, outlinks#1.toString, StructField(url,StringType,true), StructField(outlinks,StringType,true))
:        +- Project [url#18, outlinks#1]
:           +- Join Inner, (id#15 = storagepage_id#0)
:              :- Relation[id#15,body#16,lastaccessed#17L,url#18] JDBCRelation(pages) [numPartitions=1]
:              +- Relation[storagepage_id#0,outlinks#1] JDBCRelation(storagepage_outlinks) [numPartitions=1]
+- SerializeFromObject [staticinvoke(class org.apache.spark.unsafe.types.UTF8String, StringType, fromString, input[0, scala.Tuple2, true]._1, true) AS value#1771, encodeusingserializer(input[0, scala.Tuple2, true]._2, false) AS _2#1772]
   +- MapElements edu.upenn.cis455.pagerank.PageRankTask$$Lambda$17/2054286321@4bf89d3d, interface org.apache.spark.sql.Row, [StructField(url,StringType,true)], obj#1770: scala.Tuple2
      +- DeserializeToObject createexternalrow(url#18.toString, StructField(url,StringType,true)), obj#1769: org.apache.spark.sql.Row
         +- Except
            :- Project [url#18]
            :  +- Relation[id#15,body#16,lastaccessed#17L,url#18] JDBCRelation(pages) [numPartitions=1]
            +- Project [url#152]
               +- Aggregate [url#152], [url#152, collect_set(outlinks#1, 0, 0) AS collect_set(outlinks)#99]
                  +- Deduplicate [url#152, outlinks#1], false
                     +- TypedFilter edu.upenn.cis455.pagerank.PageRankTask$$Lambda$15/603456365@713e49c3, interface org.apache.spark.sql.Row, [StructField(url,StringType,true), StructField(outlinks,StringType,true)], createexternalrow(url#152.toString, outlinks#1.toString, StructField(url,StringType,true), StructField(outlinks,StringType,true))
                        +- Project [url#152, outlinks#1]
                           +- Join Inner, (id#149 = storagepage_id#0)
                              :- Relation[id#149,body#150,lastaccessed#151L,url#152] JDBCRelation(pages) [numPartitions=1]
                              +- Relation[storagepage_id#0,outlinks#1] JDBCRelation(storagepage_outlinks) [numPartitions=1]

    at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$class.failAnalysis(CheckAnalysis.scala:39)
    at org.apache.spark.sql.catalyst.analysis.Analyzer.failAnalysis(Analyzer.scala:91)
    at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1$$anonfun$apply$13$$anonfun$apply$14.apply(CheckAnalysis.scala:329)
    at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1$$anonfun$apply$13$$anonfun$apply$14.apply(CheckAnalysis.scala:326)
    at scala.collection.immutable.List.foreach(List.scala:381)
    at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1$$anonfun$apply$13.apply(CheckAnalysis.scala:326)
    at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1$$anonfun$apply$13.apply(CheckAnalysis.scala:315)
    at scala.collection.immutable.List.foreach(List.scala:381)
    at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1.apply(CheckAnalysis.scala:315)
    at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1.apply(CheckAnalysis.scala:78)
    at org.apache.spark.sql.catalyst.trees.TreeNode.foreachUp(TreeNode.scala:127)
    at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$class.checkAnalysis(CheckAnalysis.scala:78)
    at org.apache.spark.sql.catalyst.analysis.Analyzer.checkAnalysis(Analyzer.scala:91)
    at org.apache.spark.sql.execution.QueryExecution.assertAnalyzed(QueryExecution.scala:52)
    at org.apache.spark.sql.Dataset$.ofRows(Dataset.scala:66)
    at org.apache.spark.sql.Dataset.withSetOperator(Dataset.scala:2884)
    at org.apache.spark.sql.Dataset.union(Dataset.scala:1656)
    at edu.upenn.cis455.pagerank.PageRankTask.run(PageRankTask.java:95)
    at edu.upenn.cis455.pagerank.PageRankTask.main(PageRankTask.java:29)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:755)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:180)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:205)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:119)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

Body:
You can use spark.implicits().newStringArrayEncoder() for String array. Here is the sample.

public class SparkSample {
    public static void main(String[] args) {
        SparkSession spark = SparkSession
                .builder()
                .appName("SparkSample")
                .master("local[*]")
                .getOrCreate();

        List<Tuple2<String,String[]>> inputList = new ArrayList<Tuple2<String,String[]>>();
        inputList.add(new Tuple2<String,String[]>("link91",new String[]{"link620","link761"}));
        inputList.add(new Tuple2<String,String[]>("link297",new String[]{"link999","link942"}));
        Dataset<Row> dataset = spark.createDataset(inputList, Encoders.tuple(Encoders.STRING(), spark.implicits().newStringArrayEncoder())).toDF();
        dataset.show(false);
    }
}


答:
You need to call writerow for each row you want to right, which is once for each player. You can do so in a loop as:</p>

```<code>with open('Shiftdata.csv', 'w') as out:
    writer = csv.writer(out)
    header_cells = ["Player"]
    number_of_shifts = 10
    for shift_num in range(1, number_of_shifts + 1):
        header_cells.append("Shift{}".format(shift_num))
    writer.writerow(header_cells)
    for player, shifts in players.items():
        cells = [player]
        cells.extend(shifts)
        writer.writerow(cells)
</code>```

Title: Python Export to Csv

Body:
This is the data i am working with (Sample):

('Bouwmeester', [(0, 37), (155, 194), (327, 420), (541, 602), (654, 717), (761, 834), (1001, 1052), (0, 27), (79, 119), (405, 460), (546, 624), (750, 798), (834, 897), (1061, 1139), (0, 33), (170, 204), (289, 328), (447, 498), (575, 576), (729, 766), (962, 995), (1073, 1113), (1163, 1200)])
('Schwartz', [(0, 40), (165, 209), (362, 417), (550, 567), (761, 809), (881, 954), (1052, 1113), (27, 54), (195, 295), (482, 546), (707, 757), (906, 1003), (1080, 1126), (0, 33), (145, 229), (353, 408), (492, 561), (576, 640), (736, 766), (820, 870), (1094, 1163)])
('Foligno', [(0, 40), (176, 209), (362, 416), (552, 567), (761, 835), (883, 954), (459, 502), (546, 583), (757, 826), (1189, 1200), (0, 33), (212, 249), (353, 413), (575, 576), (696, 722), (722, 762)])

Here is the Script I have so far:

import csv
from itertools import combinations, product

#Header = LastName  StartTime  EndTime  Duration Period TeamAbbrev Position

#Import Game
with open('2017020397.csv', newline='') as f:
    next(f)
    skaters = '\n'.join(' '.join(row) for row in csv.reader(f))
    data = skaters.splitlines()

def to_secs(ms):
    ''' Convert a mm:ss string to seconds '''
    m, s = map(int, ms.split(':'))
    return 60 * m + s

# Store a list of (start, end) times for each player
players = {}
for row in data:
    name, start, end = row.split(None, 3)[:3]
    times = to_secs(start), to_secs(end)
    players.setdefault(name, []).append(times)

for t in players.items():
    print(t)

outfile = open("ShiftData.csv","a",newline='')
writer = csv.writer(outfile)
writer.writerow(["Player","Shift1"])
writer.writerow([name, times])
outfile.close()

Output:

Player  Shift1
Dumba   (39, 39)

The output is the last data not the Whole file. Also i would like all of the shifts to output in there own cell. Example:

Player        Shift1       Shift2      Shift3       Shift4
Bouwmeester   (0, 37)    (155, 194)  (327, 420)   (541, 602)

Body:
You need to call writerow for each row you want to right, which is once for each player. You can do so in a loop as:

with open('Shiftdata.csv', 'w') as out:
    writer = csv.writer(out)
    header_cells = ["Player"]
    number_of_shifts = 10
    for shift_num in range(1, number_of_shifts + 1):
        header_cells.append("Shift{}".format(shift_num))
    writer.writerow(header_cells)
    for player, shifts in players.items():
        cells = [player]
        cells.extend(shifts)
        writer.writerow(cells)


问:
how can i check my token on very request
Here im using angularjs with webApi  when i login with my credentials its generating Token as

```<code>data:
access_token:"SKvWJ2-IK_Zohn6xLS6HXydoV1NdovM5wvtcTvJM0hkZ"
expires_in:86399
token_type:"bearer"
</code>```

This Token is stored in

```<code> LoginFac.LoginWithToken(obj).then(function (d) {
            sessionStorage.employee = angular.toJson(d);
</code>```

I stored my authentication Details in sessionStorage.employee  when i need my access_token And token_type how can i get it back

答: You can use sessionStorage.getItem and  JSON.parse and then access the property access_token

Body:
Here im using angularjs with webApi  when i login with my credentials its generating Token as

data:
access_token:"SKvWJ2-IK_Zohn6xLS6HXydoV1NdovM5wvtcTvJM0hkZ"
expires_in:86399
token_type:"bearer"

This Token is stored in

 LoginFac.LoginWithToken(obj).then(function (d) {
            sessionStorage.employee = angular.toJson(d);

I stored my authentication Details in sessionStorage.employee  when i need my access_token And token_type how can i get it back


问:
how to stop centered css dropdown menu from twitching (chrome only)
I have a css driven dropdown menu, and in Chrome when I hover over the last option the whole thing jumps to the left slightly. I assume it's because the dropdown menu is adding to the overall width of the main list even though it's styled to float. Is there any way to fix this? (it's not doing it in firefox interestingly)

I've noticed by using webdeveloper to outline elements that the last li appears to get wider when it's hovered, but none of the others do.

the applicable sourcecode is here:
http://jsfiddle.net/WsAEW/

答:
It worked for me changing this:

```<code>#menu ul li {
    display: inline;
    position: relative;
}
</code>```

to this:

```<code>#menu ul li {
    display: inline-block;
    position: relative;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
It worked for me changing this:

#menu ul li {
    display: inline;
    position: relative;
}

to this:

#menu ul li {
    display: inline-block;
    position: relative;
}


问:
Remove duplicates Objects from List in Java
I know this kind of question is asked in stackoverflow lots of time before. But my issue is little bit different and I could not find any similar scenario, so posting this question here

Problem:
I need to remove duplicate objects from ArrayList. Structure of my arrayList is as below

```<code>dataList.add(new ObjectClass("a","b"));
dataList.add(new ObjectClass("c","n"));
dataList.add(new ObjectClass("b","a")); // should be counted as duplicate
dataList.add(new ObjectClass("z","x"));
</code>```

I need to remove objects from above list such as, it treats combination of "a,b" and "b,a" as duplicates and remove any of those duplicate

My solution:
step 1) Override equals method in DataClass class

```<code>class DataClass {
      String source;
      String destination;

      DataClass(String src, String dest) {
        this.source = src;
        this.destination = dest;
      }

      // getter setter for source and destination variables

    @Override
    public boolean equals(Object obj) {
        System.out.println("inside equals");
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ObjectClass other = (ObjectClass) obj;
        if(i.equals(other.getJ())
            && j.equals(other.getI())) {
            return true;
        } else return false;
    }
</code>```

step 2) method to remove duplicates

```<code>public List<DataClass> removeDuplicates(List<DataClass> dataList) {
            List<DataClass> resultList = new ArrayList<DataClass>();

            // Convert array list to Linked list
            LinkedList<DataClass> linkedList = new LinkedList<DataClass>();
            for(DataClass obj: dataList) {
                linkedList.add(obj);
            }

            // Iterate through linked list and remove if values are duplicates
            for(int i = 0; i<linkedList.size();i++) {
              for(int j = i+1;j<linkedList.size();j++) {
                if(linkedList.get(j).equals(linkedList.get(i))) {
                    linkedList.remove();
                }
              }
            }
            resultList.addAll(linkedList);
            return resultList;
        }
</code>```

I am still looking for any better optimized solution, if there is any. Thanks in advance

Update with solution
: my equals method was needed to correct some comparison logic. So here is my updated ObjectClass instead of DataClass including correct overridden equals method

```<code>public class ObjectClass {
    String i;
    String j;
    public  ObjectClass(String i, String j) {
        this.i = i;
        this.j = j;
    }
    // getters setters
    // override hashcode

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ObjectClass other = (ObjectClass) obj;

        if((i.equals(other.getJ()) || i.equals(other.getI()))
            && (j.equals(other.getI()) || j.equals(other.getJ()))) {
            return true;
        } else return false;
    }
}
</code>```

2) After fixing equals method I tried below implementation in removeDuplicate method as Janos mentioned and it is working fine as expected

```<code>    for(ObjectClass obj: dataList) {
        if(!resultList.contains(obj))
            resultList.add(obj);
    }
</code>```

Thank you very much

答:
example:</p>

```<code>DataClass dc = new DataClass("a","b");
List<DataClass> resultList = new ArrayList<DataClass>();
resultList .add(dc);

for (int i=0; i < resultList.size(); i++) {
 if(resultList.get(i).source.equals(dc.source) && resultList.get(i).destination.equals(dc.destination) || resultList.get(i).source.equals(dc.destination) && resultList.get(i).destination.equals(dc.source)) {
    resultList.remove(i);
 }
}
</code>```

Body:
I know this kind of question is asked in stackoverflow lots of time before. But my issue is little bit different and I could not find any similar scenario, so posting this question here

Problem:
I need to remove duplicate objects from ArrayList. Structure of my arrayList is as below

dataList.add(new ObjectClass("a","b"));
dataList.add(new ObjectClass("c","n"));
dataList.add(new ObjectClass("b","a")); // should be counted as duplicate
dataList.add(new ObjectClass("z","x"));

I need to remove objects from above list such as, it treats combination of "a,b" and "b,a" as duplicates and remove any of those duplicate

My solution:
step 1) Override equals method in DataClass class

class DataClass {
      String source;
      String destination;

      DataClass(String src, String dest) {
        this.source = src;
        this.destination = dest;
      }

      // getter setter for source and destination variables

    @Override
    public boolean equals(Object obj) {
        System.out.println("inside equals");
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ObjectClass other = (ObjectClass) obj;
        if(i.equals(other.getJ())
            && j.equals(other.getI())) {
            return true;
        } else return false;
    }

step 2) method to remove duplicates

public List<DataClass> removeDuplicates(List<DataClass> dataList) {
            List<DataClass> resultList = new ArrayList<DataClass>();

            // Convert array list to Linked list
            LinkedList<DataClass> linkedList = new LinkedList<DataClass>();
            for(DataClass obj: dataList) {
                linkedList.add(obj);
            }

            // Iterate through linked list and remove if values are duplicates
            for(int i = 0; i<linkedList.size();i++) {
              for(int j = i+1;j<linkedList.size();j++) {
                if(linkedList.get(j).equals(linkedList.get(i))) {
                    linkedList.remove();
                }
              }
            }
            resultList.addAll(linkedList);
            return resultList;
        }

I am still looking for any better optimized solution, if there is any. Thanks in advance

Update with solution
: my equals method was needed to correct some comparison logic. So here is my updated ObjectClass instead of DataClass including correct overridden equals method

public class ObjectClass {
    String i;
    String j;
    public  ObjectClass(String i, String j) {
        this.i = i;
        this.j = j;
    }
    // getters setters
    // override hashcode

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ObjectClass other = (ObjectClass) obj;

        if((i.equals(other.getJ()) || i.equals(other.getI()))
            && (j.equals(other.getI()) || j.equals(other.getJ()))) {
            return true;
        } else return false;
    }
}

2) After fixing equals method I tried below implementation in removeDuplicate method as Janos mentioned and it is working fine as expected

    for(ObjectClass obj: dataList) {
        if(!resultList.contains(obj))
            resultList.add(obj);
    }

Thank you very much

Body:
example:

DataClass dc = new DataClass("a","b");
List<DataClass> resultList = new ArrayList<DataClass>();
resultList .add(dc);

for (int i=0; i < resultList.size(); i++) {
 if(resultList.get(i).source.equals(dc.source) && resultList.get(i).destination.equals(dc.destination) || resultList.get(i).source.equals(dc.destination) && resultList.get(i).destination.equals(dc.source)) {
    resultList.remove(i);
 }
}


问:
Project Euler 18
Hey, been working at Project Euler, and this one is giving me some problems

By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.

3

7 4

2 4 6

8 5 9 3

That is, 3 + 7 + 4 + 9 = 23.

Find the maximum total from top to bottom of the triangle below:

...

NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)

here's the algorithm I've used to solve it

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

namespace Problem18
{
    class Program
    {
        static void Main(string[] args)
        {
            string triangle = @"75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23";
            string[] rows = triangle.Split('\n');
            int currindex = 1;
            int total = int.Parse(rows[0]);
            Console.WriteLine(rows[0]);
            for (int i = 1; i < rows.Length; i++)
            {
                string[] array1 = rows[i].Split(' ');
                if (array1.Length > 1)
                {
                    if (int.Parse(array1[currindex - 1]) > int.Parse(array1[currindex]))
                    {
                        Console.WriteLine(array1[currindex - 1]);
                        total += int.Parse(array1[currindex - 1]);
                    }
                    else
                    {
                        Console.WriteLine(array1[currindex]);
                        total += int.Parse(array1[currindex]);
                        currindex++;
                    }
                }
            }
            Console.WriteLine("Total: " + total);
            Console.ReadKey();
        }
    }
}
</code>```

now whenever i run it, it comes up with 1064, only 10 less then the solution -- 1074

i haven't found any problems with the algorithm and I did the problem by hand and also came up with 1064, anyone know if the solution is wrong, i'm interpreting the question wrong, or if there's just a flaw in the algorithm?

答:
You've written a greedy algorithm, which I don't think fits the requirements here. Here's a quick example to demonstrate that point:

```<code>  1
 2 1
1 1 100
</code>```

Using your algorithm you'll reach a sum of 4, although the optimal solution is 102.

Title: Project Euler 18

Body:
Hey, been working at Project Euler, and this one is giving me some problems

By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.

3

7 4

2 4 6

8 5 9 3

That is, 3 + 7 + 4 + 9 = 23.

Find the maximum total from top to bottom of the triangle below:

...

NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)

here's the algorithm I've used to solve it

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

namespace Problem18
{
    class Program
    {
        static void Main(string[] args)
        {
            string triangle = @"75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23";
            string[] rows = triangle.Split('\n');
            int currindex = 1;
            int total = int.Parse(rows[0]);
            Console.WriteLine(rows[0]);
            for (int i = 1; i < rows.Length; i++)
            {
                string[] array1 = rows[i].Split(' ');
                if (array1.Length > 1)
                {
                    if (int.Parse(array1[currindex - 1]) > int.Parse(array1[currindex]))
                    {
                        Console.WriteLine(array1[currindex - 1]);
                        total += int.Parse(array1[currindex - 1]);
                    }
                    else
                    {
                        Console.WriteLine(array1[currindex]);
                        total += int.Parse(array1[currindex]);
                        currindex++;
                    }
                }
            }
            Console.WriteLine("Total: " + total);
            Console.ReadKey();
        }
    }
}

now whenever i run it, it comes up with 1064, only 10 less then the solution -- 1074

i haven't found any problems with the algorithm and I did the problem by hand and also came up with 1064, anyone know if the solution is wrong, i'm interpreting the question wrong, or if there's just a flaw in the algorithm?

Body:
You've written a greedy algorithm, which I don't think fits the requirements here. Here's a quick example to demonstrate that point:

  1
 2 1
1 1 100

Using your algorithm you'll reach a sum of 4, although the optimal solution is 102.


问:
swift4 CAKeyframeAnimation not work
I used layer animations on a view, but I couldn't work at swift4

My view override the layerClass property

```<code>public override class var layerClass: Swift.AnyClass {
    return CoordLayer.self
}
</code>```

And custom key creation CAKeyframeAnimation

```<code>let animation = CAKeyframeAnimation(keyPath: "moveX")
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)
animation.values = values
animation.keyTimes = times.map{ NSNumber(value: $0) }
animation.duration = duration
animation.fillMode = kCAFillModeForwards
animation.delegate = self
self.layer.add(animation, forKey: "moveX")
</code>```

The CoordLayer Class

```<code> class CoordLayer: CALayer {
override class func needsDisplay(forKey key: String) -> Bool {

        if "moveX" == key {
            return true       // ..... swift4 No call ....
        }

        return super.needsDisplay(forKey: key)
    }
}

override func display(){
      // .......some custom operations......
      // ....... swift4 No call .......
}
}
</code>```

The view has no animation effect swift4

答:
KeyFrameAnimation is working as expected in swift 4 also :

Please check the implementation, you need some correction in your implementation.

Let's see it.

Define Controller :

```<code>  import UIKit

 // Controller
 class ViewController: UIViewController {

 override func viewDidLoad() {
    super.viewDidLoad()
    addView()
 }

 private let myView : MyView = {
    let view = MyView()
    view.translatesAutoresizingMaskIntoConstraints = false // enable auto layout
    view.backgroundColor = .red
    return view
 }() // execute closure

 private func addView() {
    view.addSubview(myView)

    NSLayoutConstraint.activate([
         myView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor), // leading
         myView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), // top
         myView.widthAnchor.constraint(equalTo: view.safeAreaLayoutGuide.widthAnchor, multiplier: 0.2), // width = 20 % of view width
         myView.heightAnchor.constraint(equalTo: myView.widthAnchor, multiplier: 1.0) // height = width
        ])
}
}
</code>```

Define MyView :

```<code>// View
class MyView : UIView {

// draw view
override func draw(_ rect: CGRect) {
    super.draw(rect)
}
// layerClass
public override class var layerClass: Swift.AnyClass {
    return CoordLayer.self
}
}
</code>```

Define CoordLayer :

```<code>// Layer
class CoordLayer : CALayer {

override func display() {
    // some custom operations
    backgroundColor = UIColor.red.cgColor // to visualize
    customAnimation() // add animation
    print("Display")
}

override class func needsDisplay(forKey key: String) -> Bool {
    if key == "transform.translation.x" {
         return true
    }
   return super.needsDisplay(forKey: key)
}

// add animation
private func customAnimation() {
    let values = [100,150,200,250]
    let times : [NSNumber] = [0.0, 0.25, 0.5, 1.0] // not necessary always

    let animation = CAKeyframeAnimation(keyPath: "transform.translation.x") // moving view along x direction
    animation.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)]  // array of timing function
    animation.values = values // taking the animated property values for animation
    animation.keyTimes = times // define the timing array
    animation.duration = 5.0 // CFTimeInterval
    animation.isRemovedOnCompletion = false // do not remove the animation effect, no state changes.
    animation.fillMode = kCAFillModeForwards
    animation.delegate = self

    // add animation on coordLayer
    self.add(animation, forKey: "animation")
}
}
</code>```

Animation Delegate :

```<code>extension CoordLayer : CAAnimationDelegate {
func animationDidStart(_ anim: CAAnimation) {
    print("Animation started")
}
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
    print("Animation stopped")
}
}
</code>```

Correction in your implementation :

```<code>(1) Instead of "moveX", use "transform.translation.x"
(2) Give some animation duration, animation.duration = 5.0 // CFTimeInterval
(3) animation.isRemovedOnCompletion = false , so that after animation, view will not move it's beginning position.
</code>```

You can add animation logic in MyView also because you are adding animation on layer. Animation Delegate can be conformed by MyView.(it's upto you).

You can check out the implementation here.

Thanks. :-)

Title: swift4 CAKeyframeAnimation not work

Body:
I used layer animations on a view, but I couldn't work at swift4

My view override the layerClass property

public override class var layerClass: Swift.AnyClass {
    return CoordLayer.self
}

And custom key creation CAKeyframeAnimation

let animation = CAKeyframeAnimation(keyPath: "moveX")
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)
animation.values = values
animation.keyTimes = times.map{ NSNumber(value: $0) }
animation.duration = duration
animation.fillMode = kCAFillModeForwards
animation.delegate = self
self.layer.add(animation, forKey: "moveX")

The CoordLayer Class

 class CoordLayer: CALayer {
override class func needsDisplay(forKey key: String) -> Bool {

        if "moveX" == key {
            return true       // ..... swift4 No call ....
        }

        return super.needsDisplay(forKey: key)
    }
}

override func display(){
      // .......some custom operations......
      // ....... swift4 No call .......
}
}

The view has no animation effect swift4

Body:
KeyFrameAnimation is working as expected in swift 4 also :

Please check the implementation, you need some correction in your implementation.

Let's see it.

Define Controller :

  import UIKit

 // Controller
 class ViewController: UIViewController {

 override func viewDidLoad() {
    super.viewDidLoad()
    addView()
 }

 private let myView : MyView = {
    let view = MyView()
    view.translatesAutoresizingMaskIntoConstraints = false // enable auto layout
    view.backgroundColor = .red
    return view
 }() // execute closure

 private func addView() {
    view.addSubview(myView)

    NSLayoutConstraint.activate([
         myView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor), // leading
         myView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), // top
         myView.widthAnchor.constraint(equalTo: view.safeAreaLayoutGuide.widthAnchor, multiplier: 0.2), // width = 20 % of view width
         myView.heightAnchor.constraint(equalTo: myView.widthAnchor, multiplier: 1.0) // height = width
        ])
}
}

Define MyView :

// View
class MyView : UIView {

// draw view
override func draw(_ rect: CGRect) {
    super.draw(rect)
}
// layerClass
public override class var layerClass: Swift.AnyClass {
    return CoordLayer.self
}
}

Define CoordLayer :

// Layer
class CoordLayer : CALayer {

override func display() {
    // some custom operations
    backgroundColor = UIColor.red.cgColor // to visualize
    customAnimation() // add animation
    print("Display")
}

override class func needsDisplay(forKey key: String) -> Bool {
    if key == "transform.translation.x" {
         return true
    }
   return super.needsDisplay(forKey: key)
}

// add animation
private func customAnimation() {
    let values = [100,150,200,250]
    let times : [NSNumber] = [0.0, 0.25, 0.5, 1.0] // not necessary always

    let animation = CAKeyframeAnimation(keyPath: "transform.translation.x") // moving view along x direction
    animation.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)]  // array of timing function
    animation.values = values // taking the animated property values for animation
    animation.keyTimes = times // define the timing array
    animation.duration = 5.0 // CFTimeInterval
    animation.isRemovedOnCompletion = false // do not remove the animation effect, no state changes.
    animation.fillMode = kCAFillModeForwards
    animation.delegate = self

    // add animation on coordLayer
    self.add(animation, forKey: "animation")
}
}

Animation Delegate :

extension CoordLayer : CAAnimationDelegate {
func animationDidStart(_ anim: CAAnimation) {
    print("Animation started")
}
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
    print("Animation stopped")
}
}

Correction in your implementation :

(1) Instead of "moveX", use "transform.translation.x"
(2) Give some animation duration, animation.duration = 5.0 // CFTimeInterval
(3) animation.isRemovedOnCompletion = false , so that after animation, view will not move it's beginning position.

You can add animation logic in MyView also because you are adding animation on layer. Animation Delegate can be conformed by MyView.(it's upto you).

You can check out the implementation here.

Thanks. :-)


问:
dropdown select value resets after onclick after submit
```<code><select name="txt" id="txt" style="width:180px;height:27px" data-placeholder="Choose a name ..."  class="chosen-select form-control" >
  <option value="0" selected="selected"> SELECT  </option>
  <option value="1" name="1"> a </option>
  <option value="2" name="2"> b </option>
  <option value="3" name="3"> c</option>
</select>

<br />
<select name="repttype" id="repttype" style="width:180px;height:27px" data-placeholder="Choose a name ..."  class="chosen-select form-control" >
  <option value="0"> SELECT  </option>
  <option value="1" name="check1"> 1 </option>
  <option value="2" name="check2"> 2 </option>
  <option value="3" name="check3"> 3</option>
  <option value="4" name="check4"> 4</option>
</select>

<td  align='center'>
  <input type="button"  name="go" id="go" value="Show" class="btn btn-primary btn-md" onclick="issu();"/>
</td>
</code>```

if I select value from 1st dropdown button then click on show I will get the result ao after getting result the same dropdown button should show default value as select

答:
Add following code to your issue() function,

```<code>$('#repttype').val('0');
</code>```

or
remove onclick attribute and add click handler to #go like below

```<code>$('#go').on('click', function(){
    $('#repttype').val('0');
    issue();
});
</code>```

Note: Don't forgot to Add jQuery, also if you are using these codes in <form> than use preventDefault(); to prevent default submit action.

Body:
<select name="txt" id="txt" style="width:180px;height:27px" data-placeholder="Choose a name ..."  class="chosen-select form-control" >
  <option value="0" selected="selected"> SELECT  </option>
  <option value="1" name="1"> a </option>
  <option value="2" name="2"> b </option>
  <option value="3" name="3"> c</option>
</select>

<select name="repttype" id="repttype" style="width:180px;height:27px" data-placeholder="Choose a name ..."  class="chosen-select form-control" >
  <option value="0"> SELECT  </option>
  <option value="1" name="check1"> 1 </option>
  <option value="2" name="check2"> 2 </option>
  <option value="3" name="check3"> 3</option>
  <option value="4" name="check4"> 4</option>
</select>

  <input type="button"  name="go" id="go" value="Show" class="btn btn-primary btn-md" onclick="issu();"/>

if I select value from 1st dropdown button then click on show I will get the result ao after getting result the same dropdown button should show default value as select

Body:
Add following code to your issue() function,

$('#repttype').val('0');

or
remove onclick attribute and add click handler to #go like below

$('#go').on('click', function(){
    $('#repttype').val('0');
    issue();
});

Note: Don't forgot to Add jQuery, also if you are using these codes in <form> than use preventDefault(); to prevent default submit action.


问:
Input LOG file information into MySQL using Python
I need to take a linux log file and enter the data into a mysql table, and separate each field into columns.  I have been trying to use the LOAD DATA INFILE command. Only problem is, the data is not delimited and I cannot TERMINATE FIELDS BY '' because the file includes spaces in the log message.  If anyone has any idea please let me know

Example of file:

2011-01-17 10:18:20 User xxxxxx requested backup of xxxxx (xxxxx)

2011-01-17 10:18:29 Stopping current full of xxxxxx, request by backuppc (backoff=)

2011-01-17 10:18:33 User xxxxxx requested backup of xxxxxx (xxxxxx )

2011-01-17 10:18:51 Backup canceled on xxxxxx (received signal=ALRM)

2011-01-17 10:18:52 Started full backup on xxxxxx (pid=xxxxxx , share=xxxxxx$)

2011-01-17 10:24:18 Started full backup on xxxxxx (pid=xxxxxx , share=xxxxxx$)

2011-01-17 11:00:01 Next wakeup is 2011-01-17 12:00:01

2011-01-17 12:00:03 Next wakeup is 2011-01-17 13:00:00

2011-01-17 13:00:01 Next wakeup is 2011-01-17 14:00:00

答:
Pre-format this file. I'm assuming the blank lines in your file are not there (otherwise you can remove them using the commented code). Let's say you're using python:

```<code>parsed = open("parsed.txt", 'a')
    with open("log.txt") as f:
    for i, line in enumerate(f):
        # use if your lines have spaces in between
        # if i % 2 == 0:
        parsed.write(line.replace(" ",",",2))
</code>```

Giving you a file like:

```<code>2011-01-17,10:18:20,User xxxxxx requested backup of xxxxx (xxxxx)
2011-01-17,10:18:52,Started full backup on xxxxxx (pid=xxxxxx , share=xxxxxx$)
2011-01-17,10:24:18,Started full backup on xxxxxx (pid=xxxxxx , share=xxxxxx$)
...
</code>```

Now you can:

```<code>LOAD DATA INFILE 'parsed.txt' INTO TABLE db.my_table;
</code>```

Body:
Pre-format this file. I'm assuming the blank lines in your file are not there (otherwise you can remove them using the commented code). Let's say you're using python:

parsed = open("parsed.txt", 'a')
    with open("log.txt") as f:
    for i, line in enumerate(f):
        # use if your lines have spaces in between
        # if i % 2 == 0:
        parsed.write(line.replace(" ",",",2))

Giving you a file like:

2011-01-17,10:18:20,User xxxxxx requested backup of xxxxx (xxxxx)
2011-01-17,10:18:52,Started full backup on xxxxxx (pid=xxxxxx , share=xxxxxx$)
2011-01-17,10:24:18,Started full backup on xxxxxx (pid=xxxxxx , share=xxxxxx$)
...

Now you can:

LOAD DATA INFILE 'parsed.txt' INTO TABLE db.my_table;


问:
Laravel eloquent JSON field, selecting attribute produces extra double quote
This code:

```<code>$translation = Translation::where('language_id', 2)
            ->whereNotNull('data->navigation_login')
            ->select('data->navigation_login as navigation_login')
            ->first()
            ->toArray();
dd($translation);
</code>```

Produces this result:
array(1) {["navigation_login"]=> string(7) ""Login"" }

The problem is the extra double quote arround the login string: ""Login""

How can I eliminate this?

If I run the above code without select:

```<code>$translation = Translation::where('language_id', 2)
            ->whereNotNull('data->navigation_login')
            ->first()
            ->toArray();
dd($translation);
</code>```

No double quotes:

```<code>["data"]=>
  array(3) {
    ["navigation_login"]=>
    string(5) "Login"
    ["navigation_order"]=>
    string(5) "Order"
    ["navigation_registration"]=>
    string(7) "Sign up"
  }
</code>```

Here is the model detail:

```<code>...
class Translation extends Model {

    protected $casts = [
        'data' => 'array',
    ];
...
</code>```

Here is the schema detail:

```<code>...
$table->json('data')->nullable();
...
</code>```

答:
Finally the solution:

MySQL 5.7.13 and later

Using the unquoting extraction operator ->>

->select('data->>navigation_login as navigation_login')

Or older mysql version  5.7 < MYSQL < 5.7.13

->select(\DB::raw("JSON_UNQUOTE(JSON_EXTRACT(data, '$.navigation_login')) as navigation_login"))

ContentLicense: CC BY-SA 4.0

Body:
This code:

$translation = Translation::where('language_id', 2)
            ->whereNotNull('data->navigation_login')
            ->select('data->navigation_login as navigation_login')
            ->first()
            ->toArray();
dd($translation);

Produces this result:
array(1) {["navigation_login"]=> string(7) ""Login"" }

The problem is the extra double quote arround the login string: ""Login""

How can I eliminate this?

If I run the above code without select:

$translation = Translation::where('language_id', 2)
            ->whereNotNull('data->navigation_login')
            ->first()
            ->toArray();
dd($translation);

No double quotes:

["data"]=>
  array(3) {
    ["navigation_login"]=>
    string(5) "Login"
    ["navigation_order"]=>
    string(5) "Order"
    ["navigation_registration"]=>
    string(7) "Sign up"
  }

Here is the model detail:

...
class Translation extends Model {

    protected $casts = [
        'data' => 'array',
    ];
...

Here is the schema detail:

...
$table->json('data')->nullable();
...


答:
Use HashSet for equals and hashCode so that it does not distinguish order.:

```<code>class DataClass {
  String source;
  String destination;
  private final Set<String> content = new HashSet< String >();

  DataClass(String src, String dest) {
    this.source = src;
    this.destination = dest;
    content.add(src);
    content.add(dest);
  }

  // getter setter for source and destination variables

@Override
public boolean equals(Object obj) {
    System.out.println("inside equals");
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (!DataClass.class.equals(obj.getClass()))
        return false;
    DataClass other = (DataClass) obj;
    return content.equals(other.content);
}

public int hashCode() {
    return content.hashCode();
}
</code>```

For further reading to how to implement equals and hashCode, you might want to read https://www.mkyong.com/java/java-how-to-overrides-equals-and-hashcode/

Use LinkedHashSet for finding duplicates:

```<code>public List<DataClass> removeDuplicates(List<DataClass> dataList) {
    return new ArrayList<DataClass>(new LinkedHashSet<DataClass>(dataList));
}
</code>```

Why we use LinkedHashSet instead of HashSet? LinkedHashSet preserves ordering while HashSet does not. Quoted from LinkedHashSet javadoc:

This implementation differs from HashSet in that it maintains a
  doubly-linked list running through all of its entries. This linked
  list defines the iteration ordering, which is the order in which
  elements were inserted into the set (insertion-order).

Title: Remove duplicates Objects from List in Java

Body:
Use HashSet for equals and hashCode so that it does not distinguish order.:

class DataClass {
  String source;
  String destination;
  private final Set<String> content = new HashSet< String >();

  DataClass(String src, String dest) {
    this.source = src;
    this.destination = dest;
    content.add(src);
    content.add(dest);
  }

  // getter setter for source and destination variables

@Override
public boolean equals(Object obj) {
    System.out.println("inside equals");
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (!DataClass.class.equals(obj.getClass()))
        return false;
    DataClass other = (DataClass) obj;
    return content.equals(other.content);
}

public int hashCode() {
    return content.hashCode();
}

For further reading to how to implement equals and hashCode, you might want to read https://www.mkyong.com/java/java-how-to-overrides-equals-and-hashcode/

Use LinkedHashSet for finding duplicates:

public List<DataClass> removeDuplicates(List<DataClass> dataList) {
    return new ArrayList<DataClass>(new LinkedHashSet<DataClass>(dataList));
}

Why we use LinkedHashSet instead of HashSet? LinkedHashSet preserves ordering while HashSet does not. Quoted from LinkedHashSet javadoc:

This implementation differs from HashSet in that it maintains a
  doubly-linked list running through all of its entries. This linked
  list defines the iteration ordering, which is the order in which
  elements were inserted into the set (insertion-order).


问:
Should I have to follow some extra steps to modify httpd.conf file?
I have a dedicated server. Are there some special steps which I have to follow while editing httpd.conf file? I try to revert back the changes but problem is still same.</p>

答: My problem is get solved. Actually the problem is that i have changed the WHM password and that's why it does not connect to my WHMCS and my IP get blocked in firewall. That is the reason i was not able to terminate any account through WHMCS panel. If anyone get the same problem then they first have to check Firewall for IP blocking.</p>