问:
How can I make react-table v7 multisort on two columns
I'm using react-table v7.8.0 to create a table with 4 columns. I'd like the the table to be sorted by columns date and views. My problem is that the table is only being sorted by the date column.

I have some pagination and manual sorting that appears to be working as expected. I think I've followed the documentation and I'm unsure where my mistake is.

The data is configured in the following file before being passed to a table component:

ViewsPageDayTable.js:

const postDateTemplate = { year: "numeric", month: "short", day: "numeric" }

import Link from "@/components/Link"
import { useMemo } from "react"

import siteMetadata from "@/data/siteMetadata"

import Table from "@/components/homeBrewAnalytics/table"
import LocationCountItem from "@/components/homeBrewAnalytics/locationCountItem"

export default function ViewsPageDayTable({ data }) {
  const parsedData = []
  for (var i = 0; i < data.length; i++) {
    const dataRow = {}
    for (var j in data[i]) {
      if (j === "date") {
        var date = new Date(data[i][j])
        dataRow["date"] = date.toLocaleDateString(siteMetadata.locale, postDateTemplate)
      } else if (j === "page") {
        dataRow["page"] = data[i][j]
      } else if (j === "country_count") {
        var value = 0
        if (data[i][j] == null) {
          value = "unknown"
          dataRow["country_count"] = null
        } else {
          value = data[i][j]
          value = value.replaceAll("(", "[").replaceAll(")", "]").replaceAll("'", '"')
          value = JSON.parse(value)
          dataRow["country_count"] = value
        }
      } else if (j === "views") {
        dataRow["views"] = parseInt(data[i][j])
      }
    }
    parsedData.push(dataRow)
  }

  const PageCellProcessor = ({ value, row: { index }, column: { id } }) => {
    return (
      <Link href={value} className="hover:underline">
        {" "}
        {value}{" "}
      </Link>
    )
  }

  const LocationCellProcessor = ({ value }) => {
    if (value == null) return

    const result = []
    for (var z = 0; z < value.length; z++) {
      result.push(<LocationCountItem value={value[z]} />)
    }
    return (

        {result}{" "}

    )
  }

  const columns = useMemo(
    () => [
      {
        Header: "Date",
        accessor: "date",
        sortType: (a, b) => {
          return new Date(b) - new Date(a)
        },
      },
      {
        Header: "Page",
        accessor: "page",
        Cell: PageCellProcessor,
      },
      {
        Header: "Views",
        accessor: "views",
        sortType: 'basic',
      },
      {
        Header: "Location",
        accessor: "country_count",
        Cell: LocationCellProcessor,
      },
    ],
    []
  )

  return (

  )
}
```
<p>Table.js:</p>
<pre class="lang-js prettyprint-override"><code>import { React, useMemo } from "react"

import { useTable, useFilters, useSortBy, usePagination } from "react-table"

import { useState } from "react"

export default function Table({ columns, data, isPaginated = true }) {
  const [filterInput, setFilterInput] = useState("")

  const handleFilterChange = (e) => {
    const value = e.target.value || undefined
    setFilter("page", value)
    setFilterInput(value)
  }

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    page,
    prepareRow,
    setFilter,
    canPreviousPage,
    canNextPage,
    pageOptions,
    nextPage,
    previousPage,
    state: { pageIndex, pageSize },
  } = useTable(
    {
      columns,
      data,
      initialState: {
        defaultCanSort: true,
        disableSortBy: false,
        manualSortBy: true,
        sortBy: useMemo(
          () => [
            {
              id: "date",
              desc: false,
            },
            {
              id: "views",
              desc: true,
            },
          ],
          []
        ),
        pageIndex: 0,
        pageSize: 15,
        manualPagination: true,
      },
    },
    useFilters,
    useSortBy,
    usePagination
  )
  return (
    <>
      <div className="flex justify-between align-middle">
        <div> Page Views</div>
        <input
          className="mr-0 rounded-sm border border-gray-700 dark:border-gray-500 "
          value={filterInput}
          onChange={handleFilterChange}
          placeholder={" Page name filter"}
        />
      </div>
      <table {...getTableProps()}>
        <thead>
          {headerGroups.map((headerGroup) => (
            <tr {...headerGroup.getHeaderGroupProps()}>
              {headerGroup.headers.map((column) => (
                <th
                  {...column.getHeaderProps(column.getSortByToggleProps())}
                  className={
                    column.isSorted ? (column.isSortedDesc ? "sort-desc" : "sort-asc") : ""
                  }
                >
                  {column.render("Header")}
                </th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody {...getTableBodyProps()}>
          {page.map((row, _) => {
            prepareRow(row)
            return (
              <tr {...row.getRowProps()}>
                {row.cells.map((cell) => {
                  return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>
                })}
              </tr>
            )
          })}
        </tbody>
      </table>
      {Boolean(isPaginated) && (
        <div id="pagination">
          <div id="pageNum">
            page {pageIndex + 1} of {pageOptions.length}
          </div>{" "}
          <div id="nextPrevButtons">
            {canPreviousPage ? (
              <div id="backButton" onClick={() => previousPage()}>
                Previous
              </div>
            ) : null}
            {canNextPage ? (
              <div id="nextButton" onClick={() => nextPage()}>
                Next{" "}
              </div>
            ) : null}
          </div>
        </div>
      )}
    </>
  )
}

</code>```

Body:
I'm using react-table v7.8.0 to create a table with 4 columns. I'd like the the table to be sorted by columns date and views. My problem is that the table is only being sorted by the date column.

I have some pagination and manual sorting that appears to be working as expected. I think I've followed the documentation and I'm unsure where my mistake is.

The data is configured in the following file before being passed to a table component:

ViewsPageDayTable.js:

const postDateTemplate = { year: "numeric", month: "short", day: "numeric" }

import Link from "@/components/Link"
import { useMemo } from "react"

import siteMetadata from "@/data/siteMetadata"

import Table from "@/components/homeBrewAnalytics/table"
import LocationCountItem from "@/components/homeBrewAnalytics/locationCountItem"

export default function ViewsPageDayTable({ data }) {
  const parsedData = []
  for (var i = 0; i < data.length; i++) {
    const dataRow = {}
    for (var j in data[i]) {
      if (j === "date") {
        var date = new Date(data[i][j])
        dataRow["date"] = date.toLocaleDateString(siteMetadata.locale, postDateTemplate)
      } else if (j === "page") {
        dataRow["page"] = data[i][j]
      } else if (j === "country_count") {
        var value = 0
        if (data[i][j] == null) {
          value = "unknown"
          dataRow["country_count"] = null
        } else {
          value = data[i][j]
          value = value.replaceAll("(", "[").replaceAll(")", "]").replaceAll("'", '"')
          value = JSON.parse(value)
          dataRow["country_count"] = value
        }
      } else if (j === "views") {
        dataRow["views"] = parseInt(data[i][j])
      }
    }
    parsedData.push(dataRow)
  }

  const PageCellProcessor = ({ value, row: { index }, column: { id } }) => {
    return (
      <Link href={value} className="hover:underline">
        {" "}
        {value}{" "}
      </Link>
    )
  }

  const LocationCellProcessor = ({ value }) => {
    if (value == null) return

    const result = []
    for (var z = 0; z < value.length; z++) {
      result.push(<LocationCountItem value={value[z]} />)
    }
    return (

        {result}{" "}

    )
  }

  const columns = useMemo(
    () => [
      {
        Header: "Date",
        accessor: "date",
        sortType: (a, b) => {
          return new Date(b) - new Date(a)
        },
      },
      {
        Header: "Page",
        accessor: "page",
        Cell: PageCellProcessor,
      },
      {
        Header: "Views",
        accessor: "views",
        sortType: 'basic',
      },
      {
        Header: "Location",
        accessor: "country_count",
        Cell: LocationCellProcessor,
      },
    ],
    []
  )

  return (

  )
}

Table.js:

import { React, useMemo } from "react"

import { useTable, useFilters, useSortBy, usePagination } from "react-table"

import { useState } from "react"

export default function Table({ columns, data, isPaginated = true }) {
  const [filterInput, setFilterInput] = useState("")

  const handleFilterChange = (e) => {
    const value = e.target.value || undefined
    setFilter("page", value)
    setFilterInput(value)
  }

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    page,
    prepareRow,
    setFilter,
    canPreviousPage,
    canNextPage,
    pageOptions,
    nextPage,
    previousPage,
    state: { pageIndex, pageSize },
  } = useTable(
    {
      columns,
      data,
      initialState: {
        defaultCanSort: true,
        disableSortBy: false,
        manualSortBy: true,
        sortBy: useMemo(
          () => [
            {
              id: "date",
              desc: false,
            },
            {
              id: "views",
              desc: true,
            },
          ],
          []
        ),
        pageIndex: 0,
        pageSize: 15,
        manualPagination: true,
      },
    },
    useFilters,
    useSortBy,
    usePagination
  )
  return (
    <>

 Page Views

        <input
          className="mr-0 rounded-sm border border-gray-700 dark:border-gray-500 "
          value={filterInput}
          onChange={handleFilterChange}
          placeholder={" Page name filter"}
        />

          {headerGroups.map((headerGroup) => (

              {headerGroup.headers.map((column) => (

                  {column.render("Header")}

              ))}

          ))}

          {page.map((row, _) => {
            prepareRow(row)
            return (

                {row.cells.map((cell) => {
                  return {cell.render("Cell")}
                })}

            )
          })}

      {Boolean(isPaginated) && (

            page {pageIndex + 1} of {pageOptions.length}

{" "}

            {canPreviousPage ? (

 previousPage()}>
                Previous

            ) : null}
            {canNextPage ? (

 nextPage()}>
                Next{" "}

            ) : null}

      )}
    </>
  )
}


来源: stackexchange

问:
react-native-vision-camera device is null
I am trying to run a basic example of react-native-vision-camera and getting the error device is null. I checked the app permissions through android phone and camera permissions are granted. Here is my current code:

