问:
Cannot access 'kotlin.ranges.OpenEndRange' in IDEA and Kotlin 1.7.0
I have a Kotlin + Maven project which uses Kotlin 1.7.0. When I import the project in IDEA I see an 'error' (more on that later) in the in operator when used with an IntRange:

My IDEA version is the latest as of this writing (Build #IU-223.7571.182, built on November 29, 2022).

It looks like for some reason IDEA is trying to find the OpenEndRange type introduced in 1.7.20 (https://kotlinlang.org/docs/whatsnew1720.html#preview-of-the-operator-for-creating-open-ended-ranges), but my project is using 1.7.0 and the type doesn't exist.

I noticed that in IDEA preferences it uses a newer plugin and analyzer versions than 1.7.0:

When the project is compiled on the CLI with just maven, all works. Actually, it also builds and runs in IDEA, so the red underscore is somehow bogus and confusing.

Here is my pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>idea_kotlin_test</artifactId>
    <version>0.0.1</version>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <kotlin.version>1.7.0</kotlin.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-stdlib-jdk8</artifactId>
            <version>${kotlin.version}</version>
        </dependency>
    </dependencies>

    <build>
        <sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
        <plugins>
            <plugin>
                <groupId>org.jetbrains.kotlin</groupId>
                <artifactId>kotlin-maven-plugin</artifactId>
                <version>${kotlin.version}</version>
                <executions>
                    <execution>
                        <id>compile</id>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
```
<p>and the sample code that shows the issue:</p>
<pre class="lang-kotlin prettyprint-override"><code>package com.example

import java.time.LocalDate
import java.time.temporal.ChronoField

fun foo(month: Int): Boolean {
    val start = LocalDate.now().get(ChronoField.MONTH_OF_YEAR) // as Int

    return month in (start..12) // <=== here
}

fun main() {
    println(foo(1))
}
</code>```

I imported the project into IDEA by just choosing 'File' -> 'Open' and choosing the project folder, it detects everything automatically.

It looks as though IDEA somehow doesn't like the LocalDate.get(TemporalField field) call, or rather its return value. When I add as Int, the 'error' goes away but then as Int is greyed out as 'needless cast' (which I expect); the 'error' is also not shown when I just assign a hardcoded Int to the start val. I tried calling different Java methods returning int but to no avail, I couldn't reproduce the issue.

What is going on and how can I tell IDEA to stop showing this strange 'error'? Why is the LocalDate.get(TemporalField) method special?

Body:
I have a Kotlin + Maven project which uses Kotlin 1.7.0. When I import the project in IDEA I see an 'error' (more on that later) in the in operator when used with an IntRange:

My IDEA version is the latest as of this writing (Build #IU-223.7571.182, built on November 29, 2022).

It looks like for some reason IDEA is trying to find the OpenEndRange type introduced in 1.7.20 (https://kotlinlang.org/docs/whatsnew1720.html#preview-of-the-operator-for-creating-open-ended-ranges), but my project is using 1.7.0 and the type doesn't exist.

I noticed that in IDEA preferences it uses a newer plugin and analyzer versions than 1.7.0:

When the project is compiled on the CLI with just maven, all works. Actually, it also builds and runs in IDEA, so the red underscore is somehow bogus and confusing.

Here is my pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>idea_kotlin_test</artifactId>
    <version>0.0.1</version>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <kotlin.version>1.7.0</kotlin.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-stdlib-jdk8</artifactId>
            <version>${kotlin.version}</version>
        </dependency>
    </dependencies>

    <build>
        <sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
        <plugins>
            <plugin>
                <groupId>org.jetbrains.kotlin</groupId>
                <artifactId>kotlin-maven-plugin</artifactId>
                <version>${kotlin.version}</version>
                <executions>
                    <execution>
                        <id>compile</id>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

and the sample code that shows the issue:

package com.example

import java.time.LocalDate
import java.time.temporal.ChronoField

fun foo(month: Int): Boolean {
    val start = LocalDate.now().get(ChronoField.MONTH_OF_YEAR) // as Int

    return month in (start..12) // <=== here
}

fun main() {
    println(foo(1))
}

I imported the project into IDEA by just choosing 'File' -> 'Open' and choosing the project folder, it detects everything automatically.

It looks as though IDEA somehow doesn't like the LocalDate.get(TemporalField field) call, or rather its return value. When I add as Int, the 'error' goes away but then as Int is greyed out as 'needless cast' (which I expect); the 'error' is also not shown when I just assign a hardcoded Int to the start val. I tried calling different Java methods returning int but to no avail, I couldn't reproduce the issue.

What is going on and how can I tell IDEA to stop showing this strange 'error'? Why is the LocalDate.get(TemporalField) method special?


来源: stackexchange

问:
bitnami/airflow running kubectl command
How can I create a DAG to run the command kubectl version?

DAG file

```<code>...
bash_task =
BashOperator(
 task_id="test_kubectl",
 bash_command="kubectl version"
)
...
</code>```

The logs of the airflow run shows

```<code>/bin/bash: line 1: kubectl: command not found
</code>```

I am not sure if this is the right way to run the kubectl command

ContentLicense: CC BY-SA 4.0

Title: bitnami/airflow running kubectl command

Body:
How can I create a DAG to run the command kubectl version?

DAG file

...
bash_task =
BashOperator(
 task_id="test_kubectl",
 bash_command="kubectl version"
)
...

The logs of the airflow run shows

/bin/bash: line 1: kubectl: command not found

I am not sure if this is the right way to run the kubectl command


问:
Process multiple text files for display in template

I have 2 text files (A & B) for each of 174 devices.

I have a template.xlsx (4 sheets total) that reads both device text files (A & B - 1 sheet each) in the same workbook, and displays relevant data in forms (A & B) in the same workbook.

I would like to have code that import the text files (A & B for each device) into sheets (name from text file name) and get them into the same workbook as the template sheets (4 sheets total) then save as device_serial_number_datefromtext.xlsx

I found some code that imported all the text files to separate sheets in a single book and another code to make separate books of each of the sheets of the single book, but I’m having trouble using sheets.copy to get the text sheets and template sheets in the same book.

I see 3 approaches to get from here to there, but am not skilled enought to know what direction I should be working.

a) Start with the template book and import the device text A & B files to it and save as device_serial_number_date.xlsx, somehow looping through the directory of all the text files.

b) Start with devicefileA.xlsx then copy template sheets and devicefileB sheet from devicefileB.xlsx somehow looping through all device.xlsx in the folder

c) Start with the workbook that has all the device files already imported to it, add the template sheets to it, then copy device files A & B and the template sheets to a new workbook and save as device_serial_number_date.xlsx somehow looping through all sheets.

Thank you in advance for any help you could provide.

This code will copy a sheet from a file selected in a dialog box to book the code is running in, but it does not loop.

```<code>Sub copy_sheet_to_existing_wb() 'works

Dim WorkbookA As Workbook

Set WorkbookA = ActiveWorkbook

Dim otherWorkbook As Workbook

folder = Application.GetOpenFilename("Excel (*.xlsx), *.xlsx", 1, "Select file")
Set otherWorkbook = Workbooks.Open(Filename:=folder)
otherWorkbook.ActiveSheet.Copy Before:=WorkbookA.Sheets(1)

End Sub

</code>```

Body:
I have 2 text files (A & B) for each of 174 devices.

I have a template.xlsx (4 sheets total) that reads both device text files (A & B - 1 sheet each) in the same workbook, and displays relevant data in forms (A & B) in the same workbook.

I would like to have code that import the text files (A & B for each device) into sheets (name from text file name) and get them into the same workbook as the template sheets (4 sheets total) then save as device_serial_number_datefromtext.xlsx

I found some code that imported all the text files to separate sheets in a single book and another code to make separate books of each of the sheets of the single book, but I’m having trouble using sheets.copy to get the text sheets and template sheets in the same book.

I see 3 approaches to get from here to there, but am not skilled enought to know what direction I should be working.

a) Start with the template book and import the device text A & B files to it and save as device_serial_number_date.xlsx, somehow looping through the directory of all the text files.

b) Start with devicefileA.xlsx then copy template sheets and devicefileB sheet from devicefileB.xlsx somehow looping through all device.xlsx in the folder

c) Start with the workbook that has all the device files already imported to it, add the template sheets to it, then copy device files A & B and the template sheets to a new workbook and save as device_serial_number_date.xlsx somehow looping through all sheets.

Thank you in advance for any help you could provide.

This code will copy a sheet from a file selected in a dialog box to book the code is running in, but it does not loop.

Sub copy_sheet_to_existing_wb() 'works

Dim WorkbookA As Workbook

Set WorkbookA = ActiveWorkbook

Dim otherWorkbook As Workbook

folder = Application.GetOpenFilename("Excel (*.xlsx), *.xlsx", 1, "Select file")
Set otherWorkbook = Workbooks.Open(Filename:=folder)
otherWorkbook.ActiveSheet.Copy Before:=WorkbookA.Sheets(1)

End Sub


问:
Excel spreadsheet with historical data & add more data in future using formulas and functions
I have a spreadsheet with historical data. There are rows and columns, the first couple of columns remain the same throughout the years but as we add new data, a new column must be added.
every year has 4 columns,

domestic

international

total = domestic+ International (this includes the sum formula of two columns)

Total Workforce unit = domestic*$0.52(0.52 is the fixed value which we have to pick from another cell)

The values are for fall, summer and winter and they should be calculated like that
these four columns remain the same every year

I would like to create a drop-down filter that listed the years 2017, 2018, and so on...

if we select 2017 year, then there should be information all 4 columns for fall, summer, and winter would appear with all the formulas in place. and if we select any other year, then it will display information related to that particular.

if we select 2023, then we would be able to add the information manually and save it on the same page and so on.


问:
NextJs React-Quill Dynamic import not working how can i solve this?
I am using NextJs with React-Quill ı am getting error.

Error : - error - unhandledRejection: ReferenceError: document is not defined
at Object. \node_modules\quill\dist\quill.js:7661:12)

When I did research they said to use dynamic import for this problem. But dynamic also not working.

dynamic import not working, is there any other solution ?

I also Try _app js folder conditional render (typeof window !== "undefined") not work.

My Code Here >

```<code>import React from 'react';
import { getSession } from 'next-auth/react';
import dynamic from 'next/dynamic';

const ReactQuill = dynamic(import('react-quill'), {
  ssr: false,
  loading: () => <p>Loading ...</p>,
});

function EditService() {
  return <ReactQuill />;
}

export async function getServerSideProps(context) {
  const session = await getSession({ req: context.req });

  if (!session) {
    return {
      redirect: {
        destination: '/',
        permanent: false,
      },
    };
  }
  return {
    props: {},
  };
}

export default EditService;

</code>```

Body:
I am using NextJs with React-Quill ı am getting error.

