问:
JS/TS Nested Structures with functions - Class instances vs Helpers
I Have made a little test example of nested classes with typescript interfaces.

I would like to have the least amount of duplication of my interfaces. My thought process was: I need some kind of base interface (without class references) to receive the data from the API. Then modify some of the properties to be class instances instead of objects with data. and create those classes inside the constructor.

This is what I came up with:

Example 1:

```<code>    interface TestInterface {
        id: number
        title: string
    }

    class TestClass implements TestInterface {
        title
        id

        constructor(data: TestInterface) {
            this.title = data.title
            this.id = data.id
        }

        getDescription = () => `${this.id}: ${this.title}`
    }

    interface TestWrapperInterface {
        id: number
        tests: Array<TestInterface>
    }

    interface TestWrapperClassInterface extends TestWrapperInterface {
        tests: Array<TestClass>
    }

    class TestWrapperClass implements TestWrapperClassInterface {
        id: number
        tests: Array<TestClass>

        constructor(data: TestWrapperInterface) {
            this.id = data.id
            this.tests = data.tests.map((test) => new TestClass(test))
        }

        getTestsDescriptions = () => {
            this.tests.map((test) => test.getDescription()).join(', ')
        }
    }

    // mock api function
    const getDataFromApi: () => TestWrapperInterface = () => ({
        id: 99,
        tests: [
            {
                id: 1,
                title: 'foo',
            },
            {
                id: 2,
                title: 'bar',
            },
        ],
    })

    const Wrapper = new TestWrapperClass(getDataFromApi())
    Wrapper.getTestsDescriptions()

</code>```

What would be the best way to type something like this?
Is there any way to avoid the TestWrapperClassInterface and make it more generic with typescript?

I also thought of using helperClasses:

Example 2:

```<code>    interface TestInterface {
        id: number
        title: string
    }

    interface TestWrapperInterface {
        id: number
        tests: Array<TestInterface>
    }

    const TestHelper = {
        getDescription(test: TestInterface) {
            return `${test.id}: ${test.title}`
        },
    }

    const WrapperHelper = {
        getTestDescriptions(wrapper: TestWrapperInterface) {
            wrapper.tests.map((test) => TestHelper.getDescription(test)).join(', ')
        },
    }

    const getDataFromApi: () => TestWrapperInterface = () => ({
        id: 99,
        tests: [
            {
                id: 1,
                title: 'foo',
            },
            {
                id: 2,
                title: 'bar',
            },
        ],
    })
    WrapperHelper.getTestDescriptions(getDataFromApi())
</code>```

This approach would avoid having to make nested classes / interfaces for those classes.

Differences I see:

Helpers are more verbose (WrapperHelper.getTestDescriptions(wapper) vs wrapper.getTestDescriptions()).

Storing a Class in something like local storage would require some kind of way to encode/decode and the pure object notation would not. (I do not know of any libaries that do this well)

I also think that when some objects extend others I will have a lot of duplication using the way I did it in example 1.
eg:

```<code>    interface TurboTestWrapperInterface extends TestWrapperInterface {
        turboEnabled: boolean
    }
    interface TurboTestWrapperClassInterface extends TurboTestWrapperInterface {
        tests: Array<TestClass>
    }

    class TurboTestWrapperClass extends TestWrapperClass implements TurboTestWrapperClassInterface {
        turboEnabled

        constructor(data: TurboTestWrapperInterface) {
            super(data)
            this.turboEnabled = data.turboEnabled
        }

        getSpeed = () => (this.turboEnabled ? 9001 : 1000)
    }
</code>```

vs helper classes:

```<code>    interface TurboTestWrapperInterface extends TestWrapperInterface {
        turboEnabled: boolean
    }

    // add in TestHelper:
    getSpeed = (turboTestWrapper: TurboTestWrapperInterface) => (this.turboEnabled ? 9001 : 1000)
</code>```

Are there any other obvious advantages or disadvantages over the 2 ?

Past experiences / other approaches to this problem are also welcome.. I am just trying to find the best way to structure this before I start coding on a new project which will have some nested structures (and functions that will depend on child class values (3+ levels deep)). Would also love to hear if there are any third party libraries around that address this problem.

Body:
I Have made a little test example of nested classes with typescript interfaces.

I would like to have the least amount of duplication of my interfaces. My thought process was: I need some kind of base interface (without class references) to receive the data from the API. Then modify some of the properties to be class instances instead of objects with data. and create those classes inside the constructor.

This is what I came up with:

Example 1:

    interface TestInterface {
        id: number
        title: string
    }

    class TestClass implements TestInterface {
        title
        id

        constructor(data: TestInterface) {
            this.title = data.title
            this.id = data.id
        }

        getDescription = () => `${this.id}: ${this.title}`
    }

    interface TestWrapperInterface {
        id: number
        tests: Array<TestInterface>
    }

    interface TestWrapperClassInterface extends TestWrapperInterface {
        tests: Array<TestClass>
    }

    class TestWrapperClass implements TestWrapperClassInterface {
        id: number
        tests: Array<TestClass>

        constructor(data: TestWrapperInterface) {
            this.id = data.id
            this.tests = data.tests.map((test) => new TestClass(test))
        }

        getTestsDescriptions = () => {
            this.tests.map((test) => test.getDescription()).join(', ')
        }
    }

    // mock api function
    const getDataFromApi: () => TestWrapperInterface = () => ({
        id: 99,
        tests: [
            {
                id: 1,
                title: 'foo',
            },
            {
                id: 2,
                title: 'bar',
            },
        ],
    })

    const Wrapper = new TestWrapperClass(getDataFromApi())
    Wrapper.getTestsDescriptions()

What would be the best way to type something like this?
Is there any way to avoid the TestWrapperClassInterface and make it more generic with typescript?

I also thought of using helperClasses:

Example 2:

    interface TestInterface {
        id: number
        title: string
    }

    interface TestWrapperInterface {
        id: number
        tests: Array<TestInterface>
    }

    const TestHelper = {
        getDescription(test: TestInterface) {
            return `${test.id}: ${test.title}`
        },
    }

    const WrapperHelper = {
        getTestDescriptions(wrapper: TestWrapperInterface) {
            wrapper.tests.map((test) => TestHelper.getDescription(test)).join(', ')
        },
    }

    const getDataFromApi: () => TestWrapperInterface = () => ({
        id: 99,
        tests: [
            {
                id: 1,
                title: 'foo',
            },
            {
                id: 2,
                title: 'bar',
            },
        ],
    })
    WrapperHelper.getTestDescriptions(getDataFromApi())

This approach would avoid having to make nested classes / interfaces for those classes.

Differences I see:

Helpers are more verbose (WrapperHelper.getTestDescriptions(wapper) vs wrapper.getTestDescriptions()).

Storing a Class in something like local storage would require some kind of way to encode/decode and the pure object notation would not. (I do not know of any libaries that do this well)

I also think that when some objects extend others I will have a lot of duplication using the way I did it in example 1.
eg:

    interface TurboTestWrapperInterface extends TestWrapperInterface {
        turboEnabled: boolean
    }
    interface TurboTestWrapperClassInterface extends TurboTestWrapperInterface {
        tests: Array<TestClass>
    }

    class TurboTestWrapperClass extends TestWrapperClass implements TurboTestWrapperClassInterface {
        turboEnabled

        constructor(data: TurboTestWrapperInterface) {
            super(data)
            this.turboEnabled = data.turboEnabled
        }

        getSpeed = () => (this.turboEnabled ? 9001 : 1000)
    }

vs helper classes:

    interface TurboTestWrapperInterface extends TestWrapperInterface {
        turboEnabled: boolean
    }

    // add in TestHelper:
    getSpeed = (turboTestWrapper: TurboTestWrapperInterface) => (this.turboEnabled ? 9001 : 1000)

Are there any other obvious advantages or disadvantages over the 2 ?

Past experiences / other approaches to this problem are also welcome.. I am just trying to find the best way to structure this before I start coding on a new project which will have some nested structures (and functions that will depend on child class values (3+ levels deep)). Would also love to hear if there are any third party libraries around that address this problem.


来源: stackexchange

问:
How to make my SDK file which it serves as a KEY available in my EC2 instance and hide it
I have a running django app which when on server does not find my .json file to
access my sdk key.

Is there a way to make it available just like you do with string variable ?

So far I'v tried this :

GOOGLE_APPLICATION_CREDENTIALS = '.env_files/service-account-file.json'

which it work locally

ContentLicense: CC BY-SA 4.0


问:
Extracting initVect from node stream a deciphering the rest
I have readableStream with an encrypted file and I would like to decrypt it. So far I was able to create 2 readableStreams - with 1 I extracted the IV and the second was used to decrypt the rest of the data, but I would like to just pipe it into one stream - both IV extraction AND the decryption. Something like this:

 function getDecryptionStream(password, initVectLength = 16) {
  const cipherKey = getCipherKey(password);
  const unzip = zlib.createUnzip();
  return new Transform({
      transform(chunk, encoding, callback) {
          if (!this.initVect) {
              this.initVect = chunk.subarray(0, initVectLength);
              chunk = chunk.subarray(initVectLength, chunk.length);
          }
          const decipher = crypto.createDecipheriv(algorithm, cipherKey, this.initVect);
          callback(null, chunk.pipe(decipher).pipe(unzip));
      }
  });
}

