问:
Installing django with python error on widows 10?
I seem to get errors when installing django with the following commands. I follow the instructions form the book i am using exactly but get errors. First installing pipenv gave me errors about path and updating the paths in windows manually fixed that.

```<code>pip3 install pipenv            <---- executes correlty with no errors

pipenv install django ~=3.1.0   <----- get the following errors below
</code>```
```<code>Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2800.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 197, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2800.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\Scripts\pipenv.exe\__main__.py", line 7, in <module>
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\click\core.py", line 1128, in __call__
    return self.main(*args, **kwargs)
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\click\core.py", line 1053, in main
    rv = self.invoke(ctx)
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\click\core.py", line 1659, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\click\core.py", line 1395, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\click\core.py", line 754, in invoke
    return __callback(*args, **kwargs)
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\click\decorators.py", line 84, in new_func
    return ctx.invoke(f, obj, *args, **kwargs)
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\click\core.py", line 754, in invoke
    return __callback(*args, **kwargs)
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\cli\command.py", line 194, in install
    do_install(
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\core.py", line 2046, in do_install
    pkg_requirement = Requirement.from_line(pkg_line)
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\requirementslib\models\requirements.py", line 2674, in from_line
    parsed_line = Line(line)
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\requirementslib\models\requirements.py", line 171, in __init__
    self.parse()
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\requirementslib\models\requirements.py", line 1304, in parse
    self.parse_name()
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\requirementslib\models\requirements.py", line 1027, in parse_name
    name = self._parse_name_from_line()
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\requirementslib\models\requirements.py", line 968, in _parse_name_from_line
    raise RequirementError(
pipenv.vendor.requirementslib.exceptions.RequirementError: Failed parsing requirement from 'C:\\Users\\=3.1.0'
</code>```

any help would be appreciated. I have disabled windows defender just encase it was a internet access isue even though the error does not report as such. I am running all commands through windwos power shell as administrator. I am using python 3.9

I cant seem to find anyone with similar problem online. Would appreciate some help

Thank you

答:
Just encase anyone is interested in why I was encountering the above error, it was because of the space between django and ~ .

pipenv install django ~=3.1.0  <------ gave me errors

pipenv install django~=3.1.0 <----- everything was fine.

Body:
I seem to get errors when installing django with the following commands. I follow the instructions form the book i am using exactly but get errors. First installing pipenv gave me errors about path and updating the paths in windows manually fixed that.

pip3 install pipenv            <---- executes correlty with no errors

