问:
Nodejs Dialogflow Detect intents don't do anything
I am trying to use the .detectIntent method with the @google-cloud/dialogflow module in JavaScript.
I created an agent in dialogflow, filled up some things in the Small Talk tab. Then I went to the console.cloud.google.com website, added the dialogflow API to my project (the project is the same as in the dialogflow website). I have my API keys in .json like many websites and tutorials says.

My javascript code look like this:

const CREDENTIALS = require('./service.js');
const PROJECTID = CREDENTIALS.project_id;
const CONFIGURATION = {
    credentials: {
        private_key: CREDENTIALS.private_key,
        client_email: CREDENTIALS.client_email
    }
};

const sessionClient = new dialogflow.SessionsClient(CONFIGURATION);

async function detectIntent(languageCode = 'en-US', queryText, sessionId) {
    let sessionPath = sessionClient.projectAgentSessionPath(PROJECTID, sessionId);

    let request = {
        session: sessionPath,
        queryInput: {
            text: {
                text: queryText,
                languageCode: languageCode,
            }
        }
    };

    const responses = await sessionClient.detectIntent(request, { maxResults: 1, maxRetries: 3 });
    console.log(responses)
    const result = responses[0].queryResult;
    console.log(result)

    return {
        response: result.fulfillmentText
    };
};
```
<p>My <code>service.js</code> file is the JSON with the API keys and look like this:</p>
<pre class="lang-js prettyprint-override"><code>module.exports = {
  "type": "service_account",
  "project_id": "autotask-gejf",
  "private_key_id": "XXXX",
  "private_key": "-----BEGIN PRIVATE KEY-----\nXXXXXXX\n-----END PRIVATE KEY-----\n",
  "client_email": "autotask@autotask-gejf.iam.gserviceaccount.com",
  "client_id": "xxxxxxxx",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/autotask%40autotask-gejf.iam.gserviceaccount.com"
}
</code>```

Every time I call the detectIntent function, it log nothing after the await sessionClient.detectIntent. I searched in the cloud console and in the dialogflow  metrics I have 100% errors...

Can someone help me?

EDIT: I found out in the dialogflow website that it is a "Permission denied" error but I still don't know how to resolve this...

Body:
I am trying to use the .detectIntent method with the @google-cloud/dialogflow module in JavaScript.
I created an agent in dialogflow, filled up some things in the Small Talk tab. Then I went to the console.cloud.google.com website, added the dialogflow API to my project (the project is the same as in the dialogflow website). I have my API keys in .json like many websites and tutorials says.

My javascript code look like this:

const CREDENTIALS = require('./service.js');
const PROJECTID = CREDENTIALS.project_id;
const CONFIGURATION = {
    credentials: {
        private_key: CREDENTIALS.private_key,
        client_email: CREDENTIALS.client_email
    }
};

const sessionClient = new dialogflow.SessionsClient(CONFIGURATION);

async function detectIntent(languageCode = 'en-US', queryText, sessionId) {
    let sessionPath = sessionClient.projectAgentSessionPath(PROJECTID, sessionId);

    let request = {
        session: sessionPath,
        queryInput: {
            text: {
                text: queryText,
                languageCode: languageCode,
            }
        }
    };

    const responses = await sessionClient.detectIntent(request, { maxResults: 1, maxRetries: 3 });
    console.log(responses)
    const result = responses[0].queryResult;
    console.log(result)

    return {
        response: result.fulfillmentText
    };
};

My service.js file is the JSON with the API keys and look like this:

module.exports = {
  "type": "service_account",
  "project_id": "autotask-gejf",
  "private_key_id": "XXXX",
  "private_key": "-----BEGIN PRIVATE KEY-----\nXXXXXXX\n-----END PRIVATE KEY-----\n",
  "client_email": "autotask@autotask-gejf.iam.gserviceaccount.com",
  "client_id": "xxxxxxxx",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/autotask%40autotask-gejf.iam.gserviceaccount.com"
}

Every time I call the detectIntent function, it log nothing after the await sessionClient.detectIntent. I searched in the cloud console and in the dialogflow  metrics I have 100% errors...

Can someone help me?

EDIT: I found out in the dialogflow website that it is a "Permission denied" error but I still don't know how to resolve this...


来源: stackexchange

问:
Understanding state update in React
New to React. I have a NewItem component that should be pretty simple (and I have managed to do similar stuff before without problems): it has a form with two input text fields and it should update a stateful object (I think that's what it's called) when the form is submitted. Yet the state is updated only the second time the user submit the form. Why is that and how can I fix this? (Again, I am aware it's probably a very silly thing to ask, but I have done similar stuff with arrays and thought I got it).

Thank you for your patience and help.
Here's the component:

```<code>import { useState } from "react";
const NewItem = () => {
  const [newName, setNewName] = useState("");
  const [newType, setNewType] = useState("");
  const [newItem, setNewItem] = useState({ name: "", type: "" });

  const getNewName = (event) => {
    const changedName = event.target.value;
    setNewName(changedName);
  };

  const getNewType = (event) => {
    const changedType = event.target.value;
    setNewType(changedType);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    const toAdd = { ...newItem, name: newName, type: newType };
    setNewItem(toAdd);
    console.log(toAdd);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name
        <input type="text" value={newName} onChange={getNewName} />
      </label>
      <label>
        Type
        <input type="text" value={newType} onChange={getNewType} />
      </label>
      <button type="submit">Add</button>
    </form>
  );
};

export default NewItem;
</code>```

ContentLicense: CC BY-SA 4.0

Title: Understanding state update in React

Body:
New to React. I have a NewItem component that should be pretty simple (and I have managed to do similar stuff before without problems): it has a form with two input text fields and it should update a stateful object (I think that's what it's called) when the form is submitted. Yet the state is updated only the second time the user submit the form. Why is that and how can I fix this? (Again, I am aware it's probably a very silly thing to ask, but I have done similar stuff with arrays and thought I got it).

Thank you for your patience and help.
Here's the component:

import { useState } from "react";
const NewItem = () => {
  const [newName, setNewName] = useState("");
  const [newType, setNewType] = useState("");
  const [newItem, setNewItem] = useState({ name: "", type: "" });

  const getNewName = (event) => {
    const changedName = event.target.value;
    setNewName(changedName);
  };

  const getNewType = (event) => {
    const changedType = event.target.value;
    setNewType(changedType);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    const toAdd = { ...newItem, name: newName, type: newType };
    setNewItem(toAdd);
    console.log(toAdd);
  };

  return (
    <form onSubmit={handleSubmit}>

        Name
        <input type="text" value={newName} onChange={getNewName} />

        Type
        <input type="text" value={newType} onChange={getNewType} />

      <button type="submit">Add</button>
    </form>
  );
};

export default NewItem;


问:
How to hide env variables in _app file in Next Js
In the rest of the pages, I accessed env variables using getServerSideProps, but this is not supported in _app. How can I use env variables and remain secret in the client side?</p>


问:
An unknown error occurred when fetching the script
I have "Load Unpack"ed my client-side + server-side(node.js) extension, and I get this error on the service worker.

In this thread the solution regards to chrome certificate, so i checked my certificate in chrome and it is outdated, but I'm not sure if it's relevant to my case. In the chrome documentation, no certificates are mentioned as a requirement.

Here's my service worker ("type": "module"):

```<code>import PythonShell from './node_modules/python-shell';
import express from './node_modules/@types/express';

const app = express();

app.use(express.static('public'));
app.use(express.json({limit: '1mb'}))

app.post('/api', (request, response)=>{
...
)}
PythonShell.run(...
{
});

});

</code>```

Body:
I have "Load Unpack"ed my client-side + server-side(node.js) extension, and I get this error on the service worker.

In this thread the solution regards to chrome certificate, so i checked my certificate in chrome and it is outdated, but I'm not sure if it's relevant to my case. In the chrome documentation, no certificates are mentioned as a requirement.

Here's my service worker ("type": "module"):

import PythonShell from './node_modules/python-shell';
import express from './node_modules/@types/express';

const app = express();

app.use(express.static('public'));
app.use(express.json({limit: '1mb'}))

app.post('/api', (request, response)=>{
...
)}
PythonShell.run(...
{
});

});


问:
Windows Forms Animation with 3 radio buttons for 3 different gifs question
```<code>Public Class Form1

    Dim Frame As Integer
    Dim bedLocation As Point

    Private Sub bedBtn_CheckedChanged(sender As Object, e As EventArgs) Handles bedBtn.CheckedChanged

        Timer1.Start()
        Frame = 0
        bedLocation.X = 140
        bedLocation.Y = 12
        picbed.Location = bedLocation
        picbed.Visible = True

    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

        Dim ResourceName As String
        ResourceName = Frame.ToString
        picbed.Image = My.Resources.ResourceManager.GetObject(ResourceName)

        picbed.Location = bedLocation

        Frame = Frame + 1
        If Frame > 7 Then
            Frame = 0
        End If

    End Sub

    Private Sub TripBtn_CheckedChanged(sender As Object, e As EventArgs) Handles TripBtn.CheckedChanged

        Frame = 10
        bedLocation.X = 140
        bedLocation.Y = 12

        Dim ResourceName As String
        ResourceName = Frame.ToString
        picbed.Image = My.Resources.ResourceManager.GetObject(ResourceName)

        Frame = Frame + 1
        If Frame > 17 Then
            Frame = 10
        End If

    End Sub
End Class
</code>```

The app starts find, but when the tripbtn is pushed a glimpse of the image pops up, but it still shows the timer image that automatically starts up. How can I override it to shows the Frames 10-17. I coded it in the button as the start frame to be 10 and the end frame to be 17 but its not showing.

Am I suppose to have a separate timer for the 2nd gif?