Error : - error - unhandledRejection: ReferenceError: document is not defined
at Object. \node_modules\quill\dist\quill.js:7661:12)

When I did research they said to use dynamic import for this problem. But dynamic also not working.

dynamic import not working, is there any other solution ?

I also Try _app js folder conditional render (typeof window !== "undefined") not work.

My Code Here >

import React from 'react';
import { getSession } from 'next-auth/react';
import dynamic from 'next/dynamic';

const ReactQuill = dynamic(import('react-quill'), {
  ssr: false,
  loading: () =>
Loading ...
,
});

function EditService() {
  return <ReactQuill />;
}

export async function getServerSideProps(context) {
  const session = await getSession({ req: context.req });

  if (!session) {
    return {
      redirect: {
        destination: '/',
        permanent: false,
      },
    };
  }
  return {
    props: {},
  };
}

export default EditService;


问:
Precompile/compile nunjucks refresh issue gulp-inline-source
Hi there this is a long shot but, hope someone can help,

I am using gulp-inline-source-html (https://github.com/exuanbo/gulp-inline-source-html) & gulp-nunjucks-render (https://github.com/carlitoplatanito/gulp-nunjucks-render) plus browserSync to show the updated UI

The plugin .pipe(inlineSource(... does something, but the problem is i don't think it properly writes the file after doing css changes, as the html in the build folder is not updated. Only when I do a hard refresh the UI is updated.

gulpfile.js

```<code>pipe(nunjucksRender({
   path: njkPaths,
   ext: "",
   data: ENV_VARS,
   envOptions: {
     trimBlocks: true,
     lstripBlocks: true
   }
 }))
 .pipe(inlineSource({
     compress: false,
     saveRemote: true,
     handlers: [require("./nunjucksHandler.js")] ??
 }))
</code>```

I was trying the precompile approach https://github.com/popeindustries/inline-source/issues/70#issuecomment-384548345 (comment) but got nowhere.

nunjucksHandler.js

```<code>const Nunjucks = require('nunjucks');

module.exports = function nunjucks(source, context) {
    return new Promise((resolve, reject) => {
        if (
            source.fileContent &&
            !source.content &&
            source.type == "text/css"
        ) {
        let content;
        try {
            content = Nunjucks.precompile(source.fileContent);
        } catch (err) {
            return reject(err);
        }
           // Need to expose templates for later use somehow...
           source.content = content
        }

        resolve();
    });
};
</code>```

.nunjucks

```<code><link inline href="{{ENV_PARTIALS_BASE_PATH}}/common/terms-and-conditions/index.css"
rel="stylesheet"/>
<section>html</section>
{% somenunjucks syntax etc %}
</code>```

Body:
Hi there this is a long shot but, hope someone can help,

I am using gulp-inline-source-html (https://github.com/exuanbo/gulp-inline-source-html) & gulp-nunjucks-render (https://github.com/carlitoplatanito/gulp-nunjucks-render) plus browserSync to show the updated UI

The plugin .pipe(inlineSource(... does something, but the problem is i don't think it properly writes the file after doing css changes, as the html in the build folder is not updated. Only when I do a hard refresh the UI is updated.

gulpfile.js

pipe(nunjucksRender({
   path: njkPaths,
   ext: "",
   data: ENV_VARS,
   envOptions: {
     trimBlocks: true,
     lstripBlocks: true
   }
 }))
 .pipe(inlineSource({
     compress: false,
     saveRemote: true,
     handlers: [require("./nunjucksHandler.js")] ??
 }))

I was trying the precompile approach https://github.com/popeindustries/inline-source/issues/70#issuecomment-384548345 (comment) but got nowhere.

nunjucksHandler.js

const Nunjucks = require('nunjucks');

module.exports = function nunjucks(source, context) {
    return new Promise((resolve, reject) => {
        if (
            source.fileContent &&
            !source.content &&
            source.type == "text/css"
        ) {
        let content;
        try {
            content = Nunjucks.precompile(source.fileContent);
        } catch (err) {
            return reject(err);
        }
           // Need to expose templates for later use somehow...
           source.content = content
        }

        resolve();
    });
};

.nunjucks

<link inline href="{{ENV_PARTIALS_BASE_PATH}}/common/terms-and-conditions/index.css"
rel="stylesheet"/>

html

{% somenunjucks syntax etc %}


问:
Listbox with Pivot Table Interaction Help - Excel VBA
I have created a userform and am having issues with the listbox in the userform. I currently have the listbox where when it interacts with pivot table "FilterPivot" it will filter that pivot according to what is checked in the listbox. I also have another pivot "FilterPivot2" where the main portion of the userform gets its total costs from (See image). The issue I have is with a slicer that I have connected to "FilterPivot". If it is only connected to "FilterPivot", then the listbox values stay, but the total costs do not change. When I connect "FilterPivot2" to the slicer the values will change when I change the listbox, however the listbox values will change and will now only show the values that are visible in the pivot table rather than all the values of the pivot table. What am I missing here? Thank you!

```<code>Private Sub TotalCostListUpdate_Click()

        Dim myArray() As Variant
        Dim i As Integer, count As Integer
        Dim msg
        Dim pvtItm As PivotItem
        Dim sc1 As SlicerCache

        Set sc1 = ThisWorkbook.SlicerCaches("Slicer_Alternates")

        count = 1
        For i = 0 To TotalCostList.ListCount - 1
            If TotalCostList.Selected(i) = True Then
                ReDim Preserve myArray(count)
                myArray(count) = TotalCostList.List(i)
                count = count + 1
            End If
        Next i

'== Part 2

        With Worksheets("Sheet3").PivotTables("FilterPivot").PivotFields("Alternates")
            For Each pvtItm In .PivotItems
                On Error GoTo ClearFilter
                If IsInArray(pvtItm.Caption, myArray) = False Then
                    pvtItm.Visible = False
                Else
                    pvtItm.Visible = True
                End If
            Next pvtItm
        End With

    Description = Sheet8.Range("A1").Value
    Material = Sheet8.Range("A2").Value
    Labor = Sheet8.Range("A3").Value
    SubContractor = Sheet8.Range("A4").Value
    Equipment = Sheet8.Range("A5").Value
    Other = Sheet8.Range("A6").Value
    TotalCost = Sheet8.Range("A7").Value
    Overhead = Sheet8.Range("A9").Value
    Profit = Sheet8.Range("A10").Value
    Phoenix = Sheet8.Range("A11").Value
    Bond = Sheet8.Range("A12").Value
    TotalPrice = Sheet8.Range("A14").Value
    DescriptionTotal = Sheet8.Range("B1").Value
    MaterialTotal = Sheet8.Range("B2").Value
    MaterialTotal = Format(MaterialTotal, "$#,##0.00")
    LaborTotal = Sheet8.Range("B3").Value
    LaborTotal = Format(LaborTotal, "$#,##0.00")
    SubContractorTotal = Sheet8.Range("B4").Value
    SubContractorTotal = Format(SubContractorTotal, "$#,##0.00")
    EquipmentTotal = Sheet8.Range("B5").Value
    EquipmentTotal = Format(EquipmentTotal, "$#,##0.00")
    OtherTotal = Sheet8.Range("B6").Value
    OtherTotal = Format(OtherTotal, "$#,##0.00")
    TotalCostTotal = Sheet8.Range("B7").Value
    TotalCostTotal = Format(TotalCostTotal, "$#,##0.00")
    OverheadTotal = Sheet8.Range("B9").Value
    OverheadTotal = Format(OverheadTotal, "$#,##0.00")
    ProfitTotal = Sheet8.Range("B10").Value
    ProfitTotal = Format(ProfitTotal, "$#,##0.00")
    PhoenixTotal = Sheet8.Range("B11").Value
    PhoenixTotal = Format(PhoenixTotal, "$#,##0.00")
    BondTotal = Sheet8.Range("B12").Value
    BondTotal = Format(BondTotal, "$#,##0.00")
    TotalPriceTotal = Sheet8.Range("B14").Value
    TotalPriceTotal = Format(TotalPriceTotal, "$#,##0.00")

Exit Sub

ClearFilter:
    sc1.ClearAllFilters

For i = 0 To TotalCostList.ListCount - 1
    TotalCostList.Selected(i) = True
Next i

End Sub

Private Sub UserForm_Initialize()

    Me.StartUpPosition = 0
    Me.Top = Application.Top + Application.Height - Me.Height * 1.08
    Me.Left = Application.Left + Application.Width - Me.Width * 1.76

    Description = Sheet8.Range("A1").Value
    Material = Sheet8.Range("A2").Value
    Labor = Sheet8.Range("A3").Value
    SubContractor = Sheet8.Range("A4").Value
    Equipment = Sheet8.Range("A5").Value
    Other = Sheet8.Range("A6").Value
    TotalCost = Sheet8.Range("A7").Value
    Overhead = Sheet8.Range("A9").Value
    Profit = Sheet8.Range("A10").Value
    Phoenix = Sheet8.Range("A11").Value
    Bond = Sheet8.Range("A12").Value
    TotalPrice = Sheet8.Range("A14").Value
    DescriptionTotal = Sheet8.Range("B1").Value
    MaterialTotal = Sheet8.Range("B2").Value
    MaterialTotal = Format(MaterialTotal, "$#,##0.00")
    LaborTotal = Sheet8.Range("B3").Value
    LaborTotal = Format(LaborTotal, "$#,##0.00")
    SubContractorTotal = Sheet8.Range("B4").Value
    SubContractorTotal = Format(SubContractorTotal, "$#,##0.00")
    EquipmentTotal = Sheet8.Range("B5").Value
    EquipmentTotal = Format(EquipmentTotal, "$#,##0.00")
    OtherTotal = Sheet8.Range("B6").Value
    OtherTotal = Format(OtherTotal, "$#,##0.00")
    TotalCostTotal = Sheet8.Range("B7").Value
    TotalCostTotal = Format(TotalCostTotal, "$#,##0.00")
    OverheadTotal = Sheet8.Range("B9").Value
    OverheadTotal = Format(OverheadTotal, "$#,##0.00")
    ProfitTotal = Sheet8.Range("B10").Value
    ProfitTotal = Format(ProfitTotal, "$#,##0.00")
    PhoenixTotal = Sheet8.Range("B11").Value
    PhoenixTotal = Format(PhoenixTotal, "$#,##0.00")
    BondTotal = Sheet8.Range("B12").Value
    BondTotal = Format(BondTotal, "$#,##0.00")
    TotalPriceTotal = Sheet8.Range("B14").Value
    TotalPriceTotal = Format(TotalPriceTotal, "$#,##0.00")

Dim List As New Collection
Dim Rng As Range
Dim lngIndex As Long

LastRow = Sheet8.Columns("A").Find(What:="*", LookIn:=xlValues, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

Set Rng = Sheet8.Range("A18:B" & LastRow - 1)

TotalCostList.ColumnCount = 2

With TotalCostList
    .ColumnCount = 2
    .List = Rng.Value
    .BorderStyle = fmBorderStyleSingle
End With

With Me.TotalCostList
    For lngIndex = 0 To .ListCount - 1
        .List(lngIndex, 1) = Format(.List(lngIndex, 1), "$#,##0.00")
        .TextAlign = 1 - frmTextAlignLeft
    Next lngIndex
End With

Dim i As Long

For i = 0 To TotalCostList.ListCount - 1
    TotalCostList.Selected(i) = True
Next i

End Sub

     Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
        Dim i
        For i = LBound(arr) To UBound(arr)
            If arr(i) = stringToBeFound Then
                IsInArray = True
                Exit Function
            End If
        Next i
        IsInArray = False

    End Function
</code>```

Body:
I have created a userform and am having issues with the listbox in the userform. I currently have the listbox where when it interacts with pivot table "FilterPivot" it will filter that pivot according to what is checked in the listbox. I also have another pivot "FilterPivot2" where the main portion of the userform gets its total costs from (See image). The issue I have is with a slicer that I have connected to "FilterPivot". If it is only connected to "FilterPivot", then the listbox values stay, but the total costs do not change. When I connect "FilterPivot2" to the slicer the values will change when I change the listbox, however the listbox values will change and will now only show the values that are visible in the pivot table rather than all the values of the pivot table. What am I missing here? Thank you!

Private Sub TotalCostListUpdate_Click()

        Dim myArray() As Variant
        Dim i As Integer, count As Integer
        Dim msg
        Dim pvtItm As PivotItem
        Dim sc1 As SlicerCache

        Set sc1 = ThisWorkbook.SlicerCaches("Slicer_Alternates")

        count = 1
        For i = 0 To TotalCostList.ListCount - 1
            If TotalCostList.Selected(i) = True Then
                ReDim Preserve myArray(count)
                myArray(count) = TotalCostList.List(i)
                count = count + 1
            End If
        Next i

'== Part 2

        With Worksheets("Sheet3").PivotTables("FilterPivot").PivotFields("Alternates")
            For Each pvtItm In .PivotItems
                On Error GoTo ClearFilter
                If IsInArray(pvtItm.Caption, myArray) = False Then
                    pvtItm.Visible = False
                Else
                    pvtItm.Visible = True
                End If
            Next pvtItm
        End With

    Description = Sheet8.Range("A1").Value
    Material = Sheet8.Range("A2").Value
    Labor = Sheet8.Range("A3").Value
    SubContractor = Sheet8.Range("A4").Value
    Equipment = Sheet8.Range("A5").Value
    Other = Sheet8.Range("A6").Value
    TotalCost = Sheet8.Range("A7").Value
    Overhead = Sheet8.Range("A9").Value
    Profit = Sheet8.Range("A10").Value
    Phoenix = Sheet8.Range("A11").Value
    Bond = Sheet8.Range("A12").Value
    TotalPrice = Sheet8.Range("A14").Value
    DescriptionTotal = Sheet8.Range("B1").Value
    MaterialTotal = Sheet8.Range("B2").Value
    MaterialTotal = Format(MaterialTotal, "$#,##0.00")
    LaborTotal = Sheet8.Range("B3").Value
    LaborTotal = Format(LaborTotal, "$#,##0.00")
    SubContractorTotal = Sheet8.Range("B4").Value
    SubContractorTotal = Format(SubContractorTotal, "$#,##0.00")
    EquipmentTotal = Sheet8.Range("B5").Value
    EquipmentTotal = Format(EquipmentTotal, "$#,##0.00")
    OtherTotal = Sheet8.Range("B6").Value
    OtherTotal = Format(OtherTotal, "$#,##0.00")
    TotalCostTotal = Sheet8.Range("B7").Value
    TotalCostTotal = Format(TotalCostTotal, "$#,##0.00")
    OverheadTotal = Sheet8.Range("B9").Value
    OverheadTotal = Format(OverheadTotal, "$#,##0.00")
    ProfitTotal = Sheet8.Range("B10").Value
    ProfitTotal = Format(ProfitTotal, "$#,##0.00")
    PhoenixTotal = Sheet8.Range("B11").Value
    PhoenixTotal = Format(PhoenixTotal, "$#,##0.00")
    BondTotal = Sheet8.Range("B12").Value
    BondTotal = Format(BondTotal, "$#,##0.00")
    TotalPriceTotal = Sheet8.Range("B14").Value
    TotalPriceTotal = Format(TotalPriceTotal, "$#,##0.00")

Exit Sub

ClearFilter:
    sc1.ClearAllFilters

For i = 0 To TotalCostList.ListCount - 1
    TotalCostList.Selected(i) = True
Next i

End Sub

Private Sub UserForm_Initialize()

    Me.StartUpPosition = 0
    Me.Top = Application.Top + Application.Height - Me.Height * 1.08
    Me.Left = Application.Left + Application.Width - Me.Width * 1.76

    Description = Sheet8.Range("A1").Value
    Material = Sheet8.Range("A2").Value
    Labor = Sheet8.Range("A3").Value
    SubContractor = Sheet8.Range("A4").Value
    Equipment = Sheet8.Range("A5").Value
    Other = Sheet8.Range("A6").Value
    TotalCost = Sheet8.Range("A7").Value
    Overhead = Sheet8.Range("A9").Value
    Profit = Sheet8.Range("A10").Value
    Phoenix = Sheet8.Range("A11").Value
    Bond = Sheet8.Range("A12").Value
    TotalPrice = Sheet8.Range("A14").Value
    DescriptionTotal = Sheet8.Range("B1").Value
    MaterialTotal = Sheet8.Range("B2").Value
    MaterialTotal = Format(MaterialTotal, "$#,##0.00")
    LaborTotal = Sheet8.Range("B3").Value
    LaborTotal = Format(LaborTotal, "$#,##0.00")
    SubContractorTotal = Sheet8.Range("B4").Value
    SubContractorTotal = Format(SubContractorTotal, "$#,##0.00")
    EquipmentTotal = Sheet8.Range("B5").Value
    EquipmentTotal = Format(EquipmentTotal, "$#,##0.00")
    OtherTotal = Sheet8.Range("B6").Value
    OtherTotal = Format(OtherTotal, "$#,##0.00")
    TotalCostTotal = Sheet8.Range("B7").Value
    TotalCostTotal = Format(TotalCostTotal, "$#,##0.00")
    OverheadTotal = Sheet8.Range("B9").Value
    OverheadTotal = Format(OverheadTotal, "$#,##0.00")
    ProfitTotal = Sheet8.Range("B10").Value
    ProfitTotal = Format(ProfitTotal, "$#,##0.00")
    PhoenixTotal = Sheet8.Range("B11").Value
    PhoenixTotal = Format(PhoenixTotal, "$#,##0.00")
    BondTotal = Sheet8.Range("B12").Value
    BondTotal = Format(BondTotal, "$#,##0.00")
    TotalPriceTotal = Sheet8.Range("B14").Value
    TotalPriceTotal = Format(TotalPriceTotal, "$#,##0.00")

Dim List As New Collection
Dim Rng As Range
Dim lngIndex As Long

LastRow = Sheet8.Columns("A").Find(What:="*", LookIn:=xlValues, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

Set Rng = Sheet8.Range("A18:B" & LastRow - 1)

TotalCostList.ColumnCount = 2

With TotalCostList
    .ColumnCount = 2
    .List = Rng.Value
    .BorderStyle = fmBorderStyleSingle
End With

With Me.TotalCostList
    For lngIndex = 0 To .ListCount - 1
        .List(lngIndex, 1) = Format(.List(lngIndex, 1), "$#,##0.00")
        .TextAlign = 1 - frmTextAlignLeft
    Next lngIndex
End With

Dim i As Long

For i = 0 To TotalCostList.ListCount - 1
    TotalCostList.Selected(i) = True
Next i

End Sub

     Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
        Dim i
        For i = LBound(arr) To UBound(arr)
            If arr(i) = stringToBeFound Then
                IsInArray = True
                Exit Function
            End If
        Next i
        IsInArray = False

    End Function


问:
Multiple Datasets vs Single Dataset performance in SSRS Reports
I'm working on a report where I have to get 3 different values making use of 3 queries:

Count of all our users

Users who purchased certain products in the last year

Users who have a certain attribute and have sent documents for signing

All these queries use tables from the same database. The first query takes under a second, the second one takes around 2 min and the third query takes around 1min.

I can create the report in two ways:

Create one data set and get all the required values.

Create one data set for each of these queries and let them run in parallel.

If my understanding is correct, the first method would take around 3 mins to execute whereas the second one would take around 2min. In this case, I think creating multiple data sets is much better for performance than creating one single data set. What do you think? Does running queries in parallel improve the performance in this case? What is a good practice in SSRS in these kind of scenarios? Thanks!


问:
Use YouTubeAnalytics API to get stats from other channels
This code works fine when I'm accessing my own channel:

function test(){
  const channelId = "UC702oPAKxKSQdxvqnAWlkiA"

  let response = YouTube.Channels.list('statistics',{id:channelId});
  let stats = response.items[0].statistics;
  Logger.log(stats);

  const oneMonthInMillis = 1000 * 60 * 60 * 24 * 30;
  const today = new Date();
  const lastMonth = new Date(today.getTime() - oneMonthInMillis);

  const metrics = [
    'views'
  ];
  const result = YouTubeAnalytics.Reports.query({
    ids: 'channel==' + channelId,
    startDate: formatDateString(lastMonth),
    endDate: formatDateString(today),
    metrics: metrics.join(',')
    // dimensions: 'day',
    // sort: 'day'
  });

  const out = [["Subscriber Count","30 Day Views","Total Views"],
              [stats.subscriberCount,result.rows[0][0],stats.viewCount]];
}```

However, I need to use this on accounts for my various clients. When I change the channelId to the ID of the other channel I get "GoogleJsonResponseException: API call to youtubeAnalytics.reports.query failed with error: Forbidden." The YouTube API doesn't have any problem, but it doesn't give me any ability to check the 30-day values, only the total values. I've looked at the OAuth2 instructions and frankly I'm lost there. Can this code be made to work for other channels? Can I get OAuth2 working for any channel? Can I get OAuth2 working for a specific set of channels if the client can do something? Or is this basically impossible?

Body:
This code works fine when I'm accessing my own channel:

function test(){
  const channelId = "UC702oPAKxKSQdxvqnAWlkiA"

  let response = YouTube.Channels.list('statistics',{id:channelId});
  let stats = response.items[0].statistics;
  Logger.log(stats);

  const oneMonthInMillis = 1000 * 60 * 60 * 24 * 30;
  const today = new Date();
  const lastMonth = new Date(today.getTime() - oneMonthInMillis);

  const metrics = [
    'views'
  ];
  const result = YouTubeAnalytics.Reports.query({
    ids: 'channel==' + channelId,
    startDate: formatDateString(lastMonth),
    endDate: formatDateString(today),
    metrics: metrics.join(',')
    // dimensions: 'day',
    // sort: 'day'
  });

  const out = [["Subscriber Count","30 Day Views","Total Views"],
              [stats.subscriberCount,result.rows[0][0],stats.viewCount]];
}

However, I need to use this on accounts for my various clients. When I change the channelId to the ID of the other channel I get "GoogleJsonResponseException: API call to youtubeAnalytics.reports.query failed with error: Forbidden." The YouTube API doesn't have any problem, but it doesn't give me any ability to check the 30-day values, only the total values. I've looked at the OAuth2 instructions and frankly I'm lost there. Can this code be made to work for other channels? Can I get OAuth2 working for any channel? Can I get OAuth2 working for a specific set of channels if the client can do something? Or is this basically impossible?


问:
Laravel backend not notified of Soketi events
I'm using a laravel backend and i'm trying to receive events from the socket server about user joining and leaving channels ( I know about presence channels ) but I'm having a hard time with the configuration and coordination with the backend

```<code>{"url":"http://192.168.1.2:8000/chats","event_types":["pusher:subscribe","member_added","pusher_internal:subscription_succeeded"]}
</code>```

I'm using the Broadcast::channel method (callback) in laravel backend and I'm not receiving any notifications
pushing events from my backend to the client works just fine so I don't think it's the general configuration of pusher with the backend

looked through the documentation of both laravel/soketi/pusher but didn't find anything resembling this case, looked through other forums and sites but didn't find a solution
i haven't tested it with pusher.com socket server as i have some deployment issues and i do not intend on using it in production hence why i'm using soketi

Body:
I'm using a laravel backend and i'm trying to receive events from the socket server about user joining and leaving channels ( I know about presence channels ) but I'm having a hard time with the configuration and coordination with the backend

{"url":"http://192.168.1.2:8000/chats","event_types":["pusher:subscribe","member_added","pusher_internal:subscription_succeeded"]}

I'm using the Broadcast::channel method (callback) in laravel backend and I'm not receiving any notifications
pushing events from my backend to the client works just fine so I don't think it's the general configuration of pusher with the backend

looked through the documentation of both laravel/soketi/pusher but didn't find anything resembling this case, looked through other forums and sites but didn't find a solution
i haven't tested it with pusher.com socket server as i have some deployment issues and i do not intend on using it in production hence why i'm using soketi


问:
Bootstrap one modal with different buttons
I'm trying to create a modal with varying content that would lead to different URLs depending on item's ID.
I came up with this code for modal:

```<code>{% for user_expense_category in user_expense_categories %}
                        <div class="row mb-1 d-flex justify-content-between">
                            <div>{{ user_expense_category.name }}</div><div>{% if user_expense_category.monthly_limit %}
                              Limit: {{ user_expense_category.monthly_limit }}{% endif %}</div>
                            <div><button type="button" class="btn btn-dark" data-toggle="modal" data-target="#editExpense" data-id="{{ user_expense_category.id }}"
                              data-name="{{ user_expense_category.name }}" {% if user_expense_category.monthly_limit %}data-monthly_limit="{{ user_expense_category.monthly_limit }}"{% endif %}> Edytuj </button></div>
                        </div>
                    {% endfor %}
                    <div class="modal fade" id="editExpense" tabindex="-1" aria-labelledby="#editExpense" aria-hidden="true">
                      <div class="modal-dialog">
                        <div class="modal-content">
                          <div class="modal-header">
                            <h5 class="modal-title" id="editExpenseLabel">Edytuj kategorię wydatku</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                              <span aria-hidden="true">×</span>
                            </button>
                          </div>
                          <div class="modal-body">
                            <form action="/settings/id:/editExpCat" method="post">
                              <table>
                                <tr>
                                    <td><label for="name">Nazwa:</label></td>
                                    <td><input name="name" id="name" class="form-control m-1" required></td>
                                </tr>
                                <tr>
                                    <td><label for="monthly_limit">Limit miesięczny:</label></td>
                                    <td><input name="monthly_limit" type="number" id="monthly_limit" class="form-control m-1" step="0.01" min="0.01"></td>
                                </tr>
                            </table>
                            </form>
                          </div>
                          <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Anuluj</button>
                            <button type="submit" class="btn btn-primary">Zapisz</button>
                          </div>
                        </div>
                      </div>
                    </div>
</code>```

And for JS:

```<code>$('#editIncome').on('show.bs.modal', function (event) {
  const button = $(event.relatedTarget)
  const id = button.data('id')
  const name = button.data('name')
  const monthly_limit = button.data('monthly_limit')
  const modal = $(this)
  modal.find('.modal-body form').action('/settings/' + id + '/editIncCat')
  modal.find('.modal-body input name="name"').val(name)
  modal.find('.modal-body input name="monthly_limit"').val(monthly_limit)
})
</code>```

Apparantely there is no such function as modal.find('').action so my question is: How do I insert different action for the form in the modal depending on the item's ID?

I've tried code above and got an error:

```<code>Uncaught TypeError: modal.find(...).action is not a function
    at HTMLDivElement.<anonymous> (app.js:52:34)
    at HTMLDivElement.dispatch (jquery-3.6.0.min.js:2:43064)
    at v.handle (jquery-3.6.0.min.js:2:41048)
    at Object.trigger (jquery-3.6.0.min.js:2:71515)
    at HTMLDivElement.<anonymous> (jquery-3.6.0.min.js:2:72110)
    at Function.each (jquery-3.6.0.min.js:2:3003)
    at S.fn.init.each (jquery-3.6.0.min.js:2:1481)
    at S.fn.init.trigger (jquery-3.6.0.min.js:2:72086)
    at e.show (modal.js:115:22)
    at HTMLDivElement.<anonymous> (modal.js:570:14)
</code>```

Body:
I'm trying to create a modal with varying content that would lead to different URLs depending on item's ID.
I came up with this code for modal:

{% for user_expense_category in user_expense_categories %}

{{ user_expense_category.name }}

{% if user_expense_category.monthly_limit %}
                              Limit: {{ user_expense_category.monthly_limit }}{% endif %}

<button type="button" class="btn btn-dark" data-toggle="modal" data-target="#editExpense" data-id="{{ user_expense_category.id }}"
                              data-name="{{ user_expense_category.name }}" {% if user_expense_category.monthly_limit %}data-monthly_limit="{{ user_expense_category.monthly_limit }}"{% endif %}> Edytuj </button>

                    {% endfor %}

Edytuj kategorię wydatku

                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                              ×
                            </button>

                            <form action="/settings/id:/editExpCat" method="post">

                                    Nazwa:
                                    <input name="name" id="name" class="form-control m-1" required>

                                    Limit miesięczny:
                                    <input name="monthly_limit" type="number" id="monthly_limit" class="form-control m-1" step="0.01" min="0.01">

                            </form>

                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Anuluj</button>
                            <button type="submit" class="btn btn-primary">Zapisz</button>

And for JS:

$('#editIncome').on('show.bs.modal', function (event) {
  const button = $(event.relatedTarget)
  const id = button.data('id')
  const name = button.data('name')
  const monthly_limit = button.data('monthly_limit')
  const modal = $(this)
  modal.find('.modal-body form').action('/settings/' + id + '/editIncCat')
  modal.find('.modal-body input name="name"').val(name)
  modal.find('.modal-body input name="monthly_limit"').val(monthly_limit)
})

Apparantely there is no such function as modal.find('').action so my question is: How do I insert different action for the form in the modal depending on the item's ID?

I've tried code above and got an error:

Uncaught TypeError: modal.find(...).action is not a function
    at HTMLDivElement.<anonymous> (app.js:52:34)
    at HTMLDivElement.dispatch (jquery-3.6.0.min.js:2:43064)
    at v.handle (jquery-3.6.0.min.js:2:41048)
    at Object.trigger (jquery-3.6.0.min.js:2:71515)
    at HTMLDivElement.<anonymous> (jquery-3.6.0.min.js:2:72110)
    at Function.each (jquery-3.6.0.min.js:2:3003)
    at S.fn.init.each (jquery-3.6.0.min.js:2:1481)
    at S.fn.init.trigger (jquery-3.6.0.min.js:2:72086)
    at e.show (modal.js:115:22)
    at HTMLDivElement.<anonymous> (modal.js:570:14)


问:
Explanation on subroutines in C#
I have started to code in C# winforms . One problem I'm finding is learning about subroutines. In visual basic it was really easy but I'm not sure how it works in C# with public and static and void. If when a user presses a button I want to pull up a subroutine from a class would I have the subroutine as static void or public?  Also would you use public or static for variables in a class that would be used throughout multiple forms?

An example is this:

```<code>private void button1_Click(object sender, EventArgs e)
        {
            using (OleDbConnection connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\RAV21001310\\OneDrive\\Database1.accdb;"))
            {
                connection.Open();

                using (OleDbCommand command = new OleDbCommand("SELECT * FROM tblUser WHERE Username=@Username AND Password=@Password", connection))
                {
                    command.Parameters.AddWithValue("@Username", username.Text);
                    command.Parameters.AddWithValue("@Password", password.Text);
                    using (OleDbDataReader reader = command.ExecuteReader())
                    {
                        int count = 0;
                        while (reader.Read())
                        {
                            count = count + 1;
                        }

                        if (count == 1)
                        {
                            MessageBox.Show("Username and password is correct");
                        }

                        if (count > 1)
                        {
                            MessageBox.Show("Duplicate username and password");
                        }
                        if (count == 0)
                        {
                            MessageBox.Show("Username or password incorrect");
                        }
                    }
                }
                connection.Close();
            }
        }
    }

public class User
    {
        public string Username;
        public string Password;
        public string FirstName;
        public string LastName;
        public string Gender;
        public int Age;
        public int TotalPoints;
    }

</code>```

The first block of code is a login form. If I wanted to call it UserLogin() and put it in the user class would I use static or public for it or would I just rename the private void for button click and put that in the user class instead.

Title: Explanation on subroutines in C#

Body:
I have started to code in C# winforms . One problem I'm finding is learning about subroutines. In visual basic it was really easy but I'm not sure how it works in C# with public and static and void. If when a user presses a button I want to pull up a subroutine from a class would I have the subroutine as static void or public?  Also would you use public or static for variables in a class that would be used throughout multiple forms?

An example is this:

private void button1_Click(object sender, EventArgs e)
        {
            using (OleDbConnection connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\RAV21001310\\OneDrive\\Database1.accdb;"))
            {
                connection.Open();

                using (OleDbCommand command = new OleDbCommand("SELECT * FROM tblUser WHERE Username=@Username AND Password=@Password", connection))
                {
                    command.Parameters.AddWithValue("@Username", username.Text);
                    command.Parameters.AddWithValue("@Password", password.Text);
                    using (OleDbDataReader reader = command.ExecuteReader())
                    {
                        int count = 0;
                        while (reader.Read())
                        {
                            count = count + 1;
                        }

                        if (count == 1)
                        {
                            MessageBox.Show("Username and password is correct");
                        }

                        if (count > 1)
                        {
                            MessageBox.Show("Duplicate username and password");
                        }
                        if (count == 0)
                        {
                            MessageBox.Show("Username or password incorrect");
                        }
                    }
                }
                connection.Close();
            }
        }
    }

public class User
    {
        public string Username;
        public string Password;
        public string FirstName;
        public string LastName;
        public string Gender;
        public int Age;
        public int TotalPoints;
    }

The first block of code is a login form. If I wanted to call it UserLogin() and put it in the user class would I use static or public for it or would I just rename the private void for button click and put that in the user class instead.


问:
FirebaseFirestore set() not working as intended in for loop
In a page I get a List questions through constructor.

Then, I want to add all the 'documents' to a new collection, one by one using a for loop

```<code>int item = -1;
for (var i = 0; i < widget.questions.length;i+=1) {
    setState(() {
         item += 1;
    });
    print(item);

    var doc = FirebaseFirestore.instance.colletion('collectionPath').doc();
     await doc.set({
        'data'
     });
}
</code>```

I only get the document from questions[0], although on debug I get the 0,1,2 item values, one by one

Body:
In a page I get a List questions through constructor.

Then, I want to add all the 'documents' to a new collection, one by one using a for loop

int item = -1;
for (var i = 0; i < widget.questions.length;i+=1) {
    setState(() {
         item += 1;
    });
    print(item);

    var doc = FirebaseFirestore.instance.colletion('collectionPath').doc();
     await doc.set({
        'data'
     });
}

I only get the document from questions[0], although on debug I get the 0,1,2 item values, one by one


问:
How to write a Windows batch script that uses findstr to search a file for a string that contains quotes, spaces, and colon
I'm attempting to write a batch script that searches a file using findstr for the following string:

```<code>"jobType" : "upgrade_application"
</code>```

Appreciate any assistance.

I've tried several variations of the following:

```<code>findstr /C:""jobType" : "upgrade_application"" < "Filename"
</code>```
```<code>findstr /C:"""jobType"" : ""upgrade_application""" < "Filename"
</code>```

Body:
I'm attempting to write a batch script that searches a file using findstr for the following string:

"jobType" : "upgrade_application"

Appreciate any assistance.

I've tried several variations of the following:

findstr /C:""jobType" : "upgrade_application"" < "Filename"

findstr /C:"""jobType"" : ""upgrade_application""" < "Filename"


问:
How can we mock an HTTP response using Chrome Dev Tools with Selenium 4 using C#?
I can do this using Fetch commands in Java but I am not able to do it using C#. Does anyone has some sample snippet?

```<code>IDevTools devTools = driver as IDevTools;
var session = devTools.GetDevToolsSession();

var domains = session.GetVersionSpecificDomains<DevToolsSessionDomains>();

domains.Fetch.Enable(new OpenQA.Selenium.DevTools.V108.Fetch.EnableCommandSettings());
</code>```

When I try to use Fetch in C#, I don't see it accepting RequestPattern as parameter and moving forward I need to add a listener for Fetch.requestPaused. Any help in this regard would be appreciated.

Body:
I can do this using Fetch commands in Java but I am not able to do it using C#. Does anyone has some sample snippet?

IDevTools devTools = driver as IDevTools;
var session = devTools.GetDevToolsSession();

var domains = session.GetVersionSpecificDomains<DevToolsSessionDomains>();

domains.Fetch.Enable(new OpenQA.Selenium.DevTools.V108.Fetch.EnableCommandSettings());

When I try to use Fetch in C#, I don't see it accepting RequestPattern as parameter and moving forward I need to add a listener for Fetch.requestPaused. Any help in this regard would be appreciated.


问:
How to combine Access tables based on calculated fields for an Export to Excel?
In Access I have two tables:

Table 1 called Base:

ID
Prod
Area
Ref
Col

1
124
A
124A
R

2
125
B
125B
G

3
126
C
126C
B

4
127
D
127D
G

Table 2 called Full:

ID
Item
Area
Ref
Pos

1
12403
A
124A
3

2
12502
B
125B
2

3
12605
C
126C
5

4
12702
D
127D
2

In both tables, Ref column is a calculated field based on the two previous columns. In the first table, the Prod and Area columns are added to give the Ref column. In the second table, it takes the 3 first characters of the Item column, and the Area column is added to give the Ref column for each line.

The fact is both tables have more columns.

I would like to export a table to Excel, which, based on the calculated field Ref of the Full table, contains all the columns of the Full table and adds the information present in the Base table related to Ref. If it is not clear, see below the table I would like to get in Excel:

Item
Area
Ref
Pos
Col

12403
A
124A
3
R

12502
B
125B
2
G

12605
C
126C
5
B

12702
D
127D
2
G

Thank you for your help


问:
How can I properly pass request.cookies to a fetch against the api from nextjs middleware?
I try to authenticate the user against an express.js api. The problem that api calls inside the middleware don't use the cookies from the browser where I store the tokens for autherization. I have the tokens in the request object from middleware. When I try to pass them to the fetching function they arent recognized by expressjs as it supposed to be. Any ideas how to do that or why are my cookies are not recognized?

Here is my middleware.js:

the api/user/loggenin is probaly just checks the stored tokens in the cookies if they are valid and returns false or true.

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

import { NextResponse } from 'next/server'

export async function middleware(req) {

```<code>const url = req.nextUrl;

if (url.pathname.startsWith("/admin")) {

    try {

        let mytokens = req.cookies

        const isUserAuthenticated = await getAuthenticatedUser(mytokens);
        console.log(isUserAuthenticated);
        if (isUserAuthenticated.authenticated == true) {
            return NextResponse.next();
        } else {
            url.pathname = "/login";
            return NextResponse.redirect(url);
        }
    } catch(e) {
        url.pathname = "/login";
        return NextResponse.redirect(url);
    }
};
</code>```

return NextResponse.next();

}

async function getAuthenticatedUser(tokens) {
const defaultReturnObject = {authenticated: false};

```<code>console.log(tokens)
try {
  const response = await fetch("http://localhost:5000/api/user/loggedin", {
        method: 'POST',
        withCredentials: true,
        headers : {
            'Content-Type': 'application/json',
            tokens
        }
    })
    const data = await response.json();

    return(data);

} catch (err) {
  return defaultReturnObject;
}
</code>```

}

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

Body:
I try to authenticate the user against an express.js api. The problem that api calls inside the middleware don't use the cookies from the browser where I store the tokens for autherization. I have the tokens in the request object from middleware. When I try to pass them to the fetching function they arent recognized by expressjs as it supposed to be. Any ideas how to do that or why are my cookies are not recognized?

Here is my middleware.js:

the api/user/loggenin is probaly just checks the stored tokens in the cookies if they are valid and returns false or true.

import { NextResponse } from 'next/server'

export async function middleware(req) {

const url = req.nextUrl;

if (url.pathname.startsWith("/admin")) {

    try {

        let mytokens = req.cookies

        const isUserAuthenticated = await getAuthenticatedUser(mytokens);
        console.log(isUserAuthenticated);
        if (isUserAuthenticated.authenticated == true) {
            return NextResponse.next();
        } else {
            url.pathname = "/login";
            return NextResponse.redirect(url);
        }
    } catch(e) {
        url.pathname = "/login";
        return NextResponse.redirect(url);
    }
};

return NextResponse.next();

}

async function getAuthenticatedUser(tokens) {
const defaultReturnObject = {authenticated: false};

console.log(tokens)
try {
  const response = await fetch("http://localhost:5000/api/user/loggedin", {
        method: 'POST',
        withCredentials: true,
        headers : {
            'Content-Type': 'application/json',
            tokens
        }
    })
    const data = await response.json();

    return(data);

} catch (err) {
  return defaultReturnObject;
}

}


问:
NotSerializableException when attempting to read objects from .dat file
I'm attempting to write objects to a dat file, but whenever I try to read the objects I get a NotSerializableException. The code works fine if I comment out the part where I read it and leave the part where I write to it. I double checked my code to see if I had any static members or if I forgot to implement serialization, as those seem to be the most common causes for this error, but as far as I can tell those bases are covered.

```<code>import java.io.Serializable;

public class ClsA implements Serializable, Cloneable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    //^I just put these into the code to satisfy a warning java gave. I don't know what these do, and I'm assuming it has something to do with the error, but I don't know for sure. Either way it seems to work the same with or without them here
    private int value;
    private String key;

    public ClsA() {

    }
    public ClsA(int value, String key) {
        this.value = value;
        this.key = key;
    }
    public void setValue(int value) {
        this.value = value;
    }
    public int getValue() {
        return this.value;
    }
    public String getKey() {
        return this.key;
    }
    public void setKey(String key) {
        this.key = key;
    }
    public String toString() {
        return "Value: " + value + " Key: " + key;
    }
    public boolean equals(Object obj) {
        boolean equals = true;
        if(!(this.key.equals(((ClsA) obj).key)) || !(this.value == ((ClsA) obj).value)) {
            equals = false;
        }
        return equals;
    }
}

</code>```
```<code>import java.io.Serializable;
import java.util.ArrayList;

public class ClsB implements Cloneable,Serializable{

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private ArrayList<ClsA> bag;

    public ClsB() {
        bag = new ArrayList<>();
    }
    public ClsB(ArrayList<ClsA> bag) {
        this.bag = bag;
    }

    public boolean addToBag(ClsA obj) {
        boolean added = true;
        for(int i = 0; i < this.bag.size(); i++) {
            if(this.bag.get(i).equals(obj)) {
                added = false;
                return added;
            }
        }
        this.bag.add(obj);
        return added;
    }

    public boolean removeFromBag(ClsA obj) {
        boolean removed = false;
        for(int i = 0; i < this.bag.size(); i++) {
            if(this.bag.get(i).equals(obj)) {
                this.bag.remove(i);
            }
        }
        return removed;
    }

    public int find(ClsA obj) {
        int idx = -1;
        for(int i = 0; i < this.bag.size(); i++) {
            if(this.bag.get(i).equals(obj)) {
                idx = i;
                return idx;
            }
        }
        return idx;
    }

    public ArrayList<ClsA> display(){
        return this.bag;
    }

    public boolean equals(ClsB obj) {
        boolean equals = true;
        if(this.bag.size()!=(obj.bag.size())) {
            equals = false;
            return equals;
        }
        for(int i = 0; i < this.bag.size(); i++) {
            if(!(this.bag.get(i).equals(obj.bag.get(i)))) {
                equals = false;
                return equals;
            }
        }
        return equals;
    }
    public Object clone() throws CloneNotSupportedException {
        try {
        return (ClsB)super.clone();
        } catch(CloneNotSupportedException e){
            return new ClsB(this.bag);
        }
    }

}

</code>```
```<code>import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Test {

    public static void main(String[] args) throws Exception {
        ClsB bag = new ClsB();
        ClsA obj1 = new ClsA(5,"key1");
        ClsA obj2 = new ClsA(6,"key2");
        ClsA obj3 = new ClsA(7,"key3");

        bag.addToBag(obj1);
        bag.addToBag(obj2);
        bag.addToBag(obj1);
        bag.addToBag(obj3);
        System.out.println(bag.display());
        System.out.println(bag.display());
        System.out.println(bag.find(obj1));
        File file = new File("File.dat");

        ClsB bag2 = (ClsB)bag.clone();

        if(!(file.exists())){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try(ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(
                new FileOutputStream(file,true)));){
            ClsB newBag = new ClsB();
            newBag = bag;
            oos.writeObject(newBag);
            oos.close();
        }
        catch(IOException ioe) {
            ioe.printStackTrace();

        }
        catch(Exception ie) {

        }
        ReadObjectFromFile(file);
    }
        public static void ReadObjectFromFile(File file) throws Exception {
            FileInputStream fiis = new FileInputStream(file);
            InputStream fis = new FilterInputStream(fiis) {
                @Override
                public void close() throws IOException {

                }
            };
            try {
                while (true) {
                    ObjectInputStream in = new ObjectInputStream(fis);
                    ClsB newBag = (ClsB) in.readObject();
                    System.out.println(newBag.display());
                    in.close();
                }
            } catch (EOFException ex) {

            }
            fiis.close();
    }
}

</code>```

And here is the error I got:

```<code>Exception in thread "main" java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: ClsB
    at java.base/java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1775)
    at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:543)
    at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:501)
    at Test.ReadObjectFromFile(Test.java:73)
    at Test.main(Test.java:60)
Caused by: java.io.NotSerializableException: ClsB
    at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1202)
    at java.base/java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:362)
    at Test.main(Test.java:54)
</code>```

Body:
I'm attempting to write objects to a dat file, but whenever I try to read the objects I get a NotSerializableException. The code works fine if I comment out the part where I read it and leave the part where I write to it. I double checked my code to see if I had any static members or if I forgot to implement serialization, as those seem to be the most common causes for this error, but as far as I can tell those bases are covered.

import java.io.Serializable;

public class ClsA implements Serializable, Cloneable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    //^I just put these into the code to satisfy a warning java gave. I don't know what these do, and I'm assuming it has something to do with the error, but I don't know for sure. Either way it seems to work the same with or without them here
    private int value;
    private String key;

    public ClsA() {

    }
    public ClsA(int value, String key) {
        this.value = value;
        this.key = key;
    }
    public void setValue(int value) {
        this.value = value;
    }
    public int getValue() {
        return this.value;
    }
    public String getKey() {
        return this.key;
    }
    public void setKey(String key) {
        this.key = key;
    }
    public String toString() {
        return "Value: " + value + " Key: " + key;
    }
    public boolean equals(Object obj) {
        boolean equals = true;
        if(!(this.key.equals(((ClsA) obj).key)) || !(this.value == ((ClsA) obj).value)) {
            equals = false;
        }
        return equals;
    }
}

import java.io.Serializable;
import java.util.ArrayList;

public class ClsB implements Cloneable,Serializable{

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private ArrayList<ClsA> bag;

    public ClsB() {
        bag = new ArrayList<>();
    }
    public ClsB(ArrayList<ClsA> bag) {
        this.bag = bag;
    }

    public boolean addToBag(ClsA obj) {
        boolean added = true;
        for(int i = 0; i < this.bag.size(); i++) {
            if(this.bag.get(i).equals(obj)) {
                added = false;
                return added;
            }
        }
        this.bag.add(obj);
        return added;
    }

    public boolean removeFromBag(ClsA obj) {
        boolean removed = false;
        for(int i = 0; i < this.bag.size(); i++) {
            if(this.bag.get(i).equals(obj)) {
                this.bag.remove(i);
            }
        }
        return removed;
    }

    public int find(ClsA obj) {
        int idx = -1;
        for(int i = 0; i < this.bag.size(); i++) {
            if(this.bag.get(i).equals(obj)) {
                idx = i;
                return idx;
            }
        }
        return idx;
    }

    public ArrayList<ClsA> display(){
        return this.bag;
    }

    public boolean equals(ClsB obj) {
        boolean equals = true;
        if(this.bag.size()!=(obj.bag.size())) {
            equals = false;
            return equals;
        }
        for(int i = 0; i < this.bag.size(); i++) {
            if(!(this.bag.get(i).equals(obj.bag.get(i)))) {
                equals = false;
                return equals;
            }
        }
        return equals;
    }
    public Object clone() throws CloneNotSupportedException {
        try {
        return (ClsB)super.clone();
        } catch(CloneNotSupportedException e){
            return new ClsB(this.bag);
        }
    }

}

import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Test {

    public static void main(String[] args) throws Exception {
        ClsB bag = new ClsB();
        ClsA obj1 = new ClsA(5,"key1");
        ClsA obj2 = new ClsA(6,"key2");
        ClsA obj3 = new ClsA(7,"key3");

        bag.addToBag(obj1);
        bag.addToBag(obj2);
        bag.addToBag(obj1);
        bag.addToBag(obj3);
        System.out.println(bag.display());
        System.out.println(bag.display());
        System.out.println(bag.find(obj1));
        File file = new File("File.dat");

        ClsB bag2 = (ClsB)bag.clone();

        if(!(file.exists())){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try(ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(
                new FileOutputStream(file,true)));){
            ClsB newBag = new ClsB();
            newBag = bag;
            oos.writeObject(newBag);
            oos.close();
        }
        catch(IOException ioe) {
            ioe.printStackTrace();

        }
        catch(Exception ie) {

        }
        ReadObjectFromFile(file);
    }
        public static void ReadObjectFromFile(File file) throws Exception {
            FileInputStream fiis = new FileInputStream(file);
            InputStream fis = new FilterInputStream(fiis) {
                @Override
                public void close() throws IOException {

                }
            };
            try {
                while (true) {
                    ObjectInputStream in = new ObjectInputStream(fis);
                    ClsB newBag = (ClsB) in.readObject();
                    System.out.println(newBag.display());
                    in.close();
                }
            } catch (EOFException ex) {

            }
            fiis.close();
    }
}

And here is the error I got:

Exception in thread "main" java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: ClsB
    at java.base/java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1775)
    at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:543)
    at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:501)
    at Test.ReadObjectFromFile(Test.java:73)
    at Test.main(Test.java:60)
Caused by: java.io.NotSerializableException: ClsB
    at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1202)
    at java.base/java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:362)
    at Test.main(Test.java:54)


问:
C# WebView2 - Is there a way to enable an element picker without the dev tools?
I wish to provide a user with the ability to turn on an element-picker style interaction like what's in devtools, without enabling the whole devtools system. The sole function I'd like the user to be able to do is hover their mouse over a particular element, see the highlighting system, and click the exact element they're interested in.

Once they have clicked on an element I wish to have that information returned back to the C# code so I can save that element's details somewhere.

Thank you.

I have used WebView2's DevTools window through the use of
wv.CoreWebView2.OpenDevToolsWindow();
this appears to open DevTools in a completely separate window (with Edge's element picker support) but I would like to avoid that.


问:
Fetch by custom product Name in API Url NEXTJS & MongoDB
How can I fetch my products by name like "api/product/NAME" in NextJS(SSR)? Sounds easy, but what if someone creates a product called "Samsung 29" ? Its not unique, so anybody can post a product with the same name like Amazon or a real ecommerce. I was using findById in MongoDB but the client link turns into "www.myapp.com/product/3249827398479" because of the query: [ID] asked from the API (api/product/[3249827398479]) and I dont like it.

How can I fetch products with the product name? I want "www.myapp.com/product/samsung-29"
Or how is this done in real apps?

I hope I made myself clear.


问:
How do you use named routes in Vue 3 <router-link> (when using "vite-plugin-pages") to pass an optional Object Prop?

EDIT: Just realized this is an anti-pattern, so I will be looking into alternative methods of solving this, probably by using pinia to store the Object that is bing passed.

https://github.com/vuejs/router/blob/main/packages/router/CHANGELOG.md#414-2022-08-22

Vue 3 Project Setup:

Note: This project is also using unplugin-vue-components and unplugin-auto-import which is why the imports are not present in some files.

src/main.ts

import { createApp } from "vue";
import { createRouter, createWebHashHistory } from "vue-router";
import App from "./App.vue";
import routes from "~pages";

// router
const router = createRouter({
  history: createWebHashHistory(),
  routes,
  linkActiveClass: "active",
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) return savedPosition;
    return { top: 0 };
  },
});

const app = createApp(App);
app.use(router);
app.mount("#app");
```
<h3><code>App.vue</code></h3>
<pre class="lang-html prettyprint-override"><code><script setup lang="ts"></script>

<template>
  <div id="viewport">
    <RouterView />
  </div>
</template>
</code>```

src/pages/examples/index.vue

Accessible through http://localhost:8080/#/examples

<template>

      <router-link
        v-for="e in examples.value"
        :key="e.id"
        v-slot="{ navigate }"
        :to="{
          path: `/examples/${e.id}`,
          params: { example: e },
        }"
        custom
      >

            {{ e.id }}

      </router-link>

</template>
```
<h3><code>src/pages/examples/[id].vue</code></h3>
<ul>
<li>Accessible through <code>http://localhost:8080/#/examples/1</code></li>
</ul>
<pre class="lang-html prettyprint-override"><code><script setup lang="ts">
import { ref, inject, onMounted } from "vue";

interface Props {
  id: number;
  name: string | undefined;
}

const props = defineProps<Props>();
</script>

<template>
  <div>
    {{ props.id }}
    </br>
    {{ props?.name }}
  </div>
</template>
</code>```

So far what I have here ^ works. But I get this error (and the optional Prop e is not passed to [id].vue):

```<code>[Vue Router warn]: Path "/examples/1" was passed with params but they will be ignored. Use a named route alongside params instead.
</code>```

from vue-router.mjs

Body:
EDIT: Just realized this is an anti-pattern, so I will be looking into alternative methods of solving this, probably by using pinia to store the Object that is bing passed.

https://github.com/vuejs/router/blob/main/packages/router/CHANGELOG.md#414-2022-08-22

Vue 3 Project Setup:

Note: This project is also using unplugin-vue-components and unplugin-auto-import which is why the imports are not present in some files.

src/main.ts

import { createApp } from "vue";
import { createRouter, createWebHashHistory } from "vue-router";
import App from "./App.vue";
import routes from "~pages";

// router
const router = createRouter({
  history: createWebHashHistory(),
  routes,
  linkActiveClass: "active",
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) return savedPosition;
    return { top: 0 };
  },
});

const app = createApp(App);
app.use(router);
app.mount("#app");

App.vue

<template>

    <RouterView />

</template>

src/pages/examples/index.vue

Accessible through http://localhost:8080/#/examples

<template>

      <router-link
        v-for="e in examples.value"
        :key="e.id"
        v-slot="{ navigate }"
        :to="{
          path: `/examples/${e.id}`,
          params: { example: e },
        }"
        custom
      >

            {{ e.id }}

      </router-link>

</template>

src/pages/examples/[id].vue

Accessible through http://localhost:8080/#/examples/1

<template>

    {{ props.id }}

    {{ props?.name }}

</template>

So far what I have here ^ works. But I get this error (and the optional Prop e is not passed to [id].vue):

[Vue Router warn]: Path "/examples/1" was passed with params but they will be ignored. Use a named route alongside params instead.

from vue-router.mjs


问:
AWS Restore Prod RDS Snapshot in Dev Issue
I want to share Prod RDS snapshot to Dev.. no problem
Address encryption.. no problem

Dev has nested Stack, App & RDS

Problem;
I can’t deploy the Prod snapshot in Dev because it’s going to want to create a new RDS instance ..
I just want the Prod RDS data deployed in the Dev one .. identical application.

I have some ideas but wanted to see what the community had to offer

Thanks

Tried to deploy via CFN the snapshot in Dev but it failed since there’s a running instances already


问:
Php session always timeout on CPanel
I have a website hosted on CPanel (HostGator) written in PHP. I want my session to stay alive. For now, it seems to be cleared after about one hour. I have tried to set session.gc_probability = 0; in php.ini and just to make sure, I also do ini_set('session.gc_probability', 0); before starting my session. But still, the session gets cleared after about one hour, and there are no errors in error_log. I also tried to set a huge session.gc_maxlifetime and it also does not change the time before the session gets cleared.

I can see on CPanel on the module MultiPHP INI Editor that my settings are well set. I don't understand why the session gets always cleared after about one hour. Should I try to delete the sessions files on the filesystem?

Title: Php session always timeout on CPanel


问:
R shiny – renderExplorer output within different tabPanels of navbarPage
I’m building an R Shiny app in which I would like to render explorer() output from the datadigest package to separate tabPanels within navbarPage. However, when I try to render one explorer() object to one tabPanel and another explorer() object to a different tabPanel, the results of each object render within the same tabPanel instead. Below is a small reproducible example.

When I first view the “Assessments Tables” tab, it contains only assessments tables. Nothing is in the “Scores Tables” tab except for “here is some text” (this text is expected). Clicking back to the “Assessments Tables” tab reveals that now scores tables have been appended to the bottom of the list.

To be clear, what I need is for the Assessments Tables tab to contain assessments tables (assesstab), and for the Scores Tables tab to contain scores tables (scoretab).

Maybe this is a versioning issue, so I'm including version info here:

R version 4.2.1 (2022-06-23 ucrt);
Platform: x86_64-w64-mingw32/x64 (64-bit);
Running under: Windows 10 x64 (build 19044);
shiny_1.7.2;
datadigest_1.0.2;
RStudio Version 1.4.1717

```<code>library(datadigest)
library(shiny)

assesslist <- list("mtcars"=mtcars, "beaver"=beaver1, "co2"=co2)
assesstab <- explorer(assesslist, addEnv = FALSE)

scorelist <- list("BOD"=BOD, "ChickWeight"=ChickWeight)
scoretab <- explorer(scorelist, addEnv = FALSE)

# UI with navigation bar
ui <- navbarPage("Data Digest",
                 tabPanel("Assessments Tables",
                          explorerOutput("assessout")
                 ),
                 tabPanel("Scores Tables",
                          h1("here is some text"),
                          explorerOutput("scoreout")
                 )
)

# server side
server <- function(input, output, session) {

  output$assessout <- renderExplorer({assesstab})
  output$scoreout <- renderExplorer({scoretab})

}

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

Body:
I’m building an R Shiny app in which I would like to render explorer() output from the datadigest package to separate tabPanels within navbarPage. However, when I try to render one explorer() object to one tabPanel and another explorer() object to a different tabPanel, the results of each object render within the same tabPanel instead. Below is a small reproducible example.

When I first view the “Assessments Tables” tab, it contains only assessments tables. Nothing is in the “Scores Tables” tab except for “here is some text” (this text is expected). Clicking back to the “Assessments Tables” tab reveals that now scores tables have been appended to the bottom of the list.

To be clear, what I need is for the Assessments Tables tab to contain assessments tables (assesstab), and for the Scores Tables tab to contain scores tables (scoretab).

Maybe this is a versioning issue, so I'm including version info here:

R version 4.2.1 (2022-06-23 ucrt);
Platform: x86_64-w64-mingw32/x64 (64-bit);
Running under: Windows 10 x64 (build 19044);
shiny_1.7.2;
datadigest_1.0.2;
RStudio Version 1.4.1717

library(datadigest)
library(shiny)

assesslist <- list("mtcars"=mtcars, "beaver"=beaver1, "co2"=co2)
assesstab <- explorer(assesslist, addEnv = FALSE)

scorelist <- list("BOD"=BOD, "ChickWeight"=ChickWeight)
scoretab <- explorer(scorelist, addEnv = FALSE)

# UI with navigation bar
ui <- navbarPage("Data Digest",
                 tabPanel("Assessments Tables",
                          explorerOutput("assessout")
                 ),
                 tabPanel("Scores Tables",
                          h1("here is some text"),
                          explorerOutput("scoreout")
                 )
)

# server side
server <- function(input, output, session) {

  output$assessout <- renderExplorer({assesstab})
  output$scoreout <- renderExplorer({scoretab})

}

shinyApp(ui, server)


问:
@MockBean with JUnit meta annotation for Spring Boot Test - a bug or a feature? ;-)
I have a Spring Boot test like this:

@SpringBootTest
class VendorApiTest {

  @MockBean
  VendorService service;

  // ... further @Autowired fields and test methods

}
```
<p>and I'd like to make this context configuration re-usable. I guess the recommended way would be to create a super class. But this is not my favourite.</p>
<p>Instead, I define a custom JUnit meta annotation, like this:</p>
<pre class="lang-java prettyprint-override"><code>@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@SpringBootTest
@Import(GarageApiTest.MockDomainConfiguration.class)
// further settings: Profiles, Tags, ...
public @interface GarageApiTest {

    @TestConfiguration
    class MockDomainConfiguration {

        @MockBean
        VendorService vendorService;

    }

}
</code>```

And I just use it this way and can get the mock by a simple @Autowired:

@GarageApiTest
class VendorApiTest {

  @Autowired
  VendorService service;

  // ... further @Autowired fields and test methods

}
```
<p>This works fine, but is this intended to do so?</p>
<p>I have found out, that, in case of removing the <code>@TestConfiguration</code>, the mock is injected into the configuration class, but not registered to the Spring context, so injection into the test instance fails. BUT instead of using <code>@TestConfiguration</code>, it also works when providing a bean definition for the mock in the configuration, like this:</p>
<pre class="lang-java prettyprint-override"><code>public @interface GarageApiTest {

    class MockDomainConfiguration {

        @MockBean
        @Getter(onMethod_ = @Bean(name = "vendorServiceMock"))
        VendorService vendorService;

    }

}
</code>```