pipenv install django ~=3.1.0   <----- get the following errors below

Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2800.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 197, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2800.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\Scripts\pipenv.exe\__main__.py", line 7, in <module>
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\click\core.py", line 1128, in __call__
    return self.main(*args, **kwargs)
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\click\core.py", line 1053, in main
    rv = self.invoke(ctx)
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\click\core.py", line 1659, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\click\core.py", line 1395, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\click\core.py", line 754, in invoke
    return __callback(*args, **kwargs)
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\click\decorators.py", line 84, in new_func
    return ctx.invoke(f, obj, *args, **kwargs)
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\click\core.py", line 754, in invoke
    return __callback(*args, **kwargs)
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\cli\command.py", line 194, in install
    do_install(
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\core.py", line 2046, in do_install
    pkg_requirement = Requirement.from_line(pkg_line)
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\requirementslib\models\requirements.py", line 2674, in from_line
    parsed_line = Line(line)
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\requirementslib\models\requirements.py", line 171, in __init__
    self.parse()
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\requirementslib\models\requirements.py", line 1304, in parse
    self.parse_name()
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\requirementslib\models\requirements.py", line 1027, in parse_name
    name = self._parse_name_from_line()
  File "C:\Users\zzzz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pipenv\vendor\requirementslib\models\requirements.py", line 968, in _parse_name_from_line
    raise RequirementError(
pipenv.vendor.requirementslib.exceptions.RequirementError: Failed parsing requirement from 'C:\\Users\\=3.1.0'

any help would be appreciated. I have disabled windows defender just encase it was a internet access isue even though the error does not report as such. I am running all commands through windwos power shell as administrator. I am using python 3.9

I cant seem to find anyone with similar problem online. Would appreciate some help

Thank you


来源: stackexchange

问:
Restsharp returns 403 while Postman returns 200
This is the (modified) snippet that Postman gives for successful call to my page.

```<code>var client = new RestClient("http://sub.example.com/wp-json/wp/v2/users/me");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Basic anVyYTp3MmZacmo2eGtBOHJsRWrt");
IRestResponse response = client.Execute(request);
</code>```

But when placed in my c# app it returns 403 forbidden, while Postman makes it and recieves 200.
The same thing happens when I use httpclient in my app (403).

答:
[Solution]
Use the below line for the header

Headers.Add("User-Agent: Other");

ContentLicense: CC BY-SA 3.0

Body:
This is the (modified) snippet that Postman gives for successful call to my page.

var client = new RestClient("http://sub.example.com/wp-json/wp/v2/users/me");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Basic anVyYTp3MmZacmo2eGtBOHJsRWrt");
IRestResponse response = client.Execute(request);

But when placed in my c# app it returns 403 forbidden, while Postman makes it and recieves 200.
The same thing happens when I use httpclient in my app (403).

ContentLicense: CC BY-SA 4.0


问:
Magento separate price.phtml
How can I add a new price template to the category view (template/catalog/product/list.phtml) without changing the price template that is used in (template/catalog/product/view.phtml)? Both files uses the template/catalog/product/price.phtml, but I need a separate price template in template/catalog/product/list.phtml.</p>

答:
Copy app/code/core/Mage/Catalog/Block/Product.php to app/code/local/YourModule/Catalog/Block/Product.php(about the detail of making your own module, you should see other document).

In the copied file, about Line 61, change

```<code>public function getPriceHtml($product)
    {
        $this->setTemplate('catalog/product/price.phtml');
        $this->setProduct($product);
        return $this->toHtml();
    }
</code>```

to

```<code>public function getPriceHtml($product)
    {
        $this->setTemplate('catalog/product/your_price.phtml');
        $this->setProduct($product);
        return $this->toHtml();
    }
</code>```

you can custom the view of price in your_price.phtml.

Title: Magento separate price.phtml

Body:
Copy app/code/core/Mage/Catalog/Block/Product.php to app/code/local/YourModule/Catalog/Block/Product.php(about the detail of making your own module, you should see other document).

In the copied file, about Line 61, change

public function getPriceHtml($product)
    {
        $this->setTemplate('catalog/product/price.phtml');
        $this->setProduct($product);
        return $this->toHtml();
    }

to

public function getPriceHtml($product)
    {
        $this->setTemplate('catalog/product/your_price.phtml');
        $this->setProduct($product);
        return $this->toHtml();
    }

you can custom the view of price in your_price.phtml.


问:
C++ How do I create objects from different classes in another class?
I have a program with two classes, one for points and one for a rectangle. I need to make two objects of point class within my rectangle class and make them private. I can't figure out how to use the rectangle constructor to make the points with the points constructor, every time I do so I get the error "no default constructor exists for class "Point2d"". Even when I make a default constructor I still get this. I'm at a loss here.</p>
```<code>#include <iostream>
#include <cmath>
using namespace std;

class point2D {
private:
    int x = 0;
    int y = 0;

public:
    int getX() {
        return x;
    }
    int getY() {
        return y;
    }
    point2D(int ax, int ay) {
        x = ax;
        y = ay;
    }
};

class rectangleType {
private:
    point2D p0;
    point2D p1;

public:
    int getX0() {
        return p0.getX();
    }
    int getY0() {
        return p0.getY();
    }
    int getX1() {
        return p1.getX();
    }
    int getY1() {
        return p1.getY();
    }
    int getWidth() {
        return abs(getX1() - getX0());
    }
    int getLength() {
        return abs(getY1() - getY0());
    }
    int getPerimeter() {
        return 2 * (getWidth() + getLength());
    }
    int getArea() {
        return (getWidth() * getLength());
    }
    rectangleType(int ax0, int ay0, int ax1, int ay1) {
        point2D p0(ax0, ay0);
        point2D p1(ax1, ay1);
    }
};
</code>```

答:
Members and base classes not otherwise specifically initialized in the base+member initialization list require provision of default construction. In it's simplest form, given this:

```<code>class S
{
public:
    S(int) {}
};
</code>```

this is not possible:

```<code>S s;
</code>```

because the only ctor (default copy-ctor notwithstanding) defined requires an int argument and none was provided. This is, perhaps, intentional by whomever designed S . It may not make sense to have an S without that require argument.

Carrying this forward to your specific circumstance, you have a class, point2D, whose only defined course of construction (default copy-ctor notwithstanding) is this:

```<code>point2D(int ax, int ay)
</code>```

Like S in our previous example, this means something like this:

```<code>point2D pt;
</code>```

is not possible. But that is exactly what is happening here (along with several other problems)

```<code>rectangleType(int ax0, int ay0, int ax1, int ay1)
    // here, before entering the function body below, p0 and p1
    //  must be successfully constructed *somehow*
{
    point2D p0(ax0, ay0);
    point2D p1(ax1, ay1);
}
</code>```

Before the constructor body is entered, all base classes (of which you have none), and member variables (of which you have two: p0 and p1), must be constructed. Since you are not directly initializing your p0 and p1 members in a member initialization list, the compiler attempts to find default constructors (takes no arguments, or has sufficient default values for all arguments declared).  It can't find one. By providing a non-default ctor as you have, you've declared "this is the way these should be constructed". The compiler is therefor saying it could not find a way to create these things successfully.

In your case, providing such a constructor, while possible, isn't necessarily the proper (and certainly not the only) solution. Yes, you can, but it turns out all that does is enhance later issues. For example that will allow this to compile:

```<code>rectangleType(int ax0, int ay0, int ax1, int ay1)
{
    point2D p0(ax0, ay0);
    point2D p1(ax1, ay1);
}
</code>```

But now you have another problem. Your members p0 and p1 are not the ones you see above. All the code above does is declare two more id's with the same names as your members (thereby shadowing the latter into obscurity), construct them, discard them on function exit, and ultimately leave you with your two members default-initialized, but not with the provided arguments. Shortly thereafter, you scratch your head and wonder went wrong.

You could still provide that default-ctor for point2D (which you didn't want to before, but now feel somewhat 'forced' to), and then do this:

```<code>rectangleType(int ax0, int ay0, int ax1, int ay1)
{
    p0 = point2D(ax0, ay0);
    p1 = point2D(ax1, ay1);
}
</code>```

But now we're just piling on the rubbish, and an anti-pattern is forming. Now we're default-constructing our p0 and p1 members using a ctor we didn't think we needed (and perhaps even purposely didn't want), and then were discarding those efforts by constructing two more point2D objects and using copy-assignment to reap them.

There is a better way

Member Initialization

The language provides a way of telling telling the compiler, "before entering my constructor body, first construct my base class (if any) and members like this" :

```<code>rectangleType(int ax0, int ay0, int ax1, int ay1)
    : p0(ax0, ay0)
    , p1(ax1, ay1)
{
}
</code>```

The syntax may seem a bit odd, but apart from the leading colon you've seen the rest before. In fact, you were even using it before in your prior code, but in the wrong place, and for the wrong target variables. This syntax says "construct these members like this, then enter the class constructor function body."

Another Example

That isn't the only place you can (or should) use this feature of the language. For example, your point2D constructor looks like this:

```<code>point2D(int ax, int ay)
{
    x = ax;
    y = ay;
}
</code>```

But now you know you can also do this:

```<code>point2D(int ax, int ay)
    : x(ax)
    , y(ay)
{
}
</code>```

Granted, it won't matter much, and any compiler with a grain of sanity will generate similar/identical code in the above trivial usage of this feature, but it stresses a larger overall theme. Where possible, use member-initialization lists to construct members. It is generally more efficient, and in many cases massively so.

A Special Note About Ordering

I mention this only because it is often relevant, ,and can be the cause of some interesting behavior you were otherwise not expecting. When using a member initialization list, the order of construction of the members is not dictated by the order of the list; it is dictated by the order of the member declarations. An example to show what I mean.

In your class, points p0 and p1 are declared in that specific order, top-down. Using our newly discovered member-initialization syntax, what happens when we do this (note the order in the list of members):

```<code>S s;
</code>```0

This looks like p1 will be constructed before p0. That is not the case. The order of declaration in the class is what matters. Since the class as this:

```<code>S s;
</code>```1

That means p0 will be constructed first, then p1, regardless of the order in the member-initialization list. This can lead to some interesting behavior, especially when you're not expecting it. In your trivial case it wouldn't overall matter, but it is worth noting nonetheless.

Body:
I have a program with two classes, one for points and one for a rectangle. I need to make two objects of point class within my rectangle class and make them private. I can't figure out how to use the rectangle constructor to make the points with the points constructor, every time I do so I get the error "no default constructor exists for class "Point2d"". Even when I make a default constructor I still get this. I'm at a loss here.

#include <iostream>
#include <cmath>
using namespace std;

class point2D {
private:
    int x = 0;
    int y = 0;

public:
    int getX() {
        return x;
    }
    int getY() {
        return y;
    }
    point2D(int ax, int ay) {
        x = ax;
        y = ay;
    }
};

class rectangleType {
private:
    point2D p0;
    point2D p1;

public:
    int getX0() {
        return p0.getX();
    }
    int getY0() {
        return p0.getY();
    }
    int getX1() {
        return p1.getX();
    }
    int getY1() {
        return p1.getY();
    }
    int getWidth() {
        return abs(getX1() - getX0());
    }
    int getLength() {
        return abs(getY1() - getY0());
    }
    int getPerimeter() {
        return 2 * (getWidth() + getLength());
    }
    int getArea() {
        return (getWidth() * getLength());
    }
    rectangleType(int ax0, int ay0, int ax1, int ay1) {
        point2D p0(ax0, ay0);
        point2D p1(ax1, ay1);
    }
};

Body:
Members and base classes not otherwise specifically initialized in the base+member initialization list require provision of default construction. In it's simplest form, given this:

class S
{
public:
    S(int) {}
};

this is not possible:

S s;

because the only ctor (default copy-ctor notwithstanding) defined requires an int argument and none was provided. This is, perhaps, intentional by whomever designed S . It may not make sense to have an S without that require argument.

Carrying this forward to your specific circumstance, you have a class, point2D, whose only defined course of construction (default copy-ctor notwithstanding) is this:

point2D(int ax, int ay)

Like S in our previous example, this means something like this:

point2D pt;

is not possible. But that is exactly what is happening here (along with several other problems)

rectangleType(int ax0, int ay0, int ax1, int ay1)
    // here, before entering the function body below, p0 and p1
    //  must be successfully constructed *somehow*
{
    point2D p0(ax0, ay0);
    point2D p1(ax1, ay1);
}

Before the constructor body is entered, all base classes (of which you have none), and member variables (of which you have two: p0 and p1), must be constructed. Since you are not directly initializing your p0 and p1 members in a member initialization list, the compiler attempts to find default constructors (takes no arguments, or has sufficient default values for all arguments declared).  It can't find one. By providing a non-default ctor as you have, you've declared "this is the way these should be constructed". The compiler is therefor saying it could not find a way to create these things successfully.

In your case, providing such a constructor, while possible, isn't necessarily the proper (and certainly not the only) solution. Yes, you can, but it turns out all that does is enhance later issues. For example that will allow this to compile:

rectangleType(int ax0, int ay0, int ax1, int ay1)
{
    point2D p0(ax0, ay0);
    point2D p1(ax1, ay1);
}

But now you have another problem. Your members p0 and p1 are not the ones you see above. All the code above does is declare two more id's with the same names as your members (thereby shadowing the latter into obscurity), construct them, discard them on function exit, and ultimately leave you with your two members default-initialized, but not with the provided arguments. Shortly thereafter, you scratch your head and wonder went wrong.

You could still provide that default-ctor for point2D (which you didn't want to before, but now feel somewhat 'forced' to), and then do this:

rectangleType(int ax0, int ay0, int ax1, int ay1)
{
    p0 = point2D(ax0, ay0);
    p1 = point2D(ax1, ay1);
}

But now we're just piling on the rubbish, and an anti-pattern is forming. Now we're default-constructing our p0 and p1 members using a ctor we didn't think we needed (and perhaps even purposely didn't want), and then were discarding those efforts by constructing two more point2D objects and using copy-assignment to reap them.

There is a better way

Member Initialization

The language provides a way of telling telling the compiler, "before entering my constructor body, first construct my base class (if any) and members like this" :

rectangleType(int ax0, int ay0, int ax1, int ay1)
    : p0(ax0, ay0)
    , p1(ax1, ay1)
{
}

The syntax may seem a bit odd, but apart from the leading colon you've seen the rest before. In fact, you were even using it before in your prior code, but in the wrong place, and for the wrong target variables. This syntax says "construct these members like this, then enter the class constructor function body."

Another Example

That isn't the only place you can (or should) use this feature of the language. For example, your point2D constructor looks like this:

point2D(int ax, int ay)
{
    x = ax;
    y = ay;
}

But now you know you can also do this:

point2D(int ax, int ay)
    : x(ax)
    , y(ay)
{
}

Granted, it won't matter much, and any compiler with a grain of sanity will generate similar/identical code in the above trivial usage of this feature, but it stresses a larger overall theme. Where possible, use member-initialization lists to construct members. It is generally more efficient, and in many cases massively so.

A Special Note About Ordering

I mention this only because it is often relevant, ,and can be the cause of some interesting behavior you were otherwise not expecting. When using a member initialization list, the order of construction of the members is not dictated by the order of the list; it is dictated by the order of the member declarations. An example to show what I mean.

In your class, points p0 and p1 are declared in that specific order, top-down. Using our newly discovered member-initialization syntax, what happens when we do this (note the order in the list of members):

rectangleType(int ax0, int ay0, int ax1, int ay1)
    : p1(ax1, ay1)
    , p0(ax0, ay0)
{
}

This looks like p1 will be constructed before p0. That is not the case. The order of declaration in the class is what matters. Since the class as this:

private:
    point2D p0;
    point2D p1;

That means p0 will be constructed first, then p1, regardless of the order in the member-initialization list. This can lead to some interesting behavior, especially when you're not expecting it. In your trivial case it wouldn't overall matter, but it is worth noting nonetheless.


问:
When creating stored procedure in Snowflake is there a way to return same output as a query, executed within it?
I created a stored procedure that sets the certain variable value and executes merge using this variable. Currently, it just returns a hardcoded message "Successfully executed.".
Is it possible to return the same result as the original merge query returns, like

number of rows inserted

number of rows updated

?

```<code>    CREATE OR REPLACE PROCEDURE ALERTS_MERGE_PROCEDURE ()
RETURNS STRING NOT NULL
LANGUAGE JAVASCRIPT
AS
    $$
    var sql_command = '
    MERGE INTO tablename
..
WHEN MATCHED THEN
UPDATE SET ...
WHEN NOT MATCHED THEN
INSERT ...
);
    '
    snowflake.execute(
        {
        sqlText: sql_command
        });
    return "Successfully executed.";
    $$;
</code>```

答: Yes, look at the methods of the statement object. This is all documented here: https://docs.snowflake.com/en/sql-reference/stored-procedures-api.html#object-statement</p>

Body:
I created a stored procedure that sets the certain variable value and executes merge using this variable. Currently, it just returns a hardcoded message "Successfully executed.".
Is it possible to return the same result as the original merge query returns, like

number of rows inserted

number of rows updated

?

    CREATE OR REPLACE PROCEDURE ALERTS_MERGE_PROCEDURE ()
RETURNS STRING NOT NULL
LANGUAGE JAVASCRIPT
AS
    $$
    var sql_command = '
    MERGE INTO tablename
..
WHEN MATCHED THEN
UPDATE SET ...
WHEN NOT MATCHED THEN
INSERT ...
);
    '
    snowflake.execute(
        {
        sqlText: sql_command
        });
    return "Successfully executed.";
    $$;


问:
Insert new records where one doesn't already exist
I need some help inserting new data where it doesn't already exist.

Currently I use this query:

```<code>INSERT INTO dbo.Table (column1, column2, column3, column4)
    SELECT value1, value2, value3, value4
    FROM dbo.staginTable
    LEFT JOIN dbo.Table AS A ON A.column1 = value1
                             AND A.column2 = value2
                             AND A.column3 = value3
                             AND A.column4 = value4
    WHERE A.column1 IS NULL
      AND A.column2 IS NULL
      AND A.column3 IS NULL
      AND A.column4 IS NULL
</code>```

This query works fine and doesn't insert data which already exists in the dbo.Table if none of the variables (value1, value2, value3, value4) is null.

My problem is that it`s very common that e.g. either value3 or value4 or both can be null and in this case the values will be inserted

Works:

```<code>(value1, value2, value3, value4)
('one', 'two', 'three', 'four')
</code>```

Doesn't work:

```<code>(value1, value2, value3, value4)
('one', 'two', NULL, 'four')
</code>```

I know that I could add a Unique index on the 4 columns to bypass this problem or I could use another query like insert expect but I would like to know if it's possible to use the query above or what I need to change in the query.

Thanks for your help

答:
I recommend using NOT EXISTS- because that makes logical sense. Then you need to combine your NULL compares with value compares as follows:

```<code>INSERT INTO dbo.MyTable (column1, column2, column3, column4)
    SELECT value1, value2, value3, value4
    FROM dbo.StagingTable ST
    WHERE NOT EXISTS (
      SELECT 1
      FROM dbo.MyTable MT
      WHERE (ST.value1 = MT.value1 OR (ST.value1 IS NULL AND MT.value1 IS NULL))
      AND (ST.value2 = MT.value2 OR (ST.value2 IS NULL AND MT.value2 IS NULL))
      AND (ST.value3 = MT.value3 OR (ST.value3 IS NULL AND MT.value3 IS NULL))
      AND (ST.value4 = MT.value4 OR (ST.value4 IS NULL AND MT.value4 IS NULL))
    );
</code>```

Body:
I need some help inserting new data where it doesn't already exist.

Currently I use this query:

INSERT INTO dbo.Table (column1, column2, column3, column4)
    SELECT value1, value2, value3, value4
    FROM dbo.staginTable
    LEFT JOIN dbo.Table AS A ON A.column1 = value1
                             AND A.column2 = value2
                             AND A.column3 = value3
                             AND A.column4 = value4
    WHERE A.column1 IS NULL
      AND A.column2 IS NULL
      AND A.column3 IS NULL
      AND A.column4 IS NULL

This query works fine and doesn't insert data which already exists in the dbo.Table if none of the variables (value1, value2, value3, value4) is null.

My problem is that it`s very common that e.g. either value3 or value4 or both can be null and in this case the values will be inserted

Works:

(value1, value2, value3, value4)
('one', 'two', 'three', 'four')

Doesn't work:

(value1, value2, value3, value4)
('one', 'two', NULL, 'four')

I know that I could add a Unique index on the 4 columns to bypass this problem or I could use another query like insert expect but I would like to know if it's possible to use the query above or what I need to change in the query.

Thanks for your help

Body:
I recommend using NOT EXISTS- because that makes logical sense. Then you need to combine your NULL compares with value compares as follows:

INSERT INTO dbo.MyTable (column1, column2, column3, column4)
    SELECT value1, value2, value3, value4
    FROM dbo.StagingTable ST
    WHERE NOT EXISTS (
      SELECT 1
      FROM dbo.MyTable MT
      WHERE (ST.value1 = MT.value1 OR (ST.value1 IS NULL AND MT.value1 IS NULL))
      AND (ST.value2 = MT.value2 OR (ST.value2 IS NULL AND MT.value2 IS NULL))
      AND (ST.value3 = MT.value3 OR (ST.value3 IS NULL AND MT.value3 IS NULL))
      AND (ST.value4 = MT.value4 OR (ST.value4 IS NULL AND MT.value4 IS NULL))
    );


问:
Column count of mysql.proc is wrong. Expected 20, found 16. The table is probably corrupted
I am using 000webhost.com and I am using phpMyAdmin there. I am getting this error from MySQL when I run my PHP script as the title says:

Column count of mysql.proc is wrong. Expected 20, found 16.

The table is probably corrupted.

Is there any solution for this?

```<code><?php
$username="usrname";
$password="passwd";
$database="a1xxxxx_mydb";
$host="mysqlxx.000webhost.com";
mysql_connect($host,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
if (isset($_GET["userLatitude"]) && isset($_GET["userLongitude"])) {

 $userLatitude=$_GET['userLatitude'];
 $userLongitude=$_GET['userLongitude'];
 $result = mysql_query("SELECT locationName, ( 6371 * acos( cos( radians(floatval(     $userLatitude) )) * cos( radians( locationLatitude ) ) * cos( radians( locationLongitude ) - radians( floatval($userLatitude)) ) + sin( radians(floatval($userLongitude)) ) * sin( radians( locationLatitude) ) ) ) AS distance
         FROM Location HAVING distance < 2 ORDER BY distance LIMIT 0 ,20") or die(mysql_error());
echo $result;

 // check for empty result
if (mysql_num_rows($result) > 0) {
   // looping through all results
   // products node
  $response["Location"] = array();

  while ($row = mysql_fetch_array($result)) {
    // temp user array
    $product = array();
    $product["locationName"] = $row["locationName"];
    $product["locationInfo"] = $row["locationInfo"];
    $product["locationLatitude"] = $row["locationLatitude"];
    $product["locationLongitude"] = $row["locationLongitude"];
    $product["locationPic"] = $row["locationPic"];
    $product["city"] = $row["city"];

    // push single product into final response array
    array_push($response["Location"], $product);
 }
 // success
 $response["success"] = 1;

   // echoing JSON response
   echo json_encode($response);
 } else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";

// echo no users JSON
echo json_encode($response);
 }
 }
  else {
    // required field is missing
   $response["success"] = 0;
   $response["message"] = "Required field(s) is missing";

  // echoing JSON response
  echo json_encode($response);
 }
mysql_close();
?>
</code>```

答:
This my happen when eg. upgrading instead of migrating;

The part where it reads version check failed is the relevant part:

```<code>Version check failed. Got the following error when calling the 'mysql' command line client
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
FATAL ERROR: Upgrade failed
</code>```

Obviously this is about an incompatible client version, but the mysql database is also different.

This here would be the current definition of the mysql.proc table ... which shows that enum column type has changed and that column  aggregate has been added, since MariaDB 10.3.3.

Yet another problem is:

In MariaDB 10.4 and later, this table uses the Aria storage engine.

Downgrading the server to 5.x and deleting the InnoDB log files, then restoring table proc helped; (for MariaDB 5.x): https://github.com/google/mysql/blob/master/scripts/mysql_system_tables.sql

Body:
I am using 000webhost.com and I am using phpMyAdmin there. I am getting this error from MySQL when I run my PHP script as the title says:

Column count of mysql.proc is wrong. Expected 20, found 16.

The table is probably corrupted.

Is there any solution for this?

<?php
$username="usrname";
$password="passwd";
$database="a1xxxxx_mydb";
$host="mysqlxx.000webhost.com";
mysql_connect($host,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
if (isset($_GET["userLatitude"]) && isset($_GET["userLongitude"])) {

 $userLatitude=$_GET['userLatitude'];
 $userLongitude=$_GET['userLongitude'];
 $result = mysql_query("SELECT locationName, ( 6371 * acos( cos( radians(floatval(     $userLatitude) )) * cos( radians( locationLatitude ) ) * cos( radians( locationLongitude ) - radians( floatval($userLatitude)) ) + sin( radians(floatval($userLongitude)) ) * sin( radians( locationLatitude) ) ) ) AS distance
         FROM Location HAVING distance < 2 ORDER BY distance LIMIT 0 ,20") or die(mysql_error());
echo $result;

 // check for empty result
if (mysql_num_rows($result) > 0) {
   // looping through all results
   // products node
  $response["Location"] = array();

  while ($row = mysql_fetch_array($result)) {
    // temp user array
    $product = array();
    $product["locationName"] = $row["locationName"];
    $product["locationInfo"] = $row["locationInfo"];
    $product["locationLatitude"] = $row["locationLatitude"];
    $product["locationLongitude"] = $row["locationLongitude"];
    $product["locationPic"] = $row["locationPic"];
    $product["city"] = $row["city"];

    // push single product into final response array
    array_push($response["Location"], $product);
 }
 // success
 $response["success"] = 1;

   // echoing JSON response
   echo json_encode($response);
 } else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";

// echo no users JSON
echo json_encode($response);
 }
 }
  else {
    // required field is missing
   $response["success"] = 0;
   $response["message"] = "Required field(s) is missing";

  // echoing JSON response
  echo json_encode($response);
 }
mysql_close();
?>

Body:
This my happen when eg. upgrading instead of migrating;

The part where it reads version check failed is the relevant part:

Version check failed. Got the following error when calling the 'mysql' command line client
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
FATAL ERROR: Upgrade failed

Obviously this is about an incompatible client version, but the mysql database is also different.

This here would be the current definition of the mysql.proc table ... which shows that enum column type has changed and that column  aggregate has been added, since MariaDB 10.3.3.

Yet another problem is:

In MariaDB 10.4 and later, this table uses the Aria storage engine.

Downgrading the server to 5.x and deleting the InnoDB log files, then restoring table proc helped; (for MariaDB 5.x): https://github.com/google/mysql/blob/master/scripts/mysql_system_tables.sql


问:
Windows installer removing generated log files
Hi I have windows installer that install my program and uninstall it.
everything with installation goes fine but for uninstall part.
My program is generating Log files in "program location\Log\" directory.
I would like to add custom command to clear this folder before or after uninstallation so the uninstall process will completly remove the directory and does not leave mess in program files system.

Any idea how to do this.
Also i do not want to add additional file for this, if it is possible.

thank you for your suggestions...

答: I have decided to add bat file that is executed when uninstall happens and this will clear up.</p>


问:
Vue is not rendering on right tags component
The way i am defining my props;

```<code><template>
  <div>
    <vinput id="login_name" label="Phone number"></vinput>

            <div class="flex flex-col">
                <label for="email-phone">School slug</label>
                <input type="text" id="email-phone" class="border py-2 rounded">
            </div>
  </div>
</template>

<script>
import vinput from '../../components/Input.vue'

export default {
  components:{
    vinput
  }
}
</script>
</code>```

The way i am passing the props

```<code><vinput id="login_name" label="Phone number"></vinput>
</code>```

Please why is the browser rendering it this way:

```<code><div class="mt-4">
<div class="flex flex-col" id="login_name" label="Phone number">
<label></label>
  <input type="tex" class="border py-2 rounded">
 </div>
<div class="flex flex-col"><label for="email-phone">School slug</label><input type="text"
id="email-phone" class="border py-2 rounded"></div></div>
</code>```

I was expecting interpolation in the label and input not in the div

====Edited====
vinput component

```<code><template>
  <div class="flex flex-col">
    <label :for="id">{{ label }}</label>
    <input :type="type ? type : 'tex'"
    :class="classes ? classes :''" class="border py-2 rounded"/>
  </div>
</template>

<script>
export default {
  data(){
    return {
      props:['label', 'id','type', 'classes']
    }
  }
}
</script>
</code>```

答:
Move your props:['label', 'id','type', 'classes'] away from data.

Those are totally different things.

```<code><script>
export default {
  props: ['label', 'id','type', 'classes'],
  data(){
    return {};
  },
};
</script>
</code>```

Body:
The way i am defining my props;

<template>

    <vinput id="login_name" label="Phone number"></vinput>

                School slug
                <input type="text" id="email-phone" class="border py-2 rounded">

</template>

The way i am passing the props

<vinput id="login_name" label="Phone number"></vinput>

Please why is the browser rendering it this way:

  <input type="tex" class="border py-2 rounded">

School slug<input type="text"
id="email-phone" class="border py-2 rounded">

I was expecting interpolation in the label and input not in the div

====Edited====
vinput component

<template>

    {{ label }}
    <input :type="type ? type : 'tex'"
    :class="classes ? classes :''" class="border py-2 rounded"/>

</template>

Body:
Move your props:['label', 'id','type', 'classes'] away from data.

Those are totally different things.

<script>
export default {
  props: ['label', 'id','type', 'classes'],
  data(){
    return {};
  },
};
</script>


问:
Add custuom header according to the url path
I'm finding a way to add a custom header according to the url path in haproxy or traefik.

by example:
For a url: http://domain/toto/app, I want the reverse-proxy add a header: somekey=toto before it sends to the back service.

thanks

update : in my example, /toto is a dynamic value, it is only konwn at runtime.

答:
You have several options to add a header for the request to the backend service.

http-request add-header

http-request set-header

It depends if the header is already exist or not which directive you can use.


问:
Parameterizing rendering of parent component from child
I have a Parent component that contains a Child component. Suppose that the Parent wants to ask the Child its preferred background color and uses it to modify how the Parent renders itself:

```<code>class Child extends React.Component {
   favoriteColor = () => "red";
   render = () => (<span>Hello world</span>);
}

class Parent extends React.Component {
  render = () => {
    const child = (<Child />);
    return (
      <div style={{backgroundColor: child.favoriteColor()}}>
        {child}
      </div>
    );
  };
}
</code>```

What is the idiomatic way to do this in React?

In my real project, I have a Parent component that has a dynamic set of children. The Parent wraps each child in a React Bootstrap <Col>. But sometimes a child does not want to be rendered, and the correct thing would be to omit the <Col>. So the Parent component needs to be able to ask each child "do you have anything to render?"

答:
One way to do this depending on the circumstances is to declare Child.favoriteColor as static. As a static function it has no access to the instance's props or state.

```<code>class Child extends React.Component {
   static favoriteColor = () => "red";
   render = () => (<span>Hello world</span>);
}

class Parent extends React.Component {
  render = () => {
    return (
      <div style={{backgroundColor: Child.favoriteColor()}}>
        <Child />
      </div>
    );
  };
}
</code>```

Body:
I have a Parent component that contains a Child component. Suppose that the Parent wants to ask the Child its preferred background color and uses it to modify how the Parent renders itself:

class Child extends React.Component {
   favoriteColor = () => "red";
   render = () => (Hello world);
}

class Parent extends React.Component {
  render = () => {
    const child = (<Child />);
    return (

        {child}

    );
  };
}

What is the idiomatic way to do this in React?

In my real project, I have a Parent component that has a dynamic set of children. The Parent wraps each child in a React Bootstrap <Col>. But sometimes a child does not want to be rendered, and the correct thing would be to omit the <Col>. So the Parent component needs to be able to ask each child "do you have anything to render?"

Body:
One way to do this depending on the circumstances is to declare Child.favoriteColor as static. As a static function it has no access to the instance's props or state.

class Child extends React.Component {
   static favoriteColor = () => "red";
   render = () => (<span>Hello world</span>);
}

class Parent extends React.Component {
  render = () => {
    return (
      <div style={{backgroundColor: Child.favoriteColor()}}>
        <Child />
      </div>
    );
  };
}


问:
SQLAlchemy script works fine with sqlite3 but raises errors when used with MYSQL
SQLAlchemy script works fine with sqlite3 but when connected to MYSQL database it gives different errors like:

AttributeError: '_NoResultMetaData' object has no attribute '_indexes_for_keys'

sqlalchemy.exc.NoSuchColumnError: Could not locate column in row for column 'filters.id'

KeyError: Column('id', Integer(), table=, primary_key=True, nullable=False)

The functions works fine when running separately but when used with flask they raise above errors.

My DB models:

```<code>from sqlalchemy import Column, Integer, String, MetaData, Boolean, DateTime
from sqlalchemy.ext.declarative import declarative_base

import datetime

Base = declarative_base()

class ProfileData(Base):
    __tablename__ = 'profile_data'

    id = Column(Integer, primary_key=True)
    user_id = Column("user_id", Integer)
    user_profile_link = Column(String(100))
    username = Column(String(100))
    name = Column(String(100))
    is_verified = Column(Boolean)
    website = Column(String(100))
    bio = Column(String(1000))
    location = Column(String(100))
    created_at = Column(DateTime)
    followers = Column(Integer)
    following = Column(Integer)
    _datetime = Column(DateTime, default=datetime.datetime.utcnow)
</code>```

Thanks in advance.

答:
I would suggest to do this and this how usually do my setup

first init db object from SQLAlchemy

```<code>db = SQLAlchemy()
</code>```

then declare the model using db.model

```<code>class ProfileData(db.Model):

    __tablename__ = 'profile_data'

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column("user_id", db.Integer)
    user_profile_link = db.Column(db.String(100))
    username = db.Column(db.String(100))
</code>```

hope this fix your issue

Body:
SQLAlchemy script works fine with sqlite3 but when connected to MYSQL database it gives different errors like:

AttributeError: '_NoResultMetaData' object has no attribute '_indexes_for_keys'

sqlalchemy.exc.NoSuchColumnError: Could not locate column in row for column 'filters.id'

KeyError: Column('id', Integer(), table=, primary_key=True, nullable=False)

The functions works fine when running separately but when used with flask they raise above errors.

My DB models:

from sqlalchemy import Column, Integer, String, MetaData, Boolean, DateTime
from sqlalchemy.ext.declarative import declarative_base

import datetime

Base = declarative_base()

class ProfileData(Base):
    __tablename__ = 'profile_data'

    id = Column(Integer, primary_key=True)
    user_id = Column("user_id", Integer)
    user_profile_link = Column(String(100))
    username = Column(String(100))
    name = Column(String(100))
    is_verified = Column(Boolean)
    website = Column(String(100))
    bio = Column(String(1000))
    location = Column(String(100))
    created_at = Column(DateTime)
    followers = Column(Integer)
    following = Column(Integer)
    _datetime = Column(DateTime, default=datetime.datetime.utcnow)

Thanks in advance.

Body:
I would suggest to do this and this how usually do my setup

first init db object from SQLAlchemy

db = SQLAlchemy()

then declare the model using db.model

class ProfileData(db.Model):

    __tablename__ = 'profile_data'

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column("user_id", db.Integer)
    user_profile_link = db.Column(db.String(100))
    username = db.Column(db.String(100))

hope this fix your issue


问:
Java NullPointerException when there are no variables not initialiased
I am creating this login form using java swing and what I basically do is I get the values from the relevant JtextFields and send them onto another class. Thereafter I check it with the database records. However the program is always displaying a NullPointerException everytime I run it. I tested every variable and saw that none of them contain any Null Values at all.

This is the first method (in the LoginPage class) that gets the values from the JTextField

```<code>public void actionPerformed(ActionEvent e) {
String user=textField.getText();
String pass=String.valueOf(passwordField.getPassword());

//try{
//if((user!=null)&&(pass!=null)){
//  System.out.println("user is not null");

ui.sendLogin(user,pass);

//}else{}
//}catch(NullPointerException ex){
    //System.out.println("Entered catch block og view"+ex.getMessage());
//}
</code>```

}

Thereafter it calls this method (in class LoginController)

```<code>public void sendLogin(String user, String pass) {
try{
    System.out.println("values from sendLogin"+user+"pass"+pass);
    model.verifyUser(user,pass);
}catch(NullPointerException ex){
    System.out.println("Entered catch block os sendLogin"+ex);
    ex.printStackTrace();
}
}
</code>```

Finally the verifyUser method (in class LoginModel) checks it with the database

```<code> public void verifyUser(String user,String pass){
        String username="";
        String password="";
        String acc="";
         try{
             String sql="SELECT * FROM users";
             con1.getInstance();
             Statement st = con1.getConn().createStatement();
             ResultSet rs=st.executeQuery(sql);
             rs.next();
             username=rs.getString("username");
             password=rs.getString("password");
             acc=rs.getString("accountType");
             if(username.equals(user)&&password.equals(pass)){
                 System.out.println("Logged into the system");
                 global_username=username;
                 accountType=acc;
             }else{
                 System.out.println("Unsuccessful login"+username+user+password+pass);
             }
            st.execute(sql);
        } catch (SQLException s){
            System.out.println("SQL statement is not executed!"+s);
        }

}
</code>```

This is the Stack Trace

```<code>java.lang.NullPointerException
    at org.application.view.LoginController.sendLogin(LoginController.java:64)
    at org.application.view.LoginPage$2.actionPerformed(LoginPage.java:94)
user is not null
values from sendLoginapassabc
Entered catch block os sendLoginjava.lang.NullPointerException
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$000(Unknown Source)
    at java.awt.EventQueue$1.run(Unknown Source)
    at java.awt.EventQueue$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$2.run(Unknown Source)
    at java.awt.EventQueue$2.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
</code>```

答:
Measure, don't guess.

Why guess which variable is null? The stack trace gives you the line number where the exception happens. Fire up the debugger and set a breakpoint on line 64 of the LoginController class.

Body:
I am creating this login form using java swing and what I basically do is I get the values from the relevant JtextFields and send them onto another class. Thereafter I check it with the database records. However the program is always displaying a NullPointerException everytime I run it. I tested every variable and saw that none of them contain any Null Values at all.

This is the first method (in the LoginPage class) that gets the values from the JTextField

public void actionPerformed(ActionEvent e) {
String user=textField.getText();
String pass=String.valueOf(passwordField.getPassword());

//try{
//if((user!=null)&&(pass!=null)){
//  System.out.println("user is not null");

ui.sendLogin(user,pass);

//}else{}
//}catch(NullPointerException ex){
    //System.out.println("Entered catch block og view"+ex.getMessage());
//}

}

Thereafter it calls this method (in class LoginController)

public void sendLogin(String user, String pass) {
try{
    System.out.println("values from sendLogin"+user+"pass"+pass);
    model.verifyUser(user,pass);
}catch(NullPointerException ex){
    System.out.println("Entered catch block os sendLogin"+ex);
    ex.printStackTrace();
}
}

Finally the verifyUser method (in class LoginModel) checks it with the database

 public void verifyUser(String user,String pass){
        String username="";
        String password="";
        String acc="";
         try{
             String sql="SELECT * FROM users";
             con1.getInstance();
             Statement st = con1.getConn().createStatement();
             ResultSet rs=st.executeQuery(sql);
             rs.next();
             username=rs.getString("username");
             password=rs.getString("password");
             acc=rs.getString("accountType");
             if(username.equals(user)&&password.equals(pass)){
                 System.out.println("Logged into the system");
                 global_username=username;
                 accountType=acc;
             }else{
                 System.out.println("Unsuccessful login"+username+user+password+pass);
             }
            st.execute(sql);
        } catch (SQLException s){
            System.out.println("SQL statement is not executed!"+s);
        }

}

This is the Stack Trace

java.lang.NullPointerException
    at org.application.view.LoginController.sendLogin(LoginController.java:64)
    at org.application.view.LoginPage$2.actionPerformed(LoginPage.java:94)
user is not null
values from sendLoginapassabc
Entered catch block os sendLoginjava.lang.NullPointerException
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$000(Unknown Source)
    at java.awt.EventQueue$1.run(Unknown Source)
    at java.awt.EventQueue$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$2.run(Unknown Source)
    at java.awt.EventQueue$2.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)


