问:
Consultation through relationships in laravel
I searched endlessly for a question that answered my question here and I didn't find it. My question is as follows, I have 3 models: User, Post and Comments. Where user has a relationship with one to many posting, and Post has a relationship with one to many comments as well. How can I get all of the user's comments on all posts?
Currently my solution looks like this:

Models Users:

```<code>    public function comments(){
        $comments = array();

        foreach ($this->posts()->get() as $el) {
            foreach ($el->posts()->get() as $nEl) {
                array_push($comments, $nEl);
            }
        }
        return collect($comments);
    }
</code>```

I would like a less expensive and native solution for laravel, if any.

答:
On your User model, something like:

```<code>public function getComments()
{
    return Comment::whereHas('posts', function ($query) {
        $query->where('user_id', $this->id);
    })->get();
}
</code>```

Also see:
https://laravel.com/docs/6.x/eloquent-relationships#has-many-through

Body:
I searched endlessly for a question that answered my question here and I didn't find it. My question is as follows, I have 3 models: User, Post and Comments. Where user has a relationship with one to many posting, and Post has a relationship with one to many comments as well. How can I get all of the user's comments on all posts?
Currently my solution looks like this:

Models Users:

    public function comments(){
        $comments = array();

        foreach ($this->posts()->get() as $el) {
            foreach ($el->posts()->get() as $nEl) {
                array_push($comments, $nEl);
            }
        }
        return collect($comments);
    }

I would like a less expensive and native solution for laravel, if any.

Body:
On your User model, something like:

public function getComments()
{
    return Comment::whereHas('posts', function ($query) {
        $query->where('user_id', $this->id);
    })->get();
}

Also see:
https://laravel.com/docs/6.x/eloquent-relationships#has-many-through


来源: stackexchange

问:
Register and Login form in Laravel not working
I have created a project in Laravel but i cant login and register.When i try to register it stays at the same page and all the fields stay the same the password field stays empty.While in Login page it says that "These credentials do not match our records.".I have tried to drop the database,create new and run php artisan migrate or migrate:fresh and refresh but still not working.When i try to enter a user or admin from phpmyadmin it says this error".I dont know if the error comes maybe because department table and user table are joined,foreign key and primary key,with department_id...

1062 - Duplicate entry 'admin@ana.com' for key 'users_email_unique'

Department.php

```<code>
       public function users()
        {
            return $this->hasMany(User::class);
        }

</code>```

User.php

```<code>
public function users()
{
    return $this->belongsTo(Department::class);
}

</code>```
```<code>   public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');//create_users_table
            //$table->text('avatar');
            $table->string('name');
            $table->string('lastname');
            $table->string('phone');
            $table->string('jobtitle');
            $table->integer('department_id');
            $table->timestamps();
            $table->string('usertype')->nullable();
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();

        });
    }
</code>```
```<code>
    public function up()
        {
            Schema::create('departments', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('name');
                $table->timestamps();
            });
        }

</code>```

RegisterController.php

```<code>

    class RegisterController extends Controller
    {

        use RegistersUsers;
        protected $redirectTo = RouteServiceProvider::HOME;
        public function __construct()
        {
            $this->middleware('guest');
        }

        protected function validator(array $data)
        {
            return Validator::make($data, [
                //'avatar' => ['image', 'mimes:jpeg,bmp,png,jpg', 'max:2048'],
                'name' => ['required', 'string', 'max:255'],
                'lastname' => ['required', 'string', 'max:255'],
                'phone' => ['required', 'string', 'max:10', 'min:10'],
                'jobtitle' => ['required', 'string', 'max:255'],
                'department_id' => ['required', 'string', 'max:255'],
                'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
                'password' => ['required', 'string', 'min:8', 'confirmed'],

            ]);
        }

        protected function create(array $data)
        {

            return User::create([
                'name' => $data['name'],
                'lastname' => $data['lastname'],
                'phone' => $data['phone'],
                'jobtitle' => $data['jobtitle'],
                'department_id' => $data['department'],
                'email' => $data['email'],
                'password' => Hash::make($data['password']),
            ]);
        }
    }

</code>```

答:
1062 - Duplicate entry 'admin@ana.com' for key 'users_email_unique' this error means that you have two email addresses are the same in your DB and in your migration, you defined email field as unique. So you get this error.

if the form is not working and you cannot see any errors, that's probably there are some validation errors. Here is how to show all of them.

@if ($errors->any())

            @foreach ($errors->all() as $error)

{{ $error }}

            @endforeach

@endif
```

ContentLicense: CC BY-SA 4.0

Body:
I have created a project in Laravel but i cant login and register.When i try to register it stays at the same page and all the fields stay the same the password field stays empty.While in Login page it says that "These credentials do not match our records.".I have tried to drop the database,create new and run php artisan migrate or migrate:fresh and refresh but still not working.When i try to enter a user or admin from phpmyadmin it says this error".I dont know if the error comes maybe because department table and user table are joined,foreign key and primary key,with department_id...

1062 - Duplicate entry 'admin@ana.com' for key 'users_email_unique'

Department.php

       public function users()
        {
            return $this->hasMany(User::class);
        }

User.php

public function users()
{
    return $this->belongsTo(Department::class);
}

   public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');//create_users_table
            //$table->text('avatar');
            $table->string('name');
            $table->string('lastname');
            $table->string('phone');
            $table->string('jobtitle');
            $table->integer('department_id');
            $table->timestamps();
            $table->string('usertype')->nullable();
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();

        });
    }

    public function up()
        {
            Schema::create('departments', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('name');
                $table->timestamps();
            });
        }

RegisterController.php

    class RegisterController extends Controller
    {

        use RegistersUsers;
        protected $redirectTo = RouteServiceProvider::HOME;
        public function __construct()
        {
            $this->middleware('guest');
        }

        protected function validator(array $data)
        {
            return Validator::make($data, [
                //'avatar' => ['image', 'mimes:jpeg,bmp,png,jpg', 'max:2048'],
                'name' => ['required', 'string', 'max:255'],
                'lastname' => ['required', 'string', 'max:255'],
                'phone' => ['required', 'string', 'max:10', 'min:10'],
                'jobtitle' => ['required', 'string', 'max:255'],
                'department_id' => ['required', 'string', 'max:255'],
                'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
                'password' => ['required', 'string', 'min:8', 'confirmed'],

            ]);
        }

        protected function create(array $data)
        {

            return User::create([
                'name' => $data['name'],
                'lastname' => $data['lastname'],
                'phone' => $data['phone'],
                'jobtitle' => $data['jobtitle'],
                'department_id' => $data['department'],
                'email' => $data['email'],
                'password' => Hash::make($data['password']),
            ]);
        }
    }

Body:
1062 - Duplicate entry 'admin@ana.com' for key 'users_email_unique' this error means that you have two email addresses are the same in your DB and in your migration, you defined email field as unique. So you get this error.

if the form is not working and you cannot see any errors, that's probably there are some validation errors. Here is how to show all of them.

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif


问:
I have a problem with a system I am developing in Oracle Apex
I am working on developing an online exam system for the university using Oracle Apex,
I have developed the most part of the system and have a problem showing the exam in front of the student,
Tables used in the exam section:
- Test
- Question

- Answer

This is a picture of the relationship between the tables:

I need to display the question that is in the question table and below it are four options,
The first choice, second choice, and so on ...
After the choice, I need to compare the choice made by the student with the answer that is in the answer schedule.
This process is repeated five times, this is the total questions for each exam.
Then display the result.
Thank you very much.

答:
As with all things in programming, there are many different approaches one could take depending on the requirements. I'll show you one approach given what we've discussed so far.

Given the following tables and data:

```<code>create table test (
    id    number generated by default on null as identity
          constraint test_id_pk primary key,
    name  varchar2(255)
);

create table question (
    id         number generated by default on null as identity
              constraint question_id_pk primary key,
    test_id    number
              constraint question_test_id_fk
              references test on delete cascade,
    question   varchar2(4000),
    ch1        varchar2(4000),
    ch2        varchar2(4000),
    ch3        varchar2(4000),
    ch4        varchar2(4000),
    correct_ch number constraint question_correct_ch_cc
              check (correct_ch in (1,2,3,4))
);

declare

  l_id number;

begin

  insert into test (name) values ('Math') returning id into l_id;

  insert into question (
    test_id,
    question,
    ch1,
    ch2,
    ch3,
    ch4,
    correct_ch
  ) values (
    l_id,
    'What is 1+2?',
    '3',
    '2',
    '4',
    '1',
    1
  );

  insert into question (
    test_id,
    question,
    ch1,
    ch2,
    ch3,
    ch4,
    correct_ch
  ) values (
    l_id,
    'What is 10*0?',
    '10',
    '0',
    '1',
    '100',
    2
  );

  insert into test (name) values ('Science') returning id into l_id;

  insert into question (
    test_id,
    question,
    ch1,
    ch2,
    ch3,
    ch4,
    correct_ch
  ) values (
    l_id,
    'How many planets are there?',
    '10',
    '7',
    '9',
    '8',
    4
  );

  insert into question (
    test_id,
    question,
    ch1,
    ch2,
    ch3,
    ch4,
    correct_ch
  ) values (
    l_id,
    ' What is the biggest planet in our solar system?',
    'Jupiter',
    'Earth',
    'Mars',
    'Pluto',
    1
  );

end;
/
</code>```

The following should work:

Create a new blank page. Set Name to Tests. My page number defaulted to 29, you may need to adjust the page number in what follows.

Add a new region to the page. Set Title to Tests, Type to Classic Report, and Table Name to TEST.

Right-click Columns under the Tests region, then select Create Virtual Column. Click the No Link Defined button for Target. Set Page to be one higher than the current page (30 for me). Under Set Items, put P30_TEST_ID in the Name column and &ID. in the Value column of the same row. Set Clear Cache to 30, then click OK. Set Link Text (under Target) to Take Test. If you run the page, you should see a report of the tests with a link to the test page (it will not work het).

Return to the builder and create another blank page. The Page Number should be one higher than the previous page (30 for me). Set Name to Question.

Add a new region to the page. Set Title to Answer the following question.

Add a new item to the region. Set Name to P30_TEST_ID and Type to Hidden.

Add another item to the region. Set Name to P30_QUESTION_ID and Type to Hidden.

Add another item to the region. Set Name to Question and Type to Display Only.

Add another item to the region. Set Name to P30_CHOICES and Type to Radio Group. Under List of Values, set Type to SQL Query and copy-paste the following into the SQL Query field:

```<code>select val d,
  choice_num r