Body:
Public Class Form1

    Dim Frame As Integer
    Dim bedLocation As Point

    Private Sub bedBtn_CheckedChanged(sender As Object, e As EventArgs) Handles bedBtn.CheckedChanged

        Timer1.Start()
        Frame = 0
        bedLocation.X = 140
        bedLocation.Y = 12
        picbed.Location = bedLocation
        picbed.Visible = True

    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

        Dim ResourceName As String
        ResourceName = Frame.ToString
        picbed.Image = My.Resources.ResourceManager.GetObject(ResourceName)

        picbed.Location = bedLocation

        Frame = Frame + 1
        If Frame > 7 Then
            Frame = 0
        End If

    End Sub

    Private Sub TripBtn_CheckedChanged(sender As Object, e As EventArgs) Handles TripBtn.CheckedChanged

        Frame = 10
        bedLocation.X = 140
        bedLocation.Y = 12

        Dim ResourceName As String
        ResourceName = Frame.ToString
        picbed.Image = My.Resources.ResourceManager.GetObject(ResourceName)

        Frame = Frame + 1
        If Frame > 17 Then
            Frame = 10
        End If

    End Sub
End Class

The app starts find, but when the tripbtn is pushed a glimpse of the image pops up, but it still shows the timer image that automatically starts up. How can I override it to shows the Frames 10-17. I coded it in the button as the start frame to be 10 and the end frame to be 17 but its not showing.

Am I suppose to have a separate timer for the 2nd gif?


问:
I have multiple .rmd files in a folder. How can I combine them up in a single .rmd file?
I have multiple .rmd files(R Markdown) in a folder. I want to combine them in a single .rmd file.

I need a program that targets one folder --> picks all .rmd files --> combine them into one with a new name.


问:
How can I determine a public YouTube channel's username
The YouTube Data API allows us to query data about a channel using the channel id or the channel username.

I thought that a channel's username would be its "@handle" as listed below the channel title and (commonly) in the channel URL. But 3Blue1Brown is a clear counterexample to this.

from googleapiclient.discovery import build

# Instantiate a googleapiclient.discovery.Resource object for youtube
youtube = build(
  serviceName='youtube',
  version='v3',
  developerKey='MYKEY'
)

# Define the request
request = youtube.channels().list(
  part="contentDetails",
  forUsername="3blue1brown"
)

# Execute the request and save the response
response = request.execute()

response
# {'kind': 'youtube#channelListResponse',
#  'etag': 'RuuXzTIr0OoDqI4S0RU6n4FqKEM',
#  'pageInfo': {'totalResults': 0, 'resultsPerPage': 5}}
```

I know I can just use the channel's id instead, but the id is becoming harder to find and frankly, it just bothers me that I don't know how to find a channel's username.

Body:
The YouTube Data API allows us to query data about a channel using the channel id or the channel username.

I thought that a channel's username would be its "@handle" as listed below the channel title and (commonly) in the channel URL. But 3Blue1Brown is a clear counterexample to this.

from googleapiclient.discovery import build

# Instantiate a googleapiclient.discovery.Resource object for youtube
youtube = build(
  serviceName='youtube',
  version='v3',
  developerKey='MYKEY'
)

# Define the request
request = youtube.channels().list(
  part="contentDetails",
  forUsername="3blue1brown"
)

# Execute the request and save the response
response = request.execute()

response
# {'kind': 'youtube#channelListResponse',
#  'etag': 'RuuXzTIr0OoDqI4S0RU6n4FqKEM',
#  'pageInfo': {'totalResults': 0, 'resultsPerPage': 5}}

I know I can just use the channel's id instead, but the id is becoming harder to find and frankly, it just bothers me that I don't know how to find a channel's username.


问:
Feature testing in Laravel including Passport + policies
I already tested it with Postman, but I want to test within Laravel itself with feature tests.
I followed official docs and numerous post on SO too.

This my test for simple endpoint, where beside url, it get passed two parameters. Nothing fancy.
Every endpoint also has passport middleware on it.
And result is array with objects of which some of them have subobjects.

```<code>
public function test_list_vehicles()
    {
        //Simulation of data entered by user.
        $request = [
            "type" => "truck",
            "workOrg" => "alpha"
        ];

        //Simulation of passing on token.
        Passport::actingAs(
            factory(User::class)->create(),
            ["http://secrep.test/api/list_vehicles"]
        );

        //Simulation of post method via ajax request and checking if retuned result have proper json structure.
        $response = $this->post("http://secrep.test/api/list_vehicles", $request, ["X-Requested-With" => "XMLHttpRequest"]/*Test if request is ajax*/)
        ->assertJsonStructure([
            "message",
            "vehicles" => [
                [
                    "id",
                    "registration",
                    "sec_id",
                    "created_at",
                    "updated_at",
                    "vehicle_type_id",
                    "workOrganization_id",
                    "special_permission_id",
                    "deleted_at",
                    "work_organization" => [
                        "id",
                        "name",
                        "sec_id",
                        "created_at",
                        "updated_at",
                        "deleted_at"
                    ],
                    "type" => [
                        "id",
                        "name",
                        "created_at",
                        "updated_at",
                        "deleted_at"
                    ]
                ]
            ]
        ]);// A "message"(just string) is my personal way of aknowledging if correct results are returned.

        $response->assertStatus(200);

    }

</code>```

Test is passed.

I am not sure how to test expected results apart of what i already said regarding "message".
This is expecting result:

```<code>"vehicles": [
    {
        "id": 9,
        "registration": "kamaz",
        "sec_id": 41,
        "created_at": "2022-03-17T17:21:36.000000Z",
        "updated_at": "2022-03-17T17:21:36.000000Z",
        "vehicle_type_id": 1,
        "workOrganization_id": 1,
        "special_permission_id": null,
        "deleted_at": null,
        "work_organization": {
            "id": 1,
            "name": "Alpha",
            "sec_id": 41,
            "created_at": "2021-07-17T17:19:25.000000Z",
            "updated_at": "2022-04-02T00:33:58.000000Z",
            "deleted_at": null
        },
        "type": {
            "id": 1,
            "name": "truck",
            "created_at": "2021-07-17T17:18:41.000000Z",
            "updated_at": "2021-07-17T17:18:41.000000Z",
            "deleted_at": null
        }
    }
]
</code>```

This would be array of objects with subobjects, which i for simplicity sake, presented just one.
My questions are:

<s>How to test if request is ajax</s>

<s>If its correct method i.e. "Post"</s>

<s>How to test resulting json</s>

Reminder: Test as it is, passes. Postman also returns expected results. How to go in said "depth"?

Edit1:

I'm guessing, i solved it? If it's correct way of doing it, that is.

Edit2:
Above stuff have been resolved.

How to account for policy in controller during this test?

Edit3:

Policy just check if user is admin.

```<code>return ($user->role->name=="admin") ? Response::allow() : Response::deny('Access denied.');
</code>```

Example of said error:

Edit4:

Solved it.
Instead this piece of code

```<code>
    Passport::actingAs(
       factory(User::class)->create(),
       ["http://secrep.test/api/create_vehicle"]
    );

</code>```

this:

```<code>
    Passport::actingAs(
        factory(User::class)->create(["role_id" => 1]),
        ["http://secrep.test/api/create_vehicle"]
    );

