问:
Object reference for child class
```<code>namespace Test
{
    public class Program
    {
        static void Main(string[] args)
        {
            TestClass testC = new TestClass();
            testC.AssignRec(10);
            //testC.root - this is null
        }
    }

    public class TestClass
    {
        public Childclass root;
        public void Assign(int data)
        {
           AssigRec(this.root,data);
        }
        public void AssignRec(Childclass rootnode, int data)
        {
            if (rootnode == null)
            {
                rootnode = new Childclass(data);
            }
        }
    }

    public class Childclass
    {
        public int data;
        public Childclass(int data)
        {
            this.data = data;
        }
    }
}
</code>```

Updated the Child parameter name.
Assigning value for the subclass ChildClass inside the TestClass but after assigning and if I try to access the Childcalss value it is null. Not sure the reason.

答:
We need to be careful when we have the exact same name for an argument as a field, because inside the method, the name will refer to the argument unless we specify the field using this.root.

So, what the code is doing is assigning the class field root only if the argument root is null.

Instead, it seems like you want to do the assignment if the backing field is null, in which case you would do something like:

```<code>    public void AssignRec(Childclass root, int data)
    {
        // Assign the field 'root' to the argument passed to this method unless the argument
        // to this method is 'null', in which case assign a new instance of ChildClass
        this.root = root ?? new ChildClass(data);
    }
</code>```

Although as a consumer of this class I would be a little confused if I called the Assign method and passed in some data, and nothing happened (which is what would happen if the class field root was not null).

I would also be confused by a method that takes in both a ChildClass and data, since it's not clear what the relationship between these arguments is.

Instead, I would recommend providing two overloads, each with a single argument:

```<code>public void Assign(int data)
{
    if (this.root == null)
    {
        this.root = new ChildClass(data);
    }
    else
    {
        this.root.data = data;
    }
}

public void Assign(ChildClass root)
{
    this.root = root;
}
</code>```

Title: Object reference for child class

Body:
namespace Test
{
    public class Program
    {
        static void Main(string[] args)
        {
            TestClass testC = new TestClass();
            testC.AssignRec(10);
            //testC.root - this is null
        }
    }

    public class TestClass
    {
        public Childclass root;
        public void Assign(int data)
        {
           AssigRec(this.root,data);
        }
        public void AssignRec(Childclass rootnode, int data)
        {
            if (rootnode == null)
            {
                rootnode = new Childclass(data);
            }
        }
    }

    public class Childclass
    {
        public int data;
        public Childclass(int data)
        {
            this.data = data;
        }
    }
}

Updated the Child parameter name.
Assigning value for the subclass ChildClass inside the TestClass but after assigning and if I try to access the Childcalss value it is null. Not sure the reason.

Body:
We need to be careful when we have the exact same name for an argument as a field, because inside the method, the name will refer to the argument unless we specify the field using this.root.

So, what the code is doing is assigning the class field root only if the argument root is null.

Instead, it seems like you want to do the assignment if the backing field is null, in which case you would do something like:

    public void AssignRec(Childclass root, int data)
    {
        // Assign the field 'root' to the argument passed to this method unless the argument
        // to this method is 'null', in which case assign a new instance of ChildClass
        this.root = root ?? new ChildClass(data);
    }

Although as a consumer of this class I would be a little confused if I called the Assign method and passed in some data, and nothing happened (which is what would happen if the class field root was not null).

I would also be confused by a method that takes in both a ChildClass and data, since it's not clear what the relationship between these arguments is.

Instead, I would recommend providing two overloads, each with a single argument:

public void Assign(int data)
{
    if (this.root == null)
    {
        this.root = new ChildClass(data);
    }
    else
    {
        this.root.data = data;
    }
}

public void Assign(ChildClass root)
{
    this.root = root;
}


来源: stackexchange

问:
Why is the regular expression not matching the last part of the string?
Why does this regular expression:

```<code>Summary:(\r\n\t\t\/\/     (.+))+
</code>```

