问:
ErrorException Attempt to read property "name" on null (View:
I have 2 relationships that point to the same User model: operador() and profesional().

```<code>class Cita extends Model
{

    public function paciente(){

        return $this->belongsTo('\App\Models\Paciente');

    }

    public function profesional(){

        return $this->belongsTo('\App\Models\User');

    }

    public function operador(){

        return $this->belongsTo('\App\Models\User');

    }

}
</code>```

In the view I call them like this:

```<code>                        @foreach ($comisiones as $comision)
                            <tr>

                            <td>{{ $comision->paciente->name }}</td>

                            <td>{{ $comision->profesional->name }}</td>
                            <td>{{ $comision->operador->name }}</td>

                            <td>{{ number_format($comision->total, 0, '.', '.') }}</td>
                            <td>{{ $comision->estado }}</td>
                            </tr>
                        @endforeach
</code>```

The program crashes on me when it tries to call $commision->operador->name. If I leave it as a comment it works without problems. But it gives me an error when I have the 2 relations at the same time.

Can I have 2 relationships pointing to the same model? And if not, what alternative do I have? Thanks

答:
For the fact that you are using belongTo relationship, that means User is the parent model and Professional and Operador are the child model.

Hence, it is expected that the table for Professional has a column called user_id, thesame thing for the Operador table, it should have user_id column.

With this the relationship will work just fine.

Yes, you can have 2 relationships pointing to the same model.

Body:
I have 2 relationships that point to the same User model: operador() and profesional().

class Cita extends Model
{

    public function paciente(){

        return $this->belongsTo('\App\Models\Paciente');

    }

    public function profesional(){

        return $this->belongsTo('\App\Models\User');

    }

    public function operador(){

        return $this->belongsTo('\App\Models\User');

    }

}

In the view I call them like this:

                        @foreach ($comisiones as $comision)

                            {{ $comision->paciente->name }}

                            {{ $comision->profesional->name }}
                            {{ $comision->operador->name }}

                            {{ number_format($comision->total, 0, '.', '.') }}
                            {{ $comision->estado }}

                        @endforeach

The program crashes on me when it tries to call $commision->operador->name. If I leave it as a comment it works without problems. But it gives me an error when I have the 2 relations at the same time.

Can I have 2 relationships pointing to the same model? And if not, what alternative do I have? Thanks


来源: stackexchange

问:
Sql Server 2005 using count and distinct together
I'm trying to get the count of each distinct field in my database. For example, we are using something called sourceCodes - I want to be able to see how many of each different sourceCode there is in my database. So far, I have this

```<code>SELECT sourceCode, COUNT(DISTINCT sourceCode)
FROM [SecureOrders]
WHERE DateTime >= DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
  AND DateTime < DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1)
GROUP BY sourceCode
</code>```

(I'm trying to display the name of the sourceCode first, and then the count). So far though, the only thing I ever get in my second column is "1"...and I'm positive there are more than one. I know I worded this question really poorly, but I can't really figure out any other way to say it. Can anybody see why this is happening?

答:
Remove the DISTINCT:</p>

```<code>SELECT sourceCode, COUNT(sourceCode)
FROM [SecureOrders]
WHERE DateTime >= DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
  AND DateTime < DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1)
GROUP BY sourceCode
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get the count of each distinct field in my database. For example, we are using something called sourceCodes - I want to be able to see how many of each different sourceCode there is in my database. So far, I have this

SELECT sourceCode, COUNT(DISTINCT sourceCode)
FROM [SecureOrders]
WHERE DateTime >= DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
  AND DateTime < DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1)
GROUP BY sourceCode

(I'm trying to display the name of the sourceCode first, and then the count). So far though, the only thing I ever get in my second column is "1"...and I'm positive there are more than one. I know I worded this question really poorly, but I can't really figure out any other way to say it. Can anybody see why this is happening?

Body:
Remove the DISTINCT:

SELECT sourceCode, COUNT(sourceCode)
FROM [SecureOrders]
WHERE DateTime >= DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
  AND DateTime < DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1)
GROUP BY sourceCode


问:
How to insert React state value into HTML Template with predefined value in Sun Editor?
I have some user insert fields like title, date, time, and also a select dropdown option with some values. Below these fields, there is a text editing option using suneditor react, so when I click the select dropdown then automatically an HTML template with predefined value is inserted into this text editing filed.

Now I want to replace the predefined values of text editing field with user inserted date, time etc. Any resource, video, blog or advice?

FAQ: this is an invitation template integrated with mail config, where a dropdown list item is selected then predefined data are inserted into text editing field of sun editor, now need to change some value from user inserted input field.

答:
I think you are probably looking for this:

setContents(contents)

```<code>Change the contents of the suneditor
Parameters:
Name      Type    Description
contents  String  Contents to Input

Where contents can be a state string...
</code>```
```<code>import React, { useState } from 'react';

const [content, setContent] = useState("<span>Hello monster dev!!!</span>");
<SunEditor
      name="content"
      setContents={content}// <=
      placeholder="Dev Monster"
      defaultValue={content}
      onChange={text => setContent(text)}
    ...
/>
</code>```

Ref: http://suneditor.com/sample/html/out/document-user.html

ContentLicense: CC BY-SA 4.0

Body:
I think you are probably looking for this:

setContents(contents)

Change the contents of the suneditor
Parameters:
Name      Type    Description
contents  String  Contents to Input

Where contents can be a state string...

import React, { useState } from 'react';

const [content, setContent] = useState("<span>Hello monster dev!!!</span>");
<SunEditor
      name="content"
      setContents={content}// <=
      placeholder="Dev Monster"
      defaultValue={content}
      onChange={text => setContent(text)}
    ...
/>

Ref: http://suneditor.com/sample/html/out/document-user.html


问:
Why can't radio buttons be "readonly"?
I would like to show a radio button, have its value submitted, but depending on the circumstances, have it not editable. Disabled doesn't work, because it doesn't submit the value (or does it?), and it grays out the radio button. Read-only is really what I'm looking for, but for some mysterious reason it doesn't work.

Is there some weird trick I need to pull to get read-only to work as expected? Should I just do it in JavaScript instead?

Incidentally, does anyone know why read-only doesn't work in radio buttons, while it does work in other input tags? Is this one of those incomprehensible omissions in the HTML specs?

答:
Extract from https://stackoverflow.com/a/71086058/18183749

If you can't use the 'disabled' attribut (as it erases the value's
input at POST), and noticed that html attribut 'readonly' works only
on textarea and some input(text, password, search, as far I've seen),
and finally, if you don't want to bother with duplicating all your
select, checkbox and radio with hidden input, you might find the
following function or any of his inner logics to your liking :

```<code>addReadOnlyToFormElements = function (idElement) {
    // html readonly don't work on input of type checkbox and radio, neither on select. So, a safe trick is to disable the non-selected items
    $('#' + idElement + ' input[type="radio"]:not(:checked)').prop('disabled',true);

    // and, on the selected ones, mimic readonly appearance
    $('#' + idElement + ' input[type="radio"]:checked').css('opacity','0.5');
}
</code>```

And there's nothing easier than to remove these readonly

```<code>removeReadOnlyFromFormElements = function (idElement) {
    // Remove the disabled attribut on non-selected
    $('#' + idElement + ' input[type="radio"]:not(:checked)').prop('disabled',false);

    // Remove readonly appearance on selected ones
    $('#' + idElement + ' input[type="radio"]:checked').css('opacity','');
}
</code>```

Title: Why can't radio buttons be "readonly"?

Body:
Extract from https://stackoverflow.com/a/71086058/18183749

If you can't use the 'disabled' attribut (as it erases the value's
input at POST), and noticed that html attribut 'readonly' works only
on textarea and some input(text, password, search, as far I've seen),
and finally, if you don't want to bother with duplicating all your
select, checkbox and radio with hidden input, you might find the
following function or any of his inner logics to your liking :

addReadOnlyToFormElements = function (idElement) {
    // html readonly don't work on input of type checkbox and radio, neither on select. So, a safe trick is to disable the non-selected items
    $('#' + idElement + ' input[type="radio"]:not(:checked)').prop('disabled',true);

    // and, on the selected ones, mimic readonly appearance
    $('#' + idElement + ' input[type="radio"]:checked').css('opacity','0.5');
}

And there's nothing easier than to remove these readonly

removeReadOnlyFromFormElements = function (idElement) {
    // Remove the disabled attribut on non-selected
    $('#' + idElement + ' input[type="radio"]:not(:checked)').prop('disabled',false);

    // Remove readonly appearance on selected ones
    $('#' + idElement + ' input[type="radio"]:checked').css('opacity','');
}


问:
SSL verification error when running `gem install bundler` on fresh MacBookPRO M1
Successfully installed asdf install ruby 2.6.6 following this post on my fresh MacBook Pro M1 2021, and trying to run gem install bundler, but getting this:

```<code>MacBook-Pro ~ % gem install bundler
ERROR:  SSL verification error at depth 1: unable to get local issuer certificate (20)
ERROR:  You must add /OU=GlobalSign Root CA - R3/O=GlobalSign/CN=GlobalSign to your local trusted store
ERROR:  SSL verification error at depth 1: unable to get local issuer certificate (20)
ERROR:  You must add /OU=GlobalSign Root CA - R3/O=GlobalSign/CN=GlobalSign to your local trusted store
ERROR:  SSL verification error at depth 1: unable to get local issuer certificate (20)
ERROR:  You must add /OU=GlobalSign Root CA - R3/O=GlobalSign/CN=GlobalSign to your local trusted store
ERROR:  Could not find a valid gem 'bundler' (>= 0), here is why:
  Unable to download data from https://rubygems.org/ - SSL_connect returned=1 errno=0 state=error: certificate verify failed (unable to get local issuer certificate) (https://rubygems.org/specs.4.8.gz)
ERROR:  SSL verification error at depth 1: unable to get local issuer certificate (20)
ERROR:  You must add /OU=GlobalSign Root CA - R3/O=GlobalSign/CN=GlobalSign to your local trusted store
ERROR:  SSL verification error at depth 1: unable to get local issuer certificate (20)
ERROR:  You must add /OU=GlobalSign Root CA - R3/O=GlobalSign/CN=GlobalSign to your local trusted store
</code>```

I tried to open Mac's Keychain Access window and specify Always Trust option for every GlobalSign certificate, but no luck.

OS: MacOS Monterey 12.0.1

ruby -v: 2.6.6

gem -v: 3.0.3

Homebrew: 3.3.4

答:
I also followed that guide, and ran into this issue. Try this:
check directory /opt/homebrew/etc
see if you have openssl@1.1
if not, you probably need to reinstall using brew reinstall openssl@1.1. openssl1.1 is what i use for ruby 2.6.5, you might need to check that for your ruby version.

Also, i am not entirely sure about this, but I also added a couple more env variables to the ~/zshrc file following this guide. Be sure you are changing the "openssl@1.0" to "openssl@1.1" or whatever your ruby version uses.

Body:
Successfully installed asdf install ruby 2.6.6 following this post on my fresh MacBook Pro M1 2021, and trying to run gem install bundler, but getting this:

MacBook-Pro ~ % gem install bundler
ERROR:  SSL verification error at depth 1: unable to get local issuer certificate (20)
ERROR:  You must add /OU=GlobalSign Root CA - R3/O=GlobalSign/CN=GlobalSign to your local trusted store
ERROR:  SSL verification error at depth 1: unable to get local issuer certificate (20)
ERROR:  You must add /OU=GlobalSign Root CA - R3/O=GlobalSign/CN=GlobalSign to your local trusted store
ERROR:  SSL verification error at depth 1: unable to get local issuer certificate (20)
ERROR:  You must add /OU=GlobalSign Root CA - R3/O=GlobalSign/CN=GlobalSign to your local trusted store
ERROR:  Could not find a valid gem 'bundler' (>= 0), here is why:
  Unable to download data from https://rubygems.org/ - SSL_connect returned=1 errno=0 state=error: certificate verify failed (unable to get local issuer certificate) (https://rubygems.org/specs.4.8.gz)
ERROR:  SSL verification error at depth 1: unable to get local issuer certificate (20)
ERROR:  You must add /OU=GlobalSign Root CA - R3/O=GlobalSign/CN=GlobalSign to your local trusted store
ERROR:  SSL verification error at depth 1: unable to get local issuer certificate (20)
ERROR:  You must add /OU=GlobalSign Root CA - R3/O=GlobalSign/CN=GlobalSign to your local trusted store

I tried to open Mac's Keychain Access window and specify Always Trust option for every GlobalSign certificate, but no luck.

OS: MacOS Monterey 12.0.1

ruby -v: 2.6.6

gem -v: 3.0.3

Homebrew: 3.3.4


问:
Apollo GraphQl Backend using Fetch API mutation
I am running an apollo graphql backend and vanilla javascript fetch API in front-end it is running in chrome extension
the Query works fine but the Mutation doesn't work and is returning a 400 error
I am running this in Chrome extension and the query in there works</p>
```<code>    fetch('https://dev.api.sharpstudy.io/graphql', {
        method: 'POST',
        headers: {
            authorization: `Bearer ${token}`,
            'Content-Type': 'application/json',
            Accept: "application/json, text/plain"

        },
        body: JSON.stringify({
            query: `
            mutation createBrowserTab {
                    createBrowserTab (userId: ${userId}, tabName: ${title}, tabDescription: ${title}, tabUrl:${url}, subjectId: ${subId}){
                      SavedBrowserTab {
                        tabId
                        tabUrl
                        tabName
                        tabDescription
                        subjectId
                        userId
                      }
                      message
                    }
                  }
      `,
            // variables: {
            //     userId: userId,
            //     title: title,
            //     url: url,
            //     subId: subId

            // },
        }),
    })
        .then((res) => res.json())
        .then((result) => console.log(result));

</code>```

答:
I have finally solved it I had to save the mutation in a query and then wrap it in  quotes and it works like a charm
below is the code</p>
```<code>var crateTabMutation = `
    mutation createBrowserTab {
            createBrowserTab (userId: ${userId}, tabName: "${tab.title}", tabDescription:  "${tab.title}", tabUrl:"${tab.url}", subjectId: "${subId}"){
              SavedBrowserTab {
                tabId
                tabUrl
                tabName
                tabDescription
                subjectId
                userId
              }
              message
            }
          }
`

  fetch('https://dev.api.sharpstudy.io/graphql', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      query: crateTabMutation,

    }),
  })
    .then((res) => res.json())
    .then((result) => console.log(result));

