问:
dyld: lazy symbol binding failed: Symbol not found: _pthread_jit_write_protect_supported_np
i upgraded my node version but because my mac version was too old i had to downgrade it back to V16.16.0 (and used nvm use 16.16.0) because else it wouldn't work. Now i get this error when i try to run npm run dev to start my next.js app. How can i fix this? I also tried downgrading my node to 16.0.0 but that also didn't work, i also already removed the node_modules and package-lock.json and did npm install again. I also already did npm update and npm rebuild so im kinda lost now.

```<code>dyld: lazy symbol binding failed: Symbol not found: _pthread_jit_write_protect_supported_np
  Referenced from: /Users/user/project_folder/mysite.nl/node_modules/sharp/build/Release/../.././vendor/8.13.3/darwin-x64/lib/libvips-cpp.42.dylib
  Expected in: /usr/lib/libSystem.B.dylib

dyld: Symbol not found: _pthread_jit_write_protect_supported_np
  Referenced from: /Users/user/project_folder/mysite.nl/node_modules/sharp/build/Release/../.././vendor/8.13.3/darwin-x64/lib/libvips-cpp.42.dylib
  Expected in: /usr/lib/libSystem.B.dylib

Abort trap: 6
</code>```

Body:
i upgraded my node version but because my mac version was too old i had to downgrade it back to V16.16.0 (and used nvm use 16.16.0) because else it wouldn't work. Now i get this error when i try to run npm run dev to start my next.js app. How can i fix this? I also tried downgrading my node to 16.0.0 but that also didn't work, i also already removed the node_modules and package-lock.json and did npm install again. I also already did npm update and npm rebuild so im kinda lost now.

dyld: lazy symbol binding failed: Symbol not found: _pthread_jit_write_protect_supported_np
  Referenced from: /Users/user/project_folder/mysite.nl/node_modules/sharp/build/Release/../.././vendor/8.13.3/darwin-x64/lib/libvips-cpp.42.dylib
  Expected in: /usr/lib/libSystem.B.dylib

dyld: Symbol not found: _pthread_jit_write_protect_supported_np
  Referenced from: /Users/user/project_folder/mysite.nl/node_modules/sharp/build/Release/../.././vendor/8.13.3/darwin-x64/lib/libvips-cpp.42.dylib
  Expected in: /usr/lib/libSystem.B.dylib

Abort trap: 6


来源: stackexchange

问:
How to make an array of strings part of a react form to submit to prisma
I am trying to make an app with react, graphql, prisma, apollo and typescript.

I have a prisma model with:

```<code>model IssueGroup {
  id              String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
  title           String
  description     String
  issues          Issue[]
  categories      Category[]
  createdAt       DateTime @default(now()) @db.Timestamptz(6)
  updatedAt       DateTime @default(now()) @updatedAt @db.Timestamptz(6)
}

model Issue {
  id              String      @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
  title           String
  description     String
  issueGroup      IssueGroup?  @relation(fields: [issueGroupId], references: [id], onDelete: SetNull, onUpdate: Cascade)
  issueGroupId    String?      @db.Uuid
  subscribers     UserIssue[]
  categories      Category[]
  createdAt       DateTime    @default(now()) @db.Timestamptz(6)
  updatedAt       DateTime    @default(now()) @updatedAt @db.Timestamptz(6)
}
</code>```

I intend for issues to belong to issueGroups. Issues may or may not exist. Issues should be nullable in issueGroup - because there may not be any. I can't find a way to do either of setting issues to nullable in issueGroup, in the prisma model, or find a way to add them to the inputs so that I can actually add them in the form.

I have an api/inputs/create.input.ts file with:

```<code>import { IsNotEmpty } from "class-validator"
import { Field, InputType } from "type-graphql"

import { IssueGroup } from "../issueGroup.model"

@InputType()
export class IssueGroupInput implements Partial<IssueGroup> {
  @Field()
  @IsNotEmpty()
  title: string

  @IsNotEmpty()
  @Field()
  description: string

  @Field()
// this is wrong but i can't figure out why
  issues: string[]

// this is wrong but it's also a guess so I don't know if it is close to what's required
  @Field(type => Issue)
  issues: string[]
}
</code>```

the model has:

```<code>import * as Prisma from "@prisma/client"
import { Field, ObjectType } from "type-graphql"

import { BaseModel } from "../shared/base.model"

@ObjectType()
export class IssueGroup extends BaseModel implements Prisma.IssueGroup {
  @Field()
  title: string

  @Field()
  description: string

  @Field((type) => String)
  issues: Prisma.Issue[]
}
</code>```

I am trying to make a form as follows:

```<code>import * as React from "react"
import {  CgTrash, CgEditMarkup } from "react-icons/cg"
import { VscIssues } from "react-icons/vsc"

import { gql } from "@apollo/client"
import {
  Box,
  Button,
  ButtonGroup,
  IconButton,
  useDisclosure,
  Wrap,
  Stack,
  Table,
  Tbody,
  Tr,
  Td,
  TableContainer,
  Text
} from "@chakra-ui/react"
import Head from "next/head"
import { useToast } from "lib/hooks/useToast"
import { useForm } from "lib/hooks/useForm"
import { Form } from "components/Form"
import { FormError } from "components/FormError"
import { Input } from "components/Input"
import { Textarea } from "components/Textarea"

import {
    // IssueGroupInput,
    useAllIssueGroupsQuery,
    useCreateIssueGroupMutation,
    useUpdateIssueGroupMutation,
    useDeleteIssueGroupMutation,
    IssueGroup as IssueGroupGQLType,
}  from "lib/graphql"
//
// import { AdminCreateIssueGroupForm } from "components/AdminCreateIssueGroupForm"
// import { AdminUpdateIssueGroupForm } from "components/AdminUpdateIssueGroupForm"
import { AdminLayout } from "components/AdminLayout"
import { AuthedHomeLayout } from "components/AuthedHomeLayout"
import { Modal } from "components/Modal"
import Yup from "lib/yup"

// import { PartialCheckIcon } from "components/PartialCheckIcon"
// import { Search } from "components/Search"
// import type { Sort } from "components/Table"
// import { Column, getOrderBy, Table } from "components/Table"

const __ = gql`

  mutation CreateIssueGroup($data: IssueGroupInput!) {
    createIssueGroup(data: $data) {
      id
      title
    }
  }
  query AllIssueGroups {
    allIssueGroups {
      id
      title
    }
  }

  mutation updateIssueGroup($id: String!) {
    updateIssueGroup(id: $id) {
        id
        title
        issues
    }
  }

  mutation deleteIssueGroup($id: String!) {
    deleteIssueGroup(id: $id) {
      id
      title

    }
  }
`

const IssueGroupSchema = Yup.object().shape({
    title: Yup.string().required(),
    description: Yup.string().required(),
  })

function IssueGroups() {
  const toast = useToast()
  // const [search, setSearch] = React.useState("")
  // const [selectedIssueGroups, setSelectedIssueGroups] = React.useState<string[]>([])
  const modalProps = useDisclosure()
  const modalPropsUpdate = useDisclosure()
//   // const [sort, setSort] = React.useState<Sort>({ createdAt: SortOrder.Desc })
  const [createIssueGroup] = useCreateIssueGroupMutation()
  const [updateIssueGroup] = useUpdateIssueGroupMutation()
  const [deleteIssueGroup] = useDeleteIssueGroupMutation()
  const {  data: issueGroups } = useAllIssueGroupsQuery()
  const defaultValues = {
    title: "",
    description: "",
  }
  const form = useForm({ defaultValues, schema: IssueGroupSchema })
  const [selectedIssueGroup, setSelectedIssueGroup ] = React.useState<Omit<
  IssueGroupGQLType,
  "createdAt" | "updatedAt"
> | null>(null)

</code>```

// I tried adding | "issues" to the above list but my prisma thinks this cannot be null. I don't know how to direct it otherwise (so issues can be null inside IssueGroups)

