问:
AWS - API Gateway, Lambda Authorizers, and ‘challenge/response’ style authentication
I have an automation that takes a Webhook from a service and posts it to Slack. The webhook goes to an API Gateway URL, authorizes through a Lambda authorizer function, and then goes to the Lambda function. This process is outlined here.

The verification is in the header["authentication"] field, which is validated by the authorizer. I scoped that text in the authorizer, and it passes it to the Lambda proxy as authenticationToken. If validated, a certificate is created and the webhook is passed to Lambda. This has all been working for a few months.

This year, as many companies tend to do, the service with the webhook is deprecating this auth method, and changing their authentication to a "Challenge-Response Check" style. So, the webhook sends a validation webhook, and the authorizer needs to make a hashed token out of several headers, including timestamp, and then the authorizer passes that hashed token back to the webhook, before sending the real webhook payload. Here is a node/express sample of how to do this:

```<code>app.post('/webhook', (req, res) => {

  var response

  console.log(req.body)
  console.log(req.headers)

  // construct the message string
  const message = `v0:${req.headers['x-zm-request-timestamp']}:${JSON.stringify(req.body)}`

  const hashForVerify = crypto.createHmac('sha256', process.env.ZOOM_WEBHOOK_SECRET_TOKEN).update(message).digest('hex')

  // hash the message string with your Webhook Secret Token and prepend the version semantic
  const signature = `v0=${hashForVerify}`

  // you validating the request came from Zoom https://marketplace.zoom.us/docs/api-reference/webhook-reference#notification-structure
  if (req.headers['x-zm-signature'] === signature) {

    // Zoom validating you control the webhook endpoint https://marketplace.zoom.us/docs/api-reference/webhook-reference#validate-webhook-endpoint
    if(req.body.event === 'endpoint.url_validation') {
      const hashForValidate = crypto.createHmac('sha256', process.env.ZOOM_WEBHOOK_SECRET_TOKEN).update(req.body.payload.plainToken).digest('hex')

      response = {
        message: {
          plainToken: req.body.payload.plainToken,
          encryptedToken: hashForValidate
        },
        status: 200
      }

....
</code>```

Is this methodology supported by the authorizer/Lambda method? The APIG authorizer would need to send several headers to the Lambda authorizer function, vs just the one. I see a new feature that is changing the authorizer Type to Request (from Token), but I was not able to pass the headers to the auth function that way, after re-creating and re-deploying the APIG.

Or, should I get rid of the authorizer all together, and just do my authentication on the actual Lambda?

Or, should I start to use Lambda's newer URL feature, and get rid of APIG all together?

What is the best workflow in this use case?

Any advice or links appreciated.

Body:
I have an automation that takes a Webhook from a service and posts it to Slack. The webhook goes to an API Gateway URL, authorizes through a Lambda authorizer function, and then goes to the Lambda function. This process is outlined here.

The verification is in the header["authentication"] field, which is validated by the authorizer. I scoped that text in the authorizer, and it passes it to the Lambda proxy as authenticationToken. If validated, a certificate is created and the webhook is passed to Lambda. This has all been working for a few months.

This year, as many companies tend to do, the service with the webhook is deprecating this auth method, and changing their authentication to a "Challenge-Response Check" style. So, the webhook sends a validation webhook, and the authorizer needs to make a hashed token out of several headers, including timestamp, and then the authorizer passes that hashed token back to the webhook, before sending the real webhook payload. Here is a node/express sample of how to do this:

app.post('/webhook', (req, res) => {

  var response

  console.log(req.body)
  console.log(req.headers)

  // construct the message string
  const message = `v0:${req.headers['x-zm-request-timestamp']}:${JSON.stringify(req.body)}`

  const hashForVerify = crypto.createHmac('sha256', process.env.ZOOM_WEBHOOK_SECRET_TOKEN).update(message).digest('hex')

  // hash the message string with your Webhook Secret Token and prepend the version semantic
  const signature = `v0=${hashForVerify}`

  // you validating the request came from Zoom https://marketplace.zoom.us/docs/api-reference/webhook-reference#notification-structure
  if (req.headers['x-zm-signature'] === signature) {

    // Zoom validating you control the webhook endpoint https://marketplace.zoom.us/docs/api-reference/webhook-reference#validate-webhook-endpoint
    if(req.body.event === 'endpoint.url_validation') {
      const hashForValidate = crypto.createHmac('sha256', process.env.ZOOM_WEBHOOK_SECRET_TOKEN).update(req.body.payload.plainToken).digest('hex')

      response = {
        message: {
          plainToken: req.body.payload.plainToken,
          encryptedToken: hashForValidate
        },
        status: 200
      }

....

Is this methodology supported by the authorizer/Lambda method? The APIG authorizer would need to send several headers to the Lambda authorizer function, vs just the one. I see a new feature that is changing the authorizer Type to Request (from Token), but I was not able to pass the headers to the auth function that way, after re-creating and re-deploying the APIG.

Or, should I get rid of the authorizer all together, and just do my authentication on the actual Lambda?

Or, should I start to use Lambda's newer URL feature, and get rid of APIG all together?

What is the best workflow in this use case?

Any advice or links appreciated.


来源: stackexchange

问:
Springboot deployment works on localhost but on ubuntu 20.04 server 404 not found
My Springboot application works on the localhost but on the ubuntu 20.04 server I get a 404 Not found response. Please say which files you need.

I tried everything I found in the internet.

Thanks in advance

ContentLicense: CC BY-SA 4.0


问:
Adding time spending indication on a matplotlib funcanimation window
I'm asking my question here because I haven't find any information that could solve my problem. With FuncAnimation, I'm plotting the coordinates of a moving point on a world map. Every coordinates that I take from a CSV file come from a function where I implement myself the time spending. The data are then send to a csv file that I call in my FuncAnimation function.
This is how my CSV file look like:
enter image description here

All the plotting is working but I want to improve it. This is how my plot looks like at a period t:

I would like to know if someone knows a command that would permit me to plot my coordinates and the time (on the bottom left for example) like the time spending at the bottom left of the window on my computer, something like plt.time(position= 'bottom left', time_list).

The time value would be taken from my CSV, and open as a list (time_list) at the beginning of the code.

I tried to find the function on internet but didn't find anything except how to put the time as an axe which is not what I want.


问:
How to play audio in python via youtube link (without downloading)
I'm trying to play the audio from the YouTube link on Discord, but nothing works. There are no errors.

Code for playback audio:

```<code>url = f"https://www.youtube.com/watch?v={video['id']}"
            player = await YTDLSource.from_url(f"{url}{video['id']}", loop=self.bot.loop, stream=True)
            voice_channel.play(player, after=None)
</code>```

YTDLSource class:

```<code>import youtube_dl
import disnake

youtube_dl.utils.bug_reports_message = lambda: ''

ytdl_format_options = {
    'format': 'bestaudio/best',
    'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
    'restrictfilenames': True,
    'noplaylist': True,
    'nocheckcertificate': True,
    'ignoreerrors': False,
    'logtostderr': False,
    'quiet': True,
    'no_warnings': True,
    'default_search': 'auto',
    'source_address': '192.168.0.20' # bind to ipv4 since ipv6 addresses cause issues sometimes
}

ffmpeg_options = {
    'options': '-vn'
}

ytdl = youtube_dl.YoutubeDL(ytdl_format_options)

class YTDLSource(disnake.PCMVolumeTransformer):
    def __init__(self, source, *, data, volume=0.5):
        super().__init__(source, volume)
        self.data = data
        self.title = data.get('title')
        self.url = ""

    @classmethod
    async def from_url(cls, url, *, loop=None, stream=False):
        loop = loop or asyncio.get_event_loop()
        data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))
        if 'entries' in data:
            # take first item from a playlist
            data = data['entries'][0]
        filename = data['title'] if stream else ytdl.prepare_filename(data)
        return cls(disnake.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)
</code>```

P.S: If with music installation, everything works

Body:
I'm trying to play the audio from the YouTube link on Discord, but nothing works. There are no errors.

Code for playback audio:

url = f"https://www.youtube.com/watch?v={video['id']}"
            player = await YTDLSource.from_url(f"{url}{video['id']}", loop=self.bot.loop, stream=True)
            voice_channel.play(player, after=None)

YTDLSource class:

import youtube_dl
import disnake

youtube_dl.utils.bug_reports_message = lambda: ''

ytdl_format_options = {
    'format': 'bestaudio/best',
    'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
    'restrictfilenames': True,
    'noplaylist': True,
    'nocheckcertificate': True,
    'ignoreerrors': False,
    'logtostderr': False,
    'quiet': True,
    'no_warnings': True,
    'default_search': 'auto',
    'source_address': '192.168.0.20' # bind to ipv4 since ipv6 addresses cause issues sometimes
}

ffmpeg_options = {
    'options': '-vn'
}

ytdl = youtube_dl.YoutubeDL(ytdl_format_options)

class YTDLSource(disnake.PCMVolumeTransformer):
    def __init__(self, source, *, data, volume=0.5):
        super().__init__(source, volume)
        self.data = data
        self.title = data.get('title')
        self.url = ""

    @classmethod
    async def from_url(cls, url, *, loop=None, stream=False):
        loop = loop or asyncio.get_event_loop()
        data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))
        if 'entries' in data:
            # take first item from a playlist
            data = data['entries'][0]
        filename = data['title'] if stream else ytdl.prepare_filename(data)
        return cls(disnake.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)

P.S: If with music installation, everything works


问:
Dropzone is returning JSON response instead of turbo_stream - Rails 7
I am using Dropzone with Rails 7 (Stimulus JS). I followed the documentation and somehow the image drag and drop is working fine but as I am integrating dropzone in existing form it is returning me the data in JSON response.

```<code>   def create
      return unless params[:body].present? && @benefit_request.client.present?

      Communication::SMS::SendOutboundMessage.call(body: params[:body],
                                                   client: @benefit_request.client,
                                                   sender: current_user)

      # here it is giving me error as it is expecting JSON template
      redirect_to request_sms_messages_path(@benefit_request)
    end

</code>```

As I am redirecting to the specific portion using Turbo frame so I do not want to render the whole page.

ActionController::UnknownFormat (Activation::SMSMessagesController#index is missing a template for this request format and variant.
request.formats: ["application/json"]
request.variant: []):

This is my code and I have tried to change the response using

```<code>headers: {
    "Content-Type": "application/vnd.turbo_stream"
  }
</code>```

but all in vain. I am not sure how can I pass the response data as turbo_stream

```<code></code>```

def create
return unless params[:body].present? && @benefit_request.client.present?

```<code>  Communication::SMS::SendOutboundMessage.call(body: params[:body],
                                               client: @benefit_request.client,
                                               sender: current_user)

  # here it is giving me error as it is expecting JSON template
  redirect_to request_sms_messages_path(@benefit_request)
end
</code>```
```<code></code>```

Body:
I am using Dropzone with Rails 7 (Stimulus JS). I followed the documentation and somehow the image drag and drop is working fine but as I am integrating dropzone in existing form it is returning me the data in JSON response.

   def create
      return unless params[:body].present? && @benefit_request.client.present?

      Communication::SMS::SendOutboundMessage.call(body: params[:body],
                                                   client: @benefit_request.client,
                                                   sender: current_user)

      # here it is giving me error as it is expecting JSON template
      redirect_to request_sms_messages_path(@benefit_request)
    end

As I am redirecting to the specific portion using Turbo frame so I do not want to render the whole page.

ActionController::UnknownFormat (Activation::SMSMessagesController#index is missing a template for this request format and variant.
request.formats: ["application/json"]
request.variant: []):

This is my code and I have tried to change the response using

headers: {
    "Content-Type": "application/vnd.turbo_stream"
  }

but all in vain. I am not sure how can I pass the response data as turbo_stream

def create
return unless params[:body].present? && @benefit_request.client.present?

  Communication::SMS::SendOutboundMessage.call(body: params[:body],
                                               client: @benefit_request.client,
                                               sender: current_user)

  # here it is giving me error as it is expecting JSON template
  redirect_to request_sms_messages_path(@benefit_request)
end


问:
How to download a picture .png from the cloud to MongoDB with only the URL?
After a GET request where I retrieve the url address of a picture, I want to save this picture into a MongoDB collection.

I specify that this image is not stored on my laptop, but from the cloud.

Can you show me an example or best practice, please?

I try many example from Google without success.


问:
Morphing images into another and creating a video with NodeJs
I'm trying to come up with a simple nodejs script that takes a bunch of images and create a video out of it, where each image morphs to the next one. I tried a couple of libraries, it seems like create a video out of a bunch of images is easy, however I cannot find anything that morphs the images into another.

Currently I'm using https://github.com/h2non/videoshow#readme, this doesn't supporting the morphing tho.

Does somebody know a good solution to this?


问:
Shapely polygon creates straight lines between points where it shouldn't
I'm using shapely within Python. I created a polygon using coordinates; however, when I plot it, it creates random straight lines between points where it should not.

Here is what it looks like:

And here is what I want the perimeter to look like (without the fill):

Here's the code I'm using to create the polygon and plot it:

```<code>poly_coords = coords[['lon','lat']]
poly_coords = poly_coords.values.tolist()
poly = Polygon(poly_coords)

x,y = poly.exterior.xy
plt.plot(x,y)
</code>```

Is there something I'm missing that's causing the random lines between points to be created?

Body:
I'm using shapely within Python. I created a polygon using coordinates; however, when I plot it, it creates random straight lines between points where it should not.

Here is what it looks like:

And here is what I want the perimeter to look like (without the fill):

Here's the code I'm using to create the polygon and plot it:

poly_coords = coords[['lon','lat']]
poly_coords = poly_coords.values.tolist()
poly = Polygon(poly_coords)

x,y = poly.exterior.xy
plt.plot(x,y)

Is there something I'm missing that's causing the random lines between points to be created?


问:
Use AWS DMS to convert Oracle datatypes to Postgres?
I'm confused on how to approach this. I think I have to create a DMS migration task in AWS and select the Source Endpoint as Oracle and the Target as Postgres? I see this listed on the AWS document:

```<code>Example Change data type of target column

The following example changes the data type of a target column named SALE_AMOUNT from an existing data type to int8.

{
    "rule-type": "transformation",
    "rule-id": "1",
    "rule-name": "RuleName 1",
    "rule-action": "change-data-type",
    "rule-target": "column",
    "object-locator": {
        "schema-name": "dbo",
        "table-name": "dms",
        "column-name": "SALE_AMOUNT"
    },
    "data-type": {
        "type": "int8"
    }
}
</code>```

I was told I need to use it somehow but I'm not sure how this ties into creating a DMS migration task. Where do I create the rules for the DMS transformation of the data types transforming from Oracle to Postgres? I don't know what to do and my POC isn't responding. I created a table in Oracle and now I want to load the table from Oracle to our Postgres database using DMS.

Body:
I'm confused on how to approach this. I think I have to create a DMS migration task in AWS and select the Source Endpoint as Oracle and the Target as Postgres? I see this listed on the AWS document:

Example Change data type of target column

The following example changes the data type of a target column named SALE_AMOUNT from an existing data type to int8.

{
    "rule-type": "transformation",
    "rule-id": "1",
    "rule-name": "RuleName 1",
    "rule-action": "change-data-type",
    "rule-target": "column",
    "object-locator": {
        "schema-name": "dbo",
        "table-name": "dms",
        "column-name": "SALE_AMOUNT"
    },
    "data-type": {
        "type": "int8"
    }
}

I was told I need to use it somehow but I'm not sure how this ties into creating a DMS migration task. Where do I create the rules for the DMS transformation of the data types transforming from Oracle to Postgres? I don't know what to do and my POC isn't responding. I created a table in Oracle and now I want to load the table from Oracle to our Postgres database using DMS.


问:
every Espresso "perform" gives same error: "cannot be called on the main application thread"
Writing the first instrumentation tests for an existing application's activities. The first test I've written errors out saying about onView(...).perform(typeText(...), closeSoftKeyboard())

Method cannot be called on the main application thread

here's the test so far:

class LoginActivityTests {
    @get:Rule var rule = ActivityScenarioRule(LoginActivity::class.java)

    @Test
    fun whenClickLoginStoresDomainInConnectionManager() {
        val domainName = "foo"
        val scenario = rule.scenario
        scenario.onActivity {
            onView(withId(R.id.domainEditText)).perform(typeText(domainName), closeSoftKeyboard())
        }
    }
}
```
<p>The error is thrown on the <code>onView</code> with abbreviated stacktrace</p>
```java.lang.IllegalStateException: Method cannot be called on the main application thread (on: main)
at androidx.test.internal.util.Checks.checkState(Checks.java:111)
at androidx.test.internal.util.Checks$1.checkNotMainThread(Checks.java:150)
at androidx.test.internal.util.Checks.checkNotMainThread(Checks.java:130)
at androidx.test.espresso.ViewInteraction.postAsynchronouslyOnUiThread(ViewInteraction.java:1)
at androidx.test.espresso.ViewInteraction.desugaredPerform(ViewInteraction.java:4)
at androidx.test.espresso.ViewInteraction.perform(ViewInteraction.java:8)
```
<p>I've looked at sample tests for performing clicks and text typing, and none of them seem to use any explicit specification of UI threads or anything. They just do what I've done: annotate a non-suspend function as <code>@Test</code> and then invoke <code>onView(...).perform(...)</code></p>
<p>I even tried to explicitly run in UI thread:</p>
<pre class="lang-kotlin prettyprint-override"><code>it.runOnUiThread {
                onView(withId(R.id.domainEditText)).perform(typeText(domainName), closeSoftKeyboard())
                onView(withId(R.id.loginButton)).perform(click())
                Log.d(TAG, "performed click")
            }
</code>```

Same error, same line. I've also installed android.test:rules and put @UiThreadTest on my @Before (even though there's not any UI stuff there, apparently the annotation can only take effect on After and Before methods.

Edit Question is: how do I get perform actions to work in my tests? Why am I getting this error when all the sample tests I'm finding with perform actions never have to specify UI thread or anything?

Body:
Writing the first instrumentation tests for an existing application's activities. The first test I've written errors out saying about onView(...).perform(typeText(...), closeSoftKeyboard())

Method cannot be called on the main application thread

here's the test so far:

class LoginActivityTests {
    @get:Rule var rule = ActivityScenarioRule(LoginActivity::class.java)

    @Test
    fun whenClickLoginStoresDomainInConnectionManager() {
        val domainName = "foo"
        val scenario = rule.scenario
        scenario.onActivity {
            onView(withId(R.id.domainEditText)).perform(typeText(domainName), closeSoftKeyboard())
        }
    }
}

The error is thrown on the onView with abbreviated stacktrace

java.lang.IllegalStateException: Method cannot be called on the main application thread (on: main)
at androidx.test.internal.util.Checks.checkState(Checks.java:111)
at androidx.test.internal.util.Checks$1.checkNotMainThread(Checks.java:150)
at androidx.test.internal.util.Checks.checkNotMainThread(Checks.java:130)
at androidx.test.espresso.ViewInteraction.postAsynchronouslyOnUiThread(ViewInteraction.java:1)
at androidx.test.espresso.ViewInteraction.desugaredPerform(ViewInteraction.java:4)
at androidx.test.espresso.ViewInteraction.perform(ViewInteraction.java:8)

I've looked at sample tests for performing clicks and text typing, and none of them seem to use any explicit specification of UI threads or anything. They just do what I've done: annotate a non-suspend function as @Test and then invoke onView(...).perform(...)

I even tried to explicitly run in UI thread:

it.runOnUiThread {
                onView(withId(R.id.domainEditText)).perform(typeText(domainName), closeSoftKeyboard())
                onView(withId(R.id.loginButton)).perform(click())
                Log.d(TAG, "performed click")
            }

Same error, same line. I've also installed android.test:rules and put @UiThreadTest on my @Before (even though there's not any UI stuff there, apparently the annotation can only take effect on After and Before methods.

Edit Question is: how do I get perform actions to work in my tests? Why am I getting this error when all the sample tests I'm finding with perform actions never have to specify UI thread or anything?


问:
Getting "Buffer overrun" warnings while allocating memory to a 2d array in a copy constructor in C++
I am creating a pacman game in Visual Studio 2022 with C++. For this game I have a Class "Map" to load the map from a text file and render it. I save the data from the textfile in int** map in my Map class. I now need this data for other objects in my game. So I was trying to make a copy constructor for it.

My copy constructor Map(const Map& original) works fine I guess. It copies the data to the new object and allocates memory to a new pointer and then copies the values in it without crashing or causing an error. But I still get these warnings:

Warning C6386: Buffer overrun while writing to 'map'.

Warning C6385: Reading invalid data from 'map'.

Warning C6386: Buffer overrun while writing to 'map[y]'.

Here a simplified version:

Map.h:

```<code>#pragma once
#include <stdlib.h>

class Map
{
public:
    // members would be private, only public for easier testing
    int height = 0, width = 0;
    int** map = nullptr;

    Map();
    Map(const Map& original);
    ~Map();
};
</code>```

Map.cpp:

```<code>#include "Map.h"

Map::Map()
{
    // set map size
    height = 3;
    width = 2;

    // dynamically allocating memory for int** map
    map = (int**)malloc(height * sizeof(int*));
    if (!map)
        exit(1);
    for (int i = 0; i < height; i++)
        map[i] = (int*)malloc(width * sizeof(int));

    // giving map some values
    for (int y = 0; y < height; y++)
    {
        if (!map[y])
            exit(1);
        for (int x = 0; x < width; x++)
            map[y][x] = x + y;
    }
}

Map::Map(const Map& original)
{
    // copy map size
    height = original.height;
    width = original.width;

    // allocate new memory for the new map
    map = (int**)malloc(height * sizeof(int*));
    if (!map)
        exit(2);
    for (int i = 0; i < height; i++)
        map[i] = (int*)malloc(width * sizeof(int));     // Warning C6386: Buffer overrun while writing to 'map'.

    // copy the values from original.map to this->map
    for (int y = 0; y < height; y++)
    {
        if (!map[y])        // Warning C6385: Reading invalid data from 'map'.
            exit(2);
        for (int x = 0; x < width; x++)
            map[y][x] = original.map[y][x];     // Warning C6386: Buffer overrun while writing to 'map[y]'.
    }
}

Map::~Map()
{
    // freeing allocated memory
    for (int i = 0; i < height; i++)
        free(map[i]);
    free(map);
}
</code>```

I only get these warnings in the copy construcor but not in the constructor, but I have basically written the same stuff in both of them.
I am now wondering if I should just ignore these warnings or if I have done something wrong.

I also tried doing the same thing with new / delete instead of malloc() / free() and it worked aswell but I did not get any warnings there.

Body:
I am creating a pacman game in Visual Studio 2022 with C++. For this game I have a Class "Map" to load the map from a text file and render it. I save the data from the textfile in int** map in my Map class. I now need this data for other objects in my game. So I was trying to make a copy constructor for it.

My copy constructor Map(const Map& original) works fine I guess. It copies the data to the new object and allocates memory to a new pointer and then copies the values in it without crashing or causing an error. But I still get these warnings:

Warning C6386: Buffer overrun while writing to 'map'.

Warning C6385: Reading invalid data from 'map'.

Warning C6386: Buffer overrun while writing to 'map[y]'.

Here a simplified version:

Map.h:

#pragma once
#include <stdlib.h>

class Map
{
public:
    // members would be private, only public for easier testing
    int height = 0, width = 0;
    int** map = nullptr;

    Map();
    Map(const Map& original);
    ~Map();
};

Map.cpp:

#include "Map.h"

Map::Map()
{
    // set map size
    height = 3;
    width = 2;

    // dynamically allocating memory for int** map
    map = (int**)malloc(height * sizeof(int*));
    if (!map)
        exit(1);
    for (int i = 0; i < height; i++)
        map[i] = (int*)malloc(width * sizeof(int));

    // giving map some values
    for (int y = 0; y < height; y++)
    {
        if (!map[y])
            exit(1);
        for (int x = 0; x < width; x++)
            map[y][x] = x + y;
    }
}

Map::Map(const Map& original)
{
    // copy map size
    height = original.height;
    width = original.width;

    // allocate new memory for the new map
    map = (int**)malloc(height * sizeof(int*));
    if (!map)
        exit(2);
    for (int i = 0; i < height; i++)
        map[i] = (int*)malloc(width * sizeof(int));     // Warning C6386: Buffer overrun while writing to 'map'.

    // copy the values from original.map to this->map
    for (int y = 0; y < height; y++)
    {
        if (!map[y])        // Warning C6385: Reading invalid data from 'map'.
            exit(2);
        for (int x = 0; x < width; x++)
            map[y][x] = original.map[y][x];     // Warning C6386: Buffer overrun while writing to 'map[y]'.
    }
}

Map::~Map()
{
    // freeing allocated memory
    for (int i = 0; i < height; i++)
        free(map[i]);
    free(map);
}

I only get these warnings in the copy construcor but not in the constructor, but I have basically written the same stuff in both of them.
I am now wondering if I should just ignore these warnings or if I have done something wrong.

I also tried doing the same thing with new / delete instead of malloc() / free() and it worked aswell but I did not get any warnings there.


问:
CICD initating with dalay after a new commit
I have a repository with CICD which after each new commit, it starts the CICD process.
I have some commits applying in my repo with the following order:

commit 4 - time: 14-Dec-2022 12:00:30 - CICD starts

commit 3 - time: 14-Dec-2022 12:00:20 - CICD starts

commit 2 - time: 14-Dec-2022 12:00:10 - CICD starts

commit 1 - time: 14-Dec-2022 12:00:00 - CICD starts

What I want to do is that I consider a buffer time in CICD initiation that if I have for example 5 commit in a minute, it just CICD the latest one instead of having all running and interfering with each other. Something like this:

commit 4 - time: 14-Dec-2022 12:00:30 - CICD starts

commit 3 - time: 14-Dec-2022 12:00:20 - CICD DOES NOT start

commit 2 - time: 14-Dec-2022 12:00:10 - CICD DOES NOT start

commit 1 - time: 14-Dec-2022 12:00:00 - CICD DOES NOT start

I can delay each CICD but that won't be helpful.

Even being able to cancel previous unfinished CICD workflows with the initiation of a new CICD would be helpful.


问:
Azure "continuous speech recognition with input from an audio file" Cancelled unexpectedly
I have a same audio file ran 3 times and 2 times it stopped at the roughly same place. Is there something I can set to mitigate its occurrence? TIA

```<code>CANCELED at 0
CLOSING on SpeechRecognitionCanceledEventArgs(session_id=0ab1851d71e24ca2bd4f462ecdf9995a, result=SpeechRecognitionResult(result_id=1a5ecdd8b0af4acab0cf243657b1c3ee, text="", reason=ResultReason.Canceled))
SESSION STOPPED SessionEventArgs(session_id=0ab1851d71e24ca2bd4f462ecdf9995a)
CLOSING on SessionEventArgs(session_id=0ab1851d71e24ca2bd4f462ecdf9995a)

Total Time elaped  0:05:08.909569   From 2022-12-15 08:38:08.722855   To 2022-12-15 08:43:17.632424

</code>```

Rerun and hope to get it through. Even I know it's not likely without knowing the root cause.

Body:
I have a same audio file ran 3 times and 2 times it stopped at the roughly same place. Is there something I can set to mitigate its occurrence? TIA

CANCELED at 0
CLOSING on SpeechRecognitionCanceledEventArgs(session_id=0ab1851d71e24ca2bd4f462ecdf9995a, result=SpeechRecognitionResult(result_id=1a5ecdd8b0af4acab0cf243657b1c3ee, text="", reason=ResultReason.Canceled))
SESSION STOPPED SessionEventArgs(session_id=0ab1851d71e24ca2bd4f462ecdf9995a)
CLOSING on SessionEventArgs(session_id=0ab1851d71e24ca2bd4f462ecdf9995a)

Total Time elaped  0:05:08.909569   From 2022-12-15 08:38:08.722855   To 2022-12-15 08:43:17.632424

Rerun and hope to get it through. Even I know it's not likely without knowing the root cause.


问:
SSIS Project for Change-Data-Capture
I have an SSIS proof-of-concept project all setup and working for CDC on 2 test tables.  For 2 tables it requires 4 packages, 2 for the initial load and 2 for the incremental load.  I have 75 tables to load and don't want to create a maintenance nightmare by creating 150 packages.  I've tried to use a Foreach Loop Container wrapped around the CDC Control tasks but those tasks don't seem to be configurable with more than 1 variable and don't allow expressions and my cdc_states table is not being loaded correctly.  Anyone else run into this?  At this point I'm thinking about doing this all in stored procs.</p>

Title: SSIS Project for Change-Data-Capture


问:
Is there a metric for run times, or some other recommended way to collect runtimes when tuning a model in tidymodels?
I am using the tidymodels R package to fit a random forest model with the ranger engine, but I think this question is general to tuning any type of model tidymodels supports.

When running my tuning grid, I would like to record the time it takes to fit each model and treat this run time like any another metric. The reason I want to do this is to look for areas in the parameter space where the significant gains in AUC can be had for minor increases in run time, versus areas where there is a diminishing returns on run time.

After Googling and looking through the package docs I did not find any built-in metrics.

Does anybody know of the 'official' way to collect run time information from tune_grid()? Or know a third-party package that adds run time metrics?

I can do it the old-fashioned way, by running my fits in a loop and recording system.time() at each step, but this seems like a practical need other people would have had long before me, so I'm hoping to find an existing solution that uses tidymodels workflows.


问:
Maven depencyManagement override version in child pom
Can I override a version (specified in parent pom) of a dependency in a pom within dependencyManagement. I know the inverse is commonly used, i.e. specifying a version in parent pom within  and then using that dependecy in a child pom without specifying the version.

Parent pom specifies a version of library A with version 2.5. In pom there is (within) a dependencyManagement a specification of library A, but with version 1.8


问:
Can't change Read-only on program files X86 folder
I ran updates after shutting down my pc last night. When I went to load a game after restarting I got an error: An error occurred while updating GAME NAME (missing file privileges): D:\SteamLibrary\steamapps\common\GAME NAME

I went to C:\Program Files (x86)\Steam and checked off "Read-only (only appleis to files in folder)."

I also ran command prompt and ran C:\Windows\System32>attrib -r +s "C:\Program Files (x86)\Steam"

This returned to C:\Windows\System32 which is the expected behavior in cmd prompt but when I go back to file properties it is still check "Read-only"

I went into windows defender and made sure that Controlled Folder Access was turned off.

I cleared my download cache in Steam Settings as well as changed download region. I've restarted my PC several times and also tried all steps above without restarting.


问:
TypeORM need update value of Many-to-one
need your help,i want to update user field avatar. I already have row in DB for user, and images. And dont know, how i can update this, in my file service const files: Promise<FileEntity | null> = this._commonService.getImageByName(userAvatar.filename);
i need to take id from file name and put this id to user avatar.
Thanks for help.

User Entity

```<code>import { CartEntity } from '../../cart/entities/cart.entity';
    import { FileEntity } from '../../common/entities/images.entity';
    import { OrderEntity } from '../../order/entities/order.entity';
    import {
      Entity,
      Column,
      PrimaryGeneratedColumn,
      CreateDateColumn,
      UpdateDateColumn,
      OneToMany,
      ManyToOne,
      RelationId,
    } from 'typeorm';

    export enum UserTypeEnum {
      Vendor = 'vendor',
      Customer = 'customer'
    }

    @Entity()
    export class UserEntity {

      @PrimaryGeneratedColumn()
      public id!: number;

      @Column({ nullable: true })
      public firstName?: string;

      @Column({ nullable: true })
      public lastName?: string;

      @Column({ default: false })
      public verify?: boolean;

      @Column()
      public email!: string;

      @Column()
      public password!: string;

      @Column({
        type: 'enum',
        name: 'roles',
        enum: UserTypeEnum,
        default: UserTypeEnum.Customer,
      })
      public role!: UserTypeEnum;

      @OneToMany(() => CartEntity, (cart) => cart.user)
      public carts?: CartEntity[];

      @ManyToOne(() => FileEntity, (avatar) => avatar.users)
      public avatar?: FileEntity;

      @RelationId((user: UserEntity) => user.avatar)
      public avatarId?: number;

      @OneToMany(() => OrderEntity, (order) => order.user)
      public orders?: OrderEntity[];

      @CreateDateColumn()
      public createdAt!: Date;

      @UpdateDateColumn()
      public updatedAt!: Date;

    }
</code>```

Image Entity

```<code>import { CategoriesEntity } from '../../categories/entities/categories.entity';
import { ProductEntity } from '../../product/entities/product.entity';
import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
  CreateDateColumn,
  OneToMany,
} from 'typeorm';
import { UserEntity } from '../../user/entities/user.entity';

@Entity()
export class FileEntity {

  @PrimaryGeneratedColumn()
  public id!: number;

  @Column()
  public path!: string;

  @Column()
  public size!: number;

  @OneToMany(() => ProductEntity, (product) => product.image)
  public products?: ProductEntity[];

  @OneToMany(() => CategoriesEntity, (category) => category.image)
  public categories?: CategoriesEntity[];

  @OneToMany(() => UserEntity, (user) => user.avatar)
  public users?: UserEntity[];

  @CreateDateColumn()
  public createdAt!: Date;

}
</code>```

User service

```<code>public override async updateAvatar(user: IAuthUser, userAvatar: UserAvatarDTO): Promise<UpdateResult> {
    if(!fs.existsSync('./uploads/' + userAvatar.filename)) {
      throw new NotFoundException('No such file');
    }
    const files = this._commonService.getImageByName(userAvatar.filename);
    return this._usersRepository.update({ id : user.id }, { NEED CODE)  } );

  }
</code>```

Body:
need your help,i want to update user field avatar. I already have row in DB for user, and images. And dont know, how i can update this, in my file service const files: Promise<FileEntity | null> = this._commonService.getImageByName(userAvatar.filename);
i need to take id from file name and put this id to user avatar.
Thanks for help.

User Entity

import { CartEntity } from '../../cart/entities/cart.entity';
    import { FileEntity } from '../../common/entities/images.entity';
    import { OrderEntity } from '../../order/entities/order.entity';
    import {
      Entity,
      Column,
      PrimaryGeneratedColumn,
      CreateDateColumn,
      UpdateDateColumn,
      OneToMany,
      ManyToOne,
      RelationId,
    } from 'typeorm';

    export enum UserTypeEnum {
      Vendor = 'vendor',
      Customer = 'customer'
    }

    @Entity()
    export class UserEntity {

      @PrimaryGeneratedColumn()
      public id!: number;

      @Column({ nullable: true })
      public firstName?: string;

      @Column({ nullable: true })
      public lastName?: string;

      @Column({ default: false })
      public verify?: boolean;

      @Column()
      public email!: string;

      @Column()
      public password!: string;

      @Column({
        type: 'enum',
        name: 'roles',
        enum: UserTypeEnum,
        default: UserTypeEnum.Customer,
      })
      public role!: UserTypeEnum;

      @OneToMany(() => CartEntity, (cart) => cart.user)
      public carts?: CartEntity[];

      @ManyToOne(() => FileEntity, (avatar) => avatar.users)
      public avatar?: FileEntity;

      @RelationId((user: UserEntity) => user.avatar)
      public avatarId?: number;

      @OneToMany(() => OrderEntity, (order) => order.user)
      public orders?: OrderEntity[];

      @CreateDateColumn()
      public createdAt!: Date;

      @UpdateDateColumn()
      public updatedAt!: Date;

    }

Image Entity

import { CategoriesEntity } from '../../categories/entities/categories.entity';
import { ProductEntity } from '../../product/entities/product.entity';
import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
  CreateDateColumn,
  OneToMany,
} from 'typeorm';
import { UserEntity } from '../../user/entities/user.entity';

@Entity()
export class FileEntity {

  @PrimaryGeneratedColumn()
  public id!: number;

  @Column()
  public path!: string;

  @Column()
  public size!: number;

  @OneToMany(() => ProductEntity, (product) => product.image)
  public products?: ProductEntity[];

  @OneToMany(() => CategoriesEntity, (category) => category.image)
  public categories?: CategoriesEntity[];

  @OneToMany(() => UserEntity, (user) => user.avatar)
  public users?: UserEntity[];

  @CreateDateColumn()
  public createdAt!: Date;

}

User service

public override async updateAvatar(user: IAuthUser, userAvatar: UserAvatarDTO): Promise<UpdateResult> {
    if(!fs.existsSync('./uploads/' + userAvatar.filename)) {
      throw new NotFoundException('No such file');
    }
    const files = this._commonService.getImageByName(userAvatar.filename);
    return this._usersRepository.update({ id : user.id }, { NEED CODE)  } );

  }


