问:
How to click on submenu item using selenium python

**Someone can help me please?

I need to click on the submenu item highlighted in the image, but I can't find the correct path.

**

sub_menu

I've tried find_element_by:

**id: I can't find which is the correct id index;

xpath: its xpath the same as menu

class menuItem: brought the menu above;

text_link: no such element: Unable to locate element;

css td.menuItemSeleccionado: no such element: Unable to locate element;

classe menuItemSeleccionado: no such element: Unable to locate element**

I'm trying to do this with the code below, but I can only go to the click on the previous menu.

Someone has any idea?


来源: stackexchange

问:
How to display fetched data(which is in XML) in a React App?
I'm trying to build a simple app that fetches anime details and news through this API - https://www.animenewsnetwork.com/encyclopedia/api.php and then display a few details such as the name of the anime, a few characters and news article. The API is however in XML format. The exact link I'm using to fetch is - https://cdn.animenewsnetwork.com/encyclopedia/api.xml?anime=836

enter image description here
I used react-xml-parser and json stringify to get the data in json format. How can I access the attribute's name property?
enter image description here
I've also tried doing it with DOMParser but I still do not understand how can I access the attributes. I did Google NamedNodeMap and tried some of the ways but it still doesn't work. Can anyone who has experience working with APIs in XML format help me? My code is following,
My code

ContentLicense: CC BY-SA 4.0


问:
nodejs express . For loop is blocking my simple server
I am trying to understand how nodejs and async funktions work , so i added a long for loop to test if this simple server can answar multiple request when it get a long request (in this case a long for loop).

thanks for the help in advance . and sorry for the bad english

```<code>const express = require('express')
const app = express()
const port = 3000

app.get('/',async (req, res) =\> {
x = 1
while(x<(1000000000)*3){x++}
res.send('Hello World!')
})
app.get('/normal',async (req, res) =\> {
res.send('Hello World!')
})

app.listen(port, () =\> {
console.log(`Example app listening on port ${port}`)
})
</code>```

Body:
I am trying to understand how nodejs and async funktions work , so i added a long for loop to test if this simple server can answar multiple request when it get a long request (in this case a long for loop).

thanks for the help in advance . and sorry for the bad english

const express = require('express')
const app = express()
const port = 3000

app.get('/',async (req, res) =\> {
x = 1
while(x<(1000000000)*3){x++}
res.send('Hello World!')
})
app.get('/normal',async (req, res) =\> {
res.send('Hello World!')
})

app.listen(port, () =\> {
console.log(`Example app listening on port ${port}`)
})


问:
How to conditionally render different loading while using withAuthenticationRequired in auth0
I wanted that if the user entered some other URL like (/explore) before login, he must be get redirected to the login page and in the meantime, the loading message should be displayed as "Redirecting to login...".On the other hand, when the user enters login details and gets redirected after successful login I want the loading message to be displayed as "Redirecting...".

For this purpose I am using isAuthenticated, but the problem is that even after the user logs in, the isAuthenticated stays false for a few seconds before finally turning true. Because of this, it is still rendering "Redirecting to login..." instead of "Redirecting...".

```<code>
import React from "react";
import { withAuthenticationRequired, useAuth0 } from '@auth0/auth0-react';
import Loading from "./Loading";

const PrivateRoute = ({ component, ...propsForComponent }) => {
  const {isAuthenticated} = useAuth0();

  const Cp = withAuthenticationRequired(component, {
    onRedirecting: () => {
      if (!isAuthenticated) {
        return <h3>Redirecting to login...</h3>
      } else if(isAuthenticated){
       return <h3>Redirecting...</h3>
      }

    }

  });

  return <Cp {...propsForComponent} />
}

export default PrivateRoute;
</code>```

how can I display the message "redirecting..." during the successful login?

Body:
I wanted that if the user entered some other URL like (/explore) before login, he must be get redirected to the login page and in the meantime, the loading message should be displayed as "Redirecting to login...".On the other hand, when the user enters login details and gets redirected after successful login I want the loading message to be displayed as "Redirecting...".

For this purpose I am using isAuthenticated, but the problem is that even after the user logs in, the isAuthenticated stays false for a few seconds before finally turning true. Because of this, it is still rendering "Redirecting to login..." instead of "Redirecting...".

import React from "react";
import { withAuthenticationRequired, useAuth0 } from '@auth0/auth0-react';
import Loading from "./Loading";

const PrivateRoute = ({ component, ...propsForComponent }) => {
  const {isAuthenticated} = useAuth0();

  const Cp = withAuthenticationRequired(component, {
    onRedirecting: () => {
      if (!isAuthenticated) {
        return
Redirecting to login...

      } else if(isAuthenticated){
       return
Redirecting...

      }

    }

  });

  return <Cp {...propsForComponent} />
}

export default PrivateRoute;

how can I display the message "redirecting..." during the successful login?


问:
QML TreeView and Python
I need to create tree view in QML where will be stored static 2-dimensional data. I have tried implementing QAbstractItemModel in Python but I gave up.

I found a simpler solution by creating a QStandardItemModel. The problem occurs when I want to send the model to a frontend (QML). I've never had a problem with signals, so I think I implement them correctly.

There is example I have created:

```<code>class App(QObject):
    data_api: DataAPI = None
    places_api: PlacesAPI = None
    map_api: MapAPI = None

    sendModel = Signal(QStandardItemModel)

    def __init__(self) -> None:
        super().__init__()
        self.__setattr__("data_api", DataAPI())
        self.__setattr__("places_api", PlacesAPI())
        self.__setattr__("map_api", MapAPI())

        self.model = QStandardItemModel()

        rootNode = self.model.invisibleRootItem()

        parent = QStandardItem()
        parent.setData("Item 1", Qt.DisplayRole)

        child1 = QStandardItem()
        child1.setData("Item 1.1", Qt.DisplayRole)
        child2 = QStandardItem()
        child2.setData("Item 1.2", Qt.DisplayRole)

        parent.appendRow([child1, child2])

        rootNode.appendRow(parent)
</code>```

And there is function:

```<code>function onSendModel(model){
            console.log(model)
            //treeView.model = model

        }
</code>```

This is output from terminal: "qml: undefined"

I have tried:

Create custom class, that inherits QStandardItemModel

Use setText instead of setData

I am expecting that the frontend will recognize model and it will be usable for my tree view

Title: QML TreeView and Python

Body:
I need to create tree view in QML where will be stored static 2-dimensional data. I have tried implementing QAbstractItemModel in Python but I gave up.

I found a simpler solution by creating a QStandardItemModel. The problem occurs when I want to send the model to a frontend (QML). I've never had a problem with signals, so I think I implement them correctly.

There is example I have created:

class App(QObject):
    data_api: DataAPI = None
    places_api: PlacesAPI = None
    map_api: MapAPI = None

    sendModel = Signal(QStandardItemModel)

    def __init__(self) -> None:
        super().__init__()
        self.__setattr__("data_api", DataAPI())
        self.__setattr__("places_api", PlacesAPI())
        self.__setattr__("map_api", MapAPI())

        self.model = QStandardItemModel()

        rootNode = self.model.invisibleRootItem()

        parent = QStandardItem()
        parent.setData("Item 1", Qt.DisplayRole)

        child1 = QStandardItem()
        child1.setData("Item 1.1", Qt.DisplayRole)
        child2 = QStandardItem()
        child2.setData("Item 1.2", Qt.DisplayRole)

        parent.appendRow([child1, child2])

        rootNode.appendRow(parent)

And there is function:

function onSendModel(model){
            console.log(model)
            //treeView.model = model

        }

This is output from terminal: "qml: undefined"

I have tried:

Create custom class, that inherits QStandardItemModel

Use setText instead of setData

I am expecting that the frontend will recognize model and it will be usable for my tree view


问:
QT debug widget cannot call public function
In a QT project, I have a QTableWidget.
I want to look at the QTableWidgetItem in this table in the debugger.
But when I click on the > for the table, it shows nothing.
I have tried to add an Expression Evaluator, like
aTable->item(0,0) but it return < no such value>

Could you tell me what's wrong ? how can I access the objects in a widget ?

thanks


问:
throwing Warning: a promise was rejected with a non-error: [object Object]
```<code>  function fetch(options) {
   return new Promise((resolve, reject) => {
     this.request(options, (err, response, status, xhr) => {
     console.log('err res', err, response);//#console2
     return err ? reject(err) : resolve(response);
     });
   });
  }
</code>```

This is my block of code.
I have already seen a lot of related questions but still couldn't find anything.
In my case, I'm calling this fetch method from 2 places within a project with the same input and I'm getting the same error for both the time i.e till #console2 everything is the same but while returning one time it is throwing warning promise was rejected with a non-error:  and for another call, it is not throwing anything.
Please let me know if anyone is aware of this issue.
Thanks in advance :) .

Body:
  function fetch(options) {
   return new Promise((resolve, reject) => {
     this.request(options, (err, response, status, xhr) => {
     console.log('err res', err, response);//#console2
     return err ? reject(err) : resolve(response);
     });
   });
  }

This is my block of code.
I have already seen a lot of related questions but still couldn't find anything.
In my case, I'm calling this fetch method from 2 places within a project with the same input and I'm getting the same error for both the time i.e till #console2 everything is the same but while returning one time it is throwing warning promise was rejected with a non-error:  and for another call, it is not throwing anything.
Please let me know if anyone is aware of this issue.
Thanks in advance :) .


问:
Using openxlsx to write a character vector across columns
I'm trying to write data across multiple columns in excel using a single vector as input. All my attempts, result in vertical placement.

What I want:

```<code>library(openxlsx)
vec <- c("A", "B", "C", "D")
wb <- createWorkbook()
addWorksheet(wb, "Sheet1")
writeData(wb, 1, vec,
  startCol = 1,
  startRow = 1,
  colNames = FALSE)

saveWorkbook(wb, "test1.xlsx", overwrite = T)
</code>```

I have also manipulated the vector into a string incase there was something about the vector was causing new lines.

vec <- paste(vec, sep = ",")

Any assistance would be appreciated

Body:
I'm trying to write data across multiple columns in excel using a single vector as input. All my attempts, result in vertical placement.

What I want:

library(openxlsx)
vec <- c("A", "B", "C", "D")
wb <- createWorkbook()
addWorksheet(wb, "Sheet1")
writeData(wb, 1, vec,
  startCol = 1,
  startRow = 1,
  colNames = FALSE)

saveWorkbook(wb, "test1.xlsx", overwrite = T)

I have also manipulated the vector into a string incase there was something about the vector was causing new lines.

vec <- paste(vec, sep = ",")

Any assistance would be appreciated


问:
Testing Angular Lazy Loaded
There are a lot of old answers that exist on this platform and I have tried them all, but none of them resolved my request.

Some methods were deprecated, and I found info that requires to use of NgModule instead of SpyNgModuleFactoryLoader. I also watched this video https://www.youtube.com/watch?v=PcwFcBsTAtM

But whatever I did, it didn't work. Has anyone tried testing lazy-loaded routes these days?

app-routing.module.spec.ts

import { Location } from '@angular/common';
import { NgModule } from '@angular/core';
import { ComponentFixture, fakeAsync, tick } from '@angular/core/testing';
import { TestBed } from '@angular/core/testing';
import { Router, Routes } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';

import { AppComponent } from './app.component';
import { HomeModule } from './pages/home/home.module';

export const routes: Routes = [
  {
    path: 'home',
    loadChildren: () => import('src/app/pages/home/home.module').then((m) => m.HomeModule),
  },
  {
    path: 'sample',
    loadChildren: () => import('src/app/pages/sample/sample.module').then((m) => m.SampleModule),
  },
  { path: '', redirectTo: '/home', pathMatch: 'full' },
];

