问:
How can I re order only part of a collection in swift?
I have an array of Item. The order is never guaranteed as the collection is served from an API based on a number of user actions elsewhere.

However I need to order this collection by a type field so I can iterate over it elsewhere correctly.

In the case of the example playground below, I need a reordered collection that would follow this logic:

```<code>[
  Item(type: .foo),
  Item(type: .bar),

  Item(type: .boo),
  Item(type: .baz),

  Item(type: .boom),
  Item(type: .bang)

]
</code>```

Specifically .foo and .bar should be the first 2 items, .boom and bang will be the last 2 items.

These fixed items are unique, no duplicates will exist in the response.

Everything left over should be between these 2 groups, in the same order as they are in the original collection.

I have tried to split the item into 2 collections within var output: [Item] and insert the second collection at an index, however the ordering is still off.

How can I achieve this?

import UIKit

enum ItemType: String {
  case foo
  case bar
  case boo
  case baz
  case boom
  case bang
}

struct Item {
  let type: ItemType
}

let props = [
  Item(type: .bang),
  Item(type: .bar),
  Item(type: .baz),
  Item(type: .boo),
  Item(type: .boom),
  Item(type: .foo)
]

/*
 case foo
 case bar
 > ----------- should be ordered in same order as in `props`
 case boom
 case bang
*/

var output: [Item] {
  var fixedPosition: [Item] = []
  var dynamicPosition: [Item] = []

  props.forEach { item in
    if (item.type == .foo || item.type == .bar || item.type == .boom || item.type == .bang ){
      fixedPosition.append(item)
    } else {
      dynamicPosition.append(item)
    }
  }

  var result: [Item] = fixedPosition
  result.insert(contentsOf: dynamicPosition, at: 1)

  return result
}

print(output.map { $0.type })
```

答:
You can give each enum case an int value, and stable sort it:

```<code>func intValue(for itemType: ItemType) -> Int {
    switch itemType {
    case .foo:
        return 0
    case .bar:
        return 1
    case .boo, .baz: // the order of these should remain the same, so they get the same number
        return 2
    case .boom:
        return 3
    case .bang:
        return 4
    }
}

