问:
How to pass three parameters to url address using ASP.NET Core Web API
For now I have a procedure I wish to call:

```<code>CALL Get_Discharge_Station('2022-02-02', 6, 11800);
</code>```

I want to pass these three parameters - 2022-02-02,6,11800 to url address, when I enter different date,number and number of station to get different data.

For now my API controller look like this:

```<code>using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;

namespace WebAPI.Controllers
{
    [Route("api/hqdataahs")]
    [ApiController]
    public class HQ_data_AHSController : ControllerBase
    {
        private readonly IConfiguration _configuration;

        public HQ_data_AHSController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        [HttpGet]
        public JsonResult Get()
        {
            string query = @"CALL Get_Discharge_Station('2022-02-02', 6, 11800);";

            DataTable table = new DataTable();

            string sqlDataSource = _configuration.GetConnectionString("AppCon");

            MySqlDataReader myReader;

            using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
            {
                mycon.Open();

                using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
                {
                    myReader = myCommand.ExecuteReader();
                    table.Load(myReader);

                    myReader.Close();
                    mycon.Close();
                }
            }

            return new JsonResult(table);
        }
    }
}
</code>```

What can I change to pass there three parameters in url address when I access the controller?`

答:
declare the args

```<code>    [HttpGet]
    public JsonResult Get(string dataStr, int noodle, int frumpy)
    {
</code>```

now construct the call

```<code>  string query = $"CALL Get_Discharge_Station('{dateStr}', {noodle}, {fumpy});"
</code>```

Body:
For now I have a procedure I wish to call:

CALL Get_Discharge_Station('2022-02-02', 6, 11800);

I want to pass these three parameters - 2022-02-02,6,11800 to url address, when I enter different date,number and number of station to get different data.

For now my API controller look like this:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;

namespace WebAPI.Controllers
{
    [Route("api/hqdataahs")]
    [ApiController]
    public class HQ_data_AHSController : ControllerBase
    {
        private readonly IConfiguration _configuration;

        public HQ_data_AHSController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        [HttpGet]
        public JsonResult Get()
        {
            string query = @"CALL Get_Discharge_Station('2022-02-02', 6, 11800);";

            DataTable table = new DataTable();

            string sqlDataSource = _configuration.GetConnectionString("AppCon");

            MySqlDataReader myReader;

            using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
            {
                mycon.Open();

                using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
                {
                    myReader = myCommand.ExecuteReader();
                    table.Load(myReader);

                    myReader.Close();
                    mycon.Close();
                }
            }

            return new JsonResult(table);
        }
    }
}

What can I change to pass there three parameters in url address when I access the controller?`

Body:
declare the args

    [HttpGet]
    public JsonResult Get(string dataStr, int noodle, int frumpy)
    {

now construct the call

  string query = $"CALL Get_Discharge_Station('{dateStr}', {noodle}, {fumpy});"


来源: stackexchange

答:
With the suggestion from @tdy I added the following two lines of code to add the rectangle.

```<code>rect = matplotlib.patches.Rectangle(xy=(2026, 50.8),
                                    width=1, height=2,
                                    linewidth=2, edgecolor='skyblue',
                                    alpha = 0.5,
                                    facecolor='skyblue', clip_on= False);

plt.gca().add_patch(rect)
</code>```

To set the rectangle outside the boundary of the plot, I limited the boundary of the x-axis.

```<code>plt.xlim(2015, 2025.5)
</code>```

And then I added the text using plt.text() as shown:

```<code>plt.text(x = 2027.2, y = 52, s = "Policies and action \n +x°C",)
</code>```

Finally, I get the desired plot as shown below:

ContentLicense: CC BY-SA 4.0

Title: How can I add a filled rectangle outside the boundary of the plot in place of the legend?

Body:
I have a dataframe df which looks as follows:

Indicators  Historical  Policies and action High    Policies and action Low
2015    50.625053   NaN NaN
2016    50.582576   NaN NaN
2017    51.292209   NaN NaN
2018    51.941135   NaN NaN
2019    52.035179   52.035179   51.998587
2020    NaN 49.548225   49.192943
2021    NaN 51.044943   50.036852
2022    NaN 51.859163   50.489466
2023    NaN 52.181097   50.664963
2024    NaN 52.503669   50.748202
2025    NaN 52.834307   50.791621

df.to_dict() is as shown:

{'Historical': {2015: 50.6250534,
  2016: 50.5825758,
  2017: 51.292208707843,
  2018: 51.9411345916894,
  2019: 52.0351792911552,
  2020: nan,
  2021: nan,
  2022: nan,
  2023: nan,
  2024: nan,
  2025: nan},
 'Policies and action High': {2015: nan,
  2016: nan,
  2017: nan,
  2018: nan,
  2019: 52.0351792911552,
  2020: 49.5482253492566,
  2021: 51.0449425357562,
  2022: 51.8591630733255,
  2023: 52.1810970660186,
  2024: 52.5036690312549,
  2025: 52.8343073895085},
 'Policies and action Low': {2015: nan,
  2016: nan,
  2017: nan,
  2018: nan,
  2019: 51.9985870414207,
  2020: 49.1929429878652,
  2021: 50.036851875037,
  2022: 50.4894655321311,
  2023: 50.6649626706684,
  2024: 50.7482020284128,
  2025: 50.7916209335673}}

I have plotted the Historical column as a line, and I have filled the area between Policies and action High, and Policies and action Low columns.

The code used is as shown

df.Historical.plot(color = "black",
                  lw = 3,
                  label = "Historical")

df["Policies and action High"].plot(color = "skyblue", label = "")
df["Policies and action Low"].plot(color = "skyblue", label = "")
plt.fill_between(x = df.index.tolist(),
                y1 = df["Policies and action Low"],
                y2 = df["Policies and action High"],
                color = "skyblue",
                alpha = 0.25,
                label = "Policies and action")

plt.legend()

The resulting plot is as shown:

Instead of the legend, I'd like to add a filled rectangle of the same color besides the shaded region as shown within the red perimeter, and add corresponding text besides it:

I am not sure how to add this since this needs to be added outside the boundary of the plot, but still correspond to the figure inside the boundary. How can this be achieved using matplotlib or similar visualisation libraries in Python?

Body:
With the suggestion from @tdy I added the following two lines of code to add the rectangle.

rect = matplotlib.patches.Rectangle(xy=(2026, 50.8),
                                    width=1, height=2,
                                    linewidth=2, edgecolor='skyblue',
                                    alpha = 0.5,
                                    facecolor='skyblue', clip_on= False);

plt.gca().add_patch(rect)

To set the rectangle outside the boundary of the plot, I limited the boundary of the x-axis.

plt.xlim(2015, 2025.5)

And then I added the text using plt.text() as shown:

plt.text(x = 2027.2, y = 52, s = "Policies and action \n +x°C",)

Finally, I get the desired plot as shown below:


问:
Serverless deploy throwing error: "Object notation for "service" property is not supported. Set "service" property directly with service name."
I am building a microservice using Node JS serverless framework. To be honest, this is my first time building a microservice using serverless. I have configured the AWS credentials on my machine already.

I created the project running the following command.

```<code>serverless create -u https://github.com/codingly-io/sls-base -n aution-service
</code>```

Then I run npm install inside the project folder.

This is my serverless.yml folder.

```<code>service:
  name: auction-service

plugins:
  - serverless-bundle
  - serverless-pseudo-parameters

provider:
  name: aws
  runtime: nodejs12.x
  memorySize: 256
  stage: ${opt:stage, 'dev'}
  region: eu-west-2

functions:
  hello:
    handler: src/handlers/hello.handler
    events:
      - http:
          method: GET
          path: /hello
</code>```

I already have the lambda function that comes with the template. Then I run serverless deploy to deploy the service. When I run the command, I got the following error.

```<code>Error:
Object notation for "service" property is not supported. Set "service" property directly with service name.
</code>```

What is wrong my configuration or code and how can I fix it?

答:
You can fix it by setting the name of the service directly to service property like this

```<code>service: auction-service
</code>```

The nested notation is no longer supported.

Body:
I am building a microservice using Node JS serverless framework. To be honest, this is my first time building a microservice using serverless. I have configured the AWS credentials on my machine already.

I created the project running the following command.

serverless create -u https://github.com/codingly-io/sls-base -n aution-service

Then I run npm install inside the project folder.

This is my serverless.yml folder.

service:
  name: auction-service

plugins:
  - serverless-bundle
  - serverless-pseudo-parameters

provider:
  name: aws
  runtime: nodejs12.x
  memorySize: 256
  stage: ${opt:stage, 'dev'}
  region: eu-west-2

functions:
  hello:
    handler: src/handlers/hello.handler
    events:
      - http:
          method: GET
          path: /hello

I already have the lambda function that comes with the template. Then I run serverless deploy to deploy the service. When I run the command, I got the following error.

Error:
Object notation for "service" property is not supported. Set "service" property directly with service name.

What is wrong my configuration or code and how can I fix it?

Body:
You can fix it by setting the name of the service directly to service property like this

service: auction-service

The nested notation is no longer supported.


问:
Parse a structured dictionary of entries into a prettified Excel sheet
I have this python dictionary and I want to write this data to an Excel file.

NOTE: there are many categories and each category has many cars (I used 2 categories for simplicity)

```<code>data = {"Category": {"Diesel" : [{
                                "Name": "Land Rover",
                                "Description":"No Description Found",
                                "Price": "£ x" }],

                     "Electric" : [{"Name": "Tesla Model X",
                                  "Description":"No Description Found",
                                  "Price": "£ x" }]
                    }
        }
</code>```

Desired output:

Category
Name
Description
Price

Diesel

Land Rover
No Description Found
£ x

Electric

Tesla Model X
No Description Found
£ x

答:
TL;DR - the best solution is in the end.

The most straightforward way would be to go over your data and append rows one by one:

df = pd.DataFrame(columns=['Category',  'Name', 'Description',  'Price'])
i = 0
for category, cars in data['Category'].items():
  df.loc[i, 'Category'] = category
  i += 1
  for car in cars:
    df.loc[i, ['Name',  'Description',  'Price']] = car
    i += 1
```
<p>In the end, your data frame should look like:</p>
<pre class="lang-py prettyprint-override"><code>   Category           Name           Description Price
0    Diesel            NaN                   NaN   NaN
1       NaN     Land Rover  No Description Found   £ x
2  Electric            NaN                   NaN   NaN
3       NaN  Tesla Model X  No Description Found   £ x
</code>```

Finally, just write this data frame to disk as an Excel file:

df.to_excel(...)
```
<p>By default, <code>NaN</code> cells will be empty in the Excel file, which is what you have in your example.</p>
<p>However, you can avoid loops and counters altogether by going for a pure pandas solution:</p>
<pre class="lang-py prettyprint-override"><code>pd.concat(
    df
    for category, cars in data['Category'].items()
    for df in (pd.DataFrame({'Category': [category]}), pd.DataFrame(cars)))
</code>```

Body:
I have this python dictionary and I want to write this data to an Excel file.

NOTE: there are many categories and each category has many cars (I used 2 categories for simplicity)

data = {"Category": {"Diesel" : [{
                                "Name": "Land Rover",
                                "Description":"No Description Found",
                                "Price": "£ x" }],

                     "Electric" : [{"Name": "Tesla Model X",
                                  "Description":"No Description Found",
                                  "Price": "£ x" }]
                    }
        }

Desired output:

Category
Name
Description
Price

Diesel

Land Rover
No Description Found
£ x

Electric

Tesla Model X
No Description Found
£ x

Body:
TL;DR - the best solution is in the end.

The most straightforward way would be to go over your data and append rows one by one:

df = pd.DataFrame(columns=['Category',  'Name', 'Description',  'Price'])
i = 0
for category, cars in data['Category'].items():
  df.loc[i, 'Category'] = category
  i += 1
  for car in cars:
    df.loc[i, ['Name',  'Description',  'Price']] = car
    i += 1

In the end, your data frame should look like:

   Category           Name           Description Price
0    Diesel            NaN                   NaN   NaN
1       NaN     Land Rover  No Description Found   £ x
2  Electric            NaN                   NaN   NaN
3       NaN  Tesla Model X  No Description Found   £ x

Finally, just write this data frame to disk as an Excel file:

df.to_excel(...)

By default, NaN cells will be empty in the Excel file, which is what you have in your example.

However, you can avoid loops and counters altogether by going for a pure pandas solution:

pd.concat(
    df
    for category, cars in data['Category'].items()
    for df in (pd.DataFrame({'Category': [category]}), pd.DataFrame(cars)))


问:
Solidity - Balance is zero for the deployed ERC20 contract
I'm trying to create an ERC20 token using truffle and upgradable openzeppelin contracts.
The problem is that the token balance is zero when I add the contract address into the Metamask extension.
When I use remix, Everything is Ok and I can see the correct balance of the deployed contract in the Metamask.
But I don't know where is the problem when I use it in localhost using Truffle and Ganache.

Token.sol:

```<code>pragma solidity ^0.8.2;

import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20SnapshotUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";

contract Token is
  Initializable,
  ERC20Upgradeable,
  ERC20SnapshotUpgradeable,
  OwnableUpgradeable,
  PausableUpgradeable
{
  /// @custom:oz-upgrades-unsafe-allow constructor
  constructor() initializer {}

  function initialize() public initializer {
    __ERC20_init("Token", "TKN");
    __ERC20Snapshot_init();
    __Ownable_init();
    __Pausable_init();

    _mint(msg.sender, 10000000000 * 18**decimals());
  }

  function snapshot() public onlyOwner {
    _snapshot();
  }

  function pause() public onlyOwner {
    _pause();
  }

  function unpause() public onlyOwner {
    _unpause();
  }

  function _beforeTokenTransfer(
    address from,
    address to,
    uint256 amount
  )
    internal
    override(ERC20Upgradeable, ERC20SnapshotUpgradeable)
    whenNotPaused
  {
    super._beforeTokenTransfer(from, to, amount);
  }
}
</code>```

truffle-config.js:

```<code>networks: {
    development: {
      host: "localhost",
      port: 7545,
      network_id: "*",
    },
    //  test: {
    //    host: "127.0.0.1",
    //    port: 7545,
    //    network_id: "*"
    //  }
  },
</code>```

Metamask network config:

TKN token balance:

Video:
https://youtu.be/HHWsnlJxZ7Y

答:
You must import the ganache accounts[0] to your Metamask.

When you are deploying with Remix and Metamask, deployer is your Metamask connected account, and when you are deploying initialize function being called and msg.sender is your connected account and 10000000000 token mint and transfer to that account and you can see it on your Metamask

But, when you are deploying with Truffle to your local ganache, you must get account 0 private key from ganache and import to Metamask to see that token in your wallet. If you are not provided mnemonic when running ganache, deployer(accounts[0]) in ganache every time is a newly generated address.

see this link: https://docs.nethereum.com/en/latest/ethereum-and-clients/ganache-cli/ check these flags -a accounts -m mnemonic

Body:
I'm trying to create an ERC20 token using truffle and upgradable openzeppelin contracts.
The problem is that the token balance is zero when I add the contract address into the Metamask extension.
When I use remix, Everything is Ok and I can see the correct balance of the deployed contract in the Metamask.
But I don't know where is the problem when I use it in localhost using Truffle and Ganache.

Token.sol:

pragma solidity ^0.8.2;

import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20SnapshotUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";

contract Token is
  Initializable,
  ERC20Upgradeable,
  ERC20SnapshotUpgradeable,
  OwnableUpgradeable,
  PausableUpgradeable
{
  /// @custom:oz-upgrades-unsafe-allow constructor
  constructor() initializer {}

  function initialize() public initializer {
    __ERC20_init("Token", "TKN");
    __ERC20Snapshot_init();
    __Ownable_init();
    __Pausable_init();

    _mint(msg.sender, 10000000000 * 18**decimals());
  }

  function snapshot() public onlyOwner {
    _snapshot();
  }

  function pause() public onlyOwner {
    _pause();
  }

  function unpause() public onlyOwner {
    _unpause();
  }

  function _beforeTokenTransfer(
    address from,
    address to,
    uint256 amount
  )
    internal
    override(ERC20Upgradeable, ERC20SnapshotUpgradeable)
    whenNotPaused
  {
    super._beforeTokenTransfer(from, to, amount);
  }
}

truffle-config.js:

networks: {
    development: {
      host: "localhost",
      port: 7545,
      network_id: "*",
    },
    //  test: {
    //    host: "127.0.0.1",
    //    port: 7545,
    //    network_id: "*"
    //  }
  },

Metamask network config:

TKN token balance:

Video:
https://youtu.be/HHWsnlJxZ7Y


问:
How to pass a an argument to getByText in react Testing Library?
Currently I'm doing this

```<code>getByText(/SomeText/i);
</code>```

But I want to make a function and pass some text as an argument by first storing it in a variable. I tried doing it like this:

```<code>let x = "/SomeText/i";
getByText(x);
</code>```

or

```<code>getByText(`/${x}/i`);
</code>```

But none of the options work.

答:
I had a similar scenario where I needed a variable:</p>
```<code>    const x = 'some text';
    getByText(`${x}`);
</code>```

Body:
Currently I'm doing this

getByText(/SomeText/i);

But I want to make a function and pass some text as an argument by first storing it in a variable. I tried doing it like this:

let x = "/SomeText/i";
getByText(x);

or

getByText(`/${x}/i`);

But none of the options work.

Body:
I had a similar scenario where I needed a variable:

    const x = 'some text';
    getByText(`${x}`);


问:
I keep getting a blank screen in React.JS
I was following a tutorial and my localhost is completely blank after importing {Link} from react-router-dom. Followed word for word but my local host is blank as soon as I added link in navbar.js.

```<code>import React from 'react';
import {Link} from 'react-router-dom';

function Navbar() {
    return(
        <nav class="navbar navbar-expand-lg navbar-light bg-light">
                <div class="container-fluid">

                <Link to="/" class="navbar-brand">SkyCloud</Link>

                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-togglser-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <ul class="navbar-nav ms-auto mb-2 mb-lg-0">
                    <li class="nav-item">
                        <Link to="/" class="nav-link active">Home</Link>
                    </li>

                    <li class="nav-item">
                    <Link to="/about" class="nav-link active">About</Link>
                    </li>

                    <li class="nav-item">
                    <Link to="/contact" class="nav-link active">Contact</Link>
                    </li>

                    </ul>

                </div>
                </div>
      </nav>

    );

}

export default Navbar;
</code>```

And this is my App.js file...

```<code>import React from 'react';
import Navbar from './components/inc/Navbar';
import Home from './components/pages/Home';
import About from './components/pages/About';
import Contact from './components/pages/Contact';
import {BrowserRouter as Router} from 'react-router-dom';

function App() {
  return (

    <Router>
    <div>
     <Navbar/>
    <Home/>
   <About/>
   <Contact/>

    </div>
    </Router>

  );
}

export default App;
</code>```

答:
This should solve your problem, just edit this navbar as per your need</p>
```<code>import React from "react";
import { Navbar, Nav, Container } from "react-bootstrap";
import { LinkContainer } from "react-router-bootstrap";

const Header = () => {
  return (
    <header>
      <Navbar bg='light' expand='lg'>
        <Container>
          <LinkContainer to='/'>
            <Navbar.Brand>Brand</Navbar.Brand>
          </LinkContainer>
          <Navbar.Toggle aria-controls='basic-navbar-nav' />
          <Navbar.Collapse id='basic-navbar-nav'>
            <Nav className='ml-auto'>
              <LinkContainer to='/cart'>
                <Nav.Link>
                  <i className='fas fa-shopping-cart'></i> Cart
                </Nav.Link>
              </LinkContainer>
              <LinkContainer to='/login'>
                <Nav.Link>
                  <i className='fas fa-user'></i> SignIn
                </Nav.Link>
              </LinkContainer>
            </Nav>
          </Navbar.Collapse>
        </Container>
      </Navbar>
    </header>
  );
};

export default Header;
</code>```

Body:
I was following a tutorial and my localhost is completely blank after importing {Link} from react-router-dom. Followed word for word but my local host is blank as soon as I added link in navbar.js.

import React from 'react';
import {Link} from 'react-router-dom';

function Navbar() {
    return(

                <Link to="/" class="navbar-brand">SkyCloud</Link>

                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

                </button>

                        <Link to="/" class="nav-link active">Home</Link>

                    <Link to="/about" class="nav-link active">About</Link>

                    <Link to="/contact" class="nav-link active">Contact</Link>

    );

}

export default Navbar;

And this is my App.js file...

import React from 'react';
import Navbar from './components/inc/Navbar';
import Home from './components/pages/Home';
import About from './components/pages/About';
import Contact from './components/pages/Contact';
import {BrowserRouter as Router} from 'react-router-dom';

function App() {
  return (

    <Router>

     <Navbar/>
    <Home/>
   <About/>
   <Contact/>

    </Router>

  );
}

export default App;

Body:
This should solve your problem, just edit this navbar as per your need

import React from "react";
import { Navbar, Nav, Container } from "react-bootstrap";
import { LinkContainer } from "react-router-bootstrap";

const Header = () => {
  return (
    <header>
      <Navbar bg='light' expand='lg'>
        <Container>
          <LinkContainer to='/'>
            <Navbar.Brand>Brand</Navbar.Brand>
          </LinkContainer>
          <Navbar.Toggle aria-controls='basic-navbar-nav' />
          <Navbar.Collapse id='basic-navbar-nav'>
            <Nav className='ml-auto'>
              <LinkContainer to='/cart'>
                <Nav.Link>
                  <i className='fas fa-shopping-cart'></i> Cart
                </Nav.Link>
              </LinkContainer>
              <LinkContainer to='/login'>
                <Nav.Link>
                  <i className='fas fa-user'></i> SignIn
                </Nav.Link>
              </LinkContainer>
            </Nav>
          </Navbar.Collapse>
        </Container>
      </Navbar>
    </header>
  );
};

export default Header;


问:
Diagnosing CLR errors in Windows Event Viewer
We have an .NET desktop application that crashed in production. How do we diagnose the error? I'd like to know the type of exception that occurred, the error message, and the stack trace.

Because the exception wasn't handled by our code, we received the "This application has encountered a problem and needs to close" Windows message box. The only option was to close, there was no debug button.

This MSDN article suggested looking in the Windows Event registry. I checked there, and here's the information inside it:

Faulting application Initect.Server.UI.exe,
  version 0.12.9084.90,
  time stamp 0x49cac472,
  faulting module KERNEL32.dll,
  version 6.0.6001.18000,
  time stamp 0x4791a81d,
  exception code 0xe0434f4d,
  fault offset 0x0002f35f,
  process id 0x44c,
  application start time 0x01c9ada7f320cab0

How can this information tell me the exception type, the stack trace, and the error message?

答:
That information isn't enough to get you a stack trace, exception type, error message, etc.

You can configure Windows Error Reporting (which showed you the problem & needs to close UI) on Windows Server 2008 to always collect a dump file that you can then debug.  This doesn't require you to install Visual Studio or any other debugger in your production environment.

http://blogs.technet.com/askperf/archive/2008/02/05/ws2008-windows-error-reporting.aspx shows the proper registry settings to do this.

OwnerDisplayName: Judah Himango

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Michael


问:
Bash history without line numbers
The bash history command is very cool. I understand why it shows the line numbers, but is there a way I can invoke the history command and suppress the line numbers?

The point here is to use the history command, so please don't reply cat ~/.bash_history

Current Output:

```<code>  529 man history
  530 ls
  531 ll
  532 clear
  533 cd ~
  534 histor<em>y</em></code>```

Historical graphic source.

Desired Output:

```<code>man history
ls
ll
clear
cd ~
histor<em>y</em></code>```

Historical graphic source.

Thanks to everyone for your great solutions. Paul's is the simplest and will work for me for because my bash history size is set at 2000.

I also wanted to share a cool article I found this morning. It has a couple good options that I am now using, like keeping duplicate entries out of the bash history and making sure multiple bash sessions don't overwrite the history file: http://blog.macromates.com/2008/working-with-history-in-bash/

答:
Alternatively, you could use sed:

```<code>history | sed 's/^[ ]*[0-9]\+[ ]*//'
</code>```

Using alias, you can set this as your standard (stick it in your bash_profile):

```<code>alias history="history | sed 's/^[ ]*[0-9]\+[ ]*//'"
</code>```

ContentLicense: CC BY-SA 3.0

Title: Bash history without line numbers

Body:
The bash history command is very cool. I understand why it shows the line numbers, but is there a way I can invoke the history command and suppress the line numbers?

The point here is to use the history command, so please don't reply cat ~/.bash_history

Current Output:

  529 man history
  530 ls
  531 ll
  532 clear
  533 cd ~
  534 history

Historical graphic source.

Desired Output:

man history
ls
ll
clear
cd ~
history

Historical graphic source.

Thanks to everyone for your great solutions. Paul's is the simplest and will work for me for because my bash history size is set at 2000.

I also wanted to share a cool article I found this morning. It has a couple good options that I am now using, like keeping duplicate entries out of the bash history and making sure multiple bash sessions don't overwrite the history file: http://blog.macromates.com/2008/working-with-history-in-bash/

Body:
Alternatively, you could use sed:

history | sed 's/^[ ]*[0-9]\+[ ]*//'

Using alias, you can set this as your standard (stick it in your bash_profile):

alias history="history | sed 's/^[ ]*[0-9]\+[ ]*//'"


问:
How can I return a NumPy array using FastAPI?
I have a TensorFlow Keras deep learning model in the form of an h5 file.

How can I upload an image and return a NumPy array in FastAPI?

```<code>import numpy as np
import cv2
from fastapi import FastAPI, File, UploadFile
import numpy as np
from tensorflow.keras.models import load_model
import tensorflow as tf

model=load_model("complete_model.h5")
app = FastAPI()

def prepare(image):
    IMG_SIZE = 224
    new_array = cv2.resize(image, (IMG_SIZE, IMG_SIZE))
    return new_array.reshape(-1, IMG_SIZE,IMG_SIZE,3)

@app.post("/")
async def root(file: UploadFile = File(...)):
    global model
    content = await file.read()
    nparr = np.fromstring(content, np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR).astype(np.float32)
    prediction = model.predict(prepare(img))
    return prediction
</code>```

When uploading the image using Swagger UI, I get the following error:

```<code>line 137, in jsonable_encoder
data = dict(obj)
TypeError: 'numpy.float32' object is not iterable
</code>```

Working code without FastAPI:

```<code>import numpy as np
import numpy as np
from tensorflow.keras.models import load_model
import tensorflow as tf
import cv2

model=load_model("complete_model.h5")

def prepare(image):
    IMG_SIZE = 224
    new_array = cv2.resize(image, (IMG_SIZE, IMG_SIZE))
    return new_array.reshape(-1, IMG_SIZE,IMG_SIZE,3)

img = cv2.imread("./test.jpeg").astype(np.float32)
prediction = model.predict(prepare(img))
print(prediction)
</code>```

Result in the terminal:

```<code>[[0.25442022 0.74557984]]
</code>```

How can I get the same result while using FastAPI?

答:
The error is thrown when returning the response (i.e., prediction in your case) from your endpoint. It looks like FastAPI is trying to convert the NumPy array into a dict, using the jsonable_encoder, which is used internally by FastAPI when returning a value from an endpoint, and which seems to call Python's vars() method, as shown in the error you provided here (have a look at the discussion here, as well as the documentation). Thus, what you could do is to convert the NumPy array into a Python list and then serialise it into a JSON object:

```<code>return json.dumps(prediction.tolist())
</code>```

On OpenAPI (Swagger UI), you will still be able to see the expected result. However, if you need to convert it back to a NumPy array, you can parse the JSON string as shown below.

```<code>arr = np.asarray(json.loads(resp.json()))  # resp.json() if using Python requests
</code>```

If you would like to return the NumPy array as raw bytes and display the image in the browser or download it, have a look at this answer.

Body:
I have a TensorFlow Keras deep learning model in the form of an h5 file.

How can I upload an image and return a NumPy array in FastAPI?

import numpy as np
import cv2
from fastapi import FastAPI, File, UploadFile
import numpy as np
from tensorflow.keras.models import load_model
import tensorflow as tf

model=load_model("complete_model.h5")
app = FastAPI()

def prepare(image):
    IMG_SIZE = 224
    new_array = cv2.resize(image, (IMG_SIZE, IMG_SIZE))
    return new_array.reshape(-1, IMG_SIZE,IMG_SIZE,3)

@app.post("/")
async def root(file: UploadFile = File(...)):
    global model
    content = await file.read()
    nparr = np.fromstring(content, np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR).astype(np.float32)
    prediction = model.predict(prepare(img))
    return prediction

When uploading the image using Swagger UI, I get the following error:

line 137, in jsonable_encoder
data = dict(obj)
TypeError: 'numpy.float32' object is not iterable

Working code without FastAPI:

import numpy as np
import numpy as np
from tensorflow.keras.models import load_model
import tensorflow as tf
import cv2

model=load_model("complete_model.h5")

def prepare(image):
    IMG_SIZE = 224
    new_array = cv2.resize(image, (IMG_SIZE, IMG_SIZE))
    return new_array.reshape(-1, IMG_SIZE,IMG_SIZE,3)

img = cv2.imread("./test.jpeg").astype(np.float32)
prediction = model.predict(prepare(img))
print(prediction)

Result in the terminal:

[[0.25442022 0.74557984]]

How can I get the same result while using FastAPI?

Body:
The error is thrown when returning the response (i.e., prediction in your case) from your endpoint. It looks like FastAPI is trying to convert the NumPy array into a dict, using the jsonable_encoder, which is used internally by FastAPI when returning a value from an endpoint, and which seems to call Python's vars() method, as shown in the error you provided here (have a look at the discussion here, as well as the documentation). Thus, what you could do is to convert the NumPy array into a Python list and then serialise it into a JSON object:

return json.dumps(prediction.tolist())

On OpenAPI (Swagger UI), you will still be able to see the expected result. However, if you need to convert it back to a NumPy array, you can parse the JSON string as shown below.

arr = np.asarray(json.loads(resp.json()))  # resp.json() if using Python requests

If you would like to return the NumPy array as raw bytes and display the image in the browser or download it, have a look at this answer.


问:
Unable to run Intel HAXM installer: Cannot start process, the working directory does not exist
How to resolve this error which I am getting while installing HAXM installer.

Unable to run Intel HAXM installer: Cannot start process, the working directory
'C:\Users\surabhi\AppData\Local\Android\Sdk\extras\intel\Hardware_Accelarated_Execution_Manager does not exist.

I also tried to download HAXM installer directly from Intel's website but couldn't succeed and I have also tried enabling and disabling Hyper-V.

答:
My tiny contribution: I had the same problem, I then tried to install from the SDK tools, it said it was installed and when I tried to run the emulator it said that HAXM was missing. At least from the SDK tools, the folder was created. Tried to install it many times with no success. Then I went to the folder indicated (...\AppData\Local\Android\Sdk\extras\intel\Hardware_Accelarated_Execution_Manager) and ran the installer manually and it worked.

In case this may help anyone


问:
How to build a Seurat container?
I'm trying to analyze single-cell RNAseq data by Seurat.

Recently I encountered Docker ecosystem seemingly very reproducible. I tried three manners, but all failed. Do you have any idea or good information??

Enviroment:

PC: Surface Laptop2

OS: Windows10 + WSL2

Docker: Docker desktop for Windows

DockerImages: rocker/rstudio, satijalab/seurat

1. Build rocker/tidyverse container installing Seurat package by installer2.r command.

This is a Dockerfile.

```<code>FROM rocker/tidyverse
RUN apt update

# install Seurat package via a install2.r liner
RUN install2.r Seurat --error --deps TRUE --skipinstalled --ncpus -1
</code>```

This is a Docker-compse file.

```<code>version: '3'
services:
  rocker:
    build:
      context: .
      dockerfile: ./Dockerfile
    container_name: rocker
    hostname: rocker
    ports:
      - '8787:8787'
    environment:
      - PASSWORD=pass
</code>```

But

```<code>Docker-compose up --build
</code>```

returns errors. In summary, "installation of one or more packages failed, probably ‘Cairo’, ‘mutoss’, ‘ggrastr’, ‘metap’."

2. Build Seurat container installing RStudio-server.

This is a Dockerfile.

```<code>FROM satijalab/seurat:latest
RUN apt update

# install prerequisites
RUN apt install -y \
  ca-certificates \
  libssl-dev \
  libcurl4-openssl-dev \
  libxml2-dev \
  libssh2-1-dev

# install rstudio-server for Ubntu20
RUN wget https://download2.rstudio.org/server/debian9/x86_64/rstudio-server-2021.09.2-382-amd64.deb
RUN apt install -y ./rstudio-server-2021.09.2-382-amd64.deb
RUN rm rstudio-server-2021.09.2-382-amd64.deb
</code>```

This is a Docker-compse file.

```<code>version: '3'
services:
  seurat:
    build:
      context: .
      dockerfile: ./Dockerfile
  container_name: seurat
  hostname: seurat
  ports:
    - '0.0.0.0:8787:8787'
  environment:
    - PASSWORD=pass
  tty: true
  stdin_open: true
</code>```

It created a container successfully. Then I accessed "http://localhost:8787/", it returned "ERR_EMPTY_RESPONSE." I suspected that rstudio-server didn't run.

```<code>docker exec  -it  seurat bash
</code>```

Then

```<code>rstudio-server start
</code>```

It returned "/usr/lib/rstudio-server/bin/rserver: error while loading shared libraries: libssl.so.1.0.2: cannot open shared object file: No such file or directory."

It seemed that libssl package version error occured. I changed docker-compse file from,

```<code>RUN apt install -y libssl-dev
</code>```

to,

```<code>RUN apt install -y libssl1.0.2
</code>```

but it returned no package found error.

3. Build rocker/tidyverse container. Log in to RStudio-server. install.packages("Seurat").

Simply I could build and log-in to a rocker/tidyverse container by accessing to localhost:8787.

Then I tried to install Seurat package by

```<code>install.packages("Seurat")
</code>```

At first glance it seemed install was successfully done. But

```<code>version: '3'
services:
  rocker:
    build:
      context: .
      dockerfile: ./Dockerfile
    container_name: rocker
    hostname: rocker
    ports:
      - '8787:8787'
    environment:
      - PASSWORD=pass
</code>```0

returned,

```<code>version: '3'
services:
  rocker:
    build:
      context: .
      dockerfile: ./Dockerfile
    container_name: rocker
    hostname: rocker
    ports:
      - '8787:8787'
    environment:
      - PASSWORD=pass
</code>```1

答: Satija Lab already builds Docker containers with Rocker+Seurat, so if you are only learning Docker, it would be better to use their images. Otherwise, their Dockerfiles are available on GitHub.</p>

Title: How to build a Seurat container?

Body:
I'm trying to analyze single-cell RNAseq data by Seurat.

Recently I encountered Docker ecosystem seemingly very reproducible. I tried three manners, but all failed. Do you have any idea or good information??

Enviroment:

PC: Surface Laptop2

OS: Windows10 + WSL2

Docker: Docker desktop for Windows

DockerImages: rocker/rstudio, satijalab/seurat

1. Build rocker/tidyverse container installing Seurat package by installer2.r command.

This is a Dockerfile.

FROM rocker/tidyverse
RUN apt update

# install Seurat package via a install2.r liner
RUN install2.r Seurat --error --deps TRUE --skipinstalled --ncpus -1

This is a Docker-compse file.

version: '3'
services:
  rocker:
    build:
      context: .
      dockerfile: ./Dockerfile
    container_name: rocker
    hostname: rocker
    ports:
      - '8787:8787'
    environment:
      - PASSWORD=pass

But

Docker-compose up --build

returns errors. In summary, "installation of one or more packages failed, probably ‘Cairo’, ‘mutoss’, ‘ggrastr’, ‘metap’."

2. Build Seurat container installing RStudio-server.

This is a Dockerfile.

FROM satijalab/seurat:latest
RUN apt update

# install prerequisites
RUN apt install -y \
  ca-certificates \
  libssl-dev \
  libcurl4-openssl-dev \
  libxml2-dev \
  libssh2-1-dev

# install rstudio-server for Ubntu20
RUN wget https://download2.rstudio.org/server/debian9/x86_64/rstudio-server-2021.09.2-382-amd64.deb
RUN apt install -y ./rstudio-server-2021.09.2-382-amd64.deb
RUN rm rstudio-server-2021.09.2-382-amd64.deb

This is a Docker-compse file.

version: '3'
services:
  seurat:
    build:
      context: .
      dockerfile: ./Dockerfile
  container_name: seurat
  hostname: seurat
  ports:
    - '0.0.0.0:8787:8787'
  environment:
    - PASSWORD=pass
  tty: true
  stdin_open: true

It created a container successfully. Then I accessed "http://localhost:8787/", it returned "ERR_EMPTY_RESPONSE." I suspected that rstudio-server didn't run.

docker exec  -it  seurat bash

Then

rstudio-server start

It returned "/usr/lib/rstudio-server/bin/rserver: error while loading shared libraries: libssl.so.1.0.2: cannot open shared object file: No such file or directory."

It seemed that libssl package version error occured. I changed docker-compse file from,

RUN apt install -y libssl-dev

to,

RUN apt install -y libssl1.0.2

but it returned no package found error.

3. Build rocker/tidyverse container. Log in to RStudio-server. install.packages("Seurat").

Simply I could build and log-in to a rocker/tidyverse container by accessing to localhost:8787.

Then I tried to install Seurat package by

install.packages("Seurat")

At first glance it seemed install was successfully done. But

library(Seurat)

returned,

Error: package or namespace load failed for ‘Seurat’ in dyn.load(file, DLLpath = DLLpath, ...):
 unable to load shared object '/home/rstudio/R/x86_64-pc-linux-gnu-library/4.1/igraph/libs/igraph.so':
  libglpk.so.40: cannot open shared object file: No such file or directory


问:
How to create a Website for Solana tokens transfer
I am trying to build a website using reactjs with the following goal :

Transfer Solana and tokens that are on the solana Blockchain

I took a look on the documentation that solana provides but it was kinda hard for me to understand anything because Blockchain and reactjs are still something new for me .
So the thing is :

Can Anyone help me by providing some simplified steps on how to integrate the solana
Blockchain into my website and be able to transfer some coins ?

Any help will be appreciated and thank you in advance !

答:
Here's what you will need:

A solana client library(you will need this to make rpc calls), hopefully one exists

A way to enable user to interact with your website through a browser extension like metamask. That provides wallet for your users

That's how most Web3 currently works. A client library on that enables to taking to the blockchain on the browser with User wallets integration(provided in the form of a browser extension)


问:
Comparing if an element in a dictionary is greater than a variable
I am new to Python and have just recently learnt what dictionaries are and was experimenting with some code.

```<code>import random
random_number= random.randint(0,100)
print(random_number)

scores = {89: 'Grade 9', 79: 'Grade 8', 69: 'Grade 7', 59: 'Grade 6', 49: 'Grade 5', 39: 'Grade 4', 29: 'Grade 3','Grade 2': 19,'Grade 1': 9,}

def if_random_number(score):
    if random_number > scores[]:
        print('\nYou are grade {}'.format(score, scores.get(item, 'invalid')))
</code>```

I am trying to make it compare if the random_number is greater than the elements in the list scores it, will print out your grade.

Since I'm new to coding and honestly suck I need some help

答:
Here's a rework of your code that I think does what you're looking for:

```<code>import random
random_number= random.randint(0,100)

scores = {89: 'Grade 9', 79: 'Grade 8', 69: 'Grade 7', 59: 'Grade 6', 49: 'Grade 5', 39: 'Grade 4', 29: 'Grade 3', 19: 'Grade 2',  9: 'Grade 1'}

def if_random_number(random_score):
    for score, grade in scores.items():
        if random_score >= score:
            print('\nYour score of {} is grade {}'.format(score, grade))
            break
    else:
        print('\nYou suck')

if_random_number(random_number)
</code>```

Sample results:

```<code>Your score of 9 is grade Grade 1

Your score of 79 is grade Grade 8
</code>```

You iterate over your 'scores' dictionary looking for the first entry where the key (the score) is less than the random number you computed.  The else clause is a more advanced trick where you can do something if in a for loop, your test never succeeded and so you never called break to break out of the loop.  Since your random number can be less than all keys in scores (can be < 9), you need this else clause to be sure that you always print something.

Body:
I am new to Python and have just recently learnt what dictionaries are and was experimenting with some code.

import random
random_number= random.randint(0,100)
print(random_number)

scores = {89: 'Grade 9', 79: 'Grade 8', 69: 'Grade 7', 59: 'Grade 6', 49: 'Grade 5', 39: 'Grade 4', 29: 'Grade 3','Grade 2': 19,'Grade 1': 9,}

def if_random_number(score):
    if random_number > scores[]:
        print('\nYou are grade {}'.format(score, scores.get(item, 'invalid')))

I am trying to make it compare if the random_number is greater than the elements in the list scores it, will print out your grade.

Since I'm new to coding and honestly suck I need some help

Body:
Here's a rework of your code that I think does what you're looking for:

import random
random_number= random.randint(0,100)

scores = {89: 'Grade 9', 79: 'Grade 8', 69: 'Grade 7', 59: 'Grade 6', 49: 'Grade 5', 39: 'Grade 4', 29: 'Grade 3', 19: 'Grade 2',  9: 'Grade 1'}

def if_random_number(random_score):
    for score, grade in scores.items():
        if random_score >= score:
            print('\nYour score of {} is grade {}'.format(score, grade))
            break
    else:
        print('\nYou suck')

if_random_number(random_number)

Sample results:

Your score of 9 is grade Grade 1

Your score of 79 is grade Grade 8

You iterate over your 'scores' dictionary looking for the first entry where the key (the score) is less than the random number you computed.  The else clause is a more advanced trick where you can do something if in a for loop, your test never succeeded and so you never called break to break out of the loop.  Since your random number can be less than all keys in scores (can be < 9), you need this else clause to be sure that you always print something.


问:
Simple code looping not working when method called via ASP.NET web method
Any loops or iterations aren't working when I execute the code via a WebMethod. If I run the same code normally there is no problem. Basically, the top line of the for loop is executed then anything within the curly braces ignored. Any code below will be executed. I've tried with a foreach loop and the result is the same. This is very strange behavior and I have no idea what is causing it, any help is appreciated!</p>

```<code>[WebMethod]
public static void MyPageMethod()
{

  string str = string.Empty;

  string valueWillNotChange = string.Empty;

  for (int i = 0; i < 4; i++)
  {

    str += i.ToString();

    // anything here or below will not get executed ...
    valueWillNotChange = str;

  }

}
</code>```

答:
Put your code in a stand alone unit test and validate it works at all.

As @John Saunders said, it's your code that doesn't work.

Body:
Any loops or iterations aren't working when I execute the code via a WebMethod. If I run the same code normally there is no problem. Basically, the top line of the for loop is executed then anything within the curly braces ignored. Any code below will be executed. I've tried with a foreach loop and the result is the same. This is very strange behavior and I have no idea what is causing it, any help is appreciated!

[WebMethod]
public static void MyPageMethod()
{

  string str = string.Empty;

  string valueWillNotChange = string.Empty;

  for (int i = 0; i < 4; i++)
  {

    str += i.ToString();

    // anything here or below will not get executed ...
    valueWillNotChange = str;

  }

}


答:
In Python you can iterate over dicts this way:

```<code>for key, value in dictionary.items():
    # Here you have the keys as key and values as value
</code>```

In your case:

```<code>for score in scores.keys():
    if (score >= random_number):
        print(scores[score])
</code>```

or otherwise

```<code>for score, mark in scores.items():
    if (score >= random_number):
        print(mark)
</code>```

You can also do it with list comprehension:

```<code>[print(value) for key, value in scores.items() if key >= random_number]
</code>```

Title: Comparing if an element in a dictionary is greater than a variable

Body:
In Python you can iterate over dicts this way:

for key, value in dictionary.items():
    # Here you have the keys as key and values as value

In your case:

for score in scores.keys():
    if (score >= random_number):
        print(scores[score])

or otherwise

for score, mark in scores.items():
    if (score >= random_number):
        print(mark)

You can also do it with list comprehension:

[print(value) for key, value in scores.items() if key >= random_number]


问:
Docker postgresql container IP address changes whenever it restarts

$ docker run -d \
    --name some-postgres \
    -e POSTGRES_USER=postgres \
    -e POSTGRES_PASSWORD=mysecretpassword \
    -p 5432:5432 \
    postgres
```
<p>I build postgresql container like above. Then when try to access Postgresql server. I always set the IP address like this in Python with Flask-SQLAlchemy:</p>
<pre class="lang-py prettyprint-override"><code>app.config['SQLALCHEMY_DATABASE_URI'] = postgresql://postgres:securepass@host.docker.internal:5432/some_db_name'
</code>```

instead of writing "host.docker.internal" can I set the IP address as static one?

答:
You can also choose the IP addresses for the container with --ip and --ip6 flags when you start the container on a user-defined network. See Connect a container to a network

Example:

```<code>$ docker run -itd --network=my-net --ip=10.10.9.75 busybox
</code>```

If you never created a docker network, also check out docker network create.

Body:
$ docker run -d \
    --name some-postgres \
    -e POSTGRES_USER=postgres \
    -e POSTGRES_PASSWORD=mysecretpassword \
    -p 5432:5432 \
    postgres

I build postgresql container like above. Then when try to access Postgresql server. I always set the IP address like this in Python with Flask-SQLAlchemy:

app.config['SQLALCHEMY_DATABASE_URI'] = postgresql://postgres:securepass@host.docker.internal:5432/some_db_name'

instead of writing "host.docker.internal" can I set the IP address as static one?

Body:
You can also choose the IP addresses for the container with --ip and --ip6 flags when you start the container on a user-defined network. See Connect a container to a network

Example:

$ docker run -itd --network=my-net --ip=10.10.9.75 busybox

If you never created a docker network, also check out docker network create.


问:
extract bit in Ruby Integers
I need to get the n-th bit of an Integer, either signed or unsigned, in Ruby.

```<code>x = 123 # that is 1111011
n = 2   # bit 2 is ...0
</code>```

The following piece of code doesn't work in the general case:

```<code>x.to_s(2)[-(n+1)] #0 good! but...
</code>```

because of negative numbers not represented as 2-complement:

```<code>-123.to_s(2) # "-1111011"
</code>```

So how to proceed?

Title: extract bit in Ruby Integers

Body:
I need to get the n-th bit of an Integer, either signed or unsigned, in Ruby.

x = 123 # that is 1111011
n = 2   # bit 2 is ...0

The following piece of code doesn't work in the general case:

x.to_s(2)[-(n+1)] #0 good! but...

because of negative numbers not represented as 2-complement:

-123.to_s(2) # "-1111011"

So how to proceed?

Body:
def f x, bit
  (x & 1 << bit) > 0 ? 1 : 0
end


答:
just fix the action

```<code> [HttpGet("~/api/hqdataahs/GetData")]
  //or just
 [HttpGet("GetData")]
 public JsonResult Get(string date, int num, int statNum)
{
    string query = $"CALL Get_Discharge_Station('{date}', {num}, {statNum});";
    .....
</code>```

and carefully read all comments below about sql injection.

you url should be

```<code>https://.../api/hqdataahs/GetData?date=2022-02-02&num=6&statNum=11800
</code>```

or change route

```<code> [HttpGet("~/api/hqdataahs/GetData/{date}/{num}/{statNum}")]
  //or just
 [HttpGet("GetData/{date}/{num}/{statNum}")]
[HttpGet("~api/hqdataahs/GetData
 public JsonResult Get(string date, int num, int statNum)
</code>```

in this case you url should be

```<code>https://.../api/hqdataahs/GetData/2022-02-02/6/11800
</code>```

Title: How to pass three parameters to url address using ASP.NET Core Web API

Body:
For now I have a procedure I wish to call:

CALL Get_Discharge_Station('2022-02-02', 6, 11800);

I want to pass these three parameters - 2022-02-02,6,11800 to url address, when I enter different date,number and number of station to get different data.

For now my API controller look like this:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;

namespace WebAPI.Controllers
{
    [Route("api/hqdataahs")]
    [ApiController]
    public class HQ_data_AHSController : ControllerBase
    {
        private readonly IConfiguration _configuration;

        public HQ_data_AHSController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        [HttpGet]
        public JsonResult Get()
        {
            string query = @"CALL Get_Discharge_Station('2022-02-02', 6, 11800);";

            DataTable table = new DataTable();

            string sqlDataSource = _configuration.GetConnectionString("AppCon");

            MySqlDataReader myReader;

            using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
            {
                mycon.Open();

                using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
                {
                    myReader = myCommand.ExecuteReader();
                    table.Load(myReader);

                    myReader.Close();
                    mycon.Close();
                }
            }

            return new JsonResult(table);
        }
    }
}

What can I change to pass there three parameters in url address when I access the controller?`

Body:
just fix the action

 [HttpGet("~/api/hqdataahs/GetData")]
  //or just
 [HttpGet("GetData")]
 public JsonResult Get(string date, int num, int statNum)
{
    string query = $"CALL Get_Discharge_Station('{date}', {num}, {statNum});";
    .....

and carefully read all comments below about sql injection.

you url should be

https://.../api/hqdataahs/GetData?date=2022-02-02&num=6&statNum=11800

or change route

 [HttpGet("~/api/hqdataahs/GetData/{date}/{num}/{statNum}")]
  //or just
 [HttpGet("GetData/{date}/{num}/{statNum}")]
[HttpGet("~api/hqdataahs/GetData
 public JsonResult Get(string date, int num, int statNum)

in this case you url should be

https://.../api/hqdataahs/GetData/2022-02-02/6/11800


问:
Generate App with multi language support with Tuist
my app, which i am setting up with tuist, is supposed to support localization.
how can I configure this in the tuist project?</p>

答:
In your Resources folder for the target, you can create multiple folders with the locale name like this:

Resources/

Base.lproj/

Localizable.strings

da.lproj/

Localizable.strings

pl.lproj/

Localizable.strings

When setting up your target in the Project.swift file in Tuist, you specify the resources path like .., resources: "Resources/**"... Tuist will then make sure the Xcode project is generated with the proper languages set up.


问:
redirecting to thankyou.aspx page after survey
I am trying to direct after user click on "Finish" on a sharepoint survey. But the following code executes when user click on "Respond to this survey". Any idea what is happening.</p>

```<code><script type="text/javascript">
function redirect()
{
  var inputcCtrls = document.getElementsByTagName("input");
  for(var m=0; m<inputcCtrls.length; m++)
   if(inputcCtrls[m].type=='button'&&inputcCtrls[m].value=='Finish')
     var funcOnClick = inputcCtrls[m].onclick;
         inputcCtrls[m].onclick = window.location = "http://www.google.com/";
}
redirect();
</script>
</code>```

答:
I don't know about javascript, but in c# the code block

```<code>var funcOnClick = inputcCtrls[m].onclick;
inputcCtrls[m].onclick = window.location = "http://www.google.com/";
</code>```

would need to be in parenthesis as the if statement only applies to the next line of code, so the following would work

```<code>if(inputcCtrls[m].type=='button'&&inputcCtrls[m].value=='Finish')
{
     var funcOnClick = inputcCtrls[m].onclick;
         inputcCtrls[m].onclick = window.location = "http://www.google.com/";
}
</code>```

Body:
I don't know about javascript, but in c# the code block

var funcOnClick = inputcCtrls[m].onclick;
inputcCtrls[m].onclick = window.location = "http://www.google.com/";

would need to be in parenthesis as the if statement only applies to the next line of code, so the following would work

if(inputcCtrls[m].type=='button'&&inputcCtrls[m].value=='Finish')
{
     var funcOnClick = inputcCtrls[m].onclick;
         inputcCtrls[m].onclick = window.location = "http://www.google.com/";
}


问:
How do I add two integers together from a csv file in c code?
I'll make this short. I really want to learn from the answer. I am not here to make anyone code for me, so you choose if you want to learn me how to solve this problem or simply write the whole code.

I am trying to make a script which can read a CSV with this pattern:
DATE,TEXT,EXPENSE or INCOME,BALANCE,STATUS,DENIED.
Example: 11.01.2011,Grocery shop, -200, 700, Done, No.

I want the output to be the sum of all the expenses and income and second output what the balance is. I would like this info to be stored somewhere in the CSV file, so when I open it with excel it's there.

If you are able to explain what each line does it would be great for me so I can learn as a coding noob, but if not that's all good.

If this question is already answered I am so sorry. I have tried for a couple hours to find a answer, but I have only gotten some code that I don't know how to modify to what I want to do.

答:
For any problem like this, I prefer to do it as a loop, structured in several parts:

read lines of text

when there are no more lines, we're done

for each line, break it into a number of fields

finally, do something interesting with the fields

The basic C function for step 1 is the fgets function.  It's customery to bundle step 1 and step 2 together in the header of a while loop:

```<code>char linebuf[100];
while(fgets(linebuf, sizeof(linebuf), infp) != NULL) {
    step 3; step 4;
}
</code>```

Now, in the body of the loop, we have a line of text linebuf we've just read, and it's time to break it up into fields, in this case by searching for comma characters as delimiters.  One way to do this sort of thing is using the library function strtok.  Another is described in this chapter of some programming notes.

For files with columns of data, I like to store the broken-out fields in an array of pointers:

```<code>char *fields[MAXCOLS];
</code>```

So then, you can use ordinary string operations to do interesting things with the columns (remembering that arrays in C are 0-based).

For example, to see if column 3 is the word "yes" or something else:

```<code>if(strcmp(fields[2], "yes") == 0) {
     /* column 3 was "yes" */ ;
} else {
     /* column 3 was something else */ ;
}
</code>```

If column 5 was an amount, convert it to a number so you can do something with it:

```<code>double amount, running_total;

/* ... */

amount = atof(4);
running_total += amount;
</code>```

(But beware: types float or double are not always good for dealing with monetary amounts, due to roundoff issues.)

Body:
For any problem like this, I prefer to do it as a loop, structured in several parts:

read lines of text

when there are no more lines, we're done

for each line, break it into a number of fields

finally, do something interesting with the fields

The basic C function for step 1 is the fgets function.  It's customery to bundle step 1 and step 2 together in the header of a while loop:

char linebuf[100];
while(fgets(linebuf, sizeof(linebuf), infp) != NULL) {
    step 3; step 4;
}

Now, in the body of the loop, we have a line of text linebuf we've just read, and it's time to break it up into fields, in this case by searching for comma characters as delimiters.  One way to do this sort of thing is using the library function strtok.  Another is described in this chapter of some programming notes.

For files with columns of data, I like to store the broken-out fields in an array of pointers:

char *fields[MAXCOLS];

So then, you can use ordinary string operations to do interesting things with the columns (remembering that arrays in C are 0-based).

For example, to see if column 3 is the word "yes" or something else:

if(strcmp(fields[2], "yes") == 0) {
     /* column 3 was "yes" */ ;
} else {
     /* column 3 was something else */ ;
}

If column 5 was an amount, convert it to a number so you can do something with it:

double amount, running_total;

/* ... */

amount = atof(4);
running_total += amount;

(But beware: types float or double are not always good for dealing with monetary amounts, due to roundoff issues.)


问:
Display an image on top of another CSS using hover
I'm trying to add some hover effects to my landing page and i'm stuck at doing the hover effect at the image, the hover in the title and author I was able to do easily.

I tried some stuff but I still couldn't do, the solutions that I saw here on stackoverflow was using position: absolute, but I was looking for some other solution (if there is).

If the main solution is using position: absolute and you want to please help me understand, I find very difficult to understand and use position: absolute.

Here's how my page look like right now

:root {
    --soft-blue: hsl(215, 51%, 70%);
    --cyan: hsl(178, 100%, 50%);
    --main-bg: hsl(217, 54%, 11%);
    --card-bg: hsl(216, 50%, 16%);
    --line: hsl(215, 32%, 27%);
    --white: hsl(0, 0%, 100%);
    --font-size: 18px;
    --font: 'Outfit', sans-serif;
}

body {
    margin: 0;
    font-family: var(--font);
}

.page {
    display: flex;
    height: 100vh;
    background-color: var(--main-bg);
    justify-content: center;
    align-items: center;
}

.page__container {
    box-sizing: border-box;
    padding: 20px 20px 0px 20px;
    background-color: var(--card-bg);
    width: 400px;
    height: 650px;
    border-radius: 20px;
}

.page__container img {
    margin: 0;
    max-width: 100%;
    max-height: 100%;
    border-radius: 10px;
}

.page__container h1 {
    color: var(--white);
    font-size: 26px;
    margin: 15px 0 10px;
}

.page__container h1 a {
    color: var(--white);
    text-decoration: none;
}

.page__container .description {
    margin: 0;
    font-weight: 400;
    color: var(--soft-blue);
    font-size: 20px;
}

.price-deadline {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.eth {
    display: flex;
    align-items: center;
}

.eth .eth-icon {
    max-height: 18px;
    max-width: 11px;
    margin-right: 5px;
}

.eth .eth-price {
    color: var(--cyan);
}

.deadline {
    display: flex;
    align-items: center;
}

.deadline .clock-icon {
    max-width: 17px;
    max-height: 17px;
    margin-right: 5px;
}

.deadline .due-date {
    font-weight: 600;
    color: var(--soft-blue);
}

.divisor {
    height: 1px;
    background-color: var(--soft-blue);
    border: none;
}

.author {
    display: flex;
    align-items: center;
    padding-top: 10px;
}

.author .avatar {
    border: 1px solid white;
    border-radius: 50px;
    max-height: 40px;
    max-width: 40px;
    margin-right: 10px;
}

.author .credits {
    color: var(--soft-blue);
}

.author a {
    font-size: 16px;
    color: var(--white);
    text-decoration: none;
}

/* Hover Section */

.author a:hover {
    color: var(--cyan);
}

.text h1 .link:hover {
    color: var(--cyan);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600&display=swap" rel="stylesheet">
    <link rel="shortcut icon" href="./images/favicon-32x32.png" type="image/x-icon">
    <title>NFT Preview Card</title>
</head>
<body>
    <div class="page">
        <div class="page__container">
            <img src="./images/image-equilibrium.jpg" alt="" class="equilibrium">

            </p>
            <div class="text">
                <h1>Equilibrium #3429</h1>
                <p class="description">
                    Our Equilibrium collection promotes
                    balance and calm.
                </p>
                <div class="price-deadline">
                    <div class="eth">
                        <img src="./images/icon-ethereum.svg" alt="" class="eth-icon">
                        <p class="eth-price">0.041 ETH</p>
                    </div>
                    <div class="deadline">
                        <img src="./images/icon-clock.svg" alt="" class="clock-icon">
                        <p class="due-date">3 days left</p>
                    </div>
                </div>
            </div>
            <hr class="divisor">
            <div class="author">
                <img src="./images/image-avatar.png" alt="" class="avatar">
                <p class="credits">
                    Creation of Jules Wyvern
                </p>
            </div>
        </div>
    </div>
</body>
</html></code>```

答:
i cannot think of another way without position: absolute
but i have created you an example where the the image is positioned automatically on the center using flex box https://jsfiddle.net/r5Lfcbh8/2/

Edit i use position relative on the parent div as relative make the children absolute top left 0 same as relative.

```<code><div class="overlayPar">
    <img src="https://media.marketrealist.com/brand-img/LyxvUFSpl/0x0/nft-black-1617613285599.jpg" alt="" class="equilibrium">
    <div class="imgOverlay">
        <span class="eye"></span>
    </div>
</div>

.overlayPar {
  position: relative;
}

.imgOverlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 255, 247, .4);
  display: none;
}

.imgOverlay .eye {
  background: white;
  width: 25px;
  height: 25px;
  display: block;
  margin: auto;
}

.overlayPar:hover .imgOverlay  {
  display: flex;
}

.equilibrium {
  display: block;
}
</code>```

Body:
I'm trying to add some hover effects to my landing page and i'm stuck at doing the hover effect at the image, the hover in the title and author I was able to do easily.

I tried some stuff but I still couldn't do, the solutions that I saw here on stackoverflow was using position: absolute, but I was looking for some other solution (if there is).

If the main solution is using position: absolute and you want to please help me understand, I find very difficult to understand and use position: absolute.

Here's how my page look like right now

:root {
    --soft-blue: hsl(215, 51%, 70%);
    --cyan: hsl(178, 100%, 50%);
    --main-bg: hsl(217, 54%, 11%);
    --card-bg: hsl(216, 50%, 16%);
    --line: hsl(215, 32%, 27%);
    --white: hsl(0, 0%, 100%);
    --font-size: 18px;
    --font: 'Outfit', sans-serif;
}

body {
    margin: 0;
    font-family: var(--font);
}

.page {
    display: flex;
    height: 100vh;
    background-color: var(--main-bg);
    justify-content: center;
    align-items: center;
}

.page__container {
    box-sizing: border-box;
    padding: 20px 20px 0px 20px;
    background-color: var(--card-bg);
    width: 400px;
    height: 650px;
    border-radius: 20px;
}

.page__container img {
    margin: 0;
    max-width: 100%;
    max-height: 100%;
    border-radius: 10px;
}

.page__container h1 {
    color: var(--white);
    font-size: 26px;
    margin: 15px 0 10px;
}

.page__container h1 a {
    color: var(--white);
    text-decoration: none;
}

.page__container .description {
    margin: 0;
    font-weight: 400;
    color: var(--soft-blue);
    font-size: 20px;
}

.price-deadline {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.eth {
    display: flex;
    align-items: center;
}

.eth .eth-icon {
    max-height: 18px;
    max-width: 11px;
    margin-right: 5px;
}

.eth .eth-price {
    color: var(--cyan);
}

.deadline {
    display: flex;
    align-items: center;
}

.deadline .clock-icon {
    max-width: 17px;
    max-height: 17px;
    margin-right: 5px;
}

.deadline .due-date {
    font-weight: 600;
    color: var(--soft-blue);
}

.divisor {
    height: 1px;
    background-color: var(--soft-blue);
    border: none;
}

.author {
    display: flex;
    align-items: center;
    padding-top: 10px;
}

.author .avatar {
    border: 1px solid white;
    border-radius: 50px;
    max-height: 40px;
    max-width: 40px;
    margin-right: 10px;
}

.author .credits {
    color: var(--soft-blue);
}

.author a {
    font-size: 16px;
    color: var(--white);
    text-decoration: none;
}

/* Hover Section */

.author a:hover {
    color: var(--cyan);
}

.text h1 .link:hover {
    color: var(--cyan);
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600&display=swap" rel="stylesheet">
    <link rel="shortcut icon" href="./images/favicon-32x32.png" type="image/x-icon">
    <title>NFT Preview Card</title>

Equilibrium #3429

                    Our Equilibrium collection promotes
                    balance and calm.

0.041 ETH

3 days left

                    Creation of Jules Wyvern

Body:
i cannot think of another way without position: absolute
but i have created you an example where the the image is positioned automatically on the center using flex box https://jsfiddle.net/r5Lfcbh8/2/

Edit i use position relative on the parent div as relative make the children absolute top left 0 same as relative.

<div class="overlayPar">
    <img src="https://media.marketrealist.com/brand-img/LyxvUFSpl/0x0/nft-black-1617613285599.jpg" alt="" class="equilibrium">
    <div class="imgOverlay">
        <span class="eye"></span>
    </div>
</div>

.overlayPar {
  position: relative;
}

.imgOverlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 255, 247, .4);
  display: none;
}

.imgOverlay .eye {
  background: white;
  width: 25px;
  height: 25px;
  display: block;
  margin: auto;
}

.overlayPar:hover .imgOverlay  {
  display: flex;
}

.equilibrium {
  display: block;
}


问:
Remove duplicates from array in linear time and without extra arrays
We have an array and it is unsorted. We know the range is [0,n].

We want to remove duplicates but we cannot use extra arrays and it must run in linear time.

Any ideas? Just to clarify, this is not for homework!

答: Use the array a a container with negative sign as an indicator, this will corrupt the input though.</p>


问:
how does spfx get builded? how to build custom spfx generator
I am learning spfx webpart. I open the gulpfile.js file but it only has limited code lines. how can I know the procedure of building spfx webpart?

And I notice that there is a PNP spfx generator. is it possible to create my own custom spfx generator? or involve spfx into my node project?

thanks

答:
SPFx projects are built using a complex Build System that is an npm package. You can find it under node_modules folder under the name - @microsoft/sp-build-web

This package makes use of more packages. You can go into the node_moduels folder and look for packages named @microsoft/gulp-core-build*

The entire build system is built in Object oriented code with lots of classes and interfaces using TypeScript.

If you want to just customize the Build process then you can build custom tasks which are coded in the gulpfile.js.

On good article to learn is at - https://rencore.com/blog/extending-sharepoint-framework-build-process-custom-tasks/


问:
Linking to different areas on a page
This may seem like a stupid question, but:

So what i would like to do is set up a menu section so that when the user clicked on the title of the section it would send them to that particular spot on the page with out having to scoll down. I am not entirely sure how this would work or how complicated it is to achieve.

So bacially i would have

Menu

item one (be a link)

item two (be a link)

etc (be a link)

then further down the page

item one (when item one in menu is clicked page comes to here)

"details about it here"

item two (when item two in menu is clicked page comes to here)

"details here"

How exactly would i go about doing this?

Any help or suggestions are greatly appreciated. Thanks.

答:
Its called an anchor tag and you can combine this with a # to get the desired results asked in the question.

Just put:

at the beginning of section1

The next step is to then wherever you want to link to it, just add:

here

Please note that you can also point to an ID within an element using the method above to achieve the results.

For example:

```<code><div id="section1"></div>
</code>```

This will help you, if you have any other questions regarding this let me know.

Title: Linking to different areas on a page

Body:
Its called an anchor tag and you can combine this with a # to get the desired results asked in the question.

Just put:

<a name="section1"></a>

at the beginning of section1

The next step is to then wherever you want to link to it, just add:

<a href="#section1">here</a>

Please note that you can also point to an ID within an element using the method above to achieve the results.

For example:

<div id="section1"></div>

This will help you, if you have any other questions regarding this let me know.


问:
Read out file and convert certain line into a correct form
I have a problem. I am reading in a file.
This file contains abbreviations. However, I only want to read the abbreviations. This also works. However, not in the desired format as expected, I would like to save the abbreviations cleanly per line (see below for the desired output). The problem is that I'm getting something like '\t\\acro{.... How can I convert this to my desired output?

def getPrice(symbol,
            shortForm,
            longForm):

    abbreviations = []
    with open("./file.tex", encoding="utf-8") as f:
         file = list(f)
    save = False
    for line in file:
        print("\n"+ line)
        if(line.startswith(r'\end{acronym}')):
            save = False
        if(save):
            abbreviations.append(line)
        if(line.startswith(r'\begin{acronym}')):
            save = True

    print(abbreviations)

if __name__== "__main__":
    getPrice(str(sys.argv[1]),
    str(sys.argv[2]),
    str(sys.argv[3]))

[OUT]
['\t\\acro{knmi}[KNMI]{Koninklijk Nederlands Meteorologisch Instituut}\n', '\t\\acro{test}[TESTERER]{T E SDH SADHU AHENSAD }\n']
```
```\chapter*{Short}
\addcontentsline{toc}{chapter}{Short}
\markboth{Short}{Short}
\begin{acronym}[TESTERER]
    \acro{knmi}[KNMI]{Koninklijk Nederlands Meteorologisch Instituut}
    \acro{example}[e.g.]{For example}
\end{acronym}
```
<p>Desired Output</p>
<pre class="lang-py prettyprint-override"><code>{
  "abbreviation1": {
      "symbol": "knmi",
      "shortForm": "KNMI",
      "longForm": "Koninklijk Nederlands Meteorologisch Instituut",
   }
  "abbreviation2": {
      "symbol": "example",
      "shortForm": "e.g.",
      "longForm": "For example",
   }
}
</code>```

答:
You can use re.findall() to capture all of the abbreviations, then use the json module to dump it out into a file. Your approach could work, but you'd have to do a lot of manual string parsing, which would be a pretty massive headache. (Note that a program that can parse arbitrary LaTeX would need something more powerful than regular expressions; however, since we're parsing a very small subset of LaTeX, regular expressions will do fine here.)

import re
import json

data = r"""\chapter*{Short}
\addcontentsline{toc}{chapter}{Short}
\markboth{Short}{Short}
\begin{acronym}[TESTERER]
    \acro{knmi}[KNMI]{Koninklijk Nederlands Meteorologisch Instituut}
    \acro{example}[e.g.]{For example}
\end{acronym}"""

pattern = re.compile(r"\\acro\{(.+)\}\[(.+)\]\{(.+)\}")
regex_result = re.findall(pattern, data)
final_output = {}
for index, (symbol, shortform, longform) in enumerate(regex_result, start=1):
    final_output[f'abbreviation{index}'] = \
        dict(symbol=symbol, shortform=shortform, longform=longform)

with open('output.json', 'w') as output_file:
    json.dump(final_output, output_file, indent=4)
```
<p><code>output.json</code> contains the following:</p>
<pre class="lang-json prettyprint-override"><code>{
    "abbreviation1": {
        "symbol": "knmi",
        "shortform": "KNMI",
        "longform": "Koninklijk Nederlands Meteorologisch Instituut"
    },
    "abbreviation2": {
        "symbol": "example",
        "shortform": "e.g.",
        "longform": "For example"
    }
}
</code>```

Body:
I have a problem. I am reading in a file.
This file contains abbreviations. However, I only want to read the abbreviations. This also works. However, not in the desired format as expected, I would like to save the abbreviations cleanly per line (see below for the desired output). The problem is that I'm getting something like '\t\\acro{.... How can I convert this to my desired output?

def getPrice(symbol,
            shortForm,
            longForm):

    abbreviations = []
    with open("./file.tex", encoding="utf-8") as f:
         file = list(f)
    save = False
    for line in file:
        print("\n"+ line)
        if(line.startswith(r'\end{acronym}')):
            save = False
        if(save):
            abbreviations.append(line)
        if(line.startswith(r'\begin{acronym}')):
            save = True

    print(abbreviations)

if __name__== "__main__":
    getPrice(str(sys.argv[1]),
    str(sys.argv[2]),
    str(sys.argv[3]))

[OUT]
['\t\\acro{knmi}[KNMI]{Koninklijk Nederlands Meteorologisch Instituut}\n', '\t\\acro{test}[TESTERER]{T E SDH SADHU AHENSAD }\n']

\chapter*{Short}
\addcontentsline{toc}{chapter}{Short}
\markboth{Short}{Short}
\begin{acronym}[TESTERER]
    \acro{knmi}[KNMI]{Koninklijk Nederlands Meteorologisch Instituut}
    \acro{example}[e.g.]{For example}
\end{acronym}

Desired Output

{
  "abbreviation1": {
      "symbol": "knmi",
      "shortForm": "KNMI",
      "longForm": "Koninklijk Nederlands Meteorologisch Instituut",
   }
  "abbreviation2": {
      "symbol": "example",
      "shortForm": "e.g.",
      "longForm": "For example",
   }
}

Body:
You can use re.findall() to capture all of the abbreviations, then use the json module to dump it out into a file. Your approach could work, but you'd have to do a lot of manual string parsing, which would be a pretty massive headache. (Note that a program that can parse arbitrary LaTeX would need something more powerful than regular expressions; however, since we're parsing a very small subset of LaTeX, regular expressions will do fine here.)

import re
import json

data = r"""\chapter*{Short}
\addcontentsline{toc}{chapter}{Short}
\markboth{Short}{Short}
\begin{acronym}[TESTERER]
    \acro{knmi}[KNMI]{Koninklijk Nederlands Meteorologisch Instituut}
    \acro{example}[e.g.]{For example}
\end{acronym}"""

pattern = re.compile(r"\\acro\{(.+)\}\[(.+)\]\{(.+)\}")
regex_result = re.findall(pattern, data)
final_output = {}
for index, (symbol, shortform, longform) in enumerate(regex_result, start=1):
    final_output[f'abbreviation{index}'] = \
        dict(symbol=symbol, shortform=shortform, longform=longform)

with open('output.json', 'w') as output_file:
    json.dump(final_output, output_file, indent=4)

output.json contains the following:

{
    "abbreviation1": {
        "symbol": "knmi",
        "shortform": "KNMI",
        "longform": "Koninklijk Nederlands Meteorologisch Instituut"
    },
    "abbreviation2": {
        "symbol": "example",
        "shortform": "e.g.",
        "longform": "For example"
    }
}


问:
Rotting orange problem - cannot get expected value
So the problem is given a basket of n rows and m columns, find the minimum number of days required to rot all oranges, knowing that there is always at least 1 rotten orange in the basket, and their positions are given as input nested list positions.

(EDIT: apologies, forgot to add the rotting rule, but basically adjacent oranges to a rotten orange should rot the next day e.g. if orange at [1,1] is rotten today, oranges at [0,1], [2,1], [1,0], [1,2] should rot the next day)

Just cannot get the expected output from the input below, and I cannot see where my code went wrong. Really starting to feel like the expected output given is somehow problematic. Would be great to have some advices.

Input: n = 3, m = 7, positions = [[2,4]]

Expected output: 4

Actual output: 6

```<code>def rottingOrange(n,m,positions):
    #Idea: Find cells that have not rotten
    #If either cell next to it have rotten, it will also rot
    #If there is no more cells that have not rot, stops

    def isValid(i,j,positions):
        #Determine if an orange position is adjacent to a rotten orange
        if [i-1,j] in positions or [i+1,j] in positions or [i,j-1] in positions or [i,j+1] in positions:
            return True
        else:
            return False

    def rot(grid,positions):
        #Find all oranges that should rot for the current day
        temp = []
        for i,j in grid:
            if isValid(i,j,positions):
                temp = temp + [[i,j]]
        if len(temp) < 1:
            return "cannot rot"
        else:
            grid_new = [x for x in grid if x not in temp]
            positions_new = positions + temp
            return grid_new, positions_new

    def rotting(grid, positions):
        #find the number of days taken to rot all oranges
        if len(grid) <= 0 or rot(grid, positions) == "cannot rot":
            return 0
        else:
            grid_new = rot(grid,positions)[0]
            positions_new = rot(grid,positions)[1]
            if len(grid_new) == len(grid):
                return rotting(grid_new,positions_new)
            else:
                return 1 + rotting(grid_new,positions_new)

    def grid_creation(n,m,positions):
        #create grid of size n x m, and remove all oranges that have rotten
        grid = []
        for i in range(n):
            for j in range(m):
                grid.append([i,j])
        for x in positions:
            if x in grid:
                grid.remove(x)
        return grid

    if __name__ == "__main__":
        grid = grid_creation(n,m,positions)
        return rotting(grid,positions)
</code>```

答:
Explanation video is here: https://www.youtube.com/watch?v=1dWTasnWs-M&ab_channel=yilmazbingol</p>
```<code>class Solution:
    def __init__(self):
        self.directions=[
                    [-1, 0],
                    [0, 1],
                    [1, 0],
                    [0, -1],
                    ]
    def orangesRotting(self, grid: List[List[int]]) -> int:
        fresh_oranges=0
        queue=deque()
        ROWS,COLS=len(grid),len(grid[0])
        # get the initial state of the grid
        for i in range(ROWS):
            for j in range(COLS):
                if grid[i][j]==1:
                    fresh_oranges+=1
                if grid[i][j]==2:
                    queue.append((i,j))
        minutes=0
        current_batch_size=len(queue)
        # process all the bad oranges
        while queue:
            # 1 minute passes when i process each batch
            if current_batch_size==0:
                minutes+=1
                current_batch_size=len(queue)
            current_orange=queue.popleft()
            current_row=current_orange[0]
            current_col=current_orange[1]
            current_batch_size-=1
            # check the neighbors of current_orange
            for direction in self.directions:
                next_row=current_row+direction[0]
                next_col=current_col+direction[1]
                if next_row<0 or next_row==ROWS or next_col<0 or next_col==COLS:
                    continue
                # if next orange is fresh, convert to a bad orange
                if grid[next_row][next_col]==1:
                    grid[next_row][next_col]=2
                    fresh_oranges-=1
                    queue.append((next_row,next_col))
        if fresh_oranges!=0:
            return -1
        return minutes

</code>```

Body:
So the problem is given a basket of n rows and m columns, find the minimum number of days required to rot all oranges, knowing that there is always at least 1 rotten orange in the basket, and their positions are given as input nested list positions.

(EDIT: apologies, forgot to add the rotting rule, but basically adjacent oranges to a rotten orange should rot the next day e.g. if orange at [1,1] is rotten today, oranges at [0,1], [2,1], [1,0], [1,2] should rot the next day)

Just cannot get the expected output from the input below, and I cannot see where my code went wrong. Really starting to feel like the expected output given is somehow problematic. Would be great to have some advices.

Input: n = 3, m = 7, positions = [[2,4]]

Expected output: 4

Actual output: 6

def rottingOrange(n,m,positions):
    #Idea: Find cells that have not rotten
    #If either cell next to it have rotten, it will also rot
    #If there is no more cells that have not rot, stops

    def isValid(i,j,positions):
        #Determine if an orange position is adjacent to a rotten orange
        if [i-1,j] in positions or [i+1,j] in positions or [i,j-1] in positions or [i,j+1] in positions:
            return True
        else:
            return False

    def rot(grid,positions):
        #Find all oranges that should rot for the current day
        temp = []
        for i,j in grid:
            if isValid(i,j,positions):
                temp = temp + [[i,j]]
        if len(temp) < 1:
            return "cannot rot"
        else:
            grid_new = [x for x in grid if x not in temp]
            positions_new = positions + temp
            return grid_new, positions_new

    def rotting(grid, positions):
        #find the number of days taken to rot all oranges
        if len(grid) <= 0 or rot(grid, positions) == "cannot rot":
            return 0
        else:
            grid_new = rot(grid,positions)[0]
            positions_new = rot(grid,positions)[1]
            if len(grid_new) == len(grid):
                return rotting(grid_new,positions_new)
            else:
                return 1 + rotting(grid_new,positions_new)

    def grid_creation(n,m,positions):
        #create grid of size n x m, and remove all oranges that have rotten
        grid = []
        for i in range(n):
            for j in range(m):
                grid.append([i,j])
        for x in positions:
            if x in grid:
                grid.remove(x)
        return grid

    if __name__ == "__main__":
        grid = grid_creation(n,m,positions)
        return rotting(grid,positions)

Body:
Explanation video is here: https://www.youtube.com/watch?v=1dWTasnWs-M&ab_channel=yilmazbingol

class Solution:
    def __init__(self):
        self.directions=[
                    [-1, 0],
                    [0, 1],
                    [1, 0],
                    [0, -1],
                    ]
    def orangesRotting(self, grid: List[List[int]]) -> int:
        fresh_oranges=0
        queue=deque()
        ROWS,COLS=len(grid),len(grid[0])
        # get the initial state of the grid
        for i in range(ROWS):
            for j in range(COLS):
                if grid[i][j]==1:
                    fresh_oranges+=1
                if grid[i][j]==2:
                    queue.append((i,j))
        minutes=0
        current_batch_size=len(queue)
        # process all the bad oranges
        while queue:
            # 1 minute passes when i process each batch
            if current_batch_size==0:
                minutes+=1
                current_batch_size=len(queue)
            current_orange=queue.popleft()
            current_row=current_orange[0]
            current_col=current_orange[1]
            current_batch_size-=1
            # check the neighbors of current_orange
            for direction in self.directions:
                next_row=current_row+direction[0]
                next_col=current_col+direction[1]
                if next_row<0 or next_row==ROWS or next_col<0 or next_col==COLS:
                    continue
                # if next orange is fresh, convert to a bad orange
                if grid[next_row][next_col]==1:
                    grid[next_row][next_col]=2
                    fresh_oranges-=1
                    queue.append((next_row,next_col))
        if fresh_oranges!=0:
            return -1
        return minutes


问:
Firestore: How to store data back again in the right documents after fetching data from multiple documents
In my App a user can track his workouts, which I want to save in cloud firestore. My idea is to store a list of workouts for each month to prevent that a document gets too big. So a document would look something like this:

```<code>month: '2022-02',
workouts: [
  {
  date: '2022-02-01',
  exercises: [
       {
        sets: [{'reps': 12, 'weight': 80}
               {'reps': 12, 'weight': 80}
            ],
       },
     ],
 },
{
  date: '2022-02-02',
  exercises: [
       {
        sets: [{'reps': 10, 'weight': 90}
               {'reps': 10, 'weight': 90}
            ],
       },
     ],
 },
],
</code>```

Question:

When I fetch for example the workouts from the last three month and put them in a list to let the user interact with these workouts. How can I store them again in cloud firestore sorted in the right month?

答:
To be able to write data back to the same document you read from, you will need to track the document ID for each piece of data in your list view, in addition to the fields you read from the document itself.

When you have the document ID, writing data to it is as easy as:

```<code>FirebaseFirestore.instance
  .collection("yourWorkoutsCollection")
  .document(documentIdForTheMonth)
  .update({ 'workouts': FieldValue.arrayUnion([theWorkoutToAdd]) });
</code>```

Body:
In my App a user can track his workouts, which I want to save in cloud firestore. My idea is to store a list of workouts for each month to prevent that a document gets too big. So a document would look something like this:

month: '2022-02',
workouts: [
  {
  date: '2022-02-01',
  exercises: [
       {
        sets: [{'reps': 12, 'weight': 80}
               {'reps': 12, 'weight': 80}
            ],
       },
     ],
 },
{
  date: '2022-02-02',
  exercises: [
       {
        sets: [{'reps': 10, 'weight': 90}
               {'reps': 10, 'weight': 90}
            ],
       },
     ],
 },
],

Question:

When I fetch for example the workouts from the last three month and put them in a list to let the user interact with these workouts. How can I store them again in cloud firestore sorted in the right month?

Body:
To be able to write data back to the same document you read from, you will need to track the document ID for each piece of data in your list view, in addition to the fields you read from the document itself.

When you have the document ID, writing data to it is as easy as:

FirebaseFirestore.instance
  .collection("yourWorkoutsCollection")
  .document(documentIdForTheMonth)
  .update({ 'workouts': FieldValue.arrayUnion([theWorkoutToAdd]) });