describe('Router: App', () => {
  let location: Location;
  let router: Router;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule.withRoutes(routes)],
      declarations: [AppComponent],
    }).compileComponents();
    router = TestBed.inject(Router);
    location = TestBed.inject(Location);
    fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    router.initialNavigation();
  });

  it('should navigate to files', fakeAsync(() => {
    const loader = TestBed.inject(NgModule);
    loader.stubbedModules = {
      './pages/home/home.module#HomeModule': HomeModule,
    };
    router.resetConfig([{ path: 'home', loadChildren: (): any => import('./pages/home/home.module').then((mod) => mod.HomeModule) }]);
    router.navigateByUrl('/home');
    tick(50);
    fixture.detectChanges();
    expect(location.path()).toBe('/home');
  }));
});

```
<p>This code gives me bellow error:</p>
<pre class="lang-bash prettyprint-override"><code>Chrome Headless 103.0.5060.114 (Mac OS 10.15.7) Router: App should navigate to files FAILED
        NullInjectorError: R3InjectorError(CompilerModule)[DecoratorFactory -> DecoratorFactory]:
          NullInjectorError: No provider for DecoratorFactory!
        error properties: Object({ ngTempTokenPath: null, ngTokenPath: [ 'DecoratorFactory', 'DecoratorFactory' ] })
            at NullInjector.get (http://localhost:9876/_karma_webpack_/vendor.js:49234:21)
</code>```

I tried to test angular application with lazy loaded routing, but it is not worked

Title: Testing Angular Lazy Loaded

Body:
There are a lot of old answers that exist on this platform and I have tried them all, but none of them resolved my request.

Some methods were deprecated, and I found info that requires to use of NgModule instead of SpyNgModuleFactoryLoader. I also watched this video https://www.youtube.com/watch?v=PcwFcBsTAtM

But whatever I did, it didn't work. Has anyone tried testing lazy-loaded routes these days?

app-routing.module.spec.ts

import { Location } from '@angular/common';
import { NgModule } from '@angular/core';
import { ComponentFixture, fakeAsync, tick } from '@angular/core/testing';
import { TestBed } from '@angular/core/testing';
import { Router, Routes } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';

import { AppComponent } from './app.component';
import { HomeModule } from './pages/home/home.module';

export const routes: Routes = [
  {
    path: 'home',
    loadChildren: () => import('src/app/pages/home/home.module').then((m) => m.HomeModule),
  },
  {
    path: 'sample',
    loadChildren: () => import('src/app/pages/sample/sample.module').then((m) => m.SampleModule),
  },
  { path: '', redirectTo: '/home', pathMatch: 'full' },
];

describe('Router: App', () => {
  let location: Location;
  let router: Router;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule.withRoutes(routes)],
      declarations: [AppComponent],
    }).compileComponents();
    router = TestBed.inject(Router);
    location = TestBed.inject(Location);
    fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    router.initialNavigation();
  });

  it('should navigate to files', fakeAsync(() => {
    const loader = TestBed.inject(NgModule);
    loader.stubbedModules = {
      './pages/home/home.module#HomeModule': HomeModule,
    };
    router.resetConfig([{ path: 'home', loadChildren: (): any => import('./pages/home/home.module').then((mod) => mod.HomeModule) }]);
    router.navigateByUrl('/home');
    tick(50);
    fixture.detectChanges();
    expect(location.path()).toBe('/home');
  }));
});

This code gives me bellow error:

Chrome Headless 103.0.5060.114 (Mac OS 10.15.7) Router: App should navigate to files FAILED
        NullInjectorError: R3InjectorError(CompilerModule)[DecoratorFactory -> DecoratorFactory]:
          NullInjectorError: No provider for DecoratorFactory!
        error properties: Object({ ngTempTokenPath: null, ngTokenPath: [ 'DecoratorFactory', 'DecoratorFactory' ] })
            at NullInjector.get (http://localhost:9876/_karma_webpack_/vendor.js:49234:21)

I tried to test angular application with lazy loaded routing, but it is not worked


问:
How to back one or two path with new parameter in angular routing?
I am using angular 15.0 for my project. There are two shared paths in routing-module. for example:
The first path: is: '../customer/:customerId/showInvoice/:invoiceId'
And the second path is: '../customer/:customerId/newInvoice/:customerId'.
When we have followed the second path to the end, so that a new invoice is saved, so far, we have retrieved the invoice ID from the database and we have it. For example:
../customer/3/newInvoice/3 and the retrieved invoiceId is 15. So, now we want to back one path with new parameter (i.e. we switch on the first path to show the new invoice which has created), i.e.
../customer/3/showInvoice/15.
Is this scenario possible? If so, what method can be used? Is it possible to use Angular LocalStrategy service? and how? I will be grateful if you provide a suitable solution. Best regards.


问:
Select time in video progression with Flask streaming video in chunks
I'm trying to create a streaming capability on my site with flask. I'm sending my video in chunks, but although the video loads I can't change time.

So far I've made this route to stream the video

```<code>@app.route('/v/<filename>')
def v(filename):

    time = request.args.get('time', 0, type=int)

    def generate():
        with open(os.path.join(VIDEO_FOLDER, filename), 'rb') as f:
            if time > 0:
                f.seek(time * 1024)
            data = f.read(1024)
            while data:
                yield data
                data = f.read(1024)
    return Response(generate(), mimetype='video/mp4')
</code>```

I made a simple HTML page to get the video:

```<code><video id="video" controls>
  <source id="source" src="/v/{{filename}}" type="video/mp4">

Your browser does not support the video tag.
</video>
</code>```

So far the video is loading and playing fine but I can't go to a given time (let's say 8 minutes in). I've tried many things but nothing seems to work. Can anyone tell me how I can alter this code to make it so that if I click in the progress bar of the video element it skips to the right time?

Thank you in advance for your answers.

Body:
I'm trying to create a streaming capability on my site with flask. I'm sending my video in chunks, but although the video loads I can't change time.

So far I've made this route to stream the video

@app.route('/v/<filename>')
def v(filename):

    time = request.args.get('time', 0, type=int)

    def generate():
        with open(os.path.join(VIDEO_FOLDER, filename), 'rb') as f:
            if time > 0:
                f.seek(time * 1024)
            data = f.read(1024)
            while data:
                yield data
                data = f.read(1024)
    return Response(generate(), mimetype='video/mp4')

I made a simple HTML page to get the video:

<video id="video" controls>
  <source id="source" src="/v/{{filename}}" type="video/mp4">

Your browser does not support the video tag.
</video>

So far the video is loading and playing fine but I can't go to a given time (let's say 8 minutes in). I've tried many things but nothing seems to work. Can anyone tell me how I can alter this code to make it so that if I click in the progress bar of the video element it skips to the right time?

Thank you in advance for your answers.


问:
phpmyadmin keeps defaulting to localhost
My setup:

```<code>OS: Mac Monterey - v 12.3.1
phpmyadmin - 5.2.0-rc1 - installed locally
</code>```

In my config.inc.php, I have several servers defined, they're mostly RDS instances, and I can connect to them fine.

I also have a MySQL server, 8.03, setup on on EC2 Ubuntu 22.04 instance. I added the following to my config.inc.php:

```<code>// Server: API-GWY
$i++;
$cfg['Servers'][$i]['verbose'] = 'API-GWY';
$cfg['Servers'][$i]['host'] = 'myapigway.xxxxx.xom';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['auth_type'] = 'http';
$cfg['Servers'][$i]['user'] = 'apigwy';
$cfg['Servers'][$i]['password'] = 'xxxxxxxxxx';
</code>```

Reloaded phpmyadmin, and then tried to connect. I selected API-GWY from the dropdown, and entered the credentials manually,

but I keep getting the following screen:

Any idea what's going on? Note that I can connect to the mysql server, from a terminal session locally, using the mysql command and the same credentials.

Body:
My setup:

OS: Mac Monterey - v 12.3.1
phpmyadmin - 5.2.0-rc1 - installed locally

In my config.inc.php, I have several servers defined, they're mostly RDS instances, and I can connect to them fine.

I also have a MySQL server, 8.03, setup on on EC2 Ubuntu 22.04 instance. I added the following to my config.inc.php:

// Server: API-GWY
$i++;
$cfg['Servers'][$i]['verbose'] = 'API-GWY';
$cfg['Servers'][$i]['host'] = 'myapigway.xxxxx.xom';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['auth_type'] = 'http';
$cfg['Servers'][$i]['user'] = 'apigwy';
$cfg['Servers'][$i]['password'] = 'xxxxxxxxxx';

Reloaded phpmyadmin, and then tried to connect. I selected API-GWY from the dropdown, and entered the credentials manually,

but I keep getting the following screen:

Any idea what's going on? Note that I can connect to the mysql server, from a terminal session locally, using the mysql command and the same credentials.


问:
Lambda with 1 reservedConcurrency getting throttled even when FIFO queue(trigger event) has same messageGroupId across all messages
I have a SAM stack with 1 lambda, 1 SQS and 1 DLQ. The message in SQS acts as an event source for the lambda. The lambda has ReservedConcurrentExecutions of 1. The batch size of event(from SQS to lambda) is also 1. The timeout of lambda is 300 seconds.

The SQS is a FIFO queue with ContentBasedDeduplication as true. The VisibilityTimeout is of 400 seconds and ReceiveMessageWaitTimeSeconds as 10.
SQS has a DLQ linked to it with a re drive policy of maxReceiveCount of 5.

All the messages sent to the FIFO queue have the same messageGroupId.
The idea behind this is to ensure all the messages get processed in a FIFO manner and no message is repeated by any chance.

Also, since the ReservedConcurrentExecutions of lambda is set to 1 and the messageGroupId is also same across all messages, it was assumed that this lambda will not throttle in any scenario.
But it is still getting throttled.

I can't seem to find any issue with the configuration of my stack that could cause this issue. Does anyone have any insight as to why and how this scenario could have been possible? Or is there a way I can find out which message was throttled?

Also, a point to mention here is that this lambda throttle was not happening till the time the number of messages in the queue was small. As soon as the queue has messages above 1000, the throttle error started appearing. But the count of throttle at any given time was never more than 1. And the throttle happens randomly and never in any fixed pattern. And eventually all messages were processed since I received no messages in DLQ once all messages were processed.

I had read the following on AWS

To allow your function time to process each batch of records, set the source queue's visibility timeout to at least six times the timeout that you configure on your function. The extra time allows for Lambda to retry if your function is throttled while processing a previous batch.

In my case this is not true since my queue's visibility timeout(400) is just 100 seconds more than the lambda's timeout(300). Could this be the cause of my issue?

Following is my CF script for the lambda and sqs