from question
unpivot (val for choice_num in (ch1 as '1', ch2 as '2', ch3 as '3', ch4 as '4'))
where test_id = :P30_TEST_ID
  and id = :P30_QUESTION_ID
</code>```

Disable Display Extra Values and Display Null Value under the SQL Query field.

This unpivot will turn the columns into rows so it works with the Radio Group. The user will see the text of the choice but the choice number (1-4) will be returned.

Right-click Before Header under Pre-Rendering and select Create Process. Set Name to Init page and copy-paste the following code into the PL/SQL Code field.

```<code>declare

  l_question_rec question%rowtype;

begin

  if :P30_QUESTION_ID is null
  then
    select id
    into :P30_QUESTION_ID
    from question
    where test_id = :P30_TEST_ID
    order by id
    fetch first 1 row only;
  end if;

  select *
  into l_question_rec
  from question
  where id = :P30_QUESTION_ID;

  :P30_QUESTION := l_question_rec.question;
  :P30_CHOICES := null;

end;
</code>```

Add a button to the region. Set Button Name to NEXT_QUESTION.

Under the processing tab, right-click Processing and select Create Process. Set Name to Select next question and copy-paste the following code into the PL/SQL Code field:

```<code>select id
into :P30_QUESTION_ID
from question
where test_id = :P30_TEST_ID
  and id > :P30_QUESTION_ID
order by id
fetch first 1 row only;
</code>```

At this point, if you return to the previous page and run it, you should be able to select a test and see the first question. You should also have the ability to select from the available choices and use the Next Question button to see the next question.

This is a minimum viable example. I've not provided you, up to this point, with a means of validating answers - though I could do that if you want. I suggest you try it first using the techniques I describe here: Alert message after submit and validation page in oracle apex

I've also not accounted for lots of other things: security, don't show the next question button when you're on the last question, etc. I've not done any of that because I'm just trying to give you an idea of how things could work. There will surely be many things you'll want to tweak according to your requirements.

Finally, after having played with this a little, I probably would add a third table for the choices/answers - though it wouldn't work as you had it defined before. It would just store the answers in rows rather than columns which make them a bit easier to work with relationally (no need to unpivot, for example).

Body:
As with all things in programming, there are many different approaches one could take depending on the requirements. I'll show you one approach given what we've discussed so far.

Given the following tables and data:

create table test (
    id    number generated by default on null as identity
          constraint test_id_pk primary key,
    name  varchar2(255)
);

create table question (
    id         number generated by default on null as identity
              constraint question_id_pk primary key,
    test_id    number
              constraint question_test_id_fk
              references test on delete cascade,
    question   varchar2(4000),
    ch1        varchar2(4000),
    ch2        varchar2(4000),
    ch3        varchar2(4000),
    ch4        varchar2(4000),
    correct_ch number constraint question_correct_ch_cc
              check (correct_ch in (1,2,3,4))
);

declare

  l_id number;

begin

  insert into test (name) values ('Math') returning id into l_id;

  insert into question (
    test_id,
    question,
    ch1,
    ch2,
    ch3,
    ch4,
    correct_ch
  ) values (
    l_id,
    'What is 1+2?',
    '3',
    '2',
    '4',
    '1',
    1
  );

  insert into question (
    test_id,
    question,
    ch1,
    ch2,
    ch3,
    ch4,
    correct_ch
  ) values (
    l_id,
    'What is 10*0?',
    '10',
    '0',
    '1',
    '100',
    2
  );

  insert into test (name) values ('Science') returning id into l_id;

  insert into question (
    test_id,
    question,
    ch1,
    ch2,
    ch3,
    ch4,
    correct_ch
  ) values (
    l_id,
    'How many planets are there?',
    '10',
    '7',
    '9',
    '8',
    4
  );

  insert into question (
    test_id,
    question,
    ch1,
    ch2,
    ch3,
    ch4,
    correct_ch
  ) values (
    l_id,
    ' What is the biggest planet in our solar system?',
    'Jupiter',
    'Earth',
    'Mars',
    'Pluto',
    1
  );

end;
/

The following should work:

Create a new blank page. Set Name to Tests. My page number defaulted to 29, you may need to adjust the page number in what follows.

Add a new region to the page. Set Title to Tests, Type to Classic Report, and Table Name to TEST.

Right-click Columns under the Tests region, then select Create Virtual Column. Click the No Link Defined button for Target. Set Page to be one higher than the current page (30 for me). Under Set Items, put P30_TEST_ID in the Name column and &ID. in the Value column of the same row. Set Clear Cache to 30, then click OK. Set Link Text (under Target) to Take Test. If you run the page, you should see a report of the tests with a link to the test page (it will not work het).

Return to the builder and create another blank page. The Page Number should be one higher than the previous page (30 for me). Set Name to Question.

Add a new region to the page. Set Title to Answer the following question.

Add a new item to the region. Set Name to P30_TEST_ID and Type to Hidden.

Add another item to the region. Set Name to P30_QUESTION_ID and Type to Hidden.

Add another item to the region. Set Name to Question and Type to Display Only.

Add another item to the region. Set Name to P30_CHOICES and Type to Radio Group. Under List of Values, set Type to SQL Query and copy-paste the following into the SQL Query field:

select val d,
  choice_num r
from question
unpivot (val for choice_num in (ch1 as '1', ch2 as '2', ch3 as '3', ch4 as '4'))
where test_id = :P30_TEST_ID
  and id = :P30_QUESTION_ID

Disable Display Extra Values and Display Null Value under the SQL Query field.

This unpivot will turn the columns into rows so it works with the Radio Group. The user will see the text of the choice but the choice number (1-4) will be returned.

Right-click Before Header under Pre-Rendering and select Create Process. Set Name to Init page and copy-paste the following code into the PL/SQL Code field.

declare

  l_question_rec question%rowtype;

begin

  if :P30_QUESTION_ID is null
  then
    select id
    into :P30_QUESTION_ID
    from question
    where test_id = :P30_TEST_ID
    order by id
    fetch first 1 row only;
  end if;

  select *
  into l_question_rec
  from question
  where id = :P30_QUESTION_ID;

  :P30_QUESTION := l_question_rec.question;
  :P30_CHOICES := null;

end;

Add a button to the region. Set Button Name to NEXT_QUESTION.

Under the processing tab, right-click Processing and select Create Process. Set Name to Select next question and copy-paste the following code into the PL/SQL Code field:

select id
into :P30_QUESTION_ID
from question
where test_id = :P30_TEST_ID
  and id > :P30_QUESTION_ID
order by id
fetch first 1 row only;

At this point, if you return to the previous page and run it, you should be able to select a test and see the first question. You should also have the ability to select from the available choices and use the Next Question button to see the next question.

This is a minimum viable example. I've not provided you, up to this point, with a means of validating answers - though I could do that if you want. I suggest you try it first using the techniques I describe here: Alert message after submit and validation page in oracle apex

I've also not accounted for lots of other things: security, don't show the next question button when you're on the last question, etc. I've not done any of that because I'm just trying to give you an idea of how things could work. There will surely be many things you'll want to tweak according to your requirements.

Finally, after having played with this a little, I probably would add a third table for the choices/answers - though it wouldn't work as you had it defined before. It would just store the answers in rows rather than columns which make them a bit easier to work with relationally (no need to unpivot, for example).


问:
What is the easiest and best practice way to setting all contexts to 0 in Dialogflow's node.js fulfillment?
Dialogflow has a .clearOutgoingContexts()function but seems to be deprecated, I wonder if looping through all contexts and setting their lifespan to 0 is the best way.

答:
If you saw issue dialogflow

Currently, there is no better way to do that solution


问:
Page Redirection
To help better explain my Question, here is what i have:

I am using a Precoded service, on it i have access to the Template HTML Files Only.

The URL to the Login page is : DynamicPage.aspx?Site=Mysite&WebCode=LoginRequired

The Main site URL would look like : DynamicPage.aspx?Site=Mysite&WebCode= or DynamicPage.aspx?Site=Mysite

What i need is a JavaScript I could put into the main header template file that would view "WebCode" And depending on whats entered redirect to a certain page.

I got from "Sitifensys" a code

Sitifensys

if (window.location.href!="foo.bar/login.php") window.location.href="login.php";

The problem with this code is even when i go to the main page it still redirects me to login.php which i do not want it to. I need this code to Read the "WebCode" If it is "LoginRequired" Redirect to "Login.php" else if redirect to "Test.php"

Hope this explanation is a bit better.

答:
You can add this script at the beginning of the body tag:

```<code><body>
  <script>
    if((/WebCode\=LoginRequired/).test(window.location.href)){
      window.location.href = window.location.href.
        replace(/(\?|\&)WebCode\=LoginRequired/, '');
    }
  </script>
  ...
</body>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Page Redirection

Body:
You can add this script at the beginning of the body tag:

<body>
  <script>
    if((/WebCode\=LoginRequired/).test(window.location.href)){
      window.location.href = window.location.href.
        replace(/(\?|\&)WebCode\=LoginRequired/, '');
    }
  </script>
  ...
</body>


问:
Why isn't Java Fullscreen Exclusive Mode running my max screen resolution?
I am trying to get the Java Fullscreen Exclusive Mode to run at 1080p on my computer, but it only has a size of 1536 x 864. The display mode is also set at 1920 x 1080.

GraphicsDevice device = GraphicsEnvironment
         .getLocalGraphicsEnvironment().getDefaultScreenDevice();