问:
Give 404 response on DELETE in restful Spring Boot Reactive Controller
I am fairly new to Java and Spring Boot (coming from TypeScript) and
experimenting with a small restful CRUD Controller using the
reactive Spring Boot API.

There are many tutorials and examples out there but they all lack
proper response statuses, e.g. giving a 404 on DELETE when the
resource doesn't exist.

What I like to achieve is a DELETE handler which

returns "204 No Content" if the resource existed and was deleted successfully

returns "404 Not found" if the resource doesn't exist

A simple "I don't care about HTTP status" DELETE handler
looks like this:

  @DeleteMapping("/{id}")
  public Mono<Void> deletePet(@PathVariable String id) {
    return petRepository.deleteById(id);
  }
```
<p>This always gives status 200, even when there is no Pet for this ID.</p>
<p>I tried to use <code>petRepository.findById(id)</code> and <code>.defaultIfEmpty()</code>
in several ways to catch the 404 case, but without luck. E.g. with
this implementation I am getting always 204:</p>
<pre class="lang-java prettyprint-override"><code>  @DeleteMapping("/{id}")
  public Mono<ResponseEntity<Void>> deletePet(@PathVariable String id) {
    return petRepository.findById(id)
      .map(pet1 -> new ResponseEntity<Void>(HttpStatus.NO_CONTENT))
      .defaultIfEmpty(new ResponseEntity<Void>(HttpStatus.NOT_FOUND))
      .flatMap(res -> {
        return petRepository.deleteById(id)
          .map(v -> new ResponseEntity<Void>(HttpStatus.NO_CONTENT));
      });
  }
</code>```