问:
MSAL access token not refreshing -- "entry.trim not a function" error on acquireTokenSilent call
I have been tasked with understanding why our Vue app keeps getting 401 errors for users after being active for 1 hour.  The access token seems to be valid and working fine for 1 hour after logging in, but after that point it does not refresh properly.  We are using vue-msal 3.2.0.  Tokens are being store in localStorage.

Here is our axios request interceptor

axios.interceptors.request.use(
  async request => {
    // Find token in localstorage
    var tokenrespon = await store.dispatch('acquireToken', {
      scopes: ['user.read', 'offline_access'],
      getidtoken: true
    });
    var token = tokenrespon.Idtoken;
    request.headers.Authorization = `Bearer ${token}`;
    return request;
  },
  error => {
    return Promise.reject(error);
  }
);
```
<p>and here is the aqcuireToken call that gets called in the above piece:</p>
<pre class="lang-js prettyprint-override"><code>async acquireToken({ commit }, scopes = ['user.read'], getidtoken = false) {
  var msalinstance = new PublicClientApplication(state.msalConfig)

  if (!msalinstance) {
    return null
  }
  // Set scopes for token request
  const accessTokenRequest = {
    account: state.AzureLocalID,
    scopes: scopes
  }
  let tokenResp
  try {
    // 1. Try to acquire token silently
    tokenResp = await msalinstance.acquireTokenSilent(accessTokenRequest)
    commit('setToken', tokenResp)
  } catch (err) {
    // 2. Silent process might have failed so try via popup
    tokenResp = await msalinstance.acquireTokenPopup(accessTokenRequest)
    commit('setToken', tokenResp)
  }

  // Just in case check, probably never triggers
  if (!tokenResp.accessToken) {
    commit('removeToken')
    throw new Error("### accessToken not found in response, that's bad")
  }
  if (getidtoken) {
    return tokenResp.idToken
  } else {
    return tokenResp.accessToken
  }
},
</code>```

