问:
D3 js fit text inside each node
How can I wrap text inside each node making the node automatically resize, just as in css you would do with fit-content or display flex?

Here's the snippet, available at this link: https://codepen.io/boxxello/pen/XWYvRQO

or here:
css:

html, body {
    margin: 0;
    padding: 0;
    background-color: rgb(140, 149, 226);
}
.node {
    cursor: pointer;
}

.node circle {
}
.node-leaf {

}

.node text {
    font: 10px sans-serif;
}

.link {
    fill: none;
    stroke: rgb(55, 68, 105);
    stroke-width: 1px;
}
```
<p>js:</p>
<pre class="lang-js prettyprint-override"><code>
var margin = {top: 20, right: 90, bottom: 30, left: 90},
    width = 1300 - margin.left - margin.right,
    height = 900 - margin.top - margin.bottom;
var svg = d3
    .select("body")
    .append("svg")
    .attr("width", width + margin.right + margin.left)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var i = 0,
    duration = 750,
    root;
var treemap = d3.tree().size([height, width]);
root = d3.hierarchy(treeData, function (d) {
    return d.children;
});
root.x0 = height / 2;
root.y0 = 0;
root.children.forEach(collapse);

update(root);

function collapse(d) {
    if (d.children) {
        d._children = d.children;
        d._children.forEach(collapse);
        d.children = null;
    }
}

function update(source) {
    var treeData = treemap(root);
    var nodes = treeData.descendants(),
        links = treeData.descendants().slice(1);
    nodes.forEach(function (d) {
        d.y = d.depth * 180;
    });
    var node = svg.selectAll("g.node").data(nodes, function (d) {
        return d.id || (d.id = ++i);
    });
    var nodeEnter = node
        .enter()
        .append("g")
        .attr("class", "node")
        .attr("transform", function (d) {
            return "translate(" + source.y0 + "," + source.x0 + ")";
        })
        .on("click", click);
    nodeEnter
        .attr("class", "node")
        .attr("r", 1e-6)
        .style("display", function (d) {
            if (d.depth === 0) { //Is top root
                return 'none';
            }
        });
    nodeEnter
        .append("rect")
        .attr("rx", function (d) {
            if (d.parent) return d.children || d._children ? 0 : 6;
            return 10;
        })
        .attr("ry", function (d) {
            if (d.parent) return d.children || d._children ? 0 : 6;
            return 10;
        })
        .attr("stroke-width", function (d) {
            return d.parent ? 1 : 0;
        })
        .attr("stroke", function (d) {
            return d.children || d._children
                ? "rgb(3, 192, 220)"
                : "rgb(38, 222, 176)";
        })
        .attr("stroke-dasharray", function (d) {
            return d.children || d._children ? "0" : "2.2";
        })
        .attr("stroke-opacity", function (d) {
            return d.children || d._children ? "1" : "0.6";
        })
        .attr("x", 0)
        .attr("y", -10)
        .attr("width", function (d) {
            return d.parent ? 40 : 20;
        })
        .attr("height", 20)
        .classed("node-leaf", true);

    nodeEnter
        .append("text")
        .style("fill", function (d) {
            if (d.parent) {
                return d.children || d._children ? "#ffffff" : "rgb(38, 222, 176)";
            }
            return "rgb(39, 43, 77)";
        })
        .attr("dy", ".35em")
        .attr("x", function (d) {
            return d.parent ? 20 : 10;
        })
        .attr("text-anchor", function (d) {
            return "middle";
        })
        .text(function (d) {
            return d.data.name;
        });

    var nodeUpdate = nodeEnter.merge(node);

    nodeUpdate
        .transition()
        .duration(duration)
        .attr("transform", function (d) {
            return "translate(" + d.y + "," + d.x + ")";
        });
    var nodeExit = node
        .exit()
        .transition()
        .duration(duration)
        .attr("transform", function (d) {
            return "translate(" + source.y + "," + source.x + ")";
        })
        .remove();
    nodeExit.select("rect").style("opacity", 1e-6);
    nodeExit.select("rect").attr("stroke-opacity", 1e-6);
    nodeExit.select("text").style("fill-opacity", 1e-6);
    var link = svg.selectAll("path.link").data(links, function (d) {
        return d.id;
    });
    var linkEnter = link
        .enter()
        .insert("path", "g")
        .attr("class", "link")
        .attr("d", function (d) {
            var o = {x: source.x0, y: source.y0};
            return diagonal(o, o);
        }).style("display", function (d) {
            if (d.depth === 1) { //Is top link
                return 'none';
            }
        })
    var linkUpdate = linkEnter.merge(link);
    linkUpdate
        .transition()
        .duration(duration)
        .attr("d", function (d) {
            return diagonal(d, d.parent);
        });
    var linkExit = link
        .exit()
        .transition()
        .duration(duration)
        .attr("d", function (d) {
            var o = {x: source.x, y: source.y};
            return diagonal(o, o);
        })
        .remove();
    nodes.forEach(function (d) {
        d.x0 = d.x;
        d.y0 = d.y;
    });

    function diagonal(s, d) {
        path = `M ${s.y} ${s.x}
            C ${(s.y + d.y) / 2} ${s.x},
              ${(s.y + d.y) / 2} ${d.x},
              ${d.y} ${d.x}`;

        return path;
    }

    function click(d) {
        if (d.children) {
            d._children = d.children;
            d.children = null;
        } else {
            d.children = d._children;
            d._children = null;
        }
        update(d);
    }
}
</code>```

The part where you could change the style property is at:

        .attr("width", function (d) {
            return d.parent ? 40 : 20;
        })
        .attr("height", 20)
        .classed("node-leaf", true);
```

Or at least is where I've tried to deal with it. The current version I'm using of d3js is the 4.2.2, I actually used this version it fitted my needs (found the snippet online and there have been breaking changes in the 7.* which is the current version) not because I didn't want to upgrade it (if it's easier in the newer versions please let me know.

This is an expected output, as you can see the node basically fits all the text inside it (I left the parent nodes blank because they're not relevant in this case, but they would need to do the same thing, so applying a property to all the nodes would be great.

Title: D3 js fit text inside each node

Body:
How can I wrap text inside each node making the node automatically resize, just as in css you would do with fit-content or display flex?

Here's the snippet, available at this link: https://codepen.io/boxxello/pen/XWYvRQO

or here:
css:

html, body {
    margin: 0;
    padding: 0;
    background-color: rgb(140, 149, 226);
}
.node {
    cursor: pointer;
}

.node circle {
}
.node-leaf {

}

.node text {
    font: 10px sans-serif;
}

.link {
    fill: none;
    stroke: rgb(55, 68, 105);
    stroke-width: 1px;
}

js:

var margin = {top: 20, right: 90, bottom: 30, left: 90},
    width = 1300 - margin.left - margin.right,
    height = 900 - margin.top - margin.bottom;
var svg = d3
    .select("body")
    .append("svg")
    .attr("width", width + margin.right + margin.left)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var i = 0,
    duration = 750,
    root;
var treemap = d3.tree().size([height, width]);
root = d3.hierarchy(treeData, function (d) {
    return d.children;
});
root.x0 = height / 2;
root.y0 = 0;
root.children.forEach(collapse);

update(root);

function collapse(d) {
    if (d.children) {
        d._children = d.children;
        d._children.forEach(collapse);
        d.children = null;
    }
}

function update(source) {
    var treeData = treemap(root);
    var nodes = treeData.descendants(),
        links = treeData.descendants().slice(1);
    nodes.forEach(function (d) {
        d.y = d.depth * 180;
    });
    var node = svg.selectAll("g.node").data(nodes, function (d) {
        return d.id || (d.id = ++i);
    });
    var nodeEnter = node
        .enter()
        .append("g")
        .attr("class", "node")
        .attr("transform", function (d) {
            return "translate(" + source.y0 + "," + source.x0 + ")";
        })
        .on("click", click);
    nodeEnter
        .attr("class", "node")
        .attr("r", 1e-6)
        .style("display", function (d) {
            if (d.depth === 0) { //Is top root
                return 'none';
            }
        });
    nodeEnter
        .append("rect")
        .attr("rx", function (d) {
            if (d.parent) return d.children || d._children ? 0 : 6;
            return 10;
        })
        .attr("ry", function (d) {
            if (d.parent) return d.children || d._children ? 0 : 6;
            return 10;
        })
        .attr("stroke-width", function (d) {
            return d.parent ? 1 : 0;
        })
        .attr("stroke", function (d) {
            return d.children || d._children
                ? "rgb(3, 192, 220)"
                : "rgb(38, 222, 176)";
        })
        .attr("stroke-dasharray", function (d) {
            return d.children || d._children ? "0" : "2.2";
        })
        .attr("stroke-opacity", function (d) {
            return d.children || d._children ? "1" : "0.6";
        })
        .attr("x", 0)
        .attr("y", -10)
        .attr("width", function (d) {
            return d.parent ? 40 : 20;
        })
        .attr("height", 20)
        .classed("node-leaf", true);

    nodeEnter
        .append("text")
        .style("fill", function (d) {
            if (d.parent) {
                return d.children || d._children ? "#ffffff" : "rgb(38, 222, 176)";
            }
            return "rgb(39, 43, 77)";
        })
        .attr("dy", ".35em")
        .attr("x", function (d) {
            return d.parent ? 20 : 10;
        })
        .attr("text-anchor", function (d) {
            return "middle";
        })
        .text(function (d) {
            return d.data.name;
        });

    var nodeUpdate = nodeEnter.merge(node);

    nodeUpdate
        .transition()
        .duration(duration)
        .attr("transform", function (d) {
            return "translate(" + d.y + "," + d.x + ")";
        });
    var nodeExit = node
        .exit()
        .transition()
        .duration(duration)
        .attr("transform", function (d) {
            return "translate(" + source.y + "," + source.x + ")";
        })
        .remove();
    nodeExit.select("rect").style("opacity", 1e-6);
    nodeExit.select("rect").attr("stroke-opacity", 1e-6);
    nodeExit.select("text").style("fill-opacity", 1e-6);
    var link = svg.selectAll("path.link").data(links, function (d) {
        return d.id;
    });
    var linkEnter = link
        .enter()
        .insert("path", "g")
        .attr("class", "link")
        .attr("d", function (d) {
            var o = {x: source.x0, y: source.y0};
            return diagonal(o, o);
        }).style("display", function (d) {
            if (d.depth === 1) { //Is top link
                return 'none';
            }
        })
    var linkUpdate = linkEnter.merge(link);
    linkUpdate
        .transition()
        .duration(duration)
        .attr("d", function (d) {
            return diagonal(d, d.parent);
        });
    var linkExit = link
        .exit()
        .transition()
        .duration(duration)
        .attr("d", function (d) {
            var o = {x: source.x, y: source.y};
            return diagonal(o, o);
        })
        .remove();
    nodes.forEach(function (d) {
        d.x0 = d.x;
        d.y0 = d.y;
    });

    function diagonal(s, d) {
        path = `M ${s.y} ${s.x}
            C ${(s.y + d.y) / 2} ${s.x},
              ${(s.y + d.y) / 2} ${d.x},
              ${d.y} ${d.x}`;

        return path;
    }

    function click(d) {
        if (d.children) {
            d._children = d.children;
            d.children = null;
        } else {
            d.children = d._children;
            d._children = null;
        }
        update(d);
    }
}

The part where you could change the style property is at:

        .attr("width", function (d) {
            return d.parent ? 40 : 20;
        })
        .attr("height", 20)
        .classed("node-leaf", true);

Or at least is where I've tried to deal with it. The current version I'm using of d3js is the 4.2.2, I actually used this version it fitted my needs (found the snippet online and there have been breaking changes in the 7.* which is the current version) not because I didn't want to upgrade it (if it's easier in the newer versions please let me know.

This is an expected output, as you can see the node basically fits all the text inside it (I left the parent nodes blank because they're not relevant in this case, but they would need to do the same thing, so applying a property to all the nodes would be great.


来源: stackexchange

问:
Trying to run python script using OpenCV on Replit, throws ImportError: OpenCV loader: missing configuration file: ['config.py']
Trying to implement OCR into my simple python program, but Replit is being weird as usual with the module requirements. I get multiple errors, but the following shows first.

I tried to run this code:

```<code>import cv2
import pytesseract
import numpy as np
img = cv2.imread('/Users/marius/Desktop/jimdoo.png')
#Alternatively: can be skipped if you have a Blackwhite image
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
gray, img_bin = cv2.threshold(gray,128,255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)
gray = cv2.bitwise_not(img_bin)
kernel = np.ones((2, 1), np.uint8)
img = cv2.erode(gray, kernel, iterations=1)
img = cv2.dilate(img, kernel, iterations=1)
out_below = pytesseract.image_to_string(img)
print("OUTPUT:", out_below)
</code>```

Not familiar with OCR so I can't MRE (sorry).

But this along with many other errors occured:

```<code>raise ImportError('OpenCV loader: missing configuration file: {}. Check OpenCV installation.'.format(fnames))
ImportError: OpenCV loader: missing configuration file: ['config.py']. Check OpenCV installation.
</code>```

Not very good at programming, what does this mean? Much thanks.

ContentLicense: CC BY-SA 4.0

Body:
Trying to implement OCR into my simple python program, but Replit is being weird as usual with the module requirements. I get multiple errors, but the following shows first.

I tried to run this code:

import cv2
import pytesseract
import numpy as np
img = cv2.imread('/Users/marius/Desktop/jimdoo.png')
#Alternatively: can be skipped if you have a Blackwhite image
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
gray, img_bin = cv2.threshold(gray,128,255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)
gray = cv2.bitwise_not(img_bin)
kernel = np.ones((2, 1), np.uint8)
img = cv2.erode(gray, kernel, iterations=1)
img = cv2.dilate(img, kernel, iterations=1)
out_below = pytesseract.image_to_string(img)
print("OUTPUT:", out_below)

Not familiar with OCR so I can't MRE (sorry).

But this along with many other errors occured:

raise ImportError('OpenCV loader: missing configuration file: {}. Check OpenCV installation.'.format(fnames))
ImportError: OpenCV loader: missing configuration file: ['config.py']. Check OpenCV installation.

Not very good at programming, what does this mean? Much thanks.


问:
Solidity - API calls of AccuWeather on Chainlink do not function as expected
I am at the very beginning and am trying to understand how API calls exactly work. For this reason I am trying to deploy and make calls with the code posted by AccuWeather on chainlink market.

The code:

https://market.link/nodes/AccuWeather/integrations#CurrentConditionsResult

```<code>
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "@chainlink/contracts/src/v0.8/ChainlinkClient.sol";