```<code>    const { isOpen, onOpen, onClose } = useDisclosure()

    const onCreateSubmit = async (data: Yup.InferType<typeof IssueGroupSchema>) => {
        return await form.handler(
            () =>
            createIssueGroup({ variables: { data } }),
            {
                onSuccess: async (res, toast) => {
                    // await refetchAllIssueGroups()
                    toast({
                        title: "IssueGroup created",
                        status: "success",
                    })
                    form.reset()
                    onClose()
                }
            }
        )
    }

    const handleUpdateSubmit = async (data: Yup.InferType<typeof IssueGroupSchema>) => {
        console.log(selectedIssueGroup.id)
        return await form.handler(

            () =>

            updateIssueGroup({ variables: {
                id: selectedIssueGroup.id,
                issues: "none",
                data: { ...data }
            } }),
        )
    }

    const onDeleteIssueGroup = async (id: string) => {
        return
        form.handler(
            () =>
                deleteIssueGroup({ variables: { id } }),
                {
                onSuccess: async () => {
                await fetch("api/issueGroups", { method: "delete"})
                toast({
                    title: "IssueGroup deleted",
                    status: "success",
                })
                },
                // refetchAllIssueGroups()
            },
        )
    }
  return (
    <Box>

      <Wrap mb={4} spacing={2}>
        <Button
          onClick={modalProps.onOpen}
         >
          Create issueGroup
        </Button>
      </Wrap>

      <Modal {...modalProps} title="Create IssueGroup">
        <Form {...form} onSubmit={onCreateSubmit}>
            <Stack>
                <Input name="title" label="Title" />

                <Textarea name="description" label="Describe" rows={4} />

                <FormError />
                <ButtonGroup>
                <Button onClick={modalProps.onClose}>Cancel</Button>
                <Button
                    type="submit"
                >
                    Create
                </Button>
                </ButtonGroup>
            </Stack>
            </Form>
      </Modal>

        <TableContainer maxW="80%">
            <Table variant='simple'>
            <Tbody>
            {issueGroups?.allIssueGroups.map((issueGroup) => (
                <Tr key={issueGroup.id}>

                <Td>
                    <Text textStyle="h6">{issueGroup.title}</Text>

                </Td>
                <Td>
                    <ButtonGroup>
                    <IconButton
                        // onClick={modalPropsUpdate.onOpen}
                        onClick={() => {
                            setSelectedIssueGroup(issueGroup)
                            modalPropsUpdate.onOpen()
                        }}
                     />

                    {/* {
                        selectedIssueGroup && isOpen &&
                        <Modal issueGroup={selectedIssueGroup} isOpen={isOpen} onClose={onClose}  title="Edit IssueGroup"  >
                    } */}

                        <Modal {...modalPropsUpdate } title="Edit IssueGroup"  >

                            <Form {...form} onSubmit={handleUpdateSubmit}>
                                <Stack>
                                    <Input name="title" label="Title" />

                                    <Textarea name="description" label="Describe" rows={4} />

                                    <FormError />
                                    <ButtonGroup>
                                    <Button onClick={modalPropsUpdate.onClose}>Cancel</Button>
                                    <Button
                                        type="submit"
                                    >
                                        Save changes
                                    </Button>
                                    </ButtonGroup>
                                </Stack>
                            </Form>
                        </Modal>

                    <IconButton
                        onClick={() => onDeleteIssueGroup(issueGroup.id)}
                    />
                    </ButtonGroup>

                </Td>

                </Tr>
                ))}
            </Tbody>

            </Table>
        </TableContainer>

    </Box>
  )
}

IssueGroups.getLayout = (page: React.ReactNode) => <AuthedHomeLayout><AdminLayout>{page}</AdminLayout></AuthedHomeLayout>

export default IssueGroups
</code>```

I have tried adding 'issues' to the gql in the update mutation of this form, and in the variables submitted when the form is submitted, but the error says that the value cannot be null.

Inside the form itself, VSCode says:

Type '{ id: string; issues: string; data: { [x: string]: never; title:
string; description: string; }; }' is not assignable to type 'Exact<{
id: string; data: IssueGroupInput; }>'.   Object literal may only
specify known properties, and 'issues' does not exist in type 'Exact<{
id: string; data: IssueGroupInput; }>

I don't understand what this message means.

When I try to add issues: "" to the defaultValues setting in the form, I get an error that says:

No value exists in scope for the shorthand property 'issues'. Either
declare one or provide an initializer.ts(18004)

I don't understand what this message is asking me to do.

When I try to interact with the object in the console, I get an error that says:

message: 'Cannot return null for non-nullable field
IssueGroup.issues.'

ContentLicense: CC BY-SA 4.0

Body:
I am trying to make an app with react, graphql, prisma, apollo and typescript.

I have a prisma model with:

model IssueGroup {
  id              String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
  title           String
  description     String
  issues          Issue[]
  categories      Category[]
  createdAt       DateTime @default(now()) @db.Timestamptz(6)
  updatedAt       DateTime @default(now()) @updatedAt @db.Timestamptz(6)
}

model Issue {
  id              String      @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
  title           String
  description     String
  issueGroup      IssueGroup?  @relation(fields: [issueGroupId], references: [id], onDelete: SetNull, onUpdate: Cascade)
  issueGroupId    String?      @db.Uuid
  subscribers     UserIssue[]
  categories      Category[]
  createdAt       DateTime    @default(now()) @db.Timestamptz(6)
  updatedAt       DateTime    @default(now()) @updatedAt @db.Timestamptz(6)
}

I intend for issues to belong to issueGroups. Issues may or may not exist. Issues should be nullable in issueGroup - because there may not be any. I can't find a way to do either of setting issues to nullable in issueGroup, in the prisma model, or find a way to add them to the inputs so that I can actually add them in the form.

I have an api/inputs/create.input.ts file with:

import { IsNotEmpty } from "class-validator"
import { Field, InputType } from "type-graphql"

import { IssueGroup } from "../issueGroup.model"

@InputType()
export class IssueGroupInput implements Partial<IssueGroup> {
  @Field()
  @IsNotEmpty()
  title: string

  @IsNotEmpty()
  @Field()
  description: string

  @Field()
// this is wrong but i can't figure out why
  issues: string[]

// this is wrong but it's also a guess so I don't know if it is close to what's required
  @Field(type => Issue)
  issues: string[]
}

the model has:

import * as Prisma from "@prisma/client"
import { Field, ObjectType } from "type-graphql"

import { BaseModel } from "../shared/base.model"

@ObjectType()
export class IssueGroup extends BaseModel implements Prisma.IssueGroup {
  @Field()
  title: string

  @Field()
  description: string

  @Field((type) => String)
  issues: Prisma.Issue[]
}

I am trying to make a form as follows:

import * as React from "react"
import {  CgTrash, CgEditMarkup } from "react-icons/cg"
import { VscIssues } from "react-icons/vsc"

import { gql } from "@apollo/client"
import {
  Box,
  Button,
  ButtonGroup,
  IconButton,
  useDisclosure,
  Wrap,
  Stack,
  Table,
  Tbody,
  Tr,
  Td,
  TableContainer,
  Text
} from "@chakra-ui/react"
import Head from "next/head"
import { useToast } from "lib/hooks/useToast"
import { useForm } from "lib/hooks/useForm"
import { Form } from "components/Form"
import { FormError } from "components/FormError"
import { Input } from "components/Input"
import { Textarea } from "components/Textarea"

import {
    // IssueGroupInput,
    useAllIssueGroupsQuery,
    useCreateIssueGroupMutation,
    useUpdateIssueGroupMutation,
    useDeleteIssueGroupMutation,
    IssueGroup as IssueGroupGQLType,
}  from "lib/graphql"
//
// import { AdminCreateIssueGroupForm } from "components/AdminCreateIssueGroupForm"
// import { AdminUpdateIssueGroupForm } from "components/AdminUpdateIssueGroupForm"
import { AdminLayout } from "components/AdminLayout"
import { AuthedHomeLayout } from "components/AuthedHomeLayout"
import { Modal } from "components/Modal"
import Yup from "lib/yup"

// import { PartialCheckIcon } from "components/PartialCheckIcon"
// import { Search } from "components/Search"
// import type { Sort } from "components/Table"
// import { Column, getOrderBy, Table } from "components/Table"

const __ = gql`

  mutation CreateIssueGroup($data: IssueGroupInput!) {
    createIssueGroup(data: $data) {
      id
      title
    }
  }
  query AllIssueGroups {
    allIssueGroups {
      id
      title
    }
  }

  mutation updateIssueGroup($id: String!) {
    updateIssueGroup(id: $id) {
        id
        title
        issues
    }
  }

  mutation deleteIssueGroup($id: String!) {
    deleteIssueGroup(id: $id) {
      id
      title

    }
  }
`

const IssueGroupSchema = Yup.object().shape({
    title: Yup.string().required(),
    description: Yup.string().required(),
  })