I'm getting TypeError: entry.trim is not a function on the acquireTokenSilent call in the try block.

I have changed the request interceptor to be async, it was not previously.  I also added the offline_access scope and passed that into the acquireToken but that doesnt seem to change anything.   Not sure if it is an issue with Azure/MSAL config or something in our code.

We would like for the app to auto renew the access token using the refresh token once this one hour period has been reached.

Body:
I have been tasked with understanding why our Vue app keeps getting 401 errors for users after being active for 1 hour.  The access token seems to be valid and working fine for 1 hour after logging in, but after that point it does not refresh properly.  We are using vue-msal 3.2.0.  Tokens are being store in localStorage.

Here is our axios request interceptor

axios.interceptors.request.use(
  async request => {
    // Find token in localstorage
    var tokenrespon = await store.dispatch('acquireToken', {
      scopes: ['user.read', 'offline_access'],
      getidtoken: true
    });
    var token = tokenrespon.Idtoken;
    request.headers.Authorization = `Bearer ${token}`;
    return request;
  },
  error => {
    return Promise.reject(error);
  }
);

and here is the aqcuireToken call that gets called in the above piece:

async acquireToken({ commit }, scopes = ['user.read'], getidtoken = false) {
  var msalinstance = new PublicClientApplication(state.msalConfig)

  if (!msalinstance) {
    return null
  }
  // Set scopes for token request
  const accessTokenRequest = {
    account: state.AzureLocalID,
    scopes: scopes
  }
  let tokenResp
  try {
    // 1. Try to acquire token silently
    tokenResp = await msalinstance.acquireTokenSilent(accessTokenRequest)
    commit('setToken', tokenResp)
  } catch (err) {
    // 2. Silent process might have failed so try via popup
    tokenResp = await msalinstance.acquireTokenPopup(accessTokenRequest)
    commit('setToken', tokenResp)
  }

  // Just in case check, probably never triggers
  if (!tokenResp.accessToken) {
    commit('removeToken')
    throw new Error("### accessToken not found in response, that's bad")
  }
  if (getidtoken) {
    return tokenResp.idToken
  } else {
    return tokenResp.accessToken
  }
},

I'm getting TypeError: entry.trim is not a function on the acquireTokenSilent call in the try block.

I have changed the request interceptor to be async, it was not previously.  I also added the offline_access scope and passed that into the acquireToken but that doesnt seem to change anything.   Not sure if it is an issue with Azure/MSAL config or something in our code.

We would like for the app to auto renew the access token using the refresh token once this one hour period has been reached.


问:
404 on json file when deployed in a subdirectory to azure app service
When attempting to load a json file from a blazor Web App, hosted on Azure, json is returning as a 404 when there is a different root set up (ie. wwwroot/subdir).

When the output of the blazor web app is directly in the wwwroot, the json is returned fine with no 404.

I have tried amending the web.config with the relevant mime types, but to no avail.

The app is hosted in an App Service, deployed through Github Actions.

When the app is deployed into root, (wwwroot), the json files load fine. However, when I update the base in the index.html and  in the project file so that it lives under a subdir then the json isn't loaded, and instead returns a 404. Locally it all works fine.

The json exists in the directory, as I have ftp'ed on to it, I have changed the file type to .txt and it is there and downloads fine through the browser when navigating directly to it.

I've seen a lot of comments around similar issues with the web.config, but this is fine, with the:

```<code><remove fileExtension=".json" />
</code>```

and

```<code><mimeMap fileExtension=".json" mimeType="application/json" />
</code>```

Not sure what else to try.

UPDATE 1:

99% certain it's to do with the dislike of downloading json files.

The json files have a gz alternative, which i can navigate to and download directly (e.g. zzz.json.gz) but with the .gz (zzz.json) the files still return 404.

UPDATE 2:
When viewing the logs on the server, I can see an error of "SECURITY_DENIED_BY_MIMEMAP" which then throws up the 404.

The Mimetype is definitely set, so I'm not sure what else it could be.

Body:
When attempting to load a json file from a blazor Web App, hosted on Azure, json is returning as a 404 when there is a different root set up (ie. wwwroot/subdir).

When the output of the blazor web app is directly in the wwwroot, the json is returned fine with no 404.

I have tried amending the web.config with the relevant mime types, but to no avail.

The app is hosted in an App Service, deployed through Github Actions.

When the app is deployed into root, (wwwroot), the json files load fine. However, when I update the base in the index.html and  in the project file so that it lives under a subdir then the json isn't loaded, and instead returns a 404. Locally it all works fine.

The json exists in the directory, as I have ftp'ed on to it, I have changed the file type to .txt and it is there and downloads fine through the browser when navigating directly to it.

I've seen a lot of comments around similar issues with the web.config, but this is fine, with the:

<remove fileExtension=".json" />

and

<mimeMap fileExtension=".json" mimeType="application/json" />

Not sure what else to try.

UPDATE 1:

99% certain it's to do with the dislike of downloading json files.