function decrypt({ file, newFile, passphrase }) {
  const readStream = fs.createReadStream(file);
  const writeStream = fs.createWriteStream(newFile);

  const decryptStream = getDecryptionStream(passphrase , IV_LENGTH);

  readStream
    .pipe(decryptStream)
    .pipe(writeStream);
}
```

However I cannot figure out, how to process the chunk as chunk.pipe(decipher) throws an error. TypeError: chunk.pipe is not a function as it as Buffer

Body:
I have readableStream with an encrypted file and I would like to decrypt it. So far I was able to create 2 readableStreams - with 1 I extracted the IV and the second was used to decrypt the rest of the data, but I would like to just pipe it into one stream - both IV extraction AND the decryption. Something like this:

 function getDecryptionStream(password, initVectLength = 16) {
  const cipherKey = getCipherKey(password);
  const unzip = zlib.createUnzip();
  return new Transform({
      transform(chunk, encoding, callback) {
          if (!this.initVect) {
              this.initVect = chunk.subarray(0, initVectLength);
              chunk = chunk.subarray(initVectLength, chunk.length);
          }
          const decipher = crypto.createDecipheriv(algorithm, cipherKey, this.initVect);
          callback(null, chunk.pipe(decipher).pipe(unzip));
      }
  });
}

function decrypt({ file, newFile, passphrase }) {
  const readStream = fs.createReadStream(file);
  const writeStream = fs.createWriteStream(newFile);

  const decryptStream = getDecryptionStream(passphrase , IV_LENGTH);

  readStream
    .pipe(decryptStream)
    .pipe(writeStream);
}

However I cannot figure out, how to process the chunk as chunk.pipe(decipher) throws an error. TypeError: chunk.pipe is not a function as it as Buffer


问:
why response null when return auth()->user() with Api laravel 8
I made a login controller in

and did the validation so this part is not a problem
But after authentication, I want** return auth()->user()** it to be done, but the answer is null comes back. It should be noted that I am writing Api

auth pakage laravel 8 api


问:
Click eventlistener not working for dynamically created button
click eventlistener for archiveBtn is not responding when its clicked.what's wrong.`

```<code>function readMail(id,mailbox){
  document.querySelector('#emails-view').style.display = 'none';
  document.querySelector('#compose-view').style.display = 'none';
  document.querySelector('#read-view').style.display = 'block';
  fetch(`/emails/${id}`)
  .then(response => response.json())
  .then(email => {
    document.querySelector('#read-view').innerHTML = `
    <b>From: </b>${email.sender}<br>
    <b>To: </b>${email.recipients}<br>
    <b>Subject: </b>${email.subject}<br>
    <b>Timestamp: </b>${email.timestamp}<br><br>
    <button class="btn btn-sm btn-outline-primary" id="reply">Reply</button> `
    // archive
    if (mailbox != 'sent'){
      const archiveBtn= document.createElement('button');
      archiveBtn.className = email.archived? 'btn btn-sm btn-outline-danger' : 'btn btn-sm btn-outline-success';
      archiveBtn.innerHTML = email.archived? 'Unarchive' : 'Archive';
      document.querySelector('#read-view').append(archiveBtn);
      archiveBtn.addEventListener('click',function(){
        console.log('This element has been clicked!');
        fetch(`/emails/${id}`, {
          method: 'PUT',
          body: JSON.stringify({
            archived: !email.archived
          })
        })
        .then(()=>loadMailbox('inbox'));
      });
    }
</code>```

`

i tried onClick,tried writing outside if statement,none of it works.
note:the readMail function is called by eventlistener in other function.

Body:
click eventlistener for archiveBtn is not responding when its clicked.what's wrong.`

function readMail(id,mailbox){
  document.querySelector('#emails-view').style.display = 'none';
  document.querySelector('#compose-view').style.display = 'none';
  document.querySelector('#read-view').style.display = 'block';
  fetch(`/emails/${id}`)
  .then(response => response.json())
  .then(email => {
    document.querySelector('#read-view').innerHTML = `
    From: ${email.sender}

    To: ${email.recipients}

    Subject: ${email.subject}

    Timestamp: ${email.timestamp}

    <button class="btn btn-sm btn-outline-primary" id="reply">Reply</button> `
    // archive
    if (mailbox != 'sent'){
      const archiveBtn= document.createElement('button');
      archiveBtn.className = email.archived? 'btn btn-sm btn-outline-danger' : 'btn btn-sm btn-outline-success';
      archiveBtn.innerHTML = email.archived? 'Unarchive' : 'Archive';
      document.querySelector('#read-view').append(archiveBtn);
      archiveBtn.addEventListener('click',function(){
        console.log('This element has been clicked!');
        fetch(`/emails/${id}`, {
          method: 'PUT',
          body: JSON.stringify({
            archived: !email.archived
          })
        })
        .then(()=>loadMailbox('inbox'));
      });
    }

`

i tried onClick,tried writing outside if statement,none of it works.
note:the readMail function is called by eventlistener in other function.


问:
Delete EC2 AMIs created by AWS backups using AWS CLI
There are many AMIs created on AWS using some periodic job for backups. I have root credentials and need to delete old AMIs to clean up the space.
But whenever I run deregister command I get the error:
An error occurred (AuthFailure) when calling the DeregisterImage operation: Not authorized
And the ownerId is different from the root user id.

Is there some way or method I can delete those AMIs using AWS CLI?


问:
changing x-axis of FFT plot
This is my first post here and im new to coding just to let you know.

i want to make a fft analysis of a time-series dataset spanning one year with datapoints in 15 minute intervals. The dataset I use represents the state of charge of a battery in %. I want to see the different loading cycles (horly, weekly, monthly).

I watched some youtube videos and applied the code of this video to my own data: https://www.youtube.com/watch?v=su9YSmwZmPg

here is my code:

```<code>from numpy.fft import fft, fftfreq, ifft
import matplotlib.pyplot as plt, mpld3

# setup domain
# number of points (15 min intervals within 1 year)
nl = 34943

# lengt of watched domain
# 1 year in hours
lx    = 34943/4

# creating x-achsis
x = np.linspace(0, lx, nl)

# full signal
# dataset of different values troughout the year
y = np.array(df['SOC_batt'])

# creating nexessary frequencies
freqs = fftfreq(nl)

# splitting frequencies in half
mask = freqs > 0

# fft values
fft_vals = fft(y)

# true theoretical fft
fft_theo = 2.0*np.abs(fft_vals/nl)

plt.figure(1)
plt.title('original data')
plt.plot(x, y, color='xkcd:salmon')

plt.figure(2)
# fft processed
plt.plot(freqs[mask], fft_theo[mask], label='true fft values')
plt.title('true fft values')
mpld3.display()`
</code>```

these are the plots i get.
enter image description here

enter image description here

I zoomed in the fft graph and got these x values from the peaks:

```<code># first peack of 4 at 0.01041
# second peak of 5 at 0.02083
# third peack of 1.1 at 0.03125
</code>```

how can i translate these into more meaningful values regarding im dealing with a whole year of data?
Im not sure how to include data in the post I hope my problem is still understandable though.

thanks in advance

Title: changing x-axis of FFT plot

Body:
This is my first post here and im new to coding just to let you know.

i want to make a fft analysis of a time-series dataset spanning one year with datapoints in 15 minute intervals. The dataset I use represents the state of charge of a battery in %. I want to see the different loading cycles (horly, weekly, monthly).

I watched some youtube videos and applied the code of this video to my own data: https://www.youtube.com/watch?v=su9YSmwZmPg

here is my code:

from numpy.fft import fft, fftfreq, ifft
import matplotlib.pyplot as plt, mpld3

# setup domain
# number of points (15 min intervals within 1 year)
nl = 34943

# lengt of watched domain
# 1 year in hours
lx    = 34943/4

# creating x-achsis
x = np.linspace(0, lx, nl)

# full signal
# dataset of different values troughout the year
y = np.array(df['SOC_batt'])

# creating nexessary frequencies
freqs = fftfreq(nl)

# splitting frequencies in half
mask = freqs > 0

# fft values
fft_vals = fft(y)

# true theoretical fft
fft_theo = 2.0*np.abs(fft_vals/nl)

plt.figure(1)
plt.title('original data')
plt.plot(x, y, color='xkcd:salmon')

plt.figure(2)
# fft processed
plt.plot(freqs[mask], fft_theo[mask], label='true fft values')
plt.title('true fft values')
mpld3.display()`

these are the plots i get.
enter image description here

enter image description here

I zoomed in the fft graph and got these x values from the peaks:

# first peack of 4 at 0.01041
# second peak of 5 at 0.02083
# third peack of 1.1 at 0.03125

how can i translate these into more meaningful values regarding im dealing with a whole year of data?
Im not sure how to include data in the post I hope my problem is still understandable though.

thanks in advance


问:
Floating point exception (core dumped) in linux 64bit nasm assembly
I want to write a simple program that takes two integer numbers, divides them, converts the result into string and prints it to a screen.

Here's the part of code I got. It converts floating point number to an integer portion. There's an error there somewhere. It causes the floating point exception. Here I've tried to explain myself what actually happens within my program

```<code>_getTempIntegerPortion:
        mov r8, temp
        mov rcx, 10
        xor rdx, rdx

; Input - rax as integer, r8 as pointer to temp, rcx is 10
_assignTempIntegerPortion:
        div rcx
        cmp rax, 0
        mov rax, rdx
        add rdx, 48
        mov [r8], dl
        inc r8
        jne _assignTempIntegerPortion
        ret

</code>```

Body:
I want to write a simple program that takes two integer numbers, divides them, converts the result into string and prints it to a screen.

Here's the part of code I got. It converts floating point number to an integer portion. There's an error there somewhere. It causes the floating point exception. Here I've tried to explain myself what actually happens within my program

_getTempIntegerPortion:
        mov r8, temp
        mov rcx, 10
        xor rdx, rdx

; Input - rax as integer, r8 as pointer to temp, rcx is 10
_assignTempIntegerPortion:
        div rcx
        cmp rax, 0
        mov rax, rdx
        add rdx, 48
        mov [r8], dl
        inc r8
        jne _assignTempIntegerPortion
        ret


问:
Inconsistant Panadas column data type
I have a pandas dataframe loaded from a TSV file:

```<code>ig_data = pd.read_csv('cparty_extract.txt', sep='\t', encoding="cp1252", usecols=['CParty_Id', 'CParty_IG']
</code>```

I can look up all the rows based on CParty_Id number value as shown below:

```<code>>>> ig_data.loc[ig_data['CParty_Id'] ==1005804, 'CParty_Id']
90991    1005804
Name: CParty_Id, dtype: object
>>> ig_data.loc[ig_data['CParty_Id'] ==870178, 'CParty_Id']
91000    870178
Name: CParty_Id, dtype: object
</code>```

except for one row which I have to quote the CParty_Id number value or else it will return a empty series:

```<code>>>> ig_data.loc[ig_data['CParty_Id'] == 140566, 'CParty_Id']
Series([], Name: CParty_Id, dtype: object)
>>> ig_data.loc[ig_data['CParty_Id'] == '140566', 'CParty_Id']
12340    140566
Name: CParty_Id, dtype: object
</code>```

Does anybody know what is issue with this particular row?

Title: Inconsistant Panadas column data type

Body:
I have a pandas dataframe loaded from a TSV file:

ig_data = pd.read_csv('cparty_extract.txt', sep='\t', encoding="cp1252", usecols=['CParty_Id', 'CParty_IG']

I can look up all the rows based on CParty_Id number value as shown below:

>>> ig_data.loc[ig_data['CParty_Id'] ==1005804, 'CParty_Id']
90991    1005804
Name: CParty_Id, dtype: object
>>> ig_data.loc[ig_data['CParty_Id'] ==870178, 'CParty_Id']
91000    870178
Name: CParty_Id, dtype: object

except for one row which I have to quote the CParty_Id number value or else it will return a empty series:

>>> ig_data.loc[ig_data['CParty_Id'] == 140566, 'CParty_Id']
Series([], Name: CParty_Id, dtype: object)
>>> ig_data.loc[ig_data['CParty_Id'] == '140566', 'CParty_Id']
12340    140566
Name: CParty_Id, dtype: object

Does anybody know what is issue with this particular row?


问:
How to establish connection between Nifi and SQL server using JDBC driver?
I am running Nifi on windows machine and would like to establish a connection to the MS SQL Server on the same machine.
I downloaded the JDBC driver from Microsoft and put mssql-jdbc-11.2.1.jre11.jar to the lib folder of Nifi. Below is the properties for Controller Service Detail in Nifi to connect to the Sql server.

Database Connection URL: jdbc:sqlserver://127.0.0.1;databaseName=test_database;encrypt=true;user=nifireader;password=***;
Database Driver Class Name: com.microsoft.sqlserver.jdbc.SQLServerDriver

I also created a user inside Sql Server and gave it a read access to use it for Nifi. But I get the SSL error and could not solve it so far. Is there any other steps that I need to take to establish a connection?

```<code>2022-12-09 17:47:05,052 ERROR [Timer-Driven Process Thread-6] o.a.nifi.processors.standard.ExecuteSQL ExecuteSQL[id=f76ca380-0184-1000-3a89-b878a90723ed] Unable to execute SQL select query SELECT * FROM tbl_tags due to org.apache.nifi.processor.exception.ProcessException: java.sql.SQLException: Cannot create PoolableConnectionFactory (The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target". ClientConnectionId:7fcd7f53-9532-44da-96ce-56eac78049f6). No FlowFile to route to failure
org.apache.nifi.processor.exception.ProcessException: java.sql.SQLException: Cannot create PoolableConnectionFactory (The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target". ClientConnectionId:7fcd7f53-9532-44da-96ce-56eac78049f6)
    at org.apache.nifi.dbcp.AbstractDBCPConnectionPool.getConnection(AbstractDBCPConnectionPool.java:573)
    at org.apache.nifi.dbcp.AbstractDBCPConnectionPool.getConnection(AbstractDBCPConnectionPool.java:550)
    at org.apache.nifi.dbcp.DBCPService.getConnection(DBCPService.java:55)
    at jdk.internal.reflect.GeneratedMethodAccessor111.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.apache.nifi.controller.service.StandardControllerServiceInvocationHandler.invoke(StandardControllerServiceInvocationHandler.java:254)
    at org.apache.nifi.controller.service.StandardControllerServiceInvocationHandler.invoke(StandardControllerServiceInvocationHandler.java:105)
    at com.sun.proxy.$Proxy85.getConnection(Unknown Source)
    at org.apache.nifi.processors.standard.AbstractExecuteSQL.onTrigger(AbstractExecuteSQL.java:255)
    at org.apache.nifi.processor.AbstractProcessor.onTrigger(AbstractProcessor.java:27)
    at org.apache.nifi.controller.StandardProcessorNode.onTrigger(StandardProcessorNode.java:1356)
    at org.apache.nifi.controller.tasks.ConnectableTask.invoke(ConnectableTask.java:246)
    at org.apache.nifi.controller.scheduling.TimerDrivenSchedulingAgent$1.run(TimerDrivenSchedulingAgent.java:102)
    at org.apache.nifi.engine.FlowEngine$2.run(FlowEngine.java:110)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305)
    at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.sql.SQLException: Cannot create PoolableConnectionFactory (The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target". ClientConnectionId:7fcd7f53-9532-44da-96ce-56eac78049f6)
    at org.apache.commons.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:653)
    at org.apache.commons.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:531)
    at org.apache.commons.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:731)
    at org.apache.nifi.dbcp.AbstractDBCPConnectionPool.getConnection(AbstractDBCPConnectionPool.java:560)
    ... 20 common frames omitted
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target". ClientConnectionId:7fcd7f53-9532-44da-96ce-56eac78049f6
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:3806)
    at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1906)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:3329)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2950)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:2790)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1663)
    at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1064)
    at org.apache.commons.dbcp2.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:52)
    at org.apache.commons.dbcp2.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:374)
    at org.apache.commons.dbcp2.BasicDataSource.validateConnectionFactory(BasicDataSource.java:106)
    at org.apache.commons.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:649)
    ... 23 common frames omitted