function IssueGroups() {
  const toast = useToast()
  // const [search, setSearch] = React.useState("")
  // const [selectedIssueGroups, setSelectedIssueGroups] = React.useState<string[]>([])
  const modalProps = useDisclosure()
  const modalPropsUpdate = useDisclosure()
//   // const [sort, setSort] = React.useState<Sort>({ createdAt: SortOrder.Desc })
  const [createIssueGroup] = useCreateIssueGroupMutation()
  const [updateIssueGroup] = useUpdateIssueGroupMutation()
  const [deleteIssueGroup] = useDeleteIssueGroupMutation()
  const {  data: issueGroups } = useAllIssueGroupsQuery()
  const defaultValues = {
    title: "",
    description: "",
  }
  const form = useForm({ defaultValues, schema: IssueGroupSchema })
  const [selectedIssueGroup, setSelectedIssueGroup ] = React.useState<Omit<
  IssueGroupGQLType,
  "createdAt" | "updatedAt"
> | null>(null)

// I tried adding | "issues" to the above list but my prisma thinks this cannot be null. I don't know how to direct it otherwise (so issues can be null inside IssueGroups)

    const { isOpen, onOpen, onClose } = useDisclosure()

    const onCreateSubmit = async (data: Yup.InferType<typeof IssueGroupSchema>) => {
        return await form.handler(
            () =>
            createIssueGroup({ variables: { data } }),
            {
                onSuccess: async (res, toast) => {
                    // await refetchAllIssueGroups()
                    toast({
                        title: "IssueGroup created",
                        status: "success",
                    })
                    form.reset()
                    onClose()
                }
            }
        )
    }

    const handleUpdateSubmit = async (data: Yup.InferType<typeof IssueGroupSchema>) => {
        console.log(selectedIssueGroup.id)
        return await form.handler(

            () =>

            updateIssueGroup({ variables: {
                id: selectedIssueGroup.id,
                issues: "none",
                data: { ...data }
            } }),
        )
    }

    const onDeleteIssueGroup = async (id: string) => {
        return
        form.handler(
            () =>
                deleteIssueGroup({ variables: { id } }),
                {
                onSuccess: async () => {
                await fetch("api/issueGroups", { method: "delete"})
                toast({
                    title: "IssueGroup deleted",
                    status: "success",
                })
                },
                // refetchAllIssueGroups()
            },
        )
    }
  return (
    <Box>

      <Wrap mb={4} spacing={2}>
        <Button
          onClick={modalProps.onOpen}
         >
          Create issueGroup
        </Button>
      </Wrap>

      <Modal {...modalProps} title="Create IssueGroup">
        <Form {...form} onSubmit={onCreateSubmit}>
            <Stack>
                <Input name="title" label="Title" />

                <Textarea name="description" label="Describe" rows={4} />

                <FormError />
                <ButtonGroup>
                <Button onClick={modalProps.onClose}>Cancel</Button>
                <Button
                    type="submit"
                >
                    Create
                </Button>
                </ButtonGroup>
            </Stack>
            </Form>
      </Modal>

        <TableContainer maxW="80%">

            {issueGroups?.allIssueGroups.map((issueGroup) => (

                    <Text textStyle="h6">{issueGroup.title}</Text>

                    <ButtonGroup>
                    <IconButton
                        // onClick={modalPropsUpdate.onOpen}
                        onClick={() => {
                            setSelectedIssueGroup(issueGroup)
                            modalPropsUpdate.onOpen()
                        }}
                     />

                    {/* {
                        selectedIssueGroup && isOpen &&
                        <Modal issueGroup={selectedIssueGroup} isOpen={isOpen} onClose={onClose}  title="Edit IssueGroup"  >
                    } */}

                        <Modal {...modalPropsUpdate } title="Edit IssueGroup"  >

                            <Form {...form} onSubmit={handleUpdateSubmit}>
                                <Stack>
                                    <Input name="title" label="Title" />

                                    <Textarea name="description" label="Describe" rows={4} />

                                    <FormError />
                                    <ButtonGroup>
                                    <Button onClick={modalPropsUpdate.onClose}>Cancel</Button>
                                    <Button
                                        type="submit"
                                    >
                                        Save changes
                                    </Button>
                                    </ButtonGroup>
                                </Stack>
                            </Form>
                        </Modal>

                    <IconButton
                        onClick={() => onDeleteIssueGroup(issueGroup.id)}
                    />
                    </ButtonGroup>

                ))}

        </TableContainer>

    </Box>
  )
}

IssueGroups.getLayout = (page: React.ReactNode) => <AuthedHomeLayout><AdminLayout>{page}</AdminLayout></AuthedHomeLayout>

export default IssueGroups

I have tried adding 'issues' to the gql in the update mutation of this form, and in the variables submitted when the form is submitted, but the error says that the value cannot be null.

Inside the form itself, VSCode says:

Type '{ id: string; issues: string; data: { [x: string]: never; title:
string; description: string; }; }' is not assignable to type 'Exact<{
id: string; data: IssueGroupInput; }>'.   Object literal may only
specify known properties, and 'issues' does not exist in type 'Exact<{
id: string; data: IssueGroupInput; }>

I don't understand what this message means.

When I try to add issues: "" to the defaultValues setting in the form, I get an error that says:

No value exists in scope for the shorthand property 'issues'. Either
declare one or provide an initializer.ts(18004)

I don't understand what this message is asking me to do.

When I try to interact with the object in the console, I get an error that says:

message: 'Cannot return null for non-nullable field
IssueGroup.issues.'


问:
How do I equally divide an iterator into N chunks?
I want to divide an iterator into N equal chunks. The chunks themselves need to be iterators.

Here's some examples of what I want to achieve:

iter1 = iter(range(10))
chunks = split_n(iter1, n=2)

outputs iterator:
[[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]]

iter2 = iter(range(20))
chunks = split_n(iter2, n=4)

outputs iterator:
[[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]]
```
<p>If an iterator is not evenly divisible, I want the remaining elements to be spread out so that the chunks are "as equal" as possible.</p>
<pre class="lang-py prettyprint-override"><code>iter3 = iter(range(30))
chunks = split_n(iter3, n=4)

outputs iterator:
[[0, 1, 2, 3, 4, 5, 6, 7],
[8, 9, 10, 11, 12, 13, 14, 15],
[16, 17, 18, 19, 20, 21, 22],
[23, 24, 25, 26, 27, 28, 29]]
</code>```

One important caveat is that at no point should an iterator be converted to a list, as the iterators can be very huge and it would simply consume too much memory.

Body:
I want to divide an iterator into N equal chunks. The chunks themselves need to be iterators.

Here's some examples of what I want to achieve:

iter1 = iter(range(10))
chunks = split_n(iter1, n=2)

outputs iterator:
[[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]]

iter2 = iter(range(20))
chunks = split_n(iter2, n=4)

outputs iterator:
[[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]]

If an iterator is not evenly divisible, I want the remaining elements to be spread out so that the chunks are "as equal" as possible.

iter3 = iter(range(30))
chunks = split_n(iter3, n=4)

outputs iterator:
[[0, 1, 2, 3, 4, 5, 6, 7],
[8, 9, 10, 11, 12, 13, 14, 15],
[16, 17, 18, 19, 20, 21, 22],
[23, 24, 25, 26, 27, 28, 29]]

One important caveat is that at no point should an iterator be converted to a list, as the iterators can be very huge and it would simply consume too much memory.


问:
Request flow when AWS WAF, ALB associated and ALB 4xx
We have a server configured under a ALB associated with a WAF

As the underlying service receives requests for your web sites, it forwards those requests to AWS WAF for inspection against your rules. Once a request meets a condition defined in your rules, AWS WAF instructs the underlying service to either block or allow the request based on the action you define.

Above is mentioned in AWS FAQ and according to that I have a understanding that requests first comes to ALB and then forward to WAF.

My questions are in my environment I see some bad requests comes and returns 400 on ALB. they are not counted in WAF so is that mean bad requests are process in ALB? Bad requests are not forwarded to WAF? If I want to forward all the ALB request to WAF is it possible?


问:
How can I simulate autoscaling backends with logs pulled into a DataFrame?
I'm attempting to use request logs to simulate costs and resources used by auto-scaling a dynamic number of backend service pools. My use case is specific to Google Cloud Run, but there are similar models in use by systems like Kubernetes.

In a fully on-demand Cloud Run service deployment, a load balancer distributes requests to a pool of containers that may have as few as zero active instances, up to a configurable maximum. Each container in the service pool is identical (in terms of resources, configuration, etc.) and has a fixed number of maximum concurrent requests. Containers are active for whole number multiples of 100ms intervals.

These 100ms intervals are not aligned to seconds, but that's the best I've accomplished so far with my limited Pandas knowledge. The issue is that this overcounts when, say, a request arrives at t=50ms and lasts for a 90ms duration. This should only use one container for one 100ms interval, but my approach treats the container as active for both the 0-100ms and 100-200ms intervals, as it straddles both.

My logs have a starting timestamp and duration, which I start by transforming into absolute starting and ending timestamps:

```<code>time_boundaries_df = pd.read_csv(request_log_filename, index_col=None, header=0, \
    dtype={'duration':'int64'})
time_boundaries_df['start_time'] = pd.to_datetime(time_boundaries_df['start_time'])
time_boundaries_df['duration']   = pd.to_timedelta(time_boundaries_df['duration'], unit='ms')
time_boundaries_df['end_time']   = time_boundaries_df['start_time'] + time_boundaries_df['duration']
</code>```

I'm aware that the date interpretation here is slow, but the format in the logs isn't consistent enough to use format=DATE_FORMAT.

Once I have the absolute start/end of each request, I explode each request into second-aligned 100ms windows. At this point, my model is overcounting many requests due to misalignment with the windows (the start=50ms, duration=90ms case, which is a contrived case where the overcount is 100%).

```<code>active_windows_df['active_window'] = active_windows_df.parallel_apply( \
    lambda row: pd.date_range(row['start_time'], row['end_time'], freq='100ms'), axis=1)
active_windows_df = active_windows_df.explode('active_window', ignore_index=True)
active_windows_df['active_window'] = active_windows_df['active_window'].dt.floor('100ms')
active_windows_df = active_windows_df.drop(columns=['start_time', 'duration', 'end_time'])
</code>```