</code>```

Body:
I am running an apollo graphql backend and vanilla javascript fetch API in front-end it is running in chrome extension
the Query works fine but the Mutation doesn't work and is returning a 400 error
I am running this in Chrome extension and the query in there works

    fetch('https://dev.api.sharpstudy.io/graphql', {
        method: 'POST',
        headers: {
            authorization: `Bearer ${token}`,
            'Content-Type': 'application/json',
            Accept: "application/json, text/plain"

        },
        body: JSON.stringify({
            query: `
            mutation createBrowserTab {
                    createBrowserTab (userId: ${userId}, tabName: ${title}, tabDescription: ${title}, tabUrl:${url}, subjectId: ${subId}){
                      SavedBrowserTab {
                        tabId
                        tabUrl
                        tabName
                        tabDescription
                        subjectId
                        userId
                      }
                      message
                    }
                  }
      `,
            // variables: {
            //     userId: userId,
            //     title: title,
            //     url: url,
            //     subId: subId

            // },
        }),
    })
        .then((res) => res.json())
        .then((result) => console.log(result));

Body:
I have finally solved it I had to save the mutation in a query and then wrap it in  quotes and it works like a charm
below is the code

var crateTabMutation = `
    mutation createBrowserTab {
            createBrowserTab (userId: ${userId}, tabName: "${tab.title}", tabDescription:  "${tab.title}", tabUrl:"${tab.url}", subjectId: "${subId}"){
              SavedBrowserTab {
                tabId
                tabUrl
                tabName
                tabDescription
                subjectId
                userId
              }
              message
            }
          }