not match the last line of the following string? (NOTE the whitespace at the beginning of each line is two tab characters but has been converted to all spaces, at least in my browser--it's correct in edit mode, though.)  Shouldn't the + quantifier cause the part of the pattern in the outer-most parens to match the last line too?

```
        //
        // Summary:
        //     Do absolutely nothing and don't do anything else other than to do nothing at
        //     all.
```

Here's the result on http://regexstorm.net/tester:

答:
This looks like a bug to me. Look what is happening:

Summary: is matched first

(\r\n\t\t//     (.+))+ - at Iteration 1, it grabs "\r\n\t\t//     Do absolutely nothing and don't do anything else other than to do nothing at\r" (pay attention at the last \r, . in a .NET regex, by default, matches a CR symbol)

The + quantifier signals the regex engine to try and match the substring to the right of the current match, i.e. "\n\t\t//     all.". It cannot match it as it starts with \n. The pattern should expand like "\r\n\t\t//     (.+)\r\n\t\t//     (.+)" and so on, i.e. \r\n\t\t//     (.+)(?:\r\n\t\t//     (.+))*, but it does not turn on backtracking with (.+). Indeed, the regex engine has a way to re-match the string differently as .+ qualifies for backtracking, but somehow the . that matches a CR does not want to give it back.

The workaround is to either match the first \r as an optional symbol:

```<code>Summary:(\r?\n\t\t//     (.+))+
</code>```

Or, just match any chars but CR and LF with [^\r\n]+ (this will ensure cleaner values in the Group 2 capture stack):

```<code>Summary:(\r\n\t\t//     ([^\r\n]+))+
</code>```

See the regex demo.

ContentLicense: CC BY-SA 4.0

Body:
Why does this regular expression:

Summary:(\r\n\t\t\/\/     (.+))+

not match the last line of the following string? (NOTE the whitespace at the beginning of each line is two tab characters but has been converted to all spaces, at least in my browser--it's correct in edit mode, though.)  Shouldn't the + quantifier cause the part of the pattern in the outer-most parens to match the last line too?

        //
        // Summary:
        //     Do absolutely nothing and don't do anything else other than to do nothing at
        //     all.

Here's the result on http://regexstorm.net/tester:

Body:
This looks like a bug to me. Look what is happening:

Summary: is matched first

(\r\n\t\t//     (.+))+ - at Iteration 1, it grabs "\r\n\t\t//     Do absolutely nothing and don't do anything else other than to do nothing at\r" (pay attention at the last \r, . in a .NET regex, by default, matches a CR symbol)

The + quantifier signals the regex engine to try and match the substring to the right of the current match, i.e. "\n\t\t//     all.". It cannot match it as it starts with \n. The pattern should expand like "\r\n\t\t//     (.+)\r\n\t\t//     (.+)" and so on, i.e. \r\n\t\t//     (.+)(?:\r\n\t\t//     (.+))*, but it does not turn on backtracking with (.+). Indeed, the regex engine has a way to re-match the string differently as .+ qualifies for backtracking, but somehow the . that matches a CR does not want to give it back.

The workaround is to either match the first \r as an optional symbol:

Summary:(\r?\n\t\t//     (.+))+

Or, just match any chars but CR and LF with [^\r\n]+ (this will ensure cleaner values in the Group 2 capture stack):

Summary:(\r\n\t\t//     ([^\r\n]+))+

See the regex demo.


问:
Preventing POSIX xargs from attempting to run an empty command
I'm not that good with bash, but I'm trying to create a script to kill some java processes:

```<code>/usr/ucb/ps -auxww    \
  | grep 'XUnit'      \
  | grep -v 'grep'    \
  | cut -c -2000      \
  | awk '{print $2;}' \
  | xargs kill
</code>```

cut is used here because awk can fail with excessively long lines (see references to LINE_MAX limit in the POSIX specification for awk).

The problem occurs when there are no such processes - xargs tries to run kill with no arguments, resulting in an error.

My xargs does not accept -r or --no-run-if-empty args, as suggested in answers to a related question that doesn't specify POSIX compliance.

答:
Yes normally, there's the -r option to xargs, see:

https://unix.stackexchange.com/questions/521595/if-there-is-empty-stdin-or-whatever-tell-xargs-not-to-care/521599#521599

Otherwise you can create a bash function and put in the pipeline before xargs:

```<code>handle_empty(){
  while read line; do
    if test -z "$line"; then
        echo 'There was an empty line, exiting.' > /dev/stderr
        exit 0
    fi
    echo "$line"
  done
}

export -f handle_empty
</code>```

and use it like so:

```<code>docker volume ls -qf dangling=true | handle_empty | xargs docker volume rm
</code>```

for more info see:
https://gist.github.com/ORESoftware/bb8f97354ff38ee4a0a1dd1589af571a

ContentLicense: CC BY-SA 3.0

Body:
I'm not that good with bash, but I'm trying to create a script to kill some java processes:

/usr/ucb/ps -auxww    \
  | grep 'XUnit'      \
  | grep -v 'grep'    \
  | cut -c -2000      \
  | awk '{print $2;}' \
  | xargs kill

cut is used here because awk can fail with excessively long lines (see references to LINE_MAX limit in the POSIX specification for awk).

The problem occurs when there are no such processes - xargs tries to run kill with no arguments, resulting in an error.

My xargs does not accept -r or --no-run-if-empty args, as suggested in answers to a related question that doesn't specify POSIX compliance.

Body:
Yes normally, there's the -r option to xargs, see:

https://unix.stackexchange.com/questions/521595/if-there-is-empty-stdin-or-whatever-tell-xargs-not-to-care/521599#521599

Otherwise you can create a bash function and put in the pipeline before xargs:

handle_empty(){
  while read line; do
    if test -z "$line"; then
        echo 'There was an empty line, exiting.' > /dev/stderr
        exit 0
    fi
    echo "$line"
  done
}

export -f handle_empty

and use it like so:

docker volume ls -qf dangling=true | handle_empty | xargs docker volume rm

for more info see:
https://gist.github.com/ORESoftware/bb8f97354ff38ee4a0a1dd1589af571a


问:
Move a line through a given direction in D3 js?
I created x,y,z plain using d3.js, and I want to move each axis through the initial direction. Eg: x axis - horizontally, y axis - vertically and z axis - Given direction. I could change the code to move x axis horizontally and y axis vertically. But I couldn't do it for the other (z) axis. I need to change the code to move z axis through initial direction.

Below is my d3.js code. Full code is here, x,y,z plane

```<code>var width = 600,
    height = 600,
    activeClassName = 'active-d3-item';

var svg = d3.select('.plane').append('svg');
svg.attr('width', width);
svg.attr('height', height);

//The data for our lines and endpoints
var data = [
    {
        'x1': 100,
        'y1': 300,
        'x2': 100,
        'y2': 50
    },
    {
        'x1': 100,
        'y1': 300,
        'x2': 300,
        'y2': 300
    },
    {
        'x1': 100,
        'y1': 300,
        'x2': 39,
        'y2': 239
    }
];

// Generating the svg lines attributes
var lineAttributes = {
    'x1': function(d) {
        return d.x1;
    },
    'y1': function(d) {
        return d.y1;
    },
    'x2': function(d) {
        return d.x2;
    },
    'y2': function(d) {
        return d.y2;
    }
};

// Pointer to the d3 lines
var lines = svg
    .selectAll('line')
    .data(data)
    .enter()
    .append('line')
    .attr(lineAttributes);

var topEndPoints = data.map(function(line, i) {
    return {
        'x': line.x1,
        'y': line.y1,
        'marker': 'marker-start',
        'lineIndex': i
    };
});

var bottomEndPoints = data.map(function(line, i) {
    return {
        'x': line.x2,
        'y': line.y2,
        'marker': 'marker-end',
        'lineIndex': i
    };
});

var endPointsData = bottomEndPoints;

// Generating the svg circle attributes
var endPointsAttributtes = {
    'r': 7,
    'cx': function(d) {
        return d.x;
    },
    'cy': function(d) {
        return d.y;
    }
};

var drag = d3.behavior.drag()
    .origin(function(d) { return d; })
    .on('dragstart', dragstarted)
    .on('drag', dragged)
    .on('dragend', dragended);

// Pointer to d3 circles
var endPoints = svg
    .selectAll('circle')
    .data(endPointsData)
    .enter()
    .append('circle')
    .attr(endPointsAttributtes)
    .call(drag);

function dragstarted() {
    d3.select(this).classed(activeClassName, true);
}

function dragged(d, i) {
    var marker = d3.select(this);

    // Update the marker properties
    if(d.lineIndex === 0) {
        marker.attr('cy', d.y = d3.event.y); //Drag line 1 only through y axis.
    } else if(d.lineIndex === 1) {
        marker.attr('cx', d.x = d3.event.x); //Drag line 2 only through x axis.
    } else if(d.lineIndex === 2) {
            marker.attr('cx', d.x = d3.event.x).attr('cy', d.y = d3.event.y);
    }

    // Update the line properties
    lines
        .filter(function(lineData, lineIndex) {

            return lineIndex === d.lineIndex;
        }).attr('x1', function(lineData) {
             return d.marker === 'marker-start' ? lineData.x1 = d.x : lineData.x1;
         }).attr('y1', function(lineData) {
            return d.marker === 'marker-start' ? lineData.y1 = d.y : lineData.y1;
        })
        .attr('x2', function(lineData) {
            return d.marker === 'marker-end' ? lineData.x2 = d.x : lineData.x2;
        }).attr('y2', function(lineData) {
         return d.marker === 'marker-end' ? lineData.y2 = d.y : lineData.y2;
     });
}

function dragended() {
    d3.select(this).classed(activeClassName, false);
}
</code>```

I want to move the z axis only through the initial direction.

答:
You'll have to perform the vector of mouse position from origin projection onto the unit vector of the axis; have a look at https://en.wikipedia.org/wiki/Vector_projection

<!DOCTYPE html>

  <meta charset="utf-8">

```

Body:
I created x,y,z plain using d3.js, and I want to move each axis through the initial direction. Eg: x axis - horizontally, y axis - vertically and z axis - Given direction. I could change the code to move x axis horizontally and y axis vertically. But I couldn't do it for the other (z) axis. I need to change the code to move z axis through initial direction.

Below is my d3.js code. Full code is here, x,y,z plane

var width = 600,
    height = 600,
    activeClassName = 'active-d3-item';

var svg = d3.select('.plane').append('svg');
svg.attr('width', width);
svg.attr('height', height);

//The data for our lines and endpoints
var data = [
    {
        'x1': 100,
        'y1': 300,
        'x2': 100,
        'y2': 50
    },
    {
        'x1': 100,
        'y1': 300,
        'x2': 300,
        'y2': 300
    },
    {
        'x1': 100,
        'y1': 300,
        'x2': 39,
        'y2': 239
    }
];

// Generating the svg lines attributes
var lineAttributes = {
    'x1': function(d) {
        return d.x1;
    },
    'y1': function(d) {
        return d.y1;
    },
    'x2': function(d) {
        return d.x2;
    },
    'y2': function(d) {
        return d.y2;
    }
};

// Pointer to the d3 lines
var lines = svg
    .selectAll('line')
    .data(data)
    .enter()
    .append('line')
    .attr(lineAttributes);

var topEndPoints = data.map(function(line, i) {
    return {
        'x': line.x1,
        'y': line.y1,
        'marker': 'marker-start',
        'lineIndex': i
    };
});

var bottomEndPoints = data.map(function(line, i) {
    return {
        'x': line.x2,
        'y': line.y2,
        'marker': 'marker-end',
        'lineIndex': i
    };
});

var endPointsData = bottomEndPoints;

// Generating the svg circle attributes
var endPointsAttributtes = {
    'r': 7,
    'cx': function(d) {
        return d.x;
    },
    'cy': function(d) {
        return d.y;
    }
};

var drag = d3.behavior.drag()
    .origin(function(d) { return d; })
    .on('dragstart', dragstarted)
    .on('drag', dragged)
    .on('dragend', dragended);

// Pointer to d3 circles
var endPoints = svg
    .selectAll('circle')
    .data(endPointsData)
    .enter()
    .append('circle')
    .attr(endPointsAttributtes)
    .call(drag);

function dragstarted() {
    d3.select(this).classed(activeClassName, true);
}

function dragged(d, i) {
    var marker = d3.select(this);

    // Update the marker properties
    if(d.lineIndex === 0) {
        marker.attr('cy', d.y = d3.event.y); //Drag line 1 only through y axis.
    } else if(d.lineIndex === 1) {
        marker.attr('cx', d.x = d3.event.x); //Drag line 2 only through x axis.
    } else if(d.lineIndex === 2) {
            marker.attr('cx', d.x = d3.event.x).attr('cy', d.y = d3.event.y);
    }

    // Update the line properties
    lines
        .filter(function(lineData, lineIndex) {

            return lineIndex === d.lineIndex;
        }).attr('x1', function(lineData) {
             return d.marker === 'marker-start' ? lineData.x1 = d.x : lineData.x1;
         }).attr('y1', function(lineData) {
            return d.marker === 'marker-start' ? lineData.y1 = d.y : lineData.y1;
        })
        .attr('x2', function(lineData) {
            return d.marker === 'marker-end' ? lineData.x2 = d.x : lineData.x2;
        }).attr('y2', function(lineData) {
         return d.marker === 'marker-end' ? lineData.y2 = d.y : lineData.y2;
     });
}

function dragended() {
    d3.select(this).classed(activeClassName, false);
}

I want to move the z axis only through the initial direction.

Body:
You'll have to perform the vector of mouse position from origin projection onto the unit vector of the axis; have a look at https://en.wikipedia.org/wiki/Vector_projection

<!DOCTYPE html>

<head>
  <meta charset="utf-8">
  <script src="https://d3js.org/d3.v4.min.js"></script>
  <style>
    body {
      margin: 0;
      position: fixed;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
    }
  </style>
</head>

<body>
  <script>
    var start = [0, 0];
    var end = [100, 20];

    var length = Math.sqrt(Math.pow(start[0] - end[0], 2) +
      Math.pow(start[1] - end[1], 2));

    var dirUnitVector = [
      (end[0] - start[0]) / length,
      (end[1] - start[1]) / length
    ];

    var svg = d3.select("body").append("svg")
      .attr("width", 300)
      .attr("height", 200)
      .attr('viewBox', '-10 0 120 20')
      .style('stroke', "black");

    svg.append('line')
      .attr('x1', start[0])
      .attr('y1', start[1])
      .attr('x2', end[0])
      .attr('y2', end[1]);

    var c = svg.append('circle')
      .attr('cx', start[0])
      .attr('cy', start[1])
      .attr('r', 2)
      .style('fill', 'blue')
      .call(d3.drag().on("drag", function() {
        var mouseVector = [
          d3.event.x - start[0],
          d3.event.y - start[1]
        ];
        var projection =
          mouseVector[0] * dirUnitVector[0] +
          mouseVector[1] * dirUnitVector[1];
        c.attr('cx', start[0] + dirUnitVector[0] * projection);
        c.attr('cy', start[1] + dirUnitVector[1] * projection);
      }));
  </script>
</body>


问:
Configure Heartbeat with Elasticsearch to parse Json Result
I've configured elasticsearch, kibana and heartbeat and I do see results under "heartbeat" coming in.

However whatever processors I add to a monitor I do not see any extra data:
https://www.elastic.co/guide/en/beats/heartbeat/current/add-tags.html

```<code>- type: http
  urls: ["http://localhost:8359/api/heartbeat"]
  schedule: '@every 10s'
  processors:
  - add_tags:
    tags: [web123, production123]
</code>```

I would like to store the actual JSON response which I get when i query my service: http://localhost:8359/api/heartbeat (not just HTTP 200). And would like to show this reponse in Kibana somewhere under "Uptime" section

Sample json response from endpoint:

```<code>{
    "StatusCode": 2,
    "Messages": [
        "interface not found: MyTestService"
    ],
    "Type": "MyTestService",
    "IsValid": false
}
</code>```

答:
Solution:

```<code>  schedule: '@every 2m'
  check.response:
    status: 200
    json:
      - description: Json Response
        condition:
          equals:
            Status: Ok
</code>```

Where "Status" is one of my json properties that is being returned.

Body:
I've configured elasticsearch, kibana and heartbeat and I do see results under "heartbeat" coming in.

However whatever processors I add to a monitor I do not see any extra data:
https://www.elastic.co/guide/en/beats/heartbeat/current/add-tags.html

- type: http
  urls: ["http://localhost:8359/api/heartbeat"]
  schedule: '@every 10s'
  processors:
  - add_tags:
    tags: [web123, production123]

I would like to store the actual JSON response which I get when i query my service: http://localhost:8359/api/heartbeat (not just HTTP 200). And would like to show this reponse in Kibana somewhere under "Uptime" section

Sample json response from endpoint:

{
    "StatusCode": 2,
    "Messages": [
        "interface not found: MyTestService"
    ],
    "Type": "MyTestService",
    "IsValid": false
}

Body:
Solution:

  schedule: '@every 2m'
  check.response:
    status: 200
    json:
      - description: Json Response
        condition:
          equals:
            Status: Ok

Where "Status" is one of my json properties that is being returned.


问:
Is it wrong to call component methods passed as arguments inside of redux actions?
I'm struggling with one task I've been appointed to and the only workaround I found is to call the action argument callback inside the action. Is this a bad idea from a design point of view, because the code itself works and passes numerous tests? The general purpose of this solution is to somehow trigger the component function when a certain logic is being followed.

export function myAction(componentClb: () => void): any {
  return (dispatch: Dispatch<AppStore>): void => {
    someRESTAPIcall()
      .then((condition) => {
        condition
          ? dispatch(anotherActionThatTakesCallbackAsArgument(componentClb))
          : componentClb();
      })
      .catch((error: Error) => {
        dispatch(myErrorAction());
      });
  };
}

```

答:
The biggest mistake about this is to take React components as functional classes. Components really are just to handle the WHAT and HOW of page rendering. Anything outside of rendering logics should be removed from it.

Instead of working as callback, this anotherActionThatTakesCallbackAsArgument should update the redux store.

The container that componentClb belongs to should be connected to redux store and selects the fields from the stores, and pass these fields to componentClb as props, so that componentClb can handle the rendering based on the response of myAction

With the info you provided, it's hard to give a concrete code example. Maybe describe the scenario you are trying to solve and people are able to give you more direct feedbacks.


问:
Read model with data from multiple aggregate roots (different contexts)
I'm curious to how to join data from multiple aggregate roots in an read model for an event sourced aggregate root. Can try to take a simple example:

If I have an aggregate root called Cart which supports following events in it's event stream (properties in parentheses - keep in mind this is an simple example):

```<code>AddProductToCart(cartId: Int, productId: Int)
RemoveProductFromCart(cartId: Int, productId: Int)
AddUserLicenseToProduct(cartId: Int, productId: Int, userId: Int)
RemoveUserLicenseFromProduct(cartId: Int, productId: Int, userId: Int)
EmptyCart(cartId: Int)
</code>```

It's ok when projecting read models with data coming from this event stream. I can for example project a cart object which looks something like this:

```<code>Cart(cartId: Int, products: List[Product])

Product(productId: Int, userLicenses: List[UserLicense])
UserLicense(userId: Int)
</code>```

But how does one join data from another aggregate root in another context into this cart projection. For example if I wanted to extend the read model with data from the Product aggregate root which lives in another context. Let's say I would like to extend it with productName and productType.

Take into consideration we are working in an distributed system, where Product and Cart would be live in different services/applications.

I suppose one solution would be to include the data in the commands and events. But that doesn't seem to scale very well if one would have larger read models with data from multiple aggregate roots. Also one has to be able to nuke and rebuild the read model.

I suppose another solution would be to duplicate data from other aggregate roots into the storage of other applications/services/contexts. For example duplicate the productName and productType data into storage owned be the Cart application, but not have it be a part of the Cart event stream. The Cart application would then have to listen to events (e.g. ProductCreated, ProductNameChanged) to keep data updated. I guess this might be a viable solution.

答:
Each bounded context should be loosely coupled. We had a similar issue with two of our contexts. The solution that we found was to use workflows by creating all the communication between contexts in those files. In which we could synchronize the required schemas by subscribing to an event handler. As we used Elixir, the library that we have been used is Commanded, which have its own Event Bus.

But in a distributed systems you can use Apache Kafka. At the end of the day, I think that the easier solution should keep your schemas the cleanest possible (it also going to help you to respect the GDPR compliance) and to manage all your communication through a separate layer by an event handler.

To see this solution in a "real-life" way, I can recommend you a great example repository built with Elixir.

https://leanpub.com/buildingconduit/read

Body:
I'm curious to how to join data from multiple aggregate roots in an read model for an event sourced aggregate root. Can try to take a simple example:

If I have an aggregate root called Cart which supports following events in it's event stream (properties in parentheses - keep in mind this is an simple example):

AddProductToCart(cartId: Int, productId: Int)
RemoveProductFromCart(cartId: Int, productId: Int)
AddUserLicenseToProduct(cartId: Int, productId: Int, userId: Int)
RemoveUserLicenseFromProduct(cartId: Int, productId: Int, userId: Int)
EmptyCart(cartId: Int)

It's ok when projecting read models with data coming from this event stream. I can for example project a cart object which looks something like this:

Cart(cartId: Int, products: List[Product])

Product(productId: Int, userLicenses: List[UserLicense])
UserLicense(userId: Int)

But how does one join data from another aggregate root in another context into this cart projection. For example if I wanted to extend the read model with data from the Product aggregate root which lives in another context. Let's say I would like to extend it with productName and productType.

Take into consideration we are working in an distributed system, where Product and Cart would be live in different services/applications.

I suppose one solution would be to include the data in the commands and events. But that doesn't seem to scale very well if one would have larger read models with data from multiple aggregate roots. Also one has to be able to nuke and rebuild the read model.

I suppose another solution would be to duplicate data from other aggregate roots into the storage of other applications/services/contexts. For example duplicate the productName and productType data into storage owned be the Cart application, but not have it be a part of the Cart event stream. The Cart application would then have to listen to events (e.g. ProductCreated, ProductNameChanged) to keep data updated. I guess this might be a viable solution.


问:
Validating models against the parent model
I have two models, one is the parent of the other, and the parent accepts_nested_attributes_for and validates_associated the children.

However, some of my validations have an :if that needs to check one of the properties of the parent.

I was thinking that I could do something like this:

```<code>validates_presence_of :blah, :if => Proc.new{|thing| thing.parent.some_value.present?}
</code>```

However, the 'parent' relationship doesn't appear to be setup at the time of validation (I would assume the children get instantiated and validated first.

Therefore is there any way of doing what I'm thinking of? Is it possible?

答:
This kind of validation should work:

validates_associated :children

But it won't

The reason is, as far as I understand, beause using acceptes_nested_attributes_for is creating nested objects straight to database via one transaction without passing any children validations.

What you can do here: write your own validation in parent model and validate creating children objects.

Body:
I have two models, one is the parent of the other, and the parent accepts_nested_attributes_for and validates_associated the children.

However, some of my validations have an :if that needs to check one of the properties of the parent.

I was thinking that I could do something like this:

validates_presence_of :blah, :if => Proc.new{|thing| thing.parent.some_value.present?}

However, the 'parent' relationship doesn't appear to be setup at the time of validation (I would assume the children get instantiated and validated first.

Therefore is there any way of doing what I'm thinking of? Is it possible?


问:
How to compare element position in xpath
I am trying to compare customer account values to display only different values and ignore duplicate in XPath:

XML code:

```<code><info>
  <Customer CustAccount="1"/>
  <Customer CustAccount="2"/>
  <Customer CustAccount="2"/>
  <Customer CustAccount="3"/>
</info>
</code>```

The result should compare customer 1/2/3 and display:

```<code>customer 1
customer 2
customer 3
</code>```

答:
You can achieve this with the XPath-2.0 expression

```<code>for $c in distinct-values(/info/Customer/@CustAccount) return concat('customer ',$c,'
')
</code>```

Output is:

```<code>customer 1
customer 2
customer 3
</code>```

If you do not like the newlines, remove the
 from the expression.

There is no pure XPath-1.0 expression achieving this; you could only do this with XSLT-1.0 if XPath-2.0 is unavailable.

Body:
I am trying to compare customer account values to display only different values and ignore duplicate in XPath:

XML code:

<info>
  <Customer CustAccount="1"/>
  <Customer CustAccount="2"/>
  <Customer CustAccount="2"/>
  <Customer CustAccount="3"/>
</info>

The result should compare customer 1/2/3 and display:

customer 1
customer 2
customer 3

Body:
You can achieve this with the XPath-2.0 expression

for $c in distinct-values(/info/Customer/@CustAccount) return concat('customer ',$c,'&#xa;')

Output is:

customer 1
customer 2
customer 3

If you do not like the newlines, remove the &#xa; from the expression.

There is no pure XPath-1.0 expression achieving this; you could only do this with XSLT-1.0 if XPath-2.0 is unavailable.


问:
How to fix matplotlib installation errors
I do not know how to fix this, any help is appreciated. Thanks in advance
-J

I have tried various ways of installing and importing matplotlib (though command prompt, the text editor I've been using (geany). and neither option has worked. I've also installed the .whl file from https://matplotlib.org/ and it still has not worked (gives the same error)

I originally used the code:

import matplotlib.pyplot as plt
```

<p>in my text editor (<em>geany</em>) to install <em>matplotlib</em> but this gave the error shown below</p>

<p><strong><em>Expected Results:</em></strong></p>

<p>I expect it to import and install the right version of matplotlib (I think the right version for me is matplotlib 3.0 because I'm using python 3.7).</p>

<p><strong><em>Actual Results:</em></strong></p>

<p>When I type 'python -m pip install -U matplotlib' into my command prompt (I'm on windows 10, using python 3.7) it displays: </p>

```WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))': /simple/matplotlib/
```

<p>and repeats the message for a total of 5 times then displays: </p>

```Could not fetch URL https://pypi.org/simple/matplotlib/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/matplotlib/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))) - skipping
```

<p>and finishes with the error: </p>

```ERROR: Could not find a version that satisfies the requirement matplotlib (from versions: none)
ERROR: No matching distribution found for matplotlib
```

I have tried to fix this SSLError but I haven't made any progress in this simply because I don't know where to start.

Thanks again for any help

答: A huge thank you to @Louis 'LYRO' Dupont and @Quang Hoang for helping me work through this. What I ended up doing was going to pypi.python.org and downloading all of the requirements as .whl files in order to run matplotlib. This took a bit of work as I had to try to install matplotlib after installing each requirement to see what the next one I needed was. Thanks again to both you guys and have a nice week!</p>

Body:
I do not know how to fix this, any help is appreciated. Thanks in advance
-J

I have tried various ways of installing and importing matplotlib (though command prompt, the text editor I've been using (geany). and neither option has worked. I've also installed the .whl file from https://matplotlib.org/ and it still has not worked (gives the same error)

I originally used the code:

import matplotlib.pyplot as plt

in my text editor (geany) to install matplotlib but this gave the error shown below

Expected Results:

I expect it to import and install the right version of matplotlib (I think the right version for me is matplotlib 3.0 because I'm using python 3.7).

Actual Results:

When I type 'python -m pip install -U matplotlib' into my command prompt (I'm on windows 10, using python 3.7) it displays:

WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))': /simple/matplotlib/

and repeats the message for a total of 5 times then displays:

Could not fetch URL https://pypi.org/simple/matplotlib/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/matplotlib/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))) - skipping

and finishes with the error:

ERROR: Could not find a version that satisfies the requirement matplotlib (from versions: none)
ERROR: No matching distribution found for matplotlib

I have tried to fix this SSLError but I haven't made any progress in this simply because I don't know where to start.

Thanks again for any help


问:
Why use both local variable and volatile both togather for DCL (as suggested by Sonar tool)?
There are related questions but they as the focus in those is more on volatile and not much on the usage of local variable, hence I am posting a new question, Please see the question below.

Sonar Source rule has a code according to which below code is correct and solves the issues with DCL

```<code>class ResourceFactory {
  private volatile Resource resource;

  public Resource getResource() {
    Resource localResource = resource;
    if (localResource == null) {
      synchronized (this) {
        localResource = resource;
        if (localResource == null) {
          resource = localResource = new Resource();
        }
      }
    }
    return localResource;
  }

  static class Resource {
  }
}
</code>```

I understand that we have alternate options (some better than complicated DCL) like an

enum or

static inner class holder or

a static final reference initialized during its declaration itself.

declare the entire method as synchronized.

I wish to understand the usage of volatile along with local variable to resolve the issues for DCL.

Also I understand volatile (for Java 1.5 and later versions) guarantees the  'happens-before' feature which prevents the in-complete object being returned for reading.

Question 1 I want to understand as what is the need of volatile if a local variable has already been used.  Below code has non volatile variable resource but inside the getResource() a local variable is used to read the resource. Are there still issues in the code ? (Please see comments in below code below)

```<code>class ResourceFactory {
  private Resource resource; // non volatile
  public Resource getResource() {
    Resource localResource = resource; // only 1 read without lock
    if (localResource == null) {
      synchronized (this) {
        localResource = resource; // read inside the synchronized block
        if (localResource == null) {
           localResource = new Resource(); // constructor is initialized.
           resource = localResource; // ****code reaches here only when constructor has been complete. Here is there a chance of resource being referring to incomplete object ?****
        }
      }
    }
    return localResource;
  }

  static class Resource {
  }
}
</code>```

The only advantage I see is with volatile is suppose the object was created then the first read itself would have guaranteed a memory read instead of read from thread cache preventing unnecessary acquisition of lock.

Question 2 Instead of using local variable if simple volatile was used then was the code without issues ?

答:
Question 2 is directly addressed in Effective Java; whilst it may be mentioned in other editions too, the one I have in front of me is 3rd Ed, Item 83, p335:

The code may appear a bit convoluted. In particular, the need for the local variable (result) may be unclear. What this variable does is to ensure that field is read only once in the common case where it's already initialized. While not strictly necessary, this may improve performance and is more elegant by the standards applied to low-level concurrent programming. On my machine, the method above is about 1.4 times as fast as the obvious version without a local variable.

(Note that 3rd Ed has a serious error in the code sample for double-checked locking (immediately preceding this quote) in early printings! Check out the errata for corrected code.)

Body:
There are related questions but they as the focus in those is more on volatile and not much on the usage of local variable, hence I am posting a new question, Please see the question below.

Sonar Source rule has a code according to which below code is correct and solves the issues with DCL

class ResourceFactory {
  private volatile Resource resource;

  public Resource getResource() {
    Resource localResource = resource;
    if (localResource == null) {
      synchronized (this) {
        localResource = resource;
        if (localResource == null) {
          resource = localResource = new Resource();
        }
      }
    }
    return localResource;
  }

  static class Resource {
  }
}

I understand that we have alternate options (some better than complicated DCL) like an

enum or

static inner class holder or

a static final reference initialized during its declaration itself.

declare the entire method as synchronized.

I wish to understand the usage of volatile along with local variable to resolve the issues for DCL.

Also I understand volatile (for Java 1.5 and later versions) guarantees the  'happens-before' feature which prevents the in-complete object being returned for reading.

Question 1 I want to understand as what is the need of volatile if a local variable has already been used.  Below code has non volatile variable resource but inside the getResource() a local variable is used to read the resource. Are there still issues in the code ? (Please see comments in below code below)

class ResourceFactory {
  private Resource resource; // non volatile
  public Resource getResource() {
    Resource localResource = resource; // only 1 read without lock
    if (localResource == null) {
      synchronized (this) {
        localResource = resource; // read inside the synchronized block
        if (localResource == null) {
           localResource = new Resource(); // constructor is initialized.
           resource = localResource; // ****code reaches here only when constructor has been complete. Here is there a chance of resource being referring to incomplete object ?****
        }
      }
    }
    return localResource;
  }

  static class Resource {
  }
}

The only advantage I see is with volatile is suppose the object was created then the first read itself would have guaranteed a memory read instead of read from thread cache preventing unnecessary acquisition of lock.

Question 2 Instead of using local variable if simple volatile was used then was the code without issues ?


问:
create a macro variable to store all variable names of a dataset
I'm a beginner in sas.
I have a data set work.data2 with variables that include all variables from another dataset work.data1.

here is what I want to do:

```<code>data temp;
    set data2 (keep = [list of all variables in data1] key2 key3);
run;
</code>```

First I need to create a macro variable to store all variable names in data1.
if it's in python i can just do

```<code>List=list(data1)
</code>```

but it seems much harder to realize in sas...Please help. Thank you very much!

答:
There are plenty of way to get lists of variable names into data.  You could use PROC CONTENTS with OUT= option.  Or query the DICTIONARY.COLUMNS metadata from PROC SQL. (or the view SASHELP.VCOLUMN that points to the same metadata).

But here is a method that does not require pulling the names.  First make an empty new dataset with the same structure as DATA1 plus your extra variables.  Then append the data from DATA2.

```<code>data temp;
  set data1(obs=0) data2(obs=0 keep=key1 key2);
run;
proc append base=temp data=data2 force;
run;
</code>```

Body:
I'm a beginner in sas.
I have a data set work.data2 with variables that include all variables from another dataset work.data1.

here is what I want to do:

data temp;
    set data2 (keep = [list of all variables in data1] key2 key3);
run;

First I need to create a macro variable to store all variable names in data1.
if it's in python i can just do

List=list(data1)

but it seems much harder to realize in sas...Please help. Thank you very much!

Body:
There are plenty of way to get lists of variable names into data.  You could use PROC CONTENTS with OUT= option.  Or query the DICTIONARY.COLUMNS metadata from PROC SQL. (or the view SASHELP.VCOLUMN that points to the same metadata).

But here is a method that does not require pulling the names.  First make an empty new dataset with the same structure as DATA1 plus your extra variables.  Then append the data from DATA2.

data temp;
  set data1(obs=0) data2(obs=0 keep=key1 key2);
run;
proc append base=temp data=data2 force;
run;


问:
I am unable to configure/create a project with Specflow3 and VS2017
I am trying to create POM with specflow3 in VS2017. I have added below nuget packages. I am facing issues while setting up the project itself

Specflow.Nunit

Speclow.Tools.MSBuild.Generation

Specflow.NUnit.Testrunnen

Nunit test adapter plugin and specflow2017 plugin.

I have created a feature file and i am trying to build the solution. I am getting following error.

"Program doesnot contain a static main method suitable for an entry point." Kindly let me know the solution. It would be great help. Thanks in advance

答: Can you try to use specflow version 2.4.1</p>


问:
how to extract a number in between strings using regex
I have the following text

Stat indicator : 01245 Values loaded

Some irrelevant data

Stat indicator : 13452 Values loaded

My output should be giving me numbers 01245, 13452

Heres what I have tried

```<code>with open('test.txt') as fd:
    data = fd.read()
val_to_pattern = {'stat': r'Stat indicator : .{5}\n'}
val_dict = {}
for key, patt in val_to_pattern.items():
    val_dict[key] = re.findall(patt, data)
</code>```

答:
Use

```<code>val_to_pattern = {'stat': r'Stat indicator\s*:\s*(\d+)'}
</code>```

Note that \s*:\s* pattern matches a : optionally wrapped with 0+ whitespaces and the (\d+) part matches and captures into Group 1 any 0+ digits (note that re.findall only returns captured substrings if capturing groups are set in the regex).

See the regex demo (the green text will be the result).

Alternatively, if the number of digits in the indicator stats is always 5 use either of

```<code> val_to_pattern = {'stat': r'Stat indicator\s*:\s*(\d{5})\b'}
 val_to_pattern = {'stat': r'Stat indicator\s*:\s*(\d{5})(?!\d)'}
</code>```

\b is word boundary that will require a non-word char or end of string after 5 digits and the (?!\d) is a negative lookahead that fails the match if there is a digit immediately to the right of the current location.

Body:
I have the following text

Stat indicator : 01245 Values loaded

Some irrelevant data

Stat indicator : 13452 Values loaded

My output should be giving me numbers 01245, 13452

Heres what I have tried

with open('test.txt') as fd:
    data = fd.read()
val_to_pattern = {'stat': r'Stat indicator : .{5}\n'}
val_dict = {}
for key, patt in val_to_pattern.items():
    val_dict[key] = re.findall(patt, data)

Body:
Use

val_to_pattern = {'stat': r'Stat indicator\s*:\s*(\d+)'}

Note that \s*:\s* pattern matches a : optionally wrapped with 0+ whitespaces and the (\d+) part matches and captures into Group 1 any 0+ digits (note that re.findall only returns captured substrings if capturing groups are set in the regex).

See the regex demo (the green text will be the result).

Alternatively, if the number of digits in the indicator stats is always 5 use either of

 val_to_pattern = {'stat': r'Stat indicator\s*:\s*(\d{5})\b'}
 val_to_pattern = {'stat': r'Stat indicator\s*:\s*(\d{5})(?!\d)'}

\b is word boundary that will require a non-word char or end of string after 5 digits and the (?!\d) is a negative lookahead that fails the match if there is a digit immediately to the right of the current location.


问:
Test dispatch called with correct obj inside handleChange method
I'm new to jest so I am struggling. I am using the react-select package. When you select an item it triggers the handleChange method to be called with a selectedOption argument like {value:'some value'}. I want to test that dispatch is called within handleChange and that its called with the correct object.

here is the handleChange method

```<code>export class CustomerSelect extends React.Component {
      //other code

      handleChange = selectedOption => {
        const obj = {
          type: 'SET_CUSTOMER',
          payload: selectedOption.value
        };
        this.props.dispatch(obj);
      };

     //other code
}
</code>```

here is my test code

```<code>let wrapper, instance, dispatch, customers;

beforeEach(() => {
  customers = ['test1', 'test2', 'test3'];
  dispatch = jest.fn();
  wrapper = shallow(<CustomerSelect customers={customers} dispatch={dispatch} />);
  instance = wrapper.instance();
});

  test('fire off dispatch on change', () => {
    const handleChangeSpy = jest.spyOn(instance, 'handleChange');
    instance.forceUpdate();
    const selectedOption = { value: customers[1] };
    const obj = {
        type: 'SET_CUSTOMER',
        payload: selectedOption.value
      };

    wrapper.find(Select).simulate('change', { selectedOption });

    //check handleChange was called
    expect(handleChangeSpy).toHaveBeenCalledWith({
      selectedOption
    });

    //check dispatch was called
    expect(dispatch).toHaveBeenCalledWith(obj);
  });
</code>```

What's happening is that it's not picking up on the selectedOption as I get an error

```<code>  Object {
-   "payload": "test2",
+   "payload": undefined,
    "type": "SET_ACCOUNT",
  }
</code>```

any help would be appreciated.

答:
I think you are sending wrong parameter, try that</p>

```<code>wrapper.find(Select).simulate('change', selectedOption);

//check handleChange was called
expect(handleChangeSpy).toHaveBeenCalledWith(selectedOption);
expect(dispatch).toHaveBeenCalledWith(obj);
</code>```

Body:
I'm new to jest so I am struggling. I am using the react-select package. When you select an item it triggers the handleChange method to be called with a selectedOption argument like {value:'some value'}. I want to test that dispatch is called within handleChange and that its called with the correct object.

here is the handleChange method

export class CustomerSelect extends React.Component {
      //other code

      handleChange = selectedOption => {
        const obj = {
          type: 'SET_CUSTOMER',
          payload: selectedOption.value
        };
        this.props.dispatch(obj);
      };

     //other code
}

here is my test code

let wrapper, instance, dispatch, customers;

beforeEach(() => {
  customers = ['test1', 'test2', 'test3'];
  dispatch = jest.fn();
  wrapper = shallow(<CustomerSelect customers={customers} dispatch={dispatch} />);
  instance = wrapper.instance();
});

  test('fire off dispatch on change', () => {
    const handleChangeSpy = jest.spyOn(instance, 'handleChange');
    instance.forceUpdate();
    const selectedOption = { value: customers[1] };
    const obj = {
        type: 'SET_CUSTOMER',
        payload: selectedOption.value
      };

    wrapper.find(Select).simulate('change', { selectedOption });

    //check handleChange was called
    expect(handleChangeSpy).toHaveBeenCalledWith({
      selectedOption
    });

    //check dispatch was called
    expect(dispatch).toHaveBeenCalledWith(obj);
  });

What's happening is that it's not picking up on the selectedOption as I get an error

  Object {
-   "payload": "test2",
+   "payload": undefined,
    "type": "SET_ACCOUNT",
  }

any help would be appreciated.

Body:
I think you are sending wrong parameter, try that

wrapper.find(Select).simulate('change', selectedOption);

//check handleChange was called
expect(handleChangeSpy).toHaveBeenCalledWith(selectedOption);
expect(dispatch).toHaveBeenCalledWith(obj);


问:
Google Sheets Conditional Formatting of another cell based on variable values
I have rows that include various totals of either 5, 10 or 12. I also have checkboxes that add up to a total of 12, and a cell value for each row that calculates the difference to reveal how many are left.

I'm wanting the last result cells to show colours from red to yellow to green that is independently reliant on the first cells value to show a specific shade of green/yellow/red. I'm only able to select a colour based on the single columns/cells value and not the value of another column/cell. Is this even possible?

I've run through a number of examples given on google and answers based on similar questions, but nothing seems to solve this specific situation.

This is what I'm expecting to happen: Green Yellow Red

For Green Total:

```<code>Row 0:  Column A:         | Column B:     | Column C:

Row 1:  Classes Available | Classes Left  | Colour

Row 2:  10                | 10            | Green

Row 3:  5                 | 5             | Green

Row 4:  12                | 12            | Green
</code>```

For Variable Total:

```<code>Row 0:  Column A:         | Column B:     | Column C:

Row 1:  Classes Available | Classes Left  | Colour

Row 2:  10                | 5             | Yellow

Row 3:  5                 | 4             | Green

Row 4:  12                | 3             | Red
</code>```

For Red Total:

```<code>Row 0:  Column A:         | Column B:     | Column C:

Row 1:  Classes Available | Classes Left  | Colour

Row 2:  10                | 0             | Red

Row 3:  5                 | 1             | Red

Row 4:  12                | 2             | Red
</code>```

Basically: If we're looking at 3 cells next to each other in ABC, then if B is the variable, and A is the total value, then C should show the colour based on how equal B is to A for Green, or how much lower the value of B is to A for Yellow to Red.

答: You can use cell references in your conditional formatting formulas. Try using custom formulas for more flexibility.</p>

Body:
I have rows that include various totals of either 5, 10 or 12. I also have checkboxes that add up to a total of 12, and a cell value for each row that calculates the difference to reveal how many are left.

I'm wanting the last result cells to show colours from red to yellow to green that is independently reliant on the first cells value to show a specific shade of green/yellow/red. I'm only able to select a colour based on the single columns/cells value and not the value of another column/cell. Is this even possible?

I've run through a number of examples given on google and answers based on similar questions, but nothing seems to solve this specific situation.

This is what I'm expecting to happen: Green Yellow Red

For Green Total:

Row 0:  Column A:         | Column B:     | Column C:

Row 1:  Classes Available | Classes Left  | Colour

Row 2:  10                | 10            | Green

Row 3:  5                 | 5             | Green

Row 4:  12                | 12            | Green

For Variable Total:

Row 0:  Column A:         | Column B:     | Column C:

Row 1:  Classes Available | Classes Left  | Colour

Row 2:  10                | 5             | Yellow

Row 3:  5                 | 4             | Green

Row 4:  12                | 3             | Red

For Red Total:

Row 0:  Column A:         | Column B:     | Column C:

Row 1:  Classes Available | Classes Left  | Colour

Row 2:  10                | 0             | Red

Row 3:  5                 | 1             | Red

Row 4:  12                | 2             | Red

Basically: If we're looking at 3 cells next to each other in ABC, then if B is the variable, and A is the total value, then C should show the colour based on how equal B is to A for Green, or how much lower the value of B is to A for Yellow to Red.


问:
How to add a texfield inside the App bar in Flutter?
I'am having trouble in having a TextField on the AppBar so the user can enter input  similarly to using a search bar. I need to take the user input and do something with it so it's not a search within my app. This is why it makes senses to use a TextField.

Now, I've succeeded in having the TextField on the left side of my AppBar . The problem is that the TextField is a square and doesn't take enough space so you can see what you're writing.

Link to what it looks like:

In code this is how it was made:

 @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Myseum',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
        fontFamily: 'Raleway',
      ),
      home: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text(
            "Myseum",
            style: TextStyle(
              fontFamily: 'Raleway',
              fontStyle: FontStyle.italic,
              fontSize: 25,
            ),
          ),
          leading: prefix0.TextBox(), // TextBox is the widget I made.
          backgroundColor: Colors.black,
        ),

```

<p>Now the widget <code>TextBox()</code></p>

<pre class="lang-dart prettyprint-override"><code>class TextBox extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.centerLeft,
      color: Colors.white,
      child: TextField(
        decoration:
            InputDecoration(border: InputBorder.none, hintText: 'Search'),
      ),
    );
  }
}

</code>```

答:
Like mentioned in the comments - put your text field in title widget... I converted your code to a simple stateful widget to give you an idea. </p>

```<code>class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool typing = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: typing ? TextBox() : Text("Title"),
        leading: IconButton(
          icon: Icon(typing ? Icons.done : Icons.search),
          onPressed: () {
            setState(() {
              typing = !typing;
            });
          },
        ),
      ),
      body: Center(
        child: Text("Your app content"),
      ),
    );
  }
}