Caused by: javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:131)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:369)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:312)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:307)
    at java.base/sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:654)
    at java.base/sun.security.ssl.CertificateMessage$T12CertificateConsumer.onCertificate(CertificateMessage.java:473)
    at java.base/sun.security.ssl.CertificateMessage$T12CertificateConsumer.consume(CertificateMessage.java:369)
    at java.base/sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:392)
    at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:478)
    at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:456)
    at java.base/sun.security.ssl.TransportContext.dispatch(TransportContext.java:199)
    at java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:172)
    at java.base/sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1382)
    at java.base/sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1295)
    at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:416)
    at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:388)
    at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1795)
    ... 32 common frames omitted
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:439)
    at java.base/sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:306)
    at java.base/sun.security.validator.Validator.validate(Validator.java:264)
    at java.base/sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:313)
    at java.base/sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:233)
    at java.base/sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:110)
    at com.microsoft.sqlserver.jdbc.HostNameOverrideX509TrustManager.checkServerTrusted(SQLServerTrustManager.java:86)
    at java.base/sun.security.ssl.AbstractTrustManagerWrapper.checkServerTrusted(SSLContextImpl.java:1510)
    at java.base/sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:638)
    ... 44 common frames omitted
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at java.base/sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
    at java.base/sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
    at java.base/java.security.cert.CertPathBuilder.build(CertPathBuilder.java:297)
    at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:434)
    ... 52 common frames omitted
</code>```

Body:
I am running Nifi on windows machine and would like to establish a connection to the MS SQL Server on the same machine.
I downloaded the JDBC driver from Microsoft and put mssql-jdbc-11.2.1.jre11.jar to the lib folder of Nifi. Below is the properties for Controller Service Detail in Nifi to connect to the Sql server.

Database Connection URL: jdbc:sqlserver://127.0.0.1;databaseName=test_database;encrypt=true;user=nifireader;password=***;
Database Driver Class Name: com.microsoft.sqlserver.jdbc.SQLServerDriver

I also created a user inside Sql Server and gave it a read access to use it for Nifi. But I get the SSL error and could not solve it so far. Is there any other steps that I need to take to establish a connection?

2022-12-09 17:47:05,052 ERROR [Timer-Driven Process Thread-6] o.a.nifi.processors.standard.ExecuteSQL ExecuteSQL[id=f76ca380-0184-1000-3a89-b878a90723ed] Unable to execute SQL select query SELECT * FROM tbl_tags due to org.apache.nifi.processor.exception.ProcessException: java.sql.SQLException: Cannot create PoolableConnectionFactory (The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target". ClientConnectionId:7fcd7f53-9532-44da-96ce-56eac78049f6). No FlowFile to route to failure
org.apache.nifi.processor.exception.ProcessException: java.sql.SQLException: Cannot create PoolableConnectionFactory (The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target". ClientConnectionId:7fcd7f53-9532-44da-96ce-56eac78049f6)
    at org.apache.nifi.dbcp.AbstractDBCPConnectionPool.getConnection(AbstractDBCPConnectionPool.java:573)
    at org.apache.nifi.dbcp.AbstractDBCPConnectionPool.getConnection(AbstractDBCPConnectionPool.java:550)
    at org.apache.nifi.dbcp.DBCPService.getConnection(DBCPService.java:55)
    at jdk.internal.reflect.GeneratedMethodAccessor111.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.apache.nifi.controller.service.StandardControllerServiceInvocationHandler.invoke(StandardControllerServiceInvocationHandler.java:254)
    at org.apache.nifi.controller.service.StandardControllerServiceInvocationHandler.invoke(StandardControllerServiceInvocationHandler.java:105)
    at com.sun.proxy.$Proxy85.getConnection(Unknown Source)
    at org.apache.nifi.processors.standard.AbstractExecuteSQL.onTrigger(AbstractExecuteSQL.java:255)
    at org.apache.nifi.processor.AbstractProcessor.onTrigger(AbstractProcessor.java:27)
    at org.apache.nifi.controller.StandardProcessorNode.onTrigger(StandardProcessorNode.java:1356)
    at org.apache.nifi.controller.tasks.ConnectableTask.invoke(ConnectableTask.java:246)
    at org.apache.nifi.controller.scheduling.TimerDrivenSchedulingAgent$1.run(TimerDrivenSchedulingAgent.java:102)
    at org.apache.nifi.engine.FlowEngine$2.run(FlowEngine.java:110)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305)
    at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.sql.SQLException: Cannot create PoolableConnectionFactory (The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target". ClientConnectionId:7fcd7f53-9532-44da-96ce-56eac78049f6)
    at org.apache.commons.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:653)
    at org.apache.commons.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:531)
    at org.apache.commons.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:731)
    at org.apache.nifi.dbcp.AbstractDBCPConnectionPool.getConnection(AbstractDBCPConnectionPool.java:560)
    ... 20 common frames omitted
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target". ClientConnectionId:7fcd7f53-9532-44da-96ce-56eac78049f6
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:3806)
    at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1906)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:3329)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2950)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:2790)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1663)
    at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1064)
    at org.apache.commons.dbcp2.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:52)
    at org.apache.commons.dbcp2.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:374)
    at org.apache.commons.dbcp2.BasicDataSource.validateConnectionFactory(BasicDataSource.java:106)
    at org.apache.commons.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:649)
    ... 23 common frames omitted
Caused by: javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:131)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:369)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:312)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:307)
    at java.base/sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:654)
    at java.base/sun.security.ssl.CertificateMessage$T12CertificateConsumer.onCertificate(CertificateMessage.java:473)
    at java.base/sun.security.ssl.CertificateMessage$T12CertificateConsumer.consume(CertificateMessage.java:369)
    at java.base/sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:392)
    at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:478)
    at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:456)
    at java.base/sun.security.ssl.TransportContext.dispatch(TransportContext.java:199)
    at java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:172)
    at java.base/sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1382)
    at java.base/sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1295)
    at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:416)
    at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:388)
    at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1795)
    ... 32 common frames omitted
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:439)
    at java.base/sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:306)
    at java.base/sun.security.validator.Validator.validate(Validator.java:264)
    at java.base/sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:313)
    at java.base/sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:233)
    at java.base/sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:110)
    at com.microsoft.sqlserver.jdbc.HostNameOverrideX509TrustManager.checkServerTrusted(SQLServerTrustManager.java:86)
    at java.base/sun.security.ssl.AbstractTrustManagerWrapper.checkServerTrusted(SSLContextImpl.java:1510)
    at java.base/sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:638)
    ... 44 common frames omitted
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at java.base/sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
    at java.base/sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
    at java.base/java.security.cert.CertPathBuilder.build(CertPathBuilder.java:297)
    at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:434)
    ... 52 common frames omitted


问:
Ansible - lineinfile
I would like to use the lineinfile module to automatically fill an inventory file (inventory/hosts) from another inventory file that I use to deploy VMs on vsphere.

When the file is empty, there is no problem but, when it is already filled, the module does not insert the lines when it sees that they exist elsewhere in the file. But I need it to build my inventory file.

How I can do this?

Here is my piece of code:

```<code>- name: Add parameters for connection of VMs Windows
  ansible.builtin.lineinfile:
    path: /home/ansible/inventory/hosts
    line: "{{ item }}"
  with_items:
    - '[{{ group_names[0] }}:vars]'
    - ansible_user=administrator
    - ansible_password='{{ lookup('file', '/home/ansible/directory/file_'+group_names[0] ) }}'
    - ansible_connection=winrm
    - ansible_port=5986
    - ansible_winrm_server_cert_validation=ignore
  delegate_to: localhost