```<code>
import React,{useEffect, useState} from 'react';
import { Text, View, Linking} from 'react-native';
import {useCameraDevices, Camera} from 'react-native-vision-camera';

const App = () => {

  const devices = useCameraDevices();
  const device = devices.back;

React.useEffect( () => {
  requestCameraPermission();
}, [])

const requestCameraPermission = React.useCallback( async () => {

const permission = await Camera.requestCameraPermission();

if (permission == 'denied')
{
console.log("Permission not granted");
await Linking.openSettings();
}

  }, [])

  function renderCamera()
  {
    if(device == null)
    {
      console.log("device is null");

      return (<View><Text>Camera not working</Text></View>)
    }
    else
    {
      <View>
        <Camera

        device={device}
        isActive={true}
        enableZoomGesture
        />
      </View>
    }
  }

    return(
  <View>

    {renderCamera()}
  </View>
    )
  }

 export default App;

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to run a basic example of react-native-vision-camera and getting the error device is null. I checked the app permissions through android phone and camera permissions are granted. Here is my current code:

import React,{useEffect, useState} from 'react';
import { Text, View, Linking} from 'react-native';
import {useCameraDevices, Camera} from 'react-native-vision-camera';

const App = () => {

  const devices = useCameraDevices();
  const device = devices.back;

React.useEffect( () => {
  requestCameraPermission();
}, [])

const requestCameraPermission = React.useCallback( async () => {

const permission = await Camera.requestCameraPermission();

if (permission == 'denied')
{
console.log("Permission not granted");
await Linking.openSettings();
}

  }, [])

  function renderCamera()
  {
    if(device == null)
    {
      console.log("device is null");

      return (<View><Text>Camera not working</Text></View>)
    }
    else
    {
      <View>
        <Camera

        device={device}
        isActive={true}
        enableZoomGesture
        />
      </View>
    }
  }

    return(
  <View>

    {renderCamera()}
  </View>
    )
  }

 export default App;


问:
Quarkus JAXB configuration
I'm writing a Quarkus microservice and I need to upload a file and then parse it. The file upload part is all good, now I'm trying to parse file content to XML. I'm struggling with XML namespaces

I'm using this dependency:

```<code><dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-resteasy-reactive-jaxb</artifactId>
</dependency>
</code>```

and here is my resource:

```<code>@Path("/import")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@RequestScoped
public class FileUploadResource {
    @Inject
    Unmarshaller unmarshaller;

    @POST
    public Uni<Void> importFile(final MultipartData data) {
        try {
            Document document = (Document) this.unmarshaller.unmarshal(data.file);
            return Uni.createFrom().voidItem();
        } catch (Exception e) {
            Log.error(e.getMessage(), e);
            throw new WebApplicationException(500);
        }
    }
}
</code>```

Models:

```<code>@RegisterForReflection
public class MultipartData {
    @RestForm
    public InputStream file;
}
</code>```
```<code>@XmlRootElement(namespace = "some-namespace", name="Document")
public class Document {
    @XmlElement(namespace = "some-namespace")
    public Element element;
}
</code>```

I'm uploading files with this root element: <Document xmlns="some-namespace" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> but namespaces can potentially change.

I experienced that Element is null if the namespace is not specified. Is it possible (and good practice) to unmarshall xml files regardless of the namespace?

I tried this way: https://quarkus.io/guides/resteasy-reactive#customize-the-jaxb-configuration but I don't find the correct customization

Title: Quarkus JAXB configuration

Body:
I'm writing a Quarkus microservice and I need to upload a file and then parse it. The file upload part is all good, now I'm trying to parse file content to XML. I'm struggling with XML namespaces

I'm using this dependency:

<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-resteasy-reactive-jaxb</artifactId>
</dependency>

and here is my resource:

@Path("/import")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@RequestScoped
public class FileUploadResource {
    @Inject
    Unmarshaller unmarshaller;

    @POST
    public Uni<Void> importFile(final MultipartData data) {
        try {
            Document document = (Document) this.unmarshaller.unmarshal(data.file);
            return Uni.createFrom().voidItem();
        } catch (Exception e) {
            Log.error(e.getMessage(), e);
            throw new WebApplicationException(500);
        }
    }
}

Models:

@RegisterForReflection
public class MultipartData {
    @RestForm
    public InputStream file;
}

@XmlRootElement(namespace = "some-namespace", name="Document")
public class Document {
    @XmlElement(namespace = "some-namespace")
    public Element element;
}

I'm uploading files with this root element: <Document xmlns="some-namespace" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> but namespaces can potentially change.

I experienced that Element is null if the namespace is not specified. Is it possible (and good practice) to unmarshall xml files regardless of the namespace?

I tried this way: https://quarkus.io/guides/resteasy-reactive#customize-the-jaxb-configuration but I don't find the correct customization


问:
How to make component Addresses in SHOPEE?
How can i make a Addresses component in SHOPEE or have library like that or something like that, this is the example of component. Thanks.

Have a library or code component Addresses in SHOPESS.

Address Component


问:
How to get the index of csr sparse format in pytorch through api？
I'm using torch's csr sparse format

```<code>a = torch.tensor([[4,0,9,0],
 [0, 7 ,0 ,0],
 [0 ,0, 0, 0],
 [0 ,0, 0 ,5],])
a.to_sparse_csr()

tensor(crow_indices=tensor([0, 2, 3, 3, 4]),
       col_indices=tensor([0, 2, 1, 3]),
       values=tensor([4, 9, 7, 5]), size=(4, 4), nnz=4,
       layout=torch.sparse_csr)
</code>```

how can i get the crow_indices,col_indices,values by API?
I tried a.coalesce().indices(), but this is for the coo format,not csr format

Body:
I'm using torch's csr sparse format

a = torch.tensor([[4,0,9,0],
 [0, 7 ,0 ,0],
 [0 ,0, 0, 0],
 [0 ,0, 0 ,5],])
a.to_sparse_csr()

tensor(crow_indices=tensor([0, 2, 3, 3, 4]),
       col_indices=tensor([0, 2, 1, 3]),
       values=tensor([4, 9, 7, 5]), size=(4, 4), nnz=4,
       layout=torch.sparse_csr)

how can i get the crow_indices,col_indices,values by API?
I tried a.coalesce().indices(), but this is for the coo format,not csr format


问:
Chrome extension doesn't work with dev-tools open
I'm creating my own Chrome Extension which is for use as a helper on a website. To do this, it reads a specific element on the website and then console.log() it.  The extension is a statically injected content-script.It works perfectly fine when dev-tools isn't open when the page fist loads, but the console.log() prints null if dev-tools is open on first load.

```<code>var board = document.getElementById('board-board');
var board_elements = board.getElementsByTagName('div');
....
console.log("number of elements in board class:" + board_elements.length);
</code>```

without dev-tools open: number of elements in board class:36

with dev-tools open: number of elements in board class:0

This is weird behaviour. Is this a problem with my own computer, code, or a bug with Chrome?

Body:
I'm creating my own Chrome Extension which is for use as a helper on a website. To do this, it reads a specific element on the website and then console.log() it.  The extension is a statically injected content-script.It works perfectly fine when dev-tools isn't open when the page fist loads, but the console.log() prints null if dev-tools is open on first load.

var board = document.getElementById('board-board');
var board_elements = board.getElementsByTagName('div');
....
console.log("number of elements in board class:" + board_elements.length);

without dev-tools open: number of elements in board class:36

with dev-tools open: number of elements in board class:0

This is weird behaviour. Is this a problem with my own computer, code, or a bug with Chrome?


问:
How to use Object type in mongose schema?
I am trying to store the amount of time an employee has worked in my MongoDB database, but not able to make a mongoose schema whose type will object.

The desired database should have a document like this:

```<code>{
 name: 'name of employee',
 report: {'01-01-2023':5hr, '02-01-202':7hr, '03-01-2023':8hrs}
}
</code>```

This report will contain an object whose key will be a date and the value will be minutes or hours an employee has worked on that date.

how can I make a schema to achieve the desired goal, I have tried like this but did not work.

```<code>const UserSchema = new mongoose.Schema({
    name:{
        type: String,
        required: true
    },
    report: {
        type: Object, // what should I write here
    }
})
</code>```

Body:
I am trying to store the amount of time an employee has worked in my MongoDB database, but not able to make a mongoose schema whose type will object.

The desired database should have a document like this:

{
 name: 'name of employee',
 report: {'01-01-2023':5hr, '02-01-202':7hr, '03-01-2023':8hrs}
}

This report will contain an object whose key will be a date and the value will be minutes or hours an employee has worked on that date.

how can I make a schema to achieve the desired goal, I have tried like this but did not work.

const UserSchema = new mongoose.Schema({
    name:{
        type: String,
        required: true
    },
    report: {
        type: Object, // what should I write here
    }
})


问:
Errors relating to @relation
I'm having issue related to database as shown in picture: enter image description here:

When I try to save this schema VsCode automatically creates duplicates of User Department and Class fields In User table.

```<code>enum UserRole {
  GUEST
  ADMIN
  INSTRUCTOR
  EMPLOYEE
  STUDENT
}

model User {
  id             String      @id @unique @default(cuid())
  createdAt      DateTime?   @default(now())
  updatedAt      DateTime?   @updatedAt
  deletedAt      DateTime?
  firstName      String
  lastName       String
  email          String      @unique
  password       String
  emailVerified  DateTime?
  photo          String?
  role           UserRole    @default(GUEST)
  jobTitle       String?
  hireDate       DateTime?
  enrollmentID   String?     @unique
  enrollmentDate DateTime?
  instructors    User[]      @relation("Instructors")
  students       User[]      @relation("Students")
  department     Department? @relation(fields: [departmentId], references: [id])
  departmentId   String?
  classes        Class[]     @relation(fields: [classId], references: [id])
  classId        String?

  @@index([departmentId])
  @@index([classId])
}

model Department {
  id        String  @id @unique @default(cuid())
  name      String? @unique
  employees User[]  @relation("Employees")
}