I think I understand why this isn't working, because after the .defaultIfEmpty()
the Mono isn't empty anymore and the .flatMap will have something to work
on (the 404 response) so the deleteById() is executed. This returns an (obviously)
non empty Mono as well, so the status turns into NO_CONTENT again.

But all my (many) attempts to change this failed so I hope anyone has the right
solution for this problem.

Thanks! :)

答:
After some more research I found a solution:

  @DeleteMapping("/{id}")
  @ResponseStatus(HttpStatus.NO_CONTENT)
  public Mono<ResponseEntity<Void>> deletePet(@PathVariable String id) {
    return petRepository.findById(id)
      .defaultIfEmpty(new Pet())
      .flatMap(pet -> {
        if (null == pet.id) {
          return Mono.just(new ResponseEntity<Void>(HttpStatus.NOT_FOUND));
        }
        else {
          return petRepository.deleteById(id)
            .map(v -> new ResponseEntity<Void>(HttpStatus.NO_CONTENT));
        }
      });
  }
```

Now an empty Pet object is created when findById() gives an empty
result using defaultIfEmpty().

So the flatMap() gets either the Pet for the given ID or an empty
Pet. The latter is recognized by the fact that the id property is null
which is turned into a 404 response. In the other case the Pet is
deleted and 204 is returned. But note, that the .map() there isn't executed because of the empty deleteById() result. It's just necessary to satisfy the generic interface here. The 204 comes from the @ResponseStatus annotation.

So this is a possible solution - but it looks not very elegant to me (creating an empty Pet and having this no-op deleteById().map()).

If there is a better way to do this, please give your answer here.

Body:
I am fairly new to Java and Spring Boot (coming from TypeScript) and
experimenting with a small restful CRUD Controller using the
reactive Spring Boot API.

There are many tutorials and examples out there but they all lack
proper response statuses, e.g. giving a 404 on DELETE when the
resource doesn't exist.

What I like to achieve is a DELETE handler which

returns "204 No Content" if the resource existed and was deleted successfully

returns "404 Not found" if the resource doesn't exist

A simple "I don't care about HTTP status" DELETE handler
looks like this:

  @DeleteMapping("/{id}")
  public Mono<Void> deletePet(@PathVariable String id) {
    return petRepository.deleteById(id);
  }

This always gives status 200, even when there is no Pet for this ID.

I tried to use petRepository.findById(id) and .defaultIfEmpty()
in several ways to catch the 404 case, but without luck. E.g. with
this implementation I am getting always 204:

  @DeleteMapping("/{id}")
  public Mono<ResponseEntity<Void>> deletePet(@PathVariable String id) {
    return petRepository.findById(id)
      .map(pet1 -> new ResponseEntity<Void>(HttpStatus.NO_CONTENT))
      .defaultIfEmpty(new ResponseEntity<Void>(HttpStatus.NOT_FOUND))
      .flatMap(res -> {
        return petRepository.deleteById(id)
          .map(v -> new ResponseEntity<Void>(HttpStatus.NO_CONTENT));
      });
  }

I think I understand why this isn't working, because after the .defaultIfEmpty()
the Mono isn't empty anymore and the .flatMap will have something to work
on (the 404 response) so the deleteById() is executed. This returns an (obviously)
non empty Mono as well, so the status turns into NO_CONTENT again.

But all my (many) attempts to change this failed so I hope anyone has the right
solution for this problem.

Thanks! :)

Body:
After some more research I found a solution:

  @DeleteMapping("/{id}")
  @ResponseStatus(HttpStatus.NO_CONTENT)
  public Mono<ResponseEntity<Void>> deletePet(@PathVariable String id) {
    return petRepository.findById(id)
      .defaultIfEmpty(new Pet())
      .flatMap(pet -> {
        if (null == pet.id) {
          return Mono.just(new ResponseEntity<Void>(HttpStatus.NOT_FOUND));
        }
        else {
          return petRepository.deleteById(id)
            .map(v -> new ResponseEntity<Void>(HttpStatus.NO_CONTENT));
        }
      });
  }

Now an empty Pet object is created when findById() gives an empty
result using defaultIfEmpty().

So the flatMap() gets either the Pet for the given ID or an empty
Pet. The latter is recognized by the fact that the id property is null
which is turned into a 404 response. In the other case the Pet is
deleted and 204 is returned. But note, that the .map() there isn't executed because of the empty deleteById() result. It's just necessary to satisfy the generic interface here. The 204 comes from the @ResponseStatus annotation.

So this is a possible solution - but it looks not very elegant to me (creating an empty Pet and having this no-op deleteById().map()).

If there is a better way to do this, please give your answer here.


问:
How to fix "Error: Access token has expired or is not yet valid" when calling M365 API to fetch TodoTaskLists?
I'm trying to make GET request to ("me/todo/lists") endpoint for M365. It works initially after a fresh authentication and acquiring the access-token.

It even works when the access token is saved and the request is made after a couple of minutes, meaning that the code for using the saved access token works.

But when I try to call the API after sometime by storing the access token, I get the error: "Error: Access token has expired or is not yet valid"

Here's the code for making the request with the saved access token

```<code>public async getTaskLists(accessToken: string) {
        class MyAuthenticationProvider implements AuthenticationProvider {
            /**
             * This method will get called before every request to the msgraph server
             * This should return a Promise that resolves to an accessToken (in case of success) or rejects with error (in case of failure)
             * Basically this method will contain the implementation for getting and refreshing accessTokens
             */
            public async getAccessToken(): Promise<string> {
                return accessToken;
            }
        }
        const options = {
            authProvider: new MyAuthenticationProvider(), // An instance created from previous step
        };
        const client = Client.initWithMiddleware(options);

        //this part fetches task-lists from M365 and populates them into placed in a tree-view using registerTreeDataProvider

        let dataObject = [];
        let children: string[] = [];
        try {
            let taskList = await client.api("/me/todo/lists").get();
            console.log(taskList);
            } catch (error) {
            console.log(error);
            }
    }
}