</code>```

It only inserts the ansible_password line for me, since the others exist for other groups of VMs. I also tried with blockinfile

Title: Ansible - lineinfile

Body:
I would like to use the lineinfile module to automatically fill an inventory file (inventory/hosts) from another inventory file that I use to deploy VMs on vsphere.

When the file is empty, there is no problem but, when it is already filled, the module does not insert the lines when it sees that they exist elsewhere in the file. But I need it to build my inventory file.

How I can do this?

Here is my piece of code:

- name: Add parameters for connection of VMs Windows
  ansible.builtin.lineinfile:
    path: /home/ansible/inventory/hosts
    line: "{{ item }}"
  with_items:
    - '[{{ group_names[0] }}:vars]'
    - ansible_user=administrator
    - ansible_password='{{ lookup('file', '/home/ansible/directory/file_'+group_names[0] ) }}'
    - ansible_connection=winrm
    - ansible_port=5986
    - ansible_winrm_server_cert_validation=ignore
  delegate_to: localhost

It only inserts the ansible_password line for me, since the others exist for other groups of VMs. I also tried with blockinfile


问:
How do I scale a Mobject using a Manim updater?

I can scale a Square mobject as follows with self.play()/Scene.play():

square = Square(fill_color=RED, fill_opacity=1)

self.play(square.animate.scale(3))
self.wait(3)
```
<p><img src="https://i.stack.imgur.com/oR1oB.gif" alt="enter image description here" /></p>
</li>
<li><p>But I cannot achieve the <code>scale</code> behaviour as above using this simple  <code>add_updater</code> method. All I get is a blank screen:</p>
<pre class="lang-py prettyprint-override"><code>square = Square(fill_color=RED, fill_opacity=1)

def scale_up(mob, dt):
    mob.scale(2*dt)

square.add_updater(scale_up)
self.add(square)
self.wait(3)
</code>```

Questions

How can I achieve the behaviour of No 1 above with add_updater, or other updater techniques?

I know that I can successfully animate an item with updater methods - such as doing mobject.shift() - even without using self.play()/Scene.play(). Can the behaviour of No. 1 above be achieved without using the Scene.play() method?

It appears that you can .scale() an object with scene updaters, instead of Mobject updaters. Why?

Body:
I can scale a Square mobject as follows with self.play()/Scene.play():

square = Square(fill_color=RED, fill_opacity=1)

self.play(square.animate.scale(3))
self.wait(3)

But I cannot achieve the scale behaviour as above using this simple  add_updater method. All I get is a blank screen:

square = Square(fill_color=RED, fill_opacity=1)

def scale_up(mob, dt):
    mob.scale(2*dt)

square.add_updater(scale_up)
self.add(square)
self.wait(3)

Questions

How can I achieve the behaviour of No 1 above with add_updater, or other updater techniques?

I know that I can successfully animate an item with updater methods - such as doing mobject.shift() - even without using self.play()/Scene.play(). Can the behaviour of No. 1 above be achieved without using the Scene.play() method?

It appears that you can .scale() an object with scene updaters, instead of Mobject updaters. Why?


问:
Not able to enter date in <input type=date field, using sendkeys, javascriptexecutor, actions class and even tried removing readonly property if any
this is my code

```<code>DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
String date = dateFormat.format(tomorrow());

</code>```

((JavascriptExecutor)driver).executeScript("arguments[0].value=arguments[1]",               driver.findElement(By.id("appointmentDate")), date);

```<code>or....
 driver().findElement(By.id("appointmentDate")).sendKeys(date.toString());

</code>```

enter image description here

I am able to click on the corner of input field manually and calender opens but when i try to do it in automation can't do it. And not able to inspect the table also, i tried to insert date with right format using sendkeys, javascriptexecutor and also tried to remove readonly property if any, i dont see that attribute as well but still no use. Please help me resolve this.

Body:
this is my code

DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
String date = dateFormat.format(tomorrow());

((JavascriptExecutor)driver).executeScript("arguments[0].value=arguments[1]",               driver.findElement(By.id("appointmentDate")), date);

or....
 driver().findElement(By.id("appointmentDate")).sendKeys(date.toString());

enter image description here

I am able to click on the corner of input field manually and calender opens but when i try to do it in automation can't do it. And not able to inspect the table also, i tried to insert date with right format using sendkeys, javascriptexecutor and also tried to remove readonly property if any, i dont see that attribute as well but still no use. Please help me resolve this.


问:
How to use oauth2 to get authenticated to use external API
I have been struggling for the past hours to get authenticated in order to consume an API.

This external service requires OAuth2 authentication using authorization code grant.
I currently have the client_id, the client_secret, a redirect_uri and the request authorization and retrieve tokers url's from the 3rd party side. What I am not able to do is to get the access tokens that I need to consume the API.

I tried using multiple libraries (passportjs, simple-oauth2, client-oauth2) and haven't been sucessful.

So my question is how can I do this?


问:
Howto read specific lines out of a text file to check for a login to ssh on a server?
:D

Let's say i have text file with the following content:

```<code>Server: 111.111.111.111:22
Username: user
Password: pass
</code>```

i literally spent a night searching for a script or a tool (mainly on github but looked on google as well...) which reads such a textfile and checks the logins and the corresponding password automatically. by now, i am doing it by hand and i want to let the computer do the work... ;-)

Is here any person who has an idea for a script or knows a tool which can exactly do this? It would be nice if someone knows something! =)

I wish you a great weekend, all! <3

Searched for a program for myself but couldn´t find one, just ssh bruteforcers which take every password and not one password for one username... :-/

Body:
:D

Let's say i have text file with the following content:

Server: 111.111.111.111:22
Username: user
Password: pass

i literally spent a night searching for a script or a tool (mainly on github but looked on google as well...) which reads such a textfile and checks the logins and the corresponding password automatically. by now, i am doing it by hand and i want to let the computer do the work... ;-)

Is here any person who has an idea for a script or knows a tool which can exactly do this? It would be nice if someone knows something! =)

I wish you a great weekend, all! <3

Searched for a program for myself but couldn´t find one, just ssh bruteforcers which take every password and not one password for one username... :-/


问:
Matplotlib not displaying colors correctly in customized colorbar
I am trying to obtain a colorbar like the one shown in figure A)
A)

But what I get is what is shown in figure B)
B)

Saying it better, I can obtain figure A, but the colors in the plot actually come from the colorbar shown in B, even if the colorbar A is displayed.

This is my code:

```<code>cmap = (mpl.colors.ListedColormap(['#d2fffe', '#88fefd', '#00c6ff', '#1996ff', '#3c41ff', '#3cbc3d', '#a5d71f', '#ffe600', '#ffc300', '#ff7d00', '#ff0000', '#c80000', '#d464c3', '#b5199d', '#840094', '#dcdcdc', '#b4b4b4', '#8c8c8c', '#5a5a5a']).with_extremes(over='black', under='white'))

bounds = [0.2,1,3,5,7,10,15,20,25,30,40,50,60,70,80,100,125,150,175,200]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

fig = plt.figure(figsize=(16, 12), dpi=120)
ax = fig.add_subplot(projection=cart_proj)
ax.contourf(lons, lats, my_var, levels=19, cmap=cmap, zorder=3, transform=crs.PlateCarree(), alpha=0.85)

cbar = fig.colorbar(mpl.cm.ScalarMappable(cmap=cmap, norm=norm),
    extend='both',
    extendfrac='auto',
    ticks=bounds,
    spacing='uniform')