model Class {
  id           String    @id @unique @default(cuid())
  name         String?   @unique
  startDate    DateTime?
  members      User[]    @relation("Members")
  instructor   User?     @relation(fields: [instructorId], references: [id])
  instructorId String?

  @@index([instructorId])
}
</code>```

Title: Errors relating to @relation

Body:
I'm having issue related to database as shown in picture: enter image description here:

When I try to save this schema VsCode automatically creates duplicates of User Department and Class fields In User table.

enum UserRole {
  GUEST
  ADMIN
  INSTRUCTOR
  EMPLOYEE
  STUDENT
}

model User {
  id             String      @id @unique @default(cuid())
  createdAt      DateTime?   @default(now())
  updatedAt      DateTime?   @updatedAt
  deletedAt      DateTime?
  firstName      String
  lastName       String
  email          String      @unique
  password       String
  emailVerified  DateTime?
  photo          String?
  role           UserRole    @default(GUEST)
  jobTitle       String?
  hireDate       DateTime?
  enrollmentID   String?     @unique
  enrollmentDate DateTime?
  instructors    User[]      @relation("Instructors")
  students       User[]      @relation("Students")
  department     Department? @relation(fields: [departmentId], references: [id])
  departmentId   String?
  classes        Class[]     @relation(fields: [classId], references: [id])
  classId        String?

  @@index([departmentId])
  @@index([classId])
}

model Department {
  id        String  @id @unique @default(cuid())
  name      String? @unique
  employees User[]  @relation("Employees")
}

model Class {
  id           String    @id @unique @default(cuid())
  name         String?   @unique
  startDate    DateTime?
  members      User[]    @relation("Members")
  instructor   User?     @relation(fields: [instructorId], references: [id])
  instructorId String?

  @@index([instructorId])
}


问:
How to properly use the clienthandler for certifcates when doing a web request with powershell?
My web request using a certificate, implemented in powershell code, gives an error about a certificate missing. It is supposed to work because similar code in C# does not cause this problem.

Here is my powershell code:

```<code>Add-Type -AssemblyName System.Net.Http
Add-Type -AssemblyName System.Net.Primitives
$cert = Get-Item -Path "Cert:\CurrentUser\My\$thumbprint"
$clientHandler = New-Object System.Net.Http.HttpClientHandler
$clientHandler.ClientCertificates.Add($cert)
$client = New-Object System.Net.Http.HttpClient($clientHandler)
$message = New-Object System.Net.Http.HttpRequestMessage
$message.Method = [System.Net.Http.HttpMethod]::Get
$message.RequestUri = New-Object System.Uri($url)
$response = $client.SendAsync($message)
$responseContent = $response.Result.Content
$content = $responseContent.ReadAsStringAsync().Result
$content
</code>```

Here is the response.

```<code><html>
<head><title>400 No required SSL certificate was sent</title></head>
<body>
<center><h1>400 Bad Request</h1></center>
<center>No required SSL certificate was sent</center>
<hr><center>nginx/XXXX</center>
</body>
</html>
</code>```

I do not get this response when using the certificate in my browser. My C# application also works fine. So how do I make this powershell script work?

Update

An alternative approach to execute the web request using powershell gives the same error. Here is the alternative approach:

```<code>$cert = Get-Item -Path "Cert:\CurrentUser\My\$thumbprint"
Invoke-WebRequest -Uri $url -Method GET -Certificate $cert
</code>```

Body:
My web request using a certificate, implemented in powershell code, gives an error about a certificate missing. It is supposed to work because similar code in C# does not cause this problem.

Here is my powershell code:

Add-Type -AssemblyName System.Net.Http
Add-Type -AssemblyName System.Net.Primitives
$cert = Get-Item -Path "Cert:\CurrentUser\My\$thumbprint"
$clientHandler = New-Object System.Net.Http.HttpClientHandler
$clientHandler.ClientCertificates.Add($cert)
$client = New-Object System.Net.Http.HttpClient($clientHandler)
$message = New-Object System.Net.Http.HttpRequestMessage
$message.Method = [System.Net.Http.HttpMethod]::Get
$message.RequestUri = New-Object System.Uri($url)
$response = $client.SendAsync($message)
$responseContent = $response.Result.Content
$content = $responseContent.ReadAsStringAsync().Result
$content

Here is the response.

<title>400 No required SSL certificate was sent</title>

400 Bad Request

No required SSL certificate was sent

nginx/XXXX

I do not get this response when using the certificate in my browser. My C# application also works fine. So how do I make this powershell script work?

Update

An alternative approach to execute the web request using powershell gives the same error. Here is the alternative approach:

$cert = Get-Item -Path "Cert:\CurrentUser\My\$thumbprint"
Invoke-WebRequest -Uri $url -Method GET -Certificate $cert


问:
Download button in bpmn.js react js
I have created BPMN diagram based on business needs using react js. Also am having save button to save the XML of created diagram. On clicking save button I want to get XML of created diagram.

Code

```<code> <button onClick={getXmlFromModeler}>Save</button>
useEffect(() => {
    const modeler = new Modeler({
                container,
                keyboard: {
                    bindTo: document
                }
            });
 }, [])
 function getXmlFromModeler(modeler) {
        return new Promise((resolve, reject) => {
          modeler.saveXML(
            {format: true},
            (err, xml) => {
              if (err) {
                reject(err)
              } else {
                resolve(xml)
              }
            }
           )
        })
      }
</code>```

but got an error

Uncaught (in promise) TypeError: modeler.saveXML is not a function

Any help would be appreciated

Title: Download button in bpmn.js react js

Body:
I have created BPMN diagram based on business needs using react js. Also am having save button to save the XML of created diagram. On clicking save button I want to get XML of created diagram.

Code

 <button onClick={getXmlFromModeler}>Save</button>
useEffect(() => {
    const modeler = new Modeler({
                container,
                keyboard: {
                    bindTo: document
                }
            });
 }, [])
 function getXmlFromModeler(modeler) {
        return new Promise((resolve, reject) => {
          modeler.saveXML(
            {format: true},
            (err, xml) => {
              if (err) {
                reject(err)
              } else {
                resolve(xml)
              }
            }
           )
        })
      }

but got an error

Uncaught (in promise) TypeError: modeler.saveXML is not a function

Any help would be appreciated


问:
Getting too many crashes in Xiaomi devices
I have recently find that my app is getting crash on Xiaomi/Redmi device with following stack trace

Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.destroyHardwareResources()' on a null object reference
at android.view.ViewGroup.destroyHardwareResources(ViewGroup.java:5263)
at android.view.ViewGroup.destroyHardwareResources(ViewGroup.java:5263)
at android.view.ViewGroup.destroyHardwareResources(ViewGroup.java:5263)
at android.view.ViewGroup.destroyHardwareResources(ViewGroup.java:5263)
at android.view.ViewGroup.destroyHardwareResources(ViewGroup.java:5263)
at android.view.ViewGroup.destroyHardwareResources(ViewGroup.java:5263)
at android.view.ThreadedRenderer.destroyResources(ThreadedRenderer.java:446)
at android.view.ThreadedRenderer.destroyHardwareResources(ThreadedRenderer.java:441)
at android.view.ViewRootImpl.destroyHardwareResources(ViewRootImpl.java:1315)
at android.view.WindowManagerGlobal.trimMemory(WindowManagerGlobal.java:598)
at android.app.ActivityThread.handleTrimMemory(ActivityThread.java:6499)
at android.app.ActivityThread.access$1500(ActivityThread.java:263)
at android.app.ActivityThread$ApplicationThread.lambda$scheduleTrimMemory$0(ActivityThread.java:1699)
at android.app.-$$Lambda$ActivityThread$ApplicationThread$tUGFX7CUhzB4Pg5wFd5yeqOnu38.accept(-.java:8)
at com.android.internal.util.function.pooled.PooledLambdaImpl.doInvoke(PooledLambdaImpl.java:278)
at com.android.internal.util.function.pooled.PooledLambdaImpl.invoke(PooledLambdaImpl.java:201)
at com.android.internal.util.function.pooled.OmniFunction.run(OmniFunction.java:97)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1039)
at android.view.Choreographer.doCallbacks(Choreographer.java:863)
at android.view.Choreographer.doFrame(Choreographer.java:796)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1024)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:236)
at android.app.ActivityThread.main(ActivityThread.java:8069)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:620)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1011)`

I am not able to reproduce it
Android os : 11
Devcies : Redmi Note 9,Redmi 9, Redmi 10 2022 and some more redmi devices

I have googled but did not find any solution or hint regarding this issue, is there anyone facing some issue ?


问:
Prevent font change on cell edit in tabulator table
if I click on a cell that is editable (editor:"textarea")

then the font changes:

I want the font to be the same.

So I tried to set the font family by CSS:

```<code>.tabulator-editing {
font-family: Arial, Helvetica, sans-serif;}
</code>```

But this doesn't work.

Could you please help me with this?

Body:
if I click on a cell that is editable (editor:"textarea")

then the font changes:

I want the font to be the same.

So I tried to set the font family by CSS:

.tabulator-editing {
font-family: Arial, Helvetica, sans-serif;}

But this doesn't work.

Could you please help me with this?


问:
Android Debug -> Disconnected from the target VM
Suddenly it is not possible to debug my android device. After a few seconds the device disconnects and i get the following message: "Disconnected from the target VM, address: 'localhost:49504', transport: 'socket'
I am using a Zebra Scanner.

I didn't change the code since the last time that i worked on that app.

I deselected all breakpoints.
I tried different activites.
Even by just starting the app in debug mode, it disconnets after a few seconds.
Running the app and attatching the debugger has the same result.


问:
transformer classification w/ many classes (Pytorch)
I have a transformer (for rec.) and (sequence)classification task with a lot of classes, usually for classification tasks probabilities or logits for all classes are calculated and the max value is selected. However I think there will be too man parameters in this case, so I was wondering if following approach is valid:

I want to predict 10 classes based on an input sequence of x No of classes

-convert all classes to INTs

-build transformer with mean pooling and linear output layer = 10 (then round all values) predicting classes directly

I am not sure because the ordering of class INTs has no meaning, so will the model be able to learn correct weights?

Maybe a basic question but I couldnt find anything on that.


问:
GraphQL Shield Type Validation Performed After Resolver Executed, Not Before
I'm using Apollo GraphQL Server with GraphQL shield. When I implement rule on GraphQL type, the Shield authorization performed after the resolver executed. Is that how GraphQL Shield works or is it caused by misconfiguration?

Here's the server configuration

```<code>import { ApolloServer } from 'apollo-server-express';
import { ApolloServerPluginDrainHttpServer } from 'apollo-server-core';
import http from 'http';
import { applyMiddleware } from 'graphql-middleware';
import schema from './schema';
import shield from './shield';

(async () => {
  const httpServer = http.createServer(app);
  const server = new ApolloServer({
    schema: applyMiddleware(schema, shield),
    csrfPrevention: true,
    cache: 'bounded',
    plugins: [ApolloServerPluginDrainHttpServer({ httpServer })]
  });
  await server.start();
  server.applyMiddleware({ app });
  await new Promise<void>((resolve) =>
    httpServer.listen({ port: 80 }, resolve)
  );
  console.log(`Server ready at http://localhost:80${server.graphqlPath}`);
})(schema);