</code>```

Ha, the more you know...

Body:
I already tested it with Postman, but I want to test within Laravel itself with feature tests.
I followed official docs and numerous post on SO too.

This my test for simple endpoint, where beside url, it get passed two parameters. Nothing fancy.
Every endpoint also has passport middleware on it.
And result is array with objects of which some of them have subobjects.

public function test_list_vehicles()
    {
        //Simulation of data entered by user.
        $request = [
            "type" => "truck",
            "workOrg" => "alpha"
        ];

        //Simulation of passing on token.
        Passport::actingAs(
            factory(User::class)->create(),
            ["http://secrep.test/api/list_vehicles"]
        );

        //Simulation of post method via ajax request and checking if retuned result have proper json structure.
        $response = $this->post("http://secrep.test/api/list_vehicles", $request, ["X-Requested-With" => "XMLHttpRequest"]/*Test if request is ajax*/)
        ->assertJsonStructure([
            "message",
            "vehicles" => [
                [
                    "id",
                    "registration",
                    "sec_id",
                    "created_at",
                    "updated_at",
                    "vehicle_type_id",
                    "workOrganization_id",
                    "special_permission_id",
                    "deleted_at",
                    "work_organization" => [
                        "id",
                        "name",
                        "sec_id",
                        "created_at",
                        "updated_at",
                        "deleted_at"
                    ],
                    "type" => [
                        "id",
                        "name",
                        "created_at",
                        "updated_at",
                        "deleted_at"
                    ]
                ]
            ]
        ]);// A "message"(just string) is my personal way of aknowledging if correct results are returned.

        $response->assertStatus(200);

    }

Test is passed.

I am not sure how to test expected results apart of what i already said regarding "message".
This is expecting result:

"vehicles": [
    {
        "id": 9,
        "registration": "kamaz",
        "sec_id": 41,
        "created_at": "2022-03-17T17:21:36.000000Z",
        "updated_at": "2022-03-17T17:21:36.000000Z",
        "vehicle_type_id": 1,
        "workOrganization_id": 1,
        "special_permission_id": null,
        "deleted_at": null,
        "work_organization": {
            "id": 1,
            "name": "Alpha",
            "sec_id": 41,
            "created_at": "2021-07-17T17:19:25.000000Z",
            "updated_at": "2022-04-02T00:33:58.000000Z",
            "deleted_at": null
        },
        "type": {
            "id": 1,
            "name": "truck",
            "created_at": "2021-07-17T17:18:41.000000Z",
            "updated_at": "2021-07-17T17:18:41.000000Z",
            "deleted_at": null
        }
    }
]

This would be array of objects with subobjects, which i for simplicity sake, presented just one.
My questions are:

<s>How to test if request is ajax</s>

<s>If its correct method i.e. "Post"</s>

<s>How to test resulting json</s>

Reminder: Test as it is, passes. Postman also returns expected results. How to go in said "depth"?

Edit1:

I'm guessing, i solved it? If it's correct way of doing it, that is.

Edit2:
Above stuff have been resolved.

How to account for policy in controller during this test?

Edit3:

Policy just check if user is admin.

return ($user->role->name=="admin") ? Response::allow() : Response::deny('Access denied.');

Example of said error:

Edit4:

Solved it.
Instead this piece of code

    Passport::actingAs(
       factory(User::class)->create(),
       ["http://secrep.test/api/create_vehicle"]
    );

this:

    Passport::actingAs(
        factory(User::class)->create(["role_id" => 1]),
        ["http://secrep.test/api/create_vehicle"]
    );

Ha, the more you know...


问:
If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import
django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'questions.urls' from '/home/aliasqar/Django/Online-quiz/Quiz/questions/urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import.</p>
```<code>`
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [

    path('admin/', admin.site.urls),
    path('quiz/', include("questions.urls")),

]+ static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
`
</code>```

Body:
django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'questions.urls' from '/home/aliasqar/Django/Online-quiz/Quiz/questions/urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import.

`
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [

    path('admin/', admin.site.urls),
    path('quiz/', include("questions.urls")),

]+ static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
`


问:
DiscordPHP: setting channel-specific permissions to a Member
I have a Discord\Parts\Channel instance $channel, and a member instance, which i obtained via

```<code>React\Async\await($guild->members->fetch($memberId,true)->then(function ($member) use($channel){
 // mute $member on the channel
});
</code>```

Now, i am trying to "mute" the member on the channel, where for muting i mean

if it is a voice channel, the user would get muted on the channel

if it is a text channel, i would have to remove from the user the permission to write on the channel. (Leaving him the read permission)

This is the code i have tried, which fails on text channels (and i haven't tested yet on voice channels)

```<code>React\Async\await($guild->members->fetch($memberId,true)->then(function ($member) use($channel){
  if($channel->allowVoice()) $promise = $channel->muteMember($member); // this is a voice channel
  else $promise = $channel->setPermissions($member,[],ChannelPermission::TEXT_PERMISSIONS); // this is a text channel
  $promise->then(
        function($something){
                        echo "muted";
                        return "Muted";
        },
        function($rejectReason){
            echo "rejected";
            return "Could not mute specified user: " . $rejectReason->getMessage();
        });
});
</code>```

Now, when trying the above for a text channel, i see "muted" in the output log like it succeeded, but actually it had no effect. So i must have passed wrong values to $channel->setPermissions().

Now, the declaration of Channel::setPermission() in DiscordPhp is

```<code>public function setPermissions(Part $part, array $allow = [], array $deny = [], ?string $reason = null): ExtendedPromiseInterface
</code>```

The first param can be a Role or a Member, the second one seems to be the permissions i want to "unlock" (allow), and in this case no one, and the third param seems to be the permissions i want to deny.
I have passed ChannelPermission::TEXT_PERMISSIONS , which is defined in Discord\Parts\Permissions\Permission (parent of ChannelPermissions) as:

```<code>/**
     * Array of permissions that only apply to text channels.
     * i.e. indicated T in documentation.
     *
     * @var array
     */
    public const TEXT_PERMISSIONS = [
        'add_reactions' => 6,
        'send_messages' => 11,
        'send_tts_messages' => 12,
        'manage_messages' => 13,
        'embed_links' => 14,
        'attach_files' => 15,
        'read_message_history' => 16,
        'use_external_emojis' => 18,
        'manage_webhooks' => 29,
        'use_application_commands' => 31,
        'manage_threads' => 34,
        'create_public_threads' => 35,
        'create_private_threads' => 36,
        'use_external_stickers' => 37,
        'send_messages_in_threads' => 38,
    ];
</code>```

I cannot figure out what's wrong, and if it was correct to pass that ChannelPermission::TEXT_PERMISSIONS to the third param (or anything else i am missing).
Anyone can help me?
Thank you

Body:
I have a Discord\Parts\Channel instance $channel, and a member instance, which i obtained via

React\Async\await($guild->members->fetch($memberId,true)->then(function ($member) use($channel){
 // mute $member on the channel
});

Now, i am trying to "mute" the member on the channel, where for muting i mean

if it is a voice channel, the user would get muted on the channel

if it is a text channel, i would have to remove from the user the permission to write on the channel. (Leaving him the read permission)

This is the code i have tried, which fails on text channels (and i haven't tested yet on voice channels)

React\Async\await($guild->members->fetch($memberId,true)->then(function ($member) use($channel){
  if($channel->allowVoice()) $promise = $channel->muteMember($member); // this is a voice channel
  else $promise = $channel->setPermissions($member,[],ChannelPermission::TEXT_PERMISSIONS); // this is a text channel
  $promise->then(
        function($something){
                        echo "muted";
                        return "Muted";
        },
        function($rejectReason){
            echo "rejected";
            return "Could not mute specified user: " . $rejectReason->getMessage();
        });
});

Now, when trying the above for a text channel, i see "muted" in the output log like it succeeded, but actually it had no effect. So i must have passed wrong values to $channel->setPermissions().

Now, the declaration of Channel::setPermission() in DiscordPhp is

public function setPermissions(Part $part, array $allow = [], array $deny = [], ?string $reason = null): ExtendedPromiseInterface

The first param can be a Role or a Member, the second one seems to be the permissions i want to "unlock" (allow), and in this case no one, and the third param seems to be the permissions i want to deny.
I have passed ChannelPermission::TEXT_PERMISSIONS , which is defined in Discord\Parts\Permissions\Permission (parent of ChannelPermissions) as:

/**
     * Array of permissions that only apply to text channels.
     * i.e. indicated T in documentation.
     *
     * @var array
     */
    public const TEXT_PERMISSIONS = [
        'add_reactions' => 6,
        'send_messages' => 11,
        'send_tts_messages' => 12,
        'manage_messages' => 13,
        'embed_links' => 14,
        'attach_files' => 15,
        'read_message_history' => 16,
        'use_external_emojis' => 18,
        'manage_webhooks' => 29,
        'use_application_commands' => 31,
        'manage_threads' => 34,
        'create_public_threads' => 35,
        'create_private_threads' => 36,
        'use_external_stickers' => 37,
        'send_messages_in_threads' => 38,
    ];

I cannot figure out what's wrong, and if it was correct to pass that ChannelPermission::TEXT_PERMISSIONS to the third param (or anything else i am missing).
Anyone can help me?
Thank you


问:
How can I use the keyboard arrows to navigate in my menu with JNativeHook?
I want to be able to navigate through my menu with the arrows and I don't know how to apply it on my program.

I have a simple menu

```<code>private static String[] options = {"1- Plus 1",
            "2- Minus 1",
            "3- Exit",
    };

        public void printMenu(){
            for (String option : options){
                System.out.println(option);
            }
            System.out.print("Choose an option : ");
        }

        public void main(String[] args) {

            int option = 1;
            int a = 0;
            Scanner scan = new Scanner(System.in);

            while (option != options.length=){
                printMenu();
                try {
                    option = scan.nextInt();
                    switch (option){
                        case 1: a++; break;
                        case 2: a--; break;
                        case 3: exit(0);
                    }
                }
                catch (Exception ex){
                    System.out.println("Input a number between 1 and  " + options.length);
                    scan.next();
                }
            }
        }
</code>```

and have a Class for the JNativeHook with the keys i want to use (UP, DOWN and ENTER) and I want to be able to move through the options up and down and use the Enter to select the one I want. The problem is that I don't have any idea how to do it, is there any way to do it?
PS: Here is my JNativeHook class:

```<code>
public class GlobalKeyListenerExample implements NativeKeyListener {

    public void nativeKeyPressed(NativeKeyEvent e) {
        System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));

        switch(e.getKeyCode()) {
        case NativeKeyEvent.VC_UP:
            try {
                GlobalScreen.registerNativeHook();
            }
            catch (NativeHookException ex) {
                System.err.println("There was a problem registering the native hook.");
                System.err.println(ex.getMessage());

                System.exit(1);
            }
        case NativeKeyEvent.VC_DOWN:
            try {
                GlobalScreen.registerNativeHook();
            }
            catch (NativeHookException ex) {
                System.err.println("There was a problem registering the native hook.");
                System.err.println(ex.getMessage());

                System.exit(1);
            }
        case NativeKeyEvent.VC_ENTER:
            try {
                GlobalScreen.registerNativeHook();
            }
            catch (NativeHookException ex) {
                System.err.println("There was a problem registering the native hook.");
                System.err.println(ex.getMessage());

                System.exit(1);
            }
        }
    }

    public void nativeKeyReleased(NativeKeyEvent e) {
        System.out.println("Key Released: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
    }

    public void nativeKeyTyped(NativeKeyEvent e) {
        System.out.println("Key Typed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
    }

}
</code>```

Body:
I want to be able to navigate through my menu with the arrows and I don't know how to apply it on my program.

I have a simple menu

private static String[] options = {"1- Plus 1",
            "2- Minus 1",
            "3- Exit",
    };

        public void printMenu(){
            for (String option : options){
                System.out.println(option);
            }
            System.out.print("Choose an option : ");
        }

        public void main(String[] args) {

            int option = 1;
            int a = 0;
            Scanner scan = new Scanner(System.in);

            while (option != options.length=){
                printMenu();
                try {
                    option = scan.nextInt();
                    switch (option){
                        case 1: a++; break;
                        case 2: a--; break;
                        case 3: exit(0);
                    }
                }
                catch (Exception ex){
                    System.out.println("Input a number between 1 and  " + options.length);
                    scan.next();
                }
            }
        }

and have a Class for the JNativeHook with the keys i want to use (UP, DOWN and ENTER) and I want to be able to move through the options up and down and use the Enter to select the one I want. The problem is that I don't have any idea how to do it, is there any way to do it?
PS: Here is my JNativeHook class:

public class GlobalKeyListenerExample implements NativeKeyListener {

    public void nativeKeyPressed(NativeKeyEvent e) {
        System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));

        switch(e.getKeyCode()) {
        case NativeKeyEvent.VC_UP:
            try {
                GlobalScreen.registerNativeHook();
            }
            catch (NativeHookException ex) {
                System.err.println("There was a problem registering the native hook.");
                System.err.println(ex.getMessage());

                System.exit(1);
            }
        case NativeKeyEvent.VC_DOWN:
            try {
                GlobalScreen.registerNativeHook();
            }
            catch (NativeHookException ex) {
                System.err.println("There was a problem registering the native hook.");
                System.err.println(ex.getMessage());

                System.exit(1);
            }
        case NativeKeyEvent.VC_ENTER:
            try {
                GlobalScreen.registerNativeHook();
            }
            catch (NativeHookException ex) {
                System.err.println("There was a problem registering the native hook.");
                System.err.println(ex.getMessage());

                System.exit(1);
            }
        }
    }

    public void nativeKeyReleased(NativeKeyEvent e) {
        System.out.println("Key Released: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
    }

    public void nativeKeyTyped(NativeKeyEvent e) {
        System.out.println("Key Typed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
    }

}


问:
How can I run a Selenium app with Chromedriver and Headless Chrome on Github Actions?
Context

I've created a python app that uses selenium, chromedriver & chrome to automate actions on a website (roughly similar to the one here: https://yasoob.me/posts/web-automation-with-selenium/) . I'd like to run it on a schedule (e.g. every saturday at 9am) so, as the author suggested, I put it on Github Actions. I realize that for this to work I need to install Chromedriver & Chrome Headless as part of the Github Actions workflow.

My yml file looks like this:

```<code>name: Book

on:
  schedule:
    - cron: "0 4 * * *"
  workflow_dispatch:

env:
  ACTIONS_ALLOW_UNSECURE_COMMANDS: true

jobs:
  scrape-latest:
    runs-on: ubuntu-latest
    services:
      selenium:
        image: selenium/standalone-chrome

    steps:
      - name: Checkout repo
        uses: actions/checkout@v2
      - name: Set up Python
        uses: actions/setup-python@v2.0.0
        with:
          python-version: '3.7'
      - name: Install requirements
        run: pip install -r requirements.txt

      - name: Prepare Selenium
      # https://github.com/marketplace/actions/setup-chromedriver
        uses: nanasess/setup-chromedriver@master

      - name: Run Booker
        run: python app.py
</code>```

Issue

I get the following error message:

```<code>Run python app.py
Traceback (most recent call last):
  File "app.py", line 19, in <module>
    browser = webdriver.Chrome()
  File "/opt/hostedtoolcache/Python/3.7.15/x64/lib/python3.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 81, in __init__
    desired_capabilities=desired_capabilities)
  File "/opt/hostedtoolcache/Python/3.7.15/x64/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__
    self.start_session(capabilities, browser_profile)
  File "/opt/hostedtoolcache/Python/3.7.15/x64/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "/opt/hostedtoolcache/Python/3.7.15/x64/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/opt/hostedtoolcache/Python/3.7.15/x64/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)