contract AccuweatherConsumer is ChainlinkClient {
    using Chainlink for Chainlink.Request;
    /* ========== CONSUMER STATE VARIABLES ========== */
    struct RequestParams {
        uint256 locationKey;
        string endpoint;
        string lat;
        string lon;
        string units;
    }
    struct LocationResult {
        uint256 locationKey;
        string name;
        bytes2 countryCode;
    }

    // Maps
    mapping(bytes32 => LocationResult) public requestIdLocationResult;
    mapping(bytes32 => RequestParams) public requestIdRequestParams;
    /* ========== CONSTRUCTOR ========== */
    /**
     * @param _link the LINK token address.
     * @param _oracle the Operator.sol contract address.
     */
    constructor(address _link, address _oracle) {
        setChainlinkToken(_link);
        setChainlinkOracle(_oracle);
    }
    /* ========== CONSUMER REQUEST FUNCTIONS ========== */
    /**
     * @notice Returns the location information for the given coordinates.
     * @param _specId the jobID.
     * @param _payment the LINK amount in Juels (i.e. 10^18 aka 1 LINK).
     * @param _lat the latitude (WGS84 standard, from -90 to 90).
     * @param _lon the longitude (WGS84 standard, from -180 to 180).
     */
    function requestLocation(
        bytes32 _specId,
        uint256 _payment,
        string calldata _lat,
        string calldata _lon
    ) public {
        Chainlink.Request memory req = buildChainlinkRequest(_specId, address(this), this.fulfillLocation.selector);
        req.add("endpoint", "location"); // NB: not required if it has been hardcoded in the job spec
        req.add("lat", _lat);
        req.add("lon", _lon);
        bytes32 requestId = sendChainlinkRequest(req, _payment);
        // Below this line is just an example of usage
        storeRequestParams(requestId, 0, "location", _lat, _lon, "");
    }

    /* ========== CONSUMER FULFILL FUNCTIONS ========== */
    /**
     * @notice Consumes the data returned by the node job on a particular request.
     * @dev Only when `_locationFound` is true, both `_locationFound` will contain meaningful data (as bytes). This
     * function body is just an example of usage.
     * @param _requestId the request ID for fulfillment.
     * @param _locationFound true if a location was found for the given coordinates, otherwise false.
     * @param _locationResult the location information (encoded as LocationResult).
     */
    function fulfillLocation(
        bytes32 _requestId,
        bool _locationFound,
        bytes memory _locationResult
    ) public recordChainlinkFulfillment(_requestId) {
        if (_locationFound) {
            storeLocationResult(_requestId, _locationResult);
        }
    }

    /* ========== PRIVATE FUNCTIONS ========== */
    function storeRequestParams(
        bytes32 _requestId,
        uint256 _locationKey,
        string memory _endpoint,
        string memory _lat,
        string memory _lon,
        string memory _units
    ) private {
        RequestParams memory requestParams;
        requestParams.locationKey = _locationKey;
        requestParams.endpoint = _endpoint;
        requestParams.lat = _lat;
        requestParams.lon = _lon;
        requestParams.units = _units;
        requestIdRequestParams[_requestId] = requestParams;
    }
    function storeLocationResult(bytes32 _requestId, bytes memory _locationResult) private {
        LocationResult memory result = abi.decode(_locationResult, (LocationResult));
        requestIdLocationResult[_requestId] = result;
    }
}
</code>```

I have deployed the contract, fueled it with LINKs. I can do the calls for the Location by entering the JobID, lat and long I found an AccuWeather (lat: 30.918 and long:-99.786) as well as the link payment. The call seems to be successful but when I take the requestID and use it to see the LocationResult I receive empty values.

I dont really know why it does not work or weather I forget to do something in between.

If I understand it correctly I need the LocationResult function to get information required for the fulfill function, is that correct?

I just hope someone faced the same problem and can help me. I would be very thankful for any suggestion!!

Body:
I am at the very beginning and am trying to understand how API calls exactly work. For this reason I am trying to deploy and make calls with the code posted by AccuWeather on chainlink market.

The code:

https://market.link/nodes/AccuWeather/integrations#CurrentConditionsResult

// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "@chainlink/contracts/src/v0.8/ChainlinkClient.sol";

contract AccuweatherConsumer is ChainlinkClient {
    using Chainlink for Chainlink.Request;
    /* ========== CONSUMER STATE VARIABLES ========== */
    struct RequestParams {
        uint256 locationKey;
        string endpoint;
        string lat;
        string lon;
        string units;
    }
    struct LocationResult {
        uint256 locationKey;
        string name;
        bytes2 countryCode;
    }

    // Maps
    mapping(bytes32 => LocationResult) public requestIdLocationResult;
    mapping(bytes32 => RequestParams) public requestIdRequestParams;
    /* ========== CONSTRUCTOR ========== */
    /**
     * @param _link the LINK token address.
     * @param _oracle the Operator.sol contract address.
     */
    constructor(address _link, address _oracle) {
        setChainlinkToken(_link);
        setChainlinkOracle(_oracle);
    }
    /* ========== CONSUMER REQUEST FUNCTIONS ========== */
    /**
     * @notice Returns the location information for the given coordinates.
     * @param _specId the jobID.
     * @param _payment the LINK amount in Juels (i.e. 10^18 aka 1 LINK).
     * @param _lat the latitude (WGS84 standard, from -90 to 90).
     * @param _lon the longitude (WGS84 standard, from -180 to 180).
     */
    function requestLocation(
        bytes32 _specId,
        uint256 _payment,
        string calldata _lat,
        string calldata _lon
    ) public {
        Chainlink.Request memory req = buildChainlinkRequest(_specId, address(this), this.fulfillLocation.selector);
        req.add("endpoint", "location"); // NB: not required if it has been hardcoded in the job spec
        req.add("lat", _lat);
        req.add("lon", _lon);
        bytes32 requestId = sendChainlinkRequest(req, _payment);
        // Below this line is just an example of usage
        storeRequestParams(requestId, 0, "location", _lat, _lon, "");
    }

    /* ========== CONSUMER FULFILL FUNCTIONS ========== */
    /**
     * @notice Consumes the data returned by the node job on a particular request.
     * @dev Only when `_locationFound` is true, both `_locationFound` will contain meaningful data (as bytes). This
     * function body is just an example of usage.
     * @param _requestId the request ID for fulfillment.
     * @param _locationFound true if a location was found for the given coordinates, otherwise false.
     * @param _locationResult the location information (encoded as LocationResult).
     */
    function fulfillLocation(
        bytes32 _requestId,
        bool _locationFound,
        bytes memory _locationResult
    ) public recordChainlinkFulfillment(_requestId) {
        if (_locationFound) {
            storeLocationResult(_requestId, _locationResult);
        }
    }

    /* ========== PRIVATE FUNCTIONS ========== */
    function storeRequestParams(
        bytes32 _requestId,
        uint256 _locationKey,
        string memory _endpoint,
        string memory _lat,
        string memory _lon,
        string memory _units
    ) private {
        RequestParams memory requestParams;
        requestParams.locationKey = _locationKey;
        requestParams.endpoint = _endpoint;
        requestParams.lat = _lat;
        requestParams.lon = _lon;
        requestParams.units = _units;
        requestIdRequestParams[_requestId] = requestParams;
    }
    function storeLocationResult(bytes32 _requestId, bytes memory _locationResult) private {
        LocationResult memory result = abi.decode(_locationResult, (LocationResult));
        requestIdLocationResult[_requestId] = result;
    }
}

I have deployed the contract, fueled it with LINKs. I can do the calls for the Location by entering the JobID, lat and long I found an AccuWeather (lat: 30.918 and long:-99.786) as well as the link payment. The call seems to be successful but when I take the requestID and use it to see the LocationResult I receive empty values.

I dont really know why it does not work or weather I forget to do something in between.

If I understand it correctly I need the LocationResult function to get information required for the fulfill function, is that correct?

I just hope someone faced the same problem and can help me. I would be very thankful for any suggestion!!


问:
To what does this Dynamics NAV Filter resolve
We have a Rapid Start that has an Item No. filter set to _@!#$. It is returning no records. I don't know how to interpret this filter. Can someone point me in the right direction?


问:
Reformat how JSON is compiled in response
Wrote an endpoint that loops through a date range and for each new date it calls a Stored Procedure in SQL to collect data from that date. Basically the Results I'm getting are sales from each department in a specific store. This is how the JSON response looks :

 {
  "12/3/2022": [
         {
             "Department": "1101",
             "Total $": 1887.30
         },
         {
             "Department": "6021",
             "Total $": 19.45
         },
         {
             "Department": "6030",
             "Total $": 247.33
         }
     ],
     "12/4/2022": [
         {
             "Department": "1101",
             "Total $": 1942.62
         },
         {
             "Department": "6021",
             "Total $": 0.46
         },
         {
             "Department": "6030",
             "Total $": 488.13
         }
    ]
}
```
<p>But I'd really like to have this displayed with departments as the header. So, something like this :</p>
<pre class="lang-json prettyprint-override"><code>{
 "1101": [
        {
           "12/3/2022": 1887.30,
            "12/4/2022": 1942.62
        }
        ],
 "6021": [
        {
           "12/3/2022": 19.45,
           "12/4/2022": 0.46
        }
   ],
  "6030": [
         {
             "12/3/2022": 247.33,
             "12/4/2022": 488.13
         }
   ]
}
</code>```

This is my code for collecting the data :

```<code>public HttpResponseMessage GetWeeklyStoreSummary(int appid, string fromDate, string endDate, string store)
{
    ResponseHandler response = new ResponseHandler(this.Request);
    WeeklyStoreSummaryHelper ws = new WeeklyStoreSummaryHelper();

    try
    {
        string connectionString = GetConnectionString(appid);
        WeeklyStoreSummaryDBAdapter db = new WeeklyStoreSummaryDBAdapter(connectionString);

        DataSet result;

        foreach (DateTime day in ws.EachDay(fromDate, endDate))
        {
            var currentDate = day.ToShortDateString();
            result = db.GetWeeklySummary(currentDate, store);
            response.AddTable(currentDate, result.Tables[0]);
        }

        string jsonResponse = response.GetJsonResponse();
        return response.RequestCompleted(jsonResponse);
    }
    catch (ArgumentException a)
    {
        return response.BadRequest(a.Message);
    }
    catch (Exception e)
    {
        return response.GenericError(e.Message);
    }
}
</code>```

Body:
Wrote an endpoint that loops through a date range and for each new date it calls a Stored Procedure in SQL to collect data from that date. Basically the Results I'm getting are sales from each department in a specific store. This is how the JSON response looks :

 {
  "12/3/2022": [
         {
             "Department": "1101",
             "Total $": 1887.30
         },
         {
             "Department": "6021",
             "Total $": 19.45
         },
         {
             "Department": "6030",
             "Total $": 247.33
         }
     ],
     "12/4/2022": [
         {
             "Department": "1101",
             "Total $": 1942.62
         },
         {
             "Department": "6021",
             "Total $": 0.46
         },
         {
             "Department": "6030",
             "Total $": 488.13
         }
    ]
}

But I'd really like to have this displayed with departments as the header. So, something like this :

{
 "1101": [
        {
           "12/3/2022": 1887.30,
            "12/4/2022": 1942.62
        }
        ],
 "6021": [
        {
           "12/3/2022": 19.45,
           "12/4/2022": 0.46
        }
   ],
  "6030": [
         {
             "12/3/2022": 247.33,
             "12/4/2022": 488.13
         }
   ]
}

This is my code for collecting the data :

public HttpResponseMessage GetWeeklyStoreSummary(int appid, string fromDate, string endDate, string store)
{
    ResponseHandler response = new ResponseHandler(this.Request);
    WeeklyStoreSummaryHelper ws = new WeeklyStoreSummaryHelper();

    try
    {
        string connectionString = GetConnectionString(appid);
        WeeklyStoreSummaryDBAdapter db = new WeeklyStoreSummaryDBAdapter(connectionString);

        DataSet result;

        foreach (DateTime day in ws.EachDay(fromDate, endDate))
        {
            var currentDate = day.ToShortDateString();
            result = db.GetWeeklySummary(currentDate, store);
            response.AddTable(currentDate, result.Tables[0]);
        }

        string jsonResponse = response.GetJsonResponse();
        return response.RequestCompleted(jsonResponse);
    }
    catch (ArgumentException a)
    {
        return response.BadRequest(a.Message);
    }
    catch (Exception e)
    {
        return response.GenericError(e.Message);
    }
}


问:
Getting an Error due to require field in node .js
Im just strating with node .js and cannot find a solution to this problem, im following tutorials but they do not seem to run into this issue. Maybe im just missing something or doing something wrong.
My code is as follows:

```<code>const express = import("express")
const cors = import("cors")
const morgan = import("morgan")
const low = import("lowdb")