let sorted = props.stableSorted(by: { intValue(for: $0.type) < intValue(for: $1.type) })
</code>```

stableSort is taken from this answer by leavez:

```<code>extension RandomAccessCollection {

    /// return a sorted collection
    /// this use a stable sort algorithm
    ///
    /// - Parameter areInIncreasingOrder: return nil when two element are equal
    /// - Returns: the sorted collection
    public func stableSorted(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> [Element] {

        let sorted = try enumerated().sorted { (one, another) -> Bool in
            if try areInIncreasingOrder(one.element, another.element) {
                return true
            } else {
                return one.offset < another.offset
            }
        }
        return sorted.map { $0.element }
    }
}
</code>```

Body:
I have an array of Item. The order is never guaranteed as the collection is served from an API based on a number of user actions elsewhere.

However I need to order this collection by a type field so I can iterate over it elsewhere correctly.

In the case of the example playground below, I need a reordered collection that would follow this logic:

[
  Item(type: .foo),
  Item(type: .bar),

  Item(type: .boo),
  Item(type: .baz),

  Item(type: .boom),
  Item(type: .bang)

]

Specifically .foo and .bar should be the first 2 items, .boom and bang will be the last 2 items.

These fixed items are unique, no duplicates will exist in the response.

Everything left over should be between these 2 groups, in the same order as they are in the original collection.

I have tried to split the item into 2 collections within var output: [Item] and insert the second collection at an index, however the ordering is still off.

How can I achieve this?

import UIKit

enum ItemType: String {
  case foo
  case bar
  case boo
  case baz
  case boom
  case bang
}

struct Item {
  let type: ItemType
}

let props = [
  Item(type: .bang),
  Item(type: .bar),
  Item(type: .baz),
  Item(type: .boo),
  Item(type: .boom),
  Item(type: .foo)
]

/*
 case foo
 case bar
 > ----------- should be ordered in same order as in `props`
 case boom
 case bang
*/

var output: [Item] {
  var fixedPosition: [Item] = []
  var dynamicPosition: [Item] = []

  props.forEach { item in
    if (item.type == .foo || item.type == .bar || item.type == .boom || item.type == .bang ){
      fixedPosition.append(item)
    } else {
      dynamicPosition.append(item)
    }
  }

  var result: [Item] = fixedPosition
  result.insert(contentsOf: dynamicPosition, at: 1)

  return result
}

print(output.map { $0.type })

Body:
You can give each enum case an int value, and stable sort it:

func intValue(for itemType: ItemType) -> Int {
    switch itemType {
    case .foo:
        return 0
    case .bar:
        return 1
    case .boo, .baz: // the order of these should remain the same, so they get the same number
        return 2
    case .boom:
        return 3
    case .bang:
        return 4
    }
}

let sorted = props.stableSorted(by: { intValue(for: $0.type) < intValue(for: $1.type) })

stableSort is taken from this answer by leavez:

extension RandomAccessCollection {

    /// return a sorted collection
    /// this use a stable sort algorithm
    ///
    /// - Parameter areInIncreasingOrder: return nil when two element are equal
    /// - Returns: the sorted collection
    public func stableSorted(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> [Element] {

        let sorted = try enumerated().sorted { (one, another) -> Bool in
            if try areInIncreasingOrder(one.element, another.element) {
                return true
            } else {
                return one.offset < another.offset
            }
        }
        return sorted.map { $0.element }
    }
}


来源: stackexchange

问:
legend not visible in d3.js pie chart
I am trying to add legend to pie chart. I can see the legend element added in the inspect element but I am not able to see it. Could it be due to background color ? I looked into other questions but I am not able to solve the problem.

Can somebody explain what is wrong with my code ?

I also pasted the image below showing that the legend is attached to the svg.

Here is the code snippet

<!DOCTYPE html>

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

```

答:
You simply missed to set a proper with for the content, but what you have to actually do is to implement margin convention for your chart:

<!DOCTYPE html>

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

```

ContentLicense: CC BY-SA 4.0

Title: legend not visible in d3.js pie chart

Body:
You simply missed to set a proper with for the content, but what you have to actually do is to implement margin convention for your chart:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>barchart</title>
  <script type="text/javascript" src="https://d3js.org/d3.v5.min.js"></script>
</head>

<body>
  <div id="piechart">

  </div>
  <script>
    //chart dimensions

    var width = 500;
    var height = 300;
    var radius = Math.min(width, height) / 2;
    var labelHeight = 18;
    var data = {
      2011: 9,
      2012: 12,
      2013: 10,
      2014: 8,
      2015: 12,
      2016: 20
    }

    //color scale
    var color = d3.scaleOrdinal().range(["#126608", "#049a0d", "#587b08", "#048440", "#177c0a", "#4a8d36", "#3b712b", "#4a8b00", "#426b07", "#4b940b"]);

    //arc

    var arc = d3.arc()
      .outerRadius(radius - 10)
      .innerRadius(0);

    var pie = d3.pie()
      .value(function(d) {
        return d.value;
      })

    var svg = d3.select("#piechart").append("svg")
      .attr("width", width)
      .attr("height", height)
      .append("g")
      .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

    var pie_data = pie(d3.entries(data))

    //svg.selectAll("path").remove()

    var g = svg.selectAll("path")
      .data(pie_data)
      .enter().append("g")
      .attr("class", "arc");

    g.append("path")
      .attr("d", arc)
      .style("fill", function(d) {
        return color(d.data.key)
      });

    g.append("text")
      .attr("transform", function(d) {
        return "translate(" + arc.centroid(d) + ")";
      })
      .attr("dy", ".35em")
      .style("text-anchor", "middle")
      .attr("fill", "white")
      .text(function(d) {
        return d.data.key
      });

    var legend = svg.append("g")
      .attr("class", "legend")
      .attr("font-family", "sans-serif")
      .attr("font-size", 20)
      .attr("text-anchor", "start")
      .selectAll("g")
      .data(pie_data)
      .enter().append("g")
      .attr("transform", function(d, i) {
        return "translate(0," + i * 30 + ")";
      });

    legend.append("text")
      .attr("x", radius + 30)
      .attr("y", 9.5)
      .attr("dy", "0.32em")
      .text(function(d) {
        return d.data.key;
      });

    legend.append("rect")
      .attr("x", radius + 10)
      .attr("width", 19)
      .attr("height", 19)
      .attr("fill", function(d) {
        return color(d.data.key);
      });
  </script>
</body>

</html>


问:
Why can the compiler not optimize floating point addition with 0?
I have four identity functions which do essentially nothing. Only multiplication with 1 could be optimized by clang to a single ret statement.

float id0(float x) {
    return x + 1 - 1;
}

float id1(float x) {
    return x + 0;
}

float id2(float x) {
    return x * 2 / 2;
}

float id3(float x) {
    return x * 1;
}
```

<p>And the following compiler output is: (clang 10, at -O3)</p>

```.LCPI0_0:
        .long   1065353216              # float 1
.LCPI0_1:
        .long   3212836864              # float -1
id0(float):                                # @id0(float)
        addss   xmm0, dword ptr [rip + .LCPI0_0]
        addss   xmm0, dword ptr [rip + .LCPI0_1]
        ret
id1(float):                                # @id1(float)
        xorps   xmm1, xmm1
        addss   xmm0, xmm1
        ret
.LCPI2_0:
        .long   1056964608              # float 0.5
id2(float):                                # @id2(float)
        addss   xmm0, xmm0
        mulss   xmm0, dword ptr [rip + .LCPI2_0]
        ret
id3(float):                                # @id3(float)
        ret
```

I can understand why id0 and id2 can't be optimized. They increase the value which could then turn into positive infinity and the second operation would not change it back.

But why can't id1 be optimized? Additon with infinity would yield infinity, addition with any regular number would yield that number and addition with NaN would yield NaN. So why is it not a "true" identity operation like * 1.

Example with Compiler Explorer

答:
IEEE 754 floating-point numbers have two zero values, one negative, one positive. When added together, the result is the positive one.

So id1(-0.f) is 0.f, not -0.f.

Note that id1(-0.f) == -0.f because 0.f == -0.f.

Demo

Also, note that compiling with -ffast-math in GCC does make the optimization and changes the result.

Body:
I have four identity functions which do essentially nothing. Only multiplication with 1 could be optimized by clang to a single ret statement.

float id0(float x) {
    return x + 1 - 1;
}

float id1(float x) {
    return x + 0;
}

float id2(float x) {
    return x * 2 / 2;
}

float id3(float x) {
    return x * 1;
}

And the following compiler output is: (clang 10, at -O3)

.LCPI0_0:
        .long   1065353216              # float 1
.LCPI0_1:
        .long   3212836864              # float -1
id0(float):                                # @id0(float)
        addss   xmm0, dword ptr [rip + .LCPI0_0]
        addss   xmm0, dword ptr [rip + .LCPI0_1]
        ret
id1(float):                                # @id1(float)
        xorps   xmm1, xmm1
        addss   xmm0, xmm1
        ret
.LCPI2_0:
        .long   1056964608              # float 0.5
id2(float):                                # @id2(float)
        addss   xmm0, xmm0
        mulss   xmm0, dword ptr [rip + .LCPI2_0]
        ret
id3(float):                                # @id3(float)
        ret

I can understand why id0 and id2 can't be optimized. They increase the value which could then turn into positive infinity and the second operation would not change it back.

But why can't id1 be optimized? Additon with infinity would yield infinity, addition with any regular number would yield that number and addition with NaN would yield NaN. So why is it not a "true" identity operation like * 1.

Example with Compiler Explorer


问:
`window.open` on the second monitor in Chrome
When I'm using firefox and then using window.open('blah.com','blah','left=-30,top=-300');, the popup opens in my second display above my first one but in chrome, the popup just opens at left=0,top=0. Is there a reason why chrome is doing this and how would I fix the problem?

Thanks!

答:
Take a look at this StackOverflow's post Center a popup window on screen?

I've made a little upgrade for that function a couple of years ago.

```<code>function multipleScreenPopup(url, title, w, h, centered = true, moveRight = 0, moveDown = 0, resizable = "no") {
  // Fixes dual-screen position                         Most browsers      Firefox
  var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left;
  var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top;

  var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
  var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;

  var left = 0;
  var top = 0;
  if (centered === true) {
    left = ((width / 2) - (w / 2)) + dualScreenLeft;
    top = ((height / 2) - (h / 2)) + dualScreenTop;
  } else {
    left = dualScreenLeft + moveRight;
    top = dualScreenTop + moveDown;
  }

  var newWindow = window.open(url, title, 'directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=' + resizable + ', width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);

  // Puts focus on the newWindow
  if (window.focus) {
    newWindow.focus();
    }

}

// centered as of the monitor that fired on it
multipleScreenPopup('https://google.com', '_blank', 500, 500);

// move from the left and from the top
multipleScreenPopup('https://yahoo.com', '_blank', 500, 500, false, 200, 200);
</code>```

Body:
Take a look at this StackOverflow's post Center a popup window on screen?

I've made a little upgrade for that function a couple of years ago.

function multipleScreenPopup(url, title, w, h, centered = true, moveRight = 0, moveDown = 0, resizable = "no") {
  // Fixes dual-screen position                         Most browsers      Firefox
  var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left;
  var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top;

  var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
  var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;

  var left = 0;
  var top = 0;
  if (centered === true) {
    left = ((width / 2) - (w / 2)) + dualScreenLeft;
    top = ((height / 2) - (h / 2)) + dualScreenTop;
  } else {
    left = dualScreenLeft + moveRight;
    top = dualScreenTop + moveDown;
  }

  var newWindow = window.open(url, title, 'directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=' + resizable + ', width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);

  // Puts focus on the newWindow
  if (window.focus) {
    newWindow.focus();
    }

}

// centered as of the monitor that fired on it
multipleScreenPopup('https://google.com', '_blank', 500, 500);

// move from the left and from the top
multipleScreenPopup('https://yahoo.com', '_blank', 500, 500, false, 200, 200);


问:
I have a warning "passing argument 2 of 'bins' make integer from pointer without cast"
In a binary search, I have the warning I wrote in the title:

```<code>    #include <stdio.h>
    int bins(int, int, int, int);/*this function do a binary search*/

    int main()
    {
        int n, low, high, v[]={0,1,2,3,4,5,6,7,8,9,10};
        low=0;high=11;
        printf("please enter the num you want to find\n:");
        scanf("%d", &n);
        printf("%d", bins(n, v, low, high));
    return 0;
    }
    int bins(int n, int v[], int low, int high)
    {
        int mid;
        if(low>high)
        {
            return -1;
        }
        mid=(high+low)/2;
        if(v[mid]>n)
        {
            bins(n, v, low, high-mid);
        }
        if(v[mid]<n)
        {
            bins(n, v, low+mid, high);
        }
        return mid;
    }
</code>```

Considering that the array is organized.

I have a warning "passing argument 2 of 'bins' make integer from pointer without cast".

答:
The head of the defintion of bins:

```<code>int bins(int n, int v[], int low, int high) { ...
</code>```

is different to the function´s prototype:

```<code>int bins(int, int, int, int);      /*this function do a binary search*/
</code>```

at the second parameter definition.

In the former the second parameter is of type pointer to int.
In the latter the second parameter is of type int.

There is a mismatch.

Correct the second parameter at the function´s prototype:

```<code>int bins(int, int[], int, int);      /*this function do a binary search*/
                 |
                Here
</code>```

and the code compiles without warnings.

Side note:

The algorithm in bins() seems faulty. It will always return mid = 5, no matter what n is, because mid is only assigned by (high+low) / 2.

Body:
In a binary search, I have the warning I wrote in the title:

    #include <stdio.h>
    int bins(int, int, int, int);/*this function do a binary search*/

    int main()
    {
        int n, low, high, v[]={0,1,2,3,4,5,6,7,8,9,10};
        low=0;high=11;
        printf("please enter the num you want to find\n:");
        scanf("%d", &n);
        printf("%d", bins(n, v, low, high));
    return 0;
    }
    int bins(int n, int v[], int low, int high)
    {
        int mid;
        if(low>high)
        {
            return -1;
        }
        mid=(high+low)/2;
        if(v[mid]>n)
        {
            bins(n, v, low, high-mid);
        }
        if(v[mid]<n)
        {
            bins(n, v, low+mid, high);
        }
        return mid;
    }

Considering that the array is organized.

I have a warning "passing argument 2 of 'bins' make integer from pointer without cast".

Body:
The head of the defintion of bins:

int bins(int n, int v[], int low, int high) { ...

is different to the function´s prototype:

int bins(int, int, int, int);      /*this function do a binary search*/

at the second parameter definition.

In the former the second parameter is of type pointer to int.
In the latter the second parameter is of type int.

There is a mismatch.

Correct the second parameter at the function´s prototype:

int bins(int, int[], int, int);      /*this function do a binary search*/
                 |
                Here

and the code compiles without warnings.

Side note:

The algorithm in bins() seems faulty. It will always return mid = 5, no matter what n is, because mid is only assigned by (high+low) / 2.


问:
Package 'Microsoft.EntityFrameworkCore.SqlServer' is incompatible with 'all' frameworks in the project
I was trying to add the package named Microsoft.EntityFrameworkCore.SqlServer by running the command.

```<code>dotnet add package Microsoft.EntityFrameworkCore.SqlServer
</code>```

in Visual Studio Code, but I get this error:

Package Microsoft.EntityFrameworkCore.SqlServer 2.0.0 is not compatible with netcoreapp1.1 (.NETCoreApp,Version=v1.1). Package Microsoft.EntityFrameworkCore.SqlServer 2.0.0 supports: netstandard2.0" (.NETStandard,Version=v2.0). Package 'Microsoft.EntityFrameworkCore.SqlServer' is incompatible with 'all' frameworks in project 'C:\users\username..'

答:
This Might Be Happening due to generated NuGet Cache While Installing Packages.
Go to Tools>Options>NuGet Package Manager>General and "Clear All NuGet Cache".
This Worked in my case(VS Community 2019).

Also try to update Source of nuget.org by going to Tools>Options>NuGet Package Manager>Package Source and click Update Source in case of VS 2017.

ContentLicense: CC BY-SA 3.0

Body:
I was trying to add the package named Microsoft.EntityFrameworkCore.SqlServer by running the command.

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

in Visual Studio Code, but I get this error:

Package Microsoft.EntityFrameworkCore.SqlServer 2.0.0 is not compatible with netcoreapp1.1 (.NETCoreApp,Version=v1.1). Package Microsoft.EntityFrameworkCore.SqlServer 2.0.0 supports: netstandard2.0" (.NETStandard,Version=v2.0). Package 'Microsoft.EntityFrameworkCore.SqlServer' is incompatible with 'all' frameworks in project 'C:\users\username..'


问:
Logo Centered in Menu
I'm creating a menu using Bulma CSS. I have the following logo:

And I would like to use it much like the Atlantic did, in the center of the page. However, I'm not sure how; I've tried margin-auto:0, but that didn't work out. I also tried messing with the margins, and flexbox and inline-block, but to no avail. Any help is appreciated.

Here is the page thus far (on Codepen): https://codepen.io/Refath/full/ZEQzOQX

Additional Information: The Navbar is currently using one of Bulma's Components, as follows in the snippet below:

```<code>     <nav class="navbar" role="navigation" aria-label="main navigation">
<form id="demo-2">
    <input type="search" placeholder="Search">
</form>
  <div id="navbarBasicExample" class="navbar-menu">
    <div class="navbar-start">
      <a class="navbar-item">
        Math
      </a>

      <a class="navbar-item">
        Science
      </a>
      <a class="navbar-item">
        Politics
      </a>

      <a class="navbar-item">
        Economics
      </a>

      <a class="navbar-item">
        Education
      </a>

      <a class="navbar-item">
        Literature
      </a>

      <div class="navbar-item has-dropdown is-hoverable">
        <a class="navbar-link">
          More
        </a>

        <div class="navbar-dropdown">
          <a class="navbar-item">
            About
          </a>
          <a class="navbar-item">
            Jobs
          </a>
          <a class="navbar-item">
            Contact
          </a>
          <hr class="navbar-divider">
          <a class="navbar-item">
            Report an issue
          </a>
        </div>
      </div>
    </div>

    <div class="navbar-end">
      <div class="navbar-item">
        <div class="buttons">
          <a class="button is-primary">
            <strong>Sign up</strong>
          </a>
        </div>
      </div>
    </div>
  </div>
</nav>
</code>```

答:
Use margin: 0 auto; or margin: auto;

It will work like this,

margin: auto; will be margin automatic from all four sides, and in case of

margin: 0 auto;. it will be 0 from top and bottom and auto from left and right.

Title: Logo Centered in Menu

Body:
I'm creating a menu using Bulma CSS. I have the following logo:

And I would like to use it much like the Atlantic did, in the center of the page. However, I'm not sure how; I've tried margin-auto:0, but that didn't work out. I also tried messing with the margins, and flexbox and inline-block, but to no avail. Any help is appreciated.

Here is the page thus far (on Codepen): https://codepen.io/Refath/full/ZEQzOQX

Additional Information: The Navbar is currently using one of Bulma's Components, as follows in the snippet below:

<form id="demo-2">
    <input type="search" placeholder="Search">
</form>

        Math

        Science

        Politics

        Economics

        Education

        Literature

          More

            About

            Jobs

            Contact

            Report an issue

            Sign up


问:
How to create a type parametric abstract type in F#?
I would like to create an abstract type the following way:

```<code>type IResource =
    abstract member List    : string -> List<'T>
</code>```

When I implement it I need a concrete type instead of 'T (for example int).

```<code>type Website(stage: string) =
    member this.List    stage = (this :> IResource).List    stage
    interface IResource with
      member this.List    stage = []
</code>```

Is it possible to have that in F#? If I give a type to List in the implementation the type checker complains that I use int instead of 'T.

答:
Make your interface explicitly generic by providing type parameter for inteface type:

```<code>type IResource<'T> =
    abstract member List : string -> List<'T>
</code>```

And then you can specify type when implementing the interface

```<code>type Website(stage: string) =
    member this.List stage = (this :> IResource<int>).List    stage
    interface IResource<int> with
      member this.List stage = []
</code>```

Body:
I would like to create an abstract type the following way:

type IResource =
    abstract member List    : string -> List<'T>

When I implement it I need a concrete type instead of 'T (for example int).

type Website(stage: string) =
    member this.List    stage = (this :> IResource).List    stage
    interface IResource with
      member this.List    stage = []

Is it possible to have that in F#? If I give a type to List in the implementation the type checker complains that I use int instead of 'T.

Body:
Make your interface explicitly generic by providing type parameter for inteface type:

type IResource<'T> =
    abstract member List : string -> List<'T>

And then you can specify type when implementing the interface

type Website(stage: string) =
    member this.List stage = (this :> IResource<int>).List    stage
    interface IResource<int> with
      member this.List stage = []


问:
python: efficient way to get an item by numerical index from an OrderedDict
Is there a way to implement an equivalent of the item method shown below, which gives the same functionality without copying all the data or looping?  So in this example it would return ('bar', 20).

```<code>from collections import OrderedDict

class MyOrderedDict(OrderedDict):

    def item(self, index):
        return list(self.items())[index]

d = MyOrderedDict()
d["foo"] = 10
d["bar"] = 20
d["baz"] = 25

print(d.item(1))
</code>```

答:
You can try

```<code>from collections import OrderedDict

class MyOrderedDict(OrderedDict):
    name_to_index = {}
    def item(self, index):
        return tuple([self.name_to_index[index], self[self.name_to_index[index]]])

    def __setitem__(self, key, value):
        self.name_to_index[len(self.name_to_index)] = key
        super().__setitem__(key, value)

d = MyOrderedDict()
d["foo"] = 10
d["bar"] = 20
d["baz"] = 25

print(d.item(1))
</code>```

Output

```<code>('bar', 20)
</code>```

This code will store in each assignment of value the index and the key and when you will call item with an index it will return the relevant value for the index position.

Body:
Is there a way to implement an equivalent of the item method shown below, which gives the same functionality without copying all the data or looping?  So in this example it would return ('bar', 20).

from collections import OrderedDict

class MyOrderedDict(OrderedDict):

    def item(self, index):
        return list(self.items())[index]

d = MyOrderedDict()
d["foo"] = 10
d["bar"] = 20
d["baz"] = 25

print(d.item(1))

Body:
You can try

from collections import OrderedDict

class MyOrderedDict(OrderedDict):
    name_to_index = {}
    def item(self, index):
        return tuple([self.name_to_index[index], self[self.name_to_index[index]]])

    def __setitem__(self, key, value):
        self.name_to_index[len(self.name_to_index)] = key
        super().__setitem__(key, value)

d = MyOrderedDict()
d["foo"] = 10
d["bar"] = 20
d["baz"] = 25

print(d.item(1))

Output

('bar', 20)

This code will store in each assignment of value the index and the key and when you will call item with an index it will return the relevant value for the index position.


问:
Unable to read csv file using spark read in azure databricks
My data is located in azure cosmos DB, I have mounted the dataset on azure databricks.

I can read a csv file using pandas and load it to a spark dataframe.

```<code>df = pd.read_csv('/dbfs/mnt/ajviswan/forest_efficiency/2020-04-26_2020-05-26.csv')
sdf = spark.createDataFrame(df)
sdf.head()
</code>```

This works with the following output to console, I can do further processing with this data frame.

```<code>(1) Spark Jobs
sdf:pyspark.sql.dataframe.DataFrame = [Forest: string, LoadBalanceMoveReason: string ... 4 more fields]
Out[34]: Row(Forest='AUSP282', LoadBalanceMoveReason='DefaultEncryption', CompletionDate='5/26/2020 12:00:00 AM', efficiencyRopCount=None, efficiencySize=0.9966470723725392, efficiencyIOPS=None)
</code>```

But when I try to read the file directly using spark dataframe, it fails with a read error.

```<code>df = spark.read.csv('/dbfs/mnt/ajviswan/forest_efficiency/2020-04-26_2020-05-26.csv')
df
</code>```

Returns

```<code>Py4JJavaError                             Traceback (most recent call last)
<command-4117735793908621> in <module>
----> 1 df = spark.read.csv('/dbfs/mnt/ajviswan/forest_efficiency/2020-04-26_2020-05-26.csv')
      2 df

/databricks/spark/python/pyspark/sql/readwriter.py in csv(self, path, schema, sep, encoding, quote, escape, comment, header, inferSchema, ignoreLeadingWhiteSpace, ignoreTrailingWhiteSpace, nullValue, nanValue, positiveInf, negativeInf, dateFormat, timestampFormat, maxColumns, maxCharsPerColumn, maxMalformedLogPerPartition, mode, columnNameOfCorruptRecord, multiLine, charToEscapeQuoteEscaping, samplingRatio, enforceSchema, emptyValue, locale, lineSep, pathGlobFilter, recursiveFileLookup)
    533             path = [path]
    534         if type(path) == list:
--> 535             return self._df(self._jreader.csv(self._spark._sc._jvm.PythonUtils.toSeq(path)))
    536         elif isinstance(path, RDD):
    537             def func(iterator):

/databricks/spark/python/lib/py4j-0.10.9-src.zip/py4j/java_gateway.py in __call__(self, *args)
   1303         answer = self.gateway_client.send_command(command)
   1304         return_value = get_return_value(
-> 1305             answer, self.gateway_client, self.target_id, self.name)
   1306
   1307         for temp_arg in temp_args:

/databricks/spark/python/pyspark/sql/utils.py in deco(*a, **kw)
     96     def deco(*a, **kw):
     97         try:
---> 98             return f(*a, **kw)
     99         except py4j.protocol.Py4JJavaError as e:
    100             converted = convert_exception(e.java_exception)

/databricks/spark/python/lib/py4j-0.10.9-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
    326                 raise Py4JJavaError(
    327                     "An error occurred while calling {0}{1}{2}.\n".
--> 328                     format(target_id, ".", name), value)
    329             else:
    330                 raise Py4JError(

Py4JJavaError: An error occurred while calling o3781.csv.
: java.lang.NoClassDefFoundError: org/apache/spark/sql/sources/v2/ReadSupport
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:756)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:468)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at com.databricks.backend.daemon.driver.ClassLoaders$LibraryClassLoader.loadClass(ClassLoaders.scala:151)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:756)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:468)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at com.databricks.backend.daemon.driver.ClassLoaders$LibraryClassLoader.loadClass(ClassLoaders.scala:151)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at com.databricks.backend.daemon.driver.ClassLoaders$ReplWrappingClassLoader.loadClass(ClassLoaders.scala:65)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:405)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:370)
    at java.util.ServiceLoader$LazyIterator.access$700(ServiceLoader.java:323)
    at java.util.ServiceLoader$LazyIterator$2.run(ServiceLoader.java:407)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:409)
    at java.util.ServiceLoader$1.next(ServiceLoader.java:480)
    at scala.collection.convert.Wrappers$JIteratorWrapper.next(Wrappers.scala:44)
    at scala.collection.Iterator.foreach(Iterator.scala:941)
    at scala.collection.Iterator.foreach$(Iterator.scala:941)
    at scala.collection.AbstractIterator.foreach(Iterator.scala:1429)
    at scala.collection.IterableLike.foreach(IterableLike.scala:74)
    at scala.collection.IterableLike.foreach$(IterableLike.scala:73)
    at scala.collection.AbstractIterable.foreach(Iterable.scala:56)
    at scala.collection.TraversableLike.filterImpl(TraversableLike.scala:255)
    at scala.collection.TraversableLike.filterImpl$(TraversableLike.scala:249)
    at scala.collection.AbstractTraversable.filterImpl(Traversable.scala:108)
    at scala.collection.TraversableLike.filter(TraversableLike.scala:347)
    at scala.collection.TraversableLike.filter$(TraversableLike.scala:347)
    at scala.collection.AbstractTraversable.filter(Traversable.scala:108)
    at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:696)
    at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSourceV2(DataSource.scala:780)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:317)
    at org.apache.spark.sql.DataFrameReader.csv(DataFrameReader.scala:807)
    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:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:380)
    at py4j.Gateway.invoke(Gateway.java:295)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:251)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassNotFoundException: org.apache.spark.sql.sources.v2.ReadSupport
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at com.databricks.backend.daemon.driver.ClassLoaders$LibraryClassLoader.loadClass(ClassLoaders.scala:151)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
</code>```

答:
To read via spark methods from mounted storage you shouldn't include the /dbfs prefix:

```<code>df = spark.read.csv('/mnt/ajviswan/forest_efficiency/2020-04-26_2020-05-26.csv')
</code>```

Body:
My data is located in azure cosmos DB, I have mounted the dataset on azure databricks.

I can read a csv file using pandas and load it to a spark dataframe.

df = pd.read_csv('/dbfs/mnt/ajviswan/forest_efficiency/2020-04-26_2020-05-26.csv')
sdf = spark.createDataFrame(df)
sdf.head()

This works with the following output to console, I can do further processing with this data frame.

(1) Spark Jobs
sdf:pyspark.sql.dataframe.DataFrame = [Forest: string, LoadBalanceMoveReason: string ... 4 more fields]
Out[34]: Row(Forest='AUSP282', LoadBalanceMoveReason='DefaultEncryption', CompletionDate='5/26/2020 12:00:00 AM', efficiencyRopCount=None, efficiencySize=0.9966470723725392, efficiencyIOPS=None)

But when I try to read the file directly using spark dataframe, it fails with a read error.

df = spark.read.csv('/dbfs/mnt/ajviswan/forest_efficiency/2020-04-26_2020-05-26.csv')
df

Returns

Py4JJavaError                             Traceback (most recent call last)
<command-4117735793908621> in <module>
----> 1 df = spark.read.csv('/dbfs/mnt/ajviswan/forest_efficiency/2020-04-26_2020-05-26.csv')
      2 df

/databricks/spark/python/pyspark/sql/readwriter.py in csv(self, path, schema, sep, encoding, quote, escape, comment, header, inferSchema, ignoreLeadingWhiteSpace, ignoreTrailingWhiteSpace, nullValue, nanValue, positiveInf, negativeInf, dateFormat, timestampFormat, maxColumns, maxCharsPerColumn, maxMalformedLogPerPartition, mode, columnNameOfCorruptRecord, multiLine, charToEscapeQuoteEscaping, samplingRatio, enforceSchema, emptyValue, locale, lineSep, pathGlobFilter, recursiveFileLookup)
    533             path = [path]
    534         if type(path) == list:
--> 535             return self._df(self._jreader.csv(self._spark._sc._jvm.PythonUtils.toSeq(path)))
    536         elif isinstance(path, RDD):
    537             def func(iterator):

/databricks/spark/python/lib/py4j-0.10.9-src.zip/py4j/java_gateway.py in __call__(self, *args)
   1303         answer = self.gateway_client.send_command(command)
   1304         return_value = get_return_value(
-> 1305             answer, self.gateway_client, self.target_id, self.name)
   1306
   1307         for temp_arg in temp_args:

/databricks/spark/python/pyspark/sql/utils.py in deco(*a, **kw)
     96     def deco(*a, **kw):
     97         try:
---> 98             return f(*a, **kw)
     99         except py4j.protocol.Py4JJavaError as e:
    100             converted = convert_exception(e.java_exception)

/databricks/spark/python/lib/py4j-0.10.9-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
    326                 raise Py4JJavaError(
    327                     "An error occurred while calling {0}{1}{2}.\n".
--> 328                     format(target_id, ".", name), value)
    329             else:
    330                 raise Py4JError(

Py4JJavaError: An error occurred while calling o3781.csv.
: java.lang.NoClassDefFoundError: org/apache/spark/sql/sources/v2/ReadSupport
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:756)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:468)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at com.databricks.backend.daemon.driver.ClassLoaders$LibraryClassLoader.loadClass(ClassLoaders.scala:151)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:756)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:468)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at com.databricks.backend.daemon.driver.ClassLoaders$LibraryClassLoader.loadClass(ClassLoaders.scala:151)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at com.databricks.backend.daemon.driver.ClassLoaders$ReplWrappingClassLoader.loadClass(ClassLoaders.scala:65)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:405)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:370)
    at java.util.ServiceLoader$LazyIterator.access$700(ServiceLoader.java:323)
    at java.util.ServiceLoader$LazyIterator$2.run(ServiceLoader.java:407)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:409)
    at java.util.ServiceLoader$1.next(ServiceLoader.java:480)
    at scala.collection.convert.Wrappers$JIteratorWrapper.next(Wrappers.scala:44)
    at scala.collection.Iterator.foreach(Iterator.scala:941)
    at scala.collection.Iterator.foreach$(Iterator.scala:941)
    at scala.collection.AbstractIterator.foreach(Iterator.scala:1429)
    at scala.collection.IterableLike.foreach(IterableLike.scala:74)
    at scala.collection.IterableLike.foreach$(IterableLike.scala:73)
    at scala.collection.AbstractIterable.foreach(Iterable.scala:56)
    at scala.collection.TraversableLike.filterImpl(TraversableLike.scala:255)
    at scala.collection.TraversableLike.filterImpl$(TraversableLike.scala:249)
    at scala.collection.AbstractTraversable.filterImpl(Traversable.scala:108)
    at scala.collection.TraversableLike.filter(TraversableLike.scala:347)
    at scala.collection.TraversableLike.filter$(TraversableLike.scala:347)
    at scala.collection.AbstractTraversable.filter(Traversable.scala:108)
    at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:696)
    at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSourceV2(DataSource.scala:780)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:317)
    at org.apache.spark.sql.DataFrameReader.csv(DataFrameReader.scala:807)
    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:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:380)
    at py4j.Gateway.invoke(Gateway.java:295)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:251)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassNotFoundException: org.apache.spark.sql.sources.v2.ReadSupport
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at com.databricks.backend.daemon.driver.ClassLoaders$LibraryClassLoader.loadClass(ClassLoaders.scala:151)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)