Error: Process completed with exit code 1.
</code>```

What I've tried

I've tried different versions of this, where I put chromedrive as a binary in the requirements.txt, or try to install it through the app.py file, but it seems like putting it in the workflow file is the most reasonable place to start.

My Ask

Conceptually: I've never really done anything like this before so I'm having a hard time understanding the logic of what I'm doing - I guess Github Actions runs an Ubuntu server, where each time I run the action, I need to install Chrome (in headless mode) and Chromedriver, so that I can then run the automation that's in app.py. Is that more or less correct?

Tactically: What am I doing wrong in the code above?

Thank you!

Body:
Context

I've created a python app that uses selenium, chromedriver & chrome to automate actions on a website (roughly similar to the one here: https://yasoob.me/posts/web-automation-with-selenium/) . I'd like to run it on a schedule (e.g. every saturday at 9am) so, as the author suggested, I put it on Github Actions. I realize that for this to work I need to install Chromedriver & Chrome Headless as part of the Github Actions workflow.

My yml file looks like this:

name: Book

on:
  schedule:
    - cron: "0 4 * * *"
  workflow_dispatch:

env:
  ACTIONS_ALLOW_UNSECURE_COMMANDS: true

jobs:
  scrape-latest:
    runs-on: ubuntu-latest
    services:
      selenium:
        image: selenium/standalone-chrome

    steps:
      - name: Checkout repo
        uses: actions/checkout@v2
      - name: Set up Python
        uses: actions/setup-python@v2.0.0
        with:
          python-version: '3.7'
      - name: Install requirements
        run: pip install -r requirements.txt

      - name: Prepare Selenium
      # https://github.com/marketplace/actions/setup-chromedriver
        uses: nanasess/setup-chromedriver@master

      - name: Run Booker
        run: python app.py

Issue

I get the following error message:

Run python app.py
Traceback (most recent call last):
  File "app.py", line 19, in <module>
    browser = webdriver.Chrome()
  File "/opt/hostedtoolcache/Python/3.7.15/x64/lib/python3.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 81, in __init__
    desired_capabilities=desired_capabilities)
  File "/opt/hostedtoolcache/Python/3.7.15/x64/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__
    self.start_session(capabilities, browser_profile)
  File "/opt/hostedtoolcache/Python/3.7.15/x64/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "/opt/hostedtoolcache/Python/3.7.15/x64/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/opt/hostedtoolcache/Python/3.7.15/x64/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)

Error: Process completed with exit code 1.

What I've tried

I've tried different versions of this, where I put chromedrive as a binary in the requirements.txt, or try to install it through the app.py file, but it seems like putting it in the workflow file is the most reasonable place to start.

My Ask

Conceptually: I've never really done anything like this before so I'm having a hard time understanding the logic of what I'm doing - I guess Github Actions runs an Ubuntu server, where each time I run the action, I need to install Chrome (in headless mode) and Chromedriver, so that I can then run the automation that's in app.py. Is that more or less correct?

Tactically: What am I doing wrong in the code above?

Thank you!


问:
What's a good structure for storing data during traversing of a parse tree? It's for a language server protocol implementation
I'm implementing the language server protocol for a C++ testing framework, using Python3. I use ANTLR4 to parse the text file, and I have a working parser and I use the Listener pattern to traverse the results.

But what's the best way to store the data to easily query the structure? In The features I'm looking to implement typically the input to the server is a file name and line number, and the return value is another file and line. I.e something like go-to definition.

For each given rule I understand I have to save the relevant date. For example in an Listener function like enterFunctionDefition() I could save the function name, context, line number. I imagine this could be saved a simple JSON or XML tree or even an AST (abstract syntax tree). And then search that structure for items containing the desired filename and line number.

There has to be some kind of example out there how to do this, right? I've been googling alot but I just can't seem to find the instructions, but I might be misunderstanding some concept.

Thanks in advance.


问:
Android media player not playing from url
When I open the link on the web I can listen to the streaming but the Stream never loads on the phone but on the web it plays

Permissions:

```<code> <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
</code>```

My code:

```<code>String url = "http://n13.radiojar.com/5705c71sn2zuv?rj-ttl=5&rj-tok=AAABhPz0EysAQfb4iRmp2q_BTQ";

 mediaPlayer = new MediaPlayer();
           // mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setAudioAttributes(new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build());
            mediaPlayer.setDataSource(url);
            // prepare async to not block main thread
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(player -> {
                 player.start();
                });

</code>```

Body:
When I open the link on the web I can listen to the streaming but the Stream never loads on the phone but on the web it plays

Permissions:

 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

My code:

String url = "http://n13.radiojar.com/5705c71sn2zuv?rj-ttl=5&rj-tok=AAABhPz0EysAQfb4iRmp2q_BTQ";

 mediaPlayer = new MediaPlayer();
           // mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setAudioAttributes(new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build());
            mediaPlayer.setDataSource(url);
            // prepare async to not block main thread
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(player -> {
                 player.start();
                });


问:
Why is Jupyter Note using '/' symbol?
Running Jupyter notebook from Anaconda

I've used Jupyter notebook before, but it was the actual app not through Anaconda. Why is the '/' symbol showing? And how can I prevent it from showing? Is this a version issue?

I loaded an old project I was working. And this is how it looked before I re-ran it. Once I ran it, it looked like the previous screenshot. Jupyter Notebook with Pandas Module when ran on actual Jupyter notebook

Title: Why is Jupyter Note using '/' symbol?


问:
Problem returning response from POST request with Axios in Node.js
I am writing a simple post request in a Firebase Cloud function, with Axios. This function calls an API endpoint and gets an object of profile details as response. My problem is to correctly return the response to the client.

In the code below, the Cloud Function logs the result correctly. But I can't figure out how to correctly return it to the client from the client-side callGetProfile() function. (Which runs inside a Vue3 method.)

I am probably missing something obvious but am very new to Node.js and HTPP requests.

Thanks for any help!

```<code>// MY FUNCTION IN NODE.JS (Firebase Cloud Functions)
exports.getProfile = functions.https.onCall((data, context) => {

  var postData = {
    profile_id: "xxxxxxxxxxxxxxxxx", //hardcoded here for testing but should be passed in "data" arg.
    profile_type: "personal",
  };

  let axiosConfig = {
    headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',
        'X-API-KEY': 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    }
  };

  axios.post('xxxxxxxxxxxxxxxxxxxxxxxxxxxxx', postData, axiosConfig)
  .then((res) => {
    console.log(res.data) // this works, I get all the data correctly!!
    return res // also tried res.data
  })
  .catch((err) => {
    console.log("AXIOS ERROR: ", err);
  })

});
</code>```
```<code>// MY FUNCTION CLIENT SIDE (Vue3 method)
  const functions = getFunctions();
      const callGetProfile() = httpsCallable(functions, "getProfile");
      callGetProfile()
        .then((result) => {
          console.log(result.data) // this doesn't work, data is "null"
        })
        .catch((e) => console.log(e));