</code>```

Thankyou

Body:
I'm using Apollo GraphQL Server with GraphQL shield. When I implement rule on GraphQL type, the Shield authorization performed after the resolver executed. Is that how GraphQL Shield works or is it caused by misconfiguration?

Here's the server configuration

import { ApolloServer } from 'apollo-server-express';
import { ApolloServerPluginDrainHttpServer } from 'apollo-server-core';
import http from 'http';
import { applyMiddleware } from 'graphql-middleware';
import schema from './schema';
import shield from './shield';

(async () => {
  const httpServer = http.createServer(app);
  const server = new ApolloServer({
    schema: applyMiddleware(schema, shield),
    csrfPrevention: true,
    cache: 'bounded',
    plugins: [ApolloServerPluginDrainHttpServer({ httpServer })]
  });
  await server.start();
  server.applyMiddleware({ app });
  await new Promise<void>((resolve) =>
    httpServer.listen({ port: 80 }, resolve)
  );
  console.log(`Server ready at http://localhost:80${server.graphqlPath}`);
})(schema);

Thankyou


问:
spark session build taking long time
I am new to Spark and Hadoop , I have installed both within docker container ,
in spark-submit we are calling the python script

we are trying to execute below in spark-submit

```<code> spark = (
        pyspark.sql.SparkSession.builder
        .appName('AppName ')
        .config('spark.sql.crossJoin.enabled', 'true')
        .config('spark.sql.shuffle.partitions', 2000)
        .config('spark.debug.maxToStringFields', 1000)
        .getOrCreate())
</code>```

it is not showing any errors but getting stuck

Title: spark session build taking long time

Body:
I am new to Spark and Hadoop , I have installed both within docker container ,
in spark-submit we are calling the python script

we are trying to execute below in spark-submit

 spark = (
        pyspark.sql.SparkSession.builder
        .appName('AppName ')
        .config('spark.sql.crossJoin.enabled', 'true')
        .config('spark.sql.shuffle.partitions', 2000)
        .config('spark.debug.maxToStringFields', 1000)
        .getOrCreate())

it is not showing any errors but getting stuck


问:
OrderedDictionary inside the init consisting of list of dictionaries gives the error for the state of transitions module for the state maching
In a class ABCD inside the init method I have variable state consisting of  OrderedDict containing list of dictionaries. Basically the state is of module 'transitions' which are imported from class 'machine' and inside state I have orderedDict consisting of list of dictionaries.

```<code>class ABCD(Machine)
def __init__(self,args):
self.a=opts['a']
self.a=opts['b']
self.states=orderedDict([{'name':'start'},{'name':'connection','on_enter':'go'}])

</code>```

Error is:

Argument of type "list[dict[str, str]]" cannot be assigned to parameter "__iterable" of type "Iterable[list[str]]" in function "init"

If I donot use the OrderedDict and use the dictionary instead of it, then I face the below error:

Cannot assign member "states" for type "ABCD"
"list[dict[str, str]]" is incompatible with "OrderedDict[str, State]"

Body:
In a class ABCD inside the init method I have variable state consisting of  OrderedDict containing list of dictionaries. Basically the state is of module 'transitions' which are imported from class 'machine' and inside state I have orderedDict consisting of list of dictionaries.

class ABCD(Machine)
def __init__(self,args):
self.a=opts['a']
self.a=opts['b']
self.states=orderedDict([{'name':'start'},{'name':'connection','on_enter':'go'}])

Error is:

Argument of type "list[dict[str, str]]" cannot be assigned to parameter "__iterable" of type "Iterable[list[str]]" in function "init"

If I donot use the OrderedDict and use the dictionary instead of it, then I face the below error:

Cannot assign member "states" for type "ABCD"
"list[dict[str, str]]" is incompatible with "OrderedDict[str, State]"


问:
How to get file path from a file object in reactJS
I'm trying to pass a file from a form to a hashing function, the only problem is the hashing function takes a file path as an argument, not a file object. So my idea is to choose a file from a normal file input field and then some how extracting the file path from the chosen file.

I tried searching for the file path through the documentation, but i failed to find anything


问:
Which approach is used by PM2 to run the application in cluster mode?
PM2 uses the node cluster module to run the application cluster mode.

The cluster module supports two methods of distributing incoming connections.

The first one (and the default one on all platforms except Windows) is the round-robin approach, where the primary process listens on a port, accepts new connections, and distributes them across the workers in a round-robin fashion, with some built-in smarts to avoid overloading a worker process.

The second approach is where the primary process creates the listen socket and sends it to interested workers. The workers then accept incoming connections directly.

So my question is, Which approach is used by PM2 to run the application in cluster mode?

If you know the answer let me know.


问:
Train/validation split for Costum Dataset class in PyTorch using time-series data
I am working with DNN in Pytorch with time-series data and stumbled over a problem handling the split of the train and validation set. This is a rather complex and special problem (I guess), so I'll try to keep it short while keeping all relevant information. Also feel free to critic any of my code, I am always happy about new input.

This question is more about the best ways to handle this problem, not primarily about its implementation.

Thanks in advance to anyone that takes the time reading this.

In short, I split my data into train and test set without shuffling (since I use time-series data) and want to split my train set into the "real" train set and validation set. This also needs to happen without shuffling (more later), but I can't just take the last part of the set as validation set, since I will loose the most recent data points, so I take it from the middle of the initial train set. Now using a custom Dataset class for sequential data will cause problems, since the validation set is somewhere in the middle in the train set and generating sequential samples from the class gives wrong time-series. More detailed, if I remove data from the middle of the train set, concat the train set and but the "real" train set into a Dataset class, the data points at the beginnin of the second chunk will have wrong datapoints from the past (since they will be inside the first chunk, which is not the real past, which would have been in the validatoin set).

In long, I am using time-series from the electricity market, which have the problem that close data points (close in time) are quite similar, which causes immediate overfitting when shuffling data, since the validation set will also get better if the train set gets overfitted. So training never stops with early stopping. The data is also highly non-stationary, which is the reason why I need the most recent data points of the train set to be in the training process and not in the validation set.

The Dataset class I usually use for time-series data is the following (note that this is already a special case for electricity data, since the label is not taken from the (i+1)th element but directly from the ith):

class TimeDataset(Dataset):
    def __init__(
        self,
        X,
        y,
        seq_len
    ):
        self.X = torch.Tensor(X.values)
        self.y = torch.Tensor(y.values)

        self.seq_len = seq_len

    def __getitem__(
        self,
        index
    ):
        return self.X[index:index+self.seq_len], self.y[index+self.seq_len-1]

    def __len__(self):
        return len(self.X) - self.seq_len
```
<p>For the train/validation split it's better to talk about a simple example. Assume the inital data set has <code>len(init_train_data) = 10000</code> and the validation set needs to be <code>len(val_data) = 1000</code>. Also lets say <code>seq_len = 50</code>. So the resulting train set has <code>len(train_data) = 9000</code>. But the 1000 samples for the validation set are taken from the middle of the 10000 data points, so just assume we take <code>val_data = init_train_data[8000:9000]</code> and <code>train_data = init_train_data[:8000] + init_train_data[9000:]</code>. If I use <code>TimeDataset</code> for this split, I will get wrong data for some of the training samples. For example, take <code>train_data[8000]</code>. The label will be the value of <code>init_train_data[9000]</code> but the data points from the past will be <code>init_train_data[7950:8000]</code> (not 100% correct, but I hope you get the point).</p>
<p>I have written a workaround for this, never splitting the validation set of the train set and splitting the sets on the go inside the <code>__getitem__</code> method.</p>
<pre class="lang-py prettyprint-override"><code>class TrainValDataset(Dataset):
    def __init__(
        self,
        X,
        y,
        seq_len,
        val=False,
        val_size=1000,
        recent_size=1000
    ):
        self.X = torch.Tensor(X.values)
        self.y = torch.Tensor(y.values)

        self.seq_len = seq_len

        self.len = len(self.X)
        self.val = val
        self.val_size = val_size
        self.recent_size = recent_size

    def __getitem__(
        self,
        index
    ):
        if self.val:
            if not(0 <= index < self.val_size):
                raise IndexError('list index out of range')
            edge = self.len - (self.val_size + self.recent_size)
            return self.X[edge+index-(self.seq_len-1):edge+index+1], self.y[edge+index]
        else:
            if (index + self.seq_len) > (self.len - (self.val_size + self.recent_size)):
                index += self.val_size
            if not(0 <= index < self.len):
                raise IndexError('list index out of range')
            return self.X[index:index+self.seq_len-1], self.y[index+self.seq_len-1]

    def __len__(self):
        if self.val:
            return self.val_size
        else:
            return self.len - (self.seq_len - 1) - self.val_size
</code>```

This works for the training process, but gets quite messy afterwards when analyzing the performance of the trained models, since a lot of information gets lost (like the original index of the train and validation set). Additionally, this just feels wrong, like brute-forcing a problem which almost never optimal. I am searching for a good idea to keep the implementation of this problem smooth, meaning keeping all relevant information while keeping the same performance in the model fitting process.

Ideas that (I think) don't work. Feel free to convince me that they work.

Creating all samples beforehand. This is just too much data to preprocess, I really need to do that on the go.

Keeping the index in the Dataset and returning it separately in __getitem__, like return X[...], y[...], index[...]. This slows down the training process which I don't want.

Some brainstorming:

Take the validation set at the end of the init_train set, but retrain somehow (???) with the validation set to include the most recent data points.

Find best hyperparams (mainly #epochs) with the validation set and retrain the whole model using the full init_train set (or same amount but with most recent data points included). Would be very expensive though...

I am happy for any input that takes me closer to an optimal solution for this problem. It's also fine if you can convince me that I am overthinking this problem.

Also thanks again to anyone who came this far and read the full question :)

Body:
I am working with DNN in Pytorch with time-series data and stumbled over a problem handling the split of the train and validation set. This is a rather complex and special problem (I guess), so I'll try to keep it short while keeping all relevant information. Also feel free to critic any of my code, I am always happy about new input.

This question is more about the best ways to handle this problem, not primarily about its implementation.

Thanks in advance to anyone that takes the time reading this.

In short, I split my data into train and test set without shuffling (since I use time-series data) and want to split my train set into the "real" train set and validation set. This also needs to happen without shuffling (more later), but I can't just take the last part of the set as validation set, since I will loose the most recent data points, so I take it from the middle of the initial train set. Now using a custom Dataset class for sequential data will cause problems, since the validation set is somewhere in the middle in the train set and generating sequential samples from the class gives wrong time-series. More detailed, if I remove data from the middle of the train set, concat the train set and but the "real" train set into a Dataset class, the data points at the beginnin of the second chunk will have wrong datapoints from the past (since they will be inside the first chunk, which is not the real past, which would have been in the validatoin set).