`

  fetch('https://dev.api.sharpstudy.io/graphql', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      query: crateTabMutation,

    }),
  })
    .then((res) => res.json())
    .then((result) => console.log(result));


问:
C++ Lambda - Loop over integer array
I'm trying to loop over an integer array using a lambda template.

The code to invoke the lambda would look something like this (demo purposes, not functional code):

```<code>menu.option("Set Pedestrian Health to 0").allpeds(ped => {
     SET_ENTITY_HEALTH(ped, 0);
});
</code>```

The problem: how would I make the allpeds lambda template?

allpeds would loop over an array of unique integers representing a pedestrian in the game.

I have this code so far:

```<code>template<typename T> Menu& allpeds() {
    if (pressed()) {
        int numElements = 20;
        int arrSize = numElements * 2 + 2;

        int peds[arrSize];
        peds[0] = numElements;

        int countPeds = PED::GET_PED_NEARBY_PEDS(playerPed, peds, -1);

        for (int i = 0; i < countPeds; i++) {
            int ped = peds[i * 2 + 2];

            // if this is the right way to do it,
            // how to put `ped` in an integer array, and return it
            // so I can use it in the lambda template?
        }
    }

    //return *this;
}
</code>```

I'm trying to keep the code as C as possible.

If more explanation is needed, please let me know!

答:
The example you have shown is more C# than C++, as far as the lambda syntax is concerned.  But even then, the example is clearly passing the lambda as a parameter to allpeds(), and the lambda itself takes an input parameter, too. allpeds() is not returning an array that the lambda then iterates, allpeds() calls the lambda passing it each integer value as needed.

In C++, you can use something like this:

menu.option("Set Pedestrian Health to 0").allpeds(
    [](int ped) {
        SET_ENTITY_HEALTH(ped, 0);
    }
);
```
<pre class="lang-cpp prettyprint-override"><code>template<typename FuncType>
Menu& allpeds(FuncType func) {
    if (pressed()) {
        int numElements = 20;
        int arrSize = numElements * 2 + 2;

        std::vector<int> peds(arrSize);
        peds[0] = numElements;

        int countPeds = PED::GET_PED_NEARBY_PEDS(playerPed, peds.data(), -1);

        for (int i = 0; i < countPeds; ++i) {
            int ped = peds[i * 2 + 2];
            func(ped);
        }
    }

    return *this;
}
</code>```

Title: C++ Lambda - Loop over integer array

Body:
I'm trying to loop over an integer array using a lambda template.

The code to invoke the lambda would look something like this (demo purposes, not functional code):

menu.option("Set Pedestrian Health to 0").allpeds(ped => {
     SET_ENTITY_HEALTH(ped, 0);
});

The problem: how would I make the allpeds lambda template?

allpeds would loop over an array of unique integers representing a pedestrian in the game.

I have this code so far:

template<typename T> Menu& allpeds() {
    if (pressed()) {
        int numElements = 20;
        int arrSize = numElements * 2 + 2;

        int peds[arrSize];
        peds[0] = numElements;

        int countPeds = PED::GET_PED_NEARBY_PEDS(playerPed, peds, -1);

        for (int i = 0; i < countPeds; i++) {
            int ped = peds[i * 2 + 2];

            // if this is the right way to do it,
            // how to put `ped` in an integer array, and return it
            // so I can use it in the lambda template?
        }
    }

    //return *this;
}

I'm trying to keep the code as C as possible.

If more explanation is needed, please let me know!

Body:
The example you have shown is more C# than C++, as far as the lambda syntax is concerned.  But even then, the example is clearly passing the lambda as a parameter to allpeds(), and the lambda itself takes an input parameter, too. allpeds() is not returning an array that the lambda then iterates, allpeds() calls the lambda passing it each integer value as needed.

In C++, you can use something like this:

menu.option("Set Pedestrian Health to 0").allpeds(
    [](int ped) {
        SET_ENTITY_HEALTH(ped, 0);
    }
);

template<typename FuncType>
Menu& allpeds(FuncType func) {
    if (pressed()) {
        int numElements = 20;
        int arrSize = numElements * 2 + 2;

        std::vector<int> peds(arrSize);
        peds[0] = numElements;

        int countPeds = PED::GET_PED_NEARBY_PEDS(playerPed, peds.data(), -1);

        for (int i = 0; i < countPeds; ++i) {
            int ped = peds[i * 2 + 2];
            func(ped);
        }
    }

    return *this;
}


问:
Without reloading Tableview, update the changed index cell values using Observer in iOS Swift
In the first time I collect the array values from API response and displayed it in tableview, again I will get the same response from socket and reload the values in table, But here I don't need to reload entire table, I want update the cell's which value has been changed.

Here Compare the two array's, from which index has changes, just need to update that index row cells only, without reload entire table view.old and new array, CodeSample

答:
But you should be careful if will change some indexPaths in you data stack, if it gonna happen - use tableView.deleteRows or tableView.deleteSections. This updates should be qual in table and in dataStack or crash

```<code>let indexPaths = [IndexPath]()
tableView.performBatchUpdates {
    self.tableView.reloadRows(at: indexPaths, with: .none)
}
</code>```

or

```<code>tableView.beginUpdates()
tableView.reloadRows(at: indexPaths, with: .none)
tableView.endUpdates()
</code>```

btw, you can make your indexPaths to update like let indexPaths = tableView.indexPathsForVisibleRows - method's name is speechful, in case if you have socket I suppose it would be helpful since u've got dynamic

Body:
But you should be careful if will change some indexPaths in you data stack, if it gonna happen - use tableView.deleteRows or tableView.deleteSections. This updates should be qual in table and in dataStack or crash

let indexPaths = [IndexPath]()
tableView.performBatchUpdates {
    self.tableView.reloadRows(at: indexPaths, with: .none)
}

or

tableView.beginUpdates()
tableView.reloadRows(at: indexPaths, with: .none)
tableView.endUpdates()

btw, you can make your indexPaths to update like let indexPaths = tableView.indexPathsForVisibleRows - method's name is speechful, in case if you have socket I suppose it would be helpful since u've got dynamic


问:
MapStruct - @Mapper annotation don't create bean
I downloaded application from this source https://github.com/springframeworkguru/spring5-mvc-rest/tree/vendor-api
And I have a problem with MapStruct.

```<code>@Mapper
public interface CategoryMapper {

CategoryMapper INSTANCE = Mappers.getMapper(CategoryMapper.class);

CategoryDTO categoryToCategoryDTO(Category category);
</code>```

}

```<code>@Data
public class CategoryDTO {
    private Long id;
    private String name;
}
</code>```

domain class:

```<code>@Data
@Entity
public class Category {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
}
</code>```

Service class:

```<code>@Service
public class CategoryServiceImpl implements CategoryService {

    private final CategoryMapper categoryMapper;
    private final CategoryRepository categoryRepository;

    public CategoryServiceImpl(CategoryMapper categoryMapper, CategoryRepository categoryRepository) {
        this.categoryMapper = categoryMapper;
        this.categoryRepository = categoryRepository;
    }
}
</code>```

And in pom.xml dependency, I paste only two::

```<code><properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <org.mapstruct.version>1.2.0.CR2</org.mapstruct.version>
</properties>
<dependency>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct-jdk8</artifactId>
        <version>${org.mapstruct.version}</version>
</dependency>
</code>```

And plugin:

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.7.0</version>
    <configuration>
        <source>1.8</source>
        <target>1.8</target>
        <annotationProcessorPaths>
            <path>
                 <groupId>org.projectlombok</groupId>
                 <artifactId>lombok</artifactId>
                 <version>${lombok.version}</version>
            </path>
            <path>
                 <groupId>org.mapstruct</groupId>
                 <artifactId>mapstruct-processor</artifactId>
                 <version>${org.mapstruct.version}</version>
           </path>
        </annotationProcessorPaths>
        <compilerArgs>
           <compilerArg>
                 -Amapstruct.defaultComponentModel=spring
           </compilerArg>
        </compilerArgs>
    </configuration>
</plugin>
</code>```

Description:

```<code>Parameter 0 of constructor in
guru.springfamework.services.CategoryServiceImpl required a bean of type 'guru.springfamework.api.v1.mapper.CategoryMapper' that could not be found.
</code>```

Action:

```<code>Consider defining a bean of type 'guru.springfamework.api.v1.mapper.CategoryMapper' in your configuration.
</code>```

I think that in my Intellij annotation @Mapper don't create a bean for mapper.
I didn't change code from John GitHub.
Any idea?
I tried to change path generated source to target but this doesn't help
Thanks for help.

答: I resolved this by first installing MAVEN_HOME in environment variables then do a mvn clean install. I've found out that I was running my project in eclipse and then Intellij without installing maven.

Body:
I downloaded application from this source https://github.com/springframeworkguru/spring5-mvc-rest/tree/vendor-api
And I have a problem with MapStruct.

@Mapper
public interface CategoryMapper {

CategoryMapper INSTANCE = Mappers.getMapper(CategoryMapper.class);

CategoryDTO categoryToCategoryDTO(Category category);

}

@Data
public class CategoryDTO {
    private Long id;
    private String name;
}

domain class:

@Data
@Entity
public class Category {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
}

Service class:

@Service
public class CategoryServiceImpl implements CategoryService {

    private final CategoryMapper categoryMapper;
    private final CategoryRepository categoryRepository;