class TextBox extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.centerLeft,
      color: Colors.white,
      child: TextField(
        decoration:
            InputDecoration(border: InputBorder.none, hintText: 'Search'),
      ),
    );
  }
}
</code>```

Body:
I'am having trouble in having a TextField on the AppBar so the user can enter input  similarly to using a search bar. I need to take the user input and do something with it so it's not a search within my app. This is why it makes senses to use a TextField.

Now, I've succeeded in having the TextField on the left side of my AppBar . The problem is that the TextField is a square and doesn't take enough space so you can see what you're writing.

Link to what it looks like:

In code this is how it was made:

 @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Myseum',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
        fontFamily: 'Raleway',
      ),
      home: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text(
            "Myseum",
            style: TextStyle(
              fontFamily: 'Raleway',
              fontStyle: FontStyle.italic,
              fontSize: 25,
            ),
          ),
          leading: prefix0.TextBox(), // TextBox is the widget I made.
          backgroundColor: Colors.black,
        ),

Now the widget TextBox()

class TextBox extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.centerLeft,
      color: Colors.white,
      child: TextField(
        decoration:
            InputDecoration(border: InputBorder.none, hintText: 'Search'),
      ),
    );
  }
}

Body:
Like mentioned in the comments - put your text field in title widget... I converted your code to a simple stateful widget to give you an idea.

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool typing = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: typing ? TextBox() : Text("Title"),
        leading: IconButton(
          icon: Icon(typing ? Icons.done : Icons.search),
          onPressed: () {
            setState(() {
              typing = !typing;
            });
          },
        ),
      ),
      body: Center(
        child: Text("Your app content"),
      ),
    );
  }
}

class TextBox extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.centerLeft,
      color: Colors.white,
      child: TextField(
        decoration:
            InputDecoration(border: InputBorder.none, hintText: 'Search'),
      ),
    );
  }
}


问:
Error while creating partial classes with LLBLGenPro
I simply am trying to declare partial classes for the tool-generated LLBLGenPro (partial) classes, so that I can use DataAnnotation for validation purposes. However, things don't seem to work here.

Following is how my code looks like :

```<code>namespace MyApp.DataLayer.EntityClasses
{
    [Serializable]
    public partial class LoginEntity : CommonEntityBase, ISerializable
    {
        .....
    }
}
</code>```

And for DataAnnotations ...

```<code>namespace MyApp.DataLayer.EntityClasses
{
    [MetadataType(typeof(LoginEntityValidation))]
    public partial class LoginEntity
    {

    }

    public class LoginEntityValidation
    {
        [Required(ErrorMessage = "Required !")]
        public string Username { get; set; }
    }
}
</code>```

// This gives me compile time errors "MyApp.DataLayer.EntityClasses.LoginEntity' does not contain a constructor that takes 1 arguments" and so on.

Any idea on how to make this working?

Thanks in advance !

答: You should not use your entity classes in views. You should use ViewModel classes and put validation there. For entity->viewmodel conversion you can use AutoMapper</p>

Body:
I simply am trying to declare partial classes for the tool-generated LLBLGenPro (partial) classes, so that I can use DataAnnotation for validation purposes. However, things don't seem to work here.

Following is how my code looks like :

namespace MyApp.DataLayer.EntityClasses
{
    [Serializable]
    public partial class LoginEntity : CommonEntityBase, ISerializable
    {
        .....
    }
}

And for DataAnnotations ...

namespace MyApp.DataLayer.EntityClasses
{
    [MetadataType(typeof(LoginEntityValidation))]
    public partial class LoginEntity
    {

    }

    public class LoginEntityValidation
    {
        [Required(ErrorMessage = "Required !")]
        public string Username { get; set; }
    }
}

// This gives me compile time errors "MyApp.DataLayer.EntityClasses.LoginEntity' does not contain a constructor that takes 1 arguments" and so on.

Any idea on how to make this working?

Thanks in advance !


问:
findOneAndUpdate mongodb push onto existing array
I have a 2d array of data and I want to push other arrays as single elements onto this array. The user will not have the entire array of arrays and will only put a new one in the database.

This is what I have so far but I need to know how to push the new array into my 2d array in the database:

```<code>.put((req, res)=>{
    mySchema.findOneAndUpdate({
        id:req.params.id
    },
    req.body,
    (err, updatedrate)=>{
        if(err)return res.status(500).send(err)
        return res.status(201).send(updatedrate)
    })
})
</code>```

答:
```<code>const db= new Schema({
    arrayName: [],
});