Any opinions about that? Best Practice or Bad Practice?

Body:
I have a Spring Boot test like this:

@SpringBootTest
class VendorApiTest {

  @MockBean
  VendorService service;

  // ... further @Autowired fields and test methods

}

and I'd like to make this context configuration re-usable. I guess the recommended way would be to create a super class. But this is not my favourite.

Instead, I define a custom JUnit meta annotation, like this:

@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@SpringBootTest
@Import(GarageApiTest.MockDomainConfiguration.class)
// further settings: Profiles, Tags, ...
public @interface GarageApiTest {

    @TestConfiguration
    class MockDomainConfiguration {

        @MockBean
        VendorService vendorService;

    }

}

And I just use it this way and can get the mock by a simple @Autowired:

@GarageApiTest
class VendorApiTest {

  @Autowired
  VendorService service;

  // ... further @Autowired fields and test methods

}

This works fine, but is this intended to do so?

I have found out, that, in case of removing the @TestConfiguration, the mock is injected into the configuration class, but not registered to the Spring context, so injection into the test instance fails. BUT instead of using @TestConfiguration, it also works when providing a bean definition for the mock in the configuration, like this:

public @interface GarageApiTest {

    class MockDomainConfiguration {

        @MockBean
        @Getter(onMethod_ = @Bean(name = "vendorServiceMock"))
        VendorService vendorService;

    }

}