In long, I am using time-series from the electricity market, which have the problem that close data points (close in time) are quite similar, which causes immediate overfitting when shuffling data, since the validation set will also get better if the train set gets overfitted. So training never stops with early stopping. The data is also highly non-stationary, which is the reason why I need the most recent data points of the train set to be in the training process and not in the validation set.

The Dataset class I usually use for time-series data is the following (note that this is already a special case for electricity data, since the label is not taken from the (i+1)th element but directly from the ith):

class TimeDataset(Dataset):
    def __init__(
        self,
        X,
        y,
        seq_len
    ):
        self.X = torch.Tensor(X.values)
        self.y = torch.Tensor(y.values)

        self.seq_len = seq_len

    def __getitem__(
        self,
        index
    ):
        return self.X[index:index+self.seq_len], self.y[index+self.seq_len-1]

    def __len__(self):
        return len(self.X) - self.seq_len

For the train/validation split it's better to talk about a simple example. Assume the inital data set has len(init_train_data) = 10000 and the validation set needs to be len(val_data) = 1000. Also lets say seq_len = 50. So the resulting train set has len(train_data) = 9000. But the 1000 samples for the validation set are taken from the middle of the 10000 data points, so just assume we take val_data = init_train_data[8000:9000] and train_data = init_train_data[:8000] + init_train_data[9000:]. If I use TimeDataset for this split, I will get wrong data for some of the training samples. For example, take train_data[8000]. The label will be the value of init_train_data[9000] but the data points from the past will be init_train_data[7950:8000] (not 100% correct, but I hope you get the point).

I have written a workaround for this, never splitting the validation set of the train set and splitting the sets on the go inside the __getitem__ method.

class TrainValDataset(Dataset):
    def __init__(
        self,
        X,
        y,
        seq_len,
        val=False,
        val_size=1000,
        recent_size=1000
    ):
        self.X = torch.Tensor(X.values)
        self.y = torch.Tensor(y.values)

        self.seq_len = seq_len

        self.len = len(self.X)
        self.val = val
        self.val_size = val_size
        self.recent_size = recent_size

    def __getitem__(
        self,
        index
    ):
        if self.val:
            if not(0 <= index < self.val_size):
                raise IndexError('list index out of range')
            edge = self.len - (self.val_size + self.recent_size)
            return self.X[edge+index-(self.seq_len-1):edge+index+1], self.y[edge+index]
        else:
            if (index + self.seq_len) > (self.len - (self.val_size + self.recent_size)):
                index += self.val_size
            if not(0 <= index < self.len):
                raise IndexError('list index out of range')
            return self.X[index:index+self.seq_len-1], self.y[index+self.seq_len-1]

    def __len__(self):
        if self.val:
            return self.val_size
        else:
            return self.len - (self.seq_len - 1) - self.val_size

This works for the training process, but gets quite messy afterwards when analyzing the performance of the trained models, since a lot of information gets lost (like the original index of the train and validation set). Additionally, this just feels wrong, like brute-forcing a problem which almost never optimal. I am searching for a good idea to keep the implementation of this problem smooth, meaning keeping all relevant information while keeping the same performance in the model fitting process.

Ideas that (I think) don't work. Feel free to convince me that they work.

Creating all samples beforehand. This is just too much data to preprocess, I really need to do that on the go.

Keeping the index in the Dataset and returning it separately in __getitem__, like return X[...], y[...], index[...]. This slows down the training process which I don't want.

Some brainstorming:

Take the validation set at the end of the init_train set, but retrain somehow (???) with the validation set to include the most recent data points.

Find best hyperparams (mainly #epochs) with the validation set and retrain the whole model using the full init_train set (or same amount but with most recent data points included). Would be very expensive though...

I am happy for any input that takes me closer to an optimal solution for this problem. It's also fine if you can convince me that I am overthinking this problem.

Also thanks again to anyone who came this far and read the full question :)


问:
How to use query operation with app sync auto generated resolver?
Below is the autogenerated resolver of appsync with DynamoDB. I am unable to understand what object I have to pass to use the Query operation.

```<code>#set( $limit = $util.defaultIfNull($context.args.limit, 100) )
#set( $ListRequest = {
  "version": "2018-05-29",
  "limit": $limit
} )
#if( $context.args.nextToken )
  #set( $ListRequest.nextToken = $context.args.nextToken )
#end
#if( $context.args.filter )
  #set( $ListRequest.filter = $util.parseJson("$util.transform.toDynamoDBFilterExpression($ctx.args.filter)") )
#end
#if( !$util.isNull($modelQueryExpression)
                        && !$util.isNullOrEmpty($modelQueryExpression.expression) )
  $util.qr($ListRequest.put("operation", "Query"))
  $util.qr($ListRequest.put("query", $modelQueryExpression))
  #if( !$util.isNull($ctx.args.sortDirection) && $ctx.args.sortDirection == "DESC" )
    #set( $ListRequest.scanIndexForward = false )
  #else
    #set( $ListRequest.scanIndexForward = true )
  #end
#else
  $util.qr($ListRequest.put("operation", "Scan"))
#end
$util.toJson($ListRequest)
</code>```

I have tried to pass the below query but got the all data of table. I have also tried with simple filter scan it's working and returning the data but I want to use index.

```<code>            let modelQueryExpression = {
                "expression": "#bookingtype = :bookingtype AND #bookinguserid = :bookinguserid",
                "expressionNames": {
                    "#bookinguserid": "bookinguserid",
                    "#bookingtype": "bookingtype",
                },
                "expressionValues": {
                    ":bookingtype": {
                        "S": JSON.parse(user).id,
                    },
                    ":parent": {
                        "S": 'Trip',
                    },
                }
            }
            const bookingdata = await API.graphql({ query: listBookings, variables: { modelQueryExpression } });
</code>```

Body:
Below is the autogenerated resolver of appsync with DynamoDB. I am unable to understand what object I have to pass to use the Query operation.

#set( $limit = $util.defaultIfNull($context.args.limit, 100) )
#set( $ListRequest = {
  "version": "2018-05-29",
  "limit": $limit
} )
#if( $context.args.nextToken )
  #set( $ListRequest.nextToken = $context.args.nextToken )
#end
#if( $context.args.filter )
  #set( $ListRequest.filter = $util.parseJson("$util.transform.toDynamoDBFilterExpression($ctx.args.filter)") )
#end
#if( !$util.isNull($modelQueryExpression)
                        && !$util.isNullOrEmpty($modelQueryExpression.expression) )
  $util.qr($ListRequest.put("operation", "Query"))
  $util.qr($ListRequest.put("query", $modelQueryExpression))
  #if( !$util.isNull($ctx.args.sortDirection) && $ctx.args.sortDirection == "DESC" )
    #set( $ListRequest.scanIndexForward = false )
  #else
    #set( $ListRequest.scanIndexForward = true )
  #end
#else
  $util.qr($ListRequest.put("operation", "Scan"))
#end
$util.toJson($ListRequest)

I have tried to pass the below query but got the all data of table. I have also tried with simple filter scan it's working and returning the data but I want to use index.

            let modelQueryExpression = {
                "expression": "#bookingtype = :bookingtype AND #bookinguserid = :bookinguserid",
                "expressionNames": {
                    "#bookinguserid": "bookinguserid",
                    "#bookingtype": "bookingtype",
                },
                "expressionValues": {
                    ":bookingtype": {
                        "S": JSON.parse(user).id,
                    },
                    ":parent": {
                        "S": 'Trip',
                    },
                }
            }
            const bookingdata = await API.graphql({ query: listBookings, variables: { modelQueryExpression } });


问:
explain how this pipeline work and from where this is working? Why my loss tok2vec is increasing?
```<code>- ``
- type here
- ``
</code>```

I am building Custom Spacy ner model. But i didn't understand from where this pipeline is working? and in Config.cfg file there is by default setting epoch is 0. but how this epochs values increasing? anybody please explain from attached snip?

I trained on 40000 samples and 3000 for testing.

I am Expecting answers from follwing qouestion:-
why this loss value is increasing?
why that epochs is increasing?
Which epochs value is correct?
from where this is calculating?
why same epochs value iterating many times?

Body:
- ``
- type here
- ``

I am building Custom Spacy ner model. But i didn't understand from where this pipeline is working? and in Config.cfg file there is by default setting epoch is 0. but how this epochs values increasing? anybody please explain from attached snip?

I trained on 40000 samples and 3000 for testing.

I am Expecting answers from follwing qouestion:-
why this loss value is increasing?
why that epochs is increasing?
Which epochs value is correct?
from where this is calculating?
why same epochs value iterating many times?


问:
mui datagrid get all rows for datagrid table
How can I access all of the rows in the datagrid in the form of an array, for example, we normally have 100 data, we filtered the datagrid, 20 data remained, how can I reach that 20 data?</p>


问:
Django docker doesn't hot reload for the updates in some folders somehow
I run Django docker and hot reload works normally in most folders.
But it doesn't work in some folders.
Here are my basic folder structure.

whaleserver (Django project)

api (app)

migrations

...

v1

v2

..

Any change inside v1 triggers hotreload but v2 change doesn't somehow.
Need help to diagnose this.

I already researched but couldn't find proper solution for this.
Much appreciated if anyone can give me helpful suggestion on it.
Thanks in advance.