```<code>CreateJobsQueue:
  Type: AWS::SQS::Queue
  Properties:
    QueueName: !Sub '${AWS::StackName}-CreateJobsQueue.fifo'
    ReceiveMessageWaitTimeSeconds: 10
    FifoQueue: True
    ContentBasedDeduplication: True
    VisibilityTimeout: 400
    RedrivePolicy:
      deadLetterTargetArn: !GetAtt CreateJobsDLQ.Arn
      maxReceiveCount: 5

CreateJobsDLQ:
  Type: AWS::SQS::Queue
  Properties:
    QueueName: !Sub '${AWS::StackName}-CreateJobsDLQ.fifo'
    FifoQueue: True
    ContentBasedDeduplication: True
    MessageRetentionPeriod: 604800

CreateJobsFn:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: !Sub '${AWS::StackName}-CreateJobsFn'
      CodeUri: functions/create-jobs/
      Handler: index.handler
      Runtime: nodejs16.x
      Description: Lambda function to pick up the message from CreateJobsQueue
      MemorySize: 512
      Timeout: 300
      KmsKeyArn: !Sub "arn:aws:kms:${AWS::Region}:${AWS::AccountId}:key/${AppsKMSKeyId}"
      ReservedConcurrentExecutions: 1
      Policies:
        - AWSLambdaBasicExecutionRole
        - AWSLambdaENIManagementAccess
      Environment:
        Variables:
          EMAIL_DOMAIN: ""
      Layers:
        - !Ref LambdaDependencies
      VpcConfig:
        !If
          - IsVPCRequired
          -
            SubnetIds: !Ref BFnSubnetIds
            SecurityGroupIds: !Ref BFnSecurityGroupIds
          - !Ref 'AWS::NoValue'
      Events:
        CreateJobsFnSQSEvent:
          Type: SQS
          Properties:
            Queue: !GetAtt CreateJobsQueue.Arn
            BatchSize: 1
</code>```

Please let me know if any other details needed from my end.

Body:
I have a SAM stack with 1 lambda, 1 SQS and 1 DLQ. The message in SQS acts as an event source for the lambda. The lambda has ReservedConcurrentExecutions of 1. The batch size of event(from SQS to lambda) is also 1. The timeout of lambda is 300 seconds.

The SQS is a FIFO queue with ContentBasedDeduplication as true. The VisibilityTimeout is of 400 seconds and ReceiveMessageWaitTimeSeconds as 10.
SQS has a DLQ linked to it with a re drive policy of maxReceiveCount of 5.

All the messages sent to the FIFO queue have the same messageGroupId.
The idea behind this is to ensure all the messages get processed in a FIFO manner and no message is repeated by any chance.

Also, since the ReservedConcurrentExecutions of lambda is set to 1 and the messageGroupId is also same across all messages, it was assumed that this lambda will not throttle in any scenario.
But it is still getting throttled.

I can't seem to find any issue with the configuration of my stack that could cause this issue. Does anyone have any insight as to why and how this scenario could have been possible? Or is there a way I can find out which message was throttled?

Also, a point to mention here is that this lambda throttle was not happening till the time the number of messages in the queue was small. As soon as the queue has messages above 1000, the throttle error started appearing. But the count of throttle at any given time was never more than 1. And the throttle happens randomly and never in any fixed pattern. And eventually all messages were processed since I received no messages in DLQ once all messages were processed.

I had read the following on AWS

To allow your function time to process each batch of records, set the source queue's visibility timeout to at least six times the timeout that you configure on your function. The extra time allows for Lambda to retry if your function is throttled while processing a previous batch.

In my case this is not true since my queue's visibility timeout(400) is just 100 seconds more than the lambda's timeout(300). Could this be the cause of my issue?

Following is my CF script for the lambda and sqs

CreateJobsQueue:
  Type: AWS::SQS::Queue
  Properties:
    QueueName: !Sub '${AWS::StackName}-CreateJobsQueue.fifo'
    ReceiveMessageWaitTimeSeconds: 10
    FifoQueue: True
    ContentBasedDeduplication: True
    VisibilityTimeout: 400
    RedrivePolicy:
      deadLetterTargetArn: !GetAtt CreateJobsDLQ.Arn
      maxReceiveCount: 5

CreateJobsDLQ:
  Type: AWS::SQS::Queue
  Properties:
    QueueName: !Sub '${AWS::StackName}-CreateJobsDLQ.fifo'
    FifoQueue: True
    ContentBasedDeduplication: True
    MessageRetentionPeriod: 604800

CreateJobsFn:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: !Sub '${AWS::StackName}-CreateJobsFn'
      CodeUri: functions/create-jobs/
      Handler: index.handler
      Runtime: nodejs16.x
      Description: Lambda function to pick up the message from CreateJobsQueue
      MemorySize: 512
      Timeout: 300
      KmsKeyArn: !Sub "arn:aws:kms:${AWS::Region}:${AWS::AccountId}:key/${AppsKMSKeyId}"
      ReservedConcurrentExecutions: 1
      Policies:
        - AWSLambdaBasicExecutionRole
        - AWSLambdaENIManagementAccess
      Environment:
        Variables:
          EMAIL_DOMAIN: ""
      Layers:
        - !Ref LambdaDependencies
      VpcConfig:
        !If
          - IsVPCRequired
          -
            SubnetIds: !Ref BFnSubnetIds
            SecurityGroupIds: !Ref BFnSecurityGroupIds
          - !Ref 'AWS::NoValue'
      Events:
        CreateJobsFnSQSEvent:
          Type: SQS
          Properties:
            Queue: !GetAtt CreateJobsQueue.Arn
            BatchSize: 1

Please let me know if any other details needed from my end.


问:
Python: ways to store the attributes of an object
considering the following simplified example:

```<code>class Atom:

  def __init__(self, name_ID, position, mass, charge):
    self.name_ID = name_ID # + date
    self.position, self.mass, self.charge = position, mass, charge

  def calculate_equation_of_motion(self):
    self.position, self.mass, self.charge = np.random.rand(3,3),np.random.rand(3,3),np.random.rand(3,3)

  def store_data(self):
    pass

At30 = Atom('test', 0,0,0)
At30.calculate_equation_of_motion()
#At30.store_data()

#At30_copy = load_object(name_ID='atom_30')
#print(At30_copy.charge)
</code>```

of a class that contains 10+ attributes which consist of float and array parameters and variables.

What would you suggest to manage all the calculated arrays in a way I can store an object to be "loaded" later? It might not be clear in this context but in reality, the script takes a while to integrate each array, so I'd like to save the information using a simple approach.

Body:
considering the following simplified example:

class Atom:

  def __init__(self, name_ID, position, mass, charge):
    self.name_ID = name_ID # + date
    self.position, self.mass, self.charge = position, mass, charge

  def calculate_equation_of_motion(self):
    self.position, self.mass, self.charge = np.random.rand(3,3),np.random.rand(3,3),np.random.rand(3,3)

  def store_data(self):
    pass

At30 = Atom('test', 0,0,0)
At30.calculate_equation_of_motion()
#At30.store_data()

#At30_copy = load_object(name_ID='atom_30')
#print(At30_copy.charge)

of a class that contains 10+ attributes which consist of float and array parameters and variables.

What would you suggest to manage all the calculated arrays in a way I can store an object to be "loaded" later? It might not be clear in this context but in reality, the script takes a while to integrate each array, so I'd like to save the information using a simple approach.


问:
Jib for gradle, how to set permissions on a folder
I have a Java Spring Boot project where I need to be able to copy a file into a specific folder. However I am not able to copy any files. So I need to enable permissions for a specific folder where I am copying into. I am just copying files from one area of the image to another.

Is the following code using correct syntax? It does not seem like it is working because I still am not able to copy anything.

```<code>jib {
    from {
        image = "aregistry.com/images/jre11"
        auth {
            username = "${registryUsername}"
            password = "${registryPassword}"
        }
    }
    to {
        image = "us-central1-docker.pkg.dev/myartifactregistry"
        auth {
            username = "oauth2accesstoken"
            password = "${artifactRegistryToken}"
        }
    }
    extraDirectories {
        permissions = [
                '/nativelibs': '755'
        ]
    }
}
</code>```

Specifically I am asking about the extraDirectories section. The folder lies at the root of the project.

Body:
I have a Java Spring Boot project where I need to be able to copy a file into a specific folder. However I am not able to copy any files. So I need to enable permissions for a specific folder where I am copying into. I am just copying files from one area of the image to another.

Is the following code using correct syntax? It does not seem like it is working because I still am not able to copy anything.

jib {
    from {
        image = "aregistry.com/images/jre11"
        auth {
            username = "${registryUsername}"
            password = "${registryPassword}"
        }
    }
    to {
        image = "us-central1-docker.pkg.dev/myartifactregistry"
        auth {
            username = "oauth2accesstoken"
            password = "${artifactRegistryToken}"
        }
    }
    extraDirectories {
        permissions = [
                '/nativelibs': '755'
        ]
    }
}

Specifically I am asking about the extraDirectories section. The folder lies at the root of the project.


问:
subprocess popen command arguements do not work
Using popen to run K8s commands. The SERVICE_ACCOUNT does not produce any output. I get <none>.
I have escaped the \" and \\

Original command:

oc get pods -n <namespace> -o custom-columns=POD_NAME:.metadata.name,SERVICE_ACCOUNT:.spec.serviceAccount,SCC_PROFILE:".metadata.annotations.openshift\.io/scc"
```
<p>Code:</p>
<pre class="lang-py prettyprint-override"><code>output = subprocess.Popen(["oc","get","pods","-n",smf_namespace,"-o","custom-columns=POD_NAME:.metadata.name,SERVICE_ACCOUNT:.spec.serviceAccount,SCC_PROFILE:\".metadata.annotations.openshift\\.io/scc\""],stdout=subprocess.PIPE,encoding='utf8')
</code>```

Body:
Using popen to run K8s commands. The SERVICE_ACCOUNT does not produce any output. I get <none>.
I have escaped the \" and \\

Original command:

oc get pods -n <namespace> -o custom-columns=POD_NAME:.metadata.name,SERVICE_ACCOUNT:.spec.serviceAccount,SCC_PROFILE:".metadata.annotations.openshift\.io/scc"

Code:

output = subprocess.Popen(["oc","get","pods","-n",smf_namespace,"-o","custom-columns=POD_NAME:.metadata.name,SERVICE_ACCOUNT:.spec.serviceAccount,SCC_PROFILE:\".metadata.annotations.openshift\\.io/scc\""],stdout=subprocess.PIPE,encoding='utf8')


问:
vfs transport transport is not stable in WSO2
I using EI version 6.6.0 and OS - CentOS Linux 7 (Core).
I have a proxy service and one part of its task is to copy a file with content to a backup. To do this I use the transport.vfs.replyfilename property with the OUT_ONLY property and the endpoint with the url where I want to save the backup file.
This is example my proxy :

```<code>  <target>
        <inSequence>
            <log level="custom" separator="
">
                <property name="STEP" value="Start operation"/>
                <property expression="$trp:FILE_LENGTH" name="LENGTH"/>
                <property expression="$trp:LAST_MODIFIED" name="MODIFIED"/>
                <property expression="$trp:FILE_URI" name="URI"/>
                <property expression="$trp:FILE_PATH" name="PATH"/>
                <property expression="$trp:FILE_NAME" name="NAME"/>
            </log>
            <property expression="//*[local-name()='text']" name="INPUT_FILE" scope="default" type="STRING"/>
            <property expression="$trp:FILE_NAME" name="uri.var.load_file" scope="default" type="STRING"/>
            <log level="custom">
               <property name="STEP" value="Copy input file to another location"/>
               <property name="LOAD_FILE" expression="get-property('uri.var.load_file')"/>
            </log>
            <property expression="get-property('uri.var.load_file')"
                name="transport.vfs.ReplyFileName" scope="transport" type="STRING"/>
            <property name="OUT_ONLY" scope="default" type="STRING" value="true"/>
            <send>
              <endpoint name="fileEndpoint">
                <address trace="disable" uri="vfs:file:///relaitive_path_of_backup_folder"/>
              </endpoint>
            </send>
        </inSequence>
        <outSequence/>
        <faultSequence/>
    </target>
    <parameter name="transport.PollInterval">60</parameter>
    <parameter name="transport.vfs.FailedRecordsFileDestination">file:///opt/wso2ei-6.6.0/repository/conf</parameter>
    <parameter name="transport.vfs.MaxRetryCount">5</parameter>
    <parameter name="transport.vfs.ContentType">text/plain;charset=UTF-8</parameter>
    <parameter name="transport.vfs.FileURI">vfs:ftp://login:password@host/outgoing_test?transport.vfs.ReconnectTimeout=10&transport.vfs.MaxRetryCount=5&transport.vfs.ConnectTimeout=5000</parameter>
    <parameter name="transport.vfs.ActionAfterProcess">DELETE</parameter>
    <parameter name="transport.vfs.FailedRecordsFileName">transferFails.log</parameter>
    <parameter name="transport.vfs.MoveAfterFailure">vfs:ftp://login:password@host/outgoing_test/error?transport.vfs.ReconnectTimeout=10&transport.vfs.MaxRetryCount=5&transport.vfs.ConnectTimeout=5000</parameter>
    <parameter name="transport.vfs.ActionAfterFailure">MOVE</parameter>
    <parameter name="transport.vfs.FileNamePattern">.*\.csv</parameter>
    <parameter name="transport.vfs.Locking">disable</parameter>
    <parameter name="transport.vfs.MoveFailedRecordTimestampFormat">yyyy-MM-dd'T'HH:mm:ss.SSSZ_</parameter>
</code>```