The json files have a gz alternative, which i can navigate to and download directly (e.g. zzz.json.gz) but with the .gz (zzz.json) the files still return 404.

UPDATE 2:
When viewing the logs on the server, I can see an error of "SECURITY_DENIED_BY_MIMEMAP" which then throws up the 404.

The Mimetype is definitely set, so I'm not sure what else it could be.


问:
Pulumi: Instead of using Output.Tuple, how can I reference a single parameter to access a future value?
Instead of using Output.Tuple to access a future value of a resource (yet to be created), how can I use only a single parameter to accomplish the same thing?

Note: I tried using Output.Create and observed a resource not found exception.

Code:

```<code>var appResult =
    Output.Tuple(functionApps.First().Name, functionApps.First().Name) // I shouldn't need a tuple for this
          .Apply(async tuple => await

              ListWebAppHostKeys.InvokeAsync(new ListWebAppHostKeysArgs
              {
                  Name = tuple.Item1,
                  ResourceGroupName = resourceGroup.GetResourceName()
              }));

var functionKeys = appResult.Apply(r => r.FunctionKeys);
</code>```

Body:
Instead of using Output.Tuple to access a future value of a resource (yet to be created), how can I use only a single parameter to accomplish the same thing?

Note: I tried using Output.Create and observed a resource not found exception.

Code:

var appResult =
    Output.Tuple(functionApps.First().Name, functionApps.First().Name) // I shouldn't need a tuple for this
          .Apply(async tuple => await

              ListWebAppHostKeys.InvokeAsync(new ListWebAppHostKeysArgs
              {
                  Name = tuple.Item1,
                  ResourceGroupName = resourceGroup.GetResourceName()
              }));

var functionKeys = appResult.Apply(r => r.FunctionKeys);


问:
libVLC and libvlcpp - how to use media.addOption()
I can use the vlc player from the command line on a Linux Mint PC to both play a video locally, and stream it such that I can view it on another device in the same network (i.e., using vlc player on my phone).

At the command line, I do this:

```<code>vlc /home/matt/videos/TheRobe.mkv --sout '#duplicate{dst=display,dst=std{access=http,mux=mkv,dst=:8090/stream}}'
</code>```

How can I do this using libvlcpp? The following was one of (many) attempts:

```<code>// g++ streamer.cpp -I/usr/local/include -L/usr/local/lib -o streamer -lvlc

#include "vlcpp/vlc.hpp"
#include <thread>

int main(int argc, char** argv)
{
    auto instance = VLC::Instance(0, nullptr);
    auto media = VLC::Media(instance, "/home/matt/videos/TheRobe.mkv", VLC::Media::FromPath);
    media.addOption(":sout='#duplicate{dst=display,dst=std{access=http,mux=mkv,dst=:8090/stream}}'");

    auto mp = VLC::MediaPlayer(media);
    mp.play();
    std::this_thread::sleep_for( std::chrono::seconds( 3600 ) );

    return 0;
}
</code>```

But I encounter errors when I try to run it:

```<code>$ ./streamer
[00007f8c940014a0] stream_out_standard stream out error: no mux specified or found by extension
[00007f8c94001140] main stream output error: stream chain failed for `standard{mux="",access="",dst="'#duplicate{dst=display,dst=std{access=http,mux=mkv,dst=:8090/stream}}'"}'
[000055d3d9ca6490] main input error: cannot start stream output instance, aborting
</code>```

What am I doing wrong?

NB there is a similar question, but it uses the libVLC interface, whereas I want to use libvlcpp if possible.

Body:
I can use the vlc player from the command line on a Linux Mint PC to both play a video locally, and stream it such that I can view it on another device in the same network (i.e., using vlc player on my phone).

At the command line, I do this:

vlc /home/matt/videos/TheRobe.mkv --sout '#duplicate{dst=display,dst=std{access=http,mux=mkv,dst=:8090/stream}}'

How can I do this using libvlcpp? The following was one of (many) attempts:

// g++ streamer.cpp -I/usr/local/include -L/usr/local/lib -o streamer -lvlc

#include "vlcpp/vlc.hpp"
#include <thread>

int main(int argc, char** argv)
{
    auto instance = VLC::Instance(0, nullptr);
    auto media = VLC::Media(instance, "/home/matt/videos/TheRobe.mkv", VLC::Media::FromPath);
    media.addOption(":sout='#duplicate{dst=display,dst=std{access=http,mux=mkv,dst=:8090/stream}}'");

    auto mp = VLC::MediaPlayer(media);
    mp.play();
    std::this_thread::sleep_for( std::chrono::seconds( 3600 ) );

    return 0;
}

But I encounter errors when I try to run it:

$ ./streamer
[00007f8c940014a0] stream_out_standard stream out error: no mux specified or found by extension
[00007f8c94001140] main stream output error: stream chain failed for `standard{mux="",access="",dst="'#duplicate{dst=display,dst=std{access=http,mux=mkv,dst=:8090/stream}}'"}'
[000055d3d9ca6490] main input error: cannot start stream output instance, aborting

What am I doing wrong?

NB there is a similar question, but it uses the libVLC interface, whereas I want to use libvlcpp if possible.


问:
How can I convert a MSBuild VS C++ shared library project from targeting Windows x64 to Android ARM64?
I don't want to use CMake. Only MSBuild.
Any directional help at all, would be appreciated.

Bonus: Is there a way to do this without manually editing the .vcxproj file?

I have the Android NDK & SDK installed and working to generate .so files in QtCreator. In VS, I've tried changing the "target platform" in a project's settings, but that only seems to change the CPU arch, not the OS target.


问:
Puppeteer fails to parse deep objects in DOM
I've been trying out Puppeteer to scrap profile pictures from Instagram. The goal is: with an instagram username, go to https://instagram.com/username, find profile picture URL in DOM and get the src attribute of the profile picture.

```<code>const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://instagram.com/tyva.tlse');
const arrayOfImgElements = await page.$$("img");
console.log(arrayOfImgElements);
</code>```

I expected this code to return a table with all  elements on the page. However it shows only 2 elements of the Instagram page: the Instagram and Meta logo. It seems that the "deepest" elements in the page's DOM are not found.

It seems to work with a 5 second delay. Seems that the deep data needs more time to load.

Would you have a solution or workaround to parse these images that are ignored?

Body:
I've been trying out Puppeteer to scrap profile pictures from Instagram. The goal is: with an instagram username, go to https://instagram.com/username, find profile picture URL in DOM and get the src attribute of the profile picture.

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://instagram.com/tyva.tlse');
const arrayOfImgElements = await page.$$("img");
console.log(arrayOfImgElements);

I expected this code to return a table with all  elements on the page. However it shows only 2 elements of the Instagram page: the Instagram and Meta logo. It seems that the "deepest" elements in the page's DOM are not found.

It seems to work with a 5 second delay. Seems that the deep data needs more time to load.

Would you have a solution or workaround to parse these images that are ignored?


问:
HTML metatag viewport initial-scale not working
According to the MDN documentation, the initial-scale is responsible to set the default zoom when the page loads. This minimalist HTML5 example sets the initial-scale to 10x, which is the maximum valid value for this setting but it seems to be ignored in Google Chrome and Firefox as well.

Why it's not working? There is no errors or warnings in the console.

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=10.0">
  <title>Hello page</title>

This text should be really big!

```


问:
Gnuplot module in Python
How can I include Gnuplot in Python 3.5.
I am doing python programming in Spyder 3.

Simply 'import Gnuplot' statement in the program does not work after the installation of Gnuplot-y.

Title: Gnuplot module in Python


问:
why the label doesn't clear itself before playing the voice?
When I press the Button Play_Button I would like first the label result to clear and then to read the country choosen from the dict with pttsx3 and then assign the corrispondent value from the dict to the label result.
It work fine but just doesn't clear the label</p>
```<code>Countries = {
        # 'Englang: 100,
        # "Italy": 150,
        # "Argentina": 120,
}
</code>```
```<code>class MyGrid(Widget):

    def Play_Button(self):

**# DON'T UNDESRTAND WHY THIS LABEL DOESN'T CLEAR**
        self.result.text = " "

        global country, num
        country, num = random.choice(list(Countries.items()))

        engine = pyttsx3.init()
        engine.say(country)
        engine.runAndWait()
        engine.stop()
        self.result.text = str(num)
</code>```
```<code>**# THIS IS THE KIVY PART**
<MyGrid>

    result: result
    play: Play

    GridLayout:
        cols: 1

        Label:
            text: ''
            id: result
            font_size: 50
        Button:
            text: 'Play'
            id: Play
            on_press: root.Play_Button()
</code>```

Body:
When I press the Button Play_Button I would like first the label result to clear and then to read the country choosen from the dict with pttsx3 and then assign the corrispondent value from the dict to the label result.
It work fine but just doesn't clear the label

Countries = {
        # 'Englang: 100,
        # "Italy": 150,
        # "Argentina": 120,
}

class MyGrid(Widget):

    def Play_Button(self):

**# DON'T UNDESRTAND WHY THIS LABEL DOESN'T CLEAR**
        self.result.text = " "

        global country, num
        country, num = random.choice(list(Countries.items()))

        engine = pyttsx3.init()
        engine.say(country)
        engine.runAndWait()
        engine.stop()
        self.result.text = str(num)

**# THIS IS THE KIVY PART**
<MyGrid>

    result: result
    play: Play

    GridLayout:
        cols: 1

        Label:
            text: ''
            id: result
            font_size: 50
        Button:
            text: 'Play'
            id: Play
            on_press: root.Play_Button()


问:
Wordpress Phpmyadmin SQL query for replace url in category descrption
```<code>UPDATE wpqv_term_taxonomy
SET description = replace(description, 'https://old.com/', 'https://new.com/');