</code>```

答: It is a short-lived access token that is only valid for an hour I think. You need to refresh the token before it expires to be able to make API calls successfully. That means you MUST save the refresh_token in order to do so. refresh_token can be used multiple times from my experiences which is good since it might break the connection if the refresh_token can only be used once and the refresh token response is lost due to network issues. However, it is good practice to save the last refresh_token returned from MS.

Body:
I'm trying to make GET request to ("me/todo/lists") endpoint for M365. It works initially after a fresh authentication and acquiring the access-token.

It even works when the access token is saved and the request is made after a couple of minutes, meaning that the code for using the saved access token works.

But when I try to call the API after sometime by storing the access token, I get the error: "Error: Access token has expired or is not yet valid"

Here's the code for making the request with the saved access token

public async getTaskLists(accessToken: string) {
        class MyAuthenticationProvider implements AuthenticationProvider {
            /**
             * This method will get called before every request to the msgraph server
             * This should return a Promise that resolves to an accessToken (in case of success) or rejects with error (in case of failure)
             * Basically this method will contain the implementation for getting and refreshing accessTokens
             */
            public async getAccessToken(): Promise<string> {
                return accessToken;
            }
        }
        const options = {
            authProvider: new MyAuthenticationProvider(), // An instance created from previous step
        };
        const client = Client.initWithMiddleware(options);

        //this part fetches task-lists from M365 and populates them into placed in a tree-view using registerTreeDataProvider

        let dataObject = [];
        let children: string[] = [];
        try {
            let taskList = await client.api("/me/todo/lists").get();
            console.log(taskList);
            } catch (error) {
            console.log(error);
            }
    }
}


问:
Delete and replace Nan values with mean of the rows in pandas dataframe
I have a very big DataFrame that looks like:

```<code>    c1   c2    c3
0  NaN  1.0   NaN
1  NaN  NaN   NaN
2  3.0  6.0   9.0
3  NaN  7.0  10.0
...
</code>```

I want to:

1- Delete the rows with all "Nan" values. like the second row in the sample.

2- Replace all the "Nan" values in other rows with the mean of the rows.

Note: in the rows, we have different "Nan" values.
could you please help me with that? Thanks.

Also, this link does not solve my question:
Pandas Dataframe: Replacing NaN with row average

Here is a sample of my DataFrame:

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame()
df['c1'] = [np.nan, np.nan, 3, np.nan]
df['c2'] = [1, np.nan, 6, 7]
df['c3'] = [np.nan, np.nan, 9, 10]
</code>```