</code>```

Body:
I am trying to obtain a colorbar like the one shown in figure A)
A)

But what I get is what is shown in figure B)
B)

Saying it better, I can obtain figure A, but the colors in the plot actually come from the colorbar shown in B, even if the colorbar A is displayed.

This is my code:

cmap = (mpl.colors.ListedColormap(['#d2fffe', '#88fefd', '#00c6ff', '#1996ff', '#3c41ff', '#3cbc3d', '#a5d71f', '#ffe600', '#ffc300', '#ff7d00', '#ff0000', '#c80000', '#d464c3', '#b5199d', '#840094', '#dcdcdc', '#b4b4b4', '#8c8c8c', '#5a5a5a']).with_extremes(over='black', under='white'))

bounds = [0.2,1,3,5,7,10,15,20,25,30,40,50,60,70,80,100,125,150,175,200]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

fig = plt.figure(figsize=(16, 12), dpi=120)
ax = fig.add_subplot(projection=cart_proj)
ax.contourf(lons, lats, my_var, levels=19, cmap=cmap, zorder=3, transform=crs.PlateCarree(), alpha=0.85)

cbar = fig.colorbar(mpl.cm.ScalarMappable(cmap=cmap, norm=norm),
    extend='both',
    extendfrac='auto',
    ticks=bounds,
    spacing='uniform')


问:
Creating a Roof by using PolygonMeshBuilder
I recently started to learn babylonjs. I’m trying to create a roof by using given roof data.
Would you mind sharing your knowledge for me to solve this problem?

Let me explain the project briefly here.

The data I’m given has roof azimuth and tilt and its points represent an individual roof’s coordinate.
What I tried here is that:

draw roof’s outlines for reference by using LinesMesh

get direction to get the axis to rotate(tilt) roof plane

draw a roof plane by using PolygonMeshBuilder (converted the points to start from (0, 0, 0))

rotate(tilt) the the roof plane by using direction(axis)

move back to original desired place

So the issue I’m facing is that PolygonMeshBuilder might not be the proper way I want to create a roof dynamically since:

given roof’s coordinates are all in 3d already. so if I just use its (x, y(0), z) and rotate it, it creates a gap between roof planes obviously.

given roof’s coordinates are often uneven. Flat polygons are always created so I can see sunk roof planes here and there.

The ways I could think of were that:

fill the closed line mesh with texture => the doc showed it was filled with polygon as well
create a custom mesh => the points should be triangular for that
refer the ‘adding a roof’ doc => the given data is in totally different shape for this
there are two roofs at the same time to show you more examples.
PG Link: https://playground.babylonjs.com/#QRAJQP#27

Thanks in advance! :wink:


问:
How to improve my double select query that takes too long to execute
My table has 2 date fields: start and end. I have millions of records with random durations.
For every date covered by my table I want to know the count of records.

I hope there is a different and cleaner way to approach my problem because I've come up with a solution that will take forever to compute, which is:

First create an intermediary table with the dates

```<code>DROP TABLE IF EXISTS time_points;
SELECT DISTINCT start_date AS time_point
INTO time_points
FROM data
UNION
SELECT DISTINCT end_date FROM data
; -- Totals 8.2 million records
</code>```

Then create a request using both tables

```<code>DROP TABLE IF EXISTS results;
SELECT time_points.time_point,
(SELECT COUNT(*)
 FROM data
 WHERE start_date <= time_points.time_point AND end_date >= time_points.time_point
) AS n
INTO results
FROM time_points
;
</code>```

Now I am waiting. When I run the second query with TOP(10), it takes 30 seconds. So it would take about 6 months to get my results. I would hope I could get them in half a day maybe.

-> Sample data

-> here is a sample of data

```<code>CREATE TABLE [dbo].[data_table](
    [start_date] [datetime] NULL,
    [end_date] [datetime] NULL
) ON [PRIMARY]
GO
INSERT [dbo].[data_table] ([start_date], [end_date]) VALUES (CAST(N'2021-12-08T11:07:24.000' AS DateTime), CAST(N'2021-12-08T11:28:41.000' AS DateTime))
GO
INSERT [dbo].[data_table] ([start_date], [end_date]) VALUES (CAST(N'2021-12-08T11:09:55.000' AS DateTime), CAST(N'2021-12-08T12:18:21.000' AS DateTime))
GO
INSERT [dbo].[data_table] ([start_date], [end_date]) VALUES (CAST(N'2021-12-14T12:30:01.000' AS DateTime), CAST(N'2021-12-14T12:38:40.000' AS DateTime))
GO
INSERT [dbo].[data_table] ([start_date], [end_date]) VALUES (CAST(N'2021-12-19T11:17:46.000' AS DateTime), CAST(N'2021-12-19T12:20:48.000' AS DateTime))
GO
INSERT [dbo].[data_table] ([start_date], [end_date]) VALUES (CAST(N'2021-12-31T16:34:07.000' AS DateTime), CAST(N'2021-12-31T16:39:14.000' AS DateTime))
GO
INSERT [dbo].[data_table] ([start_date], [end_date]) VALUES (CAST(N'2021-12-09T07:17:56.000' AS DateTime), CAST(N'2021-12-09T07:35:31.000' AS DateTime))
GO
INSERT [dbo].[data_table] ([start_date], [end_date]) VALUES (CAST(N'2021-12-14T07:52:21.000' AS DateTime), CAST(N'2021-12-14T07:59:02.000' AS DateTime))
GO
INSERT [dbo].[data_table] ([start_date], [end_date]) VALUES (CAST(N'2021-12-08T07:27:11.000' AS DateTime), CAST(N'2021-12-08T07:30:01.000' AS DateTime))
GO
INSERT [dbo].[data_table] ([start_date], [end_date]) VALUES (CAST(N'2021-12-01T08:01:58.000' AS DateTime), CAST(N'2021-12-01T08:06:14.000' AS DateTime))
GO
INSERT [dbo].[data_table] ([start_date], [end_date]) VALUES (CAST(N'2021-12-16T07:19:46.000' AS DateTime), CAST(N'2021-12-16T07:22:46.000' AS DateTime))
GO
</code>```

-> Sample result

```<code>DROP TABLE IF EXISTS time_points;
SELECT DISTINCT start_date AS time_point
INTO time_points
FROM data_table
UNION
SELECT DISTINCT end_date FROM data_table
;
DROP TABLE IF EXISTS results;
SELECT time_points.time_point,
(SELECT COUNT(*)
 FROM data_table
 WHERE start_date <= time_points.time_point AND end_date >= time_points.time_point
) AS n
INTO results
FROM time_points
;
SELECT * FROM results
;
</code>```

(only 2 lines of result:)

time_point n

2021-12-08 11:07:24.000   1

2021-12-08 11:09:55.000   2

Body:
My table has 2 date fields: start and end. I have millions of records with random durations.
For every date covered by my table I want to know the count of records.

I hope there is a different and cleaner way to approach my problem because I've come up with a solution that will take forever to compute, which is:

First create an intermediary table with the dates

DROP TABLE IF EXISTS time_points;
SELECT DISTINCT start_date AS time_point
INTO time_points
FROM data
UNION
SELECT DISTINCT end_date FROM data
; -- Totals 8.2 million records

Then create a request using both tables

DROP TABLE IF EXISTS results;
SELECT time_points.time_point,
(SELECT COUNT(*)
 FROM data
 WHERE start_date <= time_points.time_point AND end_date >= time_points.time_point
) AS n
INTO results
FROM time_points
;

Now I am waiting. When I run the second query with TOP(10), it takes 30 seconds. So it would take about 6 months to get my results. I would hope I could get them in half a day maybe.

-> Sample data

-> here is a sample of data

CREATE TABLE [dbo].[data_table](
    [start_date] [datetime] NULL,
    [end_date] [datetime] NULL
) ON [PRIMARY]
GO
INSERT [dbo].[data_table] ([start_date], [end_date]) VALUES (CAST(N'2021-12-08T11:07:24.000' AS DateTime), CAST(N'2021-12-08T11:28:41.000' AS DateTime))
GO
INSERT [dbo].[data_table] ([start_date], [end_date]) VALUES (CAST(N'2021-12-08T11:09:55.000' AS DateTime), CAST(N'2021-12-08T12:18:21.000' AS DateTime))
GO
INSERT [dbo].[data_table] ([start_date], [end_date]) VALUES (CAST(N'2021-12-14T12:30:01.000' AS DateTime), CAST(N'2021-12-14T12:38:40.000' AS DateTime))
GO
INSERT [dbo].[data_table] ([start_date], [end_date]) VALUES (CAST(N'2021-12-19T11:17:46.000' AS DateTime), CAST(N'2021-12-19T12:20:48.000' AS DateTime))
GO
INSERT [dbo].[data_table] ([start_date], [end_date]) VALUES (CAST(N'2021-12-31T16:34:07.000' AS DateTime), CAST(N'2021-12-31T16:39:14.000' AS DateTime))
GO
INSERT [dbo].[data_table] ([start_date], [end_date]) VALUES (CAST(N'2021-12-09T07:17:56.000' AS DateTime), CAST(N'2021-12-09T07:35:31.000' AS DateTime))
GO
INSERT [dbo].[data_table] ([start_date], [end_date]) VALUES (CAST(N'2021-12-14T07:52:21.000' AS DateTime), CAST(N'2021-12-14T07:59:02.000' AS DateTime))
GO
INSERT [dbo].[data_table] ([start_date], [end_date]) VALUES (CAST(N'2021-12-08T07:27:11.000' AS DateTime), CAST(N'2021-12-08T07:30:01.000' AS DateTime))
GO
INSERT [dbo].[data_table] ([start_date], [end_date]) VALUES (CAST(N'2021-12-01T08:01:58.000' AS DateTime), CAST(N'2021-12-01T08:06:14.000' AS DateTime))
GO
INSERT [dbo].[data_table] ([start_date], [end_date]) VALUES (CAST(N'2021-12-16T07:19:46.000' AS DateTime), CAST(N'2021-12-16T07:22:46.000' AS DateTime))
GO

-> Sample result

DROP TABLE IF EXISTS time_points;
SELECT DISTINCT start_date AS time_point
INTO time_points
FROM data_table
UNION
SELECT DISTINCT end_date FROM data_table
;
DROP TABLE IF EXISTS results;
SELECT time_points.time_point,
(SELECT COUNT(*)
 FROM data_table
 WHERE start_date <= time_points.time_point AND end_date >= time_points.time_point
) AS n
INTO results
FROM time_points
;
SELECT * FROM results
;

(only 2 lines of result:)

time_point n

2021-12-08 11:07:24.000   1

2021-12-08 11:09:55.000   2


问:
How to mock the response of a repository used by a DataLoader in a GraphQLResolver?
I am using graphql-java-kickstart to implement a GraphQL api in a springboot application. One of my resolvers needs to fetch additional data before returning the final type. I am using a DataLoader to fetch this data. In order to avoid multiple additional queries to the database, I am using the method dataLoader.loadMany(ids) to fetch all records with one query.

I want to test the resolver behavior mocking the repository response. In my test I have injected a MockBean for the repository and I am mocking its response with:

when(repository.findAllById(List.of(ids))).thenReturn(List.of(mockRecord);

The data loader registry has the mock repository registered for the right type but I cannot make it return the response that I defined. The truth is that I cannot find which repository method the data loader is using to fetch the data but the repository being a JpaRepository the only method to fetch multiple objects from a list of ids is the findAllById. I have tried to follow the flow with breakpoints but I didn't manage to find where exactly the repository is being used and which method is being called.

I am certainly missing something on how the data loader works and how I can mock the responses it gives. Does anyone has any clue what that might me?

Many thanks

UPDATE: Running the actual application and putting breakpoints in the class SimpleJpaRepository I can actually confirm that the repository method used to resolve the model is the findAllById what confuses me even more. If, when running the test, I have the right object (the mock) within the dataloader registry and a defined a return object for that mock's called method, why does it not work as expected?


问:
Angular equivalent of React's <children>
I have a giant legacy app that I'm trying to move to Angular. The app has a bunch of nested Django templates with the top-level HTML looking something like:

  {% block content %}{% endblock %}

```
<p>I'd like to be able to do something like:</p>
<pre class="lang-html prettyprint-override"><code><app-root> <!-- Angular app -->
  <div id="content">
    <!-- Django template syntax, loaded on server -->
    {% block content %}{% endblock %}
  </div>