UPDATE wpqv_term_taxonomy
SET description = replace(description, 'https://old.com/', 'https://new.com/');
</code>```


问:
helm install tekton cdf/tekton-pipeline fails with INSTALLATION FAILED no matches for kind "PodSecurityPolicy" in version "policy/v1beta1"
I am trying to install tekton helm chart into my local K8s cluster created by Kind on Windows 10. I run the following command

```<code>helm install tekton cdf/tekton-pipeline
</code>```

and it fails with

```<code>Error: INSTALLATION FAILED: unable to build kubernetes objects from release manifest: [resource mapping not found for name: "tekton-pipelines" namespace: "" from "": no matches for kind "PodSecurityPolicy" in version "policy/v1beta1"
ensure CRDs are installed first, resource mapping not found for name: "tekton-pipelines-webhook" namespace: "tekton-pipelines" from "": no matches for kind "HorizontalPodAutoscaler" in version "autoscaling/v2beta1"
ensure CRDs are installed first]
</code>```

Body:
I am trying to install tekton helm chart into my local K8s cluster created by Kind on Windows 10. I run the following command

helm install tekton cdf/tekton-pipeline

and it fails with

Error: INSTALLATION FAILED: unable to build kubernetes objects from release manifest: [resource mapping not found for name: "tekton-pipelines" namespace: "" from "": no matches for kind "PodSecurityPolicy" in version "policy/v1beta1"
ensure CRDs are installed first, resource mapping not found for name: "tekton-pipelines-webhook" namespace: "tekton-pipelines" from "": no matches for kind "HorizontalPodAutoscaler" in version "autoscaling/v2beta1"
ensure CRDs are installed first]


问:
How to Convert Response to an PDF file in JavaScript
I am working on an project where I am sending PDF file inputed by user as an request to an API to get it compressed but I am getting back an Response as an String
My question is how can I convert that Response to an PDF File allow user to Download it

const fileInput = document.getElementById("input");

document.querySelector(".files").addEventListener("click", () => {
  console.log("hello");
  var form = new FormData();
  form.append("inputFile", fileInput.files[0], "file");

  var settings = {
    url: "https://api.cloudmersive.com/convert/edit/pdf/optimize/reduce-file-size",
    method: "POST",
    timeout: 0,
    headers: {
      quality: "0.3",
      "Content-Type": "multipart/form-data",
      Apikey: "44004d43-b7af-42be-bcfb-9def6f06957f",
    },
    processData: false,
    mimeType: "multipart/form-data",
    contentType: false,
    data: form,
  };

  $.ajax(settings).done(function (response) {
    console.log(response);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
  </head>
  <body>
    <input type="file" name="" id="input" />
    <button class="files">Submit</button>
    <script src="/s2.js"></script>
  </body>
</html></code>```

Here is What Output I am Getting

Body:
I am working on an project where I am sending PDF file inputed by user as an request to an API to get it compressed but I am getting back an Response as an String
My question is how can I convert that Response to an PDF File allow user to Download it

const fileInput = document.getElementById("input");

document.querySelector(".files").addEventListener("click", () => {
  console.log("hello");
  var form = new FormData();
  form.append("inputFile", fileInput.files[0], "file");

  var settings = {
    url: "https://api.cloudmersive.com/convert/edit/pdf/optimize/reduce-file-size",
    method: "POST",
    timeout: 0,
    headers: {
      quality: "0.3",
      "Content-Type": "multipart/form-data",
      Apikey: "44004d43-b7af-42be-bcfb-9def6f06957f",
    },
    processData: false,
    mimeType: "multipart/form-data",
    contentType: false,
    data: form,
  };

  $.ajax(settings).done(function (response) {
    console.log(response);
  });
});

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>

    <input type="file" name="" id="input" />
    <button class="files">Submit</button>

Here is What Output I am Getting


问:
How to get driving distance between two points in Python
Using Python, I'm working with a dataset of taxi trips, and each row is a trip completed. The related columns here are the trip miles (trip distance), pickup_location and dropoff_location. The pick up and drop off locations are represented as Multipolygons.

What I have done is I pick a random point in pickup_location and a random point in dropoff_location, but the challenge I'm facing is how to find two points with driving distance that satisfy:

```<code>abs(trip miles - distance(start_point, end_point)) <= 0.0005
</code>```

or

```<code>diff = abs(trip miles - distance(start_point, end_point))/trip miles
</code>```

I have tried haversine and geopy, but I don't think they provide me with the driving distance that I need. Since this is for educational goals, I can't use Google maps services because they are not free nor cheap.

Any suggestions please?

Body:
Using Python, I'm working with a dataset of taxi trips, and each row is a trip completed. The related columns here are the trip miles (trip distance), pickup_location and dropoff_location. The pick up and drop off locations are represented as Multipolygons.

What I have done is I pick a random point in pickup_location and a random point in dropoff_location, but the challenge I'm facing is how to find two points with driving distance that satisfy:

abs(trip miles - distance(start_point, end_point)) <= 0.0005

or

diff = abs(trip miles - distance(start_point, end_point))/trip miles

I have tried haversine and geopy, but I don't think they provide me with the driving distance that I need. Since this is for educational goals, I can't use Google maps services because they are not free nor cheap.

Any suggestions please?


问:
Spring Retryable annotation indirect call not retrying
I have a method on a service annotated with @Retryable. If I call that method direct in a Controller the retry logic works. When I call that method indirectly through a wrapper method the retry logic does not get triggered.

```<code>public class SomeService{
  // When calling this there is no retry
  public void wrapper(){
    isOn();
  }

  // Calling this direct the retry works
  @Retryable(maxAttempts = 8)
  public boolean isOn() {
    System.out.println("Testing");
    throw new RuntimeException("Failing");
  }
}
</code>```

I want to call the method with retry logic because there is a rather unstable endpoint that needs to be connected to. After that any errors would be valid and no retry is needed.

Is there a way to make sure the nested retry logic runs without having to retry the entire wrapping method?

Body:
I have a method on a service annotated with @Retryable. If I call that method direct in a Controller the retry logic works. When I call that method indirectly through a wrapper method the retry logic does not get triggered.

public class SomeService{
  // When calling this there is no retry
  public void wrapper(){
    isOn();
  }

  // Calling this direct the retry works
  @Retryable(maxAttempts = 8)
  public boolean isOn() {
    System.out.println("Testing");
    throw new RuntimeException("Failing");
  }
}

I want to call the method with retry logic because there is a rather unstable endpoint that needs to be connected to. After that any errors would be valid and no retry is needed.

Is there a way to make sure the nested retry logic runs without having to retry the entire wrapping method?


问:
How does one stop the browser from navigating to a new URI after a user changes a field
On a landing page, we have dynamic fields loading by changing the GET request.
/gifts/?amount=5.00&gift-options=monthly

Which pre-populates the fields Gift Amount and Recurrence.

Once the form has this information it loads secure credit card fields through a PCI 3rd party and begin the transaction. Over the last 2 years we have noticed a new "feature" arise in browsers. Now when the user updates the amount, or any field that matches a value in the GET request, the browser then updates the GET string to the new value and navigates to the new URL. This is consistent even when we remove all javscript from the page and test this with no active code (js) on the form. So I know this is not from a module or javascript code we are using.

For example, if the user changes the amount to $5.01, the browsers now drop the current page and load the url: /gifts/?amount=5.01&options=monthly which reloads the page. Snippet from the browser console:

This is a terrible experience for many reasons including:

We drop a credit card transaction in process and start a new record

It looks like the user is scraping the site by requesting many urls with variations

The page is reloaded while the user is engaging the fields

The users' entered form information is lost

Options which they have changed, particularly One-time / Monthly are reset to the original which makes it looks like we are trying to force the results.

The front end of the form already re-negotiates the transaction if the user changes the amount, correctly. But we cannot manage that if the browser changes the page before that routine runs.

Questions:

What is this new browser "feature" called? I cannot find reference to this functionality in RFC's.

Is there a means of preventing this from happening natively? Otherwise I have to develop a new request routine to hide the prescribed amounts from the browser but I want to keep our secure forms and functionality above board, without causing a bad user experience.


问:
How to download file mime_type:application/octet-stream using laravel 9
Using Storage

In older version of Laravel is working fine but Laravel9 is creating an issue

File Mime type: application/octet-stream

```<code>return Storage::download($shippingLabelPrn);
</code>```

Laravel9 shows error

I research the file system and found one code

```<code>/vendor/league/flysystem/src/Local/FallbackMimeTypeDetector.php

class FallbackMimeTypeDetector implements MimeTypeDetector {

    private const INCONCLUSIVE_MIME_TYPES = [
        'application/x-empty',
        'text/plain',
        'text/x-asm',
        'application/octet-stream',
        'inode/x-empty',
    ];

    public function __construct(
            private MimeTypeDetector $detector,
            private array $inconclusiveMimetypes = self::INCONCLUSIVE_MIME_TYPES
    ) {}

    public function detectMimeTypeFromFile(string $path): ?string {
        $mimeType = $this->detector->detectMimeTypeFromFile($path);
        if ($mimeType !== null && !in_array($mimeType, $this->inconclusiveMimetypes)) { <-------this line ignore
            return $mimeType;
        }
        return $this->detector->detectMimeTypeFromPath($path);
    }
}
</code>```

Some mime types here are "INCONCLUSIVE_MIME_TYPES" which exclude.

So here the code extracts it even after getting the mimetype

So, how to download this type of mime files?

Body:
Using Storage

In older version of Laravel is working fine but Laravel9 is creating an issue

File Mime type: application/octet-stream

return Storage::download($shippingLabelPrn);

Laravel9 shows error

I research the file system and found one code

/vendor/league/flysystem/src/Local/FallbackMimeTypeDetector.php

class FallbackMimeTypeDetector implements MimeTypeDetector {

    private const INCONCLUSIVE_MIME_TYPES = [
        'application/x-empty',
        'text/plain',
        'text/x-asm',
        'application/octet-stream',
        'inode/x-empty',
    ];

    public function __construct(
            private MimeTypeDetector $detector,
            private array $inconclusiveMimetypes = self::INCONCLUSIVE_MIME_TYPES
    ) {}

    public function detectMimeTypeFromFile(string $path): ?string {
        $mimeType = $this->detector->detectMimeTypeFromFile($path);
        if ($mimeType !== null && !in_array($mimeType, $this->inconclusiveMimetypes)) { <-------this line ignore
            return $mimeType;
        }
        return $this->detector->detectMimeTypeFromPath($path);
    }
}

Some mime types here are "INCONCLUSIVE_MIME_TYPES" which exclude.

So here the code extracts it even after getting the mimetype

So, how to download this type of mime files?


问:
How do I give docker permissions to execute a file outside of a container?
I have an application on a spring-boot. The essence of the application is simple: using the first end-point I load a file with docker-compose.yml, using the second end-point I execute shell script "docker-compose up".

Of course I have volume mapping of the folder to an external system.

And when I have the application running on the local computer - everything works great. But when I wrap the application in a docker container, the application doesn't see the file when executing it. That is, it loads the file fine, but can't execute, citing that the file doesn't exist.

My guess is that the docker doesn't have enough permissions to read or execute the shell script. Am I thinking correctly and if so, how can this be resolved?

p.s. If anything, docker-compose to raise the container just with postgres+pgadmin. It doesn't really matter, just thought I'd clarify that this file is not for this spring application.


问:
Can we implement Azure managed Identity between two Azure web app?
We have two azure web apps which are using Azure AD App Registration for authentication and authorization.
As part of improving the security we are planning to implement this using managed identity.

I know we can use managed identity for connecting to Database and Key Vaults. Can we use the same for connecting between web apps:


问:
Instagram Webhook Error, cannot load profile for <igsid>
I'm trying to get instagram messages with webhooks. I cloned the example "OC Coast Clothing IG" in github and upload on heroku.

However, when I test the webhook "messages" I get an error and my server crashes.

Here is my logs:

```<code>Could not load profile for 12334(this is the test id): Bad RequestTypeError: Cannot read properties of undefined (reading 'name')
2022-12-15T17:43:32.077647+00:00 app[web.1]:     at Receive.handleTextMessage (/app/services/receive.js:78:45)
2022-12-15T17:43:32.077647+00:00 app[web.1]:     at Receive.handleMessage (/app/services/receive.js:45:28)
2022-12-15T17:43:32.077649+00:00 app[web.1]:     at /app/app.js:141:31
2022-12-15T17:43:32.077650+00:00 app[web.1]:     at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
2022-12-15T17:43:32.078205+00:00 app[web.1]: /app/services/receive.js:238
2022-12-15T17:43:32.078206+00:00 app[web.1]:         id: this.user.igsid
2022-12-15T17:43:32.078206+00:00 app[web.1]:                       ^
2022-12-15T17:43:32.078207+00:00 app[web.1]:
2022-12-15T17:43:32.078207+00:00 app[web.1]: TypeError: Cannot read properties of undefined (reading 'igsid')
2022-12-15T17:43:32.078208+00:00 app[web.1]:     at Receive.sendMessage (/app/services/receive.js:238:23)
2022-12-15T17:43:32.078208+00:00 app[web.1]:     at Receive.handleMessage (/app/services/receive.js:71:12)
2022-12-15T17:43:32.078209+00:00 app[web.1]:     at /app/app.js:141:31
2022-12-15T17:43:32.078209+00:00 app[web.1]:     at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
2022-12-15T17:43:32.078209+00:00 app[web.1]:
</code>```

I have all the needed permissions, I can see the received webhook and the JSON data. I didn't change the example github code. Do I need to install some libraries in heroku terminal or what?

Body:
I'm trying to get instagram messages with webhooks. I cloned the example "OC Coast Clothing IG" in github and upload on heroku.

However, when I test the webhook "messages" I get an error and my server crashes.

Here is my logs:

Could not load profile for 12334(this is the test id): Bad RequestTypeError: Cannot read properties of undefined (reading 'name')
2022-12-15T17:43:32.077647+00:00 app[web.1]:     at Receive.handleTextMessage (/app/services/receive.js:78:45)
2022-12-15T17:43:32.077647+00:00 app[web.1]:     at Receive.handleMessage (/app/services/receive.js:45:28)
2022-12-15T17:43:32.077649+00:00 app[web.1]:     at /app/app.js:141:31
2022-12-15T17:43:32.077650+00:00 app[web.1]:     at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
2022-12-15T17:43:32.078205+00:00 app[web.1]: /app/services/receive.js:238
2022-12-15T17:43:32.078206+00:00 app[web.1]:         id: this.user.igsid
2022-12-15T17:43:32.078206+00:00 app[web.1]:                       ^
2022-12-15T17:43:32.078207+00:00 app[web.1]:
2022-12-15T17:43:32.078207+00:00 app[web.1]: TypeError: Cannot read properties of undefined (reading 'igsid')
2022-12-15T17:43:32.078208+00:00 app[web.1]:     at Receive.sendMessage (/app/services/receive.js:238:23)
2022-12-15T17:43:32.078208+00:00 app[web.1]:     at Receive.handleMessage (/app/services/receive.js:71:12)
2022-12-15T17:43:32.078209+00:00 app[web.1]:     at /app/app.js:141:31
2022-12-15T17:43:32.078209+00:00 app[web.1]:     at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
2022-12-15T17:43:32.078209+00:00 app[web.1]:

I have all the needed permissions, I can see the received webhook and the JSON data. I didn't change the example github code. Do I need to install some libraries in heroku terminal or what?


问:
How to get an alert once on a trend on a supertrend, in pinescript,with loop or another way?
How to get an alert once on a supertrend trend,I think with while i can solve(but my knowledge is not enough),maybe is another way to solve my problem.
I need to skip the first signal(on down/up trend) and enter the second alert, and this signal  alert one time per supertrend trend.

I describe signals below in the code.

```<code>//@version=5
indicator("My-Supertrend", overlay=true, timeframe="", timeframe_gaps=true)

atrPeriod = input(13, "ATR Length")
atrPeriod2 = input(21, "ATR Length2")

factor = input.float(3.0, "Factor", step = 0.01)
factor2 = input.float(7.0, "Factor2", step = 0.01)

[supertrend, direction] = ta.supertrend(factor, atrPeriod)
[supertrend2, direction2] = ta.supertrend(factor2, atrPeriod2)

//ST 1
bodyMiddle = plot((open + close) / 2, display=display.none)
upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = #00cf42, style=plot.style_linebr,linewidth=1)
downTrend = plot(direction < 0? na : supertrend, "Down Trend", color = #bb2c01, style=plot.style_linebr,linewidth=1)
//ST 2
bodyMiddle2 = plot((open + close) / 2, display=display.none)
upTrend2 = plot(direction2 < 0 ? supertrend2 : na, "Up Trend", color = #00cf42, style=plot.style_linebr,linewidth=3)
downTrend2 = plot(direction2 < 0? na : supertrend2, "Down Trend", color = #bb2c01, style=plot.style_linebr,linewidth=3)

//ST1 color
fill(bodyMiddle, upTrend, color.new(#95bd06, 80), fillgaps=false)
fill(bodyMiddle, downTrend, color.new(#0692bd, 80), fillgaps=false)

//ST2 color
fill(bodyMiddle2, upTrend2, color.new(#5abd13, 70), fillgaps=false)
fill(bodyMiddle2, downTrend2, color.new(#bd3006,70), fillgaps=false)

//Logic
down_upTrend=direction>0 and direction2<0 and direction[1]<0
up_upTrend=direction<0 and direction2<0 and direction[1]>0
up_downTrend=direction<0 and direction2>0 and direction[1]>0
down_downTrend=direction>0 and direction2>0 and direction[1]<0

//For short
while direction2>0
    up_downTrend
    continue
    down_downTrend
    break
//For Long
while direction2<0
    down_upTrend
    continue
    up_upTrend
    break

plotshape(up_upTrend,style=shape.triangleup,location=location.belowbar,size=size.normal,color=color.rgb(27, 182, 27))
plotshape(up_downTrend,style=shape.triangleup,location=location.belowbar,size=size.normal,color=color.rgb(20, 112, 20))

plotshape(down_upTrend,style=shape.triangledown,location=location.abovebar,size=size.normal,color=color.rgb(255, 0, 0))
plotshape(down_downTrend,style=shape.triangledown,location=location.abovebar,size=size.normal,color=color.rgb(141, 21, 21))

alertcondition(up_upTrend or down_downTrend,"Long/Short","Signal")

</code>```

I try to solve with while loop(and i describe my logic in while loop),but while dont work like I think.

Body:
How to get an alert once on a supertrend trend,I think with while i can solve(but my knowledge is not enough),maybe is another way to solve my problem.
I need to skip the first signal(on down/up trend) and enter the second alert, and this signal  alert one time per supertrend trend.

I describe signals below in the code.

//@version=5
indicator("My-Supertrend", overlay=true, timeframe="", timeframe_gaps=true)

atrPeriod = input(13, "ATR Length")
atrPeriod2 = input(21, "ATR Length2")

factor = input.float(3.0, "Factor", step = 0.01)
factor2 = input.float(7.0, "Factor2", step = 0.01)

[supertrend, direction] = ta.supertrend(factor, atrPeriod)
[supertrend2, direction2] = ta.supertrend(factor2, atrPeriod2)