    public CategoryServiceImpl(CategoryMapper categoryMapper, CategoryRepository categoryRepository) {
        this.categoryMapper = categoryMapper;
        this.categoryRepository = categoryRepository;
    }
}

And in pom.xml dependency, I paste only two::

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <org.mapstruct.version>1.2.0.CR2</org.mapstruct.version>
</properties>
<dependency>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct-jdk8</artifactId>
        <version>${org.mapstruct.version}</version>
</dependency>

And plugin:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.7.0</version>
    <configuration>
        <source>1.8</source>
        <target>1.8</target>
        <annotationProcessorPaths>
            <path>
                 <groupId>org.projectlombok</groupId>
                 <artifactId>lombok</artifactId>
                 <version>${lombok.version}</version>
            </path>
            <path>
                 <groupId>org.mapstruct</groupId>
                 <artifactId>mapstruct-processor</artifactId>
                 <version>${org.mapstruct.version}</version>
           </path>
        </annotationProcessorPaths>
        <compilerArgs>
           <compilerArg>
                 -Amapstruct.defaultComponentModel=spring
           </compilerArg>
        </compilerArgs>
    </configuration>
</plugin>

Description:

Parameter 0 of constructor in
guru.springfamework.services.CategoryServiceImpl required a bean of type 'guru.springfamework.api.v1.mapper.CategoryMapper' that could not be found.

Action:

Consider defining a bean of type 'guru.springfamework.api.v1.mapper.CategoryMapper' in your configuration.

I think that in my Intellij annotation @Mapper don't create a bean for mapper.
I didn't change code from John GitHub.
Any idea?
I tried to change path generated source to target but this doesn't help
Thanks for help.


问:
I changed the value of a token between 2 requests How is it possible?
For a course about Spring boot security I wanted to demonstrate that the token was the best security because it isn't possible to change it. But it seems to be wrong, I managed to change a token between two requests !

First an example :

Token after login :

```<code>{
"id": 4,
"email": "jean.bon@monserveur.fr",
"password": "",
"username": "jean.bon",
"token": "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJqZWFuLmJvbiIsImlhdCI6MTY0MzM4MDE1NSwiZXhwIjoxNjQzNDY2NTU1fQ.JUSTGCfWS9MrbBzkyEboaxHyZcBVwzC_TAH8LRx76wJmKZ9drF1cz51EWfKs9rd4GfxqwpE33-_5e0soylfA6w",
"roles": [
    "USER"
]
</code>```

}

Result of the request employee/employee with this token :