But I have encountered that this method is not stable and does not always copy the file. There is nothing in the logs about this, no errors. Just sometimes the file is not copied to the specified path.
How to make this process guaranteed ?
What I do wrong ?

Body:
I using EI version 6.6.0 and OS - CentOS Linux 7 (Core).
I have a proxy service and one part of its task is to copy a file with content to a backup. To do this I use the transport.vfs.replyfilename property with the OUT_ONLY property and the endpoint with the url where I want to save the backup file.
This is example my proxy :

  <target>
        <inSequence>
            <log level="custom" separator="
">
                <property name="STEP" value="Start operation"/>
                <property expression="$trp:FILE_LENGTH" name="LENGTH"/>
                <property expression="$trp:LAST_MODIFIED" name="MODIFIED"/>
                <property expression="$trp:FILE_URI" name="URI"/>
                <property expression="$trp:FILE_PATH" name="PATH"/>
                <property expression="$trp:FILE_NAME" name="NAME"/>
            </log>
            <property expression="//*[local-name()='text']" name="INPUT_FILE" scope="default" type="STRING"/>
            <property expression="$trp:FILE_NAME" name="uri.var.load_file" scope="default" type="STRING"/>
            <log level="custom">
               <property name="STEP" value="Copy input file to another location"/>
               <property name="LOAD_FILE" expression="get-property('uri.var.load_file')"/>
            </log>
            <property expression="get-property('uri.var.load_file')"
                name="transport.vfs.ReplyFileName" scope="transport" type="STRING"/>
            <property name="OUT_ONLY" scope="default" type="STRING" value="true"/>
            <send>
              <endpoint name="fileEndpoint">
                <address trace="disable" uri="vfs:file:///relaitive_path_of_backup_folder"/>
              </endpoint>
            </send>
        </inSequence>
        <outSequence/>
        <faultSequence/>
    </target>
    <parameter name="transport.PollInterval">60</parameter>
    <parameter name="transport.vfs.FailedRecordsFileDestination">file:///opt/wso2ei-6.6.0/repository/conf</parameter>
    <parameter name="transport.vfs.MaxRetryCount">5</parameter>
    <parameter name="transport.vfs.ContentType">text/plain;charset=UTF-8</parameter>
    <parameter name="transport.vfs.FileURI">vfs:ftp://login:password@host/outgoing_test?transport.vfs.ReconnectTimeout=10&transport.vfs.MaxRetryCount=5&transport.vfs.ConnectTimeout=5000</parameter>
    <parameter name="transport.vfs.ActionAfterProcess">DELETE</parameter>
    <parameter name="transport.vfs.FailedRecordsFileName">transferFails.log</parameter>
    <parameter name="transport.vfs.MoveAfterFailure">vfs:ftp://login:password@host/outgoing_test/error?transport.vfs.ReconnectTimeout=10&transport.vfs.MaxRetryCount=5&transport.vfs.ConnectTimeout=5000</parameter>
    <parameter name="transport.vfs.ActionAfterFailure">MOVE</parameter>
    <parameter name="transport.vfs.FileNamePattern">.*\.csv</parameter>
    <parameter name="transport.vfs.Locking">disable</parameter>
    <parameter name="transport.vfs.MoveFailedRecordTimestampFormat">yyyy-MM-dd'T'HH:mm:ss.SSSZ_</parameter>

But I have encountered that this method is not stable and does not always copy the file. There is nothing in the logs about this, no errors. Just sometimes the file is not copied to the specified path.
How to make this process guaranteed ?
What I do wrong ?


问:
CKEditor5 Link Plugin overrides custom link plugin after saving page in Drupal
I created a custom CKEditor5 plugin that makes use of the "a" attribute similar to the default link plugin provided by CKEditor5. All the expected functionality that I created so far for this custom plugin which simply styles the link as a button works. However upon saving the page in the CMS (Drupal) and returning to the edit screen the model name for the button changes to "linkHref" which is the model name for the Link plugin. I checked before saving that the model name that I set up "button" was being recognized when using the Inspector. It kept the model name even when I toggled the "source" button. See schema and conversion code below.

```<code>  _defineSchema() {
    const schema = this.editor.model.schema;
    schema.extend('$text', {allowAttributes: ['button']});
  }
</code>```
```<code>_defineConverters() {
    const {conversion} = this.editor;

    conversion. For('downcast').attributeToElement({
      model: 'button',
      view: (modelAttributeValue, conversionApi) => {
        const {writer} = conversionApi;

        return writer.createAttributeElement(
          'a',
          {
            href: modelAttributeValue,
            class: 'btn btn-geneseo btn-primary'
          },
          {priority: 6} // I added this because the Link plugin had theirs at 5
        );
      },
      converterPriority: 'high' // Tried this made no difference
    });

    conversion.for('upcast').elementToAttribute({
      view: {
        name: 'a',
        attributes: ['href'],
        classes: 'btn btn-geneseo btn-primary'
      },
      model: {
        key: 'button',
        value: viewElement => viewElement.getAttribute('href'),
      },
      converterPriority: 'high'  // According to documentation this should be given priority
    });
  }
</code>```

This is the result the first time the button is created. Noticed that it is recognized as a button model.

After saving the page and going back to the edit screen this is the result.

Why would this happen? What would I need to change?

Body:
I created a custom CKEditor5 plugin that makes use of the "a" attribute similar to the default link plugin provided by CKEditor5. All the expected functionality that I created so far for this custom plugin which simply styles the link as a button works. However upon saving the page in the CMS (Drupal) and returning to the edit screen the model name for the button changes to "linkHref" which is the model name for the Link plugin. I checked before saving that the model name that I set up "button" was being recognized when using the Inspector. It kept the model name even when I toggled the "source" button. See schema and conversion code below.

  _defineSchema() {
    const schema = this.editor.model.schema;
    schema.extend('$text', {allowAttributes: ['button']});
  }

_defineConverters() {
    const {conversion} = this.editor;

    conversion. For('downcast').attributeToElement({
      model: 'button',
      view: (modelAttributeValue, conversionApi) => {
        const {writer} = conversionApi;

        return writer.createAttributeElement(
          'a',
          {
            href: modelAttributeValue,
            class: 'btn btn-geneseo btn-primary'
          },
          {priority: 6} // I added this because the Link plugin had theirs at 5
        );
      },
      converterPriority: 'high' // Tried this made no difference
    });

    conversion.for('upcast').elementToAttribute({
      view: {
        name: 'a',
        attributes: ['href'],
        classes: 'btn btn-geneseo btn-primary'
      },
      model: {
        key: 'button',
        value: viewElement => viewElement.getAttribute('href'),
      },
      converterPriority: 'high'  // According to documentation this should be given priority
    });
  }

This is the result the first time the button is created. Noticed that it is recognized as a button model.

After saving the page and going back to the edit screen this is the result.

Why would this happen? What would I need to change?


问:
How to export data from a Tabulator table without a refresh of the table?
I am using Tabulator 5.4, and every time we export/download the table data, it forces a refresh of the table.

Is there a way to export without a refresh?


问:
machine learning python train eror
I am using train commands while doing bitcoin data analysis and I encountered an error :

```<code>data = df.set_index('Date')

dataset = df.values

training_data_len = math.ceil(len(dataset) * .8)

scaler = MinMaxScaler(feature_range=(0,1))
scaled_data = scaler.fit_transform(dataset)

train_data = scaled_data[0:training_data_len, :]

x_train = []
y_train = []

for i in range (60, len(train_data),1):
    x_train.append(train_data[i:60:i, 0])
    y_train.append(train_data[i, 0])

x_train, y_train = np.array(x_train), np.array(y_train)

x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))

es_callback = keras.callbacks.EarlyStopping(monitor='val_loss', patience=3)

model =Sequential()
model.add(LSTM(256, return_sequences=True , input_shape =(x_train.shape[1],1)))
</code>```

On the last line it should work fine but on the last line I get this error

slice index 0 of dimension 0 out of bounds. for '{{node
lstm_6/strided_slice_2}} = StridedSlice[Index=DT_INT32, T=DT_FLOAT,
begin_mask=0, ellipsis_mask=0, end_mask=0, new_axis_mask=0,
shrink_axis_mask=1](lstm_6/transpose, lstm_6/strided_slice_2/stack,
lstm_6/strided_slice_2/stack_1, lstm_6/strided_slice_2/stack_2)' with
input shapes: [0,?,1], [1], [1], [1] and with computed input tensors:
input[1] = <0>, input[2] = <1>, input[3] = <1>.

Title: machine learning python train eror

Body:
I am using train commands while doing bitcoin data analysis and I encountered an error :

data = df.set_index('Date')

dataset = df.values

training_data_len = math.ceil(len(dataset) * .8)

scaler = MinMaxScaler(feature_range=(0,1))
scaled_data = scaler.fit_transform(dataset)

train_data = scaled_data[0:training_data_len, :]

x_train = []
y_train = []

for i in range (60, len(train_data),1):
    x_train.append(train_data[i:60:i, 0])
    y_train.append(train_data[i, 0])

x_train, y_train = np.array(x_train), np.array(y_train)

x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))

es_callback = keras.callbacks.EarlyStopping(monitor='val_loss', patience=3)

model =Sequential()
model.add(LSTM(256, return_sequences=True , input_shape =(x_train.shape[1],1)))

On the last line it should work fine but on the last line I get this error

slice index 0 of dimension 0 out of bounds. for '{{node
lstm_6/strided_slice_2}} = StridedSlice[Index=DT_INT32, T=DT_FLOAT,
begin_mask=0, ellipsis_mask=0, end_mask=0, new_axis_mask=0,
shrink_axis_mask=1](lstm_6/transpose, lstm_6/strided_slice_2/stack,
lstm_6/strided_slice_2/stack_1, lstm_6/strided_slice_2/stack_2)' with
input shapes: [0,?,1], [1], [1], [1] and with computed input tensors:
input[1] = <0>, input[2] = <1>, input[3] = <1>.


问:
How to get the current width angle of the frustrum of the camera in scene kit, for the currently running device, screen etc?

using unprojectPoint simply doesn't work, it's broken or buggy

cam.fieldOfView just doesn't work, it returns strange values in all cases

xFov and yFov (deprecated) simply don't work now (and never did)