Body:
To read via spark methods from mounted storage you shouldn't include the /dbfs prefix:

df = spark.read.csv('/mnt/ajviswan/forest_efficiency/2020-04-26_2020-05-26.csv')


问:
How to skip empty dates (weekends) in a financial Matplotlib Python graph?
```<code>ax.plot_date((dates, dates), (highs, lows), '-')
</code>```

I'm currently using this command to plot financial highs and lows using Matplotlib. It works great, but how do I remove the blank spaces in the x-axis left by days without market data, such as weekends and holidays?

I have lists of dates, highs, lows, closes and opens. I can't find any examples of creating a graph with an x-axis that show dates but doesn't enforce a constant scale.

答:
You can simply change dates to strings:</p>

```<code>import matplotlib.pyplot as plt
import datetime

f = plt.figure(1, figsize=(10,5))
ax = f.add_subplot(111)

today = datetime.datetime.today().date()
yesterday = today - datetime.timedelta(days=1)
three_days_later = today + datetime.timedelta(days=3)

x_values = [yesterday, today, three_days_later]
y_values = [75, 80, 90]

x_values = [f'{x:%Y-%m-%d}' for x in x_values]
ax.bar(x_values, y_values, color='green')
plt.show()
</code>```

ContentLicense: CC BY-SA 2.5