问:
Usage of hasPermission with Spring State Machine
I know how to secure a method with hasPermission (ex : @PreAuthorize("hasPermission(#id, 'Review', 'read')").

It seems that Spring State Machine transitions can be secured using Spring Security. But I did not find any example that uses hasPermission with a reference of the object for which the state machine has been created. In fact I cannot see how to reference an object when I define a transition of a state machine.

Did you have to secured such cases? Did you find a solution?


问:
Dynamically generate n integer variables in function return statement
In my dash application, I am dynamically creating a list of items of dropdown menu.

```<code>def generate_dropdown_item(item):
    return dbc.DropdownMenuItem(item, id=str(item))

ti_units_list = ["Week", "Month"]

dbc.DropdownMenu(
    label="Output Unit",
    id="ti_unit_dropdown",
    children=[
        generate_dropdown_item(item) for item in ti_units_list
    ],
    color="secondary", className="m-1"),

html.P(id="ti_selected_unit")
</code>```

Then I have a callback function which prints the selected item.

```<code>@app.callback(
    Output("ti_selected_unit", "children"),
    [Output(unit, "n_clicks") for unit in ti_units_list
     ],
    [
        Input(unit, "n_clicks") for unit in ti_units_list
    ]
)
def show_selected_franchise(*args):
    i = 0
    for arg in args:
        if arg:
            return ti_units_list[i], 0, 0
        i = i+1
    return " ", 0, 0
</code>```

How can I replace the 0,0 in the return statement to dynamically create a number of constant variables (not a list or array)?

Generating constants using e.g. numpy np.zeros((2,), dtype=int) does not solve the problem, because it creates an array. This causes mismatch to the expected Output dimension.

Body:
In my dash application, I am dynamically creating a list of items of dropdown menu.

def generate_dropdown_item(item):
    return dbc.DropdownMenuItem(item, id=str(item))

ti_units_list = ["Week", "Month"]

dbc.DropdownMenu(
    label="Output Unit",
    id="ti_unit_dropdown",
    children=[
        generate_dropdown_item(item) for item in ti_units_list
    ],
    color="secondary", className="m-1"),

html.P(id="ti_selected_unit")

Then I have a callback function which prints the selected item.

@app.callback(
    Output("ti_selected_unit", "children"),
    [Output(unit, "n_clicks") for unit in ti_units_list
     ],
    [
        Input(unit, "n_clicks") for unit in ti_units_list
    ]
)
def show_selected_franchise(*args):
    i = 0
    for arg in args:
        if arg:
            return ti_units_list[i], 0, 0
        i = i+1
    return " ", 0, 0

How can I replace the 0,0 in the return statement to dynamically create a number of constant variables (not a list or array)?

Generating constants using e.g. numpy np.zeros((2,), dtype=int) does not solve the problem, because it creates an array. This causes mismatch to the expected Output dimension.


问:
tomcat ApplicationFilterChain is throwing exception without any detailed error
Below is the stack trace.I am not able to figure out what is wrong.
My application used to work fine. We recently moved our application to JDK11 and amzn-tomcat8-corretto-jdk11.Started getting this error. One more thing to note here.</p>
```<code>[ErrorPageFilter] tid= Forwarding to error page from request [/v1/access] due to exception [Filter execution threw an exception] javax.servlet.ServletException: Filter execution threw an exception
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:200)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.boot.web.servlet.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:128)
    at org.springframework.boot.web.servlet.support.ErrorPageFilter.access$000(ErrorPageFilter.java:66)
    at org.springframework.boot.web.servlet.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:103)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.springframework.boot.web.servlet.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:121)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.servlet.OpenTelemetryHandlerMappingFilter.doFilter(OpenTelemetryHandlerMappingFilter.java:81)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)

As this app works fine locally. I suspect there are some extra headers being passed in other environment. I tried increasing the size of the headers in tomcat config.But issue is still the same.
</code>```

Body:
Below is the stack trace.I am not able to figure out what is wrong.
My application used to work fine. We recently moved our application to JDK11 and amzn-tomcat8-corretto-jdk11.Started getting this error. One more thing to note here.

[ErrorPageFilter] tid= Forwarding to error page from request [/v1/access] due to exception [Filter execution threw an exception] javax.servlet.ServletException: Filter execution threw an exception
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:200)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.boot.web.servlet.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:128)
    at org.springframework.boot.web.servlet.support.ErrorPageFilter.access$000(ErrorPageFilter.java:66)
    at org.springframework.boot.web.servlet.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:103)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.springframework.boot.web.servlet.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:121)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.servlet.OpenTelemetryHandlerMappingFilter.doFilter(OpenTelemetryHandlerMappingFilter.java:81)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)

As this app works fine locally. I suspect there are some extra headers being passed in other environment. I tried increasing the size of the headers in tomcat config.But issue is still the same.


问:
How to redirect user to the Google consent screen?
I'm developing a web application that communicates with Google services (e. g. Gmail and Google Drive). So I have OAuth 2.0 application created in my Google Workspace organization. It requires particular OAuth scopes for correct work.

A lot of people currently use my application. Therefore, I added new features to it recently. However, the end user should grant access to additional scopes to use those features. One possible way to handle this is to ask the user to go to the Google Workspace Admin console (https://admin.google.com/) and find my application in the list of
Google Workspace Marketplace Apps. Then he should manually grant the required Google service APIs (OAuth scopes). But this is not transparent enough. As a result, the user experience is not optimal. Moreover, my application cannot deduce whether the user granted permissions.

The best approach is redirecting the user to the Google consent screen when he opens my web application. As a result, he will be aware of the new functionality and can automatically enable it by granting required OAuth scopes.

How can I obtain the consent screen for my application and the target user organization?


问:
which schema should be used in multi content pages?
I have a multi content page in my WordPress site. such as pics, article, video, infographic, etc.

فاران فارمد

which type of schema should I choose?

I choose article schema but what about those kind of pages that is really an article without video,...


问:
When building a native image I faced: Discovered a type for which getDeclaringClass0 cannot be called: x2006.sharedTypes.STConformanceClass
Framework: Quarkus

JVM: OpenJDK Runtime Environment GraalVM CE 22.3.0 (build 17.0.5+8-jvmci-22.3-b08)
OS: macOS Monterey, Chip: M2

Command to get this error: mvn clean package -Pnative -DskipTests

When building a native image I faced this error:

Error: Discovered a type for which getDeclaringClass0 cannot be called:
org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STConformanceClass$Enum. This error is reported at image build time because class org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STConformanceClass$Enum is registered for linking at image build time by command line
com.oracle.svm.core.util.UserError$UserException: Discovered a type for which getDeclaringClass0 cannot be called: org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STConformanceClass$Enum. This error is reported at image build time because class org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STConformanceClass$Enum is registered for linking at image build time by command line
    at org.graalvm.nativeimage.builder/com.oracle.svm.core.util.UserError.abort(UserError.java:85)
    at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.FallbackFeature.reportAsFallback(FallbackFeature.java:248)
    at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.runPointsToAnalysis(NativeImageGenerator.java:776)
    at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.doRun(NativeImageGenerator.java:578)
    at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.run(NativeImageGenerator.java:535)
    at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGeneratorRunner.buildImage(NativeImageGeneratorRunner.java:403)
    at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGeneratorRunner.build(NativeImageGeneratorRunner.java:580)
    at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGeneratorRunner.main(NativeImageGeneratorRunner.java:128)
Caused by: com.oracle.graal.pointsto.constraints.UnsupportedFeatureException: Discovered a type for which getDeclaringClass0 cannot be called: org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STConformanceClass$Enum. This error is reported at image build time because class org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STConformanceClass$Enum is registered for linking at image build time by command line
    at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.SVMHost.handleLinkageError(SVMHost.java:444)
```
<p>My problem is, when I'm trying to find the implementation of this class, I did not find anything. I know if I find the implementation and I add it to pom and reflect-config.json my problem be solved.</p>
<p>I tried to add
<code>--initialize-at-run-time=org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STConformanceClass</code>
into pom and this line into reflect-config.json</p>
```{
    "name": "org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STConformanceClass"
  }
```
<p>Update:</p>
<p>The problem is solved this way:</p>
```    <dependency>
          <groupId>org.apache.poi</groupId>
          <artifactId>poi-ooxml</artifactId>
          <version>5.2.3</version>
          <exclusions>
              <exclusion>
                  <groupId>org.apache.poi</groupId>
                  <artifactId>poi-ooxml-schemas</artifactId>
               </exclusion>
              <exclusion>
                  <groupId>org.apache.poi</groupId>
                  <artifactId>poi-ooxml-lite</artifactId>
              </exclusion>
          </exclusions>
      </dependency>
      <dependency>
           <groupId>org.apache.poi</groupId>
              <artifactId>poi-ooxml-full</artifactId>
          <version>5.2.3</version>
      </dependency>
```

Body:
Framework: Quarkus

JVM: OpenJDK Runtime Environment GraalVM CE 22.3.0 (build 17.0.5+8-jvmci-22.3-b08)
OS: macOS Monterey, Chip: M2

Command to get this error: mvn clean package -Pnative -DskipTests

When building a native image I faced this error:

Error: Discovered a type for which getDeclaringClass0 cannot be called:
org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STConformanceClass$Enum. This error is reported at image build time because class org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STConformanceClass$Enum is registered for linking at image build time by command line
com.oracle.svm.core.util.UserError$UserException: Discovered a type for which getDeclaringClass0 cannot be called: org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STConformanceClass$Enum. This error is reported at image build time because class org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STConformanceClass$Enum is registered for linking at image build time by command line
    at org.graalvm.nativeimage.builder/com.oracle.svm.core.util.UserError.abort(UserError.java:85)
    at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.FallbackFeature.reportAsFallback(FallbackFeature.java:248)
    at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.runPointsToAnalysis(NativeImageGenerator.java:776)
    at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.doRun(NativeImageGenerator.java:578)
    at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.run(NativeImageGenerator.java:535)
    at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGeneratorRunner.buildImage(NativeImageGeneratorRunner.java:403)
    at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGeneratorRunner.build(NativeImageGeneratorRunner.java:580)
    at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGeneratorRunner.main(NativeImageGeneratorRunner.java:128)
Caused by: com.oracle.graal.pointsto.constraints.UnsupportedFeatureException: Discovered a type for which getDeclaringClass0 cannot be called: org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STConformanceClass$Enum. This error is reported at image build time because class org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STConformanceClass$Enum is registered for linking at image build time by command line
    at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.SVMHost.handleLinkageError(SVMHost.java:444)

My problem is, when I'm trying to find the implementation of this class, I did not find anything. I know if I find the implementation and I add it to pom and reflect-config.json my problem be solved.

I tried to add
--initialize-at-run-time=org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STConformanceClass
into pom and this line into reflect-config.json

{
    "name": "org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STConformanceClass"
  }

Update:

The problem is solved this way:

    <dependency>
          <groupId>org.apache.poi</groupId>
          <artifactId>poi-ooxml</artifactId>
          <version>5.2.3</version>
          <exclusions>
              <exclusion>
                  <groupId>org.apache.poi</groupId>
                  <artifactId>poi-ooxml-schemas</artifactId>
               </exclusion>
              <exclusion>
                  <groupId>org.apache.poi</groupId>
                  <artifactId>poi-ooxml-lite</artifactId>
              </exclusion>
          </exclusions>
      </dependency>
      <dependency>
           <groupId>org.apache.poi</groupId>
              <artifactId>poi-ooxml-full</artifactId>
          <version>5.2.3</version>
      </dependency>


问:
Trying to scrape multiple webpages article text butstuck at this position where it says find() takes no keyword argument. What i m doin wrong?
```<code>articles = []
for text in text:
  articles. append(text. find(attrs= {"class" :"td-post-content"}).text)
TypeError                                 Traceback (most recent call last)
<ipython-input-46-875997e138e5> in <module>
      1 articles = []
      2 for text in text:
----> 3   articles.append(text.find(attrs= {"class":"td-post-content"}).text)

TypeError: find() takes no keyword arguments
</code>```


问:
Network Connection Issue + Blackberry
I am facing a network connection issue. My client has sent me following mail and I am having no idea what I should do in this condition

"One of our companies have asked if it would be possible for them to use their apps with the data going via a proxy. The hve disabled WAP on their BES so they are unable to use the application. I think in this instance the data needs to be routed through the BIS."

For using BIS , I have read that application needs to be approved by RIM and we need to append    a secret String provided by the RIM to the connection URL.

For BES we append ;deviceside=false in case of simulator.

For TCP we append ;deviceside=true to the connection URL.

For Wifiwe append ;interface=wifi to the connection URL.

What should we append in the case of BIS?

ContentLicense: CC BY-SA 3.0

Title: Network Connection Issue + Blackberry


问:
H5P Instance is duplicated in reactjs
I'm developing with h5p standalone plugin in react (nextjs), passing the path as prop to a Modal Component which render the h5p activity.

useEffect(() => {
    const initH5p = async (contentLocation) => {
    const { H5P: H5PStandalone } = require('h5p-standalone')
    const h5pPath = `https://cdn.thinkeyschool.com/h5p/${contentLocation}`

    const options = {
      id: 'THINKeyLesson',
      h5pJsonPath: h5pPath,
      frameJs: '/h5p/dist/frame.bundle.js',
      frameCss: '/h5p/dist/styles/h5p.css',
    }
    let element = document.getElementById('h5p_container')
    removeAllChildNodes(element)
    await new H5PStandalone(element, options)

    fireCompleteH5PTopic(H5P)
    setIsLoaderVisible(false)
    }
    initH5p(location)
  }, [location, session.data.user.id, course.slug, topic])```
</div>
</div>
</p>
<p>With that code, I get two h5p rendered in screen. So I'm using removeAllChildren() to eliminate them from the render.</p>
``` function removeAllChildNodes(parent) {
    console.log(parent)
    while (parent.firstChild) {
      parent.removeChild(parent.firstChild)
    }
  }