[{"id":1,"name":"KING","job":{"id":1,"jobname":"President"},"managerId":null,"hiredate":"1981-11-17","salary":5000.00,"department":{"id":1,"dname":"Accounting","location":"NEW YORK"}},{"id":2,"name":"JONES","job":{"id":2,"jobname":"Manager"},"managerId":1,"hiredate":"1981-04-02","salary":3000.00,"department":{"id":1,"dname":"Accounting","location":"NEW YORK"}},...

Token modified : the last sign (w) replaced by x :

```<code>"token": "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJqZWFuLmJvbiIsImlhdCI6MTY0MzM4MDE1NSwiZXhwIjoxNjQzNDY2NTU1fQ.JUSTGCfWS9MrbBzkyEboaxHyZcBVwzC_TAH8LRx76wJmKZ9drF1cz51EWfKs9rd4GfxqwpE33-_5e0soylfA6x",
</code>```

Result of the request employee/employee :

[{"id":1,"name":"KING","job":{"id":1,"jobname":"President"},"managerId":null,"hiredate":"1981-11-17","salary":5000.00,"department":{"id":1,"dname":"Accounting","location":"NEW YORK"}},{"id":2,"name":"JONES","job":{"id":2,"jobname":"Manager"},"managerId":1,"hiredate":"1981-04-02","salary":3000.00,"department":{"id":1,"dname":"Accounting","location":"NEW YORK"}},...

If I replace the w by a sign before w, for example by a, it  doesn't work :
401 Unauthorized 11 ms 404 B

The token is generated by Spring boot security
The key
key= AzertyuiopQsdfgjklmWxcvbn1234567890!=
Expiration :
expiration= 86400000

Token generated by :

```<code>public String generateToken(Authentication authentication) {
    UserDetailsImpl userDetailsImpl = (UserDetailsImpl) authentication.getPrincipal();
    JwtBuilder jwtBuilder = Jwts.builder();
    jwtBuilder.setSubject((userDetailsImpl.getUsername()));
    jwtBuilder.setIssuedAt(new Date());
    jwtBuilder.setExpiration(new Date((new Date()).getTime() + expiration));
    jwtBuilder.signWith(SignatureAlgorithm.HS512, key);
    String token = jwtBuilder.compact();
    return token;
}
</code>```

Token validated by :

```<code>public boolean validateToken(String token) {
    Boolean ret = false;
    try {
        JwtParser jwtParser = Jwts.parser();
        jwtParser.setSigningKey(key);
        jwtParser.parseClaimsJws(token);
        ret= true;
    } catch (Exception e) {
        ret = false;
    }
    return ret;
}
</code>```

Username extracted by :

```<code>public String getUserNameFromToken(String token) {
    JwtParser jwtParser = Jwts.parser();
    jwtParser.setSigningKey(key);
    Jws<Claims> jws = jwtParser.parseClaimsJws(token);
    Claims claims = jws.getBody();
    String userName = claims.getSubject();
    return userName;
}
</code>```

答:
My guess is it's related to base64 encoding scheme. For example, if you take the "modified" Base64 encoded string, and then decode and re-encode it, you end up with the expected value.Slightly ugly test code to follow:

String stringKey = "JUSTGCfWS9MrbBzkyEboaxHyZcBVwzC_TAH8LRx76wJmKZ9drF1cz51EWfKs9rd4GfxqwpE33-_5e0soylfA6x";
byte[] bytes = Base64.getUrlDecoder().decode(stringKey);
System.out.println("Original Key: " + stringKey);
String stringKey2 = Base64.getUrlEncoder().encodeToString(bytes);
byte[] bytes2 = Base64.getUrlDecoder().decode(stringKey2);
System.out.println("Re-encoded:   " + stringKey2);

assertThat(bytes, is(bytes2));
```
<p>This test passes and outputs the following (the '=' are just padding):</p>
```Original Key: JUSTGCfWS9MrbBzkyEboaxHyZcBVwzC_TAH8LRx76wJmKZ9drF1cz51EWfKs9rd4GfxqwpE33-_5e0soylfA6x
Re-encoded:   JUSTGCfWS9MrbBzkyEboaxHyZcBVwzC_TAH8LRx76wJmKZ9drF1cz51EWfKs9rd4GfxqwpE33-_5e0soylfA6w==
```
<p>You can get similar results in this test if you change the last letter to <code>h</code>:</p>
```Original Key: JUSTGCfWS9MrbBzkyEboaxHyZcBVwzC_TAH8LRx76wJmKZ9drF1cz51EWfKs9rd4GfxqwpE33-_5e0soylfA6h
Re-encoded:   JUSTGCfWS9MrbBzkyEboaxHyZcBVwzC_TAH8LRx76wJmKZ9drF1cz51EWfKs9rd4GfxqwpE33-_5e0soylfA6g==
```

TL;DR The signature decodes to the same original bytes (so the JWT is still valid)

Body:
For a course about Spring boot security I wanted to demonstrate that the token was the best security because it isn't possible to change it. But it seems to be wrong, I managed to change a token between two requests !

First an example :

Token after login :

{
"id": 4,
"email": "jean.bon@monserveur.fr",
"password": "",
"username": "jean.bon",
"token": "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJqZWFuLmJvbiIsImlhdCI6MTY0MzM4MDE1NSwiZXhwIjoxNjQzNDY2NTU1fQ.JUSTGCfWS9MrbBzkyEboaxHyZcBVwzC_TAH8LRx76wJmKZ9drF1cz51EWfKs9rd4GfxqwpE33-_5e0soylfA6w",
"roles": [
    "USER"
]

}

Result of the request employee/employee with this token :

[{"id":1,"name":"KING","job":{"id":1,"jobname":"President"},"managerId":null,"hiredate":"1981-11-17","salary":5000.00,"department":{"id":1,"dname":"Accounting","location":"NEW YORK"}},{"id":2,"name":"JONES","job":{"id":2,"jobname":"Manager"},"managerId":1,"hiredate":"1981-04-02","salary":3000.00,"department":{"id":1,"dname":"Accounting","location":"NEW YORK"}},...

Token modified : the last sign (w) replaced by x :

"token": "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJqZWFuLmJvbiIsImlhdCI6MTY0MzM4MDE1NSwiZXhwIjoxNjQzNDY2NTU1fQ.JUSTGCfWS9MrbBzkyEboaxHyZcBVwzC_TAH8LRx76wJmKZ9drF1cz51EWfKs9rd4GfxqwpE33-_5e0soylfA6x",

Result of the request employee/employee :

[{"id":1,"name":"KING","job":{"id":1,"jobname":"President"},"managerId":null,"hiredate":"1981-11-17","salary":5000.00,"department":{"id":1,"dname":"Accounting","location":"NEW YORK"}},{"id":2,"name":"JONES","job":{"id":2,"jobname":"Manager"},"managerId":1,"hiredate":"1981-04-02","salary":3000.00,"department":{"id":1,"dname":"Accounting","location":"NEW YORK"}},...

If I replace the w by a sign before w, for example by a, it  doesn't work :
401 Unauthorized 11 ms 404 B

The token is generated by Spring boot security
The key
key= AzertyuiopQsdfgjklmWxcvbn1234567890!=
Expiration :
expiration= 86400000

Token generated by :

public String generateToken(Authentication authentication) {
    UserDetailsImpl userDetailsImpl = (UserDetailsImpl) authentication.getPrincipal();
    JwtBuilder jwtBuilder = Jwts.builder();
    jwtBuilder.setSubject((userDetailsImpl.getUsername()));
    jwtBuilder.setIssuedAt(new Date());
    jwtBuilder.setExpiration(new Date((new Date()).getTime() + expiration));
    jwtBuilder.signWith(SignatureAlgorithm.HS512, key);
    String token = jwtBuilder.compact();
    return token;
}

Token validated by :

public boolean validateToken(String token) {
    Boolean ret = false;
    try {
        JwtParser jwtParser = Jwts.parser();
        jwtParser.setSigningKey(key);
        jwtParser.parseClaimsJws(token);
        ret= true;
    } catch (Exception e) {
        ret = false;
    }
    return ret;
}

Username extracted by :

public String getUserNameFromToken(String token) {
    JwtParser jwtParser = Jwts.parser();
    jwtParser.setSigningKey(key);
    Jws<Claims> jws = jwtParser.parseClaimsJws(token);
    Claims claims = jws.getBody();
    String userName = claims.getSubject();
    return userName;
}

Body:
My guess is it's related to base64 encoding scheme. For example, if you take the "modified" Base64 encoded string, and then decode and re-encode it, you end up with the expected value.Slightly ugly test code to follow:

String stringKey = "JUSTGCfWS9MrbBzkyEboaxHyZcBVwzC_TAH8LRx76wJmKZ9drF1cz51EWfKs9rd4GfxqwpE33-_5e0soylfA6x";
byte[] bytes = Base64.getUrlDecoder().decode(stringKey);
System.out.println("Original Key: " + stringKey);
String stringKey2 = Base64.getUrlEncoder().encodeToString(bytes);
byte[] bytes2 = Base64.getUrlDecoder().decode(stringKey2);
System.out.println("Re-encoded:   " + stringKey2);

assertThat(bytes, is(bytes2));

This test passes and outputs the following (the '=' are just padding):

Original Key: JUSTGCfWS9MrbBzkyEboaxHyZcBVwzC_TAH8LRx76wJmKZ9drF1cz51EWfKs9rd4GfxqwpE33-_5e0soylfA6x
Re-encoded:   JUSTGCfWS9MrbBzkyEboaxHyZcBVwzC_TAH8LRx76wJmKZ9drF1cz51EWfKs9rd4GfxqwpE33-_5e0soylfA6w==

You can get similar results in this test if you change the last letter to h:

Original Key: JUSTGCfWS9MrbBzkyEboaxHyZcBVwzC_TAH8LRx76wJmKZ9drF1cz51EWfKs9rd4GfxqwpE33-_5e0soylfA6h
Re-encoded:   JUSTGCfWS9MrbBzkyEboaxHyZcBVwzC_TAH8LRx76wJmKZ9drF1cz51EWfKs9rd4GfxqwpE33-_5e0soylfA6g==

TL;DR The signature decodes to the same original bytes (so the JWT is still valid)


问:
c++, pointers, references, passing from one to another function, std::vector, std::string
i have a specific problem with pointers and references, with std::vector and std::string. Some question are in the following code snipped, some below.

I have basically this code

```<code>//first of all: is this function declaration good?
//or shoudl I already pass the std::vector in another way?
//I'm only reading from it
void func(const std::vector<std::string>& vec)
{
    //I need to call otherFunc(void*) with  a single element from vec:
    //otherFunc(void* arg);
    //with arg being a void* to vec[0]
}
</code>```

My IDE tells me that only &*vec[0] works as parameter for otherFunc, but this doesn't compile...

How is the best way to do these kind of parameter passing?

答:
First of all, since you only read from the vector, passing it as a const reference is a good idea and should work well.

To your second question: it is difficult to say what otherFunc will do to your object, since it expects a void pointer. This is C style and should not be used in C++, there are better and type safe ways to do so.

Body:
i have a specific problem with pointers and references, with std::vector and std::string. Some question are in the following code snipped, some below.

I have basically this code

//first of all: is this function declaration good?
//or shoudl I already pass the std::vector in another way?
//I'm only reading from it
void func(const std::vector<std::string>& vec)
{
    //I need to call otherFunc(void*) with  a single element from vec:
    //otherFunc(void* arg);
    //with arg being a void* to vec[0]
}

My IDE tells me that only &*vec[0] works as parameter for otherFunc, but this doesn't compile...

How is the best way to do these kind of parameter passing?


问:
Input Email and Checkbox validation to Enable Submit button using javascript
I have the following javascript code for a form in which I validate email with certain patterns and a checkbox with I agree with T&C label. If any of them failed then I disable the submit button. It is all working but I am using too many functions which are causing some conflicts in which if one condition gets true then submit button is available to click.

I am not able to verify both conditions at the same time because both are of different types. There are some answers on Stack overflow but they are of the same type of fields like 2 inputs, 3 checkboxes but not different fields.

Here's the code:

```<code>    window.onload = function ninjaInit() {
  validatEmail();
    validatCheckbox();
  jQuery('#nf-field-20').keyup(validatEmail);
    jQuery('#nf-field-13').change(validatCheckbox);
  }

function validatEmail() {
  var email = document.getElementById('nf-field-20');
    //console.log(email.value);
  if (
    /^[a-zA-Z0-9._%+-]+@(?!gmail.com)(?!yahoo.com)(?!hotmail.com)(?!yahoo.co.in)(?!aol.com)(?!live.com)(?!outlook.com)[a-zA-Z0-9_-]+.[a-zA-Z0-9-.]{2,61}$/.test(email.value)) {
    itWorksem();
  } else {
    notWorkingem();
  }
}
function validatCheckbox() {
    if(!jQuery('#nf-field-13').hasClass("nf-checked")){
             console.log('checkbox not checked');
        checkBoGood();
             }else{
             console.log('checkbox checked');
              checkBoBad();
             }
}

function itWorksem() {
  var errMessage = document.getElementById("nf-error-20");
  //jQuery("#nf-field-20-wrap").removeClass("nf-error");
  jQuery("#nf-field-15").removeClass("btn-disable");
  jQuery("#nf-field-20").removeClass("input-error");
  errMessage.textContent = "";
}
function notWorkingem() {
  var errMessage = document.getElementById("nf-error-20");
  //jQuery("#nf-field-20-wrap").addClass("nf-error");
  jQuery("#nf-field-15").addClass("btn-disable");
  jQuery("#nf-field-20").addClass("input-error");
  errMessage.textContent = "You need to provide a business address.";
}
function checkBoGood(){
    var errMsgPp = document.getElementById("nf-error-13");
    jQuery("#nf-field-15").removeClass("btn-disable");
//  errMsgPp.textContent = "";
}
function checkBoBad(){
    var errMsgPp = document.getElementById("nf-error-13");
    jQuery("#nf-field-15").addClass("btn-disable");
}
</code>```

Some things need to be considered here:

I am not able to check checkbox status with standard functions because that checkbox also uses a class to check if it is checked or not by adding "nf-checked" class that is why I have to check if that element has the class name "nf-checked" or not. FYI this ninja form.

I can't use Document.ready and $ because that is not working in WordPress.

All this code I have done myself so please correct me if I am doing some silly mistake. I am very much a beginner in Javascript.

If Html helps then I am adding that too below. I am not adding the whole code because I can target element using IDs.

```<code><!--Email container Start-->
<div id="nf-field-20-container" class="nf-field-container textbox-container  label-hidden ">
    <div class="nf-before-field">
    </div>
    <div class="nf-field">
        <div id="nf-field-20-wrap" class="field-wrap textbox-wrap" data-field-id="20">
            <div class="nf-field-label"><label for="nf-field-20" id="nf-label-field-20" class="">Work email address  </label>
            </div>
            <div class="nf-field-element">
                <input type="text" value="" class="ninja-forms-field nf-element input-error" placeholder="Work email address" id="nf-field-20" name="nf-field-20" aria-invalid="false" aria-describedby="nf-error-20" aria-labelledby="nf-label-field-20">
                </div>
        </div>
    </div>
    <div class="nf-after-field">
        <nf-section>
            <div class="nf-input-limit">
            </div>
            <div id="nf-error-20" class="nf-error-wrap nf-error" role="alert">You need to provide a business address.</div>
        </nf-section>
    </div>
</div>
<!--Email container Ends-->

<!--Checkbox Start-->
<div id="nf-field-13-container" class="nf-field-container checkbox-container  label-right one-half first ">
    <div class="nf-before-field">
    </div>
    <div class="nf-field"><div id="nf-field-13-wrap" class="field-wrap checkbox-wrap" data-field-id="13">
        <div class="nf-field-label"><label for="nf-field-13" id="nf-label-field-13" class=" nf-checked-label">I accept hubsell’s <a href="#">privacy policy</a>.  </label>
        </div>
    <div class="nf-field-element">
        <input id="nf-field-13" name="nf-field-13" aria-describedby="nf-error-13" class="ninja-forms-field nf-checked nf-element" type="checkbox" value="1" checked="" aria-labelledby="nf-label-field-13">
        </div>
    </div>
</div>
<div class="nf-after-field"><nf-section>
    <div class="nf-input-limit"></div>
    <div id="nf-error-13" class="nf-error-wrap nf-error" role="alert"></div>
    </nf-section>
    </div>
</div>
<!--Checkbox Ends-->

<!--Submit Start-->
<input id="nf-field-15" class="ninja-forms-field nf-element" type="button" value="Submit">
<!--Submit Ends-->
</code>```

window.onload = function ninjaInit() {
  validatEmail();
  validatCheckbox();
  jQuery('#nf-field-20').keyup(validatEmail);
  jQuery('#nf-field-13').change(validatCheckbox);
}

function validatEmail() {
  var email = document.getElementById('nf-field-20');
  //console.log(email.value);
  if (
    /^[a-zA-Z0-9._%+-]+@(?!gmail.com)(?!yahoo.com)(?!hotmail.com)(?!yahoo.co.in)(?!aol.com)(?!live.com)(?!outlook.com)[a-zA-Z0-9_-]+.[a-zA-Z0-9-.]{2,61}$/.test(email.value)) {
    itWorksem();
  } else {
    notWorkingem();
  }
}

function validatCheckbox() {
  if (!jQuery('#nf-field-13').hasClass("nf-checked")) {
    console.log('checkbox not checked');
    checkBoGood();
  } else {
    console.log('checkbox checked');
    checkBoBad();
  }
}

function itWorksem() {
  var errMessage = document.getElementById("nf-error-20");
  //jQuery("#nf-field-20-wrap").removeClass("nf-error");
  jQuery("#nf-field-15").removeClass("btn-disable");
  jQuery("#nf-field-20").removeClass("input-error");
  errMessage.textContent = "";
}

function notWorkingem() {
  var errMessage = document.getElementById("nf-error-20");
  //jQuery("#nf-field-20-wrap").addClass("nf-error");
  jQuery("#nf-field-15").addClass("btn-disable");
  jQuery("#nf-field-20").addClass("input-error");
  errMessage.textContent = "You need to provide a business address.";
}

function checkBoGood() {
  var errMsgPp = document.getElementById("nf-error-13");
  jQuery("#nf-field-15").removeClass("btn-disable");
  //  errMsgPp.textContent = "";
}

function checkBoBad() {
  var errMsgPp = document.getElementById("nf-error-13");
  jQuery("#nf-field-15").addClass("btn-disable");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--Email container Start-->
<div id="nf-field-20-container" class="nf-field-container textbox-container  label-hidden ">
  <div class="nf-before-field">
  </div>
  <div class="nf-field">
    <div id="nf-field-20-wrap" class="field-wrap textbox-wrap" data-field-id="20">
      <div class="nf-field-label"><label for="nf-field-20" id="nf-label-field-20" class="">Work email address  </label>
      </div>
      <div class="nf-field-element">
        <input type="text" value="" class="ninja-forms-field nf-element input-error" placeholder="Work email address" id="nf-field-20" name="nf-field-20" aria-invalid="false" aria-describedby="nf-error-20" aria-labelledby="nf-label-field-20">
      </div>
    </div>
  </div>
  <div class="nf-after-field">
    <nf-section>
      <div class="nf-input-limit">
      </div>
      <div id="nf-error-20" class="nf-error-wrap nf-error" role="alert">You need to provide a business address.</div>
    </nf-section>
  </div>
</div>
<!--Email container Ends-->

<!--Checkbox Start-->
<div id="nf-field-13-container" class="nf-field-container checkbox-container  label-right one-half first ">
  <div class="nf-before-field">
  </div>
  <div class="nf-field">
    <div id="nf-field-13-wrap" class="field-wrap checkbox-wrap" data-field-id="13">
      <div class="nf-field-label"><label for="nf-field-13" id="nf-label-field-13" class=" nf-checked-label">I accept hubsell’s privacy policy.  </label>
      </div>
      <div class="nf-field-element">
        <input id="nf-field-13" name="nf-field-13" aria-describedby="nf-error-13" class="ninja-forms-field nf-checked nf-element" type="checkbox" value="1" checked="" aria-labelledby="nf-label-field-13">
      </div>
    </div>
  </div>
  <div class="nf-after-field">
    <nf-section>
      <div class="nf-input-limit"></div>
      <div id="nf-error-13" class="nf-error-wrap nf-error" role="alert"></div>
    </nf-section>
  </div>
</div>
<!--Checkbox Ends-->

<!--Submit Start-->
<input id="nf-field-15" class="ninja-forms-field nf-element" type="button" value="Submit">
<!--Submit Ends--></code>```

You can see the input[type="checkbox"] has that nf-checked class already I mark the default value as checked in ninja forms.

Update: I have added the proper HTML code after ruleboy21 comment.

答:
Smaller now

function validateEmail() {
  let email = document.getElementById('nf-field-20');
  let isWorking =
    /^[a-zA-Z0-9._%+-]+@(?!gmail.com)(?!yahoo.com)(?!hotmail.com)(?!yahoo.co.in)(?!aol.com)(?!live.com)(?!outlook.com)[a-zA-Z0-9_-]+.[a-zA-Z0-9-.]{2,61}$/.test(email.value);
    console.log(isWorking);
  indicateStatus(isWorking);
}

function validateCheckbox() {
  jQuery("#nf-field-15").toggleClass("btn-disable", !jQuery('#nf-field-13').hasClass("nf-checked"));
}

function indicateStatus(isWorking) {
  var errMessage = document.getElementById("nf-error-20");
  jQuery("#nf-field-15").toggleClass("btn-disable", !isWorking);
  jQuery("#nf-field-20").toggleClass("input-error", !isWorking);
  errMessage.textContent = "";
}
window.onload = function ninjaInit() {
  validateEmail();
  validateCheckbox();
  jQuery('#nf-field-20').on('keyup', validateEmail);
  jQuery('#nf-field-13').on('change', validateCheckbox);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.input-error {
  border: solid red 1px;
}

.btn-disable {
  background-color: #ddffff;
}</code>```

Work email address

        <input type="text" value="" class="ninja-forms-field nf-element input-error" placeholder="Work email address" id="nf-field-20" name="nf-field-20" aria-invalid="false" aria-describedby="nf-error-20" aria-labelledby="nf-label-field-20">

    <nf-section>

You need to provide a business address.

    </nf-section>

I accept hubsell’s privacy policy.

        <input id="nf-field-13" name="nf-field-13" aria-describedby="nf-error-13" class="ninja-forms-field nf-checked nf-element" type="checkbox" value="1" checked="" aria-labelledby="nf-label-field-13">

    <nf-section>

    </nf-section>

<input id="nf-field-15" class="ninja-forms-field nf-element" type="button" value="Submit">
```

Body:
I have the following javascript code for a form in which I validate email with certain patterns and a checkbox with I agree with T&C label. If any of them failed then I disable the submit button. It is all working but I am using too many functions which are causing some conflicts in which if one condition gets true then submit button is available to click.

I am not able to verify both conditions at the same time because both are of different types. There are some answers on Stack overflow but they are of the same type of fields like 2 inputs, 3 checkboxes but not different fields.

Here's the code:

    window.onload = function ninjaInit() {
  validatEmail();
    validatCheckbox();
  jQuery('#nf-field-20').keyup(validatEmail);
    jQuery('#nf-field-13').change(validatCheckbox);
  }

function validatEmail() {
  var email = document.getElementById('nf-field-20');
    //console.log(email.value);
  if (
    /^[a-zA-Z0-9._%+-]+@(?!gmail.com)(?!yahoo.com)(?!hotmail.com)(?!yahoo.co.in)(?!aol.com)(?!live.com)(?!outlook.com)[a-zA-Z0-9_-]+.[a-zA-Z0-9-.]{2,61}$/.test(email.value)) {
    itWorksem();
  } else {
    notWorkingem();
  }
}
function validatCheckbox() {
    if(!jQuery('#nf-field-13').hasClass("nf-checked")){
             console.log('checkbox not checked');
        checkBoGood();
             }else{
             console.log('checkbox checked');
              checkBoBad();
             }
}

function itWorksem() {
  var errMessage = document.getElementById("nf-error-20");
  //jQuery("#nf-field-20-wrap").removeClass("nf-error");
  jQuery("#nf-field-15").removeClass("btn-disable");
  jQuery("#nf-field-20").removeClass("input-error");
  errMessage.textContent = "";
}
function notWorkingem() {
  var errMessage = document.getElementById("nf-error-20");
  //jQuery("#nf-field-20-wrap").addClass("nf-error");
  jQuery("#nf-field-15").addClass("btn-disable");
  jQuery("#nf-field-20").addClass("input-error");
  errMessage.textContent = "You need to provide a business address.";
}
function checkBoGood(){
    var errMsgPp = document.getElementById("nf-error-13");
    jQuery("#nf-field-15").removeClass("btn-disable");
//  errMsgPp.textContent = "";
}
function checkBoBad(){
    var errMsgPp = document.getElementById("nf-error-13");
    jQuery("#nf-field-15").addClass("btn-disable");
}

Some things need to be considered here:

I am not able to check checkbox status with standard functions because that checkbox also uses a class to check if it is checked or not by adding "nf-checked" class that is why I have to check if that element has the class name "nf-checked" or not. FYI this ninja form.

I can't use Document.ready and $ because that is not working in WordPress.

All this code I have done myself so please correct me if I am doing some silly mistake. I am very much a beginner in Javascript.

If Html helps then I am adding that too below. I am not adding the whole code because I can target element using IDs.

Work email address

                <input type="text" value="" class="ninja-forms-field nf-element input-error" placeholder="Work email address" id="nf-field-20" name="nf-field-20" aria-invalid="false" aria-describedby="nf-error-20" aria-labelledby="nf-label-field-20">

        <nf-section>

You need to provide a business address.

        </nf-section>

I accept hubsell’s privacy policy.

        <input id="nf-field-13" name="nf-field-13" aria-describedby="nf-error-13" class="ninja-forms-field nf-checked nf-element" type="checkbox" value="1" checked="" aria-labelledby="nf-label-field-13">

<nf-section>

    </nf-section>

<input id="nf-field-15" class="ninja-forms-field nf-element" type="button" value="Submit">

window.onload = function ninjaInit() {
  validatEmail();
  validatCheckbox();
  jQuery('#nf-field-20').keyup(validatEmail);
  jQuery('#nf-field-13').change(validatCheckbox);
}

function validatEmail() {
  var email = document.getElementById('nf-field-20');
  //console.log(email.value);
  if (
    /^[a-zA-Z0-9._%+-]+@(?!gmail.com)(?!yahoo.com)(?!hotmail.com)(?!yahoo.co.in)(?!aol.com)(?!live.com)(?!outlook.com)[a-zA-Z0-9_-]+.[a-zA-Z0-9-.]{2,61}$/.test(email.value)) {
    itWorksem();
  } else {
    notWorkingem();
  }
}

function validatCheckbox() {
  if (!jQuery('#nf-field-13').hasClass("nf-checked")) {
    console.log('checkbox not checked');
    checkBoGood();
  } else {
    console.log('checkbox checked');
    checkBoBad();
  }
}

function itWorksem() {
  var errMessage = document.getElementById("nf-error-20");
  //jQuery("#nf-field-20-wrap").removeClass("nf-error");
  jQuery("#nf-field-15").removeClass("btn-disable");
  jQuery("#nf-field-20").removeClass("input-error");
  errMessage.textContent = "";
}

function notWorkingem() {
  var errMessage = document.getElementById("nf-error-20");
  //jQuery("#nf-field-20-wrap").addClass("nf-error");
  jQuery("#nf-field-15").addClass("btn-disable");
  jQuery("#nf-field-20").addClass("input-error");
  errMessage.textContent = "You need to provide a business address.";
}

function checkBoGood() {
  var errMsgPp = document.getElementById("nf-error-13");
  jQuery("#nf-field-15").removeClass("btn-disable");
  //  errMsgPp.textContent = "";
}

function checkBoBad() {
  var errMsgPp = document.getElementById("nf-error-13");
  jQuery("#nf-field-15").addClass("btn-disable");
}

Work email address

        <input type="text" value="" class="ninja-forms-field nf-element input-error" placeholder="Work email address" id="nf-field-20" name="nf-field-20" aria-invalid="false" aria-describedby="nf-error-20" aria-labelledby="nf-label-field-20">

    <nf-section>

You need to provide a business address.

    </nf-section>

I accept hubsell’s privacy policy.

        <input id="nf-field-13" name="nf-field-13" aria-describedby="nf-error-13" class="ninja-forms-field nf-checked nf-element" type="checkbox" value="1" checked="" aria-labelledby="nf-label-field-13">

    <nf-section>

    </nf-section>

<input id="nf-field-15" class="ninja-forms-field nf-element" type="button" value="Submit">

You can see the input[type="checkbox"] has that nf-checked class already I mark the default value as checked in ninja forms.

Update: I have added the proper HTML code after ruleboy21 comment.

Body:
Smaller now

function validateEmail() {
  let email = document.getElementById('nf-field-20');
  let isWorking =
    /^[a-zA-Z0-9._%+-]+@(?!gmail.com)(?!yahoo.com)(?!hotmail.com)(?!yahoo.co.in)(?!aol.com)(?!live.com)(?!outlook.com)[a-zA-Z0-9_-]+.[a-zA-Z0-9-.]{2,61}$/.test(email.value);
    console.log(isWorking);
  indicateStatus(isWorking);
}

function validateCheckbox() {
  jQuery("#nf-field-15").toggleClass("btn-disable", !jQuery('#nf-field-13').hasClass("nf-checked"));
}

function indicateStatus(isWorking) {
  var errMessage = document.getElementById("nf-error-20");
  jQuery("#nf-field-15").toggleClass("btn-disable", !isWorking);
  jQuery("#nf-field-20").toggleClass("input-error", !isWorking);
  errMessage.textContent = "";
}
window.onload = function ninjaInit() {
  validateEmail();
  validateCheckbox();
  jQuery('#nf-field-20').on('keyup', validateEmail);
  jQuery('#nf-field-13').on('change', validateCheckbox);
}

.input-error {
  border: solid red 1px;
}

.btn-disable {
  background-color: #ddffff;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--Email container Start-->
<div id="nf-field-20-container" class="nf-field-container textbox-container  label-hidden ">
  <div class="nf-before-field">
  </div>
  <div class="nf-field">
    <div id="nf-field-20-wrap" class="field-wrap textbox-wrap" data-field-id="20">
      <div class="nf-field-label"><label for="nf-field-20" id="nf-label-field-20" class="">Work email address  </label>
      </div>
      <div class="nf-field-element">
        <input type="text" value="" class="ninja-forms-field nf-element input-error" placeholder="Work email address" id="nf-field-20" name="nf-field-20" aria-invalid="false" aria-describedby="nf-error-20" aria-labelledby="nf-label-field-20">
      </div>
    </div>
  </div>
  <div class="nf-after-field">
    <nf-section>
      <div class="nf-input-limit">
      </div>
      <div id="nf-error-20" class="nf-error-wrap nf-error" role="alert">You need to provide a business address.</div>
    </nf-section>
  </div>
</div>
<!--Email container Ends-->

<!--Checkbox Start-->
<div id="nf-field-13-container" class="nf-field-container checkbox-container  label-right one-half first ">
  <div class="nf-before-field">
  </div>
  <div class="nf-field">
    <div id="nf-field-13-wrap" class="field-wrap checkbox-wrap" data-field-id="13">
      <div class="nf-field-label"><label for="nf-field-13" id="nf-label-field-13" class=" nf-checked-label">I accept hubsell’s <a href="#">privacy policy</a>.  </label>
      </div>
      <div class="nf-field-element">
        <input id="nf-field-13" name="nf-field-13" aria-describedby="nf-error-13" class="ninja-forms-field nf-checked nf-element" type="checkbox" value="1" checked="" aria-labelledby="nf-label-field-13">
      </div>
    </div>
  </div>
  <div class="nf-after-field">
    <nf-section>
      <div class="nf-input-limit"></div>
      <div id="nf-error-13" class="nf-error-wrap nf-error" role="alert"></div>
    </nf-section>
  </div>
</div>
<!--Checkbox Ends-->

<!--Submit Start-->
<input id="nf-field-15" class="ninja-forms-field nf-element" type="button" value="Submit">
<!--Submit Ends-->


问:
Why is my Typescript "paths" setting getting removed when I run my React app?
I'm trying to use shorter import paths in my project by using a "paths" setting in my tsconfig.json file. When I set it up, my files look fine and do not complain. However, when I run the project, the "paths" gets deleted from my tsconfig.json file and my React server crashes.

Here's my tsconfig.json file:

{
  "compilerOptions": {
    "target": "es6",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react",
    "baseUrl": ".",
    "paths": {
      "@/*": [
        "src/*"
      ]
    }
  },
  "include": [
    "src"
  ]
}
```
<p>Now, when I run my server, I get the following error:</p>
```Module not found: Can't resolve '@/components/index' in '.../app/client/src/utils'
.../clients/app/client/node_modules/react-scripts/scripts/start.js:19
  throw err;
  ^

[Error: ENOENT: no such file or directory, stat '.../app/client/node_modules/babel-preset-react-app/node_modules/@babel/core/node_modules/.bin/json5'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'stat',
  path: '.../app/client/node_modules/babel-preset-react-app/node_modules/@babel/core/node_modules/.bin/json5'
}
```
<p>...and then my <code>tsconfig.ts</code> looks like this:</p>
```...
   "noEmit": true,
    "jsx": "react",
    "baseUrl": "."
  },
...
```

Am I doing something wrong? I'm attempting to do this.

答:
Well, it seems that I cannot use this configuration setting until I upgrade to React 17. There's a lot of breaking changes if I do that so I guess I'll have to wait to use this feature until I'm ready.

I was able to use this and the solution works, except VSCode complains about import errors as if the code isn't located where my code says it is.

Body:
I'm trying to use shorter import paths in my project by using a "paths" setting in my tsconfig.json file. When I set it up, my files look fine and do not complain. However, when I run the project, the "paths" gets deleted from my tsconfig.json file and my React server crashes.

Here's my tsconfig.json file:

{
  "compilerOptions": {
    "target": "es6",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react",
    "baseUrl": ".",
    "paths": {
      "@/*": [
        "src/*"
      ]
    }
  },
  "include": [
    "src"
  ]
}

Now, when I run my server, I get the following error:

Module not found: Can't resolve '@/components/index' in '.../app/client/src/utils'
.../clients/app/client/node_modules/react-scripts/scripts/start.js:19
  throw err;
  ^

[Error: ENOENT: no such file or directory, stat '.../app/client/node_modules/babel-preset-react-app/node_modules/@babel/core/node_modules/.bin/json5'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'stat',
  path: '.../app/client/node_modules/babel-preset-react-app/node_modules/@babel/core/node_modules/.bin/json5'
}

...and then my tsconfig.ts looks like this:

...
   "noEmit": true,
    "jsx": "react",
    "baseUrl": "."
  },
...

Am I doing something wrong? I'm attempting to do this.


问:
Write to another already running process stdin from Node.js without starting from inside
I have a program that isn't started from inside Node.js, so I cannot use spawn'd stdin to write to. I have the PID of the process that is listening for stdin input, how can I write to it using my node code?

I always see code examples using child_process module, and my use case is different.

答: If you have the process id then one can use ptrace or one of its variants: strace or ltrace to control, manipulate, and view process information and communication.</p>


问:
How to click on element which contains a credit card number that changes each time with Selenium Python
I have a problem to find element on credit card payment form, which contains a number that changes each time, so please help me to find the way to do it.

This is the element:

```<code><input id="adyen-checkout-encryptedCardNumber-1644589302666" data-fieldtype="encryptedCardNumber" type="text" inputmode="numeric" maxlength="24" autocomplete="cc-number" placeholder="1234 5678 9012 3456" aria-label="Champ du numéro de carte" aria-invalid="true" aria-required="true" aria-describedby="adyen-checkout-encryptedCardNumber-1644589302666-ariaError" class="js-iframe-input input-field" data-type="gsf" style="display: block;">
</code>```

答:
Thank you @undetected Selenium for you response it was a frame problem so this is what i do and its works fine for me  :</p>
```<code>WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//*[@id='adyen-card-container']/div/div/div[2]/div[1]/div[1]/label/div/span/iframe")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH,"//input[@data-fieldtype='encryptedCardNumber']"))).send_keys("0000111122223333")
##switch parent frame
self.driver.switch_to.default_content()
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it(
        (By.XPATH, "//*[@id='adyen-card-container']/div/div/div[2]/div[1]/div[2]/div[1]/label/div/span/iframe")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH,"//input[@data-fieldtype='encryptedExpiryDate']"))).send_keys("0228")
##switch parent frame
self.driver.switch_to.default_content()
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it(
        (By.XPATH,  "//*[@id='adyen-card-container']/div/div/div[2]/div[1]/div[2]/div[2]/label/div/span/iframe")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@data-fieldtype='encryptedSecurityCode']"))).send_keys("123")

</code>```

Body:
I have a problem to find element on credit card payment form, which contains a number that changes each time, so please help me to find the way to do it.

This is the element:

<input id="adyen-checkout-encryptedCardNumber-1644589302666" data-fieldtype="encryptedCardNumber" type="text" inputmode="numeric" maxlength="24" autocomplete="cc-number" placeholder="1234 5678 9012 3456" aria-label="Champ du numéro de carte" aria-invalid="true" aria-required="true" aria-describedby="adyen-checkout-encryptedCardNumber-1644589302666-ariaError" class="js-iframe-input input-field" data-type="gsf" style="display: block;">

Body:
Thank you @undetected Selenium for you response it was a frame problem so this is what i do and its works fine for me  :

WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//*[@id='adyen-card-container']/div/div/div[2]/div[1]/div[1]/label/div/span/iframe")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH,"//input[@data-fieldtype='encryptedCardNumber']"))).send_keys("0000111122223333")
##switch parent frame
self.driver.switch_to.default_content()
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it(
        (By.XPATH, "//*[@id='adyen-card-container']/div/div/div[2]/div[1]/div[2]/div[1]/label/div/span/iframe")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH,"//input[@data-fieldtype='encryptedExpiryDate']"))).send_keys("0228")
##switch parent frame
self.driver.switch_to.default_content()
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it(
        (By.XPATH,  "//*[@id='adyen-card-container']/div/div/div[2]/div[1]/div[2]/div[2]/label/div/span/iframe")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@data-fieldtype='encryptedSecurityCode']"))).send_keys("123")


问:
.Net Core 6 ModelState.IsValid Flagged As Not Valid When It Is
When trying to create a new record for USER, ModelState.IsValid is flagged as invalid. However, all the correct data is there.

The issue seems to be in Reference Key.

My Classes

```<code>   public class Users
   {
    [Key]
    public int IdUser { get; set; }
    public int IdLOB { get; set; }
    public string Email { get; set; } = default!;
    public string FullName { get; set; } = default!;
    public string? Nickname { get; set; }
    public DateTime ModifiedOn { get; set; }

    [ForeignKey("IdLOB")]
    public virtual LOBS IdLOBNavigation { get; set; } = default!;
   }

public class LOBS
{
    [Key]
    public int IdLOB { get; set; }
    public string LOB { get; set; } = default!;
    public int? ParentLOB { get; set; }

    [Display(Name = "Parent LOB")]
    [ForeignKey("ParentLOB")]
    public virtual LOBS? ParentLOBNavigation { get; set; }
}
</code>```

All data is passed to Users, including IdLOB, but it flagged as invalid because of IdLOBNavigation:

If I jump model validation, the data is processed without error and the record is created. Also, the tables in the database are correct, IdLOBNavigation is a relation and not a field.

So I believe the error is in how I'm declaring the relation in the Users Class. What is the correct way to do this in .Net 6

答:
I'm making an assumption that you are passing the domain model to an API endpoint and then adding that model to your context and trying to save.

If that is the case, then I think you need to create a request model to take in only the data you need, rather than the actual domain model. You then validate the request model with the limited dataset that you want the end user to be able pass in to be saved. I.e. IdLOB, email, fullname, nickname.

That way you limit the end user from being able to set properties they shouldn't (i.e. ModifiedOn), can validate your request model explicitly (as we never trust the client) and create a new instance of User (via constructor or mapper like AutoMapper) which is safe to be added to your context.

Body:
When trying to create a new record for USER, ModelState.IsValid is flagged as invalid. However, all the correct data is there.

The issue seems to be in Reference Key.

My Classes

   public class Users
   {
    [Key]
    public int IdUser { get; set; }
    public int IdLOB { get; set; }
    public string Email { get; set; } = default!;
    public string FullName { get; set; } = default!;
    public string? Nickname { get; set; }
    public DateTime ModifiedOn { get; set; }

    [ForeignKey("IdLOB")]
    public virtual LOBS IdLOBNavigation { get; set; } = default!;
   }

public class LOBS
{
    [Key]
    public int IdLOB { get; set; }
    public string LOB { get; set; } = default!;
    public int? ParentLOB { get; set; }

    [Display(Name = "Parent LOB")]
    [ForeignKey("ParentLOB")]
    public virtual LOBS? ParentLOBNavigation { get; set; }
}

All data is passed to Users, including IdLOB, but it flagged as invalid because of IdLOBNavigation:

If I jump model validation, the data is processed without error and the record is created. Also, the tables in the database are correct, IdLOBNavigation is a relation and not a field.

So I believe the error is in how I'm declaring the relation in the Users Class. What is the correct way to do this in .Net 6