Any opinions about that? Best Practice or Bad Practice?


问:
Having issues with adding an image from url to a pdf using jspdf and autotable
I am creating a pdf from data on my react web app using jspdf and the autotable plugin. The table on my webpage is made with mui's table components and I use the data in an array to create the pdf very handily with the autotable plugin.

The issue I am having is when I try to add images to the pdf using jspdf.addImage() it fails. The images load fine on the webpage in  tags. All the images are loaded from external urls. I have tried adding the images in many different ways that I will try to detail below but all of them are done in the didDrawCell handler property of the autoTable method call. To summarize:

Can some one tell me how to get an image from an external url to work something like this:

```<code>const pdf = new jsPDF({ unit: "mm", orientation: "l" });
autoTable(pdf, {
  head: [headers],
  body: data.map((i) => [
    ... //all my different column data
  ]),
  didDrawCell: (cellData) => {
    if (cellData.section === "body" && cellData.column.index === 0) {
      const url = "https://www.someimagesite.com/someimage.jpg"
      const dim = cellData.cell.height - cellData.cell.padding("vertical");
      const textPos = cellData.cell.getTextPos();
      pdf.addImage(url, textPos.x, textPos.y, dim, dim);
    }
  },
});
pdf.output("dataurlnewwindow");
</code>```