</app-root>
<script src="app_bundle.js"></script>
</code>```

However, I can't put {% block content %}{% endblock %} in my Angular template because it's rendered on the server. So in the app-root template, I'd like to say something like React's <children /> to indicate "I don't care what the children are, just put them there."

Is there a way to do this with Angular? I've seen posts talking about innerHtml, but:

I don't want any tags sanitized and

I want to be able to have Angular components deep in the nested Django templates, so it would be nice if they could pick up CSS correctly (which sounds like a limitation of innerHtml).

Body:
I have a giant legacy app that I'm trying to move to Angular. The app has a bunch of nested Django templates with the top-level HTML looking something like:

  {% block content %}{% endblock %}

I'd like to be able to do something like:

<app-root>

    {% block content %}{% endblock %}

</app-root>

However, I can't put {% block content %}{% endblock %} in my Angular template because it's rendered on the server. So in the app-root template, I'd like to say something like React's <children /> to indicate "I don't care what the children are, just put them there."

Is there a way to do this with Angular? I've seen posts talking about innerHtml, but:

I don't want any tags sanitized and

I want to be able to have Angular components deep in the nested Django templates, so it would be nice if they could pick up CSS correctly (which sounds like a limitation of innerHtml).


问:
Why does child proccess has to go first in piping ls and more commands in C?
```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int argc, char *argv[])
{
    int fd[2];
    pid_t pid;

    if (pipe(fd) == -1) {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    pid = fork();
    if (pid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }

    if (pid == 0) {
        dup2(fd[1], STDOUT_FILENO);
        close(fd[0]);
        close(fd[1]);
        execlp("ls", "ls", NULL);
        perror("execlp");
        exit(EXIT_FAILURE);
    } else {
        dup2(fd[0], STDIN_FILENO);
        close(fd[0]);
        close(fd[1]);
        execlp("more", "more", "-3", NULL);
        perror("execlp");
        exit(EXIT_FAILURE);
    }
}
</code>```

I dont understand, why does my program when we say if (pid == 0) works like intended where more program display 3 lines and that again 3 lines after the space and so on, and when i say if (pid!=0) ls display everything and more command doesnt work? Why is this?

Why does it matter if parent process does ls and child more command or parent does more and child ls? Either way more wont print anything until ls writes data into the pipe.

Here is the code i tried versus the one above, i tried having parent process calling "ls" command and child process call "more" command. I don't see why this would be an issue? I just changed "responsobilities", i don't see how this changes anything? child process with "more" command comes first, it will attempt to read pipe and it will block since it's empty, parent process with "ls" command will eventually write into the pipe and the child process with "more" will get unblocked, read from the pipe and print it out on the user screen. So i don't understand why is it only displaying the contents of the directory, instead of showing me three piece's of content and then after i click space another three, and so on..

```<code>    if (pid != 0) {
       dup2(fd[1], STDOUT_FILENO);
       close(fd[0]);
       close(fd[1]);
       execlp("ls", "ls", NULL);
       perror("execlp");
       exit(EXIT_FAILURE);
    }
    else {
       dup2(fd[0], STDIN_FILENO);
       close(fd[0]);
       close(fd[1]);
       execlp("more", "more", "-3", NULL);
       perror("execlp");
       exit(EXIT_FAILURE);
    }
</code>```

Body:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int argc, char *argv[])
{
    int fd[2];
    pid_t pid;

    if (pipe(fd) == -1) {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    pid = fork();
    if (pid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }

    if (pid == 0) {
        dup2(fd[1], STDOUT_FILENO);
        close(fd[0]);
        close(fd[1]);
        execlp("ls", "ls", NULL);
        perror("execlp");
        exit(EXIT_FAILURE);
    } else {
        dup2(fd[0], STDIN_FILENO);
        close(fd[0]);
        close(fd[1]);
        execlp("more", "more", "-3", NULL);
        perror("execlp");
        exit(EXIT_FAILURE);
    }
}

I dont understand, why does my program when we say if (pid == 0) works like intended where more program display 3 lines and that again 3 lines after the space and so on, and when i say if (pid!=0) ls display everything and more command doesnt work? Why is this?

Why does it matter if parent process does ls and child more command or parent does more and child ls? Either way more wont print anything until ls writes data into the pipe.

Here is the code i tried versus the one above, i tried having parent process calling "ls" command and child process call "more" command. I don't see why this would be an issue? I just changed "responsobilities", i don't see how this changes anything? child process with "more" command comes first, it will attempt to read pipe and it will block since it's empty, parent process with "ls" command will eventually write into the pipe and the child process with "more" will get unblocked, read from the pipe and print it out on the user screen. So i don't understand why is it only displaying the contents of the directory, instead of showing me three piece's of content and then after i click space another three, and so on..

    if (pid != 0) {
       dup2(fd[1], STDOUT_FILENO);
       close(fd[0]);
       close(fd[1]);
       execlp("ls", "ls", NULL);
       perror("execlp");
       exit(EXIT_FAILURE);
    }
    else {
       dup2(fd[0], STDIN_FILENO);
       close(fd[0]);
       close(fd[1]);
       execlp("more", "more", "-3", NULL);
       perror("execlp");
       exit(EXIT_FAILURE);
    }


问:
How to migrate from CXF service to Jersey service
I have to migrate an application deployed with CXF in Jersey, but i don't know how to do it.

Right now, i've just updated my pom into this:

//other code...
<dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>${jersey2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-client</artifactId>
            <version>${jersey2.version}</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>${jersey2.version}</version>
</dependency>
```

I have to do any kind of code changes or these would be enough?

Body:
I have to migrate an application deployed with CXF in Jersey, but i don't know how to do it.

Right now, i've just updated my pom into this:

//other code...
<dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>${jersey2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-client</artifactId>
            <version>${jersey2.version}</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>${jersey2.version}</version>
</dependency>

I have to do any kind of code changes or these would be enough?


问:
Excel VBA code for Pivot tables to clear filters then filter for selected range
I have multiple pivots in a workbook but one of the worksheets is called "YTD Payment Trend" and the Pivot table name is "Pivottable2". I am trying to Clear the filter named "TotalAccountBalance" and then filter for a range between -5.00 thru +5.00 only.
enter image description here

Below is what I have so far and I am attaching the image of the specific filter items but I need to be able to select a range since it can change:

```<code>Sub TESTMACRO()

    Dim PT As PivotTable
    Dim TAB1 As PivotField

    Set PT = ThisWorkbook.Worksheets("YTD Payment Trend").PivotTables("PivotTable2")
    Set TAB1 = PT.PivotFields("TotalAccountBalance")

    '//Reset Pivot Field Filter
    TAB1.ClearAllFilters

    '//Enable Multiple Items Selection
    TAB1.EnableMultiplePageItems = True

    Set TAB1 = Nothing
    Set PT = Nothing

End Sub
</code>```

Body:
I have multiple pivots in a workbook but one of the worksheets is called "YTD Payment Trend" and the Pivot table name is "Pivottable2". I am trying to Clear the filter named "TotalAccountBalance" and then filter for a range between -5.00 thru +5.00 only.
enter image description here

Below is what I have so far and I am attaching the image of the specific filter items but I need to be able to select a range since it can change:

Sub TESTMACRO()

    Dim PT As PivotTable
    Dim TAB1 As PivotField

    Set PT = ThisWorkbook.Worksheets("YTD Payment Trend").PivotTables("PivotTable2")
    Set TAB1 = PT.PivotFields("TotalAccountBalance")

    '//Reset Pivot Field Filter
    TAB1.ClearAllFilters

    '//Enable Multiple Items Selection
    TAB1.EnableMultiplePageItems = True

    Set TAB1 = Nothing
    Set PT = Nothing

End Sub


问:
WordPress is adding suffix to uploaded media that doesn't exist on the site
I have a file that, when uploaded into the media library, automatically gets a "-2" suffix added to it.

I checked the entire database by running a search through all tables in phpMyAdmin, there are no references to this file in it.

I've tried clearing the cache with multiple plugins, including WP-Optimize, Autoptimize, Optimole, and hosting tools from Nexcess. I also tried optimizing the DB with WP-Optimize.

It used to be that it added the "-1" suffix, and now it's "-2".

I removed the big image size threshold like so, so it isn't an issue with scaling:

```<code>add_filter( 'big_image_size_threshold', '__return_false' );
</code>```

I also tried uploading using a private browser.

Any idea why this is happening?

Renaming the file is not an option, as it needs to be named correctly for an import. This is just one file as an example, it is happening to many others as well.

It may have something to do with the WP All Import plugin I'm using, but then again there are no records in the PMXI tables.

Body:
I have a file that, when uploaded into the media library, automatically gets a "-2" suffix added to it.

I checked the entire database by running a search through all tables in phpMyAdmin, there are no references to this file in it.

I've tried clearing the cache with multiple plugins, including WP-Optimize, Autoptimize, Optimole, and hosting tools from Nexcess. I also tried optimizing the DB with WP-Optimize.

It used to be that it added the "-1" suffix, and now it's "-2".

I removed the big image size threshold like so, so it isn't an issue with scaling:

add_filter( 'big_image_size_threshold', '__return_false' );

I also tried uploading using a private browser.

Any idea why this is happening?

Renaming the file is not an option, as it needs to be named correctly for an import. This is just one file as an example, it is happening to many others as well.

It may have something to do with the WP All Import plugin I'm using, but then again there are no records in the PMXI tables.


问:
Unable to run feature when tests runner and step definitions are added
I am unable to run this feature. Please see screenshot below:

```<code>
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(features = "src/main/resources/features", glue = {"stepDefinition"})
public class RunCukeTest {
}
</code>```

Body:
I am unable to run this feature. Please see screenshot below:

import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(features = "src/main/resources/features", glue = {"stepDefinition"})
public class RunCukeTest {
}


问:
Express Route Parameters not working in vercel
I am working on an express project which is a URL shortener. I am generating a unique id and attaching it to the website as route parameters. E.g. https://shorturlme.vercel.app/some_code. It works fine in localhost, but when I try to host it on vercel it shows a page not found error.
Below is what I have done.

```<code>app.get("/:uid",(req, res)=>{
    res.statusCode = 200;
    res.setHeader("Content-type","text/html");
    getURL(req.params.uid, res);

});

</code>```

Please help me.
Thank you in advance.

It works fine on other hosting providers like railway, but not on vercel.
I am using vercel because railway projects are valid for only for 20 days free.

Body:
I am working on an express project which is a URL shortener. I am generating a unique id and attaching it to the website as route parameters. E.g. https://shorturlme.vercel.app/some_code. It works fine in localhost, but when I try to host it on vercel it shows a page not found error.
Below is what I have done.

app.get("/:uid",(req, res)=>{
    res.statusCode = 200;
    res.setHeader("Content-type","text/html");
    getURL(req.params.uid, res);

});

Please help me.
Thank you in advance.

It works fine on other hosting providers like railway, but not on vercel.
I am using vercel because railway projects are valid for only for 20 days free.


问:
Add-MailboxFolderPermissions script failing because [System.Management.Automation.PSObject] does not contain a method named 'op_Addition'
I'm pretty new to Exchange Online and am writing a script which is supposed to give o365 calendar permission to members of an AD group which have been exported to a CSV. All members of this group need to be able to have Reviewer permission on each other's calendars.

After the initial connect to EOL via PS, the script I've created is as follows:

```<code>$Users = import-csv "C:\Scripts\UserList.csv"
Foreach ($User in $Users)
{Add-MailboxFolderPermission –identity ($user+':\calendar') –user "user@domain" –Accessrights Reviewer}
</code>```

However I'm getting an error:

Method invocation failed because
[System.Management.Automation.PSObject] does not contain a method
named 'op_Addition'. At line:2 char:2

From what I've read it seems I'm not presenting the array correctly, but I'm not really sure how I should present it in this script. Can anyone advise? Any help would be greatly appreciated.

Thanks in advance!

Body:
I'm pretty new to Exchange Online and am writing a script which is supposed to give o365 calendar permission to members of an AD group which have been exported to a CSV. All members of this group need to be able to have Reviewer permission on each other's calendars.

After the initial connect to EOL via PS, the script I've created is as follows:

$Users = import-csv "C:\Scripts\UserList.csv"
Foreach ($User in $Users)
{Add-MailboxFolderPermission –identity ($user+':\calendar') –user "user@domain" –Accessrights Reviewer}

However I'm getting an error:

Method invocation failed because
[System.Management.Automation.PSObject] does not contain a method
named 'op_Addition'. At line:2 char:2

From what I've read it seems I'm not presenting the array correctly, but I'm not really sure how I should present it in this script. Can anyone advise? Any help would be greatly appreciated.

Thanks in advance!


问:
parallelizing Mandelbrot using MPI
I am trying to parallelize the Mandelbrot.
the correct output should be around 1.510659. however I am not getting that correctly.

**  PROGRAM: Mandelbrot area
**
**  PURPOSE: Program to compute the area of a  Mandelbrot set.
**           The correct answer should be around 1.510659.
**
**  USAGE:   Program runs without input ... just run the executable
**
reduction for numoutside.

this is my parallelized code

```<code>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <mpi.h>

#define NPOINTS 1000
#define MAXITER 1000
int P = 1;
struct d_complex
{
  double r;
  double i;
};

int testpoint(struct d_complex);

struct d_complex c;
struct d_complex cPart;
int numoutside = 1;

int main()
{
  int i, j, row;
    int res;
  double area, error, eps = 1.0e-5;
  int myrank, mysize;
  double stsec, ensec, commtime, maxcommtime;
  MPI_Status status;
  MPI_Init(NULL, NULL);
  MPI_Comm_size(MPI_COMM_WORLD, &mysize);
  MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
  stsec = MPI_Wtime();
  //   Loop over grid of points in the complex plane which contains the Mandelbrot set,
  //   testing each point to see whether it is inside or outside the set.
  /*for (i = 0; i < NPOINTS; i ++)
  {
    for (j = 0; j < NPOINTS ; j++)
    {
      c.r = -2.0 + 2.5 * (double)(i) / (double)(NPOINTS) + eps;
      c.i = 1.125 * (double)(j) / (double)(NPOINTS) + eps;
      testpoint(c);
    }
  }*/

  if (myrank == 0)
  {

    /* Begin User Program  - the master */
    //*
    int outsum, nb_pixel = NPOINTS*NPOINTS ;
    for (i = 0; i < nb_pixel; i++)
    {
      MPI_Recv(&res, 1, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status);
      // printf("Slave id %d has send : %d \n", status.MPI_SOURCE, data[2]);
      // printf("%d: [%d,%d] -> [%d,%d] = %d\n", status.MPI_SOURCE, data[0], data[1], data[0] + MAXX, data[1] + MAXY, data[2]);
      res += numoutside;
    }
     area = 2.0 * 2.5 * 1.125 * (double)(NPOINTS * NPOINTS - res) / (double)(NPOINTS * NPOINTS);
   error = area / (double)NPOINTS;
    printf("Area of Mandlebrot set = %12.8f +/- %12.8f\n", area, error);
    printf("Finish.\n");
  }
  else
  {

    for (i = myrank; i < NPOINTS; i+=mysize)
    {
      for (j = 0; j < NPOINTS; j++)
      {
        c.r = -2.0 + 2.5 * (double)(i) / (double)(NPOINTS) + eps;
        c.i = 1.125 * (double)(j) / (double)(NPOINTS) + eps;
        res=testpoint(c);
         MPI_Send(&res, 1, MPI_INT, 0, 0, MPI_COMM_WORLD);
      }
    }
  }

  // Calculate area of set and error estimate and output the results

  MPI_Finalize();
  ensec = MPI_Wtime();
  commtime = ensec - stsec;
  // area = 2.0 * 2.5 * 1.125 * (double)(NPOINTS * NPOINTS - numoutside) / (double)(NPOINTS * NPOINTS);
  // error = area / (double)NPOINTS;
  printf("Area of Mandlebrot set = %12.8f +/- %12.8f\n", area, error);

  if (myrank == 0)
  {
    printf("%.3f\n", commtime);
  }
}

int testpoint(struct d_complex c)
{

  // Does the iteration z=z*z+c, until |z| > 2 when point is known to be outside set
  // If loop count reaches MAXITER, point is considered to be inside the set

  struct d_complex z;
  int iter;
  double temp;

  z = c;
  for (iter = 0; iter < MAXITER; iter++)
  {
    temp = (z.r * z.r) - (z.i * z.i) + c.r;
    z.i = z.r * z.i * 2 + c.i;
    z.r = temp;
    if ((z.r * z.r + z.i * z.i) > 4.0)
    {
      // MPI_Send( &numoutside, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
      return numoutside;
      break;
    }
  }
  return 0;
}

</code>```

the expectation is to get around 1.510659 when running the code with NPOINTS: 1000,2000 and 2,4, processors .

Title: parallelizing Mandelbrot using MPI

Body:
I am trying to parallelize the Mandelbrot.
the correct output should be around 1.510659. however I am not getting that correctly.

**  PROGRAM: Mandelbrot area
**
**  PURPOSE: Program to compute the area of a  Mandelbrot set.
**           The correct answer should be around 1.510659.
**
**  USAGE:   Program runs without input ... just run the executable
**
reduction for numoutside.

this is my parallelized code

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <mpi.h>

#define NPOINTS 1000
#define MAXITER 1000
int P = 1;
struct d_complex
{
  double r;
  double i;
};

int testpoint(struct d_complex);

struct d_complex c;
struct d_complex cPart;
int numoutside = 1;

int main()
{
  int i, j, row;
    int res;
  double area, error, eps = 1.0e-5;
  int myrank, mysize;
  double stsec, ensec, commtime, maxcommtime;
  MPI_Status status;
  MPI_Init(NULL, NULL);
  MPI_Comm_size(MPI_COMM_WORLD, &mysize);
  MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
  stsec = MPI_Wtime();
  //   Loop over grid of points in the complex plane which contains the Mandelbrot set,
  //   testing each point to see whether it is inside or outside the set.
  /*for (i = 0; i < NPOINTS; i ++)
  {
    for (j = 0; j < NPOINTS ; j++)
    {
      c.r = -2.0 + 2.5 * (double)(i) / (double)(NPOINTS) + eps;
      c.i = 1.125 * (double)(j) / (double)(NPOINTS) + eps;
      testpoint(c);
    }
  }*/

  if (myrank == 0)
  {

    /* Begin User Program  - the master */
    //*
    int outsum, nb_pixel = NPOINTS*NPOINTS ;
    for (i = 0; i < nb_pixel; i++)
    {
      MPI_Recv(&res, 1, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status);
      // printf("Slave id %d has send : %d \n", status.MPI_SOURCE, data[2]);
      // printf("%d: [%d,%d] -> [%d,%d] = %d\n", status.MPI_SOURCE, data[0], data[1], data[0] + MAXX, data[1] + MAXY, data[2]);
      res += numoutside;
    }
     area = 2.0 * 2.5 * 1.125 * (double)(NPOINTS * NPOINTS - res) / (double)(NPOINTS * NPOINTS);
   error = area / (double)NPOINTS;
    printf("Area of Mandlebrot set = %12.8f +/- %12.8f\n", area, error);
    printf("Finish.\n");
  }
  else
  {

    for (i = myrank; i < NPOINTS; i+=mysize)
    {
      for (j = 0; j < NPOINTS; j++)
      {
        c.r = -2.0 + 2.5 * (double)(i) / (double)(NPOINTS) + eps;
        c.i = 1.125 * (double)(j) / (double)(NPOINTS) + eps;
        res=testpoint(c);
         MPI_Send(&res, 1, MPI_INT, 0, 0, MPI_COMM_WORLD);
      }
    }
  }

  // Calculate area of set and error estimate and output the results

  MPI_Finalize();
  ensec = MPI_Wtime();
  commtime = ensec - stsec;
  // area = 2.0 * 2.5 * 1.125 * (double)(NPOINTS * NPOINTS - numoutside) / (double)(NPOINTS * NPOINTS);
  // error = area / (double)NPOINTS;
  printf("Area of Mandlebrot set = %12.8f +/- %12.8f\n", area, error);

  if (myrank == 0)
  {
    printf("%.3f\n", commtime);
  }
}

int testpoint(struct d_complex c)
{

  // Does the iteration z=z*z+c, until |z| > 2 when point is known to be outside set
  // If loop count reaches MAXITER, point is considered to be inside the set

  struct d_complex z;
  int iter;
  double temp;

  z = c;
  for (iter = 0; iter < MAXITER; iter++)
  {
    temp = (z.r * z.r) - (z.i * z.i) + c.r;
    z.i = z.r * z.i * 2 + c.i;
    z.r = temp;
    if ((z.r * z.r + z.i * z.i) > 4.0)
    {
      // MPI_Send( &numoutside, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
      return numoutside;
      break;
    }
  }
  return 0;
}

the expectation is to get around 1.510659 when running the code with NPOINTS: 1000,2000 and 2,4, processors .


问:
Spring Security configuration with role-based access returns a 403 error
I am developing a small application with Spring Security configuration and JWT token-based authorization and encountered a problem - when using hasRole() or hasPermission() methods to differentiate access to requests, even if the authorized user has the roles that meet the restrictions, the request still returns a 403 code.

Implementing of UserDetails and UserDetailsService

```<code>@RequiredArgsConstructor
public class UserDetailsImpl implements UserDetails {

  private final User user;

  @Override
  public Collection<? extends GrantedAuthority> getAuthorities() {
    return user.getRoles();
  }

  @Override
  public String getPassword() {
    return user.getPassword();
  }

  @Override
  public String getUsername() {
    return user.getUsername();
  }

  @Override
  public boolean isAccountNonExpired() {
    return user.getIsEnable();
  }

  @Override
  public boolean isAccountNonLocked() {
    return user.getIsEnable();
  }

  @Override
  public boolean isCredentialsNonExpired() {
    return user.getIsEnable();
  }

  @Override
  public boolean isEnabled() {
    return user.getIsEnable();
  }
}
</code>```
```<code>@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
  private final UserRepository userRepository;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    String exceptionMsg = String.format("User with username '%s' not found", username);
    return new UserDetailsImpl(userRepository.findUserByUsername(username)
            .orElseThrow(() -> new UsernameNotFoundException(exceptionMsg)));
  }
}
</code>```

User entity and Roles

```<code>@Entity(name = "users")
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@EqualsAndHashCode(of = {"id", "username"})
public class User {
  @Transient
  private final String MAIL_REGEX =
          "^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$";

  @Id
  @GeneratedValue(strategy = IDENTITY)
  private Long id;

  @Column(unique = true, nullable = false)
  @NotBlank(message = "Username cannot be empty")
  @NotNull(message = "Username cannot be empty")
  @Size(min = 1, max = 90)
  private String username;

  @Column(nullable = false)
  @NotBlank(message = "Password cannot be empty")
  @NotNull(message = "Password cannot be empty")
  @Size(min = 8, max = 100)
  private String password;

  @Column(unique = true, nullable = false)
  @Email(message = "Invalid email address", regexp = MAIL_REGEX)
  @NotBlank(message = "Email cannot be empty")
  private String email;

  @ElementCollection(fetch = EAGER)
  private Set<Role> roles = Set.of(Role.USER, Role.ADMIN, Role.SUPER_ADMIN);

  @Column(nullable = false)
  private Boolean isEnable = true;
}
</code>```
```<code>public enum Role implements GrantedAuthority {
  USER, ADMIN, SUPER_ADMIN;

  @Override
  public String getAuthority() {
    return name();
  }
}
</code>```

Security configuration

```<code>@Configuration
public class SecurityConfig {
  @Value("${jwt.public.key}")
  RSAPublicKey publicKey;

  @Value("${jwt.private.key}")
  RSAPrivateKey privateKey;

  @Bean
  PasswordEncoder encoder() {
    return new BCryptPasswordEncoder(10);
  }

  @Bean
  public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.authorizeHttpRequests().requestMatchers("/login", "/register").permitAll();
    http.authorizeHttpRequests().requestMatchers("/hello").hasAuthority("USER");
    http.httpBasic(Customizer.withDefaults());
    http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
    http.sessionManagement(session ->
            session.sessionCreationPolicy(STATELESS));
    http.exceptionHandling()
            .authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint())
            .accessDeniedHandler(new BearerTokenAccessDeniedHandler());

    return http.build();
  }

  @Bean
  JwtDecoder jwtDecoder() {
    return NimbusJwtDecoder.withPublicKey(publicKey).build();
  }

  @Bean
  JwtEncoder jwtEncoder() {
    JWK jwk = new RSAKey.Builder(publicKey).privateKey(privateKey).build();
    JWKSource<SecurityContext> jwkSource = new ImmutableJWKSet<>(new JWKSet(jwk));
    return new NimbusJwtEncoder(jwkSource);
  }
}
</code>```

If I try to query the /hello path, it returns a forbidden error, despite the fact that the authorized user has all the possible roles. Can you tell me what could be the problem? A long time ago I did everything exactly as it is now and everything worked without errors.

Tried to add ROLE_ prefix, make roles without enum class with clear string format, applied both hasRole() and hasAuthority() methods

Body:
I am developing a small application with Spring Security configuration and JWT token-based authorization and encountered a problem - when using hasRole() or hasPermission() methods to differentiate access to requests, even if the authorized user has the roles that meet the restrictions, the request still returns a 403 code.

Implementing of UserDetails and UserDetailsService

@RequiredArgsConstructor
public class UserDetailsImpl implements UserDetails {

  private final User user;

  @Override
  public Collection<? extends GrantedAuthority> getAuthorities() {
    return user.getRoles();
  }

  @Override
  public String getPassword() {
    return user.getPassword();
  }

  @Override
  public String getUsername() {
    return user.getUsername();
  }

  @Override
  public boolean isAccountNonExpired() {
    return user.getIsEnable();
  }

  @Override
  public boolean isAccountNonLocked() {
    return user.getIsEnable();
  }

  @Override
  public boolean isCredentialsNonExpired() {
    return user.getIsEnable();
  }

  @Override
  public boolean isEnabled() {
    return user.getIsEnable();
  }
}

@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
  private final UserRepository userRepository;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    String exceptionMsg = String.format("User with username '%s' not found", username);
    return new UserDetailsImpl(userRepository.findUserByUsername(username)
            .orElseThrow(() -> new UsernameNotFoundException(exceptionMsg)));
  }
}