db.findOneAndUpdate({ _id }, { $push: { arrayName: itemAdd } }
</code>```

add itemAdd to arrayName

Body:
I have a 2d array of data and I want to push other arrays as single elements onto this array. The user will not have the entire array of arrays and will only put a new one in the database.

This is what I have so far but I need to know how to push the new array into my 2d array in the database:

.put((req, res)=>{
    mySchema.findOneAndUpdate({
        id:req.params.id
    },
    req.body,
    (err, updatedrate)=>{
        if(err)return res.status(500).send(err)
        return res.status(201).send(updatedrate)
    })
})

Body:
const db= new Schema({
    arrayName: [],
});

db.findOneAndUpdate({ _id }, { $push: { arrayName: itemAdd } }

add itemAdd to arrayName


问:
Why does this if-statement combining assignment and an equality check return true?
I've been thinking of some beginner mistakes and I ended up with the one on the if statement. I expanded a bit the code to this:

```<code>int i = 0;
if (i = 1 && i == 0) {
    std::cout << i;
}
</code>```

I have seen that the if statement returns true, and it cout's i as 1. If i is assigned 1 in the if statement, why did i == 0 return true?

答:
It has to do with parsing an the right to left rules.
Eg y = x+5.

All sub-expressions are weighted in importance.
Two expressions of equal importance are evaluated right to left, . The && expression side  is done first, followed by the LHS.

Makes sense to me.

Body:
I've been thinking of some beginner mistakes and I ended up with the one on the if statement. I expanded a bit the code to this:

int i = 0;
if (i = 1 && i == 0) {
    std::cout << i;
}

I have seen that the if statement returns true, and it cout's i as 1. If i is assigned 1 in the if statement, why did i == 0 return true?


问:
Git fatal: protocol 'https' is not supported
I am going through Github's forking guide: https://guides.github.com/activities/forking/
and I am trying to clone the repository onto my computer. However, running the command:

```<code>$ git clone https://github.com/./Spoon-Knife.git
Cloning into 'Spoon-Knife'...
fatal: protocol 'https' is not supported
</code>```

Also tried with SSH:

```<code>$ git clone git@github.com:./Spoon-Knife.git
Cloning into 'Spoon-Knife'...
Warning: Permanently added the RSA host key for IP address '.' to the list of known hosts.
git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

Do I need to change some configuration setting on my computer or is this a problem with GitHub?

Edit: I have replaced my username and IP address with "."

答:
Just use double quotes with URL, like: git clone "https://yourRepoUrl"

(It somehow sees that you are using 2 quote marks on start, don't know why).

I was getting the same error => fatal: protocol ''https' is not supported (you can see 2 quote marks on https).

Body:
I am going through Github's forking guide: https://guides.github.com/activities/forking/
and I am trying to clone the repository onto my computer. However, running the command:

$ git clone https://github.com/./Spoon-Knife.git
Cloning into 'Spoon-Knife'...
fatal: protocol 'https' is not supported

Also tried with SSH:

$ git clone git@github.com:./Spoon-Knife.git
Cloning into 'Spoon-Knife'...
Warning: Permanently added the RSA host key for IP address '.' to the list of known hosts.
git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Do I need to change some configuration setting on my computer or is this a problem with GitHub?

Edit: I have replaced my username and IP address with "."


问:
Why isn't this for loop returning any non-false members?
This for loop isn't returning any true members.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    clientList[indexPath.row].s += 1

    if clientList[indexPath.row].s % 2 == 0 {
        clientList[indexPath.row].isSelected = true
    } else if clientList[indexPath.row].s % 2 != 0{
        clientList[indexPath.row].isSelected = false
    }
}
```

<p>Here is the for-loop:</p>

<pre class="lang-swift prettyprint-override"><code>@IBAction func toClientsButton(_ sender: Any) {
    for y in 0...clientList.count - 1 {
        if clientList[y].isSelected == true {
            clientsSelected.append(clientList[y])
        }
    }
}
</code>```

When the next screen loads, no values are in the clientsSelected array.

Am I doing something wrong?

答:
Filtering out only selected clients:

```<code>let clientListSelected = clientList.filter { $0.isSelected }
</code>```

Simpler logic for your unknown purpose logic

```<code>let client = clientList[indexPath.row]
client.isSelected = client.s.isMultiple(of: 2)
</code>```

Body:
This for loop isn't returning any true members.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    clientList[indexPath.row].s += 1

    if clientList[indexPath.row].s % 2 == 0 {
        clientList[indexPath.row].isSelected = true
    } else if clientList[indexPath.row].s % 2 != 0{
        clientList[indexPath.row].isSelected = false
    }
}