Thank you in advance for the help!

Here are some things I've tried:

I have tried using the plain url in the method call:

pdf.addImage("https://www.somewebsitewithanImage.com/theimage.jpg", "JPEG", x, y, w, h)

This give back a cors error. It complains that the cors header is missing but this should be no-cors since it is an image.

---

I've tried creating a image element like this:

```<code>
...
didDrawCell: (cellData) => {
  if (cellData.section === "body" && cellData.column.index === 0) {
    const url = data[cellData.row.index].pic; //the external url
    const textPos = cellData.cell.getTextPos();
    const img = new Image(),
      canvas = document.createElement("canvas"),
      ctx = canvas.getContext("2d");
    img.crossOrigin = "anonymous";
    img.onload = function () {
      ctx?.drawImage(img, 0, 0);
      const imgData = canvas.toDataURL("image/jpeg");
      pdf.addImage(imgData, "JPEG", textPos.x, textPos.y, 109, 142);
    };
    img.src = url;
  }
},

...
</code>```

This also fails complaining about cors:
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Unless I take away the crossOrigin line of code and then it gives me this:

```<code>Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
    at img.onload
</code>```

---

I've tried making a fetch call for the image and transforming the blob response into something that the addImage method can ingest. This really encapsulate a lot of different things I tried but in general the code looked like this:

```<code>
...

didDrawCell: (cellData) => {
   if (cellData.section === "body" && cellData.column.index === 0) { //adds it to the first column
     const url = data[cellData.row.index].pic; //the external url
     const dim = cellData.cell.height - cellData.cell.padding("vertical");
     const textPos = cellData.cell.getTextPos();

     fetch(url, { mode: "no-cors" })
       .then((response) => response.blob())
       .then((blob) => {

           // convert the blob into something usable here.

         pdf.addImage(
             img,//whatever I get back from above code
             "JPEG",
             textPos.x,
             textPos.y,
             dim,
             dim
         );
       });

}
},

...
</code>```

I've tried converting the blob to a dataUrl by drawing it to a canvas.

I've tried using the blob data to create an image element which I give to the addImage()

I've tried doing a couple different combinations of the above (I've started to lose track)

All the above methods don't explicitly fail but don't add the image to the pdf. ¯\_(ツ)_/¯

I have also tried adding refs to all of the image tags and using refs to get them into the pdf but this started getting really messy as the table is auto generated from data from an api and not static images on a page.

Body:
I am creating a pdf from data on my react web app using jspdf and the autotable plugin. The table on my webpage is made with mui's table components and I use the data in an array to create the pdf very handily with the autotable plugin.

The issue I am having is when I try to add images to the pdf using jspdf.addImage() it fails. The images load fine on the webpage in  tags. All the images are loaded from external urls. I have tried adding the images in many different ways that I will try to detail below but all of them are done in the didDrawCell handler property of the autoTable method call. To summarize:

Can some one tell me how to get an image from an external url to work something like this:

const pdf = new jsPDF({ unit: "mm", orientation: "l" });
autoTable(pdf, {
  head: [headers],
  body: data.map((i) => [
    ... //all my different column data
  ]),
  didDrawCell: (cellData) => {
    if (cellData.section === "body" && cellData.column.index === 0) {
      const url = "https://www.someimagesite.com/someimage.jpg"
      const dim = cellData.cell.height - cellData.cell.padding("vertical");
      const textPos = cellData.cell.getTextPos();
      pdf.addImage(url, textPos.x, textPos.y, dim, dim);
    }
  },
});
pdf.output("dataurlnewwindow");

Thank you in advance for the help!

Here are some things I've tried:

I have tried using the plain url in the method call:

pdf.addImage("https://www.somewebsitewithanImage.com/theimage.jpg", "JPEG", x, y, w, h)

This give back a cors error. It complains that the cors header is missing but this should be no-cors since it is an image.

---

I've tried creating a image element like this:

...
didDrawCell: (cellData) => {
  if (cellData.section === "body" && cellData.column.index === 0) {
    const url = data[cellData.row.index].pic; //the external url
    const textPos = cellData.cell.getTextPos();
    const img = new Image(),
      canvas = document.createElement("canvas"),
      ctx = canvas.getContext("2d");
    img.crossOrigin = "anonymous";
    img.onload = function () {
      ctx?.drawImage(img, 0, 0);
      const imgData = canvas.toDataURL("image/jpeg");
      pdf.addImage(imgData, "JPEG", textPos.x, textPos.y, 109, 142);
    };
    img.src = url;
  }
},

...

This also fails complaining about cors:
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Unless I take away the crossOrigin line of code and then it gives me this:

Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
    at img.onload

---

I've tried making a fetch call for the image and transforming the blob response into something that the addImage method can ingest. This really encapsulate a lot of different things I tried but in general the code looked like this:

...

didDrawCell: (cellData) => {
   if (cellData.section === "body" && cellData.column.index === 0) { //adds it to the first column
     const url = data[cellData.row.index].pic; //the external url
     const dim = cellData.cell.height - cellData.cell.padding("vertical");
     const textPos = cellData.cell.getTextPos();

     fetch(url, { mode: "no-cors" })
       .then((response) => response.blob())
       .then((blob) => {

           // convert the blob into something usable here.

         pdf.addImage(
             img,//whatever I get back from above code
             "JPEG",
             textPos.x,
             textPos.y,
             dim,
             dim
         );
       });

}
},

...

I've tried converting the blob to a dataUrl by drawing it to a canvas.

I've tried using the blob data to create an image element which I give to the addImage()

I've tried doing a couple different combinations of the above (I've started to lose track)

All the above methods don't explicitly fail but don't add the image to the pdf. ¯\_(ツ)_/¯

I have also tried adding refs to all of the image tags and using refs to get them into the pdf but this started getting really messy as the table is auto generated from data from an api and not static images on a page.


问:
Python - How to get the timings of the individual sounds a voice makes in an audio file? (For lip syncing.)
This is my first StackOverflow post, and I'm not very good at python, so I apologize if I get confused about anything...

I want to make a mod for a game that imports lip syncing to a face it has, but to do that I need to figure out the timings of the different sounds in the 1000+ voicelines. (The game is called "Will You Snail" by the way, it's a great game.) I'm wondering if I can do this in a python script, and if so, how? I am an amatuer at python so I'm crossing my fingers it's something I'll be able to do with the help of an existing library. I just want to know if it's possible to do with a library and if so how hard is it.

So basically I would need to know
A) What sounds the voice made
B) What time in the audio file it started and stopped each individual sound

Thanks!

EDIT: Somebody asked me to narrow down what the problem is, so here goes:
I'm wondering if there's a python library out there that can take an audio file with someone speaking and output a list of the times each human sound started and stopped. A human sound could be things like "aah, ee, ooh, oo, ph, sh, ch," etc. Basically the basic noises we use to talk. I also need to know WHAT sound was made along with when.


问:
Why does the ld terminate with exit code -1?
I have installed MinGW through MSYS2 and it worked fine until recently.
Lately on all of my compilations it gives me this message:

```<code> *  Executing task: C/C++: g++.exe build active file

Starting build...

C:\msys64\mingw64\bin\g++.exe -fdiagnostics-color=always -g C:\Users\*USER*\Documents\GitHub\Repo\ProgettoLista\ListaOggetti.cpp -o C:\Users\*USER*\Documents\GitHub\Repo\ProgettoLista\ListaOggetti.exe
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\*USER*\AppData\Local\Temp\ccHqtMdU.o: in function `main':
C:\Users\*USER*\Documents\GitHub\Repo\ProgettoLista/ListaOggetti.cpp:10: undefined reference to `Persona::setNome()'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\*USER*\AppData\Local\Temp\ccHqtMdU.o: in function `nodo::nodo()':
C:\Users\*USER*\Documents\GitHub\Repo\ProgettoLista/lista.h:14: undefined reference to `Persona::Persona()'

collect2.exe: error: ld returned 1 exit status

Build finished with error(s).

 *  The terminal process terminated with exit code: -1.
 *  Terminal will be reused by tasks, press any key to close it.
</code>```

I have numerous times uninstalled MinGW and MSYS2 and the result is the same.

I have tried a Hello World and it works, but on most if not all cases it gives me the same error.

For instance, the code I am trying to compile is on three files.

Main

```<code>#include <iostream>
#include "lista.h"

int main() {
    lista testa = NULL;
    lista nuovoNodo = NULL;
    nuovoNodo = new nodo;
    testa = nuovoNodo;
    nuovoNodo->prev = NULL;
    nuovoNodo->nome.setNome();
    nuovoNodo->next = NULL;

    return 0;
}
</code>```

Header

```<code>#include <iostream>

using namespace std;

class Persona {
    public:
        Persona();
        string getNome();
        void setNome();
    private:
        string nome;
};

typedef struct nodo {
    struct nodo* prev;
    Persona nome;
    struct nodo* next;
} nodo;

typedef nodo* lista;
</code>```

CD

```<code>#include <iostream>
#include "lista.h"

Persona::Persona() {
    nome = "a";
}

string Persona::getNome() {
    return this->nome;
}

void Persona::setNome() {
    cout<<"Inserisci il nome della persona: ";
    cin>>this->nome;
}
</code>```

I have tried compiling from Visual Studio, Visual Studio Code, MSYS2 console, dev c++ and they all give the same results.

The only exception is onlinegdb, which leads me to believe my problem is local.

Body:
I have installed MinGW through MSYS2 and it worked fine until recently.
Lately on all of my compilations it gives me this message:

 *  Executing task: C/C++: g++.exe build active file

Starting build...

C:\msys64\mingw64\bin\g++.exe -fdiagnostics-color=always -g C:\Users\*USER*\Documents\GitHub\Repo\ProgettoLista\ListaOggetti.cpp -o C:\Users\*USER*\Documents\GitHub\Repo\ProgettoLista\ListaOggetti.exe
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\*USER*\AppData\Local\Temp\ccHqtMdU.o: in function `main':
C:\Users\*USER*\Documents\GitHub\Repo\ProgettoLista/ListaOggetti.cpp:10: undefined reference to `Persona::setNome()'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\*USER*\AppData\Local\Temp\ccHqtMdU.o: in function `nodo::nodo()':
C:\Users\*USER*\Documents\GitHub\Repo\ProgettoLista/lista.h:14: undefined reference to `Persona::Persona()'

collect2.exe: error: ld returned 1 exit status

Build finished with error(s).

 *  The terminal process terminated with exit code: -1.
 *  Terminal will be reused by tasks, press any key to close it.

I have numerous times uninstalled MinGW and MSYS2 and the result is the same.

I have tried a Hello World and it works, but on most if not all cases it gives me the same error.

For instance, the code I am trying to compile is on three files.

Main

#include <iostream>
#include "lista.h"

int main() {
    lista testa = NULL;
    lista nuovoNodo = NULL;
    nuovoNodo = new nodo;
    testa = nuovoNodo;
    nuovoNodo->prev = NULL;
    nuovoNodo->nome.setNome();
    nuovoNodo->next = NULL;

    return 0;
}

Header

#include <iostream>

using namespace std;

class Persona {
    public:
        Persona();
        string getNome();
        void setNome();
    private:
        string nome;
};

typedef struct nodo {
    struct nodo* prev;
    Persona nome;
    struct nodo* next;
} nodo;

typedef nodo* lista;

CD

#include <iostream>
#include "lista.h"

Persona::Persona() {
    nome = "a";
}

string Persona::getNome() {
    return this->nome;
}

void Persona::setNome() {
    cout<<"Inserisci il nome della persona: ";
    cin>>this->nome;
}

I have tried compiling from Visual Studio, Visual Studio Code, MSYS2 console, dev c++ and they all give the same results.

The only exception is onlinegdb, which leads me to believe my problem is local.