User entity and Roles

@Entity(name = "users")
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@EqualsAndHashCode(of = {"id", "username"})
public class User {
  @Transient
  private final String MAIL_REGEX =
          "^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$";

  @Id
  @GeneratedValue(strategy = IDENTITY)
  private Long id;

  @Column(unique = true, nullable = false)
  @NotBlank(message = "Username cannot be empty")
  @NotNull(message = "Username cannot be empty")
  @Size(min = 1, max = 90)
  private String username;

  @Column(nullable = false)
  @NotBlank(message = "Password cannot be empty")
  @NotNull(message = "Password cannot be empty")
  @Size(min = 8, max = 100)
  private String password;

  @Column(unique = true, nullable = false)
  @Email(message = "Invalid email address", regexp = MAIL_REGEX)
  @NotBlank(message = "Email cannot be empty")
  private String email;

  @ElementCollection(fetch = EAGER)
  private Set<Role> roles = Set.of(Role.USER, Role.ADMIN, Role.SUPER_ADMIN);

  @Column(nullable = false)
  private Boolean isEnable = true;
}

public enum Role implements GrantedAuthority {
  USER, ADMIN, SUPER_ADMIN;

  @Override
  public String getAuthority() {
    return name();
  }
}

Security configuration

@Configuration
public class SecurityConfig {
  @Value("${jwt.public.key}")
  RSAPublicKey publicKey;