Update:
When we don't want to consider the mean of all rows.
sample dataframe:

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame()
df['id'] = [1, 2, 3, 4, 5]
df['c1'] = [np.nan, np.nan, 3, np.nan, 5]
df['c2'] = [1, np.nan, 3, 11, 5]
df['c3'] = [1, np.nan, 3, 11, np.nan]
df['c4'] = [3, np.nan, 3, 11, 5]

output:
df = pd.DataFrame()
df['id'] = [1,  3, 4, 5]
df['c1'] = [ 5/3, 3, 11, 5]
df['c2'] = [1,  3, 11, 5]
df['c3'] = [1,  3, 11, 5]
df['c4'] = [3,  3, 11, 5]
df
</code>```

For this part, I don't want to consider the value of id for calculating the mean of row.

Body:
I have a very big DataFrame that looks like:

    c1   c2    c3
0  NaN  1.0   NaN
1  NaN  NaN   NaN
2  3.0  6.0   9.0
3  NaN  7.0  10.0
...

I want to:

1- Delete the rows with all "Nan" values. like the second row in the sample.

2- Replace all the "Nan" values in other rows with the mean of the rows.

Note: in the rows, we have different "Nan" values.
could you please help me with that? Thanks.

Also, this link does not solve my question:
Pandas Dataframe: Replacing NaN with row average

Here is a sample of my DataFrame:

import pandas as pd
import numpy as np

df = pd.DataFrame()
df['c1'] = [np.nan, np.nan, 3, np.nan]
df['c2'] = [1, np.nan, 6, 7]
df['c3'] = [np.nan, np.nan, 9, 10]

Update:
When we don't want to consider the mean of all rows.
sample dataframe:

import pandas as pd
import numpy as np

df = pd.DataFrame()
df['id'] = [1, 2, 3, 4, 5]
df['c1'] = [np.nan, np.nan, 3, np.nan, 5]
df['c2'] = [1, np.nan, 3, 11, 5]
df['c3'] = [1, np.nan, 3, 11, np.nan]
df['c4'] = [3, np.nan, 3, 11, 5]

output:
df = pd.DataFrame()
df['id'] = [1,  3, 4, 5]
df['c1'] = [ 5/3, 3, 11, 5]
df['c2'] = [1,  3, 11, 5]
df['c3'] = [1,  3, 11, 5]
df['c4'] = [3,  3, 11, 5]
df

For this part, I don't want to consider the value of id for calculating the mean of row.

Body:
how about this :

df = df.T.fillna(df.mean(axis=1)).T.dropna()
print(df)

output:

>>>
    c1   c2    c3
0  1.0  1.0   1.0
2  3.0  6.0   9.0
3  8.5  7.0  10.0


问:
Does a goroutine terminates after its Kubernetes container gets terminated?
For example, a container runs the main thread and a goroutine. The main thread encounters an issue and terminates. Note that for Golang, termination of the main thread does not result in auto-termination of the goroutine.

As the main thread has been terminated, will the container be killed and re-created? Or will the container continue running due to the goroutine is still running?

If the container will be killed and re-created after the main thread has been terminated, will this result in the goroutine getting terminated as well? Or will the goroutine continue running indefinitely and there is no easy way to terminate it now?

答:
If the main functions exists, the program is stopped. Nothing will run any more. It will release any used resource, like file descriptors and database connections.

In the below program, we will never see done being printed.

func main() {
    go func() {
        time.Sleep(time.Minute)
        fmt.Println("done")
    }()

    time.Sleep(time.Second * 3)
}
```
<p>https://play.golang.com/p/kPKZDdMcduS</p>
<p>If the program with that main function was the foreground process of the container, then the container shuts down as its standard behaviour with containers.</p>
<p>If you run the below example, you can observe how the container shuts down as soon as the sleep finishes.</p>
<pre class="lang-sh prettyprint-override"><code>$ docker run --name sample busybox sleep 3 && docker ps -a
CONTAINER ID   IMAGE     COMMAND     CREATED         STATUS                              PORTS     NAMES
fd4319261a0d   busybox   "sleep 3"   4 seconds ago   Exited (0) Less than a second ago             sample
</code>```

If the container, the program is running in, is shut down, it's more or less as if you would pull the plug of your computer. Nothing will run on your computer any more. It's impossible.

I would encourage you to create some test scenarios yourself and validate this.

Body:
If the main functions exists, the program is stopped. Nothing will run any more. It will release any used resource, like file descriptors and database connections.

In the below program, we will never see done being printed.

func main() {
    go func() {
        time.Sleep(time.Minute)
        fmt.Println("done")
    }()

    time.Sleep(time.Second * 3)
}

https://play.golang.com/p/kPKZDdMcduS

If the program with that main function was the foreground process of the container, then the container shuts down as its standard behaviour with containers.

If you run the below example, you can observe how the container shuts down as soon as the sleep finishes.

$ docker run --name sample busybox sleep 3 && docker ps -a
CONTAINER ID   IMAGE     COMMAND     CREATED         STATUS                              PORTS     NAMES
fd4319261a0d   busybox   "sleep 3"   4 seconds ago   Exited (0) Less than a second ago             sample

If the container, the program is running in, is shut down, it's more or less as if you would pull the plug of your computer. Nothing will run on your computer any more. It's impossible.

I would encourage you to create some test scenarios yourself and validate this.


问:
how to automatically update daily datetime in django
Hi I want to automatically update datetime daily in my database and put the today date as now then it show the subtract the start day and no and give me the delta is there any way to do this?</p>

答:
With TIMEZONE enabled in settings.py:

```<code>from django.utils import timezone

now = timezone.now()
</code>```

And without TIMEZONE set:

```<code>import datetime

now = datetime.datetime.now()
</code>```

And with any of above:

```<code>from datetime import timedelta

tommorow_with_same_hour = now + timedelta(days=1)
</code>```

Body:
With TIMEZONE enabled in settings.py:

from django.utils import timezone

now = timezone.now()

And without TIMEZONE set:

import datetime

now = datetime.datetime.now()

And with any of above:

from datetime import timedelta

tommorow_with_same_hour = now + timedelta(days=1)


问:
ANTLR how to discriminate two similar comments
In Antlr, if i have a rule for example:

```<code>> someRule : COMM TYPE arg EQUAL COMMENT_TEXT;
</code>```

where:

'COMM' : is '|'

'TYPE'           : is ('C'|'I'|'U')

'arg'            : can be 'number,number'(1,0) or only a number (1)

EQUALS           : '='

COMMENT_TEXT     : String

it would accept :

```<code>-   | C10,1 = comment
-   | U10 = comment
</code>```

In my grammar this rule is a DEFINITION.

When even one of these "token" is missing, I would like a generic comment:

```<code>|C1 comment   -> Generic Comment (EQUAL is missing)
|1 = comment  -> Generic comment ('type' is missing)
|C = Comment  -> Generic comment ('arg' is missing)
|comment      ....
</code>```

Grammar:

```<code>currLine : commentType | .....;

commentType: COMM (defComm | genComm);

defComm: TYPE arg EQUAL COMMENT_TEXT #defcom;
</code>```

how can i say that everything else is genComm?

genComm: ....

EDIT:

One possible solution can be:

```<code>genComment:
     : TYPE arg? EQUAL? COMMENT_TEXT?
     | arg EQUAL? COMMENT_TEXT?
     | EQUAL COMMENT_TEXT?
     | COMMENT_TEXT
     ;
</code>```

My Parser grammar:

```<code>parser grammar ParserComments;