//ST 1
bodyMiddle = plot((open + close) / 2, display=display.none)
upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = #00cf42, style=plot.style_linebr,linewidth=1)
downTrend = plot(direction < 0? na : supertrend, "Down Trend", color = #bb2c01, style=plot.style_linebr,linewidth=1)
//ST 2
bodyMiddle2 = plot((open + close) / 2, display=display.none)
upTrend2 = plot(direction2 < 0 ? supertrend2 : na, "Up Trend", color = #00cf42, style=plot.style_linebr,linewidth=3)
downTrend2 = plot(direction2 < 0? na : supertrend2, "Down Trend", color = #bb2c01, style=plot.style_linebr,linewidth=3)

//ST1 color
fill(bodyMiddle, upTrend, color.new(#95bd06, 80), fillgaps=false)
fill(bodyMiddle, downTrend, color.new(#0692bd, 80), fillgaps=false)

//ST2 color
fill(bodyMiddle2, upTrend2, color.new(#5abd13, 70), fillgaps=false)
fill(bodyMiddle2, downTrend2, color.new(#bd3006,70), fillgaps=false)

//Logic
down_upTrend=direction>0 and direction2<0 and direction[1]<0
up_upTrend=direction<0 and direction2<0 and direction[1]>0
up_downTrend=direction<0 and direction2>0 and direction[1]>0
down_downTrend=direction>0 and direction2>0 and direction[1]<0

//For short
while direction2>0
    up_downTrend
    continue
    down_downTrend
    break
//For Long
while direction2<0
    down_upTrend
    continue
    up_upTrend
    break

plotshape(up_upTrend,style=shape.triangleup,location=location.belowbar,size=size.normal,color=color.rgb(27, 182, 27))
plotshape(up_downTrend,style=shape.triangleup,location=location.belowbar,size=size.normal,color=color.rgb(20, 112, 20))

plotshape(down_upTrend,style=shape.triangledown,location=location.abovebar,size=size.normal,color=color.rgb(255, 0, 0))
plotshape(down_downTrend,style=shape.triangledown,location=location.abovebar,size=size.normal,color=color.rgb(141, 21, 21))

alertcondition(up_upTrend or down_downTrend,"Long/Short","Signal")

I try to solve with while loop(and i describe my logic in while loop),but while dont work like I think.


问:
Excel VBA How to delete shape thats within the group
I am beginner. I am trying to delete shapes in the given worksheet. If shapes are not grouped then the sub works but if the shapes are grouped it doesn't.

it still loops thru the shape but it seems that it cant delete it..

```<code>
Sub DeleteShape(SheetName As String, ShapeName As String)
    Dim shp As Shape
    For Each shp In ThisWorkbook.Sheets(SheetName).Shapes
        If shp.Name = ShapeName Then
        shp.Delete
        End If
    Next
End Sub

</code>```

Body:
I am beginner. I am trying to delete shapes in the given worksheet. If shapes are not grouped then the sub works but if the shapes are grouped it doesn't.

it still loops thru the shape but it seems that it cant delete it..

Sub DeleteShape(SheetName As String, ShapeName As String)
    Dim shp As Shape
    For Each shp In ThisWorkbook.Sheets(SheetName).Shapes
        If shp.Name = ShapeName Then
        shp.Delete
        End If
    Next
End Sub


问:
Patching Class To Return AsyncMock Returns MagicMock
```<code># a.py
import BaseClass

class ChildClass(BaseClass):
   async def do_something():
      pass

child_instance = ChildClass()

async def method_a:
   await child_instance.do_something()
</code>```
```<code>@pytest.mark.asyncio
async def test_method_a():
   mock_class = AsyncMock()
   mock_class.do_something = AsyncMock()
   mocker.patch("a.ChildClass", return_value=mock_class)  # also tried patching "a.child_instance"

   await method_a()
</code>```

I want to mock the child class but I keep running into magicmock is not awaitable, even though I'm setting the return value to be an asyncmock. How can I get my patch of the class/and or global child instance to return an awaitable asyncmock?

Body:
# a.py
import BaseClass

class ChildClass(BaseClass):
   async def do_something():
      pass

child_instance = ChildClass()

async def method_a:
   await child_instance.do_something()

@pytest.mark.asyncio
async def test_method_a():
   mock_class = AsyncMock()
   mock_class.do_something = AsyncMock()
   mocker.patch("a.ChildClass", return_value=mock_class)  # also tried patching "a.child_instance"

   await method_a()

I want to mock the child class but I keep running into magicmock is not awaitable, even though I'm setting the return value to be an asyncmock. How can I get my patch of the class/and or global child instance to return an awaitable asyncmock?


问:
socket.io application keeps loading
Why does my socket.io webapplication keeps loading, i've implemented auth with certifications, but when i try to access localhost, it keeps loading. ive tried follow this doc, but dosent help:https://socket.io/docs/v3/client-initialization/
i dont get any error.

server.s

```<code>
'use strict';

// Setup basic express server
var express = require('express');
var app = express();
var port = process.env.PORT || 4000;
var crypto = require('crypto');
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('./data/db.sqlite');
const bcrypt = require('bcrypt');
const tls = require('tls');

var validator = require('validator');

// Routing
app.use(express.static(__dirname + '/public'));
app.use(express.json());

// Chatroom

// usernames which are currently connected to the chat
var usernames = {};
var numUsers = 0;

const fs = require("fs");
const server = require("https").createServer({
  cert: fs.readFileSync("./server-cert.pem"),
  key: fs.readFileSync("./server-key.pem")
});

server.listen(port, function () {
  console.log('Server listening at port %d', port);
});
const io = require("socket.io")(server);

io.on('connection', function (socket) {
console.log("works")

}

</code>```

client.js

```<code>  const fs = require("fs");
const socket = require("socket.io-client")(4000, {
  ca: fs.readFileSync("./server-cert.pem")
});

socket.on("connect_error", (err) => {
  console.log(`connect_error due to ${err.message}`);
});

</code>```

Title: socket.io application keeps loading

Body:
Why does my socket.io webapplication keeps loading, i've implemented auth with certifications, but when i try to access localhost, it keeps loading. ive tried follow this doc, but dosent help:https://socket.io/docs/v3/client-initialization/
i dont get any error.

server.s

'use strict';

// Setup basic express server
var express = require('express');
var app = express();
var port = process.env.PORT || 4000;
var crypto = require('crypto');
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('./data/db.sqlite');
const bcrypt = require('bcrypt');
const tls = require('tls');

var validator = require('validator');

// Routing
app.use(express.static(__dirname + '/public'));
app.use(express.json());

// Chatroom

// usernames which are currently connected to the chat
var usernames = {};
var numUsers = 0;

const fs = require("fs");
const server = require("https").createServer({
  cert: fs.readFileSync("./server-cert.pem"),
  key: fs.readFileSync("./server-key.pem")
});

server.listen(port, function () {
  console.log('Server listening at port %d', port);
});
const io = require("socket.io")(server);

io.on('connection', function (socket) {
console.log("works")

}

client.js

  const fs = require("fs");
const socket = require("socket.io-client")(4000, {
  ca: fs.readFileSync("./server-cert.pem")
});

socket.on("connect_error", (err) => {
  console.log(`connect_error due to ${err.message}`);
});


问:
PostGIS - Assign value based on ST_Intersects and ST_Area
I have two data sets, US County boundaries (tiger.counties2020) and parcel data (temp.parcel). I would like to assign a county geoid to the parcel data based on a majority of the parcel polygon being within a county boundary. In some cases these parcel polygons overlap multiple counties, but I would like to assign the geoid to the county that the parcel has most of its area in.

```<code>UPDATE
    temp.parcel
SET
    geoid_majority = upd.geoid
FROM
    tiger.counties2020 upd
WHERE
    upd.geoid = '00000'
    AND ST_Intersects(temp.parcel.geom_polygon, upd.geom) = TRUE
    AND 51 <= 100 *(
        ST_Area(
            ST_Intersection(temp.parcel.geom_polygon, upd.geom)
        ) / LEAST(
            ST_Area(temp.parcel.geom_polygon),
            ST_Area(upd.geom)
        )
    )
    AND geoid_majority IS NULL;
</code>```

is what has yielded me the most results, however I still have parcels with a NULL value for geoid_majority

Body:
I have two data sets, US County boundaries (tiger.counties2020) and parcel data (temp.parcel). I would like to assign a county geoid to the parcel data based on a majority of the parcel polygon being within a county boundary. In some cases these parcel polygons overlap multiple counties, but I would like to assign the geoid to the county that the parcel has most of its area in.

UPDATE
    temp.parcel
SET
    geoid_majority = upd.geoid
FROM
    tiger.counties2020 upd
WHERE
    upd.geoid = '00000'
    AND ST_Intersects(temp.parcel.geom_polygon, upd.geom) = TRUE
    AND 51 <= 100 *(
        ST_Area(
            ST_Intersection(temp.parcel.geom_polygon, upd.geom)
        ) / LEAST(
            ST_Area(temp.parcel.geom_polygon),
            ST_Area(upd.geom)
        )
    )
    AND geoid_majority IS NULL;

is what has yielded me the most results, however I still have parcels with a NULL value for geoid_majority


问:
how to remove footer in flutter inappwebview
I have been able to remove footer in flutter webview but I am not able to remove footer in flutter inappwebview.</p>
```<code>webViewController
    .evaluateJavascript(
        source: "javascript:(function() { " +
            "var head = document.getElementsByClassName('site-footer')[0].style.display = 'none'; " +
            "})()")
    .then((value) =>
        debugPrint('Page finished loading Javascript'))
    .catchError((onError) => debugPrint('$onError'));
</code>```

Body:
I have been able to remove footer in flutter webview but I am not able to remove footer in flutter inappwebview.

webViewController
    .evaluateJavascript(
        source: "javascript:(function() { " +
            "var head = document.getElementsByClassName('site-footer')[0].style.display = 'none'; " +
            "})()")
    .then((value) =>
        debugPrint('Page finished loading Javascript'))
    .catchError((onError) => debugPrint('$onError'));


问:
Chrome Extensions public API or links to ask new versions
Is there any Chrome Extensions public API or links to ask new versions?
Any methods to send a request to extension API without credentials?
Or maybe some way to ask updates without javacript libs?

I am newby in Chrome Extensions.  I tried to find the way to do it outside the Extension, but still without luck.  I am expecting to call this link or API from Java based service.


问:
Why is JavaScript re-ordering (key ascending) my JSON?
I create randomly ordered dict in python and import it to JS, however the dict is always reordered in JS as per my console log:

Python:

```<code>def generate_translation(language):
    dictionary = DICTIONARIES[language]
    words = list(dictionary.keys())
    random.shuffle(words)
    test = dict()
    for key in words:
        test[key]=dictionary[key]
    js_test = json.dumps(test)
    with open(os.path.join("/workspaces/78624234/CS50X/project/static", "js_test.json"), "w") as f:
        f.write(js_test)
        f.close
    return test, js_test

    ...

    test, js_test = generate_translation(selected)

    return render_template("study.html", language=selected, dictionary=test, js_dictionary=js_test)

</code>```

JavaScript:

```<code>import data from './js_test.json' assert { type: 'json'};
var dict = data;
</code>```

JSON File:

```<code>{"8": "huit", "5": "cinq", "3": "trois", "9": "neuf", "2": "deux", "1": "un", "4": "quatre", "10": "dix", "7": "sept", "6": "six"}
</code>```

Console:

```<code>{1: 'un', 2: 'deux', 3: 'trois', 4: 'quatre', 5: 'cinq', 6: 'six', 7: 'sept', 8: 'huit', 9: 'neuf', 10: 'dix'}
</code>```

I expected importing would maintain the format of the stored JSON file but it always defaults to ascending order. I tired rewriting line 2 of my JS file to be var dict = JSON.parse(data) but this returned a syntax error.

Body:
I create randomly ordered dict in python and import it to JS, however the dict is always reordered in JS as per my console log:

Python:

def generate_translation(language):
    dictionary = DICTIONARIES[language]
    words = list(dictionary.keys())
    random.shuffle(words)
    test = dict()
    for key in words:
        test[key]=dictionary[key]
    js_test = json.dumps(test)
    with open(os.path.join("/workspaces/78624234/CS50X/project/static", "js_test.json"), "w") as f:
        f.write(js_test)
        f.close
    return test, js_test

    ...

    test, js_test = generate_translation(selected)

    return render_template("study.html", language=selected, dictionary=test, js_dictionary=js_test)

JavaScript:

import data from './js_test.json' assert { type: 'json'};
var dict = data;

JSON File:

{"8": "huit", "5": "cinq", "3": "trois", "9": "neuf", "2": "deux", "1": "un", "4": "quatre", "10": "dix", "7": "sept", "6": "six"}

Console:

{1: 'un', 2: 'deux', 3: 'trois', 4: 'quatre', 5: 'cinq', 6: 'six', 7: 'sept', 8: 'huit', 9: 'neuf', 10: 'dix'}

I expected importing would maintain the format of the stored JSON file but it always defaults to ascending order. I tired rewriting line 2 of my JS file to be var dict = JSON.parse(data) but this returned a syntax error.


问:
Getting the user information from the database in ASP.NET Core
I am making a website that uses the default EF Core to manipulate user data. It has a custom user with a definition like:

```<code>class AppUser : IdentityUser
{
    [ProtectedPersonalData]
    public Address HomeAdress { get; set; }

    [ProtectedPersonalData]
    public Address BusinessAddress { get; set; }

    ...
}
</code>```

It also has the same default stuff like Email, UserName, etc., which are the same as the IdentityUser. However, I noticed that when saving the addresses to the database a new table is made for Address class where a new table entry is created for each instance of Address in my user class and the Id of the Address in the Address table is stored in HomeAddressId and BusinessAddressId of my users' database entries.

Considering this information how should I receive the user information from the database, including the Address data? I aim to get every field in the user data and also get the "related" data. Should I just make a database connection and receive stuff with SQL? Is there a way to do this using UserManager?

Side Question: Is this the most efficient way to store the Address data?

Body:
I am making a website that uses the default EF Core to manipulate user data. It has a custom user with a definition like:

class AppUser : IdentityUser
{
    [ProtectedPersonalData]
    public Address HomeAdress { get; set; }

    [ProtectedPersonalData]
    public Address BusinessAddress { get; set; }

    ...
}

It also has the same default stuff like Email, UserName, etc., which are the same as the IdentityUser. However, I noticed that when saving the addresses to the database a new table is made for Address class where a new table entry is created for each instance of Address in my user class and the Id of the Address in the Address table is stored in HomeAddressId and BusinessAddressId of my users' database entries.

Considering this information how should I receive the user information from the database, including the Address data? I aim to get every field in the user data and also get the "related" data. Should I just make a database connection and receive stuff with SQL? Is there a way to do this using UserManager?

Side Question: Is this the most efficient way to store the Address data?