</code>```

Body:
I am writing a simple post request in a Firebase Cloud function, with Axios. This function calls an API endpoint and gets an object of profile details as response. My problem is to correctly return the response to the client.

In the code below, the Cloud Function logs the result correctly. But I can't figure out how to correctly return it to the client from the client-side callGetProfile() function. (Which runs inside a Vue3 method.)

I am probably missing something obvious but am very new to Node.js and HTPP requests.

Thanks for any help!

// MY FUNCTION IN NODE.JS (Firebase Cloud Functions)
exports.getProfile = functions.https.onCall((data, context) => {

  var postData = {
    profile_id: "xxxxxxxxxxxxxxxxx", //hardcoded here for testing but should be passed in "data" arg.
    profile_type: "personal",
  };

  let axiosConfig = {
    headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',
        'X-API-KEY': 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    }
  };

  axios.post('xxxxxxxxxxxxxxxxxxxxxxxxxxxxx', postData, axiosConfig)
  .then((res) => {
    console.log(res.data) // this works, I get all the data correctly!!
    return res // also tried res.data
  })
  .catch((err) => {
    console.log("AXIOS ERROR: ", err);
  })

});

// MY FUNCTION CLIENT SIDE (Vue3 method)
  const functions = getFunctions();
      const callGetProfile() = httpsCallable(functions, "getProfile");
      callGetProfile()
        .then((result) => {
          console.log(result.data) // this doesn't work, data is "null"
        })
        .catch((e) => console.log(e));


问:
Memory access violations when trying to read from structs inside of other structs
I am having trouble figuring out how to do this correctly. I have a linked list of nodes then those nodes have pointers put into an array contained in that node. These nodes make up a sort of one-way graph between the nodes. I must then traverse the nodes randomly until the node "Home" is reached.

The main issue I'm having is assigning the graph nodes into the list nodes. I want the function to take in the head of the list, the names of the nodes and the weight (cost to travel between nodes). I'm not sure how to do this correctly and I don't know what I did but I think there's an infinite loop somehow. Any help is greatly appreciated.

The input file is structured as such:

```<code>Applebees
GroundRound
BlueMoose
DrunkenNoodle
Home
STOP
Applebees BlueMoose 10
Applebees DrunkenNoodle 13
GroundRound Applebees 2
GroundRound DrunkenNoodle 7
GroundRound Home 52
STOP STOP 0
GroundRound

</code>```

Ignore the print statements in graphInsert() those are me trying to debug the loops.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

struct graphNode {
    char name[100]; // Establishment name
    int arcCnt; // Number of outgoing arc from this node
    int weights[10]; // Weights of each outgoing arc from this node
    struct graphNode* arcs[10]; // Holds other graph nodes that are connected to this node (this node is source)
};
struct listNode {
    char name[100]; // Establishment name
    struct listNode* next;
    struct graphNode* graph; // Pointer into graph
};

void listInsert(struct listNode **head, char name[100]) {

    // setup new nodes
    struct graphNode* newGraph = (struct graphNode*)malloc(sizeof(struct graphNode));
    for (int i = 0; i < 100; i++) {
        newGraph->name[i] = name[i];
    }
    for (int i = 0; i < 10; i++) {
        newGraph->arcs[i] = NULL;
    }
    newGraph->arcCnt = 0;

    struct listNode* newNode = (struct listNode*)malloc(sizeof(struct listNode));

    for (int i = 0; i < 100; i++) {
        newNode->name[i] = name[i];
    }
    newNode->next = NULL;
    newNode->graph = newGraph;

    // check if head is NULL
    if (*head == NULL) {
        *head = newNode;
        return;
    }

    // if the list is populated then add the node to the end
    struct listNode* current = *head;
    while (current->next != NULL) {
        current = current->next;
    }
    current->next = newNode;

}

void graphInsert(struct listNode** head, char src[100], char dst[100], int weight) {

    struct listNode* srcNode = *head;

    printf("CALL:");

    while (srcNode->next != NULL) { // loop through list to find src

        printf("%s %s", srcNode->name, src);
        if (strcmp(srcNode->name, src) == 0) {  // when it finds the name, find the dst  update the graph node data

            printf("FOUND");

            struct listNode* dstNode = *head;
            while (dstNode->next != NULL) { // this loop is to find the pointer to the dst node

                printf("    %s %s", dstNode->name, dst);
                if (strcmp(dstNode->name, src) == 0) { // when it finds name finally update all the info

                    printf("FOUND");
                    // assign the new arc to the right spot based on arcCnt (how many arcs there are), then return to exit the loops
                    srcNode->graph->arcs[srcNode->graph->arcCnt] = dstNode->graph;
                    srcNode->graph->weights[srcNode->graph->arcCnt] = weight;
                    srcNode->graph->arcCnt++;
                    return;
                }
                dstNode = dstNode->next;
            }
        }
        srcNode = srcNode->next;
    }
}

int main(){

    srand(2021);

    // setup variables
    struct listNode* head = NULL;
    struct graphNode* sourceNode = NULL;
    FILE* data = fopen("./hw10.data", "r");
    int i = 0;
    int section = 1; // flag to read the file correctly

    // this loop reads the file
    while (1) {
        char name[100];
        char name2[100];
        int weight = 0;
        if (section == 1) { // reads the first section

            fscanf(data, "%100s", name);
            if (strcmp(name, "STOP") == 0) { // if end of section then increment section counter
                section++;
            } else { // if its not the end of the section then add the name to the linked list
                listInsert(&head, name);
            }

        } else if (section == 2) { // reads the first section and builds the graph

            fscanf(data, "%100s %100s %d", name, name2, &weight);

            if (strcmp(name, "STOP") == 0) { // if end of section then increment section counter
                section++;
            } else {
                //graphInsert(&head, name, name2, weight);
            }

        } else if (section == 3) { // this section only reads one line and gets the

            char tmp[100];
            fscanf(data, "%100s", tmp);

            struct listNode* current = head;
            while (current->next != NULL) { // loop through to find the right node for the name

                if (strcmp(current->name, tmp) == 0) { // if names are equal update the node
                    sourceNode = current->graph;
                    break;
                }
                current = current->next;
            }

        }

        if (feof(data)) break;
        i++;
    }

    // debug print data
    printf("\n");
    struct listNode* current = head;
    while (current != NULL) {
        printf("%s\n", current->name);
        current = current->next;
    }
    printf("\n");

    // starting node
    printf("%s ", sourceNode->name);

    // now walk through the graph from sourceNode until we reach the node "Home"
    int totalWeight = 0;
    i = 0;
    while (i < 100) {
        char* tmp = sourceNode->name;
        if (strcmp(tmp, "Home") == 0) { // if were home then exit program

            // ending node and cost
            printf("%s %d", sourceNode->name, totalWeight);
            return 0;

        } else { // if were not home then keep looping

            int index = (rand() % sourceNode->arcCnt); // Generates random number between 0 and sourceNode->arcCnt
            sourceNode = sourceNode->arcs[index];
            //printf("Going to: %s, Index: %d", sourceNode->name, totalWeight);

        }
        i++;
    }

    return 0;
}
</code>```

Body:
I am having trouble figuring out how to do this correctly. I have a linked list of nodes then those nodes have pointers put into an array contained in that node. These nodes make up a sort of one-way graph between the nodes. I must then traverse the nodes randomly until the node "Home" is reached.

The main issue I'm having is assigning the graph nodes into the list nodes. I want the function to take in the head of the list, the names of the nodes and the weight (cost to travel between nodes). I'm not sure how to do this correctly and I don't know what I did but I think there's an infinite loop somehow. Any help is greatly appreciated.

The input file is structured as such:

Applebees
GroundRound
BlueMoose
DrunkenNoodle
Home
STOP
Applebees BlueMoose 10
Applebees DrunkenNoodle 13
GroundRound Applebees 2
GroundRound DrunkenNoodle 7
GroundRound Home 52
STOP STOP 0
GroundRound

Ignore the print statements in graphInsert() those are me trying to debug the loops.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

struct graphNode {
    char name[100]; // Establishment name
    int arcCnt; // Number of outgoing arc from this node
    int weights[10]; // Weights of each outgoing arc from this node
    struct graphNode* arcs[10]; // Holds other graph nodes that are connected to this node (this node is source)
};
struct listNode {
    char name[100]; // Establishment name
    struct listNode* next;
    struct graphNode* graph; // Pointer into graph
};

void listInsert(struct listNode **head, char name[100]) {

    // setup new nodes
    struct graphNode* newGraph = (struct graphNode*)malloc(sizeof(struct graphNode));
    for (int i = 0; i < 100; i++) {
        newGraph->name[i] = name[i];
    }
    for (int i = 0; i < 10; i++) {
        newGraph->arcs[i] = NULL;
    }
    newGraph->arcCnt = 0;

    struct listNode* newNode = (struct listNode*)malloc(sizeof(struct listNode));

    for (int i = 0; i < 100; i++) {
        newNode->name[i] = name[i];
    }
    newNode->next = NULL;
    newNode->graph = newGraph;

    // check if head is NULL
    if (*head == NULL) {
        *head = newNode;
        return;
    }

    // if the list is populated then add the node to the end
    struct listNode* current = *head;
    while (current->next != NULL) {
        current = current->next;
    }
    current->next = newNode;

}

void graphInsert(struct listNode** head, char src[100], char dst[100], int weight) {

    struct listNode* srcNode = *head;

    printf("CALL:");

    while (srcNode->next != NULL) { // loop through list to find src

        printf("%s %s", srcNode->name, src);
        if (strcmp(srcNode->name, src) == 0) {  // when it finds the name, find the dst  update the graph node data

            printf("FOUND");

            struct listNode* dstNode = *head;
            while (dstNode->next != NULL) { // this loop is to find the pointer to the dst node

                printf("    %s %s", dstNode->name, dst);
                if (strcmp(dstNode->name, src) == 0) { // when it finds name finally update all the info

                    printf("FOUND");
                    // assign the new arc to the right spot based on arcCnt (how many arcs there are), then return to exit the loops
                    srcNode->graph->arcs[srcNode->graph->arcCnt] = dstNode->graph;
                    srcNode->graph->weights[srcNode->graph->arcCnt] = weight;
                    srcNode->graph->arcCnt++;
                    return;
                }
                dstNode = dstNode->next;
            }
        }
        srcNode = srcNode->next;
    }
}