options {
      tokenVocab = LexerComments;
  }

prog : (line? EOL)+;
line : comment;

comment: SINGLE_COMMENT (defComm | genericComment);

defComm: TYPE arg EQUAL COMMENT_TEXT;

arg : (argument1) (VIRGOLA argument2)?;

argument1    : numbers ;
argument2    : numbers ;
numbers      : NUMBER+ ;

genericComment
 : TYPE arg? EQUAL? COMMENT_TEXT?
 | arg EQUAL? COMMENT_TEXT?
 | EQUAL COMMENT_TEXT?
 | COMMENT_TEXT
 ;

// ------ general  ------
ignored : . ;
</code>```

My Lexer grammar:

```<code>lexer grammar LexerComments;

SINGLE_COMMENT : '|' -> pushMode(COMMENT);
NUMBER : [0-9];
VIRGOLA : ',';
WS  : [ \t] -> skip ;
EOL : [\r\n]+;

// ------------ Everything INSIDE a COMMENT ------------
mode COMMENT;
    COMMENT_NUMBER  : NUMBER -> type(NUMBER);
    COMMENT_VIRGOLA : VIRGOLA -> type(VIRGOLA);

    TYPE : 'I'| 'U'| 'Q';

    EQUAL : '=';

    COMMENT_TEXT: ('a'..'z' | 'A'..'Z')+;

    WS_1        : [ \t] -> skip ;
    COMMENT_EOL : EOL -> type(EOL);
</code>```

but parsing:

| Q1,0 = text

I get a full context and ambiguity error in BaseErrorListener.

答:
A couple of changes seem to give you the results you want:

1 - you need to popMode out of COMMENT mode when you encounter an EOL:

```<code>COMMENT_EOL: EOL   -> type(EOL),popMode;
</code>```

2 - you can use the following for your genericComment rule:

```<code>genericComment: .*?;
</code>```

Basically says, match anything (but don't be greedy), so it won't match the EOL token.  As a result it will take any token up to the next EOL token.

BTW... your ignored rule is purely extraneous.  Parser rules are evaluated through a recursive descent calling structure.  If a rule is not a start rule, it can only be accessed by being referenced by another rule.

(It's not uncommon to have a final lexer rule that matches . (i.e. anything) to catch anything that prior Lexer rules did not match.  But that works because Lexer rules are not evaluated by a recursive descent algorithm)

Re: Lexer rules

The first step in ANTLR parsing your input, is to convert your input stream of characters into a stream of tokens. This process uses you Lexer rules (the rules that begin with a capital letter). At this time, the parser rules are irrelevant, the parser rules act on the stream of tokens that the Lexer produces.

When the Lexer (aka tokenizer), tokenizes your input characters, it will evaluate you input against all of your Lexer rules. When more than 1 rule can match your input, then there are two "tie-breaker" strategies:

The Lexer rule that matches the longest stream of input characters with take top priority.
If there is more than one rule that matches the same (longest) sequence of characters, then the rule that appears first "wins"

Body:
In Antlr, if i have a rule for example:

> someRule : COMM TYPE arg EQUAL COMMENT_TEXT;

where:

'COMM' : is '|'

'TYPE'           : is ('C'|'I'|'U')

'arg'            : can be 'number,number'(1,0) or only a number (1)

EQUALS           : '='

COMMENT_TEXT     : String

it would accept :

-   | C10,1 = comment
-   | U10 = comment

In my grammar this rule is a DEFINITION.

When even one of these "token" is missing, I would like a generic comment:

|C1 comment   -> Generic Comment (EQUAL is missing)
|1 = comment  -> Generic comment ('type' is missing)
|C = Comment  -> Generic comment ('arg' is missing)
|comment      ....

Grammar:

currLine : commentType | .....;

commentType: COMM (defComm | genComm);

defComm: TYPE arg EQUAL COMMENT_TEXT #defcom;

how can i say that everything else is genComm?

genComm: ....

EDIT:

One possible solution can be:

genComment:
     : TYPE arg? EQUAL? COMMENT_TEXT?
     | arg EQUAL? COMMENT_TEXT?
     | EQUAL COMMENT_TEXT?
     | COMMENT_TEXT
     ;

My Parser grammar:

parser grammar ParserComments;

options {
      tokenVocab = LexerComments;
  }

prog : (line? EOL)+;
line : comment;

comment: SINGLE_COMMENT (defComm | genericComment);

defComm: TYPE arg EQUAL COMMENT_TEXT;

arg : (argument1) (VIRGOLA argument2)?;

argument1    : numbers ;
argument2    : numbers ;
numbers      : NUMBER+ ;

genericComment
 : TYPE arg? EQUAL? COMMENT_TEXT?
 | arg EQUAL? COMMENT_TEXT?
 | EQUAL COMMENT_TEXT?
 | COMMENT_TEXT
 ;

// ------ general  ------
ignored : . ;

My Lexer grammar:

lexer grammar LexerComments;

SINGLE_COMMENT : '|' -> pushMode(COMMENT);
NUMBER : [0-9];
VIRGOLA : ',';
WS  : [ \t] -> skip ;
EOL : [\r\n]+;

// ------------ Everything INSIDE a COMMENT ------------
mode COMMENT;
    COMMENT_NUMBER  : NUMBER -> type(NUMBER);
    COMMENT_VIRGOLA : VIRGOLA -> type(VIRGOLA);

    TYPE : 'I'| 'U'| 'Q';

    EQUAL : '=';

    COMMENT_TEXT: ('a'..'z' | 'A'..'Z')+;

    WS_1        : [ \t] -> skip ;
    COMMENT_EOL : EOL -> type(EOL);

but parsing:

| Q1,0 = text

I get a full context and ambiguity error in BaseErrorListener.

Body:
A couple of changes seem to give you the results you want:

1 - you need to popMode out of COMMENT mode when you encounter an EOL:

COMMENT_EOL: EOL   -> type(EOL),popMode;

2 - you can use the following for your genericComment rule:

genericComment: .*?;

Basically says, match anything (but don't be greedy), so it won't match the EOL token.  As a result it will take any token up to the next EOL token.

BTW... your ignored rule is purely extraneous.  Parser rules are evaluated through a recursive descent calling structure.  If a rule is not a start rule, it can only be accessed by being referenced by another rule.

(It's not uncommon to have a final lexer rule that matches . (i.e. anything) to catch anything that prior Lexer rules did not match.  But that works because Lexer rules are not evaluated by a recursive descent algorithm)

Re: Lexer rules

The first step in ANTLR parsing your input, is to convert your input stream of characters into a stream of tokens. This process uses you Lexer rules (the rules that begin with a capital letter). At this time, the parser rules are irrelevant, the parser rules act on the stream of tokens that the Lexer produces.

When the Lexer (aka tokenizer), tokenizes your input characters, it will evaluate you input against all of your Lexer rules. When more than 1 rule can match your input, then there are two "tie-breaker" strategies:

The Lexer rule that matches the longest stream of input characters with take top priority.
If there is more than one rule that matches the same (longest) sequence of characters, then the rule that appears first "wins"


问:
URL Rewrite in PHP like in Smarty Template
I am banging my head from a couple of days to use the URL rewriting for a core php website. Previously the website was developed using smarty, but due to some limitations, I am redoing it in core PHP. The problem is that smarty is using some templates code to create the Pretty URL's which I am not able to do in core PHP. Like in this example.
http://amitgharat.blogspot.com/

Is any body came across this kind of problem and save me, or any idea or suggestion please. I will be really thank full.

Regards,

答:
I think what you need need is a "front controller" ref: http://www.phppatterns.com/docs/design/the_front_controller_and_php

Essentially what happens is this:

Assuming your site will have this url structure:

http://www.example.com/page/1

A .htaccess file redirects all requests to a file (index.php). You can of course write your .htaccess file so that files that do exist with certain extensions (.jpg etc) are not redirected.

In your index.php you can access the "page/1" part from your url via the $_SERVER['PHP_SELF'] variable.

When you then do from there is up to you. For example, you might break that up into an array using explode(),  do some more parsing and finally dispatch the requested call.

If you haven't already looked at the mvc pattern, I reckon it would be worth while looking at that.

Having said that, there are quite a few nice PHP frameworks out there (code igniter, symfony, etc) which can allow you to code up that site quickly.


问:
HTML to PDF with cyrillic characters
I'm making a Spring Boot application. I want to generate PDF from HTML code:

```<code>        String htmlString = "<!DOCTYPE html>\n" +
                "<html lang=\"ru\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\"/>\n" +
                "    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"/>\n" +
                "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"/>\n" +
                "</head>\n" +
                "<body>\n" +
                "    <h3>ПРЕДСТАВЛЕНИЕ</h3>\n" +
                "</body>\n" +
                "</html>";

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        String path = FileSystemView.getFileSystemView().getDefaultDirectory().getPath() + "/A.pdf";
        OutputStream outputStream = new FileOutputStream(path);

        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(htmlString);
        renderer.layout();
        renderer.createPDF(outputStream);

        byteArrayOutputStream.writeTo(outputStream);
</code>```

As you can see there is a h3 tag with cyrillic symbols. The problem is that after conversion and  saving the symbols are not presented in PDF (it's simply empty, because there is nothing more in html code to be visible). Other symbols are being displayed properly btw.

For html-to-pdf conversion i use:

```<code><dependency>
    <groupId>org.xhtmlrenderer</groupId>
    <artifactId>flying-saucer-pdf-itext5</artifactId>
    <version>9.0.1</version>