Body:
ax.plot_date((dates, dates), (highs, lows), '-')

I'm currently using this command to plot financial highs and lows using Matplotlib. It works great, but how do I remove the blank spaces in the x-axis left by days without market data, such as weekends and holidays?

I have lists of dates, highs, lows, closes and opens. I can't find any examples of creating a graph with an x-axis that show dates but doesn't enforce a constant scale.

Body:
You can simply change dates to strings:

import matplotlib.pyplot as plt
import datetime

f = plt.figure(1, figsize=(10,5))
ax = f.add_subplot(111)

today = datetime.datetime.today().date()
yesterday = today - datetime.timedelta(days=1)
three_days_later = today + datetime.timedelta(days=3)

x_values = [yesterday, today, three_days_later]
y_values = [75, 80, 90]

x_values = [f'{x:%Y-%m-%d}' for x in x_values]
ax.bar(x_values, y_values, color='green')
plt.show()


问:
How to use Win32Api in C# Windows Service App
I'm creating a windows service app in visual studio and I want to get the currently active window title.
below is the code I have tried but the function GetForegroundWindow() returns 0 every time.
Is it okay to use win32api in windows services? </p>

```<code>public partial class My_Service: ServiceBase
{
    Timer timer = new Timer();
    [DllImport("User32.dll")]
    static extern IntPtr GetForegroundWindow();

    [DllImport("User32.dll")]
    static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

    public My_Service()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        WriteToFile("Service is started at " + DateTime.Now);
        timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
        timer.Interval = 10000; //number in milisecinds
        timer.Enabled = true;
    }

    protected override void OnStop()
    {
        WriteToFile("Service is stopped at " + DateTime.Now);
    }

    private void OnElapsedTime(object source, ElapsedEventArgs e)
    {
        string title = GetActivewindow();
        WriteToFile("Service is recall at " + title + DateTime.Now);

    }

    public void WriteToFile(string Message)
    {
       ....
    }

    public string GetActivewindow()
    {
        const int nChars = 256;
        StringBuilder buff = new StringBuilder(nChars);
        string title = "- ";
        IntPtr handle;
        handle = GetForegroundWindow();
        if( GetWindowText(handle,buff,nChars) > 0)
        {
            title = buff.ToString();
        }
        return title;
    }
}
</code>```

答:
As comments, and also according to the document: About Window Stations and Desktops - Window Station and Desktop Creation.

Your service may be running under Service-0x0-3e7$\default, but the foreground window you want to retrieve is in the default desktop of the interactive window station (Winsta0\default)

The interactive window station is the only window station that can
  display a user interface or receive user input. It is assigned to the
  logon session of the interactive user, and contains the keyboard,
  mouse, and display device. It is always named "WinSta0". All other
  window stations are noninteractive, which means they cannot display a
  user interface or receive user input.

That means you cannot use GetForegroundWindow directly from the service. You could create a child process in Winsta0\default and redirect its output. Then call GetForegroundWindow in the child process and output.

Sample(removed error checking):

Child:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;
namespace ConsoleApp1
{
    class Program
    {
        [DllImport("User32.dll")]
        static extern IntPtr GetForegroundWindow();