// device.getDisplayMode() returns 1920 x 1080 and some other stats
// device.getDefaultConfiguration().getBounds() returns 1536 x 864
```

I'm hoping to try to get the screen to be at 1920 x 1080 rather than 1536 x 864. Is there an actual way to do this or is this normal?

Thanks in advance!

Edit: For now, I'm getting this to work on Windows

答: It's been a little bit of time and I realized that I didn't answer the question. I eventually figured it out and the issue was likely a bug in Java 11. When I reverted back to the Java 8 development environment (v221?), the pixels went back to 1920 x 1080.</p>

Body:
I am trying to get the Java Fullscreen Exclusive Mode to run at 1080p on my computer, but it only has a size of 1536 x 864. The display mode is also set at 1920 x 1080.

GraphicsDevice device = GraphicsEnvironment
         .getLocalGraphicsEnvironment().getDefaultScreenDevice();
// device.getDisplayMode() returns 1920 x 1080 and some other stats
// device.getDefaultConfiguration().getBounds() returns 1536 x 864

I'm hoping to try to get the screen to be at 1920 x 1080 rather than 1536 x 864. Is there an actual way to do this or is this normal?

Thanks in advance!

Edit: For now, I'm getting this to work on Windows


问:
How @Target(ElementType.ANNOTATION_TYPE) works
Java annotations are marked with a @Target annotation to declare possible joinpoints which can be decorated by that annotation. Values TYPE, FIELD, METHOD, etc. of the ElementType enum are clear and simply understandable.

Question

WHY to use @Target(ANNOTATION_TYPE) value? What are the annotated annotations good for? What is their contribution? Give me an explanation of an idea how it works and why I should use it. Some already existing and well-known example of its usage would be great too.

答:
Annotation is defined like a ordinary Java interface, but with an '@' preceding the interface keyword (i.e., @interface ). Annotations are used to provide supplemental information about a program. On the other hand, an interface can be defined as a container that stores the signatures of the methods to be implemented in the code segment.

WHY to use @Target(ANNOTATION_TYPE) value?

When there is need to apply an annotation to an another annotation. If you look at the source codes of the common Java annotations, you see often this code pattern:

```<code>@Target(ANNOTATION_TYPE)
public @interface TheAnnotation
{
  ...
}
</code>```

For example,

```<code>@Documented
@Target({ ANNOTATION_TYPE })
@Retention(RUNTIME)
public @interface Constraint {
public Class<? extends ConstraintValidator<?, ?>>[] validatedBy();
}
</code>```

What are the annotated annotations good for?

They are good or more precisely necessary if they are used to annotate other annotations.

What is their contribution?

They make possible to apply an annotation directly to an another annotation, that is a different thing than applying an annotation to a standard Java class or to method and so on.

Give me an explanation of an idea how it works and why I should use it.

For example, if you create a data model class and you may want that the program checks data validity. In that case, there might be need to create a new annotation and apply another annotations to this annotation. It is simple to add some data validity checks to this model by adding annotations to the class. For example, to check that some value is not null (@notNull) or email is valid (@ValidEmail) or length of a field is more than x characters (@Size). However, it is possible that there is not built in Java annotations for all purposes. For example, it is so if you liked to check if password and its matchingPassword  are same. This is possible by creating the annotation class PasswordMatches:

```<code>@Target({TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = PasswordMatchesValidator.class)
@Documented
public @interface PasswordMatches {

    String message() default "Passwords don't match";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

 }
</code>```

Note, there is line

```<code>@Constraint(validatedBy = PasswordMatchesValidator.class).
</code>```

In other words, the annotation class Constraint, like the other annotations in this class also, must have ANNOTATION_TYPE as a value of target annotation.

Now the password equality check is easy to include to data model class simply by adding annotation @PasswordMatches:

```<code>@PasswordMatches
public class UserDto {
...
}
</code>```

The PasswordMatchesValidator class could look like this:

```<code>public class PasswordMatchesValidator implements ConstraintValidator<PasswordMatches, Object> {

@Override
public void initialize(final PasswordMatches constraintAnnotation) {}

@Override
public boolean isValid(final Object obj, final ConstraintValidatorContext context) {
    final UserDto user = (UserDto) obj;
    return user.getPassword().equals(user.getMatchingPassword());
    }
}
</code>```

Some already existing and well-known example of its usage would be great too.

There is quite well-known example in item 4, but another known annotations which are applied frequently to custom annotations are @Retention, @Documented and @Target itself.

Body:
Annotation is defined like a ordinary Java interface, but with an '@' preceding the interface keyword (i.e., @interface ). Annotations are used to provide supplemental information about a program. On the other hand, an interface can be defined as a container that stores the signatures of the methods to be implemented in the code segment.

WHY to use @Target(ANNOTATION_TYPE) value?

When there is need to apply an annotation to an another annotation. If you look at the source codes of the common Java annotations, you see often this code pattern:

@Target(ANNOTATION_TYPE)
public @interface TheAnnotation
{
  ...
}

For example,

@Documented
@Target({ ANNOTATION_TYPE })
@Retention(RUNTIME)
public @interface Constraint {
public Class<? extends ConstraintValidator<?, ?>>[] validatedBy();
}

What are the annotated annotations good for?

They are good or more precisely necessary if they are used to annotate other annotations.

What is their contribution?

They make possible to apply an annotation directly to an another annotation, that is a different thing than applying an annotation to a standard Java class or to method and so on.

Give me an explanation of an idea how it works and why I should use it.

For example, if you create a data model class and you may want that the program checks data validity. In that case, there might be need to create a new annotation and apply another annotations to this annotation. It is simple to add some data validity checks to this model by adding annotations to the class. For example, to check that some value is not null (@notNull) or email is valid (@ValidEmail) or length of a field is more than x characters (@Size). However, it is possible that there is not built in Java annotations for all purposes. For example, it is so if you liked to check if password and its matchingPassword  are same. This is possible by creating the annotation class PasswordMatches:

@Target({TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = PasswordMatchesValidator.class)
@Documented
public @interface PasswordMatches {

    String message() default "Passwords don't match";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

 }

Note, there is line

@Constraint(validatedBy = PasswordMatchesValidator.class).

In other words, the annotation class Constraint, like the other annotations in this class also, must have ANNOTATION_TYPE as a value of target annotation.

Now the password equality check is easy to include to data model class simply by adding annotation @PasswordMatches:

@PasswordMatches
public class UserDto {
...
}

The PasswordMatchesValidator class could look like this:

public class PasswordMatchesValidator implements ConstraintValidator<PasswordMatches, Object> {

@Override
public void initialize(final PasswordMatches constraintAnnotation) {}

@Override
public boolean isValid(final Object obj, final ConstraintValidatorContext context) {
    final UserDto user = (UserDto) obj;
    return user.getPassword().equals(user.getMatchingPassword());
    }
}

Some already existing and well-known example of its usage would be great too.

There is quite well-known example in item 4, but another known annotations which are applied frequently to custom annotations are @Retention, @Documented and @Target itself.


问:
Rectify edges of a shape in mask with OpenCV
I need to rectify the edges of a shape (polygon) like the one below.

It is the result of cv2.approxPolyDPm, that approximates cv2.findContours results:

```<code>for (i, c) in enumerate(cnts):
    peri = cv2.arcLength(c, closed=True)
    approx = cv2.approxPolyDP(c, epsilon=0.01 * peri, closed=True)
</code>```

Some borders are not straight. I need them to be perfectly vertical or horizontal.
I tried modifying the epsilon value without success.

答:
You need to add another stage that forces contour vertices to form only horizontal and vertical straight lines.

If two vertices p1, p2 has very close y coordinates (say below 10 pixels), you need to fix y coordinate of p1 to be equal to y coordinate of p2 or vice versa.

Here is a working code sample (please read the comments):

```<code>import cv2
import numpy as np

font = cv2.FONT_HERSHEY_COMPLEX

img = cv2.imread('img.png', cv2.IMREAD_COLOR)

# Remove image borders
img = img[20:-20, 20:-20, :]

imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# https://pysource.com/2018/09/25/simple-shape-detection-opencv-with-python-3/
# From the black and white image we find the contours, so the boundaries of all the shapes.
_, threshold = cv2.threshold(imgray, 127, 255, cv2.THRESH_BINARY)
_, contours, _ = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

c = contours[0]

peri = cv2.arcLength(c, closed=True)
approx = cv2.approxPolyDP(c, epsilon=0.01 * peri, closed=True)

# Delat threshold
t = 10

# n - Number of vertices
n = approx.shape[0]

for i in range(n):
    #      p1              p2
    #       *--------------*
    #       |
    #       |
    #       |
    #       *
    #      p0

    p0 = approx[(i+n-1) % n][0]    # Previous vertex
    p1 = approx[i][0]              # Current vertex
    p2 = approx[(i + 1) % n][0]    # Next vertex
    dx = p2[0] - p1[0]             # Delta pixels in horizontal direction
    dy = p2[1] - p1[1]             # Delta pixels in vertical direction

    # Fix x index of vertices p1 and p2 to be with same x coordinate ([<p1>, <p2>] form horizontal line).
    if abs(dx) < t:
        if ((dx < 0) and (p0[0] > p1[0])) or ((dx > 0) and (p0[0] < p1[0])):
            p2[0] = p1[0]
        else:
            p1[0] = p2[0]

    # Fix y index of vertices p1 and p2 to be with same y coordinate ([<p1>, <p2>] form vertical line).
    if abs(dy) < t:
        if ((dy < 0) and (p0[1] > p1[1])) or ((dy > 0) and (p0[1] < p1[1])):
            p2[1] = p1[1]
        else:
            p1[1] = p2[1]

    approx[i][0] = p1
    approx[(i + 1) % n][0] = p2

cv2.drawContours(img, [approx], 0, (0, 255, 0), 1)

# Finally we display everything on the screen:
cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

Result:

Note: the solution needs some polishing (my intention was to get the contour with the minimal area).

Body:
I need to rectify the edges of a shape (polygon) like the one below.

It is the result of cv2.approxPolyDPm, that approximates cv2.findContours results:

for (i, c) in enumerate(cnts):
    peri = cv2.arcLength(c, closed=True)
    approx = cv2.approxPolyDP(c, epsilon=0.01 * peri, closed=True)

Some borders are not straight. I need them to be perfectly vertical or horizontal.
I tried modifying the epsilon value without success.

Body:
You need to add another stage that forces contour vertices to form only horizontal and vertical straight lines.

If two vertices p1, p2 has very close y coordinates (say below 10 pixels), you need to fix y coordinate of p1 to be equal to y coordinate of p2 or vice versa.

Here is a working code sample (please read the comments):

import cv2
import numpy as np

font = cv2.FONT_HERSHEY_COMPLEX

img = cv2.imread('img.png', cv2.IMREAD_COLOR)

# Remove image borders
img = img[20:-20, 20:-20, :]

imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# https://pysource.com/2018/09/25/simple-shape-detection-opencv-with-python-3/
# From the black and white image we find the contours, so the boundaries of all the shapes.
_, threshold = cv2.threshold(imgray, 127, 255, cv2.THRESH_BINARY)
_, contours, _ = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

c = contours[0]

peri = cv2.arcLength(c, closed=True)
approx = cv2.approxPolyDP(c, epsilon=0.01 * peri, closed=True)

# Delat threshold
t = 10

# n - Number of vertices
n = approx.shape[0]

for i in range(n):
    #      p1              p2
    #       *--------------*
    #       |
    #       |
    #       |
    #       *
    #      p0

    p0 = approx[(i+n-1) % n][0]    # Previous vertex
    p1 = approx[i][0]              # Current vertex
    p2 = approx[(i + 1) % n][0]    # Next vertex
    dx = p2[0] - p1[0]             # Delta pixels in horizontal direction
    dy = p2[1] - p1[1]             # Delta pixels in vertical direction

    # Fix x index of vertices p1 and p2 to be with same x coordinate ([<p1>, <p2>] form horizontal line).
    if abs(dx) < t:
        if ((dx < 0) and (p0[0] > p1[0])) or ((dx > 0) and (p0[0] < p1[0])):
            p2[0] = p1[0]
        else:
            p1[0] = p2[0]

    # Fix y index of vertices p1 and p2 to be with same y coordinate ([<p1>, <p2>] form vertical line).
    if abs(dy) < t:
        if ((dy < 0) and (p0[1] > p1[1])) or ((dy > 0) and (p0[1] < p1[1])):
            p2[1] = p1[1]
        else:
            p1[1] = p2[1]

    approx[i][0] = p1
    approx[(i + 1) % n][0] = p2

cv2.drawContours(img, [approx], 0, (0, 255, 0), 1)

# Finally we display everything on the screen:
cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Result:

Note: the solution needs some polishing (my intention was to get the contour with the minimal area).


问:
How to apply the "chrome.webnavigation.oncommitted.addlistener" in this case?
I have a Chrome extension, which changes the colors in the images of the web pages. When the extension is activated (via a icon on the Chrome browser toolbar ), the images in all open pages in tabs are recolored . When the URL of a tab is updated, the images are then recolored too. But, before show the recolored images, there are shown the original.
Inorder to solve it, I hide the document (via the "esconde.js"). Then call "recolor.js" which makes changes in the images and finally, it is injected the "mostra.js", that makes the document visible.
With this code, it was supposed that the document was visible only after the images are recolored, since the script "mostra.js" is a callback script " recolor.js " . I do not know why it does not happen as expected, ecause in most of pages I still see the original images before the recolored.
I read a few things , and I think that (perhaps) with "chrome.webnavigation.oncommitted.addlistener" instead of "chrome.tabs.onUpdated.addListener" it could solve.
However, I don't know how to substitute the "chrome.tabs.onUpdated.addListener" by "chrome.webnavigation.oncommitted.addlistener" (although it basic).
Please can someone help me in this task ?</p>

```<code>chrome.tabs.onUpdated.addListener(function(tabid, info, tab) {
  if (flag){
    if (info.status != "complete")
      chrome.tabs.executeScript(tabid, {file:"esconde.js", runAt: 'document_start' });
    if (info.status == "complete") {
      chrome.tabs.executeScript(tabid, {file:"recolor.js", runAt: 'document_start' }, function() {
        chrome.tabs.executeScript(tabid, {file:"mostra.js", runAt: 'document_start' });
      });
      chrome.browserAction.setIcon({path: "off.png", tabId:tab.id});
    }
  }
});
</code>```

答:
with arrow functions (supported by most of the modern browsers) and filters:</p>

```<code>'use strict';
console.log('RUNNING ' + new Date().toLocaleTimeString());

chrome.webNavigation.onDOMContentLoaded.addListener(details => {
    chrome.tabs.executeScript(details.tabId, { file: "content/login.js" }, (resultsArray) => {
        console.table(resultsArray);
    });
}, {
    url: [
        { pathSuffix: 'login.aspx' }
    ]
});
</code>```

Body:
I have a Chrome extension, which changes the colors in the images of the web pages. When the extension is activated (via a icon on the Chrome browser toolbar ), the images in all open pages in tabs are recolored . When the URL of a tab is updated, the images are then recolored too. But, before show the recolored images, there are shown the original.
Inorder to solve it, I hide the document (via the "esconde.js"). Then call "recolor.js" which makes changes in the images and finally, it is injected the "mostra.js", that makes the document visible.
With this code, it was supposed that the document was visible only after the images are recolored, since the script "mostra.js" is a callback script " recolor.js " . I do not know why it does not happen as expected, ecause in most of pages I still see the original images before the recolored.
I read a few things , and I think that (perhaps) with "chrome.webnavigation.oncommitted.addlistener" instead of "chrome.tabs.onUpdated.addListener" it could solve.
However, I don't know how to substitute the "chrome.tabs.onUpdated.addListener" by "chrome.webnavigation.oncommitted.addlistener" (although it basic).
Please can someone help me in this task ?

chrome.tabs.onUpdated.addListener(function(tabid, info, tab) {
  if (flag){
    if (info.status != "complete")
      chrome.tabs.executeScript(tabid, {file:"esconde.js", runAt: 'document_start' });
    if (info.status == "complete") {
      chrome.tabs.executeScript(tabid, {file:"recolor.js", runAt: 'document_start' }, function() {
        chrome.tabs.executeScript(tabid, {file:"mostra.js", runAt: 'document_start' });
      });
      chrome.browserAction.setIcon({path: "off.png", tabId:tab.id});
    }
  }
});

Body:
with arrow functions (supported by most of the modern browsers) and filters:

'use strict';
console.log('RUNNING ' + new Date().toLocaleTimeString());

chrome.webNavigation.onDOMContentLoaded.addListener(details => {
    chrome.tabs.executeScript(details.tabId, { file: "content/login.js" }, (resultsArray) => {
        console.table(resultsArray);
    });
}, {
    url: [
        { pathSuffix: 'login.aspx' }
    ]
});


问:
How can I count the number of elements in a vector that fall within a particular range using r?
Let's say we a vector a = (10,23,57,37,59,25,63,33) and we want to calculate the frequency in the bins 10-19,20-29,30-39,40-49,50-59,60-69.The output should be in the form of a vector, in this case (1,2,2,2,1).

答:
Here is the solution:</p>

```<code>a <- c(10, 23, 57, 37, 59, 25, 63, 33)
low_val  <- 10
high_val <- 70
a_breaks <- seq(low_val, high_val, 10)
res <- cut(a, a_breaks, include.lowest = T)
as.vector(table(res))
[1] 1 2 2 0 2 1
</code>```

Body:
Here is the solution:

a <- c(10, 23, 57, 37, 59, 25, 63, 33)
low_val  <- 10
high_val <- 70
a_breaks <- seq(low_val, high_val, 10)
res <- cut(a, a_breaks, include.lowest = T)
as.vector(table(res))
[1] 1 2 2 0 2 1


问:
Reset an Angular Template-Driven Form?
I'm learning Angular, and I cannot figure out how to reset the validation of a template driven form.

In the official tutorial, they show a method to reset the form so it doesn't show any error messages even if the untouched field is empty, but it doesn't work for me.

Here is the official example of the app, where "New Hero (with reset)" and "New Hero (without reset)" seem to result in the same situation (red error indicators on the left of the input, "Name is required" warning under the name input). I remove the value in the input and press the button, but the error message remains:

https://stackblitz.com/angular/kmoqyljrgve

```<code><form (ngSubmit)="onSubmit()" #heroForm="ngForm">
  <div class="form-group">
    <label for="name">Name</label>
    <input type="text" class="form-control" id="name"
           required
           [(ngModel)]="model.name" name="name"
           #name="ngModel">
    <div [hidden]="name.valid || name.pristine"
         class="alert alert-danger">
      Name is required
    </div>
  </div>

  <div class="form-group">
    <label for="alterEgo">Alter Ego</label>
    <input type="text" class="form-control" id="alterEgo"
           [(ngModel)]="model.alterEgo" name="alterEgo">
  </div>

  <div class="form-group">
    <label for="power">Hero Power</label>
    <select class="form-control" id="power"
            required
            [(ngModel)]="model.power" name="power"
            #power="ngModel">
      <option *ngFor="let pow of powers" [value]="pow">{{pow}}</option>
    </select>
    <div [hidden]="power.valid || power.pristine" class="alert alert-danger">
      Power is required
    </div>
  </div>

  <button type="submit" class="btn btn-success" [disabled]="!heroForm.form.valid">Submit</button>
  <button type="button" class="btn btn-default" (click)="newHero(); heroForm.reset()">New Hero</button>
  <i>with</i> reset

  <button type="button" class="btn btn-default" (click)="newHero()">New Hero</button>
  <i>without</i> reset

 <!-- NOT SHOWN IN DOCS -->
  <div>
    <hr>
    Name via form.controls = {{showFormControls(heroForm)}}
  </div>
 <!-- - -->
</form>
</code>```

Can anyone explain this or show me what i misunderstood?

Thanks in advance

答:
```<code>For select drop down use the below:

/* html */

<form #itemForm="ngForm" (ngSubmit)="onSubmit(itemForm)" style="font-family: Montserrat-Regular;">
    <div class="form-group">
        <input type="text" class="form-control" id="name" name="name" aria-describedby="emailHelp" placeholder="Name"
        #name="ngModel" [class.is-invalid]="name.invalid && name.touched" ngModel [(ngModel)]="drinkname" required>
        <p style="color: red; font-size: 12px" [class.d-none]="name.valid || name.untouched">Name is required</p>
    </div>
    <div class="form-group">
        <select class="form-control" id="rating" name="rating" #rating="ngModel"
        [class.is-invalid]="rating.invalid && rating.touched" ngModel [(ngModel)]="drinkrating" required>
        <option value="undefined" hidden>Select Rating</option>
              <option value="3">3</option>
              <option value="4">4</option>
              <option value="5">5</option>
              <option value="6">6</option>
              <option value="7">7</option>
              <option value="8">8</option>
              <option value="9">9</option>
              <option value="10">10</option>
        </select>
        <p style="color: red; font-size: 12px" [class.d-none]="count.valid || count.untouched">Count is required</p>
    </div>
    <button type="submit" class="btn btn-primary" [disabled]="itemForm.form.invalid">Submit</button>
  </form>

/* ts */

onSubmit(userForm: NgForm) {

      this.formData = new FormData();
      this.formData.append('name', this.drinkname);
      this.formData.append('rating', this.drinkrating);

    const options = {
      headers: new HttpHeaders()
        .set('Authorization', 'Bearer ' + localStorage.getItem('token'))
    }

    this.http.post('http://localhost:8099/createi', this.formData, options)
      .subscribe(
        data => {
          var status = data['status'];
          var message = data['message'];
          if (status == -1){
            this.notifyService.showError(message,"Exists");
            return;
          }

          // this is the important code, dont worry about name input because it will use placeholder as default value
          userForm.resetForm({
            rating: "undefined",

         });
        },
        error => console.log(error)
      );
  }
</code>```

Title: Reset an Angular Template-Driven Form?

Body:
I'm learning Angular, and I cannot figure out how to reset the validation of a template driven form.

In the official tutorial, they show a method to reset the form so it doesn't show any error messages even if the untouched field is empty, but it doesn't work for me.

Here is the official example of the app, where "New Hero (with reset)" and "New Hero (without reset)" seem to result in the same situation (red error indicators on the left of the input, "Name is required" warning under the name input). I remove the value in the input and press the button, but the error message remains:

https://stackblitz.com/angular/kmoqyljrgve

<form (ngSubmit)="onSubmit()" #heroForm="ngForm">

    Name
    <input type="text" class="form-control" id="name"
           required
           [(ngModel)]="model.name" name="name"
           #name="ngModel">

      Name is required

    Alter Ego
    <input type="text" class="form-control" id="alterEgo"
           [(ngModel)]="model.alterEgo" name="alterEgo">

    Hero Power
    <select class="form-control" id="power"
            required
            [(ngModel)]="model.power" name="power"
            #power="ngModel">
      <option *ngFor="let pow of powers" [value]="pow">{{pow}}</option>
    </select>

      Power is required

  <button type="submit" class="btn btn-success" [disabled]="!heroForm.form.valid">Submit</button>
  <button type="button" class="btn btn-default" (click)="newHero(); heroForm.reset()">New Hero</button>
  with reset

  <button type="button" class="btn btn-default" (click)="newHero()">New Hero</button>
  without reset

    Name via form.controls = {{showFormControls(heroForm)}}

</form>

Can anyone explain this or show me what i misunderstood?

Thanks in advance


问:
Method Illuminate\Routing\Route::resource does not exist. In Macroable.php line 78
I'm trying to see the help of php artisan make:controller --help method but I get this error:

In Macroable.php line 78:
  Method Illuminate\Routing\Route::resource does not exist.

答:
Ok, I found the problem. I just needed to import this:
use Illuminate\Support\Facades\Route;

I don't know why it wasn't there when I created the project. Btw I'm using Laravel 5.8


问:
GraphQL api consuming with spring boot Resttemplate resulting in {"errors":[{"message":"No query string was present"}]} always
Currently we want to consume a graphQL endpoint in a springboot application using resttemplate

However, when we make a POST request with the below query we are always receiving the same error {"errors":[{"message":"No query string was present"}]}

Below is the snippet, we want to run,

```<code>    @Test
    public void testSwoop(){

        RestTemplate restTemplate = restTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer *************");
        headers.add("content-type", "application/graphql");

        String query1 = "{\n" +
                "  \"query\": query {\n" +
                "    \"locationTypes\": {\n" +
                "      \"edges\": \n" +
                "        {\n" +
                "          \"node\": \n" +
                "        {\n" +
                "          \"name\"\n" +
                "        }\n" +
                "        }\n" +
                "    }\n" +
                "  }\n" +
                "}";

        String URL = "https://staging.joinswoop.com/graphql";

        ResponseEntity<String> response = restTemplate.postForEntity(URL, new HttpEntity<>(query1, headers), String.class);
      System.out.println("The response================="+response);
    }
</code>```

However from Postman, we dont have any issue in consuming the endpoint, and we get response just fine

Can someone please help us in directing us to the correct resource

答:
you set the content type header to "application/graphql", but yo are sending a JSON as data.
Two solutions that might work:

Sending JSON:

Set the content type to "application/json" and send a JSON formatted query:

```<code>@Test
public void testSwoop(){

    RestTemplate restTemplate = restTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Bearer *************");
    headers.add("content-type", "application/json"); // just modified graphql into json

    String query1 = "{\n" +
            "  \"query\": query {\n" +
            "    \"locationTypes\": {\n" +
            "      \"edges\": \n" +
            "        {\n" +
            "          \"node\": \n" +
            "        {\n" +
            "          \"name\"\n" +
            "        }\n" +
            "        }\n" +
            "    }\n" +
            "  }\n" +
            "}";

    String URL = "https://staging.joinswoop.com/graphql";

    ResponseEntity<String> response = restTemplate.postForEntity(URL, new HttpEntity<>(query1, headers), String.class);
  System.out.println("The response================="+response);
}
</code>```

Sending GraphQL Query:

If your server support this (it should), set the content type to "application/graphql", and send a real graphql query as a string.

```<code>@Test
public void testSwoop(){

    RestTemplate restTemplate = restTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Bearer *************");
    headers.add("content-type", "application/graphql"); // maintain graphql

    // query is a grapql query wrapped into a String
    String query1 = "{\n" +
            "    locationTypes: {\n" +
            "      edges: \n" +
            "        {\n" +
            "          node: \n" +
            "        {\n" +
            "          name\n" +
            "        }\n" +
            "        }\n" +
            "    }\n" +
            "  }";

    String URL = "https://staging.joinswoop.com/graphql";

    ResponseEntity<String> response = restTemplate.postForEntity(URL, new HttpEntity<>(query1, headers), String.class);
  System.out.println("The response================="+response);
}
</code>```

Body:
Currently we want to consume a graphQL endpoint in a springboot application using resttemplate

However, when we make a POST request with the below query we are always receiving the same error {"errors":[{"message":"No query string was present"}]}

Below is the snippet, we want to run,

    @Test
    public void testSwoop(){

        RestTemplate restTemplate = restTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer *************");
        headers.add("content-type", "application/graphql");

        String query1 = "{\n" +
                "  \"query\": query {\n" +
                "    \"locationTypes\": {\n" +
                "      \"edges\": \n" +
                "        {\n" +
                "          \"node\": \n" +
                "        {\n" +
                "          \"name\"\n" +
                "        }\n" +
                "        }\n" +
                "    }\n" +
                "  }\n" +
                "}";

        String URL = "https://staging.joinswoop.com/graphql";

        ResponseEntity<String> response = restTemplate.postForEntity(URL, new HttpEntity<>(query1, headers), String.class);
      System.out.println("The response================="+response);
    }

However from Postman, we dont have any issue in consuming the endpoint, and we get response just fine

Can someone please help us in directing us to the correct resource

Body:
you set the content type header to "application/graphql", but yo are sending a JSON as data.
Two solutions that might work:

Sending JSON:

Set the content type to "application/json" and send a JSON formatted query:

@Test
public void testSwoop(){

    RestTemplate restTemplate = restTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Bearer *************");
    headers.add("content-type", "application/json"); // just modified graphql into json

    String query1 = "{\n" +
            "  \"query\": query {\n" +
            "    \"locationTypes\": {\n" +
            "      \"edges\": \n" +
            "        {\n" +
            "          \"node\": \n" +
            "        {\n" +
            "          \"name\"\n" +
            "        }\n" +
            "        }\n" +
            "    }\n" +
            "  }\n" +
            "}";

    String URL = "https://staging.joinswoop.com/graphql";

    ResponseEntity<String> response = restTemplate.postForEntity(URL, new HttpEntity<>(query1, headers), String.class);
  System.out.println("The response================="+response);
}

Sending GraphQL Query:

If your server support this (it should), set the content type to "application/graphql", and send a real graphql query as a string.

@Test
public void testSwoop(){

    RestTemplate restTemplate = restTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Bearer *************");
    headers.add("content-type", "application/graphql"); // maintain graphql

    // query is a grapql query wrapped into a String
    String query1 = "{\n" +
            "    locationTypes: {\n" +
            "      edges: \n" +
            "        {\n" +
            "          node: \n" +
            "        {\n" +
            "          name\n" +
            "        }\n" +
            "        }\n" +
            "    }\n" +
            "  }";

    String URL = "https://staging.joinswoop.com/graphql";

    ResponseEntity<String> response = restTemplate.postForEntity(URL, new HttpEntity<>(query1, headers), String.class);
  System.out.println("The response================="+response);
}


问:
'Could not find member 'type' on object of type 'PolicyParameter'
I having hard time with those Polcies and deployment through Azure Pipelines. Now it is expecting defined type when it is already defined.

I using Azure Policies Deploy Template (Create and assign task both have version 3)
Error message:

InvalidRequestContent : The request content was invalid and could not
  be deserialized: 'Could not find member 'type' on object of type
  'PolicyParameter'. Path 'properties.parameters.envValue.type', line 9,
  position 15.'.

Prof

What is wrong with my parameres file?

```<code>{
  "envValue": {
    "type": "String",
    "metadata": {
      "displayName": "Tag Value",
      "description": "Deployment Environment of the resource"
    },
    "defaultValue": "Dev",
    "allowedValues": [
      "Dev",
      "Qas",
      "prd"
    ]
  }
}
</code>```

My assignment task:

```<code># Input variables: set these values in the variables section of the release pipeline

#   AssignmentName        - [required] Policy assignment name
#   AssignmentDisplayName - [optional] Policy assignment display name
#   AssignmentDescription - [optional] Policy assignment description
#   PolicyName            - [optional] Name of policy definition to assign
#   PolicySetName         - [optional] Name of policy set definition to assign
#   ResourceGroupName     - [optional] Name of resource group the policy [set] definition will be applied to
#   SubscriptionId        - [optional] Id of subscription the policy [set] definition will be applied to
#   ManagementGroupName   - [optional] Name of management group the policy [set] definition will be applied to
#  PolicyParameters      - [optional] Policy parameter values in JSON string format

# Notes:
#   Refer to https://learn.microsoft.com/en-us/azure/azure-policy/ for documentation on the Powershell cmdlets and the JSON input formats

$assignmentName = "$(AssignmentName)"
$assignmentDisplayName = "$(AssignmentDisplayName)"
$assignmentDescription = "$(AssignmentDescription)"
$policyName = "$(PolicyName)"
$policySetName = "$(PolicySetName)"
$resourceGroupName = "$(ResourceGroupName)"
$subscriptionId = "$(SubscriptionId)"
$managementGroupName = "$(managementGroupName)"
$policyParameters = "$(PolicyParameters)"

if (!$assignmentName)
{
    throw "Unable to create policy assignment: required input variable value `$(AssignmentName) was not provided"
}