Here is the for-loop:

@IBAction func toClientsButton(_ sender: Any) {
    for y in 0...clientList.count - 1 {
        if clientList[y].isSelected == true {
            clientsSelected.append(clientList[y])
        }
    }
}

When the next screen loads, no values are in the clientsSelected array.

Am I doing something wrong?

Body:
Filtering out only selected clients:

let clientListSelected = clientList.filter { $0.isSelected }

Simpler logic for your unknown purpose logic

let client = clientList[indexPath.row]
client.isSelected = client.s.isMultiple(of: 2)


问:
How to fix ipykernel_launcher.py: error: unrecognized arguments in jupyter?
I am following this tensorflow tutorial after two days setting up the environment I finally could run premade_estimator.py using cmd

but when I try to run the same code in a jupyter notebook I am getting this error:

```<code>usage: ipykernel_launcher.py [-h] [--batch_size BATCH_SIZE]
                             [--train_steps TRAIN_STEPS]

ipykernel_launcher.py: error: unrecognized arguments: -f C:\Users\david\AppData\Roaming\jupyter\runtime\kernel-4faecb24-6e87-40b4-bf15-5d24520d7130.json
</code>```

An exception has occurred, use %tb to see the full traceback.

```<code>SystemExit: 2

C:\Anaconda3\envs\python3x\lib\site-packages\IPython\core\interactiveshell.py:2918:
UserWarning: To exit: use 'exit', 'quit', or Ctrl-D. warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
</code>```