        [DllImport("User32.dll")]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
        static void Main(string[] args)
        {
            const int nChars = 256;
            StringBuilder buff = new StringBuilder(nChars);
            string title = "- ";
            IntPtr handle;
            handle = GetForegroundWindow();
            if (GetWindowText(handle, buff, nChars) > 0)
            {
                title = buff.ToString();
            }
            Console.WriteLine(title);
            return;
        }
    }
}
</code>```

Service:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.IO;
using System.Diagnostics.Tracing;

namespace WindowsService3
{
    public partial class MyNewService : ServiceBase
    {
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        internal struct STARTUPINFO
        {
            public Int32 cb;
            public string lpReserved;
            public string lpDesktop;
            public string lpTitle;
            public Int32 dwX;
            public Int32 dwY;
            public Int32 dwXSize;
            public Int32 dwYSize;
            public Int32 dwXCountChars;
            public Int32 dwYCountChars;
            public Int32 dwFillAttribute;
            public Int32 dwFlags;
            public Int16 wShowWindow;
            public Int16 cbReserved2;
            public IntPtr lpReserved2;
            public IntPtr hStdInput;
            public IntPtr hStdOutput;
            public IntPtr hStdError;
        }
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        internal struct PROCESS_INFORMATION
        {
            public IntPtr hProcess;
            public IntPtr hThread;
            public Int32 dwProcessId;
            public Int32 dwThreadId;
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct SECURITY_ATTRIBUTES
        {
            public int nLength;
            public IntPtr lpSecurityDescriptor;
            public int bInheritHandle;
        }

        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern bool CreateProcessAsUser(
            IntPtr hToken,
            string lpApplicationName,
            string lpCommandLine,
            IntPtr lpProcessAttributes,
            IntPtr lpThreadAttributes,
            bool bInheritHandles,
            uint dwCreationFlags,
            IntPtr lpEnvironment,
            IntPtr lpCurrentDirectory,
            ref STARTUPINFO lpStartupInfo,
            out PROCESS_INFORMATION lpProcessInformation);
        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern bool CreatePipe(
            ref IntPtr hReadPipe,
            ref IntPtr hWritePipe,
            ref SECURITY_ATTRIBUTES lpPipeAttributes,
            uint nSize);
        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern bool ReadFile(
            IntPtr hFile,
            byte[] lpBuffer,
            uint nNumberOfBytesToRead,
            out uint lpNumberOfBytesRead,
            IntPtr lpOverlapped);
        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern bool CloseHandle(IntPtr hObject);
        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern uint WTSGetActiveConsoleSessionId();
        [DllImport("Wtsapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern bool WTSQueryUserToken(UInt32 SessionId, out IntPtr hToken);

        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern uint WaitForSingleObject(IntPtr hProcess, uint dwMilliseconds);
        public MyNewService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            System.Diagnostics.Debugger.Launch();
            using (StreamWriter sw = File.CreateText("Path\\Log.txt"))
            {
                IntPtr read = new IntPtr();
                IntPtr write = new IntPtr();
                IntPtr read2 = new IntPtr();
                IntPtr write2 = new IntPtr();
                SECURITY_ATTRIBUTES saAttr = new SECURITY_ATTRIBUTES();
                saAttr.nLength = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES));
                saAttr.bInheritHandle = 1;
                saAttr.lpSecurityDescriptor = IntPtr.Zero;

                CreatePipe(ref read, ref write, ref saAttr, 0);
                CreatePipe(ref read2, ref write2, ref saAttr, 0);

                uint CREATE_NO_WINDOW = 0x08000000;
                int STARTF_USESTDHANDLES = 0x00000100;
                STARTUPINFO si = new STARTUPINFO();
                si.cb = Marshal.SizeOf(typeof(STARTUPINFO));
                si.hStdOutput = write;
                si.hStdError = write;
                si.hStdInput = read2;
                si.lpDesktop = "Winsta0\\default";
                si.dwFlags = STARTF_USESTDHANDLES;
                PROCESS_INFORMATION pi;

                IntPtr hToken;
                bool err = WTSQueryUserToken(WTSGetActiveConsoleSessionId(), out hToken);
                string path = "Path\\ConsoleApp1.exe";
                if (CreateProcessAsUser(hToken, path, null, IntPtr.Zero, IntPtr.Zero, true, CREATE_NO_WINDOW, IntPtr.Zero, IntPtr.Zero, ref si, out pi))
                {
                    uint ret = WaitForSingleObject(pi.hProcess, 2000); //wait for the child process exit.
                    if (ret == 0)
                    {
                        byte[] title = new byte[200];
                        uint reads = 0;
                        CloseHandle(write);
                        err = ReadFile(read, title, 200, out reads, IntPtr.Zero);
                        string result = System.Text.Encoding.UTF8.GetString(title).Replace("\0","").Replace("\r", "").Replace("\n", "");

                        sw.WriteLine(result);

                    }
                }
                CloseHandle(read2);
                CloseHandle(write2);
                CloseHandle(read);
            }

        }

        protected override void OnStop()
        {

        }
    }
}
</code>```

Body:
I'm creating a windows service app in visual studio and I want to get the currently active window title.
below is the code I have tried but the function GetForegroundWindow() returns 0 every time.
Is it okay to use win32api in windows services?

public partial class My_Service: ServiceBase
{
    Timer timer = new Timer();
    [DllImport("User32.dll")]
    static extern IntPtr GetForegroundWindow();

    [DllImport("User32.dll")]
    static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

    public My_Service()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        WriteToFile("Service is started at " + DateTime.Now);
        timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
        timer.Interval = 10000; //number in milisecinds
        timer.Enabled = true;
    }

    protected override void OnStop()
    {
        WriteToFile("Service is stopped at " + DateTime.Now);
    }

    private void OnElapsedTime(object source, ElapsedEventArgs e)
    {
        string title = GetActivewindow();
        WriteToFile("Service is recall at " + title + DateTime.Now);

    }

    public void WriteToFile(string Message)
    {
       ....
    }

    public string GetActivewindow()
    {
        const int nChars = 256;
        StringBuilder buff = new StringBuilder(nChars);
        string title = "- ";
        IntPtr handle;
        handle = GetForegroundWindow();
        if( GetWindowText(handle,buff,nChars) > 0)
        {
            title = buff.ToString();
        }
        return title;
    }
}

Body:
As comments, and also according to the document: About Window Stations and Desktops - Window Station and Desktop Creation.

Your service may be running under Service-0x0-3e7$\default, but the foreground window you want to retrieve is in the default desktop of the interactive window station (Winsta0\default)

The interactive window station is the only window station that can
  display a user interface or receive user input. It is assigned to the
  logon session of the interactive user, and contains the keyboard,
  mouse, and display device. It is always named "WinSta0". All other
  window stations are noninteractive, which means they cannot display a
  user interface or receive user input.

That means you cannot use GetForegroundWindow directly from the service. You could create a child process in Winsta0\default and redirect its output. Then call GetForegroundWindow in the child process and output.

Sample(removed error checking):

Child:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;
namespace ConsoleApp1
{
    class Program
    {
        [DllImport("User32.dll")]
        static extern IntPtr GetForegroundWindow();

        [DllImport("User32.dll")]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
        static void Main(string[] args)
        {
            const int nChars = 256;
            StringBuilder buff = new StringBuilder(nChars);
            string title = "- ";
            IntPtr handle;
            handle = GetForegroundWindow();
            if (GetWindowText(handle, buff, nChars) > 0)
            {
                title = buff.ToString();
            }
            Console.WriteLine(title);
            return;
        }
    }
}

Service:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.IO;
using System.Diagnostics.Tracing;

namespace WindowsService3
{
    public partial class MyNewService : ServiceBase
    {
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        internal struct STARTUPINFO
        {
            public Int32 cb;
            public string lpReserved;
            public string lpDesktop;
            public string lpTitle;
            public Int32 dwX;
            public Int32 dwY;
            public Int32 dwXSize;
            public Int32 dwYSize;
            public Int32 dwXCountChars;
            public Int32 dwYCountChars;
            public Int32 dwFillAttribute;
            public Int32 dwFlags;
            public Int16 wShowWindow;
            public Int16 cbReserved2;
            public IntPtr lpReserved2;
            public IntPtr hStdInput;
            public IntPtr hStdOutput;
            public IntPtr hStdError;
        }
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        internal struct PROCESS_INFORMATION
        {
            public IntPtr hProcess;
            public IntPtr hThread;
            public Int32 dwProcessId;
            public Int32 dwThreadId;
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct SECURITY_ATTRIBUTES
        {
            public int nLength;
            public IntPtr lpSecurityDescriptor;
            public int bInheritHandle;
        }

        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern bool CreateProcessAsUser(
            IntPtr hToken,
            string lpApplicationName,
            string lpCommandLine,
            IntPtr lpProcessAttributes,
            IntPtr lpThreadAttributes,
            bool bInheritHandles,
            uint dwCreationFlags,
            IntPtr lpEnvironment,
            IntPtr lpCurrentDirectory,
            ref STARTUPINFO lpStartupInfo,
            out PROCESS_INFORMATION lpProcessInformation);
        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern bool CreatePipe(
            ref IntPtr hReadPipe,
            ref IntPtr hWritePipe,
            ref SECURITY_ATTRIBUTES lpPipeAttributes,
            uint nSize);
        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern bool ReadFile(
            IntPtr hFile,
            byte[] lpBuffer,
            uint nNumberOfBytesToRead,
            out uint lpNumberOfBytesRead,
            IntPtr lpOverlapped);
        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern bool CloseHandle(IntPtr hObject);
        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern uint WTSGetActiveConsoleSessionId();
        [DllImport("Wtsapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern bool WTSQueryUserToken(UInt32 SessionId, out IntPtr hToken);

        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern uint WaitForSingleObject(IntPtr hProcess, uint dwMilliseconds);
        public MyNewService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            System.Diagnostics.Debugger.Launch();
            using (StreamWriter sw = File.CreateText("Path\\Log.txt"))
            {
                IntPtr read = new IntPtr();
                IntPtr write = new IntPtr();
                IntPtr read2 = new IntPtr();
                IntPtr write2 = new IntPtr();
                SECURITY_ATTRIBUTES saAttr = new SECURITY_ATTRIBUTES();
                saAttr.nLength = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES));
                saAttr.bInheritHandle = 1;
                saAttr.lpSecurityDescriptor = IntPtr.Zero;

                CreatePipe(ref read, ref write, ref saAttr, 0);
                CreatePipe(ref read2, ref write2, ref saAttr, 0);

                uint CREATE_NO_WINDOW = 0x08000000;
                int STARTF_USESTDHANDLES = 0x00000100;
                STARTUPINFO si = new STARTUPINFO();
                si.cb = Marshal.SizeOf(typeof(STARTUPINFO));
                si.hStdOutput = write;
                si.hStdError = write;
                si.hStdInput = read2;
                si.lpDesktop = "Winsta0\\default";
                si.dwFlags = STARTF_USESTDHANDLES;
                PROCESS_INFORMATION pi;

                IntPtr hToken;
                bool err = WTSQueryUserToken(WTSGetActiveConsoleSessionId(), out hToken);
                string path = "Path\\ConsoleApp1.exe";
                if (CreateProcessAsUser(hToken, path, null, IntPtr.Zero, IntPtr.Zero, true, CREATE_NO_WINDOW, IntPtr.Zero, IntPtr.Zero, ref si, out pi))
                {
                    uint ret = WaitForSingleObject(pi.hProcess, 2000); //wait for the child process exit.
                    if (ret == 0)
                    {
                        byte[] title = new byte[200];
                        uint reads = 0;
                        CloseHandle(write);
                        err = ReadFile(read, title, 200, out reads, IntPtr.Zero);
                        string result = System.Text.Encoding.UTF8.GetString(title).Replace("\0","").Replace("\r", "").Replace("\n", "");

                        sw.WriteLine(result);

                    }
                }
                CloseHandle(read2);
                CloseHandle(write2);
                CloseHandle(read);
            }

        }