(Incredibly, I have to do this now, to actually find edges and hence know the camera viewing width angle. https://stackoverflow.com/a/72669555/294884 )

Does anyone know the current real solution?


问:
Catching SIGTRAP in C - without aborting the program
I would like to enable/set the trap flag on an x86_64 machine, then execute some instructions, then disable/unset the trap flag again. When trapping, I want my own handler to be called. My attempt to do this is below.

It does not work as expected, instead, the trap seems to happen and my program is aborted. Why is that so and how can I fix it?

The output I currently see is this (on a linux 5.10.0 machine):

```<code>./test
Starting execution...
Trace/breakpoint trap
</code>```
```<code>#include <assert.h>
#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

void setTrapFlag() {
  asm volatile("pushfq\n" // push status register to stack
               "xorl $0x100, (%rsp)\n" // set trap-flag of on-stack value
               "popfq\n" // pop status register
               );
}

void trapHandler(int signo, siginfo_t *info, void *context) {
  setTrapFlag();
}

int main ()
{
 struct sigaction trapSa;

 // set up trap signal handler
  trapSa.sa_flags = SA_SIGINFO;
  trapSa.sa_sigaction = trapHandler;
  int ret = sigaction(SIGTRAP, &trapSa, NULL);
  assert(ret == 0);

 printf("Starting execution...\n");
 setTrapFlag();
 printf("Set trap flag!\n");
 setTrapFlag();
 printf("UnSet trap flag!\n");

 printf ("all done\n");
 return 0;
}
</code>```

I was expecting an output of

```<code>./test
Starting execution...
Set trap flag!
UnSet trap flag!
all done
</code>```

Body:
I would like to enable/set the trap flag on an x86_64 machine, then execute some instructions, then disable/unset the trap flag again. When trapping, I want my own handler to be called. My attempt to do this is below.

It does not work as expected, instead, the trap seems to happen and my program is aborted. Why is that so and how can I fix it?

The output I currently see is this (on a linux 5.10.0 machine):

./test
Starting execution...
Trace/breakpoint trap

#include <assert.h>
#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

void setTrapFlag() {
  asm volatile("pushfq\n" // push status register to stack
               "xorl $0x100, (%rsp)\n" // set trap-flag of on-stack value
               "popfq\n" // pop status register
               );
}

void trapHandler(int signo, siginfo_t *info, void *context) {
  setTrapFlag();
}

int main ()
{
 struct sigaction trapSa;

 // set up trap signal handler
  trapSa.sa_flags = SA_SIGINFO;
  trapSa.sa_sigaction = trapHandler;
  int ret = sigaction(SIGTRAP, &trapSa, NULL);
  assert(ret == 0);

 printf("Starting execution...\n");
 setTrapFlag();
 printf("Set trap flag!\n");
 setTrapFlag();
 printf("UnSet trap flag!\n");

 printf ("all done\n");
 return 0;
}

I was expecting an output of

./test
Starting execution...
Set trap flag!
UnSet trap flag!
all done


问:
Show Remote Cursor Position correctly on Scaled Window
Im working on a shared Whiteboard Application with Canvas (React-Konva) and Websockets. On the page i want to show the a connected remote users cursor position on the page and it works well.

Problem:

When I the Host scale my Canvas the position of the remote Users cursor is wrong. How do i get the remote Users Cursor to still display correctly when i scale my Canvas?

Right Canvas unscaled

Right Canvas scaled

Heres my code for sending the cursorPosintion to the Server

Ive tried multiplying the user.cursorPositions with the canvas Scale but it makes it worse

```<code> const handleMouseMove = () => {
    if (stageRef.current) {
      const stage = stageRef.current;
      const pos = stage.getRelativePointerPosition();
      if (pos && socket) {
        const { x, y } = pos;
        const cursorPos = {
          x: x,
          y: y,
          remoteUser: socket.id,
          roomId: roomId,
        };
        if (socket !== null) {
          socket?.emit('cursor', cursorPos);
        }
      }
    }
  };
</code>```

Heres how i use it in the Canvas

```<code>  {users?.map((user) => (
        <>
          {stageRef.current && user.userId !== socket?.id && user.hasFocus === true && (
            <Cursor
              key={user.userId}
              userName={user.userName}
              x={user.cursorPos.x}
              y={user.cursorPos.y}
            />
          )}
        </>
      ))}
</code>```

Body:
Im working on a shared Whiteboard Application with Canvas (React-Konva) and Websockets. On the page i want to show the a connected remote users cursor position on the page and it works well.

Problem:

When I the Host scale my Canvas the position of the remote Users cursor is wrong. How do i get the remote Users Cursor to still display correctly when i scale my Canvas?

Right Canvas unscaled

Right Canvas scaled

Heres my code for sending the cursorPosintion to the Server

Ive tried multiplying the user.cursorPositions with the canvas Scale but it makes it worse

 const handleMouseMove = () => {
    if (stageRef.current) {
      const stage = stageRef.current;
      const pos = stage.getRelativePointerPosition();
      if (pos && socket) {
        const { x, y } = pos;
        const cursorPos = {
          x: x,
          y: y,
          remoteUser: socket.id,
          roomId: roomId,
        };
        if (socket !== null) {
          socket?.emit('cursor', cursorPos);
        }
      }
    }
  };

Heres how i use it in the Canvas

  {users?.map((user) => (
        <>
          {stageRef.current && user.userId !== socket?.id && user.hasFocus === true && (
            <Cursor
              key={user.userId}
              userName={user.userName}
              x={user.cursorPos.x}
              y={user.cursorPos.y}
            />
          )}
        </>
      ))}


问:
How to get the current route name inside a pinia store?
I'm creating an application that needs to query different collections for each view.

I believe that the simplest way to do this would be to assign the name of the route to a variable that corresponds to the name of the collection in the Firestore within my pinia store.

And then call that variable when querying the collection, like this.

```<code>async getNotes() {

      getNotesSnapshot = onSnapshot(collection(db, 'users', userId, thisRouteName)
, (querySnapshot) => {
        let notes = []
        querySnapshot.forEach((doc) => {
        let note = {
          id: doc.id,
          content: doc.data().content,
          date: doc.data().date
        }
        notes.push(note)

        })
        this.notes = notes
      })
    }
</code>```

How do I assign the current route name in thisRouteName variable?

Body:
I'm creating an application that needs to query different collections for each view.

I believe that the simplest way to do this would be to assign the name of the route to a variable that corresponds to the name of the collection in the Firestore within my pinia store.

And then call that variable when querying the collection, like this.

async getNotes() {

      getNotesSnapshot = onSnapshot(collection(db, 'users', userId, thisRouteName)
, (querySnapshot) => {
        let notes = []
        querySnapshot.forEach((doc) => {
        let note = {
          id: doc.id,
          content: doc.data().content,
          date: doc.data().date
        }
        notes.push(note)

        })
        this.notes = notes
      })
    }

How do I assign the current route name in thisRouteName variable?


问:
Jquery & vanilla javascript mixed, cart not reciving updated data [SOLVED]
to start I'm very new to code. Ive been stuck on this one problem for a week now and its killing me so i came here.

I want the h2 innerText of .item with the class of .item-selected to appear in cart once .cartadd is clicked

here's how I tired to do that:

```<code>let itemname = $('.item-selected h1').text();

    $('.cart').show()

      $('.cart').append('<h2>' + itemname + '</h2>');
</code>```

When I do this I don't get anything though as if it didn't exist

when I console.log

```<code>let items = $(.item-selected) console.log(items)
</code>```

I get log = Object { length: 0, prevObject: {…} }

I think the problem has to do with parts of the css being implemented by vanilla javascript and not jquery but not sure if that's the case or which part excatly.

heres that code

```<code>
const dropdowns = document.querySelectorAll('.dropdownbox')
const dropdowns2 = document.querySelectorAll('.dropdownbox2')
const itemboxQER = document.querySelectorAll('.item')

const shirtBox = document.querySelector('.shirtbox')
const hoodiebox = document.querySelector('.hoodiebox')
const sockbox = document.querySelector('.sockbox')
const pantbox = document.querySelector('.pantbox')
const underwearbox = document.querySelector('.underwearbox')
const stuffbox = document.querySelector('.stuffbox')
let selected;
//================CSS==========================

dropdowns.forEach(dropdown =>{
  const select = dropdown.querySelector('.select')
  const caret = dropdown.querySelector('.caret')
  const menu = dropdown.querySelector('.menu')
  const options = dropdown.querySelectorAll('.menu li')
  selected = dropdown.querySelector('.selected')

  select.addEventListener('click', () =>{
    sel2.pause()
    sel2.currentTime = 0
    sel2.play()
    select.classList.toggle('select-clicked')
    caret.classList.toggle('caret-rotate')
    menu.classList.toggle('menu-open')
  })

  options.forEach(option =>{
    option.addEventListener('click', () =>{
      sel2.pause()
      sel2.currentTime = 0
      sel2.play()
      selected.innerText = option.innerText

      if (selected.innerText === "Shirts") {
        shirtBox.style.display = "block";
      } else { shirtBox.style.display = "none";}

      if(selected.innerText === "Socks")
      {
        sockbox.style.display = "block";
      } else {sockbox.style.display = "none";}

      if(selected.innerText === "Hoodies")
      {
        hoodiebox.style.display = "block";
      } else {hoodiebox.style.display = "none";}

      if(selected.innerText === "Pants")
      {
        pantbox.style.display = "block";
      } else {pantbox.style.display = "none";}

      if(selected.innerText === "Underwear")
      {
        underwearbox.style.display = "block";
      } else {underwearbox.style.display = "none";}

      if(selected.innerText === "Stuff & Things")
      {
        stuffbox.style.display = "block";
      } else {stuffbox.style.display = "none";}

      select.classList.remove('select-clicked')
      caret.classList.remove('caret-rotate')
      menu.classList.remove('menu-open')
      options.forEach(option =>{
        option.classList.add('active')
      })
    })
  })
})
//====================================================

dropdowns2.forEach(dropdown =>{
  const select2 = dropdown.querySelector('.select2')
  const caret2 = dropdown.querySelector('.caret2')
  const menu2 = dropdown.querySelector('.menu2')
  const options2 = dropdown.querySelectorAll('.menu2 li')
  const selected2 = dropdown.querySelector('.selected2')

  select2.addEventListener('click', () =>{
    sel2.pause()
    sel2.currentTime = 0
    sel2.play()
    select2.classList.toggle('select-clicked2')
    caret2.classList.toggle('caret-rotate2')
    menu2.classList.toggle('menu-open2')
  })

  options2.forEach(option =>{
    option.addEventListener('click', () =>{
      sel2.pause()
      sel2.currentTime = 0
      sel2.play()
      selected2.innerText = option.innerText

      select2.classList.remove('select-clicked2')
      caret2.classList.remove('caret-rotate2')
      menu2.classList.remove('menu-open2')
      options2.forEach(option =>{
        option.classList.add('active2')
      })
    })
  })
})
//====================================================
itemboxQER.forEach(item =>{

  item.addEventListener('click', () =>
    {

      itemboxQER.forEach(otherItem => {
        if (otherItem !== item) {
          otherItem.classList.remove('item-selected');
        }
      });

    item.classList.toggle('item-selected')
    sel2.pause()
    sel2.currentTime = 0
    sel2.play()
    })

  })
</code>```

Any leads would be much appreciated!

relevant html (fixed duplicate id's, but same problem as they weren't used anyway)

```<code>          <div class="mainGUI" id="mainGUI">

      <button class="MIN" id="MIN">shrink/enlarge</button>

      <div class="dropdownbox" id="dropdownbox">
        <div class="select">
        <span class="selected" ><h1>SELECT CATEGORY </h1></span>
        <div class="caret"><img class="Icon" src="images/DOWNARROW.png" alt="broken"></div>
        </div>
        <ul class="menu" id="menu">
          <li class="Hoodies">Hoodies <img src="images/hoodie.png" alt=""></li>
          <li class="Shirts">Shirts <img src="images/shirt.png" alt=""></li>
          <li class="Pants">Pants <img src="images/pants.png" alt=""> </li>
          <li class="Underwear">Underwear <img src="images/under.png" alt=""></li>
          <li class="Socks">Socks <img src="images/socks.png" alt=""></li>
          <li class="StuffThings">Stuff & Things <img src="images/stuff.png" alt=""></li>
        </ul>
      </div>

<!-- OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOooooMERCHOoooOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO -->

<div class="shirtbox" id="shirtbox">

      <div class="item" id="freeshirt"><img src="images/shirttemp.png" alt="">

        <div class="itemHeaderBox">
          <h1>FREE PNG</h1>
          <div class="priceofitem">
            <h2>0$</h2>
          </div>
        </div>

      </div>

      <div class="item" id="rnbshirt"><img src="images/rnbbot.png" alt="">

        <div class="itemHeaderBox">
          <h1>RNB BOT SHIRT</h1>
          <div class="priceofitem">
            <h2>20$</h2>
          </div>
        </div>

      </div>

  </div>
<div class="hoodiebox" id="hoodiebox">

      <div class="item"><img src="images/hoodiloon.png" alt="">

        <div class="itemHeaderBox">
          <h1>FREE SHIRT PNG</h1>
        </div>

      </div>

  </div>
<div class="sockbox" id="sockbox">

<!-- /////// -->
  <div class="item" id="item"><img src="./images/sock.png" alt="">

    <div class="itemHeaderBox">
      <h1>FREE SHIRT PNG</h1>
    </div>
  </div>
  <!-- /////// -->

<!-- /////// -->
  <div class="item" id="item"><img src="./images/sock.png" alt="">

    <div class="itemHeaderBox">
      <h1>FREE SHIRT PNG</h1>
    </div>
  </div>
  <!-- /////// -->

<!-- /////// -->
  <div class="item" id="item"><img src="./images/sock.png" alt="">

    <div class="itemHeaderBox">
      <h1>FREE SHIRT PNG</h1>
    </div>
  </div>
  <!-- /////// -->

<!-- /////// -->
  <div class="item" id="item"><img src="./images/sock.png" alt="">

    <div class="itemHeaderBox">
      <h1>FREE SHIRT PNG</h1>
    </div>
  </div>
  <!-- /////// -->

<!-- /////// -->
  <div class="item" id="item"><img src="./images/sock.png" alt="">

    <div class="itemHeaderBox">
      <h1>FREE SHIRT PNG</h1>
    </div>
  </div>
  <!-- /////// -->

<!-- /////// -->
  <div class="item" id="item"><img src="./images/sock.png" alt="">

    <div class="itemHeaderBox">
      <h1>FREE SHIRT PNG</h1>
    </div>
  </div>
  <!-- /////// -->

  </div>
<div class="pantbox" id="pantbox">

      <div class="item"><img src="images/pantaloon.png" alt="">

        <div class="itemHeaderBox">
          <h1>FREE SHIRT PNG</h1>
        </div>

      </div>

  </div>
<div class="underwearbox" id="underwearbox">

      <div class="item"><img src="images/underiloon.png" alt="">

        <div class="itemHeaderBox">
          <h1>thong</h1>
        </div>

      </div>

  </div>
<div class="stuffbox" id="stuffbox">

      <div class="item" ><img src="images/catstuff.png" alt="">

        <div class="itemHeaderBox">
          <h1>cat</h1>
        </div>

      </div>

  </div>
  <!-- OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOooooMERCHOoooOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO -->

<!-- =======================================size/color================================================ -->
      <div class="dropdownbox2" id="dropdownsize">
        <div class="select2">
        <span class="selected2" id="selectedSize" ><h1>size</h1></span>
        <div class="caret2"><img class="Icon2" src="images/DOWNARROW.png" alt="broken"></div>
        </div>
        <ul class="menu2" id="sizemenu">
          <li class="small">small</li>
          <li class="medium">medium</li>
          <li class="large">large</li>
          <li class="X-large">X-large</li>
          <li class="XX-large">XX-large</li>
          <li class="XXX-large">XXX-large</li>
        </ul>
      </div>

      <div class="dropdownbox2" id="dropdowncolor">
        <div class="select2">
        <span class="selected2" id="selectedSize" ><h1>color</h1></span>
        <div class="caret2"><img class="Icon2" src="images/DOWNARROW.png" alt="broken"></div>
        </div>
        <ul class="menu2" id="colormenu">
          <li class="white">white</li>
          <li class="black">black</li>
          <li class="pink">pink</li>
          <li class="red">red</li>
          <li class="blue">blue</li>
          <li class="green">green</li>
        </ul>
      </div>

      <div class="cartadd" id="cartadd">Add to Cart</div>

      <div class="cart" id="cart">
        <div class="carttitle">CART</div>
      </div>

      <div class="done" id="done">DONE</div>

  </div>
</code>```

update, so the problem was a mix of jquery not detecting the change because the change was made in vanilla javascript & the check for .item-selected needed to be made a function and checked every frame:

```<code>  function SELECTCHECK(){
  $('.item').each(function() {

if ($(this).hasClass('item item-selected')) {

  itemprice = $(this).find('h2').text();
}

})}
</code>```

and the animation

```<code>  function TICK(timestamp) {

  requestAnimationFrame(TICK)

  SELECTCHECK()
}
requestAnimationFrame(TICK)
</code>```

hopefully this can help someone in the future. Rule of thumb, DONT't mix jquery event listeners with vanilla javascript event listeners.

Body:
to start I'm very new to code. Ive been stuck on this one problem for a week now and its killing me so i came here.

I want the h2 innerText of .item with the class of .item-selected to appear in cart once .cartadd is clicked

here's how I tired to do that:

let itemname = $('.item-selected h1').text();

    $('.cart').show()

      $('.cart').append('
' + itemname + '
');

When I do this I don't get anything though as if it didn't exist

when I console.log

let items = $(.item-selected) console.log(items)

I get log = Object { length: 0, prevObject: {…} }

I think the problem has to do with parts of the css being implemented by vanilla javascript and not jquery but not sure if that's the case or which part excatly.

heres that code

const dropdowns = document.querySelectorAll('.dropdownbox')
const dropdowns2 = document.querySelectorAll('.dropdownbox2')
const itemboxQER = document.querySelectorAll('.item')

const shirtBox = document.querySelector('.shirtbox')
const hoodiebox = document.querySelector('.hoodiebox')
const sockbox = document.querySelector('.sockbox')
const pantbox = document.querySelector('.pantbox')
const underwearbox = document.querySelector('.underwearbox')
const stuffbox = document.querySelector('.stuffbox')
let selected;
//================CSS==========================

dropdowns.forEach(dropdown =>{
  const select = dropdown.querySelector('.select')
  const caret = dropdown.querySelector('.caret')
  const menu = dropdown.querySelector('.menu')
  const options = dropdown.querySelectorAll('.menu li')
  selected = dropdown.querySelector('.selected')

  select.addEventListener('click', () =>{
    sel2.pause()
    sel2.currentTime = 0
    sel2.play()
    select.classList.toggle('select-clicked')
    caret.classList.toggle('caret-rotate')
    menu.classList.toggle('menu-open')
  })

  options.forEach(option =>{
    option.addEventListener('click', () =>{
      sel2.pause()
      sel2.currentTime = 0
      sel2.play()
      selected.innerText = option.innerText

      if (selected.innerText === "Shirts") {
        shirtBox.style.display = "block";
      } else { shirtBox.style.display = "none";}

      if(selected.innerText === "Socks")
      {
        sockbox.style.display = "block";
      } else {sockbox.style.display = "none";}

      if(selected.innerText === "Hoodies")
      {
        hoodiebox.style.display = "block";
      } else {hoodiebox.style.display = "none";}

      if(selected.innerText === "Pants")
      {
        pantbox.style.display = "block";
      } else {pantbox.style.display = "none";}

      if(selected.innerText === "Underwear")
      {
        underwearbox.style.display = "block";
      } else {underwearbox.style.display = "none";}

      if(selected.innerText === "Stuff & Things")
      {
        stuffbox.style.display = "block";
      } else {stuffbox.style.display = "none";}

      select.classList.remove('select-clicked')
      caret.classList.remove('caret-rotate')
      menu.classList.remove('menu-open')
      options.forEach(option =>{
        option.classList.add('active')
      })
    })
  })
})
//====================================================

dropdowns2.forEach(dropdown =>{
  const select2 = dropdown.querySelector('.select2')
  const caret2 = dropdown.querySelector('.caret2')
  const menu2 = dropdown.querySelector('.menu2')
  const options2 = dropdown.querySelectorAll('.menu2 li')
  const selected2 = dropdown.querySelector('.selected2')

  select2.addEventListener('click', () =>{
    sel2.pause()
    sel2.currentTime = 0
    sel2.play()
    select2.classList.toggle('select-clicked2')
    caret2.classList.toggle('caret-rotate2')
    menu2.classList.toggle('menu-open2')
  })

  options2.forEach(option =>{
    option.addEventListener('click', () =>{
      sel2.pause()
      sel2.currentTime = 0
      sel2.play()
      selected2.innerText = option.innerText

      select2.classList.remove('select-clicked2')
      caret2.classList.remove('caret-rotate2')
      menu2.classList.remove('menu-open2')
      options2.forEach(option =>{
        option.classList.add('active2')
      })
    })
  })
})
//====================================================
itemboxQER.forEach(item =>{

  item.addEventListener('click', () =>
    {

      itemboxQER.forEach(otherItem => {
        if (otherItem !== item) {
          otherItem.classList.remove('item-selected');
        }
      });

    item.classList.toggle('item-selected')
    sel2.pause()
    sel2.currentTime = 0
    sel2.play()
    })

  })

Any leads would be much appreciated!

relevant html (fixed duplicate id's, but same problem as they weren't used anyway)

      <button class="MIN" id="MIN">shrink/enlarge</button>

SELECT CATEGORY

Hoodies

Shirts

Pants

Underwear

Socks

Stuff & Things

FREE PNG

0$

RNB BOT SHIRT

20$

FREE SHIRT PNG

FREE SHIRT PNG

FREE SHIRT PNG

FREE SHIRT PNG

FREE SHIRT PNG

FREE SHIRT PNG

FREE SHIRT PNG

FREE SHIRT PNG

thong

cat

size

small

medium

large

X-large

XX-large

XXX-large

color

white

black

pink

red

blue

green

Add to Cart

CART

DONE

update, so the problem was a mix of jquery not detecting the change because the change was made in vanilla javascript & the check for .item-selected needed to be made a function and checked every frame:

  function SELECTCHECK(){
  $('.item').each(function() {

if ($(this).hasClass('item item-selected')) {

  itemprice = $(this).find('h2').text();
}

})}

and the animation

  function TICK(timestamp) {

  requestAnimationFrame(TICK)

  SELECTCHECK()
}
requestAnimationFrame(TICK)

hopefully this can help someone in the future. Rule of thumb, DONT't mix jquery event listeners with vanilla javascript event listeners.


问:
Create interactive ggraph tree with ggiraph package in RShiny app
I am trying to create an interactive ggraph tree plot (or network plot) using the ggiraph package. Previously I used the plotly package but hat didnt work since plotly doesnt support drawing edges.

For the ggiraph package I can get the graph to appear but I have nowhere to add a "tooltip" argument or data_id argument since ggraph uses 'geom_node_point' or 'geom_node_text' which do not have an equivalent 'geom_..._interactive' in the ggiraph package.

```<code># Packages ----------------------------------------------------
library(shiny)
library(plotly)
library(ggraph)
library(igraph)
library(ggiraph)

edges <- data.frame(c("Start", "Start"), c("P1", "P2"))
colnames(edges) <- c("from", "to")

vert <- data.frame(c("Start", "P1", "P2"), c(1, 2, 3), c("this", "is", "info"))
colnames(vert) <- c("name", "Value", "Info")

# Ui ---------------------------------------------------------
ui <- fluidPage(
  girafeOutput(outputId = "tree_plot_out")
)

# Server -----------------------------------------------------
server <- function(input, output, session) {
  #create Tree plot
  tree_plot <- reactive({
    g <- graph_from_data_frame(edges, vertices = vert)

    ggraph(g) +
      geom_edge_link() +
      geom_node_point(aes(col = V(g)$Value)) +
      geom_node_text(aes(label =  V(g)$Info), size = 5, nudge_y = -0.1)
  })

  # output tree plot
  output$tree_plot_out <- renderGirafe({
    girafe(ggobj = tree_plot())
  })

}

shinyApp(ui = ui, server = server)
</code>```

This is a reduced example with how I draw the interactive giraph plot. However I cant add the argument "tooltip" anywhere to display info on hovering.
Neither can I use the data_id function exeplified on the giraph website https://davidgohel.github.io/ggiraph/articles/offcran/shiny.html

How can I create an interactive plot from this?
Is there a workaround for plotly?

Body:
I am trying to create an interactive ggraph tree plot (or network plot) using the ggiraph package. Previously I used the plotly package but hat didnt work since plotly doesnt support drawing edges.

For the ggiraph package I can get the graph to appear but I have nowhere to add a "tooltip" argument or data_id argument since ggraph uses 'geom_node_point' or 'geom_node_text' which do not have an equivalent 'geom_..._interactive' in the ggiraph package.

# Packages ----------------------------------------------------
library(shiny)
library(plotly)
library(ggraph)
library(igraph)
library(ggiraph)

edges <- data.frame(c("Start", "Start"), c("P1", "P2"))
colnames(edges) <- c("from", "to")

vert <- data.frame(c("Start", "P1", "P2"), c(1, 2, 3), c("this", "is", "info"))
colnames(vert) <- c("name", "Value", "Info")

# Ui ---------------------------------------------------------
ui <- fluidPage(
  girafeOutput(outputId = "tree_plot_out")
)

# Server -----------------------------------------------------
server <- function(input, output, session) {
  #create Tree plot
  tree_plot <- reactive({
    g <- graph_from_data_frame(edges, vertices = vert)

    ggraph(g) +
      geom_edge_link() +
      geom_node_point(aes(col = V(g)$Value)) +
      geom_node_text(aes(label =  V(g)$Info), size = 5, nudge_y = -0.1)
  })

  # output tree plot
  output$tree_plot_out <- renderGirafe({
    girafe(ggobj = tree_plot())
  })

}

shinyApp(ui = ui, server = server)

This is a reduced example with how I draw the interactive giraph plot. However I cant add the argument "tooltip" anywhere to display info on hovering.
Neither can I use the data_id function exeplified on the giraph website https://davidgohel.github.io/ggiraph/articles/offcran/shiny.html

How can I create an interactive plot from this?
Is there a workaround for plotly?


问:
How to smoothly interpolate colors in a Voronoi diagram to remove cell borders?
I am trying to create a Voronoi diagram where the color of each cell smoothly interpolates between the colors of its nearest control points. Currently, there are visible borders between the cells in the diagram. How can I get rid of these borders and smoothly interpolate the colors of the cells?

here is a working example: https://codepen.io/miguel007/pen/BaPzxxy?editors=0011

this is the drawVoronoiNoise

function drawVoronoiNoise(canvas,cells=50,noiseScale=0.06,distortionStrength=5) {
  // Get the canvas context
  const ctx = canvas.getContext('2d');

  // Generate a random set of control points
  const controlPoints = [];
  for (let i = 0; i < cells; i++) {
    var x = seededRandom(i) * canvas.width
    var y = seededRandom(i+1) * canvas.height
    const j = noise(x/188.05, y/188.05)*255;

    controlPoints.push({
      x:x,
      y:y,
      color: {r:j ,g: j ,b: j }
    });
  }

//`rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`
  const points = [];
  for (let x = 0; x < canvas.width; x++) {
    for (let y = 0; y < canvas.height; y++) {
      points.push({x, y});
    }
  }
  // For each point, find the nearest control point
  for (const point of points) {
    let nearestDistance = Infinity;
    let nearestControlPoint;
    for (const controlPoint of controlPoints) {
      // Distort the distance between the point and the control point using noise
      const noiseX = noise(point.x * noiseScale, point.y * noiseScale) * distortionStrength;
      const noiseY = noise(point.x * noiseScale + 100, point.y * noiseScale + 100) * distortionStrength;
      const distance = Math.hypot(point.x - controlPoint.x + noiseX, point.y - controlPoint.y + noiseY);
      if (distance < nearestDistance) {
        nearestDistance = distance;
        nearestControlPoint = controlPoint;
      }
    }

    // Interpolate the color of the current point based on the distance to the nearest control point
    const color = nearestControlPoint.color;
    const t = 6*nearestDistance / Math.sqrt(canvas.width ** 2 + canvas.height ** 2);
    const r = Math.round(color.r + t * (255 - color.r));
    const g = Math.round(color.g + t * (255 - color.g));
    const b = Math.round(color.b + t * (255 - color.b));
    ctx.fillStyle = `rgb(${r}, ${g}, ${b})`;
    ctx.fillRect(point.x, point.y, 1, 1);
  }
}
```


问:
Applying fastai transforms to single input
I trained a CNN on audio spectrogram images using fastai. Here is my training code:

```<code>cfg = AudioConfig.BasicMelSpectrogram(n_fft=512)
a2s = AudioToSpec.from_cfg(cfg)
auds = DataBlock(blocks = (AudioBlock(crop_signal_to=6*1000), CategoryBlock),
                 get_x = ColReader("filename"),
                 splitter = CrossValidationSplitter(fold=1),
                 batch_tfms = [a2s],
                 get_y = ColReader("category"))
dbunch = auds.dataloaders(df_combined, bs=64)
learn = cnn_learner(dbunch,
            resnet18,
            n_in=1,  # <- This is the only audio specific modification here
            loss_func=CrossEntropyLossFlat(),
            metrics=[accuracy])
learn.export('model.pkl')
</code>```

Now, I want to load the model and run inference on a single input image. The code below runs:

```<code>learn.load('model.pkl')
test_file = 'test.wav'
learn.predict(test_file)
</code>```

This works, but my predictions are really off. I think I am not adequately transforming the input data to match to transforms performed on the training data.

How do I transform an individual audio file for inference? I can't find any documentation on this. I need to apply the crop_to_signal and a2s transforms.

Body:
I trained a CNN on audio spectrogram images using fastai. Here is my training code:

cfg = AudioConfig.BasicMelSpectrogram(n_fft=512)
a2s = AudioToSpec.from_cfg(cfg)
auds = DataBlock(blocks = (AudioBlock(crop_signal_to=6*1000), CategoryBlock),
                 get_x = ColReader("filename"),
                 splitter = CrossValidationSplitter(fold=1),
                 batch_tfms = [a2s],
                 get_y = ColReader("category"))
dbunch = auds.dataloaders(df_combined, bs=64)
learn = cnn_learner(dbunch,
            resnet18,
            n_in=1,  # <- This is the only audio specific modification here
            loss_func=CrossEntropyLossFlat(),
            metrics=[accuracy])
learn.export('model.pkl')

Now, I want to load the model and run inference on a single input image. The code below runs:

learn.load('model.pkl')
test_file = 'test.wav'
learn.predict(test_file)

This works, but my predictions are really off. I think I am not adequately transforming the input data to match to transforms performed on the training data.

How do I transform an individual audio file for inference? I can't find any documentation on this. I need to apply the crop_to_signal and a2s transforms.


问:
How to add scrollbars to Column?
I made scrollable content, but how to add scrollbarThumbVertical?

```<code>Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.SpaceBetween,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .verticalScroll(rememberScrollState())//how to add here scrollbar?
                .weight(1f, fill = false)
        ) {
            //content
        }
        //another not scrollable content
}
</code>```

Title: How to add scrollbars to Column?

Body:
I made scrollable content, but how to add scrollbarThumbVertical?

Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.SpaceBetween,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .verticalScroll(rememberScrollState())//how to add here scrollbar?
                .weight(1f, fill = false)
        ) {
            //content
        }
        //another not scrollable content
}


问:
How to add role claims to AzureAD token for Managed Identity?
The role assignments claims aren't coming through on receiving a token from AzureAD in our tenant for managed identities.

Here's an example of a token returned by AzureAD for the client id of an app registration:

Here's the token returned by AzureAD for a managed identity that has a role assigned to it (the role claims are not present):

The token from the managed identity has all the same properties except the roles.  I can see in azure that the managed identity has a role assignment, but it is not returning in the token.  Any advice?

I'm expecting the role assignments assigned to the Managed Identity to be returned in the AzureAD token.


问:
PYQT5 Cannot display window
I'm a pyqt novice. I try to build a window. This is my code

```<code>import sys