int main(){

    srand(2021);

    // setup variables
    struct listNode* head = NULL;
    struct graphNode* sourceNode = NULL;
    FILE* data = fopen("./hw10.data", "r");
    int i = 0;
    int section = 1; // flag to read the file correctly

    // this loop reads the file
    while (1) {
        char name[100];
        char name2[100];
        int weight = 0;
        if (section == 1) { // reads the first section

            fscanf(data, "%100s", name);
            if (strcmp(name, "STOP") == 0) { // if end of section then increment section counter
                section++;
            } else { // if its not the end of the section then add the name to the linked list
                listInsert(&head, name);
            }

        } else if (section == 2) { // reads the first section and builds the graph

            fscanf(data, "%100s %100s %d", name, name2, &weight);

            if (strcmp(name, "STOP") == 0) { // if end of section then increment section counter
                section++;
            } else {
                //graphInsert(&head, name, name2, weight);
            }

        } else if (section == 3) { // this section only reads one line and gets the

            char tmp[100];
            fscanf(data, "%100s", tmp);

            struct listNode* current = head;
            while (current->next != NULL) { // loop through to find the right node for the name

                if (strcmp(current->name, tmp) == 0) { // if names are equal update the node
                    sourceNode = current->graph;
                    break;
                }
                current = current->next;
            }

        }

        if (feof(data)) break;
        i++;
    }

    // debug print data
    printf("\n");
    struct listNode* current = head;
    while (current != NULL) {
        printf("%s\n", current->name);
        current = current->next;
    }
    printf("\n");

    // starting node
    printf("%s ", sourceNode->name);

    // now walk through the graph from sourceNode until we reach the node "Home"
    int totalWeight = 0;
    i = 0;
    while (i < 100) {
        char* tmp = sourceNode->name;
        if (strcmp(tmp, "Home") == 0) { // if were home then exit program

            // ending node and cost
            printf("%s %d", sourceNode->name, totalWeight);
            return 0;

        } else { // if were not home then keep looping

            int index = (rand() % sourceNode->arcCnt); // Generates random number between 0 and sourceNode->arcCnt
            sourceNode = sourceNode->arcs[index];
            //printf("Going to: %s, Index: %d", sourceNode->name, totalWeight);

        }
        i++;
    }

    return 0;
}


问:
How to get environment object in UIViewController?
I write SwiftUI module, but there is a feature that uses UIKit functionality. So in my SwiftUI view there is a UIViewRepresentable wrapper, that makes UIKit controller. In its turn it makes a collection view where view is SwiftUI view.

So I have a chain like this: View -> ViewRepresentable -> CollectionView -> View

And the problem is that I have @State variable in the first View, and I want to access and change it in the last view. How can I do it?

FirstView.swift

```<code>...

@ObservedObject var viewModel: ViewModel

struct FirstView: View {

    var body: some View {
        CollectionWrapper()
            .environmentObject(viewModel)
    }
}
...
</code>```

Wrapper.swift

```<code>...
struct CollectionWrapper: UIViewRepresentable {
    @EnvironmentObject var viewModel: Model

    func makeUIView(context: Context) -> CollectionView {
        CollectionView() // how I can pass the variable? DI is not actually working right.
    }

    func updateUIView(_ uiView: UITextView, context: Context) {
    }
}
...
</code>```

CollectionView.swift

```<code>...
class CollectionView: UICollectionView {
    ...

    func makeView() -> UIView {
        // Make hosting controller etc.
        hostingContoller.view = ModelView() // and here I somehow should pass my view model
    }
    ...
}
...
</code>```

I have already tried to do DI through the wrapper in makeUIView method, but my app is crashing because .environmentObject doesn't work in hosting controller for some reason.

Body:
I write SwiftUI module, but there is a feature that uses UIKit functionality. So in my SwiftUI view there is a UIViewRepresentable wrapper, that makes UIKit controller. In its turn it makes a collection view where view is SwiftUI view.

So I have a chain like this: View -> ViewRepresentable -> CollectionView -> View

And the problem is that I have @State variable in the first View, and I want to access and change it in the last view. How can I do it?

FirstView.swift

...

@ObservedObject var viewModel: ViewModel

struct FirstView: View {

    var body: some View {
        CollectionWrapper()
            .environmentObject(viewModel)
    }
}
...

Wrapper.swift

...
struct CollectionWrapper: UIViewRepresentable {
    @EnvironmentObject var viewModel: Model

    func makeUIView(context: Context) -> CollectionView {
        CollectionView() // how I can pass the variable? DI is not actually working right.
    }

    func updateUIView(_ uiView: UITextView, context: Context) {
    }
}
...

CollectionView.swift

...
class CollectionView: UICollectionView {
    ...

    func makeView() -> UIView {
        // Make hosting controller etc.
        hostingContoller.view = ModelView() // and here I somehow should pass my view model
    }
    ...
}
...

I have already tried to do DI through the wrapper in makeUIView method, but my app is crashing because .environmentObject doesn't work in hosting controller for some reason.


问:
Create a slidy presentation from *Quarto*
Create a slidy presentation using R markdown is straightforward R Markdown: The Definitive Guide. By
Yihui Xie, J. J. Allaire and Garrett Grolemund.

I try Quarto document (HTML format) to create such presentation (Multiple html page in one file), but horizontal rule (---) do not work to create a new slide/page.

Is there any way to create such presentation using Quarto?

Thanks

```<code>---
title: "Test document"
format: html
---

## Running Code

When you click the **Render** button a document will be generated that includes both content and the output of embedded code. You can embed code like this:

```{r}
1 + 1
```

---

You can add options to executable code like this

```{r}
#| echo: false
2 * 2
```
</code>```

Body:
Create a slidy presentation using R markdown is straightforward R Markdown: The Definitive Guide. By
Yihui Xie, J. J. Allaire and Garrett Grolemund.

I try Quarto document (HTML format) to create such presentation (Multiple html page in one file), but horizontal rule (---) do not work to create a new slide/page.

Is there any way to create such presentation using Quarto?

Thanks

---
title: "Test document"
format: html
---

## Running Code

When you click the **Render** button a document will be generated that includes both content and the output of embedded code. You can embed code like this:

```{r}
1 + 1
```

---

You can add options to executable code like this

```{r}
#| echo: false
2 * 2
```


问:
Rust argument requires that is borrowed for `'static`
Simple code that demonstrate my problem:

```<code>use std::thread;

fn main() {
    let data1 = vec!["1","2","3","4","5",];
    let data2 = vec!["a","b","c","d","e",];

    let mut h = Vec::new();
    for (i, j) in data1.iter().zip(data2.iter()) {
        let tmp = thread::spawn(move || {
            println!("{} {}", i, j);
        });
        h.push(tmp);
    }
    for jh in h.into_iter() {
        jh.join().unwrap();
    }
}
</code>```

Playgorund

Error:

```<code>Compiling playground v0.0.1 (/playground)
error[E0597]: `data1` does not live long enough
  --> src/main.rs:8:19
   |
8  |       for (i, j) in data1.iter().zip(data2.iter()) {
   |                     ^^^^^^^^^^^^ borrowed value does not live long enough
9  |           let tmp = thread::spawn(move || {
   |  ___________________-
10 | |             println!("{} {}", i, j);
11 | |         });
   | |__________- argument requires that `data1` is borrowed for `'static`
...
17 |   }
   |   - `data1` dropped here while still borrowed

error[E0597]: `data2` does not live long enough
  --> src/main.rs:8:36
   |
8  |       for (i, j) in data1.iter().zip(data2.iter()) {
   |                                      ^^^^^^^^^^^^ borrowed value does not live long enough
9  |           let tmp = thread::spawn(move || {
   |  ___________________-
10 | |             println!("{} {}", i, j);
11 | |         });
   | |__________- argument requires that `data2` is borrowed for `'static`
...
17 |   }
   |   - `data2` dropped here while still borrowed

For more information about this error, try `rustc --explain E0597`.
error: could not compile `playground` due to 2 previous errors
</code>```

If I understand correctly problem is that complier does not know that my data1 and data2, live till the end of program ? That is why it is requiring that data1 and data2 need to be 'static. But what is confusing to me is that it know that data1 and data2 will be dropped at line 17, what is end of program. Maybe it is confused because I use threads and it does not know that I do join() on threads ?

Anyway any ideas how to solve it ?

Body:
Simple code that demonstrate my problem:

use std::thread;

fn main() {
    let data1 = vec!["1","2","3","4","5",];
    let data2 = vec!["a","b","c","d","e",];

    let mut h = Vec::new();
    for (i, j) in data1.iter().zip(data2.iter()) {
        let tmp = thread::spawn(move || {
            println!("{} {}", i, j);
        });
        h.push(tmp);
    }
    for jh in h.into_iter() {
        jh.join().unwrap();
    }
}

Playgorund

Error:

Compiling playground v0.0.1 (/playground)
error[E0597]: `data1` does not live long enough
  --> src/main.rs:8:19
   |
8  |       for (i, j) in data1.iter().zip(data2.iter()) {
   |                     ^^^^^^^^^^^^ borrowed value does not live long enough
9  |           let tmp = thread::spawn(move || {
   |  ___________________-
10 | |             println!("{} {}", i, j);
11 | |         });
   | |__________- argument requires that `data1` is borrowed for `'static`
...
17 |   }
   |   - `data1` dropped here while still borrowed

error[E0597]: `data2` does not live long enough
  --> src/main.rs:8:36
   |
8  |       for (i, j) in data1.iter().zip(data2.iter()) {
   |                                      ^^^^^^^^^^^^ borrowed value does not live long enough
9  |           let tmp = thread::spawn(move || {
   |  ___________________-
10 | |             println!("{} {}", i, j);
11 | |         });
   | |__________- argument requires that `data2` is borrowed for `'static`
...
17 |   }
   |   - `data2` dropped here while still borrowed