if (!$policyName -and !$policySetName)
{
    throw "Unable to create policy assignment: neither `$(PolicyName) nor `$(PolicySetName) was provided. One or the other must be provided."
}

if ($policyName -and $policySetName)
{
    throw "Unable to create policy assignment: `$(PolicyName) '$policyName' and `$(PolicySetName) '$policySetName' were both provided. Either may be provided, but not both."
}

if ($subscriptionId -and $managementGroupName)
{
    throw "Unable to create policy assignment: `$(SubscriptionId) '$subscriptionId' and `$(ManagementGroupName) '$managementGroupName' were both provided. Either may be provided, but not both."
}

if ($managementGroupName -and $resourceGroupName)
{
    throw "Unable to create policy assignment: `$(ManagementGroupName) '$managementGroupName' and `$(ResourceGroupName) '$resourceGroupName' were both provided. Either may be provided, but not both."
}

if ($managementGroupName)
{
    $scope = "/providers/Microsoft.Management/managementGroups/$managementGroupName"
    $searchParameters = @{ManagementGroupName=$managementGroupName}
}
else
{
    if (!$subscriptionId)
    {
        $subscription = Get-AzureRmContext | Select-Object -Property Subscription
        $subscriptionId = $subscription.Id
    }

    $scope = "/subscriptions/$subscriptionId"
    $searchParameters = @{SubscriptionId=$subscriptionId}

    if ($resourceGroupName)
    {
        $scope += "/resourceGroups/$resourceGroupName"
    }
}