I have tried to fix it without success using:

```<code>pip install --ignore-installed --upgrade jupyter

pip install ipykernel
python -m ipykernel install

conda install notebook ipykernel
ipython kernelspec install-self
</code>```

Any idea will be appreciate! Thanks!

答:
I just ran into this problem today and found a quick, stupid solution is to insert an argument processor for the -f argument that qtconsole/ipython passes though and we did not expect. At end of parser.add_argument I put in:

```<code>parser.add_argument("-f", "--fff", help="a dummy argument to fool ipython", default="1")
</code>```

I don't use the -f parameter, so there's no loss for me.

I'd rather not re-engineer a larger argument processing framework just because of ipython cropping up in workflow on one particular computer...

Body:
I am following this tensorflow tutorial after two days setting up the environment I finally could run premade_estimator.py using cmd

but when I try to run the same code in a jupyter notebook I am getting this error:

usage: ipykernel_launcher.py [-h] [--batch_size BATCH_SIZE]
                             [--train_steps TRAIN_STEPS]

ipykernel_launcher.py: error: unrecognized arguments: -f C:\Users\david\AppData\Roaming\jupyter\runtime\kernel-4faecb24-6e87-40b4-bf15-5d24520d7130.json

An exception has occurred, use %tb to see the full traceback.

SystemExit: 2

C:\Anaconda3\envs\python3x\lib\site-packages\IPython\core\interactiveshell.py:2918:
UserWarning: To exit: use 'exit', 'quit', or Ctrl-D. warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)

I have tried to fix it without success using:

pip install --ignore-installed --upgrade jupyter

pip install ipykernel
python -m ipykernel install

conda install notebook ipykernel
ipython kernelspec install-self

Any idea will be appreciate! Thanks!

Body:
I just ran into this problem today and found a quick, stupid solution is to insert an argument processor for the -f argument that qtconsole/ipython passes though and we did not expect. At end of parser.add_argument I put in:

parser.add_argument("-f", "--fff", help="a dummy argument to fool ipython", default="1")

I don't use the -f parameter, so there's no loss for me.

I'd rather not re-engineer a larger argument processing framework just because of ipython cropping up in workflow on one particular computer...


问:
Why does C not decrement the stack pointer if a variable leaves the scope?
```<code>#include <stdio.h>
void main() {
    {
        int x;
        printf("%p\n", &x);
    }
    {
        int x;
        printf("%p\n", &x);
    }
}
</code>```

I would think running this that it would output the same thing twice. When it declares the first variable, it increments the stack pointer, but then leaves the scope, so it decrements it, and then just repeats the process the second time, so int x would occupy the same memory location on the stack both times.

But this isn't the case. The stack pointer is not decremented and int x in both cases occupy different locations in the stack. In fact, the first int x is still reachable even though its scope is gone.

```<code>#include <stdio.h>
void main() {
    {
        int x = 10;
        printf("%p\n", &x);
    }
    {
        int x = 25;
        printf("%p\n", &x);
    }
    {
        int x = 71;
        printf("%p\n", &x);

        int *p = &x;
        printf("%i %i %i\n", *(p + 2), *(p + 1), *p);
    }
}
</code>```

Why is this? What am I misunderstanding?

答:
The C standard does not even mention a stack. The compiler is free to optimize variables away when they are not needed. There is absolutely nothing in the C standard that implies that the printouts should be neither equal or not equal.

On my computer, this manifests itself by giving different output depending on optimization level:

```<code>$ gcc c.c

/tmp$ ./a.out
0x7ffd8733c3ac
0x7ffd8733c3a8

/tmp$ gcc c.c -O3

/tmp$ ./a.out
0x7fff4e91544c
0x7fff4e91544c
</code>```

In fact, the first "int x" is still reachable even though its scope is gone.

Accessing a variable that has gone out of scope causes undefined behavior, which means that anything can happen. This includes the case where the program works as intended.

Here is the output from your second snippet with different optimizations:

```<code>/tmp$ ./a.out
0x7ffd4df94864
0x7ffd4df94860
0x7ffd4df9485c
10 25 71

/tmp$ gcc c.c -O3

/tmp$ ./a.out
0x7ffc30b4e44c
0x7ffc30b4e44c
0x7ffc30b4e44c
0 0 71
</code>```

When you get different behavior depending on optimization level, that's an almost 100% sign that your program has something that is causing undefined behavior. There is a very, very small chance that you have encountered a bug in the compiler. And apart from those two reasons, I cannot think of anything else that could be the cause.

Body:
#include <stdio.h>
void main() {
    {
        int x;
        printf("%p\n", &x);
    }
    {
        int x;
        printf("%p\n", &x);
    }
}

I would think running this that it would output the same thing twice. When it declares the first variable, it increments the stack pointer, but then leaves the scope, so it decrements it, and then just repeats the process the second time, so int x would occupy the same memory location on the stack both times.

But this isn't the case. The stack pointer is not decremented and int x in both cases occupy different locations in the stack. In fact, the first int x is still reachable even though its scope is gone.

#include <stdio.h>
void main() {
    {
        int x = 10;
        printf("%p\n", &x);
    }
    {
        int x = 25;
        printf("%p\n", &x);
    }
    {
        int x = 71;
        printf("%p\n", &x);

        int *p = &x;
        printf("%i %i %i\n", *(p + 2), *(p + 1), *p);
    }
}

