问:
AttributeError: module 'sipbuild.api' has no attribute 'prepare_metadata_for_build_wheel' for PyQt5 5.15.0
A program I am trying to install requires the installation of PyQt5 5.15.0 , which gives me this error. The odd thing is that the installation works fine for the latest version of PyQt5 (5.15.2), but this program requires 5.15.0 specifically.

Command Output:

```<code>Collecting PyQt5==5.15.0
  Using cached PyQt5-5.15.0.tar.gz (3.3 MB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
    Preparing wheel metadata ... error
    ERROR: Command errored out with exit status 1:
     command: 'c:\users\mshal\appdata\local\programs\python\python39\python.exe' 'C:\Users\mshal\AppData\Roaming\Python\Python39\site-packages\pip\_vendor\pep517\_in_process.py' prepare_metadata_for_build_wheel 'C:\Users\mshal\AppData\Local\Temp\tmp41s11ev6'
         cwd: C:\Users\mshal\AppData\Local\Temp\pip-install-sfw90hvc\pyqt5_e2cc46859b554da7b84798abae5378ba
    Complete output (31 lines):
    Traceback (most recent call last):
      File "C:\Users\mshal\AppData\Roaming\Python\Python39\site-packages\pip\_vendor\pep517\_in_process.py", line 126, in prepare_metadata_for_build_wheel
        hook = backend.prepare_metadata_for_build_wheel
    AttributeError: module 'sipbuild.api' has no attribute 'prepare_metadata_for_build_wheel'

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "C:\Users\mshal\AppData\Roaming\Python\Python39\site-packages\pip\_vendor\pep517\_in_process.py", line 280, in <module>
        main()
      File "C:\Users\mshal\AppData\Roaming\Python\Python39\site-packages\pip\_vendor\pep517\_in_process.py", line 263, in main
        json_out['return_val'] = hook(**hook_input['kwargs'])
      File "C:\Users\mshal\AppData\Roaming\Python\Python39\site-packages\pip\_vendor\pep517\_in_process.py", line 130, in prepare_metadata_for_build_wheel
        return _get_wheel_metadata_from_wheel(backend, metadata_directory,
      File "C:\Users\mshal\AppData\Roaming\Python\Python39\site-packages\pip\_vendor\pep517\_in_process.py", line 159, in _get_wheel_metadata_from_wheel
        whl_basename = backend.build_wheel(metadata_directory, config_settings)
      File "C:\Users\mshal\AppData\Local\Temp\pip-build-env-nnx_yu09\overlay\Lib\site-packages\sipbuild\api.py", line 51, in build_wheel
        project = AbstractProject.bootstrap('pep517')
      File "C:\Users\mshal\AppData\Local\Temp\pip-build-env-nnx_yu09\overlay\Lib\site-packages\sipbuild\abstract_project.py", line 83, in bootstrap
        project.setup(pyproject, tool, tool_description)
      File "C:\Users\mshal\AppData\Local\Temp\pip-build-env-nnx_yu09\overlay\Lib\site-packages\sipbuild\project.py", line 479, in setup
        self.apply_user_defaults(tool)
      File "project.py", line 62, in apply_user_defaults
        super().apply_user_defaults(tool)
      File "C:\Users\mshal\AppData\Local\Temp\pip-build-env-nnx_yu09\overlay\Lib\site-packages\pyqtbuild\project.py", line 79, in apply_user_defaults
        super().apply_user_defaults(tool)
      File "C:\Users\mshal\AppData\Local\Temp\pip-build-env-nnx_yu09\overlay\Lib\site-packages\sipbuild\project.py", line 225, in apply_user_defaults
        self.builder.apply_user_defaults(tool)
      File "C:\Users\mshal\AppData\Local\Temp\pip-build-env-nnx_yu09\overlay\Lib\site-packages\pyqtbuild\builder.py", line 66, in apply_user_defaults
        raise PyProjectOptionException('qmake',
    sipbuild.pyproject.PyProjectOptionException
    ----------------------------------------
ERROR: Command errored out with exit status 1: 'c:\users\mshal\appdata\local\programs\python\python39\python.exe' 'C:\Users\mshal\AppData\Roaming\Python\Python39\site-packages\pip\_vendor\pep517\_in_process.py' prepare_metadata_for_build_wheel 'C:\Users\mshal\AppData\Local\Temp\tmp41s11ev6' Check the logs for full command output.
</code>```

I am on the latest version of pip. Any ideas on the root cause of this issue?

答:
For MacOS users.

I am on Apple M1 silicon using Python 3.9.8. What worked for me was @Apaul's comment in the original question section. Install pyqt5-sip prior to pyqt5.

I also have an Intel Mac and on that machine, I do not need to do this.

Body:
A program I am trying to install requires the installation of PyQt5 5.15.0 , which gives me this error. The odd thing is that the installation works fine for the latest version of PyQt5 (5.15.2), but this program requires 5.15.0 specifically.

Command Output:

Collecting PyQt5==5.15.0
  Using cached PyQt5-5.15.0.tar.gz (3.3 MB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
    Preparing wheel metadata ... error
    ERROR: Command errored out with exit status 1:
     command: 'c:\users\mshal\appdata\local\programs\python\python39\python.exe' 'C:\Users\mshal\AppData\Roaming\Python\Python39\site-packages\pip\_vendor\pep517\_in_process.py' prepare_metadata_for_build_wheel 'C:\Users\mshal\AppData\Local\Temp\tmp41s11ev6'
         cwd: C:\Users\mshal\AppData\Local\Temp\pip-install-sfw90hvc\pyqt5_e2cc46859b554da7b84798abae5378ba
    Complete output (31 lines):
    Traceback (most recent call last):
      File "C:\Users\mshal\AppData\Roaming\Python\Python39\site-packages\pip\_vendor\pep517\_in_process.py", line 126, in prepare_metadata_for_build_wheel
        hook = backend.prepare_metadata_for_build_wheel
    AttributeError: module 'sipbuild.api' has no attribute 'prepare_metadata_for_build_wheel'

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "C:\Users\mshal\AppData\Roaming\Python\Python39\site-packages\pip\_vendor\pep517\_in_process.py", line 280, in <module>
        main()
      File "C:\Users\mshal\AppData\Roaming\Python\Python39\site-packages\pip\_vendor\pep517\_in_process.py", line 263, in main
        json_out['return_val'] = hook(**hook_input['kwargs'])
      File "C:\Users\mshal\AppData\Roaming\Python\Python39\site-packages\pip\_vendor\pep517\_in_process.py", line 130, in prepare_metadata_for_build_wheel
        return _get_wheel_metadata_from_wheel(backend, metadata_directory,
      File "C:\Users\mshal\AppData\Roaming\Python\Python39\site-packages\pip\_vendor\pep517\_in_process.py", line 159, in _get_wheel_metadata_from_wheel
        whl_basename = backend.build_wheel(metadata_directory, config_settings)
      File "C:\Users\mshal\AppData\Local\Temp\pip-build-env-nnx_yu09\overlay\Lib\site-packages\sipbuild\api.py", line 51, in build_wheel
        project = AbstractProject.bootstrap('pep517')
      File "C:\Users\mshal\AppData\Local\Temp\pip-build-env-nnx_yu09\overlay\Lib\site-packages\sipbuild\abstract_project.py", line 83, in bootstrap
        project.setup(pyproject, tool, tool_description)
      File "C:\Users\mshal\AppData\Local\Temp\pip-build-env-nnx_yu09\overlay\Lib\site-packages\sipbuild\project.py", line 479, in setup
        self.apply_user_defaults(tool)
      File "project.py", line 62, in apply_user_defaults
        super().apply_user_defaults(tool)
      File "C:\Users\mshal\AppData\Local\Temp\pip-build-env-nnx_yu09\overlay\Lib\site-packages\pyqtbuild\project.py", line 79, in apply_user_defaults
        super().apply_user_defaults(tool)
      File "C:\Users\mshal\AppData\Local\Temp\pip-build-env-nnx_yu09\overlay\Lib\site-packages\sipbuild\project.py", line 225, in apply_user_defaults
        self.builder.apply_user_defaults(tool)
      File "C:\Users\mshal\AppData\Local\Temp\pip-build-env-nnx_yu09\overlay\Lib\site-packages\pyqtbuild\builder.py", line 66, in apply_user_defaults
        raise PyProjectOptionException('qmake',
    sipbuild.pyproject.PyProjectOptionException
    ----------------------------------------
ERROR: Command errored out with exit status 1: 'c:\users\mshal\appdata\local\programs\python\python39\python.exe' 'C:\Users\mshal\AppData\Roaming\Python\Python39\site-packages\pip\_vendor\pep517\_in_process.py' prepare_metadata_for_build_wheel 'C:\Users\mshal\AppData\Local\Temp\tmp41s11ev6' Check the logs for full command output.

I am on the latest version of pip. Any ideas on the root cause of this issue?


来源: stackexchange

问:
Getting error "connect ECONNREFUSED 127.0.0.1:3306" while connecting to mysql
I'm new to nodeJs and trying to develop my first application. I installed mysql package through npm, It got installed and I can see a successful entry of it in package.json. However, when I'm trying to connect to mysql server, it gives me this error connect ECONNREFUSED 127.0.0.1:3306. I searched for this issue on StackOverflow and the other users who had the very same issue got it running by adding an entry socketPath: '/var/run/mysqld/mysqld.sock' to the configuration object. But when I added this to my configuration object, I got a new error connect ENOENT /var/run/mysqld/mysqld.sock.

Here's the code by which I'm trying to connect to the server

```<code>var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'blog',
    socketPath: '/var/run/mysqld/mysqld.sock'
});

connection.connect();
module.exports = router;
</code>```

I'm using a Windows machine and had mysql installed before via XAMPP package. Can this be the reason behind the connection failure?

答: Check the password inserted, usually it should be "password".</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm new to nodeJs and trying to develop my first application. I installed mysql package through npm, It got installed and I can see a successful entry of it in package.json. However, when I'm trying to connect to mysql server, it gives me this error connect ECONNREFUSED 127.0.0.1:3306. I searched for this issue on StackOverflow and the other users who had the very same issue got it running by adding an entry socketPath: '/var/run/mysqld/mysqld.sock' to the configuration object. But when I added this to my configuration object, I got a new error connect ENOENT /var/run/mysqld/mysqld.sock.

Here's the code by which I'm trying to connect to the server

var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'blog',
    socketPath: '/var/run/mysqld/mysqld.sock'
});

connection.connect();
module.exports = router;

I'm using a Windows machine and had mysql installed before via XAMPP package. Can this be the reason behind the connection failure?

ContentLicense: CC BY-SA 4.0


问:
Parameter 'e' implicitly has an 'any' type React TypeScript
I'm trying to implement this in a React TypeScript File:

```<code>export class MainInfo extends Component<IProps>{
  continue = e => {
    e.preventDefault();
    this.props.nextStep();
  };

  render() {
    const { values1, handleChange } = this.props
    return (
      <div>
        <Formik
          validateOnChange={true}
          validationSchema={validationSchema}
          initialValues={{ Title: '', ActivationDate: '', ExpirationDate: '', DirectManager: '', HRBP: '' }}
          onSubmit={(data) => {
            console.log(data)
          }}
</code>```

But I receive a Parameter 'e' implicitly has an 'any' type React TypeScript error. How should I fix this?

Edit: I have these in another file that Im using them here as props

```<code>nextStep = () => {
    const { step } = this.state;
    this.setState({
      step: step + 1
    });
  };

  // Go back to prev step
  prevStep = () => {
    const { step } = this.state;
    this.setState({
      step: step - 1
    });
  };

  // Handle fields change
  handleChange = input => e => {
    this.setState({ [input]: e.target.value });
  };
</code>```

答:
If you want to handle a form submission using onSubmit handler, give React.FormEvent<HTMLFormElement> type to e:

```<code>function MyComponent(props) {
  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
  }

  return (
      <form onSubmit={handleSubmit}>
        { props.children }
      </form>
    )
}
</code>```

Body:
I'm trying to implement this in a React TypeScript File:

export class MainInfo extends Component<IProps>{
  continue = e => {
    e.preventDefault();
    this.props.nextStep();
  };

  render() {
    const { values1, handleChange } = this.props
    return (

        <Formik
          validateOnChange={true}
          validationSchema={validationSchema}
          initialValues={{ Title: '', ActivationDate: '', ExpirationDate: '', DirectManager: '', HRBP: '' }}
          onSubmit={(data) => {
            console.log(data)
          }}

But I receive a Parameter 'e' implicitly has an 'any' type React TypeScript error. How should I fix this?

Edit: I have these in another file that Im using them here as props

nextStep = () => {
    const { step } = this.state;
    this.setState({
      step: step + 1
    });
  };

  // Go back to prev step
  prevStep = () => {
    const { step } = this.state;
    this.setState({
      step: step - 1
    });
  };

  // Handle fields change
  handleChange = input => e => {
    this.setState({ [input]: e.target.value });
  };

Body:
If you want to handle a form submission using onSubmit handler, give React.FormEvent<HTMLFormElement> type to e:

function MyComponent(props) {
  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
  }

  return (
      <form onSubmit={handleSubmit}>
        { props.children }
      </form>
    )
}


问:
How to get highcharts dates in the x axis?
Is there a standard way to get dates on the x-axis for Highcharts?  Can't find it in their documentation: https://api.highcharts.com/highcharts/xAxis.type

When my time range is large enough, it shows dates.  However, when the time range isn't large enough, it just shows hours, like this:

This is less than ideal... if it could show a date and time in this case, that'd be great.  Anyone know how?

答:
Check this sample out from the Highcharts API.

Replace this

```<code>return Highcharts.dateFormat('%a %d %b', this.value);
</code>```

With this

```<code>return Highcharts.dateFormat('%a %d %b %H:%M:%S', this.value);
</code>```

Look here about the dateFormat() function.

Also see - tickInterval and pointInterval

Body:
Check this sample out from the Highcharts API.

Replace this

return Highcharts.dateFormat('%a %d %b', this.value);

With this

return Highcharts.dateFormat('%a %d %b %H:%M:%S', this.value);

Look here about the dateFormat() function.

Also see - tickInterval and pointInterval


问:
Can I send a Image to whatsApp using html hyperlink / a tag?
we can send text using html a tag with the following code

Hello, world!

or

Hello, World!

now If I want to send a Image attachment , how can do that?

答:
I guess it would be like this if you are trying to create an image which acts like a link

```

Body:
I guess it would be like this if you are trying to create an image which acts like a link

<a href="https://web.whatsapp.com/send?text=Hello%20World!"><img src="myCoolImage.png" width="500" height="500"></a>


问:
Schema qualified tables with SQLAlchemy, SQLite and Postgresql?
I have a Pylons project and a SQLAlchemy model that implements schema qualified tables:

```<code>class Hockey(Base):
    __tablename__ = "hockey"
    __table_args__ = {'schema':'winter'}
    hockey_id = sa.Column(sa.types.Integer, sa.Sequence('score_id_seq', optional=True), primary_key=True)
    baseball_id = sa.Column(sa.types.Integer, sa.ForeignKey('summer.baseball.baseball_id'))
</code>```

This code works great with Postgresql but fails when using SQLite on table and foreign key names (due to SQLite's lack of schema support)

sqlalchemy.exc.OperationalError: (OperationalError) unknown database "winter" 'PRAGMA "winter".table_info("hockey")' ()

I'd like to continue using SQLite for dev and testing.

Is there a way of have this fail gracefully on SQLite?

答:
I know this is a 10+ year old question, but I ran into the same problem recently: Postgres in production and sqlite in development.

The solution was to register an event listener for when the engine calls the "connect" method.

```<code>@sqlalchemy.event.listens_for(engine, "connect")
def connect(dbapi_connection, connection_record):
    dbapi_connection.execute('ATTACH "your_data_base_name.db" AS "schema_name"')
</code>```

Using ATTACH statement only once will not work, because it affects only a single connection. This is why we need the event listener, to make the ATTACH statement over all connections.

ContentLicense: CC BY-SA 2.5

Body:
I have a Pylons project and a SQLAlchemy model that implements schema qualified tables:

class Hockey(Base):
    __tablename__ = "hockey"
    __table_args__ = {'schema':'winter'}
    hockey_id = sa.Column(sa.types.Integer, sa.Sequence('score_id_seq', optional=True), primary_key=True)
    baseball_id = sa.Column(sa.types.Integer, sa.ForeignKey('summer.baseball.baseball_id'))

This code works great with Postgresql but fails when using SQLite on table and foreign key names (due to SQLite's lack of schema support)

sqlalchemy.exc.OperationalError: (OperationalError) unknown database "winter" 'PRAGMA "winter".table_info("hockey")' ()

I'd like to continue using SQLite for dev and testing.

Is there a way of have this fail gracefully on SQLite?

Body:
I know this is a 10+ year old question, but I ran into the same problem recently: Postgres in production and sqlite in development.

The solution was to register an event listener for when the engine calls the "connect" method.

@sqlalchemy.event.listens_for(engine, "connect")
def connect(dbapi_connection, connection_record):
    dbapi_connection.execute('ATTACH "your_data_base_name.db" AS "schema_name"')

Using ATTACH statement only once will not work, because it affects only a single connection. This is why we need the event listener, to make the ATTACH statement over all connections.


问:
Unable to log egress traffic HTTP requests with the istio-proxy
I am following this guide.

Ingress requests are getting logged. Egress traffic control is working as expected, except I am unable to log egress HTTP requests. What is missing?

apiVersion: networking.istio.io/v1beta1
kind: Sidecar
metadata:
  name: myapp
spec:
  workloadSelector:
    labels:
      app: myapp

  outboundTrafficPolicy:
    mode: REGISTRY_ONLY

  egress:
    - hosts:
        - default/*.example.com
```
<pre class="lang-yaml prettyprint-override"><code>apiVersion: networking.istio.io/v1alpha3
kind: ServiceEntry
metadata:
  name: example

spec:
  location: MESH_EXTERNAL
  resolution: NONE
  hosts:
    - '*.example.com'

  ports:
    - name: https
      protocol: TLS
      number: 443
</code>```

apiVersion: telemetry.istio.io/v1alpha1
kind: Telemetry
metadata:
  name: mesh-default
  namespace: istio-system
spec:
  accessLogging:
    - providers:
        - name: envoy

```

Kubernetes 1.22.2 Istio 1.11.4

答:
AFAIK istio collects only ingress HTTP logs by default.

In the istio documentation there is an old article (from 2018) describing how to enable egress traffic HTTP logs.

Please keep in mind that some of the information may be outdated, however I believe this is the part that you are missing.

Body:
I am following this guide.

Ingress requests are getting logged. Egress traffic control is working as expected, except I am unable to log egress HTTP requests. What is missing?

apiVersion: networking.istio.io/v1beta1
kind: Sidecar
metadata:
  name: myapp
spec:
  workloadSelector:
    labels:
      app: myapp

  outboundTrafficPolicy:
    mode: REGISTRY_ONLY

  egress:
    - hosts:
        - default/*.example.com

apiVersion: networking.istio.io/v1alpha3
kind: ServiceEntry
metadata:
  name: example

spec:
  location: MESH_EXTERNAL
  resolution: NONE
  hosts:
    - '*.example.com'

  ports:
    - name: https
      protocol: TLS
      number: 443

apiVersion: telemetry.istio.io/v1alpha1
kind: Telemetry
metadata:
  name: mesh-default
  namespace: istio-system
spec:
  accessLogging:
    - providers:
        - name: envoy

Kubernetes 1.22.2 Istio 1.11.4


问:
inline code on server control properties
I have a public POCO property (SiteDetail) on my page and I need to know what's the best approach when setting properties of server controls:

Use inline code and Page.DataBind(); on load

<asp:Label ID="lbName" runat="server" Text="<%# SiteDetail.Name %>"/>

Do not use inline code and set control properties on page load

lbName.Text = SiteDetail.Name;

Is it "dangerous" to use Page.DataBind() on load?

答:
Did you see the rendered source? There is no difference at all. Both labels will render text in the span. Just perform a simple test and it will be clear to you.

here is what I have for a test

```<code><asp:Label ID="Label1" runat="server" Text='<%#test %>'></asp:Label>
<asp:Label ID="Label2" runat="server"></asp:Label>
</code>```

here is generated source below.

```<code> <span id="Label1">this text is from binding expression</span>
 <span id="Label2"><br/>this text set from code behind</span>
</code>```

You will see no difference at all

Body:
Did you see the rendered source? There is no difference at all. Both labels will render text in the span. Just perform a simple test and it will be clear to you.

here is what I have for a test

<asp:Label ID="Label1" runat="server" Text='<%#test %>'></asp:Label>
<asp:Label ID="Label2" runat="server"></asp:Label>

here is generated source below.

 <span id="Label1">this text is from binding expression</span>
 <span id="Label2"><br/>this text set from code behind</span>

You will see no difference at all


问:
How to make my CodeChef solution code faster?
I am a beginner currently in first semester. I have been practising on Code Chef and am stuck at this problem. They are asking to reduce the execution time of my code. The problem goes as follows:

Meliodas and Ban are fighting over chocolates. Meliodas has X chocolates, while Ban has Y. Whoever has lesser number of chocolates eats as many chocolates as he has from the other's collection. This eatfest war continues till either they have the same number of chocolates, or at least one of them is left with no chocolates.
Can you help Elizabeth predict the total no of chocolates they'll be left with at the end of their war?

Input:
First line will contain T, number of testcases. Then the testcases follow.
Each testcase contains of a single line of input, which contains two integers X,Y, the no of chocolates Meliodas and Ban have, respectively.

Output:
For each testcase, output in a single line the no of chocolates that remain after Ban and Meliodas stop fighting.

Sample Input:

```<code>3
5 3
10 10
4 8
</code>```

Sample Output:

```<code>2
20
8
</code>```

My code is as follows:

```<code>#include <iostream>
using namespace std;

int main()
{
    unsigned int t,B,M;
    cin>>t;
    while(t--)
    {
        cin>>M>>B;
        if(B==M)
        {
            cout<<B+M<<endl;
        }
        else
        {
            for(int i=1;B!=M;i++)
            {
                if(B>M)
                B=B-M;
                else
                M=M-B;
            }
            cout<<M+B<<endl;
        }
    }
    return 0;
}
</code>```

答:
Assuming that Band Mare different from 0, this algorithm corresponds to one version of the Euclidean algorithm. Therefore, you can simply:

```<code>std::cout << 2 * std::gcd(B, M) << "\n";
</code>```

If at least one of the quantity is equal to 0, then just print B + M.

Body:
I am a beginner currently in first semester. I have been practising on Code Chef and am stuck at this problem. They are asking to reduce the execution time of my code. The problem goes as follows:

Meliodas and Ban are fighting over chocolates. Meliodas has X chocolates, while Ban has Y. Whoever has lesser number of chocolates eats as many chocolates as he has from the other's collection. This eatfest war continues till either they have the same number of chocolates, or at least one of them is left with no chocolates.
Can you help Elizabeth predict the total no of chocolates they'll be left with at the end of their war?

Input:
First line will contain T, number of testcases. Then the testcases follow.
Each testcase contains of a single line of input, which contains two integers X,Y, the no of chocolates Meliodas and Ban have, respectively.

Output:
For each testcase, output in a single line the no of chocolates that remain after Ban and Meliodas stop fighting.

Sample Input:

3
5 3
10 10
4 8

Sample Output:

2
20
8

My code is as follows:

#include <iostream>
using namespace std;

int main()
{
    unsigned int t,B,M;
    cin>>t;
    while(t--)
    {
        cin>>M>>B;
        if(B==M)
        {
            cout<<B+M<<endl;
        }
        else
        {
            for(int i=1;B!=M;i++)
            {
                if(B>M)
                B=B-M;
                else
                M=M-B;
            }
            cout<<M+B<<endl;
        }
    }
    return 0;
}

Body:
Assuming that Band Mare different from 0, this algorithm corresponds to one version of the Euclidean algorithm. Therefore, you can simply:

std::cout << 2 * std::gcd(B, M) << "\n";

If at least one of the quantity is equal to 0, then just print B + M.


问:
Laravel Slug Exist
I want to create slug for blog categories. I do it like this;

```<code>Str::slug($request->title)
</code>```

But I have to check if slug exist. If exist, I want to do like this;

```<code>// For example title is test. Slug must be test.
// But if slug exist I want to do it test1
if(count(blog_tags::where('slug',$slug)->get()) > 0){
     $slug = $slug . '1';
}
// But test1 too can be exist. So I have to test it.
</code>```

If I test it again and again, system will be slow. What should I do?

答:
Add the following function in your controller class to check ending number in slug

```<code>protected function countEndingDigits($string)
{
    $tailing_number_digits =  0;
    $i = 0;
    $from_end = -1;
    while ($i < strlen($string)) :
      if (is_numeric(substr($string, $from_end - $i, 1))) :
        $tailing_number_digits++;
      else :
        // End our while if we don't find a number anymore
        break;
      endif;
      $i++;
    endwhile;
    return $tailing_number_digits;
}
</code>```

Add the following function in your controller class to check slug already exists or not

```<code>protected function checkSlug($slug) {

if(blog_tags::where('slug',$slug)->count() > 0){
 $numIn = $this->countEndingDigits($slug);
 if ($numInUN > 0) {
          $base_portion = substr($slug, 0, -$numInUN);
          $digits_portion = abs(substr($slug, -$numInUN));
  } else {
          $base_portion = $slug . "-";
          $digits_portion = 0;
  }

  $slug = $base_portion . intval($digits_portion + 1);
  $slug = $this->checkSlug($slug)
}

return $slug
}
</code>```

Now you will get a unique incremental slug

```<code>$slug = $this->checkSlug(Str::slug(string));
</code>```

Title: Laravel Slug Exist

Body:
I want to create slug for blog categories. I do it like this;

Str::slug($request->title)

But I have to check if slug exist. If exist, I want to do like this;

// For example title is test. Slug must be test.
// But if slug exist I want to do it test1
if(count(blog_tags::where('slug',$slug)->get()) > 0){
     $slug = $slug . '1';
}
// But test1 too can be exist. So I have to test it.

If I test it again and again, system will be slow. What should I do?

Body:
Add the following function in your controller class to check ending number in slug

protected function countEndingDigits($string)
{
    $tailing_number_digits =  0;
    $i = 0;
    $from_end = -1;
    while ($i < strlen($string)) :
      if (is_numeric(substr($string, $from_end - $i, 1))) :
        $tailing_number_digits++;
      else :
        // End our while if we don't find a number anymore
        break;
      endif;
      $i++;
    endwhile;
    return $tailing_number_digits;
}

Add the following function in your controller class to check slug already exists or not

protected function checkSlug($slug) {

if(blog_tags::where('slug',$slug)->count() > 0){
 $numIn = $this->countEndingDigits($slug);
 if ($numInUN > 0) {
          $base_portion = substr($slug, 0, -$numInUN);
          $digits_portion = abs(substr($slug, -$numInUN));
  } else {
          $base_portion = $slug . "-";
          $digits_portion = 0;
  }

  $slug = $base_portion . intval($digits_portion + 1);
  $slug = $this->checkSlug($slug)
}

return $slug
}

Now you will get a unique incremental slug

$slug = $this->checkSlug(Str::slug(string));


问:
How to use 'same' padding for maxpool1d
Tensorflow tf.keras.layers.MaxPool1D has the option to set padding='same' to make the input shape the same as the output shape. Is there something equivalent for torch.nn.MaxPool1d ? I see that torch.nn.Conv1d has the option to set padding='same', but this option seems to be missing from maxpool. What is the current workaround for this?

答:
Note that the output of the keras version is only really the same shape as the input whenever you use it with stride and dilation set to 1, so I'll assume the same parameters in this answer.

For any uneven kernel size, this is quite easily achievable in PyTorch by setting the padding to (kernel_size - 1)/2.

For an even kernel size, both sides of the input need to be padded by a different amount, and this seems not possible in the current implementation of MaxPool1d.

Title: How to use 'same' padding for maxpool1d


问:
Pyspark : Convert nested JSON struct to pyspark dataframe
Is there an easy way to convert the below sample json into Pyspark dataframe ?

Input :

{
"user": {
  "1": {
    "name": "Joe",
    "age": 28
  },
  "2" :{
    "name": "Chris",
    "age": 14
  },
  "3" :{
    "name": "Hally",
    "age": 21
  }
}
}
```
<p>Expected output (dataframe):</p>
<pre class="lang-json prettyprint-override"><code>root
 |-- age: long (nullable = true)
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)

+---+---+-----+
|age|id |name |
+---+---+-----+
|28 |1  |Joe  |
|14 |2  |Chris|
|21 |3  |Hally|
+---+---+-----+
</code>```

答:
Read the JSON into dataframe, get the list of user IDs then create an array and explode it into multiple rows like this:

from pyspark.sql import functions as F

json_example = '{"user":{"1":{"name":"Joe","age":28},"2":{"name":"Chris","age":14},"3":{"name":"Hally","age":21}}}'
df = spark.read.json(spark.sparkContext.parallelize([json_example]))

result = df.select(F.array(*[
    F.struct(F.lit(i).alias("id"), F.col(f"user.{i}.name"), F.col(f"user.{i}.age"))
    for i in df.select("user.*").columns
]).alias("users")).selectExpr("inline(users)")

result.show()
#+---+-----+---+
#| id| name|age|
#+---+-----+---+
#|  1|  Joe| 28|
#|  2|Chris| 14|
#|  3|Hally| 21|
#+---+-----+---+
```
<hr />
<p>Or simply using <code>stack</code> expression:</p>
<pre class="lang-py prettyprint-override"><code>from itertools import chain

df1 = df.select("user.*")

result = df1.selectExpr(
    f"stack({len(df1.columns)}," + ','.join(chain(*[(f"`{c}`", c) for c in df1.columns])) + ")"
).selectExpr("col1 as id", "col0.*")
</code>```

Body:
Is there an easy way to convert the below sample json into Pyspark dataframe ?

Input :

{
"user": {
  "1": {
    "name": "Joe",
    "age": 28
  },
  "2" :{
    "name": "Chris",
    "age": 14
  },
  "3" :{
    "name": "Hally",
    "age": 21
  }
}
}

Expected output (dataframe):

root
 |-- age: long (nullable = true)
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)

+---+---+-----+
|age|id |name |
+---+---+-----+
|28 |1  |Joe  |
|14 |2  |Chris|
|21 |3  |Hally|
+---+---+-----+

Body:
Read the JSON into dataframe, get the list of user IDs then create an array and explode it into multiple rows like this:

from pyspark.sql import functions as F

json_example = '{"user":{"1":{"name":"Joe","age":28},"2":{"name":"Chris","age":14},"3":{"name":"Hally","age":21}}}'
df = spark.read.json(spark.sparkContext.parallelize([json_example]))

result = df.select(F.array(*[
    F.struct(F.lit(i).alias("id"), F.col(f"user.{i}.name"), F.col(f"user.{i}.age"))
    for i in df.select("user.*").columns
]).alias("users")).selectExpr("inline(users)")

result.show()
#+---+-----+---+
#| id| name|age|
#+---+-----+---+
#|  1|  Joe| 28|
#|  2|Chris| 14|
#|  3|Hally| 21|
#+---+-----+---+

Or simply using stack expression:

from itertools import chain

df1 = df.select("user.*")

result = df1.selectExpr(
    f"stack({len(df1.columns)}," + ','.join(chain(*[(f"`{c}`", c) for c in df1.columns])) + ")"
).selectExpr("col1 as id", "col0.*")


问:
How to write statement that deletes extra space in C++?
I have been working on a project. I am limited to using a few libraries so any additional library would not be helpful. I am building a project, but I am noticing an extra space after the last number when the calendar is finished. How do I fix this extra spacing issue?</p>
```<code>//extracted...
         if (day >= 9)
         {
            std::cout << day;
         }
         else
          std::cout << day << " ";
          std::cout << " ";
      }
   }

</code>```

答:
std::cout << std::setw(2) << day might get rid of if (day >= 9) stuff.

Then to write number with some separator, I tend to use following pattern

```<code>const char* sep = "";
for (auto e : some_list) {
    std::cout << sep << e;
    sep = ", "; // or any separator
}
</code>```

Resulting into

```<code>const char* sep = "";
for (day = 1; day <= days_per; day++)
{
    std::cout << sep << std::setw(2) << day;
    sep = " ";
    if (++count > 6)
    {
        std::cout << '\n';
        count = 0;
        sep = "";
    }
}
</code>```

Demo

Body:
I have been working on a project. I am limited to using a few libraries so any additional library would not be helpful. I am building a project, but I am noticing an extra space after the last number when the calendar is finished. How do I fix this extra spacing issue?

//extracted...
         if (day >= 9)
         {
            std::cout << day;
         }
         else
          std::cout << day << " ";
          std::cout << " ";
      }
   }

Body:
std::cout << std::setw(2) << day might get rid of if (day >= 9) stuff.

Then to write number with some separator, I tend to use following pattern

const char* sep = "";
for (auto e : some_list) {
    std::cout << sep << e;
    sep = ", "; // or any separator
}

Resulting into

const char* sep = "";
for (day = 1; day <= days_per; day++)
{
    std::cout << sep << std::setw(2) << day;
    sep = " ";
    if (++count > 6)
    {
        std::cout << '\n';
        count = 0;
        sep = "";
    }
}

Demo


问:
Targeting S+ (version 31 and above) requires that an explicit value for android:exported be defined when intent filters are present]
While debugging the application in android 12, the app is getting crashed.</p>

答:
In AndroidManifest.xml

```<code>     <activity
        android:exported="true"
        android:name="com.YOU.APP.activities.MainActivity"
        android:launchMode="singleTask"
        android:hardwareAccelerated="true">
        <intent-filter>
            <action android:name="android.intent.action.SEND" />

            <category android:name="android.intent.category.DEFAULT" />

            <data android:mimeType="text/plain" />
        </intent-filter>
    </activity>
</code>```

Body:
In AndroidManifest.xml

     <activity
        android:exported="true"
        android:name="com.YOU.APP.activities.MainActivity"
        android:launchMode="singleTask"
        android:hardwareAccelerated="true">
        <intent-filter>
            <action android:name="android.intent.action.SEND" />

            <category android:name="android.intent.category.DEFAULT" />

            <data android:mimeType="text/plain" />
        </intent-filter>
    </activity>


问:
How to pass the latitude and longitude values to the ns url?
Iam developing one application.In that i use the google api for getting the location information.For that i use the CLLocationManager for getting the location latitude and longitude values.And my pblm is how to pass these latitude and longitude values to nsurl .ANd iam directly given the one location values to the url like below.

```<code>NSURL *URL = [NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/search           /json?location=40.7143528,-74.0059731&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM"];
</code>```

I write this one in below method for get and pass the latitude and longitude values.

```<code>- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
}
</code>```

So please tell me how to pass the newlocation.Coordinates.latitude and newlocation.Coordinates.longitude to that url in that method. Or Is there any way to pass that values in any other method.

答:
This should work, however is brain compiled :)

```<code>- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
//Filter the location first here, it could be an invalid location or maybe too recent to the last one because this method is called several times in short times of periods.

//Then use the value
NSString *address = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f, %f&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM", newLocation.lattitude, newLocation.longitude];
NSURL *url = [NSURL URLFromString:address];
//do your thing here...

}
</code>```

I hope it helps

Body:
Iam developing one application.In that i use the google api for getting the location information.For that i use the CLLocationManager for getting the location latitude and longitude values.And my pblm is how to pass these latitude and longitude values to nsurl .ANd iam directly given the one location values to the url like below.

NSURL *URL = [NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/search           /json?location=40.7143528,-74.0059731&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM"];

I write this one in below method for get and pass the latitude and longitude values.

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
}

So please tell me how to pass the newlocation.Coordinates.latitude and newlocation.Coordinates.longitude to that url in that method. Or Is there any way to pass that values in any other method.

Body:
This should work, however is brain compiled :)

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
//Filter the location first here, it could be an invalid location or maybe too recent to the last one because this method is called several times in short times of periods.

//Then use the value
NSString *address = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f, %f&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM", newLocation.lattitude, newLocation.longitude];
NSURL *url = [NSURL URLFromString:address];
//do your thing here...

}

I hope it helps


问:
First argument error in pytorch.loads() function when working with Emotic demo
Basically, I'm creating an emotion recognition application, and I'm using Emotic's image dataset. They have their own premade program and trained model for a demo (The colab link below) but for some reason the third cell under  I. Prepare places pretrained model is encountering the error:
the first argument must be callable on line 19 in the 4th Google Colab cell.
Code:

# Converting model weights to python3.6 format
import torch
from PIL import Image
from torch.autograd import Variable as V
import torchvision.models as models
from torchvision import transforms as trn
from torch.nn import functional as F
import os

model_path = './places'
archs = ['resnet18']
for arch in archs:
    model_file = os.path.join(model_path,'%s_places365.pth.tar' % arch)
    save_file = os.path.join(model_path,'%s_places365_py36.pth.tar' % arch)

    from functools import partial
    import pickle
    pickle.load = partial(pickle.load, encoding="latin1")
    pickle.Unpickler = partial(pickle.Unpickler, encoding="latin1")
    model = torch.load(model_file, map_location=lambda storage, loc: storage, pickle_module=pickle)
    torch.save(model, save_file)
    print('converting %s -> %s'%(model_file, save_file))

print ('completed cell')
# Saving the model weights to use ahead in the notebook

# the architecture to use
arch = 'resnet18'
model_weight = os.path.join(model_path, 'resnet18_places365_py36.pth.tar')

# create the network architecture
model = models.__dict__[arch](num_classes=365)

#model_weight = '%s_places365.pth.tar' % arch

checkpoint = torch.load(model_weight) # model trained in GPU could be deployed in CPU machine like this!
state_dict = {str.replace(k,'module.',''): v for k,v in checkpoint['state_dict'].items()} # the data parallel layer will add 'module' before each layer name
model.load_state_dict(state_dict)
model.eval()

model.cpu()
torch.save(model, os.path.join(model_path, 'res_context' + '.pth'))
print ('completed cell')
```
<p>Does anyone have any idea why this is happening? (Haven't changed any code this is the demo offered by Emotic)</p>
<p>Error:</p>
```TypeError                                 Traceback (most recent call last)
<ipython-input-8-1a9e3bc55eae> in <module>()
     17 #model_weight = '%s_places365.pth.tar' % arch
     18
---> 19 checkpoint = torch.load(model_weight) # model trained in GPU could be deployed in CPU machine like this!
     20 state_dict = {str.replace(k,'module.',''): v for k,v in checkpoint['state_dict'].items()} # the data parallel layer will add 'module' before each layer name
     21 model.load_state_dict(state_dict)

1 frames
/usr/local/lib/python3.7/dist-packages/torch/serialization.py in _load(zip_file, map_location, pickle_module, pickle_file, **pickle_load_args)
    867     # because it's marked readonly in pickle.
    868     # The type: ignore is because mypy can't statically determine the type of this class.
--> 869     class UnpicklerWrapper(pickle_module.Unpickler):  # type: ignore[name-defined]
    870         # from https://stackoverflow.com/questions/13398462/unpickling-python-objects-with-a-changed-module-path/13405732
    871         # Lets us override the imports that pickle uses when unpickling an object.

TypeError: the first argument must be callable
```

Public Gopogle Colab link:
https://colab.research.google.com/github/Tandon-A/emotic/blob/master/Colab_train_emotic.ipynb

答:
I am the author of this repository. I had fixed this issue back in August 2021. The issue is caused due to some changes in the Python Pickle module in the python 3.7 version. The code used to work properly in the Python 3.6 version.

You can try the Colab_train_emotic.ipynb file.

Body:
Basically, I'm creating an emotion recognition application, and I'm using Emotic's image dataset. They have their own premade program and trained model for a demo (The colab link below) but for some reason the third cell under  I. Prepare places pretrained model is encountering the error:
the first argument must be callable on line 19 in the 4th Google Colab cell.
Code:

# Converting model weights to python3.6 format
import torch
from PIL import Image
from torch.autograd import Variable as V
import torchvision.models as models
from torchvision import transforms as trn
from torch.nn import functional as F
import os

model_path = './places'
archs = ['resnet18']
for arch in archs:
    model_file = os.path.join(model_path,'%s_places365.pth.tar' % arch)
    save_file = os.path.join(model_path,'%s_places365_py36.pth.tar' % arch)

    from functools import partial
    import pickle
    pickle.load = partial(pickle.load, encoding="latin1")
    pickle.Unpickler = partial(pickle.Unpickler, encoding="latin1")
    model = torch.load(model_file, map_location=lambda storage, loc: storage, pickle_module=pickle)
    torch.save(model, save_file)
    print('converting %s -> %s'%(model_file, save_file))

print ('completed cell')
# Saving the model weights to use ahead in the notebook

# the architecture to use
arch = 'resnet18'
model_weight = os.path.join(model_path, 'resnet18_places365_py36.pth.tar')

# create the network architecture
model = models.__dict__[arch](num_classes=365)

#model_weight = '%s_places365.pth.tar' % arch

checkpoint = torch.load(model_weight) # model trained in GPU could be deployed in CPU machine like this!
state_dict = {str.replace(k,'module.',''): v for k,v in checkpoint['state_dict'].items()} # the data parallel layer will add 'module' before each layer name
model.load_state_dict(state_dict)
model.eval()

model.cpu()
torch.save(model, os.path.join(model_path, 'res_context' + '.pth'))
print ('completed cell')

Does anyone have any idea why this is happening? (Haven't changed any code this is the demo offered by Emotic)

Error:

TypeError                                 Traceback (most recent call last)
<ipython-input-8-1a9e3bc55eae> in <module>()
     17 #model_weight = '%s_places365.pth.tar' % arch
     18
---> 19 checkpoint = torch.load(model_weight) # model trained in GPU could be deployed in CPU machine like this!
     20 state_dict = {str.replace(k,'module.',''): v for k,v in checkpoint['state_dict'].items()} # the data parallel layer will add 'module' before each layer name
     21 model.load_state_dict(state_dict)

1 frames
/usr/local/lib/python3.7/dist-packages/torch/serialization.py in _load(zip_file, map_location, pickle_module, pickle_file, **pickle_load_args)
    867     # because it's marked readonly in pickle.
    868     # The type: ignore is because mypy can't statically determine the type of this class.
--> 869     class UnpicklerWrapper(pickle_module.Unpickler):  # type: ignore[name-defined]
    870         # from https://stackoverflow.com/questions/13398462/unpickling-python-objects-with-a-changed-module-path/13405732
    871         # Lets us override the imports that pickle uses when unpickling an object.

TypeError: the first argument must be callable

Public Gopogle Colab link:
https://colab.research.google.com/github/Tandon-A/emotic/blob/master/Colab_train_emotic.ipynb


问:
Eval of ASP.Net is not using not equals
I need to disable a div for db data value which fetched from code behind but how i can achieve with below Equals code

Requirement : Not Equal("1") then disable div.

my code is below : instead of Equals in below code ,I have to use not Equals.....

```<code> <div class="row" style='<%# (Eval("Test").ToString().Equals("1"))? "display:none;" : string.Empty %>'>
</code>```

答:
```<code><div class="row" style='<%= ((Test != "1") ? "display:none;" : string.Empty) %>'>
    <h1>Lorem ipsum dolor sit amet ...</h1>
</div>
</code>```

assuming Test here, is an instance public property of type string in the code-behind of your page.

Or this could work too :

```<code><div class="row" style='<%# ((Eval("Test").ToString() != "1") ? "display:none;" : string.Empty) %>'>
    <h1>Lorem ipsum dolor sit amet ...</h1>
</div>
</code>```

Title: Eval of ASP.Net is not using not equals

Body:
I need to disable a div for db data value which fetched from code behind but how i can achieve with below Equals code

Requirement : Not Equal("1") then disable div.

my code is below : instead of Equals in below code ,I have to use not Equals.....

 <div class="row" style='<%# (Eval("Test").ToString().Equals("1"))? "display:none;" : string.Empty %>'>

Body:
<div class="row" style='<%= ((Test != "1") ? "display:none;" : string.Empty) %>'>
    <h1>Lorem ipsum dolor sit amet ...</h1>
</div>

assuming Test here, is an instance public property of type string in the code-behind of your page.

Or this could work too :

<div class="row" style='<%# ((Eval("Test").ToString() != "1") ? "display:none;" : string.Empty) %>'>
    <h1>Lorem ipsum dolor sit amet ...</h1>
</div>


问:
How do I convert String to Instant concatenating a date string to a time string?
I need to convert this String to a Instant, i do it this way:

```<code>String inputStartDate = startDate+" 00:00:00.000";
String inputEndDate = endDate+" 23:59:59.999";
</code>```

startDate is only the date because i get the String from another call, but i need to keep the hour static, the same way to the endDate.

Then, i convert to Instant like this:

```<code>Instant newStarDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(inputStartDate).toInstant();
Instant newEndDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(inputEndDate).toInstant();
</code>```

But when i convert to instant, it's convert wrong.
For example:

```<code>startDate="2022-02-04"
endDate="2022-02-04"
</code>```

When i do the concat the string is like this:

```<code>inputStartDate: "2022-02-03 00:00:00.000"
inputEndDate: "2022-02-04 23:59:59.999"
</code>```

And the result when i transform to instant it's like this, i don't know what is wrong.

```<code>newStartDate:"2022-02-03T03:00:00Z"
newEndDate:"2022-02-05T02:59:59.999Z"
</code>```

I need the yyyy-MM-dd HH:mm:ss.SSS to do a mongodb query and it's need to be a Instant.

答:
I got the answer, it was more easier than i think.

Instead of giving it a SimpleDateFormat you have to transform it directly to Instant like this:

```<code>Instant finalStartDate = Instant.parse(startDate+"T00:00:00.000Z");
Instant finalEndDate = Instant.parse(endDate+"T23:59:59.999Z");
</code>```

You have to add the T and the Z.

Body:
I need to convert this String to a Instant, i do it this way:

String inputStartDate = startDate+" 00:00:00.000";
String inputEndDate = endDate+" 23:59:59.999";

startDate is only the date because i get the String from another call, but i need to keep the hour static, the same way to the endDate.

Then, i convert to Instant like this:

Instant newStarDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(inputStartDate).toInstant();
Instant newEndDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(inputEndDate).toInstant();

But when i convert to instant, it's convert wrong.
For example:

startDate="2022-02-04"
endDate="2022-02-04"

When i do the concat the string is like this:

inputStartDate: "2022-02-03 00:00:00.000"
inputEndDate: "2022-02-04 23:59:59.999"

And the result when i transform to instant it's like this, i don't know what is wrong.

newStartDate:"2022-02-03T03:00:00Z"
newEndDate:"2022-02-05T02:59:59.999Z"

I need the yyyy-MM-dd HH:mm:ss.SSS to do a mongodb query and it's need to be a Instant.

Body:
I got the answer, it was more easier than i think.

Instead of giving it a SimpleDateFormat you have to transform it directly to Instant like this:

Instant finalStartDate = Instant.parse(startDate+"T00:00:00.000Z");
Instant finalEndDate = Instant.parse(endDate+"T23:59:59.999Z");

You have to add the T and the Z.


问:
How to install bundler with the version written in "BUNDLED WITH" in Gemfile.lock
I want to install bundler with a specific version written in Gemfile.lock. Do you know how to do it? I want to let ci like Jenkins automatically install bundler of  the version.

```<code>BUNDLED WITH
   1.13.5
</code>```

答: Probably a bit late to the party, but bundler 2.3 does this for you by default. See https://bundler.io/blog/2022/01/23/bundler-v2-3.html.</p>

Body:
I want to install bundler with a specific version written in Gemfile.lock. Do you know how to do it? I want to let ci like Jenkins automatically install bundler of  the version.

BUNDLED WITH
   1.13.5


问:
Why isn't my JavaFX application showing a web browser?
I have a modular JavaFX application with the following Java code:

```<code>package webbrowser;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebView;
import javafx.scene.web.WebEngine;
import javafx.stage.Stage;

public class WebBrowser extends Application {

    @Override
    public void start(Stage stage) {
        WebView browser = new WebView();
        WebEngine webEngine = browser.getEngine();
        webEngine.load("http://www.oracle.com");
        Scene scene = new Scene(browser, 500, 500);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }

}
</code>```

Here is the module-info.java file:

```<code>module webBrowser {
    requires javafx.controls;
    requires javafx.web;

    exports webbrowser;
}
</code>```

I compile the modular JavaFX application with the following command:

```<code>javac -d out --module-source-path . --module-path $JAVAFX_SDK/libs:$JAVAFX_JMODS --module webBrowser
</code>```

I package the modular JavaFX application with the following command:

```<code>jpackage --type dmg --module-path $JAVAFX_JMODS:$JAVAFX_SDK/lib:out --add-modules javafx.controls,javafx.web,javafx.graphics,javafx.media --module webBrowser/webbrowser.WebBrowser
</code>```

Then I save the application in my /Applications folder (I'm on Mac OS) and open the application. The application opens a 500x500 window, but it doesn't render any graphics, and it doesn't open a web browser. The application just opens a white blank 500x500 window.

Why isn't the application running properly?

When I run the application with java (and forego jpackage) the application runs fine in the JVM, opens a web browser, and opens the oracle.com webpage.

```<code>java --module-path out:$JAVAFX_JMODS:$JAVAFX_SDK/lib --add-modules javafx.controls,javafx.web --module webBrowser/webbrowser.WebBrowser
</code>```

Why doesn't the application work when I use jpackage, install the dmg and run the Mac OS app?

答:
The section of the openjfx.io documentation on runtime images, modular from CLI, demonstrates some of the points outlined below and provides examples of the command line arguments to use for compiling, linking, packaging and executing the application.

I suggest you get the linked openjfx demo working in your environment, then try the same for your project.

Some issues to address:

jmods can't be used at runtime, only at compile or link time.

e.g. don't pass the jmods to the java command.

For more info, see the answer to:

Add a custom JMOD to the module path with Java 9

--add-modules is not required for java/javac when you have a module-info.java.

for jpackage just list your app module in --add-modules, you don't need to list the javafx package because it can work that out from your module-info.

Your lib directory is inconsistent, always use the same (correct) directory:

sometimes you use lib and sometimes you use libs.

Provide an onError handler.

When using jpackage you should have only the JavaFX mods.

you don't need the mods and SDK lib, use only mods.

Further points to check are highlighted in the answer to:

Java FX Application with Jpackage not work

Body:
I have a modular JavaFX application with the following Java code:

package webbrowser;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebView;
import javafx.scene.web.WebEngine;
import javafx.stage.Stage;

public class WebBrowser extends Application {

    @Override
    public void start(Stage stage) {
        WebView browser = new WebView();
        WebEngine webEngine = browser.getEngine();
        webEngine.load("http://www.oracle.com");
        Scene scene = new Scene(browser, 500, 500);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }

}

Here is the module-info.java file:

module webBrowser {
    requires javafx.controls;
    requires javafx.web;

    exports webbrowser;
}

I compile the modular JavaFX application with the following command:

javac -d out --module-source-path . --module-path $JAVAFX_SDK/libs:$JAVAFX_JMODS --module webBrowser

I package the modular JavaFX application with the following command:

jpackage --type dmg --module-path $JAVAFX_JMODS:$JAVAFX_SDK/lib:out --add-modules javafx.controls,javafx.web,javafx.graphics,javafx.media --module webBrowser/webbrowser.WebBrowser

Then I save the application in my /Applications folder (I'm on Mac OS) and open the application. The application opens a 500x500 window, but it doesn't render any graphics, and it doesn't open a web browser. The application just opens a white blank 500x500 window.

Why isn't the application running properly?

When I run the application with java (and forego jpackage) the application runs fine in the JVM, opens a web browser, and opens the oracle.com webpage.

java --module-path out:$JAVAFX_JMODS:$JAVAFX_SDK/lib --add-modules javafx.controls,javafx.web --module webBrowser/webbrowser.WebBrowser

Why doesn't the application work when I use jpackage, install the dmg and run the Mac OS app?


问:
TensorFlow Model is throwing an Invalid Argument Error at the 1st Epoch
I have a simple 2 layer Tensorflow model that I am trying to train on a dataset of equal-sized stereo audio files to tell me if the sound is coming more from the left side or the right side. This means the input is an array of 3072 by 2 arrays and the output is an array of 1's and 0's to represent left and right.

The problem is that when I run the program, it fails at model.fit() with an invalid argument error.

Code:

```<code># -*- coding: utf-8 -*-
"""
Created on Tue Jan 18 15:51:56 2022

@author: andre
"""

import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras import layers
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ModelCheckpoint
from sklearn.model_selection import train_test_split
from datetime import datetime
from sklearn import metrics
from scipy.io import wavfile
import os
import glob

# Load in Right Side .WAV Data.
X1 = []
count1 = 0
database_path = "C:\\Users\\andre\\OneDrive\\Documents\\ESI2022\\MLDatabases\\Right\\"
for filename in glob.glob(os.path.join(database_path, '*.wav')):
    X1.append(wavfile.read(filename)[1])
    count1 = count1 + 1

# Load in Left side .WAV Data.
X2 = []
count2 = 0
database_path2 = "C:\\Users\\andre\\OneDrive\\Documents\\ESI2022\\MLDatabases\\Right\\"
for filename2 in glob.glob(os.path.join(database_path2, '*.wav')):
    X2.append(wavfile.read(filename2)[1])
    count2 = count2 + 1

# Get the smallest size audio file (this will be sample size input to model)
sample_size = len(X1[0])
for data in X1:
    if len(data) < sample_size:
        sample_size = len(data)

# Make audio data into equal size chunks
X1e = []
for i in X1:
    num_chunks = len(i)//sample_size
    for j in range(num_chunks):
        X1e.append(i[(j+1)*sample_size-sample_size:(j+1)*sample_size])
X1 = X1e

X2e = []
for i in X2:
    num_chunks = len(i)//sample_size
    for j in range(num_chunks):
        X2e.append(i[(j+1)*sample_size-sample_size:(j+1)*sample_size])
X2=X2e

del X1e
del X2e

# Create Output data that is the same length as the input data.
Y1 = np.ones([X1.__len__()],dtype='float32').tolist()
Y2 = np.zeros([X2.__len__()],dtype='float32').tolist()

# Concatenate Left and Right .WAV data and output data as numpy arrays.
X1.extend(X2)
X = np.asarray(X1)
Y = np.asarray(Y1+Y2).astype(np.int16)

#X=list(X)
#Y=list(Y)

# Split data into test training data.
X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.2,random_state=0,shuffle=True)

'''
print(X[1])
time = np.linspace(0.,33792, 33792)
plt.plot(time, X[1][:,1], label="Left channel")
plt.plot(time, X[1][:,0], label="Right channel")
plt.legend()
plt.xlabel("Time [s]")
plt.ylabel("Amplitude")
plt.show()
'''

# Create the Model
model = Sequential()

# Add a LSTM layer with 1 output, and ambiguous input data length.
model.add(layers.LSTM(1,batch_input_shape=(1,sample_size,2),return_sequences=True))
model.add(layers.LSTM(1,return_sequences=False))

# Compile Model
#history = model.compile(loss='mean_absolute_error', metrics=['accuracy'],optimizer='adam',output='sparse_categorical_crossentropy')
optimizer = Adam(learning_rate=2*1e-4)

'''
history = model.compile(optimizer=optimizer, loss={
                  'output': 'sparse_categorical_crossentropy', },
              metrics={
                  'output': 'sparse_categorical_accuracy', },
              sample_weight_mode='temporal')
'''

history = model.compile(
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    optimizer="adam",
    metrics=["accuracy"],
)
model.summary()

# Define Training Parameters
num_epochs = 200
num_batch_size = 1

# Save the most accurate model to file. (Verbosity Gives more information)
checkpointer = ModelCheckpoint(filepath="SavedModels/checkpointModel.hdf5", verbose=1,save_best_only=True)

# Start the timer
start = datetime.now()

# Train the model
model.fit(X_train,Y_train,batch_size=num_batch_size, epochs=num_epochs, validation_data=(X_test,Y_test), callbacks=[checkpointer],verbose=1)

# Get and Print Model Validation Accuracy
test_accuracy=model.evaluate(X_test,Y_test,verbose=0)
print(test_accuracy[1])
</code>```

Output & error:

```<code>Model: "sequential_1"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 lstm_2 (LSTM)               (1, 3072, 1)              16

 lstm_3 (LSTM)               (1, 1)                    12

=================================================================
Total params: 28
Trainable params: 28
Non-trainable params: 0
_________________________________________________________________
Epoch 1/200

2022-02-07 09:40:36.348127: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cudart64_110.dll'; dlerror: cudart64_110.dll not found
2022-02-07 09:40:36.348459: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
2022-02-07 09:40:43.978976: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'nvcuda.dll'; dlerror: nvcuda.dll not found
2022-02-07 09:40:43.979029: W tensorflow/stream_executor/cuda/cuda_driver.cc:269] failed call to cuInit: UNKNOWN ERROR (303)
2022-02-07 09:40:43.985710: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:169] retrieving CUDA diagnostic information for host: DESKTOP-0FFTIDB
2022-02-07 09:40:43.986092: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:176] hostname: DESKTOP-0FFTIDB
2022-02-07 09:40:43.990164: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2022-02-07 09:40:48.470415: W tensorflow/core/framework/op_kernel.cc:1745] OP_REQUIRES failed at sparse_xent_op.cc:103 : INVALID_ARGUMENT: Received a label value of 1 which is outside the valid range of [0, 1).  Label values: 1
2022-02-07 09:58:29.070767: W tensorflow/core/framework/op_kernel.cc:1745] OP_REQUIRES failed at sparse_xent_op.cc:103 : INVALID_ARGUMENT: Received a label value of 1 which is outside the valid range of [0, 1).  Label values: 1
Traceback (most recent call last):

  File "C:\Users\andre\OneDrive\Documents\ESI2022\PythonScripts\BeltML\testML.py", line 127, in <module>
    model.fit(X_train,Y_train,batch_size=num_batch_size, epochs=num_epochs, validation_data=(X_test,Y_test), callbacks=[checkpointer],verbose=1)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\eager\execute.py", line 58, in quick_execute
    tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,

InvalidArgumentError:  Received a label value of 1 which is outside the valid range of [0, 1).  Label values: 1
     [[node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits
 (defined at C:\ProgramData\Anaconda3\lib\site-packages\keras\backend.py:5113)
]] [Op:__inference_train_function_9025]

Errors may have originated from an input operation.
Input Source operations connected to node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits:
In[0] sparse_categorical_crossentropy/Reshape_1 (defined at C:\ProgramData\Anaconda3\lib\site-packages\keras\backend.py:5109)
In[1] sparse_categorical_crossentropy/Reshape (defined at C:\ProgramData\Anaconda3\lib\site-packages\keras\backend.py:3561)

Operation defined at: (most recent call last)
  File "C:\ProgramData\Anaconda3\lib\runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,

  File "C:\ProgramData\Anaconda3\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\console\__main__.py", line 23, in <module>
    start.main()

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\console\start.py", line 328, in main
    kernel.start()

  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\kernelapp.py", line 677, in start
    self.io_loop.start()

  File "C:\ProgramData\Anaconda3\lib\site-packages\tornado\platform\asyncio.py", line 199, in start
    self.asyncio_loop.run_forever()

  File "C:\ProgramData\Anaconda3\lib\asyncio\base_events.py", line 570, in run_forever
    self._run_once()

  File "C:\ProgramData\Anaconda3\lib\asyncio\base_events.py", line 1859, in _run_once
    handle._run()

  File "C:\ProgramData\Anaconda3\lib\asyncio\events.py", line 81, in _run
    self._context.run(self._callback, *self._args)

  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 457, in dispatch_queue
    await self.process_one()

  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 446, in process_one
    await dispatch(*args)

  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 353, in dispatch_shell
    await result

  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 648, in execute_request
    reply_content = await reply_content

  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\ipkernel.py", line 353, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)

  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\zmqshell.py", line 533, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)

  File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2901, in run_cell
    result = self._run_cell(

  File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2947, in _run_cell
    return runner(coro)

  File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\async_helpers.py", line 68, in _pseudo_sync_runner
    coro.send(None)

  File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3172, in run_cell_async
    has_raised = await self.run_ast_nodes(code_ast.body, cell_name,

  File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3364, in run_ast_nodes
    if (await self.run_code(code, result,  async_=asy)):

  File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3444, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)

  File "C:\Users\andre\AppData\Local\Temp/ipykernel_3604/1229251547.py", line 1, in <module>
    runfile('C:/Users/andre/OneDrive/Documents/ESI2022/PythonScripts/BeltML/testML.py', wdir='C:/Users/andre/OneDrive/Documents/ESI2022/PythonScripts/BeltML')

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 577, in runfile
    exec_code(file_code, filename, ns_globals, ns_locals,

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 465, in exec_code
    exec(compiled, ns_globals, ns_locals)

  File "C:\Users\andre\OneDrive\Documents\ESI2022\PythonScripts\BeltML\testML.py", line 127, in <module>
    model.fit(X_train,Y_train,batch_size=num_batch_size, epochs=num_epochs, validation_data=(X_test,Y_test), callbacks=[checkpointer],verbose=1)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\utils\traceback_utils.py", line 64, in error_handler
    return fn(*args, **kwargs)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 1216, in fit
    tmp_logs = self.train_function(iterator)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 878, in train_function
    return step_function(self, iterator)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 867, in step_function
    outputs = model.distribute_strategy.run(run_step, args=(data,))

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 860, in run_step
    outputs = model.train_step(data)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 809, in train_step
    loss = self.compiled_loss(

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\compile_utils.py", line 201, in __call__
    loss_value = loss_obj(y_t, y_p, sample_weight=sw)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\losses.py", line 141, in __call__
    losses = call_fn(y_true, y_pred)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\losses.py", line 245, in call
    return ag_fn(y_true, y_pred, **self._fn_kwargs)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\losses.py", line 1737, in sparse_categorical_crossentropy
    return backend.sparse_categorical_crossentropy(

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\backend.py", line 5113, in sparse_categorical_crossentropy
    res = tf.nn.sparse_softmax_cross_entropy_with_logits(
</code>```

答:
According to the documentation, the argument labels must be a batch_size vector with values in [0, num_classes)
From your logs:

```<code>received label value of 1 which is outside the valid range of [0, 1)
</code>```

Perhaps the framework thinks that you have only one class because I also see that your Neural Network also has just 1 output.

Maybe for applying that SparseSoftmaxCrossEntropyWithLogits loss function you need 2 outputs. And your labels must be either 0 or 1.

Body:
I have a simple 2 layer Tensorflow model that I am trying to train on a dataset of equal-sized stereo audio files to tell me if the sound is coming more from the left side or the right side. This means the input is an array of 3072 by 2 arrays and the output is an array of 1's and 0's to represent left and right.

The problem is that when I run the program, it fails at model.fit() with an invalid argument error.

Code:

# -*- coding: utf-8 -*-
"""
Created on Tue Jan 18 15:51:56 2022

@author: andre
"""

import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras import layers
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ModelCheckpoint
from sklearn.model_selection import train_test_split
from datetime import datetime
from sklearn import metrics
from scipy.io import wavfile
import os
import glob

# Load in Right Side .WAV Data.
X1 = []
count1 = 0
database_path = "C:\\Users\\andre\\OneDrive\\Documents\\ESI2022\\MLDatabases\\Right\\"
for filename in glob.glob(os.path.join(database_path, '*.wav')):
    X1.append(wavfile.read(filename)[1])
    count1 = count1 + 1

# Load in Left side .WAV Data.
X2 = []
count2 = 0
database_path2 = "C:\\Users\\andre\\OneDrive\\Documents\\ESI2022\\MLDatabases\\Right\\"
for filename2 in glob.glob(os.path.join(database_path2, '*.wav')):
    X2.append(wavfile.read(filename2)[1])
    count2 = count2 + 1

# Get the smallest size audio file (this will be sample size input to model)
sample_size = len(X1[0])
for data in X1:
    if len(data) < sample_size:
        sample_size = len(data)

# Make audio data into equal size chunks
X1e = []
for i in X1:
    num_chunks = len(i)//sample_size
    for j in range(num_chunks):
        X1e.append(i[(j+1)*sample_size-sample_size:(j+1)*sample_size])
X1 = X1e

X2e = []
for i in X2:
    num_chunks = len(i)//sample_size
    for j in range(num_chunks):
        X2e.append(i[(j+1)*sample_size-sample_size:(j+1)*sample_size])
X2=X2e

del X1e
del X2e

# Create Output data that is the same length as the input data.
Y1 = np.ones([X1.__len__()],dtype='float32').tolist()
Y2 = np.zeros([X2.__len__()],dtype='float32').tolist()

# Concatenate Left and Right .WAV data and output data as numpy arrays.
X1.extend(X2)
X = np.asarray(X1)
Y = np.asarray(Y1+Y2).astype(np.int16)

#X=list(X)
#Y=list(Y)

# Split data into test training data.
X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.2,random_state=0,shuffle=True)

'''
print(X[1])
time = np.linspace(0.,33792, 33792)
plt.plot(time, X[1][:,1], label="Left channel")
plt.plot(time, X[1][:,0], label="Right channel")
plt.legend()
plt.xlabel("Time [s]")
plt.ylabel("Amplitude")
plt.show()
'''

# Create the Model
model = Sequential()

# Add a LSTM layer with 1 output, and ambiguous input data length.
model.add(layers.LSTM(1,batch_input_shape=(1,sample_size,2),return_sequences=True))
model.add(layers.LSTM(1,return_sequences=False))

# Compile Model
#history = model.compile(loss='mean_absolute_error', metrics=['accuracy'],optimizer='adam',output='sparse_categorical_crossentropy')
optimizer = Adam(learning_rate=2*1e-4)

'''
history = model.compile(optimizer=optimizer, loss={
                  'output': 'sparse_categorical_crossentropy', },
              metrics={
                  'output': 'sparse_categorical_accuracy', },
              sample_weight_mode='temporal')
'''

history = model.compile(
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    optimizer="adam",
    metrics=["accuracy"],
)
model.summary()

# Define Training Parameters
num_epochs = 200
num_batch_size = 1

# Save the most accurate model to file. (Verbosity Gives more information)
checkpointer = ModelCheckpoint(filepath="SavedModels/checkpointModel.hdf5", verbose=1,save_best_only=True)

# Start the timer
start = datetime.now()

# Train the model
model.fit(X_train,Y_train,batch_size=num_batch_size, epochs=num_epochs, validation_data=(X_test,Y_test), callbacks=[checkpointer],verbose=1)

# Get and Print Model Validation Accuracy
test_accuracy=model.evaluate(X_test,Y_test,verbose=0)
print(test_accuracy[1])

Output & error:

Model: "sequential_1"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 lstm_2 (LSTM)               (1, 3072, 1)              16

 lstm_3 (LSTM)               (1, 1)                    12

=================================================================
Total params: 28
Trainable params: 28
Non-trainable params: 0
_________________________________________________________________
Epoch 1/200

2022-02-07 09:40:36.348127: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cudart64_110.dll'; dlerror: cudart64_110.dll not found
2022-02-07 09:40:36.348459: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
2022-02-07 09:40:43.978976: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'nvcuda.dll'; dlerror: nvcuda.dll not found
2022-02-07 09:40:43.979029: W tensorflow/stream_executor/cuda/cuda_driver.cc:269] failed call to cuInit: UNKNOWN ERROR (303)
2022-02-07 09:40:43.985710: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:169] retrieving CUDA diagnostic information for host: DESKTOP-0FFTIDB
2022-02-07 09:40:43.986092: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:176] hostname: DESKTOP-0FFTIDB
2022-02-07 09:40:43.990164: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2022-02-07 09:40:48.470415: W tensorflow/core/framework/op_kernel.cc:1745] OP_REQUIRES failed at sparse_xent_op.cc:103 : INVALID_ARGUMENT: Received a label value of 1 which is outside the valid range of [0, 1).  Label values: 1
2022-02-07 09:58:29.070767: W tensorflow/core/framework/op_kernel.cc:1745] OP_REQUIRES failed at sparse_xent_op.cc:103 : INVALID_ARGUMENT: Received a label value of 1 which is outside the valid range of [0, 1).  Label values: 1
Traceback (most recent call last):

  File "C:\Users\andre\OneDrive\Documents\ESI2022\PythonScripts\BeltML\testML.py", line 127, in <module>
    model.fit(X_train,Y_train,batch_size=num_batch_size, epochs=num_epochs, validation_data=(X_test,Y_test), callbacks=[checkpointer],verbose=1)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None

  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\eager\execute.py", line 58, in quick_execute
    tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,

InvalidArgumentError:  Received a label value of 1 which is outside the valid range of [0, 1).  Label values: 1
     [[node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits
 (defined at C:\ProgramData\Anaconda3\lib\site-packages\keras\backend.py:5113)
]] [Op:__inference_train_function_9025]

Errors may have originated from an input operation.
Input Source operations connected to node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits:
In[0] sparse_categorical_crossentropy/Reshape_1 (defined at C:\ProgramData\Anaconda3\lib\site-packages\keras\backend.py:5109)
In[1] sparse_categorical_crossentropy/Reshape (defined at C:\ProgramData\Anaconda3\lib\site-packages\keras\backend.py:3561)

Operation defined at: (most recent call last)
  File "C:\ProgramData\Anaconda3\lib\runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,

  File "C:\ProgramData\Anaconda3\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\console\__main__.py", line 23, in <module>
    start.main()

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\console\start.py", line 328, in main
    kernel.start()

  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\kernelapp.py", line 677, in start
    self.io_loop.start()

  File "C:\ProgramData\Anaconda3\lib\site-packages\tornado\platform\asyncio.py", line 199, in start
    self.asyncio_loop.run_forever()

  File "C:\ProgramData\Anaconda3\lib\asyncio\base_events.py", line 570, in run_forever
    self._run_once()

  File "C:\ProgramData\Anaconda3\lib\asyncio\base_events.py", line 1859, in _run_once
    handle._run()

  File "C:\ProgramData\Anaconda3\lib\asyncio\events.py", line 81, in _run
    self._context.run(self._callback, *self._args)

  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 457, in dispatch_queue
    await self.process_one()

  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 446, in process_one
    await dispatch(*args)

  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 353, in dispatch_shell
    await result

  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 648, in execute_request
    reply_content = await reply_content

  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\ipkernel.py", line 353, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)

  File "C:\ProgramData\Anaconda3\lib\site-packages\ipykernel\zmqshell.py", line 533, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)

  File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2901, in run_cell
    result = self._run_cell(

  File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2947, in _run_cell
    return runner(coro)

  File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\async_helpers.py", line 68, in _pseudo_sync_runner
    coro.send(None)

  File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3172, in run_cell_async
    has_raised = await self.run_ast_nodes(code_ast.body, cell_name,

  File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3364, in run_ast_nodes
    if (await self.run_code(code, result,  async_=asy)):

  File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3444, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)

  File "C:\Users\andre\AppData\Local\Temp/ipykernel_3604/1229251547.py", line 1, in <module>
    runfile('C:/Users/andre/OneDrive/Documents/ESI2022/PythonScripts/BeltML/testML.py', wdir='C:/Users/andre/OneDrive/Documents/ESI2022/PythonScripts/BeltML')

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 577, in runfile
    exec_code(file_code, filename, ns_globals, ns_locals,

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 465, in exec_code
    exec(compiled, ns_globals, ns_locals)

  File "C:\Users\andre\OneDrive\Documents\ESI2022\PythonScripts\BeltML\testML.py", line 127, in <module>
    model.fit(X_train,Y_train,batch_size=num_batch_size, epochs=num_epochs, validation_data=(X_test,Y_test), callbacks=[checkpointer],verbose=1)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\utils\traceback_utils.py", line 64, in error_handler
    return fn(*args, **kwargs)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 1216, in fit
    tmp_logs = self.train_function(iterator)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 878, in train_function
    return step_function(self, iterator)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 867, in step_function
    outputs = model.distribute_strategy.run(run_step, args=(data,))

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 860, in run_step
    outputs = model.train_step(data)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\training.py", line 809, in train_step
    loss = self.compiled_loss(

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\compile_utils.py", line 201, in __call__
    loss_value = loss_obj(y_t, y_p, sample_weight=sw)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\losses.py", line 141, in __call__
    losses = call_fn(y_true, y_pred)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\losses.py", line 245, in call
    return ag_fn(y_true, y_pred, **self._fn_kwargs)

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\losses.py", line 1737, in sparse_categorical_crossentropy
    return backend.sparse_categorical_crossentropy(

  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\backend.py", line 5113, in sparse_categorical_crossentropy
    res = tf.nn.sparse_softmax_cross_entropy_with_logits(

Body:
According to the documentation, the argument labels must be a batch_size vector with values in [0, num_classes)
From your logs:

received label value of 1 which is outside the valid range of [0, 1)

Perhaps the framework thinks that you have only one class because I also see that your Neural Network also has just 1 output.

Maybe for applying that SparseSoftmaxCrossEntropyWithLogits loss function you need 2 outputs. And your labels must be either 0 or 1.


问:
Output CosmosDB String
I'm trying to call out Connection Strings from the CosmosDB in to KeyVault Secret. I keep getting this error but am unsure what the fix is.

There is nothing online what suggests on how to call out the CosmosDB

The output code is

```<code>output "connection_strings" {
value = azurerm_cosmosdb_account.cosmos_db.connection_strings
}
</code>```

and on key vault resource is setout as this

```<code>resource "azurerm_key_vault_secret" "test" {
name = "Tst"
value = module.cosmosDB.connection_strings
key_vault_id = module.kv-secrets.id
}
</code>```

The error that I get in the CLI is module.cosmosDB.connection_strings is list of string with 4 elements

答:
The way to access the first element of the connection_strings array for cosmos in terraform is like so

```<code>azurerm_cosmosdb_account.foo.connection_strings.0
</code>```

Where foo is the local name of the terraform resource you have defined e.g.

```<code>resource "azurerm_cosmosdb_account" "foo" {
   ...
}
</code>```

Title: Output CosmosDB String

Body:
I'm trying to call out Connection Strings from the CosmosDB in to KeyVault Secret. I keep getting this error but am unsure what the fix is.

There is nothing online what suggests on how to call out the CosmosDB

The output code is

output "connection_strings" {
value = azurerm_cosmosdb_account.cosmos_db.connection_strings
}

and on key vault resource is setout as this

resource "azurerm_key_vault_secret" "test" {
name = "Tst"
value = module.cosmosDB.connection_strings
key_vault_id = module.kv-secrets.id
}

The error that I get in the CLI is module.cosmosDB.connection_strings is list of string with 4 elements

Body:
The way to access the first element of the connection_strings array for cosmos in terraform is like so

azurerm_cosmosdb_account.foo.connection_strings.0

Where foo is the local name of the terraform resource you have defined e.g.

resource "azurerm_cosmosdb_account" "foo" {
   ...
}


问:
belongsToMany doesn't return the expected query
In my application I have a table called users, each user can have one or multiple roles (I'm using laratrust), in this scenario I will cover the tenant and the patient role.

The package santigator/laratrust handle the role within this tables:

roles: all the roles available

role_user: pivot table

Now, my app allows patient users to invite other users to register to the app, and they will automatically have the role of tenant. The patient user must also associate one or more riskareas for the invited user. In this way the "tenant" will have access only to certain areas of the patient user.

I handle the situation above in the invites table, this is the design to explain better:

The problem here is that we have a single users model that manages multiple roles (patient and tenant) and I have to make sure that the user model is able to return the tenants associated with a patient and vice versa.

So I though to declare in the User model two methods: patients() and tenants(), I started with the patients method:

```<code>public function patients()
{
    return $this->belongsToMany(User::class, 'invites')->withPivot('tenant_id');
}
</code>```

when I do:

```<code>dd(auth()->user()->patients()->toSql());
</code>```

It returns the following query:

```<code>"select * from `users` inner join `invites` on `users`.`id` = `invites`.`user_id` where `invites`.`user_id` = ? and `users`.`deleted_at` is null"
</code>```

which returns an empty collection, the query should return this:

```<code>"select * from `users` inner join `invites` on `users`.`id` = `invites`.`user_id` where `invites`.`tenant_id` = ? and `users`.`deleted_at` is null"
</code>```

I'm not sure if I'm handling this situation correctly. Someone could give me an help on this?

Kind regards

UPDATE

```<code>return $this->hasManyThrough(
    User::class,
    Invite::class,
    'tenant_id',
    'id',
    '123',
    'user_id'
);
</code>```

RESULT:

```<code>"select * from `users` inner join `invites` on `invites`.`user_id` = `users`.`id` where `invites`.`tenant_id` is null and `users`.`deleted_at` is null and `invites`.`deleted_at` is null"
</code>```

Why: where invites.tenant_id is null ?

答:
You have an issue with your foreign keys:

public function patients()
{
    return $this->belongsToMany(User::class,'invites', 'user_id', 'tenant_id');
}
```

More info about belongsToMany: https://laravel.com/docs/8.x/eloquent-relationships#many-to-many-model-structure

Body:
In my application I have a table called users, each user can have one or multiple roles (I'm using laratrust), in this scenario I will cover the tenant and the patient role.

The package santigator/laratrust handle the role within this tables:

roles: all the roles available

role_user: pivot table

Now, my app allows patient users to invite other users to register to the app, and they will automatically have the role of tenant. The patient user must also associate one or more riskareas for the invited user. In this way the "tenant" will have access only to certain areas of the patient user.

I handle the situation above in the invites table, this is the design to explain better:

The problem here is that we have a single users model that manages multiple roles (patient and tenant) and I have to make sure that the user model is able to return the tenants associated with a patient and vice versa.

So I though to declare in the User model two methods: patients() and tenants(), I started with the patients method:

public function patients()
{
    return $this->belongsToMany(User::class, 'invites')->withPivot('tenant_id');
}

when I do:

dd(auth()->user()->patients()->toSql());

It returns the following query:

"select * from `users` inner join `invites` on `users`.`id` = `invites`.`user_id` where `invites`.`user_id` = ? and `users`.`deleted_at` is null"

which returns an empty collection, the query should return this:

"select * from `users` inner join `invites` on `users`.`id` = `invites`.`user_id` where `invites`.`tenant_id` = ? and `users`.`deleted_at` is null"

I'm not sure if I'm handling this situation correctly. Someone could give me an help on this?

Kind regards

UPDATE

return $this->hasManyThrough(
    User::class,
    Invite::class,
    'tenant_id',
    'id',
    '123',
    'user_id'
);

RESULT:

"select * from `users` inner join `invites` on `invites`.`user_id` = `users`.`id` where `invites`.`tenant_id` is null and `users`.`deleted_at` is null and `invites`.`deleted_at` is null"

Why: where invites.tenant_id is null ?

Body:
You have an issue with your foreign keys:

public function patients()
{
    return $this->belongsToMany(User::class,'invites', 'user_id', 'tenant_id');
}

More info about belongsToMany: https://laravel.com/docs/8.x/eloquent-relationships#many-to-many-model-structure


问:
× TypeError: Cannot read properties of undefined (reading 'name') react js
i am not able to display country name,image and rating can anyone explain me why this is happening [https://api.tvmaze.com/search/shows?q=avengers] it is the API link.all other data are displaying but these 3 are not working and throwing error.</p>
```<code>import React, {useState, useEffect} from 'react'
import ReactDOM from 'react-dom'
import axios from 'axios'

const App = () => {
  const url = 'https://api.tvmaze.com/search/shows?q=avengers'

  const [data, setData] = useState([])

  useEffect(() => {
    axios.get(url).then((json) => setData(json.data))
  }, [])

  const renderTable = () => {
    return data.map((user) => {
      return (
        <tr>
          <td>{user.show.name}</td>
          <td>{user.show.language}</td>
          <td>{user.show.genres}</td>
          <td>{user.show.runtime}</td>
          <td>{user.show.premiered}</td>
          <td>{user.show.rating}</td>
          <td>{user.show.country.name}</td>
          <td>{user.image.medium}</td>

        </tr>
      )
    })
  }

  return (
    <div>
      <h1 id="title">API Table</h1>
      <table id="users">
        <thead>
          <tr>
            <th>Name</th>
            <th>language</th>
            <th>genres</th>
            <th>runtime</th>
            <th>premiered</th>
            <th>Rating</th>
            <th>country name</th>
            <th>image</th>

          </tr>
        </thead>
        <tbody>{renderTable()}</tbody>
      </table>
    </div>
  )
}
export default App
</code>```

答:
Those fields are missing from the API data for some of the items. You should guard against that eventuality by using them as:

```<code><td>{user?.show?.country?.name}</td>
<td>{user?.image?.medium}</td>
</code>```

EDIT:
I've also noticed some of the fields were just wrong. Maybe try the following for the last 3 lines:

```<code><td>{user?.show?.rating?.average}</td>
<td>{user?.show?.country?.name}</td>
<td>{user?.show?.image?.medium}</td>
</code>```

Body:
i am not able to display country name,image and rating can anyone explain me why this is happening [https://api.tvmaze.com/search/shows?q=avengers] it is the API link.all other data are displaying but these 3 are not working and throwing error.

import React, {useState, useEffect} from 'react'
import ReactDOM from 'react-dom'
import axios from 'axios'

const App = () => {
  const url = 'https://api.tvmaze.com/search/shows?q=avengers'

  const [data, setData] = useState([])

  useEffect(() => {
    axios.get(url).then((json) => setData(json.data))
  }, [])

  const renderTable = () => {
    return data.map((user) => {
      return (

          {user.show.name}
          {user.show.language}
          {user.show.genres}
          {user.show.runtime}
          {user.show.premiered}
          {user.show.rating}
          {user.show.country.name}
          {user.image.medium}

      )
    })
  }

  return (

API Table

            Name
            language
            genres
            runtime
            premiered
            Rating
            country name
            image

{renderTable()}

  )
}
export default App

Body:
Those fields are missing from the API data for some of the items. You should guard against that eventuality by using them as:

<td>{user?.show?.country?.name}</td>
<td>{user?.image?.medium}</td>

EDIT:
I've also noticed some of the fields were just wrong. Maybe try the following for the last 3 lines:

<td>{user?.show?.rating?.average}</td>
<td>{user?.show?.country?.name}</td>
<td>{user?.show?.image?.medium}</td>