from PyQt5.QtWidgets import QApplication, QWidget

if __name__ == '__main__':
   app = QApplication(sys.argv)

   w = QWidget()

   # 设置窗口标题
   w.setWindowTitle("第一个PyQt")

   # 展示窗口
   w.show()

   # 程序进行循环等待状态
   app.exec()
</code>```

However, after running, no window is displayed and no related error is obtained. The console prints ：Process finished with exit code -1073741819 (0xC0000005)

I don't know why. Any help would be appreciated

Title: PYQT5 Cannot display window

Body:
I'm a pyqt novice. I try to build a window. This is my code

import sys

from PyQt5.QtWidgets import QApplication, QWidget

if __name__ == '__main__':
   app = QApplication(sys.argv)

   w = QWidget()

   # 设置窗口标题
   w.setWindowTitle("第一个PyQt")

   # 展示窗口
   w.show()

   # 程序进行循环等待状态
   app.exec()

However, after running, no window is displayed and no related error is obtained. The console prints ：Process finished with exit code -1073741819 (0xC0000005)

I don't know why. Any help would be appreciated


问:
Does the SpringBoot Hikari Data source property -> queryTimeout terminates the sql execution after the timeout happened?
In our SpringBoot application we use Stored Procedures and Spring.datasource.hikari.data-source-properties.queryTimeOut is set to 60 seconds

But after the queryTimeout the Application receives timeout exception but still the SP continues to run in the DB.

How to terminate the SQL execution once the timeout occurs


问:
Angular | Retrieve the length of an array in unit test directly from the component?
I have this method in my user.component.ts

```<code> getUsers() {
      this.userService.APIkey = this.urlVal as string
      this.userService.nUsers = this.nUserForm.value.userNumber;
    this.userService.getUsers().subscribe(users => this.users = users);
    this.userService.getUsers().subscribe(users => console.log(this.users = users)); //10

  }