For more information about this error, try `rustc --explain E0597`.
error: could not compile `playground` due to 2 previous errors

If I understand correctly problem is that complier does not know that my data1 and data2, live till the end of program ? That is why it is requiring that data1 and data2 need to be 'static. But what is confusing to me is that it know that data1 and data2 will be dropped at line 17, what is end of program. Maybe it is confused because I use threads and it does not know that I do join() on threads ?

Anyway any ideas how to solve it ?


问:
artifactory after upgrade to 7.47.11 not started - Unexpected response status code: 500
My original version was not old, around 7.41.x, after updating to the latest version, artifactory no longer starts. I can't understand the problem as I don't understand the architecture well. Please help me figure it out. There are no specific errors in the logs.

Artifactory status web page

As far as I understand, the problem is that for some reason the service that implements the user interface on port 8070 does not start.

There is nothing interesting in the logs for this service.

last errors in logs console.log

```<code>2022-12-10T19:48:33.842Z [jfrou] [ERROR] [5fb2daba52b5d736] [healthcheck.go:66             ] [main                ] [] - Checking health of service 'jffe_000-artifactory' using URL 'http://localhost:8070/readiness' returned an error: Get "http://localhost:8070/readiness": dial tcp 127.0.0.1:8070: connect: connection refused
2022-12-10T19:48:33.852Z [jfrou] [ERROR] [5fb2daba52b5d736] [healthcheck.go:71             ] [main                ] [] - Checking health of service 'jfrt_01d96rcgsyfzkj1xnv8zqe1snm-artifactory' using URL 'http://localhost:8091/artifactory/api/v1/system/readiness' returned unexpected response status: 500
2022-12-10T19:48:33.853Z [jfrou] [WARN ] [5fb2daba52b5d736] [local_topology.go:274         ] [main                ] [] - Readiness test failed with the following error: "required node services are missing or unhealthy"
2022-12-10T19:48:35.991Z [jfac ] [ERROR] [52b88c5fcb86903d] [o.j.c.ExecutionUtils:190      ] [jf-common-pool-2    ] - Router readiness check failed, cannot start Access
2022-12-10T19:48:35.994Z [jfac ] [ERROR] [52b88c5fcb86903d] [a.s.b.AccessServerRegistrar:79] [jf-common-pool-1    ] - Could not register access
2022-12-10T20:09:28.988Z [jfrou] [ERROR] [37b0a206df08bfae] [healthcheck.go:66             ] [main                ] [] - Checking health of service 'jffe_000-artifactory' using URL 'http://localhost:8070/readiness' returned an error: Get "http://localhost:8070/readiness": dial tcp 127.0.0.1:8070: connect: connection refused
2022-12-10T20:09:28.995Z [jfrou] [ERROR] [37b0a206df08bfae] [healthcheck.go:71             ] [main                ] [] - Checking health of service 'jfrt_01d96rcgsyfzkj1xnv8zqe1snm-artifactory' using URL 'http://localhost:8091/artifactory/api/v1/system/readiness' returned unexpected response status: 500
</code>```

I checked the access rights, the availability of the database, the correctness of the configuration files. Tried running ./artifactory.sh and watching the launch progress.

```<code>[jfrou] [ERROR] [1dd615d3e5a6357a] [healthcheck.go:71             ] [main                ] [] - Checking health of service 'jfrt_01d96rcgsyfzkj1xnv8zqe1snm-artifactory' using URL 'http://localhost:8091/artifactory/api/v1/system/readiness' returned unexpected response status: 500
</code>```
```<code>curl http://localhost:8091/artifactory/api/v1/system/readiness
{
  "errors" : [ {
    "status" : 500,
    "message" : "Bad credentials"
  } ]
</code>```

add:
I spent more than 10 hours on the analysis, turned on the debug. I found this problem, maybe this is just the reason.
I can't find how to fix it yet.

```<code>2022-12-11T06:33:14.769Z [jfrt ] [DEBUG] [349c95a5eb2a97e9] [.AuthenticationFilterUtils:146] [http-nio-8081-exec-8] - Entering ArtifactorySsoAuthenticationFilter.getRemoteUserName
2022-12-11T06:33:14.769Z [jfrt ] [DEBUG] [349c95a5eb2a97e9] [o.a.w.s.AccessFilter:519      ] [http-nio-8081-exec-8] - Using anonymous
2022-12-11T06:33:14.770Z [jfrt ] [DEBUG] [349c95a5eb2a97e9] [o.a.w.s.AccessFilter:232      ] [http-nio-8081-exec-8] - Non-UI authentication cache accessed
2022-12-11T06:33:14.770Z [jfrt ] [DEBUG] [349c95a5eb2a97e9] [o.a.w.s.AccessFilter:227      ] [http-nio-8081-exec-8] - UI authentication cache accessed
2022-12-11T06:33:14.770Z [jfrt ] [DEBUG] [349c95a5eb2a97e9] [o.a.w.s.AccessFilter:523      ] [http-nio-8081-exec-8] - Creating the Anonymous token
2022-12-11T06:33:14.775Z [jfrt ] [DEBUG] [349c95a5eb2a97e9] [PassAuthenticationProvider:126] [http-nio-8081-exec-8] - 401, Access didn't authenticate user: 'anonymous'
2022-12-11T06:33:14.776Z [jfrt ] [DEBUG] [349c95a5eb2a97e9] [priseAuthenticationProvider:87] [http-nio-8081-exec-8] - Non docker request. Github provider supports only docker requests.
2022-12-11T06:33:14.781Z [jfrt ] [DEBUG] [                ] [o.a.w.s.ArtifactoryFilter:130 ] [http-nio-8081-exec-8] - org.artifactory.webapp.servlet.ArtifactoryFilter
org.springframework.security.authentication.BadCredentialsException: Bad credentials
    at org.artifactory.security.db.DbAuthenticationProvider.additionalAuthenticationChecks(DbAuthenticationProvider.java:64)
    at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:147)
    at org.artifactory.security.db.DbAuthenticationProvider.authenticate(DbAuthenticationProvider.java:53)
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:182)
    at org.artifactory.security.RealmAwareAuthenticationManager.authenticate(RealmAwareAuthenticationManager.java:68)
    at org.artifactory.webapp.servlet.AccessFilter.useAnonymousIfPossible(AccessFilter.java:533)
    at org.artifactory.webapp.servlet.AccessFilter.doFilterInternal(AccessFilter.java:301)
    at org.artifactory.webapp.servlet.AccessFilter.doFilter(AccessFilter.java:218)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.artifactory.webapp.servlet.RequestFilter.doFilter(RequestFilter.java:88)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.artifactory.webapp.servlet.ArtifactoryCsrfFilter.doFilter(ArtifactoryCsrfFilter.java:83)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.session.web.http.SessionRepositoryFilter.doFilterInternal(SessionRepositoryFilter.java:164)
    at org.springframework.session.web.http.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:80)
    at org.artifactory.webapp.servlet.SessionFilter.doFilter(SessionFilter.java:67)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.artifactory.webapp.servlet.ArtifactoryTracingFilter.doFilter(ArtifactoryTracingFilter.java:38)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.artifactory.webapp.servlet.ArtifactoryFilter.doFilter(ArtifactoryFilter.java:126)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.valves.rewrite.RewriteValve.invoke(RewriteValve.java:289)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:924)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1743)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:833)
</code>```

Body:
My original version was not old, around 7.41.x, after updating to the latest version, artifactory no longer starts. I can't understand the problem as I don't understand the architecture well. Please help me figure it out. There are no specific errors in the logs.

Artifactory status web page

As far as I understand, the problem is that for some reason the service that implements the user interface on port 8070 does not start.

There is nothing interesting in the logs for this service.

last errors in logs console.log

2022-12-10T19:48:33.842Z [jfrou] [ERROR] [5fb2daba52b5d736] [healthcheck.go:66             ] [main                ] [] - Checking health of service 'jffe_000-artifactory' using URL 'http://localhost:8070/readiness' returned an error: Get "http://localhost:8070/readiness": dial tcp 127.0.0.1:8070: connect: connection refused
2022-12-10T19:48:33.852Z [jfrou] [ERROR] [5fb2daba52b5d736] [healthcheck.go:71             ] [main                ] [] - Checking health of service 'jfrt_01d96rcgsyfzkj1xnv8zqe1snm-artifactory' using URL 'http://localhost:8091/artifactory/api/v1/system/readiness' returned unexpected response status: 500
2022-12-10T19:48:33.853Z [jfrou] [WARN ] [5fb2daba52b5d736] [local_topology.go:274         ] [main                ] [] - Readiness test failed with the following error: "required node services are missing or unhealthy"
2022-12-10T19:48:35.991Z [jfac ] [ERROR] [52b88c5fcb86903d] [o.j.c.ExecutionUtils:190      ] [jf-common-pool-2    ] - Router readiness check failed, cannot start Access
2022-12-10T19:48:35.994Z [jfac ] [ERROR] [52b88c5fcb86903d] [a.s.b.AccessServerRegistrar:79] [jf-common-pool-1    ] - Could not register access
2022-12-10T20:09:28.988Z [jfrou] [ERROR] [37b0a206df08bfae] [healthcheck.go:66             ] [main                ] [] - Checking health of service 'jffe_000-artifactory' using URL 'http://localhost:8070/readiness' returned an error: Get "http://localhost:8070/readiness": dial tcp 127.0.0.1:8070: connect: connection refused
2022-12-10T20:09:28.995Z [jfrou] [ERROR] [37b0a206df08bfae] [healthcheck.go:71             ] [main                ] [] - Checking health of service 'jfrt_01d96rcgsyfzkj1xnv8zqe1snm-artifactory' using URL 'http://localhost:8091/artifactory/api/v1/system/readiness' returned unexpected response status: 500