        protected override void OnStop()
        {

        }
    }
}


问:
What is the difference between signed and unsigned variables?
I have seen these mentioned in the context of C and C++, but what is the difference between signed and unsigned variables? </p>

答:
Unsigned variables can only be positive numbers, because they lack the ability to indicate that they are negative.

This ability is called the 'sign' or 'signing bit'.

A side effect is that without a signing bit, they have one more bit that can be used to represent the number, doubling the maximum number it can represent.

OwnerDisplayName: thomasrutter


问:
Sqlserver 2008 : Restored Failed for Server 'System 16'(Microsoft.Sqlserver.smoextended'
I am getting the following error when i tried to restore the bak file i have

```<code>TITLE: Microsoft SQL Server Management Studio
------------------------------

Restore failed for Server 'SYSTEM16'.  (Microsoft.SqlServer.SmoExtended)

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.0.1600.22+((SQL_PreRelease).080709-1414+)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Restore+Server&LinkId=20476

------------------------------
ADDITIONAL INFORMATION:

System.Data.SqlClient.SqlError: The database was backed up on a server running version 10.50.1600. That version is incompatible with this server, which is running version 10.00.1600. Either restore the database on a server that supports the backup, or use a backup that is compatible with this server. (Microsoft.SqlServer.Smo)
</code>```

Can any one tell how to resolve this.

答: The answer appears to be in your error message. It looks like you may have taken the backup from SQL 2008 R2 and are trying to restore it to SQL 2008 R1. You can't restore backups taken on newer versions of SQL Server to older versions.</p>

Body:
I am getting the following error when i tried to restore the bak file i have

TITLE: Microsoft SQL Server Management Studio
------------------------------

Restore failed for Server 'SYSTEM16'.  (Microsoft.SqlServer.SmoExtended)

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.0.1600.22+((SQL_PreRelease).080709-1414+)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Restore+Server&LinkId=20476

------------------------------
ADDITIONAL INFORMATION:

System.Data.SqlClient.SqlError: The database was backed up on a server running version 10.50.1600. That version is incompatible with this server, which is running version 10.00.1600. Either restore the database on a server that supports the backup, or use a backup that is compatible with this server. (Microsoft.SqlServer.Smo)

Can any one tell how to resolve this.


问:
Routing to an external application (such as Wordpress) in Angular
I am building an Angular 9 application and I'd like the /blog route of this site to be a separate application running either Wordpress or Umbraco but I have no idea how I can get Angular to ignore this specific route. Whether this opens a separate browser tab or does a complete page redirect is not important, but I need some way to get there without Angular getting involved.

I also have not chosen which webserver I am going to use yet, I guess it's either IIS or Apache, but I'd also like to know what I'd need to set up on the webserver to make this possible.

Thanks for your time.

答:
Disclaimer. As an Umbraco dev, it's a pretty narrow sighted answer.

Integrating both front-ends gives you lots of issues which will never have the "best" solution. It will always be a workaround.
You will have lots issues whether you try to integrate with iframes, hosting sub applications, using a reverse proxy, ...

I think there are only two good solutions:

The easiest way is probably open a new window (_target=blank) and redirect (301) to a separate website (eg blog.yourdomain.com).

Or secondly: Only use the umbraco backend, do not develop any front-end in Umbraco. Throw in some API endpoints on your umbraco where you retrieve the information about your blog and show the blog posts inside of your angular9 application. This approach will save you all the editor/backend development for the blog.

eg add a blogController with a summary and a detail(id) method which return the json. That json can then be interpreted by your Angular app.

Sidenode, there is a commercial product (umbraco heartcore) which is build for this purpose. But you can choose to install a free Umbraco "on premise" and do it yourselves.


问:
How to do the ngrx state structure correctly?
I am trying to implement a feature state which has a graph state, two subfeatures: a node state and a link state;

the graph state and reducer I am implementing it like this:

```<code>export interface GraphState {
  [fromNode.featureKey]: fromNode.State;
  [fromLink.featureKey]: fromLink.State;
}
export interface AppState extends fromRoot.State {
  readonly [featureKey]: GraphState;
}

export const reducers: ActionReducerMap<GraphState> = {
  [fromNode.featureKey]: fromNode.reducer,
  [fromLink.featureKey]: fromLink.reducer,
};//The main reducer

//feature module
StoreModule.forFeature(fromGraph.graphsFeatureKey, fromGraph.reducers),

//components that use this store
private _store: Store<fromGraph.AppState>
this._nodes$ = this._store.pipe(select(fromGraph.getNodes));
this._links$ = this._store.pipe(select(fromGraph.getLinks));
this._store.dispatch(fromGraphActions.AddNode({ node }));
</code>```

and it is doing fine;
but now I am learning Entity, and I've read some posts, it seems that the way I implemented is not correct.

How do I implement this using Entity correctly?

I want the components can CRUD the node and link from the main feature which is the graph feature, and I want to select graph to get the nodes and links at once this.nodesAndLinks$ = this._store.pipe(select(fromGraph.getNodesAndLinks))

答:
With ngrx entity you need to create 2 states: one for the link entity and another one for the node entity.

for example like that:

interface Link {
  id: string;
  link: string;
}
export interface LinkState extends EntityState<Link> {}

interface Node {
  id: string;
  nodeIds: Array<string>;
  linkIds: Array<string>;
}
export interface NodeState extends EntityState<Node> {}
```

<p>depends what is the best fit for you, and then you can use their adapters to fetch the data.</p>

```const linkAdapter = createEntityAdapter<Link>();
const nodeAdapter = createEntityAdapter<Node>();

export getLinks = createSelector(
  selectLinkFeature(),
  linkAdapter.getSelectors().selectAll,
);

export getNodes = createSelector(
  selectNodeFeature(),
  nodeAdapter.getSelectors().selectAll,
);
```

If you want to build a graph based on the nodeIds and linkIds you can use ngrx-entity-relationship, but it would require more coding to setup everything.

Body:
I am trying to implement a feature state which has a graph state, two subfeatures: a node state and a link state;

the graph state and reducer I am implementing it like this:

export interface GraphState {
  [fromNode.featureKey]: fromNode.State;
  [fromLink.featureKey]: fromLink.State;
}
export interface AppState extends fromRoot.State {
  readonly [featureKey]: GraphState;
}

export const reducers: ActionReducerMap<GraphState> = {
  [fromNode.featureKey]: fromNode.reducer,
  [fromLink.featureKey]: fromLink.reducer,
};//The main reducer

//feature module
StoreModule.forFeature(fromGraph.graphsFeatureKey, fromGraph.reducers),

//components that use this store
private _store: Store<fromGraph.AppState>
this._nodes$ = this._store.pipe(select(fromGraph.getNodes));
this._links$ = this._store.pipe(select(fromGraph.getLinks));
this._store.dispatch(fromGraphActions.AddNode({ node }));

and it is doing fine;
but now I am learning Entity, and I've read some posts, it seems that the way I implemented is not correct.

How do I implement this using Entity correctly?

I want the components can CRUD the node and link from the main feature which is the graph feature, and I want to select graph to get the nodes and links at once this.nodesAndLinks$ = this._store.pipe(select(fromGraph.getNodesAndLinks))

Body:
With ngrx entity you need to create 2 states: one for the link entity and another one for the node entity.

for example like that:

interface Link {
  id: string;
  link: string;
}
export interface LinkState extends EntityState<Link> {}

interface Node {
  id: string;
  nodeIds: Array<string>;
  linkIds: Array<string>;
}
export interface NodeState extends EntityState<Node> {}

depends what is the best fit for you, and then you can use their adapters to fetch the data.

const linkAdapter = createEntityAdapter<Link>();
const nodeAdapter = createEntityAdapter<Node>();

export getLinks = createSelector(
  selectLinkFeature(),
  linkAdapter.getSelectors().selectAll,
);

export getNodes = createSelector(
  selectNodeFeature(),
  nodeAdapter.getSelectors().selectAll,
);

If you want to build a graph based on the nodeIds and linkIds you can use ngrx-entity-relationship, but it would require more coding to setup everything.


问:
How do I test the Asp.Net Core controller which has Db Context and Logger?
I have a controller with two parameters and need to test them via unit tests. Want to test 4 parameters, ViewBug, etc. But how I can make fake DB context and logger? I'm stuck at this moment:

```<code>        [Fact]
    public void IndexReturnsAViewResultWithAListOfUsers()
    {
        // Arrange
        var mock = new Mock<AircraftsController>();
        var controller = new AircraftsController(/*params*/);

        // Act

        // Assert
    }
</code>```

This is my controller:

```<code> public class AircraftsController : Controller
{
    #region DbContext, Logger
    public AppDbContext Context { get; }
    private readonly ILogger<AircraftsController> _logger;

    public AircraftsController(AppDbContext context, ILogger<AircraftsController> logger)
    {
        Context = context;
        _logger = logger;
        _logger.LogDebug(1, "NLog injected into Controller");
    }
    #endregion

    [HttpGet]
    public IActionResult Compare(int vehicle1, int vehicle2, int vehicle3, int vehicle4)
    {
        var planesFromDb = Context.Planes.OrderBy(x => x.BR).ToList();
        planesFromDb.Insert(0, new Plane { Image = "~/images/EmptyPlane.png", Nation = "EmptyFlag", Name = "Select aircraft", VehicleId=0 });
        var selectedPlanes = new List<Plane>();
        ViewBag.AllPlanesSelected = planesFromDb;

        selectedPlanes.Add(planesFromDb.FirstOrDefault(p => p.VehicleId == vehicle1));
        selectedPlanes.Add(planesFromDb.FirstOrDefault(p => p.VehicleId == vehicle2));
        selectedPlanes.Add(planesFromDb.FirstOrDefault(p => p.VehicleId == vehicle3));
        selectedPlanes.Add(planesFromDb.FirstOrDefault(p => p.VehicleId == vehicle4));

        _logger.LogInformation("Log Message");

        return View(selectedPlanes);
    }

}
</code>```

答:
As Stephen has suggested the in-memory provider is a good option for mocking an EFCore db context. It works for most things.

I have a requirement to use Moq for 3rd party dependencies so I'd create mocks for both. For the db context I'd use EntityFrameworkCore.Testing (disclaimer, I am the author):

```<code>var mockedDbContext = Create.MockedDbContextFor<AppDbContext>();
</code>```

Then for the logger I'd create a mock using Mock.Of

```<code>var mockedLogger = Mock.Of<ILogger<AircraftsController>>();
</code>```

Easy one liners that you can then use to create your controller in your unit test. Overall I am an advocate of using the EFCore in-memory provider if it suits the unit test. Using mocks does have other advantages such as allowing you to verify invocations.

Body:
I have a controller with two parameters and need to test them via unit tests. Want to test 4 parameters, ViewBug, etc. But how I can make fake DB context and logger? I'm stuck at this moment:

        [Fact]
    public void IndexReturnsAViewResultWithAListOfUsers()
    {
        // Arrange
        var mock = new Mock<AircraftsController>();
        var controller = new AircraftsController(/*params*/);

        // Act

        // Assert
    }

This is my controller:

 public class AircraftsController : Controller
{
    #region DbContext, Logger
    public AppDbContext Context { get; }
    private readonly ILogger<AircraftsController> _logger;

    public AircraftsController(AppDbContext context, ILogger<AircraftsController> logger)
    {
        Context = context;
        _logger = logger;
        _logger.LogDebug(1, "NLog injected into Controller");
    }
    #endregion

    [HttpGet]
    public IActionResult Compare(int vehicle1, int vehicle2, int vehicle3, int vehicle4)
    {
        var planesFromDb = Context.Planes.OrderBy(x => x.BR).ToList();
        planesFromDb.Insert(0, new Plane { Image = "~/images/EmptyPlane.png", Nation = "EmptyFlag", Name = "Select aircraft", VehicleId=0 });
        var selectedPlanes = new List<Plane>();
        ViewBag.AllPlanesSelected = planesFromDb;

        selectedPlanes.Add(planesFromDb.FirstOrDefault(p => p.VehicleId == vehicle1));
        selectedPlanes.Add(planesFromDb.FirstOrDefault(p => p.VehicleId == vehicle2));
        selectedPlanes.Add(planesFromDb.FirstOrDefault(p => p.VehicleId == vehicle3));
        selectedPlanes.Add(planesFromDb.FirstOrDefault(p => p.VehicleId == vehicle4));

        _logger.LogInformation("Log Message");

        return View(selectedPlanes);
    }

}

Body:
As Stephen has suggested the in-memory provider is a good option for mocking an EFCore db context. It works for most things.

I have a requirement to use Moq for 3rd party dependencies so I'd create mocks for both. For the db context I'd use EntityFrameworkCore.Testing (disclaimer, I am the author):

var mockedDbContext = Create.MockedDbContextFor<AppDbContext>();

Then for the logger I'd create a mock using Mock.Of

var mockedLogger = Mock.Of<ILogger<AircraftsController>>();

Easy one liners that you can then use to create your controller in your unit test. Overall I am an advocate of using the EFCore in-memory provider if it suits the unit test. Using mocks does have other advantages such as allowing you to verify invocations.


问:
Error fetching custom collections: Error in Watson Visual Recognition service: Recieved invalid status 403 response
I am using IBM Watson Visual Recognition for a custom model. I have uploaded my dataset as .zip files, which is fine so far. However, I cannot test  already trained model and  I cannot label new images. When I go on my Watson services, it says:

```<code>Error fetching custom collections: Error in Watson Visual Recognition service: Recieved invalid status 403 in getAllCollections response for guid crn:v1:bluemix:public:watson-vision-combined:us-south:a/649b0335a5a44f6d80d1fd6909e466f9:8a71daa3-b0be-42ac-bb72-1473de835c19:: at endpoint https://gateway.watsonplatform.net/visual-recognition/api/
</code>```

When I try to label new images , it says: Error in Watson Visual Recognition service: Received empty image data response

To the best of my knowledge, I have checked Google and StackOverflow for solutions, but didn't find any. I am using the Lite version. I only have one project, and one Visual Recognition instance. Please note that it worked for a different Visual Recognition model before, but later I could not use or access that model.

答:
403 is a forbidden error, implying that you don't have authority to access the custom collections. Which is strange as its part of the V4 API available to lite accounts.

If you are doing everything inside Watson Studio, then Watson Studio is accessing the service on your behalf. Watson Studio may have expired its access token. Try flushing your browser cache, logging back into Watson Studio and trying again.

If that doesn't work, you should raise a ticket against Watson Studio.

You can verify if it is a Watson Studio problem by using cURL to list the customised collections - https://cloud.ibm.com/apidocs/visual-recognition/visual-recognition-v4#list-collections

```<code>curl -u "apikey:{apikey}" "{url}/v4/collections?version=2019-02-11"
</code>```

If you still get a 403, then the problem lies with the service. If the cURL command works, then the problem lies with Watson Studio, and how you are using it.

Body:
I am using IBM Watson Visual Recognition for a custom model. I have uploaded my dataset as .zip files, which is fine so far. However, I cannot test  already trained model and  I cannot label new images. When I go on my Watson services, it says:

Error fetching custom collections: Error in Watson Visual Recognition service: Recieved invalid status 403 in getAllCollections response for guid crn:v1:bluemix:public:watson-vision-combined:us-south:a/649b0335a5a44f6d80d1fd6909e466f9:8a71daa3-b0be-42ac-bb72-1473de835c19:: at endpoint https://gateway.watsonplatform.net/visual-recognition/api/

When I try to label new images , it says: Error in Watson Visual Recognition service: Received empty image data response

To the best of my knowledge, I have checked Google and StackOverflow for solutions, but didn't find any. I am using the Lite version. I only have one project, and one Visual Recognition instance. Please note that it worked for a different Visual Recognition model before, but later I could not use or access that model.

Body:
403 is a forbidden error, implying that you don't have authority to access the custom collections. Which is strange as its part of the V4 API available to lite accounts.

If you are doing everything inside Watson Studio, then Watson Studio is accessing the service on your behalf. Watson Studio may have expired its access token. Try flushing your browser cache, logging back into Watson Studio and trying again.

If that doesn't work, you should raise a ticket against Watson Studio.

You can verify if it is a Watson Studio problem by using cURL to list the customised collections - https://cloud.ibm.com/apidocs/visual-recognition/visual-recognition-v4#list-collections

curl -u "apikey:{apikey}" "{url}/v4/collections?version=2019-02-11"

If you still get a 403, then the problem lies with the service. If the cURL command works, then the problem lies with Watson Studio, and how you are using it.


问:
The view 'Edit' or its master was not found or no view engine supports the searched locations
I want to edit blogs. I have Edit view in View folder in BlogAdmin folder.

```<code> <a  href="/BlogAdmin/Edit/@item.id" class=" btn btn-sm btn-primary float-right"> Edit </a>
</code>```

Controller:

```<code>  public ActionResult Edit(int? id)
         {
        if (id == null)
        {
            return HttpNotFound();
        }
        List<Blog> EditBg = db.Blogs.Where(i => i.id==id).ToList();
        if (EditBg== null)
        {
            return HttpNotFound();
        }
        var vm = new VmBlog
        {
            blogcatg = db.BlogCategories.ToList(),
            Blog = db.Blogs.Where(i => i.id == id).ToList(),
            Content=db.Blogs.FirstOrDefault(i=>i.id==id).posttext

        };

        return View(vm);

    }
</code>```

Get method is working. There is no error here:

Everything seems correctly. But I am getting this error:

The view 'Edit' or its master was not found or no view engine supports the searched locations. The following locations were searched:

~/Views/BlogAdmin/Edit.aspx

~/Views/BlogAdmin/Edit.ascx

~/Views/Shared/Edit.aspx

~/Views/Shared/Edit.ascx

~/Views/BlogAdmin/Edit.cshtml

~/Views/BlogAdmin/Edit.vbhtml

~/Views/Shared/Edit.cshtml

~/Views/Shared/Edit.vbhtml

Why does error happen?

答:
Check Microsoft documentation on Views, specifically the section about View Discovery

It doesn't matter if you implicitly return the ViewResult with return View(); or explicitly pass the view name to the View method with return View("");. In both cases, view discovery searches for a matching view file in this order:

Views/[ControllerName]/[ViewName].cshtml

Views/Shared/[ViewName].cshtml

It seems that your folder structure does not account for the specified view discovery

If you want to change the folder structure and View discovery

You can customize the default convention for how views are located within the app by using a custom IViewLocationExpander.

A very nice answer on this, can be found Working with IViewLocationExpander in mvc

Body:
I want to edit blogs. I have Edit view in View folder in BlogAdmin folder.

  Edit

Controller:

  public ActionResult Edit(int? id)
         {
        if (id == null)
        {
            return HttpNotFound();
        }
        List<Blog> EditBg = db.Blogs.Where(i => i.id==id).ToList();
        if (EditBg== null)
        {
            return HttpNotFound();
        }
        var vm = new VmBlog
        {
            blogcatg = db.BlogCategories.ToList(),
            Blog = db.Blogs.Where(i => i.id == id).ToList(),
            Content=db.Blogs.FirstOrDefault(i=>i.id==id).posttext

        };

        return View(vm);

    }

Get method is working. There is no error here:

Everything seems correctly. But I am getting this error:

The view 'Edit' or its master was not found or no view engine supports the searched locations. The following locations were searched:

~/Views/BlogAdmin/Edit.aspx

~/Views/BlogAdmin/Edit.ascx

~/Views/Shared/Edit.aspx

~/Views/Shared/Edit.ascx

~/Views/BlogAdmin/Edit.cshtml

~/Views/BlogAdmin/Edit.vbhtml

~/Views/Shared/Edit.cshtml

~/Views/Shared/Edit.vbhtml

Why does error happen?


问:
mongoose; 404 when remove object from collection with _id
I have a strange behavior on a mongoose api who remove object from collection.

i call an the api passing the id as parameter (i checked and the ID exist),
but what i obtain is a response 404.

here how i call the api using angular service:

```<code>  private deleteInvoice = 'http://localhost:3000/api/elimina_fattura';

 deleteInvoices(id){
   let headers = new Headers();
   headers.append('Content-Type', 'application/json');
   return this.http.post(this.deleteInvoice+'/'+id, {headers: headers})
   .map((response: Response) => response.json())
 }
</code>```

here the api defined in mongoose

```<code>app.delete('/api/elimina_fattura/:id',(req,res)=>{
Fatture.remove({_id: req.params.id})
.then(()=>{
    res.json({'status':'ok'});
 })
 .catch((err)=>{
    res.json(err);
});
});
</code>```

here the message when i call the api

i have tried to do the same query in robomongo, and seems working

答:
I can see on front-end you have mentioned request type POST try changing it to DELETE </p>

```<code> deleteInvoices(id){
   let headers = new Headers();
   headers.append('Content-Type', 'application/json');
   return this.http.delete(this.deleteInvoice+'/'+id, {headers: headers}) // changed HTTP method
   .map((response: Response) => response.json())
 }
</code>```

Body:
I have a strange behavior on a mongoose api who remove object from collection.

i call an the api passing the id as parameter (i checked and the ID exist),
but what i obtain is a response 404.

here how i call the api using angular service:

  private deleteInvoice = 'http://localhost:3000/api/elimina_fattura';

 deleteInvoices(id){
   let headers = new Headers();
   headers.append('Content-Type', 'application/json');
   return this.http.post(this.deleteInvoice+'/'+id, {headers: headers})
   .map((response: Response) => response.json())
 }

here the api defined in mongoose

app.delete('/api/elimina_fattura/:id',(req,res)=>{
Fatture.remove({_id: req.params.id})
.then(()=>{
    res.json({'status':'ok'});
 })
 .catch((err)=>{
    res.json(err);
});
});

here the message when i call the api

i have tried to do the same query in robomongo, and seems working

Body:
I can see on front-end you have mentioned request type POST try changing it to DELETE

 deleteInvoices(id){
   let headers = new Headers();
   headers.append('Content-Type', 'application/json');
   return this.http.delete(this.deleteInvoice+'/'+id, {headers: headers}) // changed HTTP method
   .map((response: Response) => response.json())
 }


问:
Netbeans 10.0  for simple Hello world program
Hi, I just installed Netbeans 10.0 and I can't run my Java project because apparently my main is missing but the class main is there!

I tried to right click the project and create a new main class but it didn't help.

the error

答:
try to change the package name to another one which different from the project name, for example make it "hello_pkg", same for the class name, try to make all the 3 have different names to avoid any confusion.

for example:

Project name: helloProject

Package: hello_pkg

Class : Hello

EDIT:(after providing more information in comments)

Netbeans 10 doesn't support JDK 14, use JDK 10 instead (or older)

Title: Netbeans 10.0 <main classes not found> for simple Hello world program


问:
Align Materials to same widths and heights without a Table
I created a material for my app which should enclose some text. It looks like this:

Sometimes, there is overflowing text. With a flexible it looks like this:

And I also want it to align like in a Table. Without alignment to the others it looks like this:

The Border between the colors should be at the same position for all of those elements so it looks clean.

How can I achieve all of this? The Flexible Widget throws a WrongParent Exception when Put into a Table.

My Code:

```<code>import 'dart:math';

import 'package:flutter/material.dart';

import 'nook_constants.dart';

class NookTable extends StatelessWidget {
  final double width;
  final double height;
  final EdgeInsets margin;
  final Widget child;
  final String title;
  final String text;
  final String font;

  NookTable({
    this.width,
    this.height,
    this.margin: nookDefaultMargin,
    this.child,
    this.title,
    this.text,
    this.font
  });

  final cell = (Widget widget) => Padding(
      padding: EdgeInsets.only(left: 15, top: 5, bottom: 5, right: 15),
      child: widget,
    );

  @override
  Widget build(BuildContext context) {
    var margin = EdgeInsets.only(
      left: this.margin?.left ?? 0.0,
      right: this.margin?.right ?? 0.0,
      top: this.margin?.top ?? 0.0,
      bottom: max(2, this.margin?.bottom ?? 0.0),
    );

    return Container(
      width: width,
      height: height,
      clipBehavior: Clip.antiAlias,
      margin: EdgeInsets.only(left: 15, top: 5, bottom: 5, right: 15),
      decoration: BoxDecoration(
        color: Colors.transparent,
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          NookTitleDetails(text: title, width: width,),
          NookTextDetails(text: text,),
        ],
      ),
    );
  }
}