```
<p>That hack is working fine, but when I try to send the xAPI statement to my database, it fires twice</p>
```const fireCompleteH5PTopic = async (H5P) => {
    H5P.externalDispatcher.on("xAPI", (event) => {
      // console.log('event fired')
      if (event?.data?.statement?.result?.completion) {
        setCounter(counter + 1)
        completeH5PTopic(event, session.data.user.id, course.slug, topic)
        return true
      }
    })
  }
```

Any help regarding why it fires twice? I think it may be related to h5p rendering twice too.

Thanks in advance.

I tried using a state to render only once, but it is not working.

Title: H5P Instance is duplicated in reactjs

Body:
I'm developing with h5p standalone plugin in react (nextjs), passing the path as prop to a Modal Component which render the h5p activity.

useEffect(() => {
    const initH5p = async (contentLocation) => {
    const { H5P: H5PStandalone } = require('h5p-standalone')
    const h5pPath = `https://cdn.thinkeyschool.com/h5p/${contentLocation}`

    const options = {
      id: 'THINKeyLesson',
      h5pJsonPath: h5pPath,
      frameJs: '/h5p/dist/frame.bundle.js',
      frameCss: '/h5p/dist/styles/h5p.css',
    }
    let element = document.getElementById('h5p_container')
    removeAllChildNodes(element)
    await new H5PStandalone(element, options)

    fireCompleteH5PTopic(H5P)
    setIsLoaderVisible(false)
    }
    initH5p(location)
  }, [location, session.data.user.id, course.slug, topic])

With that code, I get two h5p rendered in screen. So I'm using removeAllChildren() to eliminate them from the render.

 function removeAllChildNodes(parent) {
    console.log(parent)
    while (parent.firstChild) {
      parent.removeChild(parent.firstChild)
    }
  }

That hack is working fine, but when I try to send the xAPI statement to my database, it fires twice

const fireCompleteH5PTopic = async (H5P) => {
    H5P.externalDispatcher.on("xAPI", (event) => {
      // console.log('event fired')
      if (event?.data?.statement?.result?.completion) {
        setCounter(counter + 1)
        completeH5PTopic(event, session.data.user.id, course.slug, topic)
        return true
      }
    })
  }

Any help regarding why it fires twice? I think it may be related to h5p rendering twice too.

Thanks in advance.

I tried using a state to render only once, but it is not working.


问:
$geoNear with pipeline from official documentation does not seem to work
I was browsing through documentation about geoNear examples, and this particular snippets does not work, raising error: $geoNear requires a 'near' option as an Array

Sample Link: https://www.mongodb.com/docs/manual/reference/operator/aggregation/geoNear/

Sample :

```<code>db.places.insertMany( [
   {
      name: "Central Park",
      location: { type: "Point", coordinates: [ -73.97, 40.77 ] },
      category: "Parks"
   },
   {
      name: "Sara D. Roosevelt Park",
      location: { type: "Point", coordinates: [ -73.9928, 40.7193 ] },
      category: "Parks"
   },
   {
      name: "Polo Grounds",
      location: { type: "Point", coordinates: [ -73.9375, 40.8303 ] },
      category: "Stadiums"
   }
] )
</code>```

Do the aggregation:

```<code>db.places.aggregate( [
   {
      $lookup: {
         from: "places",
         let: { pt: "$location" },
         pipeline: [
            {
               $geoNear: {
                  near: "$$pt",
                  distanceField: "distance"
               }
            }
         ],
         as: "joinedField"
      }
   },
   {
      $match: { name: "Sara D. Roosevelt Park" }
   }
] );
</code>```

What is the correct way to do the aggregation then?

Edit: MongoDB compass screen shot

Edit 2: the other approach I tried

The snippets I used on VS code playground:

```<code>use('hello');

db.world.drop();

db.world.insertMany([
  {
  'PRSN': '099HP0002',
  'address': 'nan',
  'applicantCategory': 'company',
  'applicantName': 'companyNameA',
  'buildingAdmins': 'nan',
  'buildingOwners': 'nan',
  'center': {'coordinates': [120.36521, 23.20558], 'type': 'Point'},
  'georeferencedParcels': ['433300860001'],
  },
  {
  'PRSN': '099HP0005',
  'address': 'nan',
  'applicantCategory': 'company',
  'applicantName': 'companyNameB',
  'buildingAdmins': 'nan',
  'buildingOwners': 'nan',
  'center': {'coordinates': [120.33333, 23.20555], 'type': 'Point'},
  'georeferencedParcels': ['433300860004'],
  },
  {
  'PRSN': '099HP0008',
  'address': 'nan',
  'applicantCategory': 'company',
  'applicantName': 'companyNameC',
  'buildingAdmins': 'nan',
  'buildingOwners': 'nan',
  'center': {'coordinates': [120.40000, 23.20551], 'type': 'Point'},
  'georeferencedParcels': ['433300860004'],
  }
]);

db.world.createIndex( { center: "2dsphere" } )

db.world.aggregate([
  {
    $lookup: {
      from: "world",
      let: {
        pt: "$center"
      },
      pipeline: [
        {
          $geoNear: {
            near: "$$pt",
            distanceField: "distance"
          }
        }
      ],
      as: "joinedField"
    }
  },
  {
    $match: {
      name: "companyNameB"
    }
  }
])

</code>```

Body:
I was browsing through documentation about geoNear examples, and this particular snippets does not work, raising error: $geoNear requires a 'near' option as an Array

Sample Link: https://www.mongodb.com/docs/manual/reference/operator/aggregation/geoNear/

Sample :

db.places.insertMany( [
   {
      name: "Central Park",
      location: { type: "Point", coordinates: [ -73.97, 40.77 ] },
      category: "Parks"
   },
   {
      name: "Sara D. Roosevelt Park",
      location: { type: "Point", coordinates: [ -73.9928, 40.7193 ] },
      category: "Parks"
   },
   {
      name: "Polo Grounds",
      location: { type: "Point", coordinates: [ -73.9375, 40.8303 ] },
      category: "Stadiums"
   }
] )

Do the aggregation:

db.places.aggregate( [
   {
      $lookup: {
         from: "places",
         let: { pt: "$location" },
         pipeline: [
            {
               $geoNear: {
                  near: "$$pt",
                  distanceField: "distance"
               }
            }
         ],
         as: "joinedField"
      }
   },
   {
      $match: { name: "Sara D. Roosevelt Park" }
   }
] );

What is the correct way to do the aggregation then?

Edit: MongoDB compass screen shot

Edit 2: the other approach I tried

The snippets I used on VS code playground:

use('hello');

db.world.drop();

db.world.insertMany([
  {
  'PRSN': '099HP0002',
  'address': 'nan',
  'applicantCategory': 'company',
  'applicantName': 'companyNameA',
  'buildingAdmins': 'nan',
  'buildingOwners': 'nan',
  'center': {'coordinates': [120.36521, 23.20558], 'type': 'Point'},
  'georeferencedParcels': ['433300860001'],
  },
  {
  'PRSN': '099HP0005',
  'address': 'nan',
  'applicantCategory': 'company',
  'applicantName': 'companyNameB',
  'buildingAdmins': 'nan',
  'buildingOwners': 'nan',
  'center': {'coordinates': [120.33333, 23.20555], 'type': 'Point'},
  'georeferencedParcels': ['433300860004'],
  },
  {
  'PRSN': '099HP0008',
  'address': 'nan',
  'applicantCategory': 'company',
  'applicantName': 'companyNameC',
  'buildingAdmins': 'nan',
  'buildingOwners': 'nan',
  'center': {'coordinates': [120.40000, 23.20551], 'type': 'Point'},
  'georeferencedParcels': ['433300860004'],
  }
]);

db.world.createIndex( { center: "2dsphere" } )

db.world.aggregate([
  {
    $lookup: {
      from: "world",
      let: {
        pt: "$center"
      },
      pipeline: [
        {
          $geoNear: {
            near: "$$pt",
            distanceField: "distance"
          }
        }
      ],
      as: "joinedField"
    }
  },
  {
    $match: {
      name: "companyNameB"
    }
  }
])


问:
Getting anonymous error on JoinEnrichment processor org.apache.calcite.sql.validate.SqlValidatorExceptionannot
I am getting error on JoinEnrichment and don't know why it is coming.

My query in JoinEnrichment :

```<code>SELECT original.*, enrichment.*
FROM original
FULL JOIN enrichment
ON original.name = enrichment.name
</code>```