$cmdletParameters = @{Name=$assignmentName; Scope=$scope}
if ($assignmentDisplayName)
{
    $cmdletParameters += @{DisplayName=$assignmentDisplayName}
}

if ($assignmentDescription)
{
    $cmdletParameters += @{Description=$assignmentDescription}
}

if ($policyName)
{
    $policyDefinition = Get-AzureRmPolicyDefinition @searchParameters | Where-Object { $_.Name -eq $policyName }
    if (!$policyDefinition)
    {
        throw "Unable to create policy assignment: policy definition $policyName does not exist"
    }

    $cmdletParameters += @{PolicyDefinition=$policyDefinition}
}

if ($policySetName)
{
    $policySetDefinition = Get-AzureRmPolicySetDefinition @searchParameters | Where-Object { $_.Name -eq $policySetName }
    if (!$policySetDefinition)
    {
        throw "Unable to create policy assignment: policy set definition $policySetName does not exist"
    }

    $cmdletParameters += @{PolicySetDefinition=$policySetDefinition}
}

if ($policyParameters)
{
    $cmdletParameters += @{PolicyParameter=$policyParameters}
}

&New-AzureRmPolicyAssignment @cmdletParameters
</code>```

答: It looks like creating your policy definition task succeeded meaning that your parameters and rule should be already established. The issue is at assignment time meaning that you are probably sending the policy parameter not in a string format to the pipeline. </p>

Body:
I having hard time with those Polcies and deployment through Azure Pipelines. Now it is expecting defined type when it is already defined.

I using Azure Policies Deploy Template (Create and assign task both have version 3)
Error message:

InvalidRequestContent : The request content was invalid and could not
  be deserialized: 'Could not find member 'type' on object of type
  'PolicyParameter'. Path 'properties.parameters.envValue.type', line 9,
  position 15.'.

Prof

What is wrong with my parameres file?

{
  "envValue": {
    "type": "String",
    "metadata": {
      "displayName": "Tag Value",
      "description": "Deployment Environment of the resource"
    },
    "defaultValue": "Dev",
    "allowedValues": [
      "Dev",
      "Qas",
      "prd"
    ]
  }
}

My assignment task:

# Input variables: set these values in the variables section of the release pipeline

#   AssignmentName        - [required] Policy assignment name
#   AssignmentDisplayName - [optional] Policy assignment display name
#   AssignmentDescription - [optional] Policy assignment description
#   PolicyName            - [optional] Name of policy definition to assign
#   PolicySetName         - [optional] Name of policy set definition to assign
#   ResourceGroupName     - [optional] Name of resource group the policy [set] definition will be applied to
#   SubscriptionId        - [optional] Id of subscription the policy [set] definition will be applied to
#   ManagementGroupName   - [optional] Name of management group the policy [set] definition will be applied to
#  PolicyParameters      - [optional] Policy parameter values in JSON string format

# Notes:
#   Refer to https://learn.microsoft.com/en-us/azure/azure-policy/ for documentation on the Powershell cmdlets and the JSON input formats

$assignmentName = "$(AssignmentName)"
$assignmentDisplayName = "$(AssignmentDisplayName)"
$assignmentDescription = "$(AssignmentDescription)"
$policyName = "$(PolicyName)"
$policySetName = "$(PolicySetName)"
$resourceGroupName = "$(ResourceGroupName)"
$subscriptionId = "$(SubscriptionId)"
$managementGroupName = "$(managementGroupName)"
$policyParameters = "$(PolicyParameters)"

if (!$assignmentName)
{
    throw "Unable to create policy assignment: required input variable value `$(AssignmentName) was not provided"
}