const PORT = process.env.PORT || 4000;

const FileSync = require("lowdb/adapters/FileSync")

const adapter = new FileSync("db.json")
const db = low(adapter)

db.defaults({ books: [] }).write()

const app = express()

app.db = db;

app.use(cors())
app.use(express.json())
app.use(morgan("dev"))

app.listen(PORT, () => console.log('The server is running on port ${PORT}'))
</code>```

The error occurs with the "const FileSync" line and the error message is as follows:

```<code>Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './adapters/FileSync' is not defined by "exports" in "{PATH}"
</code>```

Ive went to a few sites that explain this issue and tried their solutions like deleting the locked file and using npm update and those solutions, but none seem to work.

Body:
Im just strating with node .js and cannot find a solution to this problem, im following tutorials but they do not seem to run into this issue. Maybe im just missing something or doing something wrong.
My code is as follows:

const express = import("express")
const cors = import("cors")
const morgan = import("morgan")
const low = import("lowdb")

const PORT = process.env.PORT || 4000;

const FileSync = require("lowdb/adapters/FileSync")

const adapter = new FileSync("db.json")
const db = low(adapter)

db.defaults({ books: [] }).write()

const app = express()

app.db = db;

app.use(cors())
app.use(express.json())
app.use(morgan("dev"))

app.listen(PORT, () => console.log('The server is running on port ${PORT}'))

The error occurs with the "const FileSync" line and the error message is as follows:

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './adapters/FileSync' is not defined by "exports" in "{PATH}"

Ive went to a few sites that explain this issue and tried their solutions like deleting the locked file and using npm update and those solutions, but none seem to work.


问:
Ionic In App Browser - avoid popup blocker using dynamics links
I'm working with Ionic and Node.Js on a feature that uses a 3rd party payment platform.

Some users are facing issues when they have popups blocked in their chrome or Safari mobile browser because they don't even realize that a new window is trying to open to allow them to perform a payment.

I'm going to an endpoint to create the URL that the user must open.
The question: there is a way to perform a backend call to obtain the URL and use the URL in the in-appbrowser.create without being caught for a popup blocker?

I know that the action must be executed by the user (like a button click).

In my html I have this :

```<code>  <ion-button (click)="pay()" >Pay with the best payment tool</ion-button>
</code>```

And this is my ts code:

pay() {

```<code>this.pageService.showLoading();
const endPoint = this.settings.endPoints.payments + this.settings.endPointsMethods.payments.create;

let paymentToCreate: any = {
  payment: {
    title: 'Inscripción a evento - ' +  this.raceCategory.event.name,
    description: this.raceCategory.event.name,
    referenceType: 'inscriptions',
    unitPrice: this.totalPrice,
    quantity: 1,
    organizator:  this.raceCategory.event.user
  }
};

this.pageService.httpPost(endPoint, paymentToCreate, false).then( (result) => {
  this.payment = result.data;

  if(this.payment) {
    this.openMPInitPoint();
    this.pageService.hideLoading();
  }
  else {
    this.sendMails(true);
  }
})
.catch( error => {
  this.pageService.showError(error);
  this.pageService.hideLoading();
});
</code>```

}

openMPInitPoint() {

```<code>const browser = this.pageService.iab.create(this.payment.initPoint, '_blank', {
  location:"yes",
  closebuttoncaption:"volver",
  hardwareback:"yes"
});