Error

JoinEnrichment[id=a17b1f06-f80c-3641-945f-c2ff331f8028] Failed to join 'original' FlowFile FlowFile[filename=cmdbci-mtaas] and 'enrichment' FlowFile FlowFile[filename=cmdbci-mtaas]; routing to failure: java.sql.SQLException: Error while preparing statement [SELECT original., enrichment.
FROM original
FULL JOIN enrichment
ON original.name = enrichment.name]

Caused by: org.apache.calcite.runtime.CalciteContextException: From line 4, column 4 to line 4, column 34: Cannot apply '=' to arguments of type '<JAVATYPE(CLASS JAVA.LANG.OBJECT)> = <JAVATYPE(CLASS JAVA.LANG.STRING)>'. Supported form(s): '<COMPARABLE_TYPE> = <COMPARABLE_TYPE>'

Caused by: : Corg.apache.calcite.sql.validate.SqlValidatorExceptionannot apply '=' to arguments of type '<JAVATYPE(CLASS JAVA.LANG.OBJECT)> = <JAVATYPE(CLASS JAVA.LANG.STRING)>'. Supported form(s): '<COMPARABLE_TYPE> = <COMPARABLE_TYPE>'

Sample input from original

```<code>Location,Environment,ip_address,category,name,dv_sys_updated_on
"",,,Hardware,Ndiggan,2022-12-17 22:37:28
"",,,Hardware,class,2022-12-31 22:37:38
"",,,,Vlan2,2022-12-27 02:17:13
</code>```

Sample input from enrichment

```<code>Location,Environment,ip_address,category,name,dv_sys_updated_on
"",,,Hardware,vpna,2022-12-17 22:36:02
"",,,Hardware,dlcccno,2022-12-17 22:37:04
"",,,Hardware,Ndiggan,2022-12-17 22:37:28
</code>```

Body:
I am getting error on JoinEnrichment and don't know why it is coming.

My query in JoinEnrichment :

SELECT original.*, enrichment.*
FROM original
FULL JOIN enrichment
ON original.name = enrichment.name

Error

JoinEnrichment[id=a17b1f06-f80c-3641-945f-c2ff331f8028] Failed to join 'original' FlowFile FlowFile[filename=cmdbci-mtaas] and 'enrichment' FlowFile FlowFile[filename=cmdbci-mtaas]; routing to failure: java.sql.SQLException: Error while preparing statement [SELECT original., enrichment.
FROM original
FULL JOIN enrichment
ON original.name = enrichment.name]

Caused by: org.apache.calcite.runtime.CalciteContextException: From line 4, column 4 to line 4, column 34: Cannot apply '=' to arguments of type '<JAVATYPE(CLASS JAVA.LANG.OBJECT)> = <JAVATYPE(CLASS JAVA.LANG.STRING)>'. Supported form(s): '<COMPARABLE_TYPE> = <COMPARABLE_TYPE>'

Caused by: : Corg.apache.calcite.sql.validate.SqlValidatorExceptionannot apply '=' to arguments of type '<JAVATYPE(CLASS JAVA.LANG.OBJECT)> = <JAVATYPE(CLASS JAVA.LANG.STRING)>'. Supported form(s): '<COMPARABLE_TYPE> = <COMPARABLE_TYPE>'

Sample input from original

Location,Environment,ip_address,category,name,dv_sys_updated_on
"",,,Hardware,Ndiggan,2022-12-17 22:37:28
"",,,Hardware,class,2022-12-31 22:37:38
"",,,,Vlan2,2022-12-27 02:17:13

Sample input from enrichment

Location,Environment,ip_address,category,name,dv_sys_updated_on
"",,,Hardware,vpna,2022-12-17 22:36:02
"",,,Hardware,dlcccno,2022-12-17 22:37:04
"",,,Hardware,Ndiggan,2022-12-17 22:37:28


问:
How do I edit the label and x-axis of a laravel/chart.js boxplot?
Chart.js translation for plotting on frontend side in Laravel. There is a yield of 3 months dates and their datas. How should I fit charjs that overlap and not all dates are written at the end of x? (texts are overlapping, i dont want it, and I want all the dates to be on the x-axis, I think chartjs skipped it because couldn't fit it.) it is important can you contact with me

```<code> var myChart1 = new Chart(ctx1, {
        type: 'bar',
        data: {
                labels: dates,
                datasets: [{
        label: 'BACKLOG ON HOLD INCIDENTS AVG PERFORMANCE- BURSA',
        data: results,
        backgroundColor: [
            'rgba(76, 196, 23, 0.6)'

        ],
        borderColor: [
            'rgba(219, 249, 219, 1)',

        ],
        borderWidth: 1,
                }]
        },
        plugins: [ChartDataLabels],
        options: {

                plugins:{
                legend:{
                        display:true
                },
        datalabels:{
                color:'blue',
                anchor:'end',
        font:{
                weight:'bold',
                size:8
             }
                  }
        },
        scales: {
        y: {
            beginAtZero: true
           },
        x: {
            ticks: {
                maxRotation: 90,
                minRotation: 90,
                font: {
                size: 8,
            }
            }
           }
        },
        animation: {
            duration: 0
        }
        }
    });
</code>```

Body:
Chart.js translation for plotting on frontend side in Laravel. There is a yield of 3 months dates and their datas. How should I fit charjs that overlap and not all dates are written at the end of x? (texts are overlapping, i dont want it, and I want all the dates to be on the x-axis, I think chartjs skipped it because couldn't fit it.) it is important can you contact with me

 var myChart1 = new Chart(ctx1, {
        type: 'bar',
        data: {
                labels: dates,
                datasets: [{
        label: 'BACKLOG ON HOLD INCIDENTS AVG PERFORMANCE- BURSA',
        data: results,
        backgroundColor: [
            'rgba(76, 196, 23, 0.6)'

        ],
        borderColor: [
            'rgba(219, 249, 219, 1)',

        ],
        borderWidth: 1,
                }]
        },
        plugins: [ChartDataLabels],
        options: {

                plugins:{
                legend:{
                        display:true
                },
        datalabels:{
                color:'blue',
                anchor:'end',
        font:{
                weight:'bold',
                size:8
             }
                  }
        },
        scales: {
        y: {
            beginAtZero: true
           },
        x: {
            ticks: {
                maxRotation: 90,
                minRotation: 90,
                font: {
                size: 8,
            }
            }
           }
        },
        animation: {
            duration: 0
        }
        }
    });


问:
How could I do to mmap a large memory area with Anonymous Mappings but no-zero-filled to be done?
As *The Linux Programming Interface * said Anonymous Mappings: With both the MAP_ANONYMOUS and the /dev/zero techniques, the bytes of the resulting mapping are initialized to 0.

I want to mmap a memory area with very big size(1 GB). The source area is filled with my own data. But these data would be zero-filled in dest mmaped area if I use Anonymous mmap which will not use any File Descriptor.

HOW could I do to mmap a big size memory area with my own data still valid in dest area after mmap operation?

Or is there another way to achieve this goals?


问:
How to set font family in react js website globally?
I have issue to set helvetica neue font family globally. It gives error as: Failed to load resource: net::ERR_BLOCKED_BY_RESPONSE.NotSameOrigin.
Then I have used crossorigin="anonymous" with it but doesn't work and again gives error GET https://fonts.cdnfonts.com/css/helvetica-neue-9 net::ERR_ABORTED 503. How can I solve this issue?

In index.html I am using font inside Head tag as:

<link href="https://fonts.cdnfonts.com/css/helvetica-neue-9" rel="stylesheet" />

In index.css file I am using as:

body {
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue",
Helvetica, "Lucida Grande";
}

Error in console:


问:
Why does my for loop does not continue to execute with PyQt?
I am scraping a web page with PyQt. In order to facilitate this, I have constructed the following class:

```<code>class Client (QWebEnginePage):
def __init__(self, url):
    self.app = QApplication(sys.argv)
    QWebEnginePage.__init__(self)
    self.html = ''
    self.loadFinished.connect(self._on_load_finished)
    self.load(QUrl(url))
    self.app.exec_()

def _on_load_finished(self):
    self.html = self.toHtml(self.Callable)
    print('Load finished')

def Callable(self, html_str):
    self.html = html_str
    self.app.quit()
</code>```

I then use this class to obtain data from multiple subpages that I loop over with a for loop:

from config import o_u_types,countries,leagues,limited_league_countries,bookmakers

def getodds(url):

```<code>    for i in o_u_types:

        ou_i_df= pd.DataFrame()

        url_appendix="#over-under;2;{:.2f};0".format(i)
        o_u_type= i
        o_u_match_url= str(url)+str(url_appendix)
        print(o_u_match_url)
        ou_page=Client(o_u_match_url)

#Here some actions are performed, after which the output is store in a data frame (data_df) that is then appended to the master_df that stores the data across loops

       pd.concat([master_df,data_df])
    print(master_df)
    return master_df
</code>```

After opening the client with the individual match URL, i perform some further actions that should not be relevant to the issue (but happy to include them if needed)

This works fine for the first iteration, but execution always concludes without an error message before moving on to the second execution.

What might be the issue here?

Body:
I am scraping a web page with PyQt. In order to facilitate this, I have constructed the following class:

class Client (QWebEnginePage):
def __init__(self, url):
    self.app = QApplication(sys.argv)
    QWebEnginePage.__init__(self)
    self.html = ''
    self.loadFinished.connect(self._on_load_finished)
    self.load(QUrl(url))
    self.app.exec_()

def _on_load_finished(self):
    self.html = self.toHtml(self.Callable)
    print('Load finished')

def Callable(self, html_str):
    self.html = html_str
    self.app.quit()

I then use this class to obtain data from multiple subpages that I loop over with a for loop:

from config import o_u_types,countries,leagues,limited_league_countries,bookmakers

def getodds(url):

    for i in o_u_types:

        ou_i_df= pd.DataFrame()

        url_appendix="#over-under;2;{:.2f};0".format(i)
        o_u_type= i
        o_u_match_url= str(url)+str(url_appendix)
        print(o_u_match_url)
        ou_page=Client(o_u_match_url)

#Here some actions are performed, after which the output is store in a data frame (data_df) that is then appended to the master_df that stores the data across loops

       pd.concat([master_df,data_df])
    print(master_df)
    return master_df

After opening the client with the individual match URL, i perform some further actions that should not be relevant to the issue (but happy to include them if needed)

This works fine for the first iteration, but execution always concludes without an error message before moving on to the second execution.

What might be the issue here?