if (!$policyName -and !$policySetName)
{
    throw "Unable to create policy assignment: neither `$(PolicyName) nor `$(PolicySetName) was provided. One or the other must be provided."
}

if ($policyName -and $policySetName)
{
    throw "Unable to create policy assignment: `$(PolicyName) '$policyName' and `$(PolicySetName) '$policySetName' were both provided. Either may be provided, but not both."
}

if ($subscriptionId -and $managementGroupName)
{
    throw "Unable to create policy assignment: `$(SubscriptionId) '$subscriptionId' and `$(ManagementGroupName) '$managementGroupName' were both provided. Either may be provided, but not both."
}

if ($managementGroupName -and $resourceGroupName)
{
    throw "Unable to create policy assignment: `$(ManagementGroupName) '$managementGroupName' and `$(ResourceGroupName) '$resourceGroupName' were both provided. Either may be provided, but not both."
}

if ($managementGroupName)
{
    $scope = "/providers/Microsoft.Management/managementGroups/$managementGroupName"
    $searchParameters = @{ManagementGroupName=$managementGroupName}
}
else
{
    if (!$subscriptionId)
    {
        $subscription = Get-AzureRmContext | Select-Object -Property Subscription
        $subscriptionId = $subscription.Id
    }

    $scope = "/subscriptions/$subscriptionId"
    $searchParameters = @{SubscriptionId=$subscriptionId}

    if ($resourceGroupName)
    {
        $scope += "/resourceGroups/$resourceGroupName"
    }
}

$cmdletParameters = @{Name=$assignmentName; Scope=$scope}
if ($assignmentDisplayName)
{
    $cmdletParameters += @{DisplayName=$assignmentDisplayName}
}

if ($assignmentDescription)
{
    $cmdletParameters += @{Description=$assignmentDescription}
}

if ($policyName)
{
    $policyDefinition = Get-AzureRmPolicyDefinition @searchParameters | Where-Object { $_.Name -eq $policyName }
    if (!$policyDefinition)
    {
        throw "Unable to create policy assignment: policy definition $policyName does not exist"
    }

    $cmdletParameters += @{PolicyDefinition=$policyDefinition}
}

if ($policySetName)
{
    $policySetDefinition = Get-AzureRmPolicySetDefinition @searchParameters | Where-Object { $_.Name -eq $policySetName }
    if (!$policySetDefinition)
    {
        throw "Unable to create policy assignment: policy set definition $policySetName does not exist"
    }

    $cmdletParameters += @{PolicySetDefinition=$policySetDefinition}
}

if ($policyParameters)
{
    $cmdletParameters += @{PolicyParameter=$policyParameters}
}

&New-AzureRmPolicyAssignment @cmdletParameters


问:
Powershell/C# XmlDocument selecting only the nodes without attributes
I'm trying to read a Visual Studio project file to select the <PropertyGroup> item that has no attributes to extract the value from the <AssemblyName> node.  The post is close to what I'm looking for but instead of not having a specific attribute I need it to have no attributes

I've tried the following in Powershell without any success.

```<code>$xml = [System.Xml.XmlDocument]::new();

$xml.Load("WebApplication4.csproj")
$ns = [System.Xml.XmlNamespaceManager]::new($xml.NameTable);
$ns.AddNamespace("prj", "http://schemas.microsoft.com/developer/msbuild/2003")

$xml.SelectNodes("//prj:PropertyGroup", $ns).Count
</code>```

Is there a way to use xpath syntax in the selectsinglenode method that would return just the one node that has no attributes?

```<code><?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.7\build\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props" Condition="Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.7\build\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" />
  <Import Project="..\packages\Microsoft.Net.Compilers.2.1.0\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.2.1.0\build\Microsoft.Net.Compilers.props')" />
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>
    </ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{7EC4A73B-EA1B-4A6C-B2ED-093E3615C40E}</ProjectGuid>
    <ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>WebApplication4</RootNamespace>
    <AssemblyName>WebApplication4</AssemblyName>
    <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
    <UseIISExpress>true</UseIISExpress>
    <Use64BitIISExpress />
    <IISExpressSSLPort />
    <IISExpressAnonymousAuthentication />
    <IISExpressWindowsAuthentication />
    <IISExpressUseClassicPipelineMode />
    <UseGlobalApplicationHostFile />
    <NuGetPackageImportStamp>
    </NuGetPackageImportStamp>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
</Project>
</code>```

答:
Jack Fleeting's helpful answer shows how to do it properly with XPath alone.

The following alternative shows how to perform the filtering after the fact, in PowerShell code.

You need to check the length of the .Attributes collection on the target elements to find the one(s) without attributes:

```<code>$xml.SelectNodes("//prj:PropertyGroup", $ns).Where({ $_.Attributes.Count -eq 0 })
</code>```

Note that .Where() is a PowerShell-supplied array (collection) method that enables filtering of any collection via a script block ({ ... }) that needs to return $true for each element ($_) to be selected.

Body:
I'm trying to read a Visual Studio project file to select the <PropertyGroup> item that has no attributes to extract the value from the <AssemblyName> node.  The post is close to what I'm looking for but instead of not having a specific attribute I need it to have no attributes

I've tried the following in Powershell without any success.

$xml = [System.Xml.XmlDocument]::new();

$xml.Load("WebApplication4.csproj")
$ns = [System.Xml.XmlNamespaceManager]::new($xml.NameTable);
$ns.AddNamespace("prj", "http://schemas.microsoft.com/developer/msbuild/2003")