if (browser.on('exit')) {
  browser.on('exit').subscribe(event => {
    this.checkPayment();
  });
} else {
  this.checkPayment();
}
</code>```

}

Body:
I'm working with Ionic and Node.Js on a feature that uses a 3rd party payment platform.

Some users are facing issues when they have popups blocked in their chrome or Safari mobile browser because they don't even realize that a new window is trying to open to allow them to perform a payment.

I'm going to an endpoint to create the URL that the user must open.
The question: there is a way to perform a backend call to obtain the URL and use the URL in the in-appbrowser.create without being caught for a popup blocker?

I know that the action must be executed by the user (like a button click).

In my html I have this :

  <ion-button (click)="pay()" >Pay with the best payment tool</ion-button>

And this is my ts code:

pay() {

this.pageService.showLoading();
const endPoint = this.settings.endPoints.payments + this.settings.endPointsMethods.payments.create;

let paymentToCreate: any = {
  payment: {
    title: 'Inscripción a evento - ' +  this.raceCategory.event.name,
    description: this.raceCategory.event.name,
    referenceType: 'inscriptions',
    unitPrice: this.totalPrice,
    quantity: 1,
    organizator:  this.raceCategory.event.user
  }
};

this.pageService.httpPost(endPoint, paymentToCreate, false).then( (result) => {
  this.payment = result.data;

  if(this.payment) {
    this.openMPInitPoint();
    this.pageService.hideLoading();
  }
  else {
    this.sendMails(true);
  }
})
.catch( error => {
  this.pageService.showError(error);
  this.pageService.hideLoading();
});

}

openMPInitPoint() {

const browser = this.pageService.iab.create(this.payment.initPoint, '_blank', {
  location:"yes",
  closebuttoncaption:"volver",
  hardwareback:"yes"
});

if (browser.on('exit')) {
  browser.on('exit').subscribe(event => {
    this.checkPayment();
  });
} else {
  this.checkPayment();
}

}


问:
How to count null values for each column of a csv file inside of multiple tar.gz files?
I have a directory of over 10,000 large csv files (~200-600 MB per csv file) that were all compressed into individual tar.gz files (~40-80 MB per tar.gz file). The csv files were created through a script that pulls weather data for the last 8 years from an API. Over those 8 years there were some new attributes (columns) added, but the script should have added those columns and filled with nulls.

Each csv file should have the same column headers, but they may be in different orders.

I need to review the data for consistency and ensure that all of the data was pulled into the csv correctly, and that the tar process did not corrupt any of the files. To do this, my idea was to create one table with all of the file names, the columns, and the counts of null values in each column.

I need to do this using Python, but can utilize Anaconda, Jupyter Notebook, or any other IDE or terminal.

Here was my first though on how to do this, but I bet there is a better/faster way to accomplish this.

```<code>- create a master_df with all of the column names plus a column for the file name
- create a loop
    - extract the csv from the tar
    - load the csv into a pandas df
    - add the filename as the first column
    - *somehow count the number of null values for each row
    - save the null counts into the master_df
- compare the rows for any discrepancies
</code>```

Thank you for your ideas!!!

master_file (one row for each csv file):

filename,U component of wind,latitude,longitude,V component of wind,Wind speed (gust),Temperature,Relative humidity,Ozone mixing ratio,Absolute vorticity,Cloud mixing ratio,Haines Index,Snow depth,2 metre temperature,2 metre dewpoint temperature,Apparent temperature,Percent frozen precipitation,Sunshine Duration,Convective available potential energy,Precipitable water,Cloud water,Total ozone,Storm relative helicity,U-component storm motion,V-component storm motion,Vertical speed shear,Pressure,Specific humidity,Pressure reduced to MSL,timestamp,Rain mixing ratio,Categorical snow,Categorical rain,Ice water mixing ratio,Total Cloud Cover,High cloud cover,Low cloud cover,Precipitation rate,Vegetation,Visibility
gfs.0p25.2016070300.f000.grib2.csv.tar.gz,0,0,0,0,0,0,0,0,0,0,1038242,1038242,0,0,0,0,1038242,0,0,0,0,1038242,1038242,1038242,1038242,1038242,1038242,1038242,0,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242
gfs.0p25.2017081118.f000.grib2.csv.tar.gz,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242,0,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242
gfs.0p25.2017091318.f000.grib2.csv.tar.gz,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242
gfs.0p25.2021111706.f000.grib2.csv.tar.gz,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1038242,1038242,0,1038242,0
gfs.0p25.2022070418.f000.grib2.csv.tar.gz,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
```
<p>csv file example (rows greatly condensed):</p>
<pre class="lang-none prettyprint-override"><code>U component of wind,latitude,longitude,V component of wind,Wind speed (gust),Temperature,Relative humidity,Ozone mixing ratio,Absolute vorticity,Cloud mixing ratio,Haines Index,Snow depth,2 metre temperature,2 metre dewpoint temperature,Apparent temperature,Percent frozen precipitation,Sunshine Duration,Convective available potential energy,Precipitable water,Cloud water,Total ozone,Storm relative helicity,U-component storm motion,V-component storm motion,Vertical speed shear,Pressure,Specific humidity,Pressure reduced to MSL,timestamp,Rain mixing ratio,Categorical snow,Categorical rain,Ice water mixing ratio,Total Cloud Cover,High cloud cover,Low cloud cover,Precipitation rate,Vegetation,Visibility
-2.068722534,3.25,109.75,-0.593682861,2.112927246,186.1549609,0,2.94E-07,-1.70E-05,0,--,--,302.2038818,296.9999878,306.7051636,-50.0000061,6609,1479,51.48387609,0,263.386084,3.693237305,-2.701022949,4.627927246,0.014727142,20646.275,2.94E-06,100593,7/3/2022 12:00,0,0,0,0,0,100,0,0,--,24135.00724
-2.068722534,3.25,110,-1.093682861,2.212927246,186.2349609,0,2.94E-07,-3.00E-05,0,--,--,302.2038818,297.0999878,306.7051636,-50.0000061,6600,1512,51.09347609,0,263.586084,4.693237305,-2.521022949,4.537927246,0.013727142,20175.875,2.94E-06,100590.2,7/3/2022 12:00,0,0,0,0,0,57.4,0,0,--,24135.00724
-1.868722534,3.25,110.25,-1.393682861,2.212927246,186.3249609,0,2.94E-07,-3.60E-05,0,--,--,302.2038818,296.9999878,306.6051636,-50.0000061,6518,1470,50.17507609,0,263.786084,0.693237305,-1.721022949,4.717927246,0.005727142,19412.675,2.94E-06,100583,7/3/2022 12:00,0,0,0,0,0,5.6,0,0,--,24135.00724
</code>```

Body:
I have a directory of over 10,000 large csv files (~200-600 MB per csv file) that were all compressed into individual tar.gz files (~40-80 MB per tar.gz file). The csv files were created through a script that pulls weather data for the last 8 years from an API. Over those 8 years there were some new attributes (columns) added, but the script should have added those columns and filled with nulls.

Each csv file should have the same column headers, but they may be in different orders.

I need to review the data for consistency and ensure that all of the data was pulled into the csv correctly, and that the tar process did not corrupt any of the files. To do this, my idea was to create one table with all of the file names, the columns, and the counts of null values in each column.

I need to do this using Python, but can utilize Anaconda, Jupyter Notebook, or any other IDE or terminal.

Here was my first though on how to do this, but I bet there is a better/faster way to accomplish this.

- create a master_df with all of the column names plus a column for the file name
- create a loop
    - extract the csv from the tar
    - load the csv into a pandas df
    - add the filename as the first column
    - *somehow count the number of null values for each row
    - save the null counts into the master_df
- compare the rows for any discrepancies

Thank you for your ideas!!!

master_file (one row for each csv file):

filename,U component of wind,latitude,longitude,V component of wind,Wind speed (gust),Temperature,Relative humidity,Ozone mixing ratio,Absolute vorticity,Cloud mixing ratio,Haines Index,Snow depth,2 metre temperature,2 metre dewpoint temperature,Apparent temperature,Percent frozen precipitation,Sunshine Duration,Convective available potential energy,Precipitable water,Cloud water,Total ozone,Storm relative helicity,U-component storm motion,V-component storm motion,Vertical speed shear,Pressure,Specific humidity,Pressure reduced to MSL,timestamp,Rain mixing ratio,Categorical snow,Categorical rain,Ice water mixing ratio,Total Cloud Cover,High cloud cover,Low cloud cover,Precipitation rate,Vegetation,Visibility
gfs.0p25.2016070300.f000.grib2.csv.tar.gz,0,0,0,0,0,0,0,0,0,0,1038242,1038242,0,0,0,0,1038242,0,0,0,0,1038242,1038242,1038242,1038242,1038242,1038242,1038242,0,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242
gfs.0p25.2017081118.f000.grib2.csv.tar.gz,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242,0,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242
gfs.0p25.2017091318.f000.grib2.csv.tar.gz,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242,1038242
gfs.0p25.2021111706.f000.grib2.csv.tar.gz,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1038242,1038242,0,1038242,0
gfs.0p25.2022070418.f000.grib2.csv.tar.gz,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

csv file example (rows greatly condensed):

U component of wind,latitude,longitude,V component of wind,Wind speed (gust),Temperature,Relative humidity,Ozone mixing ratio,Absolute vorticity,Cloud mixing ratio,Haines Index,Snow depth,2 metre temperature,2 metre dewpoint temperature,Apparent temperature,Percent frozen precipitation,Sunshine Duration,Convective available potential energy,Precipitable water,Cloud water,Total ozone,Storm relative helicity,U-component storm motion,V-component storm motion,Vertical speed shear,Pressure,Specific humidity,Pressure reduced to MSL,timestamp,Rain mixing ratio,Categorical snow,Categorical rain,Ice water mixing ratio,Total Cloud Cover,High cloud cover,Low cloud cover,Precipitation rate,Vegetation,Visibility
-2.068722534,3.25,109.75,-0.593682861,2.112927246,186.1549609,0,2.94E-07,-1.70E-05,0,--,--,302.2038818,296.9999878,306.7051636,-50.0000061,6609,1479,51.48387609,0,263.386084,3.693237305,-2.701022949,4.627927246,0.014727142,20646.275,2.94E-06,100593,7/3/2022 12:00,0,0,0,0,0,100,0,0,--,24135.00724
-2.068722534,3.25,110,-1.093682861,2.212927246,186.2349609,0,2.94E-07,-3.00E-05,0,--,--,302.2038818,297.0999878,306.7051636,-50.0000061,6600,1512,51.09347609,0,263.586084,4.693237305,-2.521022949,4.537927246,0.013727142,20175.875,2.94E-06,100590.2,7/3/2022 12:00,0,0,0,0,0,57.4,0,0,--,24135.00724
-1.868722534,3.25,110.25,-1.393682861,2.212927246,186.3249609,0,2.94E-07,-3.60E-05,0,--,--,302.2038818,296.9999878,306.6051636,-50.0000061,6518,1470,50.17507609,0,263.786084,0.693237305,-1.721022949,4.717927246,0.005727142,19412.675,2.94E-06,100583,7/3/2022 12:00,0,0,0,0,0,5.6,0,0,--,24135.00724


问:
Trouble with scrolling multi-layer parallax effect for cover graphic
I'm working on a custom HTML block that creates a multi-layer parallax effect for a feature image in my WordPress site. I got the code mostly working in a code example (see below) but I'm having an issue where the parallax effect only works if you use the scrollbar that is created on the right side of the cover div. But if you scroll with the main page scrollbar, the image doesn't move at all (no effect).

I created this code sample based on a tutorial I read here, but I'm not sure how to modify the code to allow the effect to work when not scrolling the internal scrollbar within the cover. I added a div above and below the cover to give some space to scroll through to illustrate the problem. Any help / pointers greatly appreciated.

body {
  margin: 0;
}

  .parallax_layer {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}

#parallax {
    perspective: 1px;
    height: 90vh;
    overflow-x: hidden;
    overflow-y: auto;
}

.cover {
        position: relative;
        width: 100vw;
        height: 100vh;
        left: 50% !important;
        transform: translateX(-50%) !important;
    transform-style: preserve-3d;
}

.parallax__layer--front {
        transform: translateZ(0);
}

  .parallax__layer--middle {
        transform: translateZ(-1px) scale(2);
  }

  .parallax__layer--back {
        transform: translateZ(-2px) scale(3);
  }

  .parallax__layer--base {
        transform: translateZ(-3px) scale(4);
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="height: 50vh"></div>
    <div id="parallax" class="cover">
        <img class="parallax_layer parallax__layer--base" src="https://www.staging7.midstory.org/wp-content/uploads/2022/12/Blue-mountains-background.png">
        <img class="parallax_layer parallax__layer--back" src="https://www.staging7.midstory.org/wp-content/uploads/2022/12/circle-in-sky.png">
    <img class="parallax_layer parallax__layer--middle" src="https://www.staging7.midstory.org/wp-content/uploads/2022/12/Airport.png">
        <img class="parallax_layer parallax__layer--front" src="https://www.staging7.midstory.org/wp-content/uploads/2022/12/Gold-ribbon.png">
        <img class="parallax_layer parallax__layer--front" src="https://www.staging7.midstory.org/wp-content/uploads/2022/12/Airplane.png">
    </div>
<div style="height: 50vh"></div></code>```