</dependency>
</code>```

I suppose there is a problem with charset, fonts etc. How can I fix it?

答:
This worked for me!

```<code>public static void main(String[] args) throws DocumentException, IOException, SAXException, ParserConfigurationException {
        String htmlString = "<!DOCTYPE html>\n" + "<html lang=\"ru\">\n" + "<head>\n"
                + "    <meta charset=\"UTF-8\"/>\n" + "    <meta http-equiv=\"Content-Type\" content=\"text/html\"/>\n"
                + "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"/>\n"
                + "    <style type='text/css'> "
                + "        * { font-family: Verdana; }/n"
                + "    </style>/n"
                + "</head>\n"
                + "<body>\n" + "    <h3>ПРЕДСТАВЛЕНИЕ</h3>\n" + "</body>\n" + "</html>";

    String path = FileSystemView.getFileSystemView().getDefaultDirectory().getPath() + "/A.pdf";
    OutputStream os = new FileOutputStream(path);
    ITextRenderer renderer = new ITextRenderer();
    renderer.getFontResolver().addFont("c:/windows/fonts/verdana.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
    renderer.setDocumentFromString(htmlString);
    renderer.layout();
    renderer.createPDF(os);
    os.close();
}
</code>```

I think the trick is to add the CSS to the HTML and the font must match what you set on the PDF.

Title: HTML to PDF with cyrillic characters

Body:
I'm making a Spring Boot application. I want to generate PDF from HTML code:

        String htmlString = "<!DOCTYPE html>\n" +
                "\n" +
                "\n" +
                "    <meta charset=\"UTF-8\"/>\n" +
                "    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"/>\n" +
                "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"/>\n" +
                "\n" +
                "\n" +
                "
ПРЕДСТАВЛЕНИЕ
\n" +
                "\n" +
                "";

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        String path = FileSystemView.getFileSystemView().getDefaultDirectory().getPath() + "/A.pdf";
        OutputStream outputStream = new FileOutputStream(path);

        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(htmlString);
        renderer.layout();
        renderer.createPDF(outputStream);

        byteArrayOutputStream.writeTo(outputStream);

As you can see there is a h3 tag with cyrillic symbols. The problem is that after conversion and  saving the symbols are not presented in PDF (it's simply empty, because there is nothing more in html code to be visible). Other symbols are being displayed properly btw.

For html-to-pdf conversion i use:

<dependency>
    <groupId>org.xhtmlrenderer</groupId>
    <artifactId>flying-saucer-pdf-itext5</artifactId>
    <version>9.0.1</version>
</dependency>

I suppose there is a problem with charset, fonts etc. How can I fix it?

Body:
This worked for me!

public static void main(String[] args) throws DocumentException, IOException, SAXException, ParserConfigurationException {
        String htmlString = "<!DOCTYPE html>\n" + "<html lang=\"ru\">\n" + "<head>\n"
                + "    <meta charset=\"UTF-8\"/>\n" + "    <meta http-equiv=\"Content-Type\" content=\"text/html\"/>\n"
                + "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"/>\n"
                + "    <style type='text/css'> "
                + "        * { font-family: Verdana; }/n"
                + "    </style>/n"
                + "</head>\n"
                + "<body>\n" + "    <h3>ПРЕДСТАВЛЕНИЕ</h3>\n" + "</body>\n" + "</html>";

    String path = FileSystemView.getFileSystemView().getDefaultDirectory().getPath() + "/A.pdf";
    OutputStream os = new FileOutputStream(path);
    ITextRenderer renderer = new ITextRenderer();
    renderer.getFontResolver().addFont("c:/windows/fonts/verdana.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
    renderer.setDocumentFromString(htmlString);
    renderer.layout();
    renderer.createPDF(os);
    os.close();
}

I think the trick is to add the CSS to the HTML and the font must match what you set on the PDF.


问:
Javascript Search multiple fields in JSON
I have the following javascript search function

```<code>function findMatches(srchFor, srchList, keyobj) {
        return srchList.filter(srchList => {
            const regex = new RegExp(srchFor, 'gi');
            return srchList[keyobj].match(regex);
        });
    }
</code>```

Example Json object to search;

```<code>    Customers = {"entity": [{
            "Id": "ACB123",
            "OrderId": 0,
            "EntityType": "CU",
            "Name": "ABC Company",
            "Address1": "123 Main Street",
            "Address2": null,
            "City": "CROCKETT",
            "State": "CA",
            "Zip": "94525",
            "Country": "USA",
            "Phone": null,
            "Email": null,
            "Contact": null,
            "IdCodeQual": null,
            "IdCode": null,
            "LastUpdate": "2021-04-06T17:31:02",
            "Attrib01": null,
            "Attrib02": null,
            "Attrib03": null,
            "Attrib04": null,
            "Attrib05": null
        },
        {
            "Id": "WFCH",
            "OrderId": 0,
            "EntityType": "CU",
            "Name": "World's Finest Company",
            "Address1": "100 State Street",
            "Address2": null,
            "City": "Chicago",
            "State": "IL",
            "Zip": "60632",
            "Country": "USA",
            "Phone": "773-555-1200",
            "Email": null,
            "Contact": null,
            "IdCodeQual": null,
            "IdCode": null,
            "LastUpdate": "2016-09-20T12:59:25",
            "Attrib01": null,
            "Attrib02": null,
            "Attrib03": null,
            "Attrib04": null,
            "Attrib05": null
        }
    ]
}
</code>```

This function works fine as is for searching one field with usage as

```<code>var result = findMatches('ABC',Customers,'Id')
</code>```

What I would like to be able to do is pass in more than one field to search as such

```<code>var result = findMatches('ABC',Customers,['Id','Name'])
</code>```

so I can search both the name and Id fields for a match without having to have an explicitly defined search.  I'd like the same function to work for

```<code>var result = findMatches('ABC',Customers,['City','Address1'])
</code>```

答:
This solution filters array depending on several fields</p>
```<code>const Customers = {
    entity: [
        {
            Id: "ACB123",
            OrderId: 0,
            EntityType: "CU",
            Name: "ABC Company",
            Address1: "123 Main Street",
            Address2: null,
            City: "CROCKETT",
            State: "CA",
            Zip: "94525",
            Country: "USA",
            Phone: null,
            Email: null,
            Contact: null,
            IdCodeQual: null,
            IdCode: null,
            LastUpdate: "2021-04-06T17:31:02",
            Attrib01: null,
            Attrib02: null,
            Attrib03: null,
            Attrib04: null,
            Attrib05: null,
        },
        {
            Id: "WFCH",
            OrderId: 0,
            EntityType: "CU",
            Name: "World's Finest Company",
            Address1: "100 State Street",
            Address2: null,
            City: "Chicago",
            State: "IL",
            Zip: "60632",
            Country: "USA",
            Phone: "773-555-1200",
            Email: null,
            Contact: null,
            IdCodeQual: null,
            IdCode: null,
            LastUpdate: "2016-09-20T12:59:25",
            Attrib01: null,
            Attrib02: null,
            Attrib03: null,
            Attrib04: null,
            Attrib05: null,
        },
    ],
};

//Returns what recieves
const pass = (input) => input;

const findInArray = (array, searchRegExp, fields) => {
    return array.filter((item) => {
        // returs true if at least one of fields value match to regexp
        return fields.map((field) => searchRegExp.test(item[field])).some(pass);
    });
};

console.log(findInArray(Customers.entity, /ACB/, ["Id", "Name"]));
</code>```

Body:
I have the following javascript search function

function findMatches(srchFor, srchList, keyobj) {
        return srchList.filter(srchList => {
            const regex = new RegExp(srchFor, 'gi');
            return srchList[keyobj].match(regex);
        });
    }

Example Json object to search;

    Customers = {"entity": [{
            "Id": "ACB123",
            "OrderId": 0,
            "EntityType": "CU",
            "Name": "ABC Company",
            "Address1": "123 Main Street",
            "Address2": null,
            "City": "CROCKETT",
            "State": "CA",
            "Zip": "94525",
            "Country": "USA",
            "Phone": null,
            "Email": null,
            "Contact": null,
            "IdCodeQual": null,
            "IdCode": null,
            "LastUpdate": "2021-04-06T17:31:02",
            "Attrib01": null,
            "Attrib02": null,
            "Attrib03": null,
            "Attrib04": null,
            "Attrib05": null
        },
        {
            "Id": "WFCH",
            "OrderId": 0,
            "EntityType": "CU",
            "Name": "World's Finest Company",
            "Address1": "100 State Street",
            "Address2": null,
            "City": "Chicago",
            "State": "IL",
            "Zip": "60632",
            "Country": "USA",
            "Phone": "773-555-1200",
            "Email": null,
            "Contact": null,
            "IdCodeQual": null,
            "IdCode": null,
            "LastUpdate": "2016-09-20T12:59:25",
            "Attrib01": null,
            "Attrib02": null,
            "Attrib03": null,
            "Attrib04": null,
            "Attrib05": null
        }
    ]
}

This function works fine as is for searching one field with usage as

var result = findMatches('ABC',Customers,'Id')

What I would like to be able to do is pass in more than one field to search as such

var result = findMatches('ABC',Customers,['Id','Name'])

so I can search both the name and Id fields for a match without having to have an explicitly defined search.  I'd like the same function to work for

var result = findMatches('ABC',Customers,['City','Address1'])

Body:
This solution filters array depending on several fields

const Customers = {
    entity: [
        {
            Id: "ACB123",
            OrderId: 0,
            EntityType: "CU",
            Name: "ABC Company",
            Address1: "123 Main Street",
            Address2: null,
            City: "CROCKETT",
            State: "CA",
            Zip: "94525",
            Country: "USA",
            Phone: null,
            Email: null,
            Contact: null,
            IdCodeQual: null,
            IdCode: null,
            LastUpdate: "2021-04-06T17:31:02",
            Attrib01: null,
            Attrib02: null,
            Attrib03: null,
            Attrib04: null,
            Attrib05: null,
        },
        {
            Id: "WFCH",
            OrderId: 0,
            EntityType: "CU",
            Name: "World's Finest Company",
            Address1: "100 State Street",
            Address2: null,
            City: "Chicago",
            State: "IL",
            Zip: "60632",
            Country: "USA",
            Phone: "773-555-1200",
            Email: null,
            Contact: null,
            IdCodeQual: null,
            IdCode: null,
            LastUpdate: "2016-09-20T12:59:25",
            Attrib01: null,
            Attrib02: null,
            Attrib03: null,
            Attrib04: null,
            Attrib05: null,
        },
    ],
};

//Returns what recieves
const pass = (input) => input;

const findInArray = (array, searchRegExp, fields) => {
    return array.filter((item) => {
        // returs true if at least one of fields value match to regexp
        return fields.map((field) => searchRegExp.test(item[field])).some(pass);
    });
};

console.log(findInArray(Customers.entity, /ACB/, ["Id", "Name"]));