class NookTextDetails extends StatelessWidget {
  final String text;
  final String font;

  NookTextDetails({
    this.text,
    this.font
  });

  final cell = (Widget widget) => Padding(
      padding: EdgeInsets.only(left: 15, top: 5, bottom: 5, right: 15),
      child: widget,
    );

  @override
  Widget build(BuildContext context) {
    return Flexible(
      child: Material(
        clipBehavior: Clip.antiAlias,
        borderRadius: BorderRadius.only(bottomRight: Radius.circular(25), topRight: Radius.circular(25)),
        color: nookBeige,
        child: cell(Text(text))
      ),
    );
  }
}
class NookTitleDetails extends StatelessWidget {
  final String text;
  final String font;
  final double width;

  NookTitleDetails({
    this.text,
    this.font,
    this.width
  });

  final cell = (Widget widget) => Padding(
      padding: EdgeInsets.only(left: 15, top: 5, bottom: 5, right: 15),
      child: widget,
    );

  @override
  Widget build(BuildContext context) {
    return Container(
      width: width,
      child: Material(
        clipBehavior: Clip.antiAlias,
        borderRadius: BorderRadius.only(bottomLeft: Radius.circular(25), topLeft: Radius.circular(25)),
        color: nooklightGreen,
        child: cell(Text(text, style: TextStyle(color: nookWhite)))
      ),
    );
  }
}
</code>```

答:
<img src="https://i.stack.imgur.com/smFHB.png" alt="enter image description here">   </p>

```<code>Container(

              decoration: BoxDecoration(
                  color: Colors.lime,
                  borderRadius: BorderRadius.all(Radius.circular(10))

              ),

              child: Row(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Flexible(
                        flex: 1,
                        child: Stack(

                          children: <Widget>[Container(
                            width: 100,

                              padding: EdgeInsets.all(5),
                              child: Text('Fundort',textAlign: TextAlign.center,))],
                        )),
                    Expanded(
                      flex: 4,
                      child: Container(
                        decoration: BoxDecoration(
                            color: Colors.lightGreen,
                            borderRadius: BorderRadius.horizontal(right:Radius.circular(10))

                        ),

                        padding: EdgeInsets.all(10),
                        child: Text('Sign in with FacebookSign in with Facebook',
                            style: TextStyle(fontSize: 18, color: Colors.white)),
                      ),
                    )
                  ]),
            ),