问:
Powershell forgetting basic commands
I'm using Azure Devops Pipelines

Pipeline calls a powershell script that has a function inside of it.

I make a database call to get some data about a client that will get updated.

I loop the clients and call the function to do the actual updating of the client (updating db, updating code, other things)

$Function = Get-Command runUpdate
$clientList| ForEach-Object -ThrottleLimit 5 -Parallel {
        $client = $_
        write-host "##[section]starting: $client"
        $refObj = $using:Function
        [System.Threading.Monitor]::Enter($refObj)
        ${function:runUpdate} = $using:Function
        runUpdate -client $client -version $($using:prVersion) -packagePath $($using:packagePath)
        write-host "##[section]finished: $client"
        [System.Threading.Monitor]::Exit($refObj)
}
```
<p>It will work fine most of the time, but then while inside of the runUpdate function I'll get errors such as</p>
```The term 'write-host' is not recognized as a name of a cmdlet, function, script file, or executable program.
The term 'Test-Path' is not recognized as a name of a cmdlet, function, script file, or executable program.
The term 'Add-Content' is not recognized as a name of a cmdlet, function, script file, or executable program.
```

I used to have the function within a job and it seems to work more consistently without errors, I swapped it over to threaded jobs so it could actually write out the output so it didn't appear as a mystery function that was being invoked.

Is there some other way I should be calling the function?
Is there a reason that powershell would have issues with basic commands like Write-Host?

Title: Powershell forgetting basic commands

Body:
I'm using Azure Devops Pipelines

Pipeline calls a powershell script that has a function inside of it.

I make a database call to get some data about a client that will get updated.

I loop the clients and call the function to do the actual updating of the client (updating db, updating code, other things)

$Function = Get-Command runUpdate
$clientList| ForEach-Object -ThrottleLimit 5 -Parallel {
        $client = $_
        write-host "##[section]starting: $client"
        $refObj = $using:Function
        [System.Threading.Monitor]::Enter($refObj)
        ${function:runUpdate} = $using:Function
        runUpdate -client $client -version $($using:prVersion) -packagePath $($using:packagePath)
        write-host "##[section]finished: $client"
        [System.Threading.Monitor]::Exit($refObj)
}

It will work fine most of the time, but then while inside of the runUpdate function I'll get errors such as

The term 'write-host' is not recognized as a name of a cmdlet, function, script file, or executable program.
The term 'Test-Path' is not recognized as a name of a cmdlet, function, script file, or executable program.
The term 'Add-Content' is not recognized as a name of a cmdlet, function, script file, or executable program.

I used to have the function within a job and it seems to work more consistently without errors, I swapped it over to threaded jobs so it could actually write out the output so it didn't appear as a mystery function that was being invoked.

Is there some other way I should be calling the function?
Is there a reason that powershell would have issues with basic commands like Write-Host?


问:
The anti-forgery token could not be decrypted error
I have hosted ASP.NET MVC website on Windows Server, but when use login page to log in the user this error appear (The error happens on the server):

```<code>The anti-forgery token could not be decrypted. If this application is hosted by a Web Farm or cluster, ensure that all machines are running the same version of ASP.NET Web Pages and that the <machineKey> configuration specifies explicit encryption and validation keys. AutoGenerate cannot be used in a cluster.
</code>```

There are one AntiForgeryToken() in the view, I review all code many times but not catch error

This the code of Log in Action:

```<code>        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                ShowErrorMessages("InValid Password");
                return View(model);
            }
            var email = Business.User.Instance.GetUserEmail();

            var result = await SignInManager.PasswordSignInAsync(email, model.Password.Trim(), model.RememberMe, shouldLockout: false);
            switch (result)
            {
                case SignInStatus.Success:
                    return RedirectToLocal(returnUrl);
                case SignInStatus.LockedOut:
                    return View("Lockout");
                case SignInStatus.RequiresVerification:
                    return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
                case SignInStatus.Failure:
                default:
                    ShowErrorMessages("Not Valid Password");
                    return View(model);
            }
        }
</code>```

This the code of view:

```<code>@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
            {
                @Html.AntiForgeryToken()

                <div class="col-12">
                    <br />
                    @Html.LabelFor(m => m.Password, new { @class = "control-label" })
                    @Html.PasswordFor(m => m.Password, new { @class = "form-control", @maxlength = 30 })
                    @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
                </div>

                <div class="col-12">
                    <div class="checkbox">
                        <br />
                        @Html.CheckBoxFor(m => m.RememberMe)
                        @Html.LabelFor(m => m.RememberMe)
                    </div>
                </div>

                <div class="col-12">
                    <br />
                    <input type="submit" value="Log in" class="btn btn-success" />
                </div>

            }
</code>```

This the web.config:

```<code>   <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=134.154.22.53;Initial Catalog=myDatabaseName" providerName="System.Data.SqlClient" />
  <system.web>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="533000" slidingExpiration="true"/>
    </authentication>
    <compilation debug="true" targetFramework="4.7.2" />
    <httpRuntime targetFramework="4.7.2" />
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
    <defaultDocument enabled="true">
        <files>
            <clear />
            <add value="index.cshtml"/>
        </files>
    </defaultDocument>
  </system.webServer>
</code>```

I try many attempts but cannot catch it

Body:
I have hosted ASP.NET MVC website on Windows Server, but when use login page to log in the user this error appear (The error happens on the server):

The anti-forgery token could not be decrypted. If this application is hosted by a Web Farm or cluster, ensure that all machines are running the same version of ASP.NET Web Pages and that the <machineKey> configuration specifies explicit encryption and validation keys. AutoGenerate cannot be used in a cluster.

There are one AntiForgeryToken() in the view, I review all code many times but not catch error

This the code of Log in Action:

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                ShowErrorMessages("InValid Password");
                return View(model);
            }
            var email = Business.User.Instance.GetUserEmail();

            var result = await SignInManager.PasswordSignInAsync(email, model.Password.Trim(), model.RememberMe, shouldLockout: false);
            switch (result)
            {
                case SignInStatus.Success:
                    return RedirectToLocal(returnUrl);
                case SignInStatus.LockedOut:
                    return View("Lockout");
                case SignInStatus.RequiresVerification:
                    return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
                case SignInStatus.Failure:
                default:
                    ShowErrorMessages("Not Valid Password");
                    return View(model);
            }
        }

This the code of view:

@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
            {
                @Html.AntiForgeryToken()

                    @Html.LabelFor(m => m.Password, new { @class = "control-label" })
                    @Html.PasswordFor(m => m.Password, new { @class = "form-control", @maxlength = 30 })
                    @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })

                        @Html.CheckBoxFor(m => m.RememberMe)
                        @Html.LabelFor(m => m.RememberMe)

                    <input type="submit" value="Log in" class="btn btn-success" />

            }

This the web.config:

   <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=134.154.22.53;Initial Catalog=myDatabaseName" providerName="System.Data.SqlClient" />
  <system.web>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="533000" slidingExpiration="true"/>
    </authentication>
    <compilation debug="true" targetFramework="4.7.2" />
    <httpRuntime targetFramework="4.7.2" />
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
    <defaultDocument enabled="true">
        <files>
            <clear />
            <add value="index.cshtml"/>
        </files>
    </defaultDocument>
  </system.webServer>

I try many attempts but cannot catch it


问:
Github CICD Polling Time out
How to increase Github Polling time on CICD?

Here is the error I receive:

cloud.exceptions.PlayTimeout: Polling timeout has been reached for ******. Status remains running. 32 Error: Process completed with exit code 1.

Title: Github CICD Polling Time out


问:
Keycloak with postgres on minikube: cannot connect to database
I have one pod with postgres and one pod with keycloak on minikube.
The pod with keycloak deployed via an helm chart from codecentric (chart version 17.0.1, application version 16.1.1) is failing to initialize.
I have inspected the logs and it is failing to connect to the database:

```<code>FATAL [org.keycloak.services] (ServerService Thread Pool -- 64) Error during startup: java.lang.RuntimeException: Failed to connect to database
...

Caused by: org.postgresql.util.PSQLException: Connection to 127.0.0.1:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

</code>```

values.yml used to deploy the helm chart

```<code>postgresql:
  enabled: false

extraEnv: |
  - name: DB_VENDOR
    value: postgres
  - name: DB_ADDR
    value: "127.0.0.1"
  - name: DB_PORT
    value: "5432"
  - name: DB_DATABASE
    value: keycloak
  - name: DB_USER
    value: keycloak
  - name: DB_PASSWORD
    value: keycloak
  - name: KEYCLOAK_USER
    value: "admin"
  - name: KEYCLOAK_PASSWORD
    value: "admin"
  - name: PROXY_ADDRESS_FORWARDING
    value: "true"
  - name: JDBC_PARAMS
    value: "connectTimeout=30000"
</code>```

Files used to deploy the postgresql pod:

postgres-configmap.yml:

```<code>apiVersion: v1
kind: ConfigMap
metadata:
  name: postgres-config-old
  labels:
    app: postgres-old
data:
  POSTGRES_DB: keycloak
  POSTGRES_USER: keycloak
  POSTGRES_PASSWORD: keycloak