Finally, I'm counting container concurrency for each service pool via overlaps:

```<code># Convert each aligned time window with request concurrency for each service pool
# (with a pool defined as a unique site_id/env_id pair).
container_concurrency_df = active_windows_df.groupby(['site_id', 'env_id', 'active_window']) \
    .size().reset_index(name='concurrency')

# Convert request concurrency to container concurrency by dividing
# by the concurrency each container supports and taking the ceiling.
container_concurrency_df['concurrency'] = np.ceil(container_concurrency_df['concurrency'] \
    .div(CONTAINER_CONCURRENCY))

# Finally, determine the number of 100ms slices each service pool would have used
# for the entire simulation.
container_concurrency_df = container_concurrency_df.groupby(['site_id', 'env_id'])['concurrency'] \
    .sum().reset_index(name='container_slices')
</code>```

Because most requests are actually 400ms+ (since any single request can misalign to add up to one additional 100ms slot), the misalignment overcounting is probably limited to 25%, but I'd still like to solve it.

The Real Question

Is it possible for Pandas to count overlaps of rolling, dynamic 100ms windows rather than the alignment model I'm trying?

Finding a Correct Solution

A correct solution should fix the start=50ms, duration=90ms case by using only one 100ms container, and that container should also count as handling other requests (up to its concurrency limit) while it's active.

A correct solution should also only use one container for 300ms when:

Request A: start=50ms, duration=90ms

Request B: start=190ms, duration=50ms

A correct solution should also only use one container (assuming concurrency at least two) for 100ms when:

Request A: start=50ms, duration=90ms

Request B: start=60ms, duration=50ms

Google's own visualization of billable container time may be helpful. I'm simulating the "CPU only during requests" model.

Body:
I'm attempting to use request logs to simulate costs and resources used by auto-scaling a dynamic number of backend service pools. My use case is specific to Google Cloud Run, but there are similar models in use by systems like Kubernetes.

In a fully on-demand Cloud Run service deployment, a load balancer distributes requests to a pool of containers that may have as few as zero active instances, up to a configurable maximum. Each container in the service pool is identical (in terms of resources, configuration, etc.) and has a fixed number of maximum concurrent requests. Containers are active for whole number multiples of 100ms intervals.

These 100ms intervals are not aligned to seconds, but that's the best I've accomplished so far with my limited Pandas knowledge. The issue is that this overcounts when, say, a request arrives at t=50ms and lasts for a 90ms duration. This should only use one container for one 100ms interval, but my approach treats the container as active for both the 0-100ms and 100-200ms intervals, as it straddles both.

My logs have a starting timestamp and duration, which I start by transforming into absolute starting and ending timestamps:

time_boundaries_df = pd.read_csv(request_log_filename, index_col=None, header=0, \
    dtype={'duration':'int64'})
time_boundaries_df['start_time'] = pd.to_datetime(time_boundaries_df['start_time'])
time_boundaries_df['duration']   = pd.to_timedelta(time_boundaries_df['duration'], unit='ms')
time_boundaries_df['end_time']   = time_boundaries_df['start_time'] + time_boundaries_df['duration']

I'm aware that the date interpretation here is slow, but the format in the logs isn't consistent enough to use format=DATE_FORMAT.

Once I have the absolute start/end of each request, I explode each request into second-aligned 100ms windows. At this point, my model is overcounting many requests due to misalignment with the windows (the start=50ms, duration=90ms case, which is a contrived case where the overcount is 100%).

active_windows_df['active_window'] = active_windows_df.parallel_apply( \
    lambda row: pd.date_range(row['start_time'], row['end_time'], freq='100ms'), axis=1)
active_windows_df = active_windows_df.explode('active_window', ignore_index=True)
active_windows_df['active_window'] = active_windows_df['active_window'].dt.floor('100ms')
active_windows_df = active_windows_df.drop(columns=['start_time', 'duration', 'end_time'])

Finally, I'm counting container concurrency for each service pool via overlaps:

# Convert each aligned time window with request concurrency for each service pool
# (with a pool defined as a unique site_id/env_id pair).
container_concurrency_df = active_windows_df.groupby(['site_id', 'env_id', 'active_window']) \
    .size().reset_index(name='concurrency')

# Convert request concurrency to container concurrency by dividing
# by the concurrency each container supports and taking the ceiling.
container_concurrency_df['concurrency'] = np.ceil(container_concurrency_df['concurrency'] \
    .div(CONTAINER_CONCURRENCY))

# Finally, determine the number of 100ms slices each service pool would have used
# for the entire simulation.
container_concurrency_df = container_concurrency_df.groupby(['site_id', 'env_id'])['concurrency'] \
    .sum().reset_index(name='container_slices')

Because most requests are actually 400ms+ (since any single request can misalign to add up to one additional 100ms slot), the misalignment overcounting is probably limited to 25%, but I'd still like to solve it.

The Real Question

Is it possible for Pandas to count overlaps of rolling, dynamic 100ms windows rather than the alignment model I'm trying?

Finding a Correct Solution

A correct solution should fix the start=50ms, duration=90ms case by using only one 100ms container, and that container should also count as handling other requests (up to its concurrency limit) while it's active.

A correct solution should also only use one container for 300ms when:

Request A: start=50ms, duration=90ms

Request B: start=190ms, duration=50ms

A correct solution should also only use one container (assuming concurrency at least two) for 100ms when:

Request A: start=50ms, duration=90ms

Request B: start=60ms, duration=50ms

Google's own visualization of billable container time may be helpful. I'm simulating the "CPU only during requests" model.


问:
Is there any optimization solution based on Scikit-learn MiniBatchKMeans?
The sparse samples with a scale size of (trillion, 80 -> feature number) are pending to be clustered. The current scheme is to split it into several pieces. However, the total time consumption still cannot satisfy the requirement of the project.

I have tried multiple libraries worked on standalone, and Sklearn has the best performance. Is any optimization / acceleration strategy based on the source code of Sklearn to enhance the time performance further?


问:
Is it possible to run a command from a pip installed python cli package within a node package?
I want to use the cli commands from openAI's python package in the cli of my node package. Is this possible?

From what I've looked up, I know you can run general shell commands in javascript using the child_process module. Is there a way I can somehow include the python package as a dependency that gets installed along with my node package, so that I can run its CLI commands using child_process?


问:
How to disable the white boxes for Astro in vscode?
screenshot of issue

In Astro specifically, whenever I click a div, all the divs in the whole file get a white box around them. I imagine it's vscode not playing nice with Astro just yet. I have the official Astro extension installed and am trying different things (listed below). Has anyone else encountered this?

I tried changing various highlight settings, tried changing matching settings. None seemed to change anything. This appears to be language/file specific because it doesn't happen in conventional HTML files.

I also tried this, base on a previous post:

```<code>  "[astro]": {
    "editor.matchBrackets": "never"
  },
</code>```

As well as changing the highlighter for One Dark Pro

Body:
screenshot of issue

In Astro specifically, whenever I click a div, all the divs in the whole file get a white box around them. I imagine it's vscode not playing nice with Astro just yet. I have the official Astro extension installed and am trying different things (listed below). Has anyone else encountered this?

I tried changing various highlight settings, tried changing matching settings. None seemed to change anything. This appears to be language/file specific because it doesn't happen in conventional HTML files.

I also tried this, base on a previous post:

  "[astro]": {
    "editor.matchBrackets": "never"
  },

As well as changing the highlighter for One Dark Pro


问:
dcc.Upload to create dcc.graph, but how is placeholder dcc.graph already in layout updated?
I'm using dcc.Upload to read data from a spreadsheet.  That data is manipulated, put into a pandas data frame, and then px.line is created.  I wish to pass px.line to a dcc.Graph in my layout.  The graph can be displayed with .show() but not in the dcc.Graph created in my layout.

Intuitively, I simply want to update dcc.Graph in my layout, but that doesn't seem possible without a callback.  I can return px.line to the function associated with dcc.Upload, but I can't get it from there to the dcc.Graph I wish to update.  Adding a second output to dcc.Upload to update dcc.Graph in my layout doesn't work.

Essentially, I'm trying to update a graph by pointing to a spreadsheet with dcc.Upload.

Any help greatly appreciated.

Thanks, little_old_man

As mentioned, I tried adding a second output to the dcc.Upload callback to update dcc.Graph in my layout, but that led to an error.

I've looked at dcc.Interval to poll for some signal to update the graph independent of any user input.  Pointing to the spreadsheet in dcc.Upload is the user input.

I'm still stuck moving the data created from the input spreadsheet outside the scope of dcc.Upload to the dcc.Graph in my  layout.  Is dcc.Store needed?


问:
npm ERR! [nodegit] ERROR - finished with error code: 1 (wsl)
I get this error when I run npm i in wsl, I don't know how to fix it:

```<code>npm ERR! gyp ERR! cwd /home/server/RbxJs2016-main/node_modules/nodegit
npm ERR! gyp
npm ERR! ERR! node -v v17.0.0
npm ERR! gyp ERR! node-gyp -v v8.2.0
npm ERR! gyp
npm ERR! ERR! not ok
npm ERR! node-pre-gyp
npm ERR! ERR! build error
npm ERR! node-pre-gyp
npm ERR! ERR! stack Error: Failed to execute '/usr/local/bin/node /usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js configure --fallback-to-build --module=/home/server/RbxJs2016-main/node_modules/nodegit/build/Release/nodegit.node --module_name=nodegit --module_path=/home/server/RbxJs2016-main/node_modules/nodegit/build/Release --napi_version=8 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v102' (1)
npm ERR! node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (/home/server/RbxJs2016-main/node_modules/@mapbox/node-pre-gyp/lib/util/compile.js:89:23)
npm ERR! node-pre-gyp ERR! stack     at ChildProcess.emit (node:events:390:28)
npm ERR! node-pre-gyp ERR! stack
npm ERR! at maybeClose (node:internal/child_process:1062:16)
npm ERR! node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:301:5)
npm ERR! node-pre-gyp
npm ERR! ERR! System Linux 5.10.102.1-microsoft-standard-WSL2
npm ERR! node-pre-gyp ERR! command "/usr/local/bin/node" "/home/server/RbxJs2016-main/node_modules/.bin/node-pre-gyp" "install" "--fallback-to-build"
npm ERR! node-pre-gyp ERR! cwd /home/server/RbxJs2016-main/node_modules/nodegit
npm ERR! node-pre-gyp ERR! node -v v17.0.0
npm ERR! node-pre-gyp ERR! node-pre-gyp -v v1.0.9
npm ERR! node-pre-gyp ERR!
npm ERR! not ok
npm ERR! [nodegit] ERROR - Could not finish install
npm ERR! [nodegit] ERROR - finished with error code: 1
</code>```

I've tried several things but it won't work!
Im using WSL Ubuntu 22.04 LTS, and node 16.19.0
the problem seems to come from node-gyp but I don't know how to fix it

Body:
I get this error when I run npm i in wsl, I don't know how to fix it:

npm ERR! gyp ERR! cwd /home/server/RbxJs2016-main/node_modules/nodegit
npm ERR! gyp
npm ERR! ERR! node -v v17.0.0
npm ERR! gyp ERR! node-gyp -v v8.2.0
npm ERR! gyp
npm ERR! ERR! not ok
npm ERR! node-pre-gyp
npm ERR! ERR! build error
npm ERR! node-pre-gyp
npm ERR! ERR! stack Error: Failed to execute '/usr/local/bin/node /usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js configure --fallback-to-build --module=/home/server/RbxJs2016-main/node_modules/nodegit/build/Release/nodegit.node --module_name=nodegit --module_path=/home/server/RbxJs2016-main/node_modules/nodegit/build/Release --napi_version=8 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v102' (1)
npm ERR! node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (/home/server/RbxJs2016-main/node_modules/@mapbox/node-pre-gyp/lib/util/compile.js:89:23)
npm ERR! node-pre-gyp ERR! stack     at ChildProcess.emit (node:events:390:28)
npm ERR! node-pre-gyp ERR! stack
npm ERR! at maybeClose (node:internal/child_process:1062:16)
npm ERR! node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:301:5)
npm ERR! node-pre-gyp
npm ERR! ERR! System Linux 5.10.102.1-microsoft-standard-WSL2
npm ERR! node-pre-gyp ERR! command "/usr/local/bin/node" "/home/server/RbxJs2016-main/node_modules/.bin/node-pre-gyp" "install" "--fallback-to-build"
npm ERR! node-pre-gyp ERR! cwd /home/server/RbxJs2016-main/node_modules/nodegit
npm ERR! node-pre-gyp ERR! node -v v17.0.0
npm ERR! node-pre-gyp ERR! node-pre-gyp -v v1.0.9
npm ERR! node-pre-gyp ERR!
npm ERR! not ok
npm ERR! [nodegit] ERROR - Could not finish install
npm ERR! [nodegit] ERROR - finished with error code: 1

I've tried several things but it won't work!
Im using WSL Ubuntu 22.04 LTS, and node 16.19.0
the problem seems to come from node-gyp but I don't know how to fix it


问:
I'm lost as to how to access my MySQL database from my Vercel Deployed Next.js App on other devices or computers that are not my local computer
I have created a database of flashcards using MySQL workbench. I have set up the localhost in workbench so I can access the database from my app when I open my app on my localhost:3000.

When I deploy my Next.js app on Vercel I open the page through the vercel weblink and everything works –  I guess this is beacuse it is on the same computer that is hosting the local server.

However, when I open the same weblink on my phone or another computer I am getting empty spaces where the flashcards from the database usually are.