$xml.SelectNodes("//prj:PropertyGroup", $ns).Count

Is there a way to use xpath syntax in the selectsinglenode method that would return just the one node that has no attributes?

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.7\build\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props" Condition="Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.7\build\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" />
  <Import Project="..\packages\Microsoft.Net.Compilers.2.1.0\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.2.1.0\build\Microsoft.Net.Compilers.props')" />
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>
    </ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{7EC4A73B-EA1B-4A6C-B2ED-093E3615C40E}</ProjectGuid>
    <ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>WebApplication4</RootNamespace>
    <AssemblyName>WebApplication4</AssemblyName>
    <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
    <UseIISExpress>true</UseIISExpress>
    <Use64BitIISExpress />
    <IISExpressSSLPort />
    <IISExpressAnonymousAuthentication />
    <IISExpressWindowsAuthentication />
    <IISExpressUseClassicPipelineMode />
    <UseGlobalApplicationHostFile />
    <NuGetPackageImportStamp>
    </NuGetPackageImportStamp>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
</Project>

Body:
Jack Fleeting's helpful answer shows how to do it properly with XPath alone.

The following alternative shows how to perform the filtering after the fact, in PowerShell code.

You need to check the length of the .Attributes collection on the target elements to find the one(s) without attributes:

$xml.SelectNodes("//prj:PropertyGroup", $ns).Where({ $_.Attributes.Count -eq 0 })

Note that .Where() is a PowerShell-supplied array (collection) method that enables filtering of any collection via a script block ({ ... }) that needs to return $true for each element ($_) to be selected.


问:
Run kafka producer with a fixed/static list of brokers
Usually the kafka java client (used within Spring boot, but that does not really matter here, I think, just as a side node) uses the boostrap.servers config (which expects a list of broker addresses:port) to establish an initial connection. Afterwards, a metadata request is used to discover all members of the cluster, which are currently registered.

My question now is, how this discovery can be disabled in the java client. I want to have the KafkaProducer use the list of brokers I supply to it as a fixed, static one.

A little bit more background

The platform my Spring application is deployed to, does not allow internet access to any port, except when using an HTTP proxy (443 or 80). The other alternative is to use a TCP proxy, which works similar to this:

The proxy provides a hostname and port an application can connect to

Once connected, the data stream is forwarded to the previously (during the creation of the proxy) named hostname and port

In that way, the platform can control what traffic is coming from who and is going where, which is a security requirement in my organisation. The communication path then looks like:

```<code>----------------------         -------------         -----------------------
| Application client |  <--->  | TCP Proxy |  <--->  | Target (e.g. kafka) |
----------------------         -------------         -----------------------
</code>```