I checked the access rights, the availability of the database, the correctness of the configuration files. Tried running ./artifactory.sh and watching the launch progress.

[jfrou] [ERROR] [1dd615d3e5a6357a] [healthcheck.go:71             ] [main                ] [] - Checking health of service 'jfrt_01d96rcgsyfzkj1xnv8zqe1snm-artifactory' using URL 'http://localhost:8091/artifactory/api/v1/system/readiness' returned unexpected response status: 500

curl http://localhost:8091/artifactory/api/v1/system/readiness
{
  "errors" : [ {
    "status" : 500,
    "message" : "Bad credentials"
  } ]

add:
I spent more than 10 hours on the analysis, turned on the debug. I found this problem, maybe this is just the reason.
I can't find how to fix it yet.

2022-12-11T06:33:14.769Z [jfrt ] [DEBUG] [349c95a5eb2a97e9] [.AuthenticationFilterUtils:146] [http-nio-8081-exec-8] - Entering ArtifactorySsoAuthenticationFilter.getRemoteUserName
2022-12-11T06:33:14.769Z [jfrt ] [DEBUG] [349c95a5eb2a97e9] [o.a.w.s.AccessFilter:519      ] [http-nio-8081-exec-8] - Using anonymous
2022-12-11T06:33:14.770Z [jfrt ] [DEBUG] [349c95a5eb2a97e9] [o.a.w.s.AccessFilter:232      ] [http-nio-8081-exec-8] - Non-UI authentication cache accessed
2022-12-11T06:33:14.770Z [jfrt ] [DEBUG] [349c95a5eb2a97e9] [o.a.w.s.AccessFilter:227      ] [http-nio-8081-exec-8] - UI authentication cache accessed
2022-12-11T06:33:14.770Z [jfrt ] [DEBUG] [349c95a5eb2a97e9] [o.a.w.s.AccessFilter:523      ] [http-nio-8081-exec-8] - Creating the Anonymous token
2022-12-11T06:33:14.775Z [jfrt ] [DEBUG] [349c95a5eb2a97e9] [PassAuthenticationProvider:126] [http-nio-8081-exec-8] - 401, Access didn't authenticate user: 'anonymous'
2022-12-11T06:33:14.776Z [jfrt ] [DEBUG] [349c95a5eb2a97e9] [priseAuthenticationProvider:87] [http-nio-8081-exec-8] - Non docker request. Github provider supports only docker requests.
2022-12-11T06:33:14.781Z [jfrt ] [DEBUG] [                ] [o.a.w.s.ArtifactoryFilter:130 ] [http-nio-8081-exec-8] - org.artifactory.webapp.servlet.ArtifactoryFilter
org.springframework.security.authentication.BadCredentialsException: Bad credentials
    at org.artifactory.security.db.DbAuthenticationProvider.additionalAuthenticationChecks(DbAuthenticationProvider.java:64)
    at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:147)
    at org.artifactory.security.db.DbAuthenticationProvider.authenticate(DbAuthenticationProvider.java:53)
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:182)
    at org.artifactory.security.RealmAwareAuthenticationManager.authenticate(RealmAwareAuthenticationManager.java:68)
    at org.artifactory.webapp.servlet.AccessFilter.useAnonymousIfPossible(AccessFilter.java:533)
    at org.artifactory.webapp.servlet.AccessFilter.doFilterInternal(AccessFilter.java:301)
    at org.artifactory.webapp.servlet.AccessFilter.doFilter(AccessFilter.java:218)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.artifactory.webapp.servlet.RequestFilter.doFilter(RequestFilter.java:88)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.artifactory.webapp.servlet.ArtifactoryCsrfFilter.doFilter(ArtifactoryCsrfFilter.java:83)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.session.web.http.SessionRepositoryFilter.doFilterInternal(SessionRepositoryFilter.java:164)
    at org.springframework.session.web.http.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:80)
    at org.artifactory.webapp.servlet.SessionFilter.doFilter(SessionFilter.java:67)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.artifactory.webapp.servlet.ArtifactoryTracingFilter.doFilter(ArtifactoryTracingFilter.java:38)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.artifactory.webapp.servlet.ArtifactoryFilter.doFilter(ArtifactoryFilter.java:126)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.valves.rewrite.RewriteValve.invoke(RewriteValve.java:289)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:924)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1743)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:833)


问:
Why is stack not auto detecting my module?
I am trying to write a script that uses Diagrams but the stack package detection feature is confusing me. I have two files and when the support module imports SVGFonts stack doesn't add it to the list of modules that are found. Instead, it's hidden. When the import is in the main file, however, it downloads it and finds it for the build just fine.

Main.hs

```<code>-- stack --resolver lts-19.0 script

{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE FlexibleContexts          #-}
{-# LANGUAGE TypeFamilies              #-}

import Diagrams.Prelude
import MyMod (val)

import Diagrams.Backend.SVG

main = print val
</code>```

MyMod.hs

```<code>module MyMod where

import Diagrams.Backend.SVG

val = 1
</code>```

And I am getting this error

```<code>    Could not load module ‘Diagrams.Backend.SVG’
    It is a member of the hidden package ‘diagrams-svg-1.4.3.1’.
    You can run ‘:set -package diagrams-svg’ to expose it.
    (Note: this unloads all the modules in the current scope.)
    Use -v (or `:set -v` in ghci) to see a list of the files searched for.
  |
3 | import Diagrams.Backend.SVG (loadFont)
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
</code>```

How can I get stack to automatically find that I need SVGFonts and import it properly without adding the import to my main file?

Body:
I am trying to write a script that uses Diagrams but the stack package detection feature is confusing me. I have two files and when the support module imports SVGFonts stack doesn't add it to the list of modules that are found. Instead, it's hidden. When the import is in the main file, however, it downloads it and finds it for the build just fine.

Main.hs

-- stack --resolver lts-19.0 script

{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE FlexibleContexts          #-}
{-# LANGUAGE TypeFamilies              #-}

import Diagrams.Prelude
import MyMod (val)

import Diagrams.Backend.SVG

main = print val

MyMod.hs

module MyMod where

import Diagrams.Backend.SVG

val = 1

And I am getting this error

    Could not load module ‘Diagrams.Backend.SVG’
    It is a member of the hidden package ‘diagrams-svg-1.4.3.1’.
    You can run ‘:set -package diagrams-svg’ to expose it.
    (Note: this unloads all the modules in the current scope.)
    Use -v (or `:set -v` in ghci) to see a list of the files searched for.
  |
3 | import Diagrams.Backend.SVG (loadFont)
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

How can I get stack to automatically find that I need SVGFonts and import it properly without adding the import to my main file?


问:
Why change state to maximized hiding some pixels C# WPF
I have made WPF project with window style of none (can resize) then I created custom taskbar on top with exit, maximize and minimize buttons. So exactly this.WindowState = WindowState.Normal; looks like this:

when I press maximize button windows state changes to this.WindowState = WindowState.Maximized; and it does change but hiding some pixels on top and sides (probably on bottom too), see image bellow:

I'cant find anything about it on google and stackoverflow. So here is code am using to change window state:

```<code>        private void maximize_Click(object sender, RoutedEventArgs e)
        {
            if(this.WindowState == WindowState.Normal)
            {
                this.WindowState = WindowState.Maximized;
            } else
            {
                this.WindowState = WindowState.Normal;
            }
        }
</code>```

and to make it maximized without hiding windows bottom taskbar am using this:

```<code>        public MainWindow()
        {
            InitializeComponent();
            MaxWidth = SystemParameters.MaximizedPrimaryScreenWidth;
            MaxHeight = SystemParameters.MaximizedPrimaryScreenHeight;
        }
</code>```

I have found reason of this (but not fix yet):

```<code>    <WindowChrome.WindowChrome>
        <WindowChrome GlassFrameThickness="0" CornerRadius="0" CaptionHeight="0"
            UseAeroCaptionButtons="False" ResizeBorderThickness="7" />
    </WindowChrome.WindowChrome>
</code>```

if there is already question about but I couldn't find it please let me know

Body:
I have made WPF project with window style of none (can resize) then I created custom taskbar on top with exit, maximize and minimize buttons. So exactly this.WindowState = WindowState.Normal; looks like this:

when I press maximize button windows state changes to this.WindowState = WindowState.Maximized; and it does change but hiding some pixels on top and sides (probably on bottom too), see image bellow:

I'cant find anything about it on google and stackoverflow. So here is code am using to change window state:

        private void maximize_Click(object sender, RoutedEventArgs e)
        {
            if(this.WindowState == WindowState.Normal)
            {
                this.WindowState = WindowState.Maximized;
            } else
            {
                this.WindowState = WindowState.Normal;
            }
        }

and to make it maximized without hiding windows bottom taskbar am using this:

        public MainWindow()
        {
            InitializeComponent();
            MaxWidth = SystemParameters.MaximizedPrimaryScreenWidth;
            MaxHeight = SystemParameters.MaximizedPrimaryScreenHeight;
        }

I have found reason of this (but not fix yet):

    <WindowChrome.WindowChrome>
        <WindowChrome GlassFrameThickness="0" CornerRadius="0" CaptionHeight="0"
            UseAeroCaptionButtons="False" ResizeBorderThickness="7" />
    </WindowChrome.WindowChrome>

if there is already question about but I couldn't find it please let me know


问:
Creating OOP decoupling with events
Is Creating an app that communicates with events, from a infrastructure point, a good thing? Or is better to just call methods and be simple, I was thinking about something as a observers pattern but in a large system. Other question, this could affect the performance? Here is a exemple is vanilla js:

How it could work

class someClass{

    someMethod() {
        let event =  new Event('event')
        document.dispatchEvent(event)
        console.log('ok');
    }

}

class otherClass {
    constructor(){
        this.initEventSearching();
    }

    initEventSearching(){
        document.addEventListener('event', () => {
            // block
            console.log('hey');
        })
    }
}

let aVariable = new someClass()
let bVariable = new otherClass()
aVariable.someMethod()
```

Title: Creating OOP decoupling with events