  @Value("${jwt.private.key}")
  RSAPrivateKey privateKey;

  @Bean
  PasswordEncoder encoder() {
    return new BCryptPasswordEncoder(10);
  }

  @Bean
  public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.authorizeHttpRequests().requestMatchers("/login", "/register").permitAll();
    http.authorizeHttpRequests().requestMatchers("/hello").hasAuthority("USER");
    http.httpBasic(Customizer.withDefaults());
    http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
    http.sessionManagement(session ->
            session.sessionCreationPolicy(STATELESS));
    http.exceptionHandling()
            .authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint())
            .accessDeniedHandler(new BearerTokenAccessDeniedHandler());

    return http.build();
  }

  @Bean
  JwtDecoder jwtDecoder() {
    return NimbusJwtDecoder.withPublicKey(publicKey).build();
  }

  @Bean
  JwtEncoder jwtEncoder() {
    JWK jwk = new RSAKey.Builder(publicKey).privateKey(privateKey).build();
    JWKSource<SecurityContext> jwkSource = new ImmutableJWKSet<>(new JWKSet(jwk));
    return new NimbusJwtEncoder(jwkSource);
  }
}

If I try to query the /hello path, it returns a forbidden error, despite the fact that the authorized user has all the possible roles. Can you tell me what could be the problem? A long time ago I did everything exactly as it is now and everything worked without errors.

Tried to add ROLE_ prefix, make roles without enum class with clear string format, applied both hasRole() and hasAuthority() methods