I tried to set up a remote server in workbench (i don't know if that is the correct course of action) , however I could not get it to work.

If someone could just push me in the right direction as to what I need to learn or do in order to access the Mysql database I've created on my computer from anywhere on any device.


问:
Creating tls secrets in Kubernetes from Azure Vault Certificates in Go
I could use the Azure Key Vault provider for Secrets Store CSI driver (https://learn.microsoft.com/en-us/azure/aks/csi-secrets-store-driver)

but I need to have a bit more control over the certificates via a custom k8 management API am developing for my use case. I had some challenges with this.

I think I have a good enough solution but want to put it out in the world for comment from others that may have done this in the past.

here is what I did...

When one creates the certificates (or uploads them) in Azure vault the values are stored in secrets. I used the Azure sdk for Go to get them

I use base64 package to decode what Azure sends me (a PFX containing private and public keys

I use pkcs12 package pkcs12.toPEM function to break it apart into an array of pem.Block.

Each block has a value that contains headers in the value

I need to strip the headers out before I use them in the kubernetes secret

```<code>package secretcreator

import (
    "context"
    "encoding/base64"
    "encoding/pem"
    "log"
    "time"

    "github.com/Azure/azure-sdk-for-go/sdk/keyvault/azcertificates"
    "github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets"
    "golang.org/x/crypto/pkcs12"
    v1 "k8s.io/api/core/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
)

type MyStruct struct {
    kubeClientSet          *kubernetes.Clientset
    azureVaultSecrets      *azsecrets.Client
    azureVaultCertificates *azcertificates.Client
    beNamespace            *v1.Namespace
    identitySecrests       *v1.Secret
}

func (t *MyStruct) createSecrets() error {

    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()

    //tlsSecret.value is a base64 encoded PEM/PFX containing PRIVATE KEY and CERTIFICATES blocks
    tlsSecret, err := t.azureVaultSecrets.GetSecret(ctx, `myCertName`, ``, nil)
    if err != nil {
        log.Printf(`Failed to retrieve cert :%s`, err.Error())
        return err
    }

    //pfxBytes is the Byte representation of the string stored in tlsSecret.Value
    pfxBytes, err := base64.StdEncoding.Strict().DecodeString(*tlsSecret.Value)
    if err != nil {
        log.Printf(`Failed to decode cert PFX:%s`, err.Error())
        return err
    }
    // pemBlocks is a array of *pem.Block - in my case I have 1 PRIVATE KEY Block and three CERTIFICATE Blocks
    //the blocks have headers too that look something like this on the PRIVATE KEY, after encoding the encoded string looks like this
    //
    // -----BEGIN PRIVATE KEY-----
    // Microsoft CSP Name: Microsoft Enhanced Cryptographic Provider v1.0
    // friendlyName: {D06B3D5A-98D1-45F1-A8C2-DC091232D6A7}
    // localKeyId: 01000000
    //
    // MIIEAI.......ymfjsQ==
    // -----END PRIVATE KEY-----
    pemBlocks, err := pkcs12.ToPEM(pfxBytes, "")
    if err != nil {
        log.Printf(`Failed to decode key or cert from PEM Blocks:%s`, err.Error())
        return err
    }

    // k8 needs to store TLS in a secret with key value pairs in the data - one for tls.key and the other for tls.crt
    // this code iterates through the blocks, looks at the type of data stored and breaks it up into tls.key and tls.crt
    // k8.nginx does not like the headers for some reason - so i strip them out using base64.StdEncoding.Encode to string and
    // then adding "-----BEGIN..." and "-----END..." strings"
    var tlsKey []byte
    var tlsCert []byte
    for _, b := range pemBlocks {
        if b.Type == "PRIVATE KEY" {
            block, _ := pem.Decode(pem.EncodeToMemory(b))

            tlsKey = append(tlsKey, "-----BEGIN PRIVATE KEY-----\n"...)
            tlsKey = append(tlsKey, base64.StdEncoding.EncodeToString(block.Bytes)...)
            tlsKey = append(tlsKey, "-----END PRIVATE KEY-----\n"...)
        }
        if b.Type == "CERTIFICATE" {
            block, _ := pem.Decode(pem.EncodeToMemory(b))

            tlsCert = append(tlsCert, "-----BEGIN CERTIFICATE-----\n"...)
            tlsCert = append(tlsCert, base64.StdEncoding.EncodeToString(block.Bytes)...)
            tlsCert = append(tlsCert, "-----END CERTIFICATE-----\n"...)
        }

    }

    // this following code uses client-go package to create a TLS secret in kubernetes
    tlsData := make(map[string][]byte)
    tlsData[`tls.key`] = tlsKey
    tlsData[`tls.crt`] = tlsCert

    beTls := &v1.Secret{
        ObjectMeta: metav1.ObjectMeta{
            Name:      `mycertname`,
            Namespace: t.beNamespace.Name,
        },
        Data: tlsData,
        Type: v1.SecretTypeTLS,
    }
    _, err = t.kubeClientSet.CoreV1().Secrets(t.beNamespace.Name).Create(ctx, beTls, metav1.CreateOptions{})
    if err != nil {
        log.Printf(`Failed to create TLS secret :%s`, err.Error())
        return err
    }

    return nil
}
,,,
</code>```

Body:
I could use the Azure Key Vault provider for Secrets Store CSI driver (https://learn.microsoft.com/en-us/azure/aks/csi-secrets-store-driver)

but I need to have a bit more control over the certificates via a custom k8 management API am developing for my use case. I had some challenges with this.

I think I have a good enough solution but want to put it out in the world for comment from others that may have done this in the past.

here is what I did...

When one creates the certificates (or uploads them) in Azure vault the values are stored in secrets. I used the Azure sdk for Go to get them

I use base64 package to decode what Azure sends me (a PFX containing private and public keys

I use pkcs12 package pkcs12.toPEM function to break it apart into an array of pem.Block.

Each block has a value that contains headers in the value

I need to strip the headers out before I use them in the kubernetes secret

package secretcreator

import (
    "context"
    "encoding/base64"
    "encoding/pem"
    "log"
    "time"

    "github.com/Azure/azure-sdk-for-go/sdk/keyvault/azcertificates"
    "github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets"
    "golang.org/x/crypto/pkcs12"
    v1 "k8s.io/api/core/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
)

type MyStruct struct {
    kubeClientSet          *kubernetes.Clientset
    azureVaultSecrets      *azsecrets.Client
    azureVaultCertificates *azcertificates.Client
    beNamespace            *v1.Namespace
    identitySecrests       *v1.Secret
}

func (t *MyStruct) createSecrets() error {

    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()

    //tlsSecret.value is a base64 encoded PEM/PFX containing PRIVATE KEY and CERTIFICATES blocks
    tlsSecret, err := t.azureVaultSecrets.GetSecret(ctx, `myCertName`, ``, nil)
    if err != nil {
        log.Printf(`Failed to retrieve cert :%s`, err.Error())
        return err
    }

    //pfxBytes is the Byte representation of the string stored in tlsSecret.Value
    pfxBytes, err := base64.StdEncoding.Strict().DecodeString(*tlsSecret.Value)
    if err != nil {
        log.Printf(`Failed to decode cert PFX:%s`, err.Error())
        return err
    }
    // pemBlocks is a array of *pem.Block - in my case I have 1 PRIVATE KEY Block and three CERTIFICATE Blocks
    //the blocks have headers too that look something like this on the PRIVATE KEY, after encoding the encoded string looks like this
    //
    // -----BEGIN PRIVATE KEY-----
    // Microsoft CSP Name: Microsoft Enhanced Cryptographic Provider v1.0
    // friendlyName: {D06B3D5A-98D1-45F1-A8C2-DC091232D6A7}
    // localKeyId: 01000000
    //
    // MIIEAI.......ymfjsQ==
    // -----END PRIVATE KEY-----
    pemBlocks, err := pkcs12.ToPEM(pfxBytes, "")
    if err != nil {
        log.Printf(`Failed to decode key or cert from PEM Blocks:%s`, err.Error())
        return err
    }

    // k8 needs to store TLS in a secret with key value pairs in the data - one for tls.key and the other for tls.crt
    // this code iterates through the blocks, looks at the type of data stored and breaks it up into tls.key and tls.crt
    // k8.nginx does not like the headers for some reason - so i strip them out using base64.StdEncoding.Encode to string and
    // then adding "-----BEGIN..." and "-----END..." strings"
    var tlsKey []byte
    var tlsCert []byte
    for _, b := range pemBlocks {
        if b.Type == "PRIVATE KEY" {
            block, _ := pem.Decode(pem.EncodeToMemory(b))

            tlsKey = append(tlsKey, "-----BEGIN PRIVATE KEY-----\n"...)
            tlsKey = append(tlsKey, base64.StdEncoding.EncodeToString(block.Bytes)...)
            tlsKey = append(tlsKey, "-----END PRIVATE KEY-----\n"...)
        }
        if b.Type == "CERTIFICATE" {
            block, _ := pem.Decode(pem.EncodeToMemory(b))

            tlsCert = append(tlsCert, "-----BEGIN CERTIFICATE-----\n"...)
            tlsCert = append(tlsCert, base64.StdEncoding.EncodeToString(block.Bytes)...)
            tlsCert = append(tlsCert, "-----END CERTIFICATE-----\n"...)
        }

    }

    // this following code uses client-go package to create a TLS secret in kubernetes
    tlsData := make(map[string][]byte)
    tlsData[`tls.key`] = tlsKey
    tlsData[`tls.crt`] = tlsCert

    beTls := &v1.Secret{
        ObjectMeta: metav1.ObjectMeta{
            Name:      `mycertname`,
            Namespace: t.beNamespace.Name,
        },
        Data: tlsData,
        Type: v1.SecretTypeTLS,
    }
    _, err = t.kubeClientSet.CoreV1().Secrets(t.beNamespace.Name).Create(ctx, beTls, metav1.CreateOptions{})
    if err != nil {
        log.Printf(`Failed to create TLS secret :%s`, err.Error())
        return err
    }

    return nil
}
,,,


问:
How to exclude transitively included package assets from flutter build?
I have a flutter package flutter_opencc_ffi_web, which contains some JS files. This package is transitively included in another project of mine. When I build a non-web bundle, I'd like to exclude the JS assets(about 1Mb). How can I achieve that?

I've tried the build_config, but don't know how to exclude package assets. The following config doesn't work.

build.yaml

targets:
  $default:
    sources:
      exclude:
        - assets/opencc/**
        - assets/packages/flutter_opencc_ffi_web/assets/opencc/**
    dependencies:
      flutter_opencc_ffi_web:
        exclude:
          - assets/opencc/**
```


问:
Query failed in NebulaGraph workspace when creating Edge tag with GeoPoint
When creating a tag with GEOPOINT, the query cannot be performed in the nGQL, and it reported: Storage Error: Edge prop not found.

```<code>E0712 13:16:26.017154 34888 RowReaderV2.cpp:190] Geography::fromWKB failed: Failed to parse an valid Geography instance from the wkb `'
E0712 13:16:26.017154 34888 RowReaderV2.cpp:190] Geography::fromWKB failed: Failed to parse an valid Geography instance from the wkb `'
E0712 13:16:26.471570 34888 RowReaderV2.cpp:190] Geography::fromWKB failed: Failed to parse an valid Geography instance from the wkb `'
E0712 13:16:26.773860 34888 RowReaderV2.cpp:190] Geography::fromWKB failed: Failed to parse an valid Geography instance from the wkb `'
E0712 13:16:27.073959 34888 RowReaderV2.cpp:190] Geography::fromWKB failed: Failed to parse an valid Geography instance from the wkb `'
</code>```

Statement to create a node;

```<code>INSERT VERTEX IF NOT EXISTS CONCEPT (id, name, iri, nicks, source_type, source_name, source_batch, create_user, update_user, create_time, update_time) VALUES
"75c5eebd3eaea875c822ad5598aef065":("75c5eebd3eaea875c822ad5598aef065", "AAA", "https://g.w/test#AAA", NULL, "MANUAL", "test", "test-0711", "jal", "jal", datetime("2022-03-22 11:10:00.000"), datetime("2022-07-01 20:29:54.342")),
"91b32acd631cfdcc171ce93":("91b32acd631cfdcc171ce93", "BBB", "https://g.w/test#BBB", NULL, "MANUAL", "test", "test-0711", "jal", "jal", datetime("2022-03-22 11:10:00.000"), datetime("2022-07-01 20:29:54.342"))
</code>```

Statement to create an edge:

```<code>INSERT EDGE RELATETO (id, ontrelid, ontreliri, name, nicks, weight, time_start, time_finish, address_point, address_name, address_detail, source_type, source_name, source_batch, create_user, update_user, create_time, update_time) VALUES "75c5eebd3eaea875c822ad5598aef065"->"cb3a063a491b32acd631cfdcc171ce93"@0:("d6ba99a8aafcd2a6e6bc6e4c46745c82", "74004a7a62f3dd1fe160f02203c6933c", null, "居住", "", 0.0, null, null, ST_Point(39.657589, 116.070870), "房山区", "世界名园A区", "MANUAL", "el51:9101", "20220623", "el51:9101", "el51:9101", datetime("2022-03-22 11:10:00.000"), datetime("2022-07-01 20:29:54.342"));
</code>```

Query statement (both OpenCypher and nGQL  were tried).

```<code>MATCH p=(m:ENTITY {id: "5f136053f62099a86cb15d2121f2dace"})-[r:RELATETO]-(n:ENTITY)  RETURN p
</code>```
```<code>MATCH p=(v)-[e:RELATETO*1]-(v2)
WHERE id(v) IN ["75c5eebd3eaea875c822ad5598aef065"]
     RETURN p LIMIT 100
</code>```

Body:
When creating a tag with GEOPOINT, the query cannot be performed in the nGQL, and it reported: Storage Error: Edge prop not found.

E0712 13:16:26.017154 34888 RowReaderV2.cpp:190] Geography::fromWKB failed: Failed to parse an valid Geography instance from the wkb `'
E0712 13:16:26.017154 34888 RowReaderV2.cpp:190] Geography::fromWKB failed: Failed to parse an valid Geography instance from the wkb `'
E0712 13:16:26.471570 34888 RowReaderV2.cpp:190] Geography::fromWKB failed: Failed to parse an valid Geography instance from the wkb `'
E0712 13:16:26.773860 34888 RowReaderV2.cpp:190] Geography::fromWKB failed: Failed to parse an valid Geography instance from the wkb `'
E0712 13:16:27.073959 34888 RowReaderV2.cpp:190] Geography::fromWKB failed: Failed to parse an valid Geography instance from the wkb `'

Statement to create a node;

INSERT VERTEX IF NOT EXISTS CONCEPT (id, name, iri, nicks, source_type, source_name, source_batch, create_user, update_user, create_time, update_time) VALUES
"75c5eebd3eaea875c822ad5598aef065":("75c5eebd3eaea875c822ad5598aef065", "AAA", "https://g.w/test#AAA", NULL, "MANUAL", "test", "test-0711", "jal", "jal", datetime("2022-03-22 11:10:00.000"), datetime("2022-07-01 20:29:54.342")),
"91b32acd631cfdcc171ce93":("91b32acd631cfdcc171ce93", "BBB", "https://g.w/test#BBB", NULL, "MANUAL", "test", "test-0711", "jal", "jal", datetime("2022-03-22 11:10:00.000"), datetime("2022-07-01 20:29:54.342"))

Statement to create an edge:

INSERT EDGE RELATETO (id, ontrelid, ontreliri, name, nicks, weight, time_start, time_finish, address_point, address_name, address_detail, source_type, source_name, source_batch, create_user, update_user, create_time, update_time) VALUES "75c5eebd3eaea875c822ad5598aef065"->"cb3a063a491b32acd631cfdcc171ce93"@0:("d6ba99a8aafcd2a6e6bc6e4c46745c82", "74004a7a62f3dd1fe160f02203c6933c", null, "居住", "", 0.0, null, null, ST_Point(39.657589, 116.070870), "房山区", "世界名园A区", "MANUAL", "el51:9101", "20220623", "el51:9101", "el51:9101", datetime("2022-03-22 11:10:00.000"), datetime("2022-07-01 20:29:54.342"));

Query statement (both OpenCypher and nGQL  were tried).

MATCH p=(m:ENTITY {id: "5f136053f62099a86cb15d2121f2dace"})-[r:RELATETO]-(n:ENTITY)  RETURN p

MATCH p=(v)-[e:RELATETO*1]-(v2)
WHERE id(v) IN ["75c5eebd3eaea875c822ad5598aef065"]
     RETURN p LIMIT 100


问:
VSCode python debugger isn't hitting breakpoint in a Notebook callback function
I'm running a(n) .ipynb file within VSCode, trying to debug a callback function. No breakpoints within the callback function are hit, although the breakpoint I've set in the main code cell correctly pauses code execution when running the cell in debug mode. Is there something specific I can do to hit the breakpoint within the callback after pressing the interact manual button?

Below is the code cell I'm trying to breakpoint.

```<code>from IPython.core.getipython import get_ipython
from IPython.core.debugger import set_trace
from ipywidgets import interact, interact_manual
from IPython.display import display, Javascript

def add_code_cell(s):
    if s=="test":
        file_text=s
    else:
        file_text="No such file"

    text=file_text.replace('\n','\\n').replace("\"","\\\"").replace("'", "\\'")
    javascript = Javascript('''
    var cell = IPython.notebook.insert_cell_below("code")
    cell.set_text("{}")
    '''.format(f'{text}'))

    return javascript

im = interact_manual(add_code_cell, s=["test","test_two","best_test"]);
</code>```

I've tried adding breakpoint() within the add_code_cells function, but no luck. I would like to hit a breakpoint within the add_code_cells method once I press the button created from the interact_manual.

Body:
I'm running a(n) .ipynb file within VSCode, trying to debug a callback function. No breakpoints within the callback function are hit, although the breakpoint I've set in the main code cell correctly pauses code execution when running the cell in debug mode. Is there something specific I can do to hit the breakpoint within the callback after pressing the interact manual button?

Below is the code cell I'm trying to breakpoint.

from IPython.core.getipython import get_ipython
from IPython.core.debugger import set_trace
from ipywidgets import interact, interact_manual
from IPython.display import display, Javascript

def add_code_cell(s):
    if s=="test":
        file_text=s
    else:
        file_text="No such file"

    text=file_text.replace('\n','\\n').replace("\"","\\\"").replace("'", "\\'")
    javascript = Javascript('''
    var cell = IPython.notebook.insert_cell_below("code")
    cell.set_text("{}")
    '''.format(f'{text}'))

    return javascript

im = interact_manual(add_code_cell, s=["test","test_two","best_test"]);

I've tried adding breakpoint() within the add_code_cells function, but no luck. I would like to hit a breakpoint within the add_code_cells method once I press the button created from the interact_manual.


问:
How to place another shape behind a square?
I'm trying to create a custom shape that has a triangle that overflows on the square left side.

I've tried to use absolute and relative positions to achieve it by putting the square behind it but then it hides the spans on the main square. How can I do it?

Shape that I'm trying to achieve

My code:

```<code>        <div class="h-96 p-6 bg-white relative rounded-3xl border-3 border-white shadow-sm transition ease-in-out hover:scale-110">

            <div class="flex justify-between">
                <i class="fa-solid fa-gem text-4xl text-secondary"></i>

                <div class="absolute -top-5 right-8 flex flex-col items-center p-4 bg-blue">
                    <span class="text-purewhite font-semibold text-3xl">25€</span>
                    <span class="text-gray-200 font-semibold">for month</span>
                </div>

                <!-- <span class="text-3xl text-primary font-medium">Base</span> -->
            </div>
        </div>
</code>```

This is what my current UI looks like

Already written in the top

Body:
I'm trying to create a custom shape that has a triangle that overflows on the square left side.

I've tried to use absolute and relative positions to achieve it by putting the square behind it but then it hides the spans on the main square. How can I do it?

Shape that I'm trying to achieve

My code:

                    25€
                    for month

This is what my current UI looks like

Already written in the top


问:
How to identify if one json contains specific value in json schema
There is a json result like this below, and I need to check if a specific value is contained in shop_ids, for example, 232323 is contained, while 232324 is not. Is it possible to achieve that with JSON Schema? How?

```<code>{
    "request":{
        "0":{
            "cids":{
                "0":"a",
                "1":"b",
                "2":"c",
                "3":"d",
                "4":"e",
                "5":"f",
                "6":"g",
                "7":"h"
            },
            "data_type":"1",
            "key_type":"1",
            "one_item_id":"0",
            "queries":{
                "0":{
                    "0":"query1"
                },
                "1":{
                    "0":"query2"
                }
            },
            "shop_ids":{
                "0":"11111",
                "1":"232323",
                "2":"33333",
                "3":"124151",
                "4":"55555",
                "5":"12121"
            },
            "num":"30"
        }
    }
}
</code>```

note: the shop_ids may contain more numeric fields, not just 0-5.

I tried "patternProperties", it does work for checking specific key-value but returns fail on other key-value. What I need is just any of "shop_ids" match the specific value is ok.

Body:
There is a json result like this below, and I need to check if a specific value is contained in shop_ids, for example, 232323 is contained, while 232324 is not. Is it possible to achieve that with JSON Schema? How?

{
    "request":{
        "0":{
            "cids":{
                "0":"a",
                "1":"b",
                "2":"c",
                "3":"d",
                "4":"e",
                "5":"f",
                "6":"g",
                "7":"h"
            },
            "data_type":"1",
            "key_type":"1",
            "one_item_id":"0",
            "queries":{
                "0":{
                    "0":"query1"
                },
                "1":{
                    "0":"query2"
                }
            },
            "shop_ids":{
                "0":"11111",
                "1":"232323",
                "2":"33333",
                "3":"124151",
                "4":"55555",
                "5":"12121"
            },
            "num":"30"
        }
    }
}

note: the shop_ids may contain more numeric fields, not just 0-5.

I tried "patternProperties", it does work for checking specific key-value but returns fail on other key-value. What I need is just any of "shop_ids" match the specific value is ok.


问:
cmake file to include relative directory out of current directory
my folder like

```<code>my_dir
   CMakeLists.txt
   my_cpp.cpp
common_utils
   common_util.h
   common_util.cpp
</code>```

In my_dir/CMakeLists.txt

```<code>include_directories(${CMAKE_SOURCE_DIR}/../common_utils)
</code>```

In my_cpp.cpp I use

```<code>#include "common_util.h"
</code>```

but I got compiling error for "no such file or directory" of "common_util.h".

How to solve the problem in CMakeLists.txt? Thanks.

Body:
my folder like

my_dir
   CMakeLists.txt
   my_cpp.cpp
common_utils
   common_util.h
   common_util.cpp

In my_dir/CMakeLists.txt

include_directories(${CMAKE_SOURCE_DIR}/../common_utils)

In my_cpp.cpp I use

#include "common_util.h"

but I got compiling error for "no such file or directory" of "common_util.h".

How to solve the problem in CMakeLists.txt? Thanks.


问:
Including header or prototype of std::object
I have a function which returns a type std::istringstream inside one of my classes. To avoid #include <sstream> in my header file, I wrote the prototype class istringstream; at the top of my header file and wrote the return type as istringstream. When defining the function in my cpp file, I wrote the return type as std::istringstream.

I now have ambiguity issues where I am unable to use istringstream without declaring it as std::istringstream, although I have using std::istringstream.

What is the best practice here? I had always learned to declare prototypes instead of including the full header when possible.

Here is an example for clarity:

example.h

```<code>class istringstream;

istringstream myFunction();
</code>```

example.cpp

```<code>#include "example.h"
using std::istringstream;

std::istringstream myFunction(){} // istringstream is ambiguous
</code>```

Update:

Answered in comments -> it is not recommended to forward declare and is in fact undefined behavior.

Body:
I have a function which returns a type std::istringstream inside one of my classes. To avoid #include <sstream> in my header file, I wrote the prototype class istringstream; at the top of my header file and wrote the return type as istringstream. When defining the function in my cpp file, I wrote the return type as std::istringstream.

I now have ambiguity issues where I am unable to use istringstream without declaring it as std::istringstream, although I have using std::istringstream.

What is the best practice here? I had always learned to declare prototypes instead of including the full header when possible.

Here is an example for clarity:

example.h

class istringstream;

istringstream myFunction();

example.cpp

#include "example.h"
using std::istringstream;

std::istringstream myFunction(){} // istringstream is ambiguous

Update:

Answered in comments -> it is not recommended to forward declare and is in fact undefined behavior.


问:
Cookies rejected by chrome
I want to implement jwts stored in httpOnly cookeis into my applicaition but the cookies are being rejected by chrome and an empty cookie object is being recieved at the backend.

This is how the cookie is being set in the auth controller triggered by the /login api end point where the refresh token is created and stored in a cookie

```<code>res.cookie("jwt",refreshToken,{httpOnly: true, sameSite: "lax", maxAge: 24*60*60*1000});
</code>```

Refresh controller

```<code>const jwt = require('jsonwebtoken');
const User = require('../model/User');

const handleRefresh = async (req,res) => {
    console.log(req.cookies);
    const cookies = req.cookies;
    if(!cookies?.jwt) return res.sendStatus(401);

    const refreshToken = cookies.jwt;
    const foundUser = await User.findOne({refreshToken: refreshToken}).exec();

    jwt.verify(
        refreshToken,
        process.env.REFRESH_TOKEN,
        (err,decoded) => {
            const roles = Object.values(foundUser.roles);
            if(err || decoded.username !== foundUser.username) return res.sendStatus(403);

            const accessToken = jwt.sign({
                "userInfo":{
                    "username": decoded.username,
                    "roles": roles
                }
            },
            process.env.ACCESS_TOKEN,
            {expiresIn: "300s"});

            return res.json({"accessToken":accessToken});
        }
    );
}

module.exports = {handleRefresh};
</code>```

Refresh function in react making a call to the refresh endpoint

```<code>    const useRefreshToken = () => {
    const {setUser} = useAuth();

    const refresh = async () => {
        const response = await axios.get('/refresh',{
            withCredentials: true
        });
        console.log(response);
        setUser(prevState => {
            console.log(prevState);
            console.log(response.data.accessToken);
            return {...prevState, accessToken: response.data.accessToken}
        })}

        return refresh;
    }
</code>```

axios instance

```<code>const BASE_URL = "http://localhost:4500";

export default axios.create({
    baseURL: BASE_URL
});
</code>```

Whenever I call the useRefeshToken func and make the request through my react application I get an error which is as a result of the if(!cookies?.jwt) return res.sendStatus(401); in my refresh controller, meaning the cookie object is empty. But when I use Thunder Client to make requests to the same refresh endpoint the cookie is sent and I get back my jwt object.

PS - I have already handled the CORS so this isn't a cors error.

Title: Cookies rejected by chrome

Body:
I want to implement jwts stored in httpOnly cookeis into my applicaition but the cookies are being rejected by chrome and an empty cookie object is being recieved at the backend.

This is how the cookie is being set in the auth controller triggered by the /login api end point where the refresh token is created and stored in a cookie

res.cookie("jwt",refreshToken,{httpOnly: true, sameSite: "lax", maxAge: 24*60*60*1000});

Refresh controller

const jwt = require('jsonwebtoken');
const User = require('../model/User');

const handleRefresh = async (req,res) => {
    console.log(req.cookies);
    const cookies = req.cookies;
    if(!cookies?.jwt) return res.sendStatus(401);

    const refreshToken = cookies.jwt;
    const foundUser = await User.findOne({refreshToken: refreshToken}).exec();

    jwt.verify(
        refreshToken,
        process.env.REFRESH_TOKEN,
        (err,decoded) => {
            const roles = Object.values(foundUser.roles);
            if(err || decoded.username !== foundUser.username) return res.sendStatus(403);

            const accessToken = jwt.sign({
                "userInfo":{
                    "username": decoded.username,
                    "roles": roles
                }
            },
            process.env.ACCESS_TOKEN,
            {expiresIn: "300s"});

            return res.json({"accessToken":accessToken});
        }
    );
}

module.exports = {handleRefresh};

Refresh function in react making a call to the refresh endpoint

    const useRefreshToken = () => {
    const {setUser} = useAuth();

    const refresh = async () => {
        const response = await axios.get('/refresh',{
            withCredentials: true
        });
        console.log(response);
        setUser(prevState => {
            console.log(prevState);
            console.log(response.data.accessToken);
            return {...prevState, accessToken: response.data.accessToken}
        })}

        return refresh;
    }

axios instance

const BASE_URL = "http://localhost:4500";

export default axios.create({
    baseURL: BASE_URL
});

Whenever I call the useRefeshToken func and make the request through my react application I get an error which is as a result of the if(!cookies?.jwt) return res.sendStatus(401); in my refresh controller, meaning the cookie object is empty. But when I use Thunder Client to make requests to the same refresh endpoint the cookie is sent and I get back my jwt object.

PS - I have already handled the CORS so this isn't a cors error.


问:
How can I animate dialog in Jetpack compose Navigation?
I have a question about animating dialogs.

in basic library, there's a dialog function. But it doesn't seem I can apply some animation when it opens.
So, I created this function called animatedDialog. Is this normal way or does this have any problem or is there any better solution to solve this issue?

```<code>fun NavGraphBuilder.animatedDialog(
    route: String,
    arguments: List<NamedNavArgument> = emptyList(),
    deepLinks: List<NavDeepLink> = emptyList(),
    enter: EnterTransition = fadeIn() + expandIn(),
    exit: ExitTransition = shrinkOut() + fadeOut(),
    dialogProperties: DialogProperties = DialogProperties(),
    content: @Composable (NavBackStackEntry) -> Unit
) {
    addDestination(
        Destination(
            provider[AnimatedDialogNavigator::class],
            enter = enter,
            exit = exit,
            dialogProperties,
            content
        ).apply {
            this.route = route
            arguments.forEach { (argumentName, argument) ->
                addArgument(argumentName, argument)
            }
            deepLinks.forEach { deepLink ->
                addDeepLink(deepLink)
            }
        }
    )
}
</code>```

Body:
I have a question about animating dialogs.

in basic library, there's a dialog function. But it doesn't seem I can apply some animation when it opens.
So, I created this function called animatedDialog. Is this normal way or does this have any problem or is there any better solution to solve this issue?

fun NavGraphBuilder.animatedDialog(
    route: String,
    arguments: List<NamedNavArgument> = emptyList(),
    deepLinks: List<NavDeepLink> = emptyList(),
    enter: EnterTransition = fadeIn() + expandIn(),
    exit: ExitTransition = shrinkOut() + fadeOut(),
    dialogProperties: DialogProperties = DialogProperties(),
    content: @Composable (NavBackStackEntry) -> Unit
) {
    addDestination(
        Destination(
            provider[AnimatedDialogNavigator::class],
            enter = enter,
            exit = exit,
            dialogProperties,
            content
        ).apply {
            this.route = route
            arguments.forEach { (argumentName, argument) ->
                addArgument(argumentName, argument)
            }
            deepLinks.forEach { deepLink ->
                addDeepLink(deepLink)
            }
        }
    )
}