</code>```

I would like to retrieve the length of the array in the unit test of user.component.spec.ts, but this way I get this error "Expected 0 to equal 10."

```<code>it("method getUsers().length", () => {
  spyOn(component, 'getUsers').and.returnValue()
  fixture.detectChanges();
  expect(component.getUsers.length).toEqual(10);
});
</code>```

How can I do? Is this a value I can get from the component or do I have to get it from user.service.spec.ts?

Body:
I have this method in my user.component.ts

 getUsers() {
      this.userService.APIkey = this.urlVal as string
      this.userService.nUsers = this.nUserForm.value.userNumber;
    this.userService.getUsers().subscribe(users => this.users = users);
    this.userService.getUsers().subscribe(users => console.log(this.users = users)); //10

  }

I would like to retrieve the length of the array in the unit test of user.component.spec.ts, but this way I get this error "Expected 0 to equal 10."

it("method getUsers().length", () => {
  spyOn(component, 'getUsers').and.returnValue()
  fixture.detectChanges();
  expect(component.getUsers.length).toEqual(10);
});

How can I do? Is this a value I can get from the component or do I have to get it from user.service.spec.ts?


问:
pytorch-pretrained-bert and pytorch-transformers give different outputs?
I'm migrating my code from pytorch-pretrained-bert to pytorch-transformers. Testing the same code expecting same outputs.

I used identical code to pass a sentence through pytorch_pretrained_bert and transformers. I expected the 24 encoding layers should have the same output. However, that's the case. What am I missing? Thanks!

```<code>
from pytorch_pretrained_bert import BertTokenizer, BertModel
import torch
torch.manual_seed(0)
tokenizer = BertTokenizer.from_pretrained('bert-large-cased', do_lower_case=False)
model = BertModel.from_pretrained('bert-large-cased')
model.eval()
model.to(device)
text = "[CLS] Who was Jim Henson ? [SEP] Jim Henson was a puppeteer [SEP]"
tokenized_text = tokenizer.tokenize(text)
indexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_text)
segments_ids = [1 for x in tokenized_text]
tokens_tensor = torch.tensor([indexed_tokens])
segments_tensors = torch.tensor([segments_ids])
tokens_tensor = tokens_tensor.to('cuda')
segments_tensors = segments_tensors.to('cuda')
with torch.no_grad():
    outputs = model(tokens_tensor, segments_tensors)