However, this method does not really work with the public kafka cluster I need to talk to, as the kafka broker in the boostrap.servers list (which I can connect to perfectly fine) will return the list of nodes with the public endpoint names I can not connect to (as they're not going through the proxy).

So, instead of using the discovery functionality of the Kafka client, I would like to use a fixed, pre-defined list of brokers, which I can setup to use the TCP proxy. However, I didn't see any solution for that in the API so far and hope for some help here.

I'm aware, that not using this functionality makes it impossible for the application to use the dynamic changes of the kafka cluster state (when a broker goes away and another one is spinned up), however, this is ok in my scenario and all given circumstances.

答: As an alternative to directly connecting to each broker on its advertised hostname, which is necessary for the functionality of Kafka, you might also consider setting up 1 or more Kafka REST proxies within your network, and then either pointing the proxy to that, or pointing the proxy to a load-balancer which balances across multiple Kafka REST proxies.</p>

Body:
Usually the kafka java client (used within Spring boot, but that does not really matter here, I think, just as a side node) uses the boostrap.servers config (which expects a list of broker addresses:port) to establish an initial connection. Afterwards, a metadata request is used to discover all members of the cluster, which are currently registered.

My question now is, how this discovery can be disabled in the java client. I want to have the KafkaProducer use the list of brokers I supply to it as a fixed, static one.

A little bit more background

The platform my Spring application is deployed to, does not allow internet access to any port, except when using an HTTP proxy (443 or 80). The other alternative is to use a TCP proxy, which works similar to this:

The proxy provides a hostname and port an application can connect to

Once connected, the data stream is forwarded to the previously (during the creation of the proxy) named hostname and port

In that way, the platform can control what traffic is coming from who and is going where, which is a security requirement in my organisation. The communication path then looks like:

----------------------         -------------         -----------------------
| Application client |  <--->  | TCP Proxy |  <--->  | Target (e.g. kafka) |
----------------------         -------------         -----------------------

However, this method does not really work with the public kafka cluster I need to talk to, as the kafka broker in the boostrap.servers list (which I can connect to perfectly fine) will return the list of nodes with the public endpoint names I can not connect to (as they're not going through the proxy).

So, instead of using the discovery functionality of the Kafka client, I would like to use a fixed, pre-defined list of brokers, which I can setup to use the TCP proxy. However, I didn't see any solution for that in the API so far and hope for some help here.

I'm aware, that not using this functionality makes it impossible for the application to use the dynamic changes of the kafka cluster state (when a broker goes away and another one is spinned up), however, this is ok in my scenario and all given circumstances.


问:
Is there a better way to change every variable in a struct, C
I'm curious if there's a better way of changing every variable in a structure instead of the following block of code.

```<code>struct RuntimeData
{
    double runtime_ms, sum_ms, avg_time_ms, best_time_ms;
};

int main()
{
    struct RuntimeData selection;

    // The '0' values are just for example..
    selection.runtime_ms = 0;
    selection.sum_ms = 0;
    selection.avg_time_ms = 0;
    selection.best_time_ms = 0;
}
</code>```

I'd much rather be able to do something similar to this...

```<code>struct RuntimeData selection;

selection = { .runtime_ms=0,
              .sum_ms = 0,
              .avg_time_ms = 0,
              .best_time_ms = 0
};
</code>```

...or something similar. I know you can do the latter codeblock while initializing the structure, but it results in a compilation error after the struct has already been initialized.

EDIT: Using Nate's and Vlad's answers, a compound literal is exactly what I needed! Thank you so much.

答:
You can use a compound literal:

```<code>struct RuntimeData selection;

void foo(void) {
  selection = (struct RuntimeData){ 0, 0, 0, 0 };
}
</code>```

This can be combined with designated initializers:

```<code>struct RuntimeData selection;

void foo(void) {
  selection = (struct RuntimeData){
                    .sum_ms = 42.3,
                    .avg_time_ms = 123.4,
                    .best_time_ms = -7e17,
                    .runtime_ms = 0.0001
  };
}
</code>```

Body:
I'm curious if there's a better way of changing every variable in a structure instead of the following block of code.

struct RuntimeData
{
    double runtime_ms, sum_ms, avg_time_ms, best_time_ms;
};

int main()
{
    struct RuntimeData selection;

    // The '0' values are just for example..
    selection.runtime_ms = 0;
    selection.sum_ms = 0;
    selection.avg_time_ms = 0;
    selection.best_time_ms = 0;
}

I'd much rather be able to do something similar to this...

struct RuntimeData selection;

selection = { .runtime_ms=0,
              .sum_ms = 0,
              .avg_time_ms = 0,
              .best_time_ms = 0
};

...or something similar. I know you can do the latter codeblock while initializing the structure, but it results in a compilation error after the struct has already been initialized.

EDIT: Using Nate's and Vlad's answers, a compound literal is exactly what I needed! Thank you so much.

Body:
You can use a compound literal:

struct RuntimeData selection;

void foo(void) {
  selection = (struct RuntimeData){ 0, 0, 0, 0 };
}

This can be combined with designated initializers:

struct RuntimeData selection;

void foo(void) {
  selection = (struct RuntimeData){
                    .sum_ms = 42.3,
                    .avg_time_ms = 123.4,
                    .best_time_ms = -7e17,
                    .runtime_ms = 0.0001
  };
}


问:
How do i get the uuid of a player in minecraft with nodeJS?
I am working on a discord bot that gets information from a server. for this to work, i need the uuid of a minecraft player. I am using a dependency, but it is not working. Even if I enter a valid name, it still gives me this:
code & output

the string of numbers in the console is a character in minecraft named undefined... so yeah, if you see that my code isn't in the right data type (for example, it was supposed to be an integer instead of a string), please tell me. Thank you!

答:
Send a request to:

https://api.mojang.com/users/profiles/minecraft/

This will give you the UUID of the specified Minecraft username.


问:
Trying to control multithreaded access to array using std::atomic
I'm trying to control multithreaded access to a vector of data which is fixed in size, so threads will wait until their current position in it has been filled before trying to use it, or will fill it themselves if no-one else has yet. (But ensure no-one is waiting around if their position is already filled, or no-one has done it yet)

However, I am struggling to understand a good way to do this, especially involving std::atomic. I'm just not very familiar with C++ multithreading concepts aside from basic std::thread usage.

Here is a very rough example of the problem:

```<code>class myClass
{
  struct Data
  {
    int res1;
  };

  std::vector<Data*> myData;

  int foo(unsigned long position)
  {
    if (!myData[position])
      {
        bar(myData[position]);
      }

    // Do something with the data
    return 5 * myData[position]->res1;
  }

  void bar(Data* &data)
  {
    data = new Data;

    // Do a whole bunch of calculations and so-on here

    data->res1 = 42;
  }
};
</code>```

Now imagine if foo() is being called multi-threaded, and multiple threads may (or may not) have the same position at once. If that happens, there's a chance that a thread may (between when the Data was created and when bar() is finished, try to actually use the data.

So, what are the options?

1: Make a std::mutex for every position in myData. What if there are 10,000 elements in myData? That's 10,000 std::mutexes, not great.

2: Put a lock_guard around it like this:

```<code>std::mutex myMutex;
</code>```

```<code>{
    const std::lock_guard<std::mutex> lock(myMutex);

    if (!myData[position])
      {
        bar(myData[position]);
      }
}
</code>```

While this works, it also means if different threads are working in different positions, they wait needlessly, wasting all of the threading advantage.

3: Use a vector of chars and a spinlock as a poor man's mutex? Here's what that might look like:

```<code>static std::vector<char> positionInProgress;
static std::vector<char> positionComplete;

class myClass
{
  struct Data
  {
    int res1;
  };

  std::vector<Data*> myData;

  int foo(unsigned long position)
  {
    if (positionInProgress[position])
      {
        while (positionInProgress[position])
          {
            ;  // do nothing, just wait until it is done
          }
      }
    else
      {
        if (!positionComplete[position])
          {
            // Fill the data and prevent anyone from using it until it is complete
            positionInProgress[position] = true;
            bar(myData[position]);
            positionInProgress[position] = false;

            positionComplete[position] = true;
          }
      }

    // Do something with the data
    return 5 * myData[position]->res1;
  }

  void bar(Data* data)
  {
    data = new Data;

    // Do a whole bunch of calculations and so-on here

    data->res1 = 42;
  }
};
</code>```

This seems to work, but none of the test or set operations are atomic, so I have a feeling I'm just getting lucky.

4: What about std::atomic and std::atomic_flag? Well, there are a few problems.

std::atomic_flag doesn't have a way to test without setting in C++11...which makes this kind of difficult.

std::atomic is not movable or copy-constructable, so I cannot make a vector of them (I do not know the number of positions during construction of myClass)

Conclusion:

This is the simplest example that (likely) compiles I can think of that demonstrates my real problem. In reality, myData is a 2-dimensional vector implemented using a special hand-rolled solution, Data itself is a vector of pointers to more complex data types, the data isn't simply returned, etc. This is the best I could come up with.

答:
The biggest problem you're likely to have is that a vector itself is not thread-safe, so you can't do ANY operation that might chage the vector (invalidate references to elements of the vector) while another thread might be accessing it, such as resize or push_back.  However, if you vector is effectively "fixed" (you set the size prior to ever spawning threads and thereafter only ever access elements using at or operator[] and never ever modify the vector itself), you can get away with using a vector of atomic objects.  In this case you could have:

```<code>std::vector<std::atomic<Data*>> myData;
</code>```

and your code to setup and use an element could look like:

```<code>if (!myData[position]) {
    Data *tmp = new Data;
    if (!mydata[position].compare_exchange_strong(nullptr, tmp)) {
        // some other thread did the setup
        delete tmp; } }
myData[position]->bar();
</code>```

Of course you still need to make sure that the operations done on members of Data in bar are themselves threadsafe, as you can get mulitple threads calling bar on the same Data instance here.

Body:
I'm trying to control multithreaded access to a vector of data which is fixed in size, so threads will wait until their current position in it has been filled before trying to use it, or will fill it themselves if no-one else has yet. (But ensure no-one is waiting around if their position is already filled, or no-one has done it yet)

However, I am struggling to understand a good way to do this, especially involving std::atomic. I'm just not very familiar with C++ multithreading concepts aside from basic std::thread usage.

Here is a very rough example of the problem:

class myClass
{
  struct Data
  {
    int res1;
  };

  std::vector<Data*> myData;

  int foo(unsigned long position)
  {
    if (!myData[position])
      {
        bar(myData[position]);
      }

    // Do something with the data
    return 5 * myData[position]->res1;
  }

  void bar(Data* &data)
  {
    data = new Data;

    // Do a whole bunch of calculations and so-on here

    data->res1 = 42;
  }
};

Now imagine if foo() is being called multi-threaded, and multiple threads may (or may not) have the same position at once. If that happens, there's a chance that a thread may (between when the Data was created and when bar() is finished, try to actually use the data.

So, what are the options?

1: Make a std::mutex for every position in myData. What if there are 10,000 elements in myData? That's 10,000 std::mutexes, not great.

2: Put a lock_guard around it like this:

std::mutex myMutex;

{
    const std::lock_guard<std::mutex> lock(myMutex);

    if (!myData[position])
      {
        bar(myData[position]);
      }
}

While this works, it also means if different threads are working in different positions, they wait needlessly, wasting all of the threading advantage.

3: Use a vector of chars and a spinlock as a poor man's mutex? Here's what that might look like:

static std::vector<char> positionInProgress;
static std::vector<char> positionComplete;

class myClass
{
  struct Data
  {
    int res1;
  };

  std::vector<Data*> myData;

  int foo(unsigned long position)
  {
    if (positionInProgress[position])
      {
        while (positionInProgress[position])
          {
            ;  // do nothing, just wait until it is done
          }
      }
    else
      {
        if (!positionComplete[position])
          {
            // Fill the data and prevent anyone from using it until it is complete
            positionInProgress[position] = true;
            bar(myData[position]);
            positionInProgress[position] = false;

            positionComplete[position] = true;
          }
      }

    // Do something with the data
    return 5 * myData[position]->res1;
  }

  void bar(Data* data)
  {
    data = new Data;

    // Do a whole bunch of calculations and so-on here

    data->res1 = 42;
  }
};

This seems to work, but none of the test or set operations are atomic, so I have a feeling I'm just getting lucky.

4: What about std::atomic and std::atomic_flag? Well, there are a few problems.

std::atomic_flag doesn't have a way to test without setting in C++11...which makes this kind of difficult.

std::atomic is not movable or copy-constructable, so I cannot make a vector of them (I do not know the number of positions during construction of myClass)

Conclusion:

This is the simplest example that (likely) compiles I can think of that demonstrates my real problem. In reality, myData is a 2-dimensional vector implemented using a special hand-rolled solution, Data itself is a vector of pointers to more complex data types, the data isn't simply returned, etc. This is the best I could come up with.

Body:
The biggest problem you're likely to have is that a vector itself is not thread-safe, so you can't do ANY operation that might chage the vector (invalidate references to elements of the vector) while another thread might be accessing it, such as resize or push_back.  However, if you vector is effectively "fixed" (you set the size prior to ever spawning threads and thereafter only ever access elements using at or operator[] and never ever modify the vector itself), you can get away with using a vector of atomic objects.  In this case you could have:

std::vector<std::atomic<Data*>> myData;

and your code to setup and use an element could look like:

if (!myData[position]) {
    Data *tmp = new Data;
    if (!mydata[position].compare_exchange_strong(nullptr, tmp)) {
        // some other thread did the setup
        delete tmp; } }
myData[position]->bar();

Of course you still need to make sure that the operations done on members of Data in bar are themselves threadsafe, as you can get mulitple threads calling bar on the same Data instance here.


答:
You can use the compound literal. Here you are.

```<code>#include <stdio.h>

struct RuntimeData
{
    double runtime_ms, sum_ms, avg_time_ms, best_time_ms;
};

int main(void)
{
    struct RuntimeData selection =
    {
        .runtime_ms=0,
        .sum_ms = 0,
        .avg_time_ms = 0,
        .best_time_ms = 0
    };

    {
        selection = ( struct RuntimeData )
        {
            .runtime_ms=1,
            .sum_ms = 1,
            .avg_time_ms = 1,
            .best_time_ms = 1
        };
    }

    printf( "%.1f, %.1f, %.1f, %.1f\n ",
            selection.runtime_ms,
            selection.sum_ms,
            selection.avg_time_ms,
            selection.best_time_ms );

    return 0;
}
</code>```

The program output is

```<code>1.0, 1.0, 1.0, 1.0
</code>```

Of course you can simplify the compound literal the following way

```<code>selection = ( struct RuntimeData ) { 1, 1, 1, 1 };
</code>```

I enclosed the assignment in braces to make shorter the life-time of the compound literal.

Title: Is there a better way to change every variable in a struct, C

Body:
You can use the compound literal. Here you are.

#include <stdio.h>

struct RuntimeData
{
    double runtime_ms, sum_ms, avg_time_ms, best_time_ms;
};

int main(void)
{
    struct RuntimeData selection =
    {
        .runtime_ms=0,
        .sum_ms = 0,
        .avg_time_ms = 0,
        .best_time_ms = 0
    };

    {
        selection = ( struct RuntimeData )
        {
            .runtime_ms=1,
            .sum_ms = 1,
            .avg_time_ms = 1,
            .best_time_ms = 1
        };
    }

    printf( "%.1f, %.1f, %.1f, %.1f\n ",
            selection.runtime_ms,
            selection.sum_ms,
            selection.avg_time_ms,
            selection.best_time_ms );

    return 0;
}

The program output is

1.0, 1.0, 1.0, 1.0

Of course you can simplify the compound literal the following way

selection = ( struct RuntimeData ) { 1, 1, 1, 1 };

I enclosed the assignment in braces to make shorter the life-time of the compound literal.


问:
mvn command returns: [ERROR] The goal you specified requires a project to execute but there is no POM in this directory
Creating a project with archetype:generate in the same way as described in Maven in 5 Minutes.

Got this error:

```<code>[ERROR] The goal you specified requires a project to execute but there is no POM in this directory (/mnt/c/Users/etomort/quartz-poc). Please verify you invoked Maven from the correct directory. -> [Help 1]
org.apache.maven.lifecycle.MissingProjectException: The goal you specified requires a project to execute but there is no POM in this directory (/mnt/c/Users/etomort/quartz-poc). Please verify you invoked Maven from the correct directory.
</code>```

Since it is such a basic thing, I just got confused...

I checked these two questions:

Error “The goal you specified requires a project to execute but there is no POM in this directory” after executing maven command

maven generating pom file

But neither the accepted answers solved the issue.

So, I am creating this question in case someone hits it and do not get it at first.

By the way, the Maven command entered is:

```<code>mvn archetype:generate -DgroupId=com.mycompany -DartifactId=quartz-poc -DarchetypeArtifactId= maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false
</code>```

答:
Watch out for spaces in mvn command!

Any spaces before and after = makes mvn fail:

In my question, the extra space is in archetypeArtifactId.

Though wherever it is, Maven will complain with the same message.

I inadvertently introduced spaces with bash auto-completion capability:

Body:
Creating a project with archetype:generate in the same way as described in Maven in 5 Minutes.

Got this error:

[ERROR] The goal you specified requires a project to execute but there is no POM in this directory (/mnt/c/Users/etomort/quartz-poc). Please verify you invoked Maven from the correct directory. -> [Help 1]
org.apache.maven.lifecycle.MissingProjectException: The goal you specified requires a project to execute but there is no POM in this directory (/mnt/c/Users/etomort/quartz-poc). Please verify you invoked Maven from the correct directory.

Since it is such a basic thing, I just got confused...

I checked these two questions:

Error “The goal you specified requires a project to execute but there is no POM in this directory” after executing maven command

maven generating pom file

But neither the accepted answers solved the issue.

So, I am creating this question in case someone hits it and do not get it at first.

By the way, the Maven command entered is:

mvn archetype:generate -DgroupId=com.mycompany -DartifactId=quartz-poc -DarchetypeArtifactId= maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false