</code>```

postgres-deployment.yml:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: postgres-old
spec:
  replicas: 1
  selector:
    matchLabels:
      app: postgres-old
  template:
    metadata:
      labels:
        app: postgres-old
    spec:
      containers:
        - name: postgres-old
          image: docker.io/library/postgres:14.4
          imagePullPolicy: "IfNotPresent"
          ports:
            - containerPort: 5432
          envFrom:
            - configMapRef:
                name: postgres-config-old
          volumeMounts:
            - mountPath: /var/lib/postgresql/14/data
              name: postgredb-old
      volumes:
        - name: postgredb-old
          persistentVolumeClaim:
            claimName: postgres-pv-claim-old
</code>```

postgres-service.yml:

```<code>apiVersion: v1
kind: Service
metadata:
  name: postgres-old
  labels:
    app: postgres-old
spec:
  type: NodePort
  ports:
   - port: 5432
  selector:
   app: postgres-old
</code>```

postgres-storage.yml:

```<code>kind: PersistentVolume
apiVersion: v1
metadata:
  name: postgres-pv-volume-old
  labels:
    type: local
    app: postgres-old
spec:
  storageClassName: manual
  capacity:
    storage: 5Gi
  accessModes:
    - ReadWriteMany
  hostPath:
    path: "/mnt/data"
---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: postgres-pv-claim-old
  labels:
    app: postgres-old
spec:
  storageClassName: manual
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 5Gi
</code>```

I've also tried to expose an external port with:

```<code> minikube service postgres-old --url
</code>```

and add this port on values.yml instead of 5432 but with no luck.

I am running minikube on wsl2.

Body:
I have one pod with postgres and one pod with keycloak on minikube.
The pod with keycloak deployed via an helm chart from codecentric (chart version 17.0.1, application version 16.1.1) is failing to initialize.
I have inspected the logs and it is failing to connect to the database:

FATAL [org.keycloak.services] (ServerService Thread Pool -- 64) Error during startup: java.lang.RuntimeException: Failed to connect to database
...

Caused by: org.postgresql.util.PSQLException: Connection to 127.0.0.1:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

values.yml used to deploy the helm chart

postgresql:
  enabled: false

extraEnv: |
  - name: DB_VENDOR
    value: postgres
  - name: DB_ADDR
    value: "127.0.0.1"
  - name: DB_PORT
    value: "5432"
  - name: DB_DATABASE
    value: keycloak
  - name: DB_USER
    value: keycloak
  - name: DB_PASSWORD
    value: keycloak
  - name: KEYCLOAK_USER
    value: "admin"
  - name: KEYCLOAK_PASSWORD
    value: "admin"
  - name: PROXY_ADDRESS_FORWARDING
    value: "true"
  - name: JDBC_PARAMS
    value: "connectTimeout=30000"

Files used to deploy the postgresql pod:

postgres-configmap.yml:

apiVersion: v1
kind: ConfigMap
metadata:
  name: postgres-config-old
  labels:
    app: postgres-old
data:
  POSTGRES_DB: keycloak
  POSTGRES_USER: keycloak
  POSTGRES_PASSWORD: keycloak

postgres-deployment.yml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: postgres-old
spec:
  replicas: 1
  selector:
    matchLabels:
      app: postgres-old
  template:
    metadata:
      labels:
        app: postgres-old
    spec:
      containers:
        - name: postgres-old
          image: docker.io/library/postgres:14.4
          imagePullPolicy: "IfNotPresent"
          ports:
            - containerPort: 5432
          envFrom:
            - configMapRef:
                name: postgres-config-old
          volumeMounts:
            - mountPath: /var/lib/postgresql/14/data
              name: postgredb-old
      volumes:
        - name: postgredb-old
          persistentVolumeClaim:
            claimName: postgres-pv-claim-old

postgres-service.yml:

apiVersion: v1
kind: Service
metadata:
  name: postgres-old
  labels:
    app: postgres-old
spec:
  type: NodePort
  ports:
   - port: 5432
  selector:
   app: postgres-old

postgres-storage.yml:

kind: PersistentVolume
apiVersion: v1
metadata:
  name: postgres-pv-volume-old
  labels:
    type: local
    app: postgres-old
spec:
  storageClassName: manual
  capacity:
    storage: 5Gi
  accessModes:
    - ReadWriteMany
  hostPath:
    path: "/mnt/data"
---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: postgres-pv-claim-old
  labels:
    app: postgres-old
spec:
  storageClassName: manual
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 5Gi

I've also tried to expose an external port with:

 minikube service postgres-old --url

and add this port on values.yml instead of 5432 but with no luck.

I am running minikube on wsl2.


问:
ERROR: Could not find a version that satisfies the requirement kerastuner (from versions: none) - PyCharm
Attempting to install keras_tuner for hyperparameter and in my attempt to install the package, it gives me this error:

```<code>ERROR: Could not find a version that satisfies the requirement kerastuner (from versions: none)
ERROR: No matching distribution found for kerastuner
</code>```

I've used terminal pip install method along with the three different names for keras tuner, as I want to use the RandomSearch function. What am I doing wrong? Am I using the wrong name? In the python interpreter, when attempting to install the name it only comes up as "kerastuner" but has no versions to choose from.

Body:
Attempting to install keras_tuner for hyperparameter and in my attempt to install the package, it gives me this error:

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

I've used terminal pip install method along with the three different names for keras tuner, as I want to use the RandomSearch function. What am I doing wrong? Am I using the wrong name? In the python interpreter, when attempting to install the name it only comes up as "kerastuner" but has no versions to choose from.


问:
$lookup in two collections with nested documents in MongoDb
I have this scenario:

Doc01:

```<code>    {
      _id: "Unit123",
      name: "Test Unit",
      sections: [
        {
          _id: "63925553eeb147dc9bd894e1",
          name: "TestSection 1",
          contents: [
            {
              _id: "1",
              type: "TEXT_PAGE",
              pageTitle: "Lorem ipsum dolor sit amet, consectetur adipiscing elit..",
              pageContent: "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
            },
            {
              _id: "2",
              type: "TEXT_PAGE",
              pageTitle: "Lorem ipsum dolor sit amet, consectetur adipiscing elit..",
              pageContent: "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
            }
          ],
        },
      ],
    },
</code>```

Doc02:

```<code>    {
      _id: "63925553eeb147dc9bd894e3",
      unit: "Unit123",
      user: 3,
      lastContent: "2",
      progressions: [
        {
          _id: "1",
          isCompleted: true,
        },
        {
          _id: "2",
          isCompleted: true,
        },
      ]
    },
</code>```

I want to achieve this structure:

```<code>    {
      _id: "Unit123",
      name: "Test Unit",
      sections: [
        {
          _id: "63925553eeb147dc9bd894e1",
          name: "TestSection 1",
          contents: [
            {
              _id: "1",
              type: "TEXT_PAGE",
              pageTitle: "Lorem ipsum dolor sit amet, consectetur adipiscing elit..",
              pageContent: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
              unitProgression:  {
                  _id: "1",
                  isCompleted: true,
               },
            },
            {
              _id: "2",
              type: "TEXT_PAGE",
              pageTitle: "Lorem ipsum dolor sit amet, consectetur adipiscing elit..",
              pageContent: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
              unitProgression:  {
                  _id: "2",
                  isCompleted: true,
               },
            }
          ],
        },
      ],
    },
</code>```

I'm stucked in turning the sections and contents a group after the lookup.
This is my query:

```<code>db.units.aggregate([
  {
    "$unwind": "$sections"
  },
  {
    "$unwind": "$sections.contents"
  },
  {
    "$lookup": {
      "from": "unitProgressions",
      let: {
        contentsId: "$sections.contents._id"
      },
      pipeline: [
        {
          "$unwind": "$progressions"
        },
        {
          $match: {
            $expr: {
              $eq: [
                "$$contentsId",
                "$progressions._id"
              ]
            }
          }
        },

      ],
      "as": "sections.contents.unitProgression"
    }
  },
  {
    "$unwind": {
      path: "$sections.contents.unitProgression",
      "preserveNullAndEmptyArrays": true
    }
  },

])
</code>```

I tried to use group but it only groups the parent fields.
Is it possible to build this structure? Is there a better way to organize this schemas? It feels that I'll have problems with this query speed.

MongoDB Playground

Thanks!

Body:
I have this scenario:

Doc01:

    {
      _id: "Unit123",
      name: "Test Unit",
      sections: [
        {
          _id: "63925553eeb147dc9bd894e1",
          name: "TestSection 1",
          contents: [
            {
              _id: "1",
              type: "TEXT_PAGE",
              pageTitle: "Lorem ipsum dolor sit amet, consectetur adipiscing elit..",
              pageContent: "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
            },
            {
              _id: "2",
              type: "TEXT_PAGE",
              pageTitle: "Lorem ipsum dolor sit amet, consectetur adipiscing elit..",
              pageContent: "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
            }
          ],
        },
      ],
    },

Doc02:

    {
      _id: "63925553eeb147dc9bd894e3",
      unit: "Unit123",
      user: 3,
      lastContent: "2",
      progressions: [
        {
          _id: "1",
          isCompleted: true,
        },
        {
          _id: "2",
          isCompleted: true,
        },
      ]
    },

I want to achieve this structure:

    {
      _id: "Unit123",
      name: "Test Unit",
      sections: [
        {
          _id: "63925553eeb147dc9bd894e1",
          name: "TestSection 1",
          contents: [
            {
              _id: "1",
              type: "TEXT_PAGE",
              pageTitle: "Lorem ipsum dolor sit amet, consectetur adipiscing elit..",
              pageContent: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
              unitProgression:  {
                  _id: "1",
                  isCompleted: true,
               },
            },
            {
              _id: "2",
              type: "TEXT_PAGE",
              pageTitle: "Lorem ipsum dolor sit amet, consectetur adipiscing elit..",
              pageContent: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
              unitProgression:  {
                  _id: "2",
                  isCompleted: true,
               },
            }
          ],
        },
      ],
    },

I'm stucked in turning the sections and contents a group after the lookup.
This is my query:

db.units.aggregate([
  {
    "$unwind": "$sections"
  },
  {
    "$unwind": "$sections.contents"
  },
  {
    "$lookup": {
      "from": "unitProgressions",
      let: {
        contentsId: "$sections.contents._id"
      },
      pipeline: [
        {
          "$unwind": "$progressions"
        },
        {
          $match: {
            $expr: {
              $eq: [
                "$$contentsId",
                "$progressions._id"
              ]
            }
          }
        },

      ],
      "as": "sections.contents.unitProgression"
    }
  },
  {
    "$unwind": {
      path: "$sections.contents.unitProgression",
      "preserveNullAndEmptyArrays": true
    }
  },

])

I tried to use group but it only groups the parent fields.
Is it possible to build this structure? Is there a better way to organize this schemas? It feels that I'll have problems with this query speed.

MongoDB Playground

Thanks!


问:
restAPI login implementation when using password hashing with a salt (argon2)
I'm currently building a rest api and stumbled across this problem:

The users password is stored hashed with a salt in the database as a typical argon2 string.

A user tries to login and sends therewith his email and password (unhashed).
But how do I compare hashes if I cant hash the password again ( as I'm missing the original salt).
Should I get the hash from the database and the compare the two or what's the best practice there?

I tried it with getting the hash form the database but I'm not sure if it's allowed to "get" something from a database if the user's request is a post-request.


问:
Open stack Magnum docker private repo
I am working in Open stack Magnum,  and resent days I am facing issue in deploying magnum , due to docker pulling rate limit Magnum is not pulling the docker containers.  Please help me how to point private repo to mangum to avoid this pulling rate.

Hi Team,
I am working in Open stack Magnum,  and resent days I am facing issue in deploying magnum , due to docker pulling rate limit Magnum is not pulling the docker containers.  Please help me how to point private repo to mangum to avoid this pulling rate.

Title: Open stack Magnum docker private repo


问:
"_ setUrl: unrecognized selector sent to instance" setting the url property to the Swift Publisher
I want to set the url variable that Published in Swift

Error:

```<code>2022-12-15 21:55:27.837982+0100 WebviewIosExample[23481:8227336] [native] Error setting property 'url' of WebView with tag #7: Exception thrown while executing UI block:
-[_TtGC7SwiftUI14_UIHostingViewV24react_native_webview_ios7WebView_ setUrl:]: unrecognized selector sent to instance 0x104417700
</code>```
```<code>//WebViewManager.swift
@available(iOS 14.0, *)
@objc(WebViewManager)
class WebViewManager: RCTViewManager {

    public var vc = UIHostingController(rootView: WebView())

    @objc var url: String {
        set { vc.rootView.props.url = newValue }
        get { return vc.rootView.props.url }
    }

    @objc override func view() -> UIView! {
        return vc.view
    }

    override static func requiresMainQueueSetup() -> Bool {
        return true
    }

}
</code>```
```<code>//WebViewManager.m

#import <React/RCTViewManager.h>

@interface RCT_EXTERN_MODULE(WebViewManager, RCTViewManager)

RCT_EXPORT_VIEW_PROPERTY(url, NSString)

@end

</code>```
```<code>// Bridgin-Header
#import <React/RCTViewManager.h>

</code>```
```<code>// WebView.Swift
@available(iOS 14.0, *)
struct WebView: UIViewRepresentable {

    @ObservedObject var props = WebViewStore()

    func makeUIView(context: Context) -> WKWebView {
        let prefs = WKWebpagePreferences()
        prefs.allowsContentJavaScript = true
        let config = WKWebViewConfiguration()
        config.defaultWebpagePreferences = prefs
        let webView = WKWebView(frame: .zero, configuration: config)
        return webView
    }

    func updateUIView(_ webView: WKWebView, context: Context) {
        guard let theUrl = URL(string: props.url) else {
            return
        }

        let request = URLRequest(url: theUrl)
        webView.load(request)
    }

}
</code>```

I want to set the WebViewStoreManager url while it passed to from React Native Code

```<code>@objc var url: String {
    set { vc.rootView.props.url = newValue }
    get { return vc.rootView.props.url }
}
</code>```

Usage in RN:

```<code>import { WebView } from 'react-native-webview-ios';

// ...

<WebView url="https://open.spotify.com" />;
</code>```

I tried:

```<code>@objc(setUrl:)
public func setUrl(url: String) {
    vc.rootView.props.url = url
}
</code>```

Body:
I want to set the url variable that Published in Swift

Error:

2022-12-15 21:55:27.837982+0100 WebviewIosExample[23481:8227336] [native] Error setting property 'url' of WebView with tag #7: Exception thrown while executing UI block:
-[_TtGC7SwiftUI14_UIHostingViewV24react_native_webview_ios7WebView_ setUrl:]: unrecognized selector sent to instance 0x104417700

//WebViewManager.swift
@available(iOS 14.0, *)
@objc(WebViewManager)
class WebViewManager: RCTViewManager {

    public var vc = UIHostingController(rootView: WebView())

    @objc var url: String {
        set { vc.rootView.props.url = newValue }
        get { return vc.rootView.props.url }
    }

    @objc override func view() -> UIView! {
        return vc.view
    }

    override static func requiresMainQueueSetup() -> Bool {
        return true
    }

}

//WebViewManager.m

#import <React/RCTViewManager.h>

@interface RCT_EXTERN_MODULE(WebViewManager, RCTViewManager)

RCT_EXPORT_VIEW_PROPERTY(url, NSString)

@end

// Bridgin-Header
#import <React/RCTViewManager.h>

// WebView.Swift
@available(iOS 14.0, *)
struct WebView: UIViewRepresentable {

    @ObservedObject var props = WebViewStore()

    func makeUIView(context: Context) -> WKWebView {
        let prefs = WKWebpagePreferences()
        prefs.allowsContentJavaScript = true
        let config = WKWebViewConfiguration()
        config.defaultWebpagePreferences = prefs
        let webView = WKWebView(frame: .zero, configuration: config)
        return webView
    }

    func updateUIView(_ webView: WKWebView, context: Context) {
        guard let theUrl = URL(string: props.url) else {
            return
        }

        let request = URLRequest(url: theUrl)
        webView.load(request)
    }

}

I want to set the WebViewStoreManager url while it passed to from React Native Code

@objc var url: String {
    set { vc.rootView.props.url = newValue }
    get { return vc.rootView.props.url }
}

Usage in RN:

import { WebView } from 'react-native-webview-ios';

// ...

<WebView url="https://open.spotify.com" />;

I tried:

@objc(setUrl:)
public func setUrl(url: String) {
    vc.rootView.props.url = url
}


问:
Ajax returns only first result in a PHP while loop
I am building a chat application and when I click the available users list (which is generated from a php while loop) the chat area is supposed to carry the information of that user and previous chat history (if any). However, for some reason ajax onclick keeps returning just the first user on the list into the chat area.

I have tried different methods of getting each user's id from the users-list (a separate php file) and passing it to the active-chat area (another php file) using ajax. I believe I'm missing something or doing something wrong. Every suggestion or different approach will be very much appreciated.

User's List PHP Code:

```<code><?php
// this php is an include in another php file if certain conditions are met.
while($users = mysqli_fetch_assoc($sql)){

    // the list of users generated into the home page
    $output .= '<li id="contact" class="get-user-chats">
                    <input type="hidden" id="getUserId" value="'.$users['user_id'].'"/>
                    <span class="avatar"><img src="'.$users['display_pic'].'" height="42" width="42" alt="Generic placeholder image" />
                        <span class="'.$users['online_status'].'"></span>
                    </span>
                    <div class="chat-info flex-grow-1">
                        <h5 class="mb-0">'.$users['full_name'].'</h5>
                        <p class="card-text text-truncate">
                            This is just a test message to see if the truncate feature works
                        </p>
                    </div>
                    <div class="chat-meta text-nowrap">
                        <small class="float-end mb-25 chat-time">4:14 PM</small>
                        <span class="badge bg-danger rounded-pill float-end">3</span>
                    </div>
                </li>';

}
?>
</code>```

Ajax Code:

```<code>$(document).ready(function(){
            $('.users-list').click(function(){
            //users-list is a class from the home page where the users list displays in a div
            var $container = $(this).find(".get-user-chats");
            var chatid = $container.find("#getUserId").val();
            $.ajax({
                url: './code/active-chat.php',
                type: 'POST',
                data: {
                    chatuserid: chatid
                },
                success: function(response){
                    //alert(chatid)
                    $('.get-active-chat-user').html(response);
                },
                dataType: 'text'
                });
            });
        });
</code>```

active-chat.php

```<code><?php
// active-chat.php
session_start();
define('BASEPATH', true);
require "../../../../private/engine.php";
$chatid = $_POST['chatuserid'];

$sql = "SELECT * FROM users WHERE user_id = '{$chatid}'";
$fetchdata = mysqli_query($connection, $sql);

while($sub = mysqli_fetch_array($fetchdata)){
    ?>
    <header class="chat-header">
        <div class="d-flex align-items-center">
            <div class="sidebar-toggle d-block d-lg-none me-1">
                <i data-feather="menu" class="font-medium-5"></i>
            </div>
            <div class="avatar avatar-border user-profile-toggle m-0 me-1">
                <img src="<?php echo $sub['display_pic']; ?>" alt="avatar" height="36" width="36" />
                <span class="<?php echo $sub['online_status']; ?>"></span>
            </div>
            <h6 class="mb-0"><?php echo $sub['full_name'] ?></h6>
        </div>
        <div class="d-flex align-items-center">
            <i data-feather="phone-call" class="cursor-pointer d-sm-block d-none font-medium-2 me-1"></i>
            <i data-feather="video" class="cursor-pointer d-sm-block d-none font-medium-2 me-1"></i>
            <!-- <i data-feather="search" class="cursor-pointer d-sm-block d-none font-medium-2"></i> -->
            <div class="dropdown">
                <button class="btn-icon btn btn-transparent hide-arrow btn-sm dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    <i data-feather="more-vertical" id="chat-header-actions" class="font-medium-2"></i>
                </button>
                <div class="dropdown-menu dropdown-menu-end" aria-labelledby="chat-header-actions">
                    <a class="dropdown-item" href="#">View Contact</a>
                    <a class="dropdown-item" href="#">Mute Notifications</a>
                    <a class="dropdown-item" href="#">Block Contact</a>
                    <a class="dropdown-item" href="#">Clear Chat</a>
                    <a class="dropdown-item" href="#">Report</a>
                </div>
            </div>
        </div>
    </header>
<?php } ?>
</code>```

Screenshot of the Chat Screen:
Chat Screen

I have researched on related topics but none of them seems to address my specific issue.

Body:
I am building a chat application and when I click the available users list (which is generated from a php while loop) the chat area is supposed to carry the information of that user and previous chat history (if any). However, for some reason ajax onclick keeps returning just the first user on the list into the chat area.

I have tried different methods of getting each user's id from the users-list (a separate php file) and passing it to the active-chat area (another php file) using ajax. I believe I'm missing something or doing something wrong. Every suggestion or different approach will be very much appreciated.

User's List PHP Code:

<?php
// this php is an include in another php file if certain conditions are met.
while($users = mysqli_fetch_assoc($sql)){

    // the list of users generated into the home page
    $output .= '

                    <input type="hidden" id="getUserId" value="'.$users['user_id'].'"/>

'.$users['full_name'].'

                            This is just a test message to see if the truncate feature works

                        4:14 PM
                        3

';

}
?>

Ajax Code:

$(document).ready(function(){
            $('.users-list').click(function(){
            //users-list is a class from the home page where the users list displays in a div
            var $container = $(this).find(".get-user-chats");
            var chatid = $container.find("#getUserId").val();
            $.ajax({
                url: './code/active-chat.php',
                type: 'POST',
                data: {
                    chatuserid: chatid
                },
                success: function(response){
                    //alert(chatid)
                    $('.get-active-chat-user').html(response);
                },
                dataType: 'text'
                });
            });
        });

active-chat.php

<?php
// active-chat.php
session_start();
define('BASEPATH', true);
require "../../../../private/engine.php";
$chatid = $_POST['chatuserid'];

$sql = "SELECT * FROM users WHERE user_id = '{$chatid}'";
$fetchdata = mysqli_query($connection, $sql);

while($sub = mysqli_fetch_array($fetchdata)){
    ?>

                <img src="<?php echo $sub['display_pic']; ?>" alt="avatar" height="36" width="36" />
                <span class="<?php echo $sub['online_status']; ?>">

<?php echo $sub['full_name'] ?>

                <button class="btn-icon btn btn-transparent hide-arrow btn-sm dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">

                </button>

                    View Contact
                    Mute Notifications
                    Block Contact
                    Clear Chat
                    Report

<?php } ?>

Screenshot of the Chat Screen:
Chat Screen

I have researched on related topics but none of them seems to address my specific issue.


问:
I have multiple buttons and I want to capture the id of the clicked button and use it in a switch case statement
I have several buttons that I want to trigger a block of HML code based on which button is clicked.  I want to capture the clicked button id and use it in my switch case statement.  I am new and trying to teach myself.

Do I need to enclose my group of buttns in a script.  Where do I place the HTML code for my case statement.  here is my related cod3.

```<code><button type="button" id = "seahawks"      onClick="GetStadium(this.id)">  </button>
<button type="button" id = "buccaneers"    onClick="GetStadium(this.id)">  </button>
<button type="button" id = "titans"        onClick="GetStadium(this.id)">  </button>
<button type="button" id = "commanders"    onClick="GetStadium(this.id)">  </button>

<script>
function GetStadium(team) {
Switch (team) {
case "seahawks":
Code for seahawks here.  Should this HTML code be in a div or something else?
break;
case 'buccaneers';
break;
case 'titans';
break;}}

I am expecting a mapped image f the stadium seating chart to appear.
</code>```
```<code>    <button type="button" id = "seahawks"      onClick="GetStadium(this.id)">  </button>
    <button type="button" id = "buccaneers"    onClick="GetStadium(this.id)">  </button>
    <button type="button" id = "titans"        onClick="GetStadium(this.id)">  </button>
    <button type="button" id = "commanders"    onClick="GetStadium(this.id)">  </button>

    <script>
    function GetStadium(team) {
    Switch (team) {
     case "seahawks":
           Code for seahawks here.  Should this HTML code be in a div or something else?
     break;
     case 'buccaneers';
      break;
     case 'titans';
    break;}}

    <P style="text-align:center; font-family:times new roman;font-size:50px;  color:purple"><b>RAVENS S      TADIUM SEATING CHART</b></p>
    <p style="text-align:center; font-family:times new roman;font-size:20px;  color:black>" <b>CLICK ON SECTION IN SEATING CHART TO SEE YOUR VIEW FROM THAT SECTION </b></p>
    <center>

    <img clas="contain"         src="https://static.wixstatic.com/media/785ee8_aaeb22067b9c43088809130df1ac153b~mv2.jpg" alt="Ravens     Stadium" usemap="#ravens"  </img>

<    /center>
    <map name="ravens">

    <area target="_blank" alt="Sect 100" title="Sect 100" href="https://www.youtube.com/watch?v=977dYY_k0HA" coords="781,300,852,300,843,424,782,425" shape="poly">
    <area target="_blank" alt="Sect 101" title="Sect 101" href="https://www.youtube.com/watch?v=977dYY_k0HA" coords="856,302,915,305,908,424,852,421" shape="poly">
    <area target="_blank" alt="Sect 102" title="Sect 102" href="https://www.youtube.com/watch?v=977dYY_k0HA" coords="924,305,980,307,966,429,918,427" shape="poly">
    <area target="_blank" alt="Sect 103" title="Sect 103" href="https://www.youtube.com/watch?v=977dYY_k0HA" oords="992,311,1052,316,1034,439,979,434" shape="poly">
</code>```

Body:
I have several buttons that I want to trigger a block of HML code based on which button is clicked.  I want to capture the clicked button id and use it in my switch case statement.  I am new and trying to teach myself.

Do I need to enclose my group of buttns in a script.  Where do I place the HTML code for my case statement.  here is my related cod3.

<button type="button" id = "seahawks"      onClick="GetStadium(this.id)">  </button>
<button type="button" id = "buccaneers"    onClick="GetStadium(this.id)">  </button>
<button type="button" id = "titans"        onClick="GetStadium(this.id)">  </button>
<button type="button" id = "commanders"    onClick="GetStadium(this.id)">  </button>


问:
Is there a way to update a Notion block so it adds another elemtent inside ["paragraph"]["text"]?
I want to be able to update a Notion block in a way that it adds a piece of text when it finds a bolded word. I want it in this way:

This text is important for some reason.

The text before running the code.

This text is important(1) for some reason.

The text after running the code.

I see that Notion fragments the contents of a block into pieces with different styles, so the previous line can be accessed, after retrieving and a JSON formatting, through ["paragraph"]["rich_text"][0], [1] and [2].

What I tried is to add that "(1)" through insert, but everytime I try to send it to Notion it throws the same error:

ValueError: too many values to unpack (expected 2)

I dumped the old and the new data into a json file and it looks nicely inserted. I don't know where the error can be. I'm quite new into programming so it's hard to see where the error is leading me to. This is the code I'm using for the insertion:

```<code>data = retrieveBlock()

newData = {
  'type': 'text',
  'text': {
    'content': '(1)',
    'link': None
  },
  'annotations': {
    'bold': False,
    'italic': False,
    'strikethrough': False,
    'underline': False,
    'code': False,
    'color': 'default'
  },
  'plain_text': '(1)',
  'href': None
}

data.insert(2, newData)

res = requests.request("PATCH",
                        block_url + block_id,
                        data=data,
                        headers=headers)
</code>```

Thanks for the help!

I tried loading and dumping JSON before and after calling the old and the new data. I also tried reformatting the keys on the new data, but it looks like they are later ordered automatically.

Body:
I want to be able to update a Notion block in a way that it adds a piece of text when it finds a bolded word. I want it in this way:

This text is important for some reason.

The text before running the code.

This text is important(1) for some reason.

The text after running the code.

I see that Notion fragments the contents of a block into pieces with different styles, so the previous line can be accessed, after retrieving and a JSON formatting, through ["paragraph"]["rich_text"][0], [1] and [2].

What I tried is to add that "(1)" through insert, but everytime I try to send it to Notion it throws the same error:

ValueError: too many values to unpack (expected 2)

I dumped the old and the new data into a json file and it looks nicely inserted. I don't know where the error can be. I'm quite new into programming so it's hard to see where the error is leading me to. This is the code I'm using for the insertion:

data = retrieveBlock()

newData = {
  'type': 'text',
  'text': {
    'content': '(1)',
    'link': None
  },
  'annotations': {
    'bold': False,
    'italic': False,
    'strikethrough': False,
    'underline': False,
    'code': False,
    'color': 'default'
  },
  'plain_text': '(1)',
  'href': None
}

data.insert(2, newData)

res = requests.request("PATCH",
                        block_url + block_id,
                        data=data,
                        headers=headers)

Thanks for the help!

I tried loading and dumping JSON before and after calling the old and the new data. I also tried reformatting the keys on the new data, but it looks like they are later ordered automatically.


问:
Unity Ar foundation body tracking. Is it possible to track multiple bodies?
If you use the latest version of AR foundation (I had to manually edit Packages/manifest.json to get it) and also have an iphone with an A12 processor or later, you can have body tracking.

You can track 3d or 2d human bodies.
I am interested in the 2d tracking.

In Unity's demo they are using this line of code to get the human body data

```<code>var joints = m_HumanBodyManager.GetHumanBodyPose2DJoints(Allocator.Temp);
</code>```

Which seems to only return info for one body even if the phone can see 2 or more.
I am wondering if tracking multiple bodies is possible, some functions of the humanBodyManager class seem to hint at this being possible. eg.

This function

```<code>    OnTrackablesChanged(List<ARHumanBody>, List<ARHumanBody>, List<ARHumanBody>)

    List<ARHumanBody>   added
    The list of human bodies added to the set of trackables.
    List<ARHumanBody>   updated
    The list of human bodies updated in the set of trackables.
    List<ARHumanBody>   removed
    The list of human bodies removed to the set of trackables.
</code>```

and this event

```<code>public event Action<ARHumanBodiesChangedEventArgs> humanBodiesChanged

The event that is fired when a change to the detected human bodies is reported.
</code>```

That function is protected, and I have tried subscribing to that event but it doesnt ever seem to be called. Its also very weird as its an event which wants to call functions which return an action that takes ARHumanBodiesChangedEventArgs as a paramater... I dunno why anyone would ever write a thing like that tbh.

Anyway writing visual debug code and then building to iOS to test all these semi documented classes is a massive pain. If someone could just let me know if multiple body tracking is even possible with ar foundation that would help me a lot. Thanks!

Body:
If you use the latest version of AR foundation (I had to manually edit Packages/manifest.json to get it) and also have an iphone with an A12 processor or later, you can have body tracking.

You can track 3d or 2d human bodies.
I am interested in the 2d tracking.

In Unity's demo they are using this line of code to get the human body data

var joints = m_HumanBodyManager.GetHumanBodyPose2DJoints(Allocator.Temp);

Which seems to only return info for one body even if the phone can see 2 or more.
I am wondering if tracking multiple bodies is possible, some functions of the humanBodyManager class seem to hint at this being possible. eg.

This function

    OnTrackablesChanged(List<ARHumanBody>, List<ARHumanBody>, List<ARHumanBody>)

    List<ARHumanBody>   added
    The list of human bodies added to the set of trackables.
    List<ARHumanBody>   updated
    The list of human bodies updated in the set of trackables.
    List<ARHumanBody>   removed
    The list of human bodies removed to the set of trackables.

and this event

public event Action<ARHumanBodiesChangedEventArgs> humanBodiesChanged

The event that is fired when a change to the detected human bodies is reported.

That function is protected, and I have tried subscribing to that event but it doesnt ever seem to be called. Its also very weird as its an event which wants to call functions which return an action that takes ARHumanBodiesChangedEventArgs as a paramater... I dunno why anyone would ever write a thing like that tbh.

Anyway writing visual debug code and then building to iOS to test all these semi documented classes is a massive pain. If someone could just let me know if multiple body tracking is even possible with ar foundation that would help me a lot. Thanks!