</code>```

Body:
I created a material for my app which should enclose some text. It looks like this:

Sometimes, there is overflowing text. With a flexible it looks like this:

And I also want it to align like in a Table. Without alignment to the others it looks like this:

The Border between the colors should be at the same position for all of those elements so it looks clean.

How can I achieve all of this? The Flexible Widget throws a WrongParent Exception when Put into a Table.

My Code:

import 'dart:math';

import 'package:flutter/material.dart';

import 'nook_constants.dart';

class NookTable extends StatelessWidget {
  final double width;
  final double height;
  final EdgeInsets margin;
  final Widget child;
  final String title;
  final String text;
  final String font;

  NookTable({
    this.width,
    this.height,
    this.margin: nookDefaultMargin,
    this.child,
    this.title,
    this.text,
    this.font
  });

  final cell = (Widget widget) => Padding(
      padding: EdgeInsets.only(left: 15, top: 5, bottom: 5, right: 15),
      child: widget,
    );

  @override
  Widget build(BuildContext context) {
    var margin = EdgeInsets.only(
      left: this.margin?.left ?? 0.0,
      right: this.margin?.right ?? 0.0,
      top: this.margin?.top ?? 0.0,
      bottom: max(2, this.margin?.bottom ?? 0.0),
    );

    return Container(
      width: width,
      height: height,
      clipBehavior: Clip.antiAlias,
      margin: EdgeInsets.only(left: 15, top: 5, bottom: 5, right: 15),
      decoration: BoxDecoration(
        color: Colors.transparent,
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          NookTitleDetails(text: title, width: width,),
          NookTextDetails(text: text,),
        ],
      ),
    );
  }
}

class NookTextDetails extends StatelessWidget {
  final String text;
  final String font;

  NookTextDetails({
    this.text,
    this.font
  });

  final cell = (Widget widget) => Padding(
      padding: EdgeInsets.only(left: 15, top: 5, bottom: 5, right: 15),
      child: widget,
    );

  @override
  Widget build(BuildContext context) {
    return Flexible(
      child: Material(
        clipBehavior: Clip.antiAlias,
        borderRadius: BorderRadius.only(bottomRight: Radius.circular(25), topRight: Radius.circular(25)),
        color: nookBeige,
        child: cell(Text(text))
      ),
    );
  }
}
class NookTitleDetails extends StatelessWidget {
  final String text;
  final String font;
  final double width;

  NookTitleDetails({
    this.text,
    this.font,
    this.width
  });

  final cell = (Widget widget) => Padding(
      padding: EdgeInsets.only(left: 15, top: 5, bottom: 5, right: 15),
      child: widget,
    );

  @override
  Widget build(BuildContext context) {
    return Container(
      width: width,
      child: Material(
        clipBehavior: Clip.antiAlias,
        borderRadius: BorderRadius.only(bottomLeft: Radius.circular(25), topLeft: Radius.circular(25)),
        color: nooklightGreen,
        child: cell(Text(text, style: TextStyle(color: nookWhite)))
      ),
    );
  }
}


问:
what is the best procedure to store bulk list of images as blobs in browser cache?
Currently i am using localForage and caching axios request which stores image blobs with over 2 gb image list , user frequently uses this images so i need to cache this in browser</p>

答:
2GB of size is not cacheable what you can do is load fragment of the image that the user asks for try using openseagragon library
I used it to view on web images up to 7GB of size