#%%
import torch
from transformers import BertTokenizer, BertModel, BertForMaskedLM
torch.manual_seed(0)
tokenizer = BertTokenizer.from_pretrained('bert-large-cased', do_lower_case=False)
model = BertModel.from_pretrained('bert-large-cased', output_hidden_states=True)
model.eval()
model.to(device)
text = "[CLS] Who was Jim Henson ? [SEP] Jim Henson was a puppeteer [SEP]"
tokenized_text = tokenizer.tokenize(text)
indexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_text)
segments_ids = [1 for x in tokenized_text]
tokens_tensor = torch.tensor([indexed_tokens])
segments_tensors = torch.tensor([segments_ids])
tokens_tensor = tokens_tensor.to('cuda')
segments_tensors = segments_tensors.to('cuda')
with torch.no_grad():
    outputs = model(tokens_tensor, segments_tensors)
</code>```

System Info

transformers version: 4.25.1

Platform: Linux-5.4.0-122-generic-x86_64-with-glibc2.31

Python version: 3.9.5

Huggingface_hub version: 0.11.1

PyTorch version (GPU?): 1.13.1+cu117 (True)

Body:
I'm migrating my code from pytorch-pretrained-bert to pytorch-transformers. Testing the same code expecting same outputs.

I used identical code to pass a sentence through pytorch_pretrained_bert and transformers. I expected the 24 encoding layers should have the same output. However, that's the case. What am I missing? Thanks!

from pytorch_pretrained_bert import BertTokenizer, BertModel
import torch
torch.manual_seed(0)
tokenizer = BertTokenizer.from_pretrained('bert-large-cased', do_lower_case=False)
model = BertModel.from_pretrained('bert-large-cased')
model.eval()
model.to(device)
text = "[CLS] Who was Jim Henson ? [SEP] Jim Henson was a puppeteer [SEP]"
tokenized_text = tokenizer.tokenize(text)
indexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_text)
segments_ids = [1 for x in tokenized_text]
tokens_tensor = torch.tensor([indexed_tokens])
segments_tensors = torch.tensor([segments_ids])
tokens_tensor = tokens_tensor.to('cuda')
segments_tensors = segments_tensors.to('cuda')
with torch.no_grad():
    outputs = model(tokens_tensor, segments_tensors)

#%%
import torch
from transformers import BertTokenizer, BertModel, BertForMaskedLM
torch.manual_seed(0)
tokenizer = BertTokenizer.from_pretrained('bert-large-cased', do_lower_case=False)
model = BertModel.from_pretrained('bert-large-cased', output_hidden_states=True)
model.eval()
model.to(device)
text = "[CLS] Who was Jim Henson ? [SEP] Jim Henson was a puppeteer [SEP]"
tokenized_text = tokenizer.tokenize(text)
indexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_text)
segments_ids = [1 for x in tokenized_text]
tokens_tensor = torch.tensor([indexed_tokens])
segments_tensors = torch.tensor([segments_ids])
tokens_tensor = tokens_tensor.to('cuda')
segments_tensors = segments_tensors.to('cuda')
with torch.no_grad():
    outputs = model(tokens_tensor, segments_tensors)

System Info

transformers version: 4.25.1

Platform: Linux-5.4.0-122-generic-x86_64-with-glibc2.31

Python version: 3.9.5

Huggingface_hub version: 0.11.1

PyTorch version (GPU?): 1.13.1+cu117 (True)


问:
Session and JWT Callbacks Next Auth does not work
I have an issue with callbacks on Next Auth this is my code:

```<code>import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";

import connectDB from "../../../helpers/mongodb";
import User from "../../../models/auth/user";

export const authOptions = {
    session: {
        strategy: "jwt",
    },
    secret: process.env.NEXTAUTH_SECRET,
    providers: [
        CredentialsProvider({
            name: "Credentials",

            async authorize(credentials, req) {
                //Conectar a la DB
                await connectDB();

                //Buscar el usuario que esta intentando hacer login
                const userInDB = await User.findOne({ email: credentials.email });

                //Verificar que exista el usuario
                if (userInDB === "null") {
                    throw new Error("Usuario no encontrado!...");
                }

                //Verificar Password ingresada vs password en DB
                if (!userInDB.authenticate(credentials.password)) {
                    throw new Error("Usuario y Password no coinciden...");
                }

                const { _id, name, email, role, specialty, gender, currency } = userInDB;

                //Retornan el Token con la información que se requiere
                return userInDB;
            },
            callbacks: {
                async jwt({ token, user }) {
                    console.log("CALLBACK JWT ");
                    return Promise.resolve(token);
                },

                async session({ session, token }) {
                    console.log("ENTRO CALLBACK SESSION");
                    return Promise.resolve(session);
                },
            },
        }),
    ],
};

export default NextAuth(authOptions);
</code>```

The result on console.log is nothing... nothing happens... and the session has only the "Default" fields:

```<code>user: {name: 'Miguel2', email: 'miguel2@miguel.com'}
</code>```

So I tells me that the "Callbacks" are not triggerd.

Body:
I have an issue with callbacks on Next Auth this is my code:

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";

import connectDB from "../../../helpers/mongodb";
import User from "../../../models/auth/user";

export const authOptions = {
    session: {
        strategy: "jwt",
    },
    secret: process.env.NEXTAUTH_SECRET,
    providers: [
        CredentialsProvider({
            name: "Credentials",

            async authorize(credentials, req) {
                //Conectar a la DB
                await connectDB();

                //Buscar el usuario que esta intentando hacer login
                const userInDB = await User.findOne({ email: credentials.email });

                //Verificar que exista el usuario
                if (userInDB === "null") {
                    throw new Error("Usuario no encontrado!...");
                }

                //Verificar Password ingresada vs password en DB
                if (!userInDB.authenticate(credentials.password)) {
                    throw new Error("Usuario y Password no coinciden...");
                }

                const { _id, name, email, role, specialty, gender, currency } = userInDB;

                //Retornan el Token con la información que se requiere
                return userInDB;
            },
            callbacks: {
                async jwt({ token, user }) {
                    console.log("CALLBACK JWT ");
                    return Promise.resolve(token);
                },

                async session({ session, token }) {
                    console.log("ENTRO CALLBACK SESSION");
                    return Promise.resolve(session);
                },
            },
        }),
    ],
};

export default NextAuth(authOptions);

The result on console.log is nothing... nothing happens... and the session has only the "Default" fields:

user: {name: 'Miguel2', email: 'miguel2@miguel.com'}

So I tells me that the "Callbacks" are not triggerd.


问:
Scrapy to parse multiple URLs into a single json
Currently using scrapy with multiple URLs on the start_urls parameter which I load like this:

```<code>    with open('urllist.txt') as f:
        start_urls = f.read().splitlines()
</code>```

Then, I parse it the page with this code:

```<code>    def parse(self, response):
    yield {
            'date': datetime.now().strftime("%d/%m/%Y %H:%M"),
            'item': response.xpath("//font[contains(@id, 'item')]/a/text()").get(),
            'price': response.xpath("//font[contains(@id, 'price')]/a/text()").get(),
          }
</code>```

It works fine, but the resulting json file looks like this (notice two lines per execution):

```<code>{"date": "05/01/2023 02:39:49", "item": "Item 1", "price": "6.80"}
{"date": "05/01/2023 02:39:49", "item": "Item 2", "price": "8.50"}
{"date": "06/01/2023 02:39:49", "item": "Item 1", "price": "6.70"}
{"date": "06/01/2023 02:39:49", "item": "Item 2", "price": "8.50"}
</code>```

My expectation was something like:

```<code>{"scans": [
    {"date": "05/01/2023 02:39:49", "item": "Item 1", "price": "6.80"},
    {"date": "05/01/2023 02:39:49", "item": "Item 2", "price": "8.50"},
    {"date": "06/01/2023 02:39:49", "item": "Item 1", "price": "6.70"},
    {"date": "06/01/2023 02:39:49", "item": "Item 2", "price": "8.50"}]}
</code>```

Should I post-process the results to add the "scans" level? I will later import this on a page and ajax doesn't like broken JSON files.

Body:
Currently using scrapy with multiple URLs on the start_urls parameter which I load like this:

    with open('urllist.txt') as f:
        start_urls = f.read().splitlines()

Then, I parse it the page with this code:

    def parse(self, response):
    yield {
            'date': datetime.now().strftime("%d/%m/%Y %H:%M"),
            'item': response.xpath("//font[contains(@id, 'item')]/a/text()").get(),
            'price': response.xpath("//font[contains(@id, 'price')]/a/text()").get(),
          }

It works fine, but the resulting json file looks like this (notice two lines per execution):

{"date": "05/01/2023 02:39:49", "item": "Item 1", "price": "6.80"}
{"date": "05/01/2023 02:39:49", "item": "Item 2", "price": "8.50"}
{"date": "06/01/2023 02:39:49", "item": "Item 1", "price": "6.70"}
{"date": "06/01/2023 02:39:49", "item": "Item 2", "price": "8.50"}

My expectation was something like:

{"scans": [
    {"date": "05/01/2023 02:39:49", "item": "Item 1", "price": "6.80"},
    {"date": "05/01/2023 02:39:49", "item": "Item 2", "price": "8.50"},
    {"date": "06/01/2023 02:39:49", "item": "Item 1", "price": "6.70"},
    {"date": "06/01/2023 02:39:49", "item": "Item 2", "price": "8.50"}]}

Should I post-process the results to add the "scans" level? I will later import this on a page and ajax doesn't like broken JSON files.