Why is this? What am I misunderstanding?

Body:
The C standard does not even mention a stack. The compiler is free to optimize variables away when they are not needed. There is absolutely nothing in the C standard that implies that the printouts should be neither equal or not equal.

On my computer, this manifests itself by giving different output depending on optimization level:

$ gcc c.c

/tmp$ ./a.out
0x7ffd8733c3ac
0x7ffd8733c3a8

/tmp$ gcc c.c -O3

/tmp$ ./a.out
0x7fff4e91544c
0x7fff4e91544c

In fact, the first "int x" is still reachable even though its scope is gone.

Accessing a variable that has gone out of scope causes undefined behavior, which means that anything can happen. This includes the case where the program works as intended.

Here is the output from your second snippet with different optimizations:

/tmp$ ./a.out
0x7ffd4df94864
0x7ffd4df94860
0x7ffd4df9485c
10 25 71

/tmp$ gcc c.c -O3

/tmp$ ./a.out
0x7ffc30b4e44c
0x7ffc30b4e44c
0x7ffc30b4e44c
0 0 71

When you get different behavior depending on optimization level, that's an almost 100% sign that your program has something that is causing undefined behavior. There is a very, very small chance that you have encountered a bug in the compiler. And apart from those two reasons, I cannot think of anything else that could be the cause.


问:
Error: Namespace "iOS" does not exist in Unity.Notifications
I added

```<code>using Unity.Notifications.Android;
using Unity.Notifications.iOS;
</code>```

to my script.

VisualStudio says everything is fine, the intellisense sees fields from both namespaces fine, and I'm able to run in the editor fine.

But then when I try to build for Android to test of my phone, it says the namespace iOS does not exist in Unity.Notifications.

If I remove all iOS code it builds fine.

答:
Well it makes totally sense that the according namespace only exists on a certain target platform. It doesn't sound like a big surprise that a namespace called iOS is not included in a build for Android and viceversa..

Have a look at Platform depended compilation

and remove according code blocks using #if preprocessors

```<code>#if UNITY_IOS
    using Unity.Notifications.iOS;
#elseif UNITY_ANDROID
    using Unity.Notifications.Android;
#endif

...

#if UNITY_IOS
    <Code for IOS>
#elseif UNITY_ANDROID
    <Code for Android>
#endif
</code>```

They did probably exactly the same wrapping the entire namespaces in such preprocessors in order to exclude them on the according target platforms.

Body:
I added

using Unity.Notifications.Android;
using Unity.Notifications.iOS;

to my script.

VisualStudio says everything is fine, the intellisense sees fields from both namespaces fine, and I'm able to run in the editor fine.

But then when I try to build for Android to test of my phone, it says the namespace iOS does not exist in Unity.Notifications.

If I remove all iOS code it builds fine.

Body:
Well it makes totally sense that the according namespace only exists on a certain target platform. It doesn't sound like a big surprise that a namespace called iOS is not included in a build for Android and viceversa..

Have a look at Platform depended compilation

and remove according code blocks using #if preprocessors

#if UNITY_IOS
    using Unity.Notifications.iOS;
#elseif UNITY_ANDROID
    using Unity.Notifications.Android;
#endif

...

#if UNITY_IOS
    <Code for IOS>
#elseif UNITY_ANDROID
    <Code for Android>
#endif

They did probably exactly the same wrapping the entire namespaces in such preprocessors in order to exclude them on the according target platforms.


问:
Is it possible to duplicate a row based on a column value, and change another column value?
I have a table with an INT column of time in seconds, another column with the type of that record, and a foreign ID.

I want to select the same row repeated everytime it's seconds row is greater than X, and in the first row it keeps X seconds with type 1, and in the second row it shows the seconds left (seconds - X, up to X) with type 2. The same with Y. No more than 3 rows. So row 1 is up to x, row 2 up to Y and row 3 is Y+1 and beyond

Eg:

X is 5. Y is 9.
I want this:

```<code>| id | type | seconds |
|----|------|---------|
|  1 |  10  |   19    |
|  2 |  10  |   12    |
|  3 |  10  |    7    |
</code>```

to become this:

```<code>| id | type | seconds |
|----|------|---------|
|  1 |   1  |    5    |
|  1 |   2  |    4    |
|  1 |   3  |   10    |
|  2 |   1  |    5    |
|  2 |   2  |    4    |
|  2 |   3  |    3    |
|  3 |   1  |    5    |
|  3 |   2  |    2    |
</code>```

Is that possible?

I've seen solutions to this (syntax-) exclusively for oracle.
But how do I do this in SQL Server?

Edit: Only for this type id (10 in the example), letting others unchanged.

答:
For this type of problem I like to use a recursive CTE. Borrowed the extra test cases from @Luis Cazares. Also added test cases for type 15 you mentioned in comments. In the solution below you can swap out values of X and Y and it will calculate accordingly.</p>

```<code>CREATE TABLE #TestData
(
    id INT
    , type INT
    , seconds int
);

INSERT INTO #TestData VALUES
(1, 10, 19)
, (2, 10, 12)
, (3, 10, 7)
, (4, 10, 5)
, (5, 10, 3)
, (6, 15, 54)
, (7, 15, 8);

DECLARE
    @X INT = 5
    , @Y INT = 9;

SET @Y = @Y - @X;

WITH CTE AS
(
    SELECT id, CASE WHEN type = 10 THEN 0 ELSE type END AS type, seconds, seconds AS ov
    FROM #TestData
    UNION ALL
    SELECT
        id
        , type + 1
        , CASE
            WHEN type = 0 THEN seconds - @X
            WHEN type = 1 THEN seconds - @Y
            WHEN type = 2 THEN seconds
            END
        , ov
    FROM CTE
    WHERE seconds > 0
)

SELECT
    id
    , type
    , CASE
        WHEN type = 1 AND seconds > 0 THEN @X
        WHEN type = 2 AND seconds > 0 THEN @Y
        WHEN type = 2 AND seconds < 0 THEN ov - @X
        WHEN type = 3 AND seconds > 0 THEN seconds
        ELSE ov
        END
FROM CTE
WHERE type <> 0 AND CTE.seconds IS NOT NULL
ORDER BY id, type

DROP TABLE #TestData;
</code>```

Body:
I have a table with an INT column of time in seconds, another column with the type of that record, and a foreign ID.

I want to select the same row repeated everytime it's seconds row is greater than X, and in the first row it keeps X seconds with type 1, and in the second row it shows the seconds left (seconds - X, up to X) with type 2. The same with Y. No more than 3 rows. So row 1 is up to x, row 2 up to Y and row 3 is Y+1 and beyond

Eg:

X is 5. Y is 9.
I want this:

| id | type | seconds |
|----|------|---------|
|  1 |  10  |   19    |
|  2 |  10  |   12    |
|  3 |  10  |    7    |

to become this:

| id | type | seconds |
|----|------|---------|
|  1 |   1  |    5    |
|  1 |   2  |    4    |
|  1 |   3  |   10    |
|  2 |   1  |    5    |
|  2 |   2  |    4    |
|  2 |   3  |    3    |
|  3 |   1  |    5    |
|  3 |   2  |    2    |

Is that possible?

I've seen solutions to this (syntax-) exclusively for oracle.
But how do I do this in SQL Server?

Edit: Only for this type id (10 in the example), letting others unchanged.

Body:
For this type of problem I like to use a recursive CTE. Borrowed the extra test cases from @Luis Cazares. Also added test cases for type 15 you mentioned in comments. In the solution below you can swap out values of X and Y and it will calculate accordingly.

CREATE TABLE #TestData
(
    id INT
    , type INT
    , seconds int
);

INSERT INTO #TestData VALUES
(1, 10, 19)
, (2, 10, 12)
, (3, 10, 7)
, (4, 10, 5)
, (5, 10, 3)
, (6, 15, 54)
, (7, 15, 8);

DECLARE
    @X INT = 5
    , @Y INT = 9;

SET @Y = @Y - @X;

WITH CTE AS
(
    SELECT id, CASE WHEN type = 10 THEN 0 ELSE type END AS type, seconds, seconds AS ov
    FROM #TestData
    UNION ALL
    SELECT
        id
        , type + 1
        , CASE
            WHEN type = 0 THEN seconds - @X
            WHEN type = 1 THEN seconds - @Y
            WHEN type = 2 THEN seconds
            END
        , ov
    FROM CTE
    WHERE seconds > 0
)

SELECT
    id
    , type
    , CASE
        WHEN type = 1 AND seconds > 0 THEN @X
        WHEN type = 2 AND seconds > 0 THEN @Y
        WHEN type = 2 AND seconds < 0 THEN ov - @X
        WHEN type = 3 AND seconds > 0 THEN seconds
        ELSE ov
        END
FROM CTE
WHERE type <> 0 AND CTE.seconds IS NOT NULL
ORDER BY id, type

DROP TABLE #TestData;


问:
Error in installing line-in package: NodeJS
I am trying to use the line-in package to stream the input audio data as output. While installing the package, I get the error stating node-gyp rebuild command failed.

I am using NodeJS, and I really don't know why node-gyp is trying to access my python.exe file. Can anybody help me to sort this problem out?

```<code>gyp ERR! stack Error: Command failed: C:\Users\NikhileshSubramanian\AppData\Local\Programs\Python\Python37\python.EXE -c import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack   File "<string>", line 1
gyp ERR! stack     import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack                                ^
gyp ERR! stack SyntaxError: invalid syntax
gyp ERR! stack
gyp ERR! stack     at ChildProcess.exithandler (child_process.js:294:12)
gyp ERR! stack     at ChildProcess.emit (events.js:182:13)
gyp ERR! stack     at maybeClose (internal/child_process.js:962:16)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:251:5)
gyp ERR! System Windows_NT 10.0.17134
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd F:\Topgear\SpeechToText\node_modules\line-in
gyp ERR! node -v v10.15.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
npm WARN SpeechToText@1.0.0 No description
npm WARN SpeechToText@1.0.0 No repository field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! line-in@0.1.2 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the line-in@0.1.2 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.```

```

答:
node-gyp requires python2.7:

https://github.com/nodejs/node-gyp

python (v2.7 recommended, v3.x.x is not supported)

There are some windows specific instructions that may help you:

https://github.com/nodejs/node-gyp#on-windows

Body:
I am trying to use the line-in package to stream the input audio data as output. While installing the package, I get the error stating node-gyp rebuild command failed.

I am using NodeJS, and I really don't know why node-gyp is trying to access my python.exe file. Can anybody help me to sort this problem out?

gyp ERR! stack Error: Command failed: C:\Users\NikhileshSubramanian\AppData\Local\Programs\Python\Python37\python.EXE -c import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack   File "<string>", line 1
gyp ERR! stack     import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack                                ^
gyp ERR! stack SyntaxError: invalid syntax
gyp ERR! stack
gyp ERR! stack     at ChildProcess.exithandler (child_process.js:294:12)
gyp ERR! stack     at ChildProcess.emit (events.js:182:13)
gyp ERR! stack     at maybeClose (internal/child_process.js:962:16)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:251:5)
gyp ERR! System Windows_NT 10.0.17134
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd F:\Topgear\SpeechToText\node_modules\line-in
gyp ERR! node -v v10.15.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
npm WARN SpeechToText@1.0.0 No description
npm WARN SpeechToText@1.0.0 No repository field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! line-in@0.1.2 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the line-in@0.1.2 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.```


问:
Open a OpenFileDialog to change the value of a property in a PropertyGrid control?
In Windows Forms, I'm representing a custom class in a PropertyGid control, which has various string properties as you can notice in the next image:

The problem is that I'm not totally satisfied with the current behavior for changing the value of the string properties. For those properties that expects a file or directory path, like "Target" or "Working Directory" properties, I would like to know if it could be possible and viable to implement a TypeConverter / Type Descriptor that would open a OpenFileDialog when clicking in the down arrow at the right of the field in the property grid. That is, to select a file or folder through a OpenFileDialog, instead of directly writing the path in the property grid, but still letting the option to directly write the path if I want to do so.

Maybe .NET Framework class library already provides the TypeConverter / TypeDescriptor that I'm requesting?. If not, is this possible to do?. And how to start doing so?.

Or any other idea to be able open a OpenFileDialog to change the value of a specific property in a PropertyGrid control?.

答:
There are builtin FileNameEditor and FolderNameEditor UI type editors which let you choose file name and folder name, for example:

```<code>using System.ComponentModel;
using System.Drawing.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
public class MyClass
{
    [Editor(typeof(FileNameEditor), typeof(UITypeEditor))]
    public string FilePath { get; set; }

    [Editor(typeof(FolderNameEditor), typeof(UITypeEditor))]
    public string FolderPath { get; set; }
}
</code>```

If you want to customize the FileNameEditor to show just txt files, you can override its InitializeDialog method:

```<code>public class MyFileNameEditor : FileNameEditor
{
    protected override void InitializeDialog(OpenFileDialog openFileDialog)
    {
        base.InitializeDialog(openFileDialog);
        openFileDialog.Filter = "text files (*.txt)|*.txt";
    }
}
</code>```

Body:
There are builtin FileNameEditor and FolderNameEditor UI type editors which let you choose file name and folder name, for example:

using System.ComponentModel;
using System.Drawing.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
public class MyClass
{
    [Editor(typeof(FileNameEditor), typeof(UITypeEditor))]
    public string FilePath { get; set; }

    [Editor(typeof(FolderNameEditor), typeof(UITypeEditor))]
    public string FolderPath { get; set; }
}

If you want to customize the FileNameEditor to show just txt files, you can override its InitializeDialog method:

public class MyFileNameEditor : FileNameEditor
{
    protected override void InitializeDialog(OpenFileDialog openFileDialog)
    {
        base.InitializeDialog(openFileDialog);
        openFileDialog.Filter = "text files (*.txt)|*.txt";
    }
}


问:
How to insert txt data into mongodb using python
I need to  insert data from file.txt into new MongoDB database.collection using python.

.txt file contains data like:

```<code>a={
    "_id"          : "67a2c0e2e559fb56bf055502",
    "field1"       : "value1",
    "field2" : ["value21","value22"],
    "field3"  : {
                       "_id"  : "37a2c0e2e559fb56bf055502",
                       "subfield1" : "subvalue1"
                     }
};

b={
    "_id"          : "67a2c0e2e559fb56bf055503",
    "field1"       : "value1",
    "field2" : ["value21","value22"],
    "field3"  : {
                       "_id"  : "27a2c0e2e559fb56bf055503",
                       "subfield1" : "subvalue1"
                     }
};

c={....
};
</code>```

I want to insert all documents if we say a=doc1, b=doc2, C=doc3, d...
I tried to split them in a list using l=split(read,';') and add it to Mongo with insert_many but I get this error

```<code>TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping
</code>```

is there any way to insert the data without creating json file?
Thanks

Code

def insert():
    client = pymongo.MongoClient(dbStringConnection)

    db = client[dbName]

    collectionR = db[dbCollection]

    list1 = []
    with open (file, 'r') as f:
        reader= f.read()
        #print (reader)
    f.close()
    reader= reader.replace('\n', '')
    reader= reader.replace('  ','')
    list1 = reader.split(';')
   # print(list1[0])

    list2={}

    for i in range(len(lista)-1):

        s=''
        t=list1[i][0:1]
        s=s+str(list1[i][2:len(list1[i])])
        list2[t]=s
    collectionR.insert_many(list2)

```

答:
collection.insert_many() expects a list of dict, by simply loading the content of the txt file in a string and splitting on ";", you obtain a list of strings like

```<code>'a={ "_id" : "67a2c0e2e559fb56bf055502", "field1" : "value1", "field2" : ["value21","value22"], "field3" : { "_id" : "37a2c0e2e559fb56bf055502", "subfield1" : "subvalue1" } }'
</code>```

And pymongo/mongodb does not let you insert strings, it expects documents (python dict's)

See below (using insert_one but principle is the same with insert_many):

```<code>s = 'a={ "_id" : "67a2c0e2e559fb56bf055502", "field1" : "value1", "field2" : ["value21","value22"], "field3" : { "_id" : "37a2c0e2e559fb56bf055502", "subfield1" : "subvalue1" } }'
c.insert_one(s)   # raise TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument,...
</code>```

What you need to achieve is to load the string into a dict:

```<code>dic = { "_id" : "67a2c0e2e559fb56bf055502", "field1" : "value1", "field2" : ["value21","value22"], "field3" : { "_id" : "37a2c0e2e559fb56bf055502", "subfield1" : "subvalue1" } }
c.insert_one(dic)
</code>```

If you manage to turn your strings like 'a={"key1":"value1", "key2":"value2"}' into strings like '{"key1":"value1", "key2:value2"}', then you can use eval to turn the string to a dict with my_dict=eval('{"key1":"value1", "key2":"value2"}')

Body:
I need to  insert data from file.txt into new MongoDB database.collection using python.

.txt file contains data like:

a={
    "_id"          : "67a2c0e2e559fb56bf055502",
    "field1"       : "value1",
    "field2" : ["value21","value22"],
    "field3"  : {
                       "_id"  : "37a2c0e2e559fb56bf055502",
                       "subfield1" : "subvalue1"
                     }
};

b={
    "_id"          : "67a2c0e2e559fb56bf055503",
    "field1"       : "value1",
    "field2" : ["value21","value22"],
    "field3"  : {
                       "_id"  : "27a2c0e2e559fb56bf055503",
                       "subfield1" : "subvalue1"
                     }
};

c={....
};

I want to insert all documents if we say a=doc1, b=doc2, C=doc3, d...
I tried to split them in a list using l=split(read,';') and add it to Mongo with insert_many but I get this error

TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping

is there any way to insert the data without creating json file?
Thanks

Code

def insert():
    client = pymongo.MongoClient(dbStringConnection)

    db = client[dbName]

    collectionR = db[dbCollection]

    list1 = []
    with open (file, 'r') as f:
        reader= f.read()
        #print (reader)
    f.close()
    reader= reader.replace('\n', '')
    reader= reader.replace('  ','')
    list1 = reader.split(';')
   # print(list1[0])

    list2={}

    for i in range(len(lista)-1):

        s=''
        t=list1[i][0:1]
        s=s+str(list1[i][2:len(list1[i])])
        list2[t]=s
    collectionR.insert_many(list2)

Body:
collection.insert_many() expects a list of dict, by simply loading the content of the txt file in a string and splitting on ";", you obtain a list of strings like

'a={ "_id" : "67a2c0e2e559fb56bf055502", "field1" : "value1", "field2" : ["value21","value22"], "field3" : { "_id" : "37a2c0e2e559fb56bf055502", "subfield1" : "subvalue1" } }'

And pymongo/mongodb does not let you insert strings, it expects documents (python dict's)

See below (using insert_one but principle is the same with insert_many):

s = 'a={ "_id" : "67a2c0e2e559fb56bf055502", "field1" : "value1", "field2" : ["value21","value22"], "field3" : { "_id" : "37a2c0e2e559fb56bf055502", "subfield1" : "subvalue1" } }'
c.insert_one(s)   # raise TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument,...

What you need to achieve is to load the string into a dict:

dic = { "_id" : "67a2c0e2e559fb56bf055502", "field1" : "value1", "field2" : ["value21","value22"], "field3" : { "_id" : "37a2c0e2e559fb56bf055502", "subfield1" : "subvalue1" } }
c.insert_one(dic)

If you manage to turn your strings like 'a={"key1":"value1", "key2":"value2"}' into strings like '{"key1":"value1", "key2:value2"}', then you can use eval to turn the string to a dict with my_dict=eval('{"key1":"value1", "key2":"value2"}')


问:
How to create a Pulse effect inward in CSS?
In the code below, there is a CSS Pulse animation. The effect is towards the outside of the logo. How to create the same effect towards the logo's interior ?

```<code>If possible can you show me how to do both effects :
</code>```

from the edge of the logo inwards.

from inside the logo to the edge.

https://codepen.io/olam/pen/zcqea

答:
You literately just flip the effect. Here goes:

```<code>@keyframes pulse {
  100% {
    -moz-box-shadow: 0 0 0 0 rgba(204,169,44, 0.4);
    box-shadow: 0 0 0 0 rgba(204,169,44, 0.4);
  }
  30% {
      -moz-box-shadow: 0 0 0 10px rgba(204,169,44, 0);
      box-shadow: 0 0 0 10px rgba(204,169,44, 0);
  }
  0% {
      -moz-box-shadow: 0 0 0 0 rgba(204,169,44, 0);
      box-shadow: 0 0 0 0 rgba(204,169,44, 0);
  }
}
</code>```

I just switched 100% and 0% and changed 70% to 30%. Try it out. Hope this helps

Body:
In the code below, there is a CSS Pulse animation. The effect is towards the outside of the logo. How to create the same effect towards the logo's interior ?

If possible can you show me how to do both effects :

from the edge of the logo inwards.

from inside the logo to the edge.

https://codepen.io/olam/pen/zcqea

Body:
You literately just flip the effect. Here goes:

@keyframes pulse {
  100% {
    -moz-box-shadow: 0 0 0 0 rgba(204,169,44, 0.4);
    box-shadow: 0 0 0 0 rgba(204,169,44, 0.4);
  }
  30% {
      -moz-box-shadow: 0 0 0 10px rgba(204,169,44, 0);
      box-shadow: 0 0 0 10px rgba(204,169,44, 0);
  }
  0% {
      -moz-box-shadow: 0 0 0 0 rgba(204,169,44, 0);
      box-shadow: 0 0 0 0 rgba(204,169,44, 0);
  }
}

I just switched 100% and 0% and changed 70% to 30%. Try it out. Hope this helps