问:
SwiftUI: Cannot set 'zoomScale' of an PKCanvasView()
I want to set the Zoom scale of my PKCanvasView()

I tried adding this function:

```<code>func setCanvasZoom() {
    canvasView.zoomScale = 2.0
    print("CanvasView: \(canvasView.zoomScale)")
}
</code>```

But that function always throws 1.0 in the console...

I am calling the setCanvasView() function, after my ScrollView appeared:

```<code>ZStack {
    ScrollView {
        VStack {
            CanvasView(canvasView: $canvasView)
        }
    }.onAppear(perform: {
        setCanvasZoom()
    })
}
</code>```

The canvasView variable is declared like that:

```<code>@State var canvasView = PKCanvasView()
</code>```

Do you guys have any Idea why this happens?

Body:
I want to set the Zoom scale of my PKCanvasView()

I tried adding this function:

func setCanvasZoom() {
    canvasView.zoomScale = 2.0
    print("CanvasView: \(canvasView.zoomScale)")
}

But that function always throws 1.0 in the console...

I am calling the setCanvasView() function, after my ScrollView appeared:

ZStack {
    ScrollView {
        VStack {
            CanvasView(canvasView: $canvasView)
        }
    }.onAppear(perform: {
        setCanvasZoom()
    })
}

The canvasView variable is declared like that:

@State var canvasView = PKCanvasView()

Do you guys have any Idea why this happens?


来源: stackexchange

问:
How can I convert PSPDFKIT API's python version in to golang
i am using an API which named PSPDFKIT, this API can convert your local field in .pdf field .It has already write many language to demonstration,but i have a few proplem when converting in to golang.
This is the version of Python which provided by PSPDFKIT:
`

```<code>import requests
import json

instructions = {
  'parts': [
    {
      'html': 'index.html'
    }
  ]
}

response = requests.request(
  'POST',
  'https://api.pspdfkit.com/build',
  headers = {
    'Authorization': 'Bearer API key'
  },
  files = {
    'index.html': open('index.html', 'rb')
  },
  data = {
    'instructions': json.dumps(instructions)
  },
  stream = True
)

if response.ok:
  with open('result.pdf', 'wb') as fd:
    for chunk in response.iter_content(chunk_size=8096):
      fd.write(chunk)
else:
  print(response.text)
  exit()
</code>```

`

and this is my code:

`

```<code>package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "io/ioutil"
    "net/http"
    "os"
)

type instructions struct {
    Parts []struct {
        HTML string `json:"html"`
    } `json:"parts"`
}

func main() {
    instructions := `{
        'parts': [
          {
            'html': 'index.html'
          }
        ]
      }`
    instructionsBytes, err := json.Marshal(instructions)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    file, err := os.Open("document.pdf")
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    defer file.Close()

    response, _ := http.NewRequest("POST", "https://api.pspdfkit.com/build", bytes.NewBuffer(instructionsBytes))
    defer response.Body.Close()
    response.Header.Set("Authorization", "API key")
    response.Header.Set("Content-Type", "multipart/form-data")

    body, err := ioutil.ReadAll(response.Body)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    fmt.Println(string(body))
    os.Exit(1)

    result, err := os.Create("result.pdf")
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    defer result.Close()

    _, err = io.Copy(result, response.Body)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
}
</code>```

`
This API request the multipart/form-data in json:instructions and local field i guess,but i am not sure how to post multipart/form-data correctly,and i always received the empty .pdf field after running my code.

Can anyone help me? thanks a lot .

i wish to know how to post  multipart/form-data correctly,also the right way to convert the code in golang,and finally it can produce the .pdf field that are not empty PDF.

ContentLicense: CC BY-SA 4.0

Body:
i am using an API which named PSPDFKIT, this API can convert your local field in .pdf field .It has already write many language to demonstration,but i have a few proplem when converting in to golang.
This is the version of Python which provided by PSPDFKIT:
`

import requests
import json

instructions = {
  'parts': [
    {
      'html': 'index.html'
    }
  ]
}

response = requests.request(
  'POST',
  'https://api.pspdfkit.com/build',
  headers = {
    'Authorization': 'Bearer API key'
  },
  files = {
    'index.html': open('index.html', 'rb')
  },
  data = {
    'instructions': json.dumps(instructions)
  },
  stream = True
)

if response.ok:
  with open('result.pdf', 'wb') as fd:
    for chunk in response.iter_content(chunk_size=8096):
      fd.write(chunk)
else:
  print(response.text)
  exit()

`

and this is my code:

`

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "io/ioutil"
    "net/http"
    "os"
)

type instructions struct {
    Parts []struct {
        HTML string `json:"html"`
    } `json:"parts"`
}

func main() {
    instructions := `{
        'parts': [
          {
            'html': 'index.html'
          }
        ]
      }`
    instructionsBytes, err := json.Marshal(instructions)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    file, err := os.Open("document.pdf")
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    defer file.Close()

    response, _ := http.NewRequest("POST", "https://api.pspdfkit.com/build", bytes.NewBuffer(instructionsBytes))
    defer response.Body.Close()
    response.Header.Set("Authorization", "API key")
    response.Header.Set("Content-Type", "multipart/form-data")

    body, err := ioutil.ReadAll(response.Body)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    fmt.Println(string(body))
    os.Exit(1)

    result, err := os.Create("result.pdf")
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    defer result.Close()

    _, err = io.Copy(result, response.Body)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
}

`
This API request the multipart/form-data in json:instructions and local field i guess,but i am not sure how to post multipart/form-data correctly,and i always received the empty .pdf field after running my code.

Can anyone help me? thanks a lot .

i wish to know how to post  multipart/form-data correctly,also the right way to convert the code in golang,and finally it can produce the .pdf field that are not empty PDF.


问:
how to animated swiper.js slider like modern slider
This slider has 3 slides per view and also has a full-width background image. Whenever the slider changes, the background image will change according to the slider index. I tried animating it like the site https://stinna-it.nl/alle-projecten. Not only did I try to animate it, I tried to create exactly this slider using Swiper.js. For the animation, I used GSAP but I can only use autoAlpha for now; if I try to use other things like scale(0) to scale(1), it gets messed up.

  const imgs = document.querySelectorAll(".prjctbg");

  var swiper = new Swiper(".swiper-container", {
    pagination: {
      el: ".swiper-pagination",
      clickable: true,
    },
    spaceBetween: 1,
    slidesPerView: 2.5,
    centeredSlides: true,
    roundLengths: true,
    loop: true,
    loopAdditionalSlides: 30,
    navigation: {
      nextEl: ".swiper-button-next",
      prevEl: ".swiper-button-prev",
    },
    on: {
      slideChangeTransitionStart: function () {
        // Get the current slide index
        var slideIndex = this.realIndex;
         // console.log(slideIndex);
        imgs.forEach((img) => {
          const index = img.getAttribute("data-index");
          if (index == slideIndex) {
            img.classList.add("activeBG");
          } else {
            img.classList.remove("activeBG");
          }
        });
        gsap.fromTo(
          ".activeBG",
          1,
          {
            autoAlpha: 0,
            scale: 1.2,
          },
          {
            autoAlpha: 1,
            scale: 1,
          }
        );
      },
    },
    breakpoints: {
      768: {
        slidesPerView: 1,
      },
    },
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,300;0,400;0,500;0,600;1,200&display=swap');
* {
  margin: 0;
  padding: 0;
font-family: 'Poppins', sans-serif;
  box-sizing: border-box;
}

body a {
  text-decoration: none;
  color: #ffffff;
}

.projectSlider {
  width: 100vw;
  height: 100vh;
  position: relative;
}
.projectSlider .swiper-pagination-fraction,
.projectSlider .swiper-pagination-custom,
.projectSlider .swiper-container-horizontal > .swiper-pagination-bullets {
  bottom: 26px;
}
.projectSlider .swiper-slide.swiper-slide-prev {
  display: flex;
  justify-content: flex-end;
}
.projectSlider .swiper-slide.swiper-slide-next {
  display: flex;
  justify-content: flex-start;
}
.projectSlider .swiper-button-prev,
.projectSlider .swiper-container-rtl .swiper-button-next {
  background-image: url("../images/icons/prev.svg");
  left: inherit;
  right: 100px;
}
.projectSlider .swiper-button-next,
.projectSlider .swiper-container-rtl .swiper-button-prev {
  background-image: url("../images/icons/next.svg");
  right: 35px;
  left: auto;
}
.projectSlider .swiper-button-prev,
.projectSlider .swiper-button-next {
  top: 94%;
  width: 50px;
  height: 50px;
  background-size: contain;
  background-position: center;
}
.projectSlider .container {
  width: 100%;
  height: 100%;
}
.projectSlider .prjctbg {
  position: absolute;
  width: 100%;
  height: 100%;
  -o-object-fit: cover;
     object-fit: cover;
  filter: blur(8px);
  -webkit-filter: blur(8px);
}
.projectSlider .prjctbg.activeBG {
  z-index: 1;
  transition: transform 1000ms cubic-bezier(0.165, 0.84, 0.44, 1) 0.2s, transform 0.5s cubic-bezier(0.165, 0.84, 0.44, 1) 0.2s;
}

.swiper-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.swiper-slide {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 200ms cubic-bezier(0.165, 0.84, 0.44, 1);
  transform: scale(0.8);
  text-align: center;
}
.swiper-slide p {
  overflow: hidden;
  color: #fff;
  font-size: 1em;
}
.swiper-slide p span {
  transform: translateY(100px);
  transition: transform 1000ms cubic-bezier(0.165, 0.84, 0.44, 1) 0.2s, transform 0.5s cubic-bezier(0.165, 0.84, 0.44, 1) 0.2s;
  display: block;
}
.swiper-slide h1 {
  color: #fff;
  font-size: 3.8em;
  line-height: 100%;
  transition: transform 1000ms cubic-bezier(0.165, 0.84, 0.44, 1) 0.2s, transform 0.5s cubic-bezier(0.165, 0.84, 0.44, 1) 0.2s;
  margin: 0px 0px 30px 0px;
  transform: scale(0.5);
  font-weight: 600;
}
.swiper-slide.swiper-slide-active {
  transform: scale(1);
}
.swiper-slide.swiper-slide-active p {
  opacity: 1;
  transition-delay: 0.5s;
}
.swiper-slide.swiper-slide-active p span {
  transition: transform 1000ms cubic-bezier(0.165, 0.84, 0.44, 1) 0.2s, transform 0.5s cubic-bezier(0.165, 0.84, 0.44, 1) 0.2s;
  transform: translateY(0px);
  display: block;
}
.swiper-slide.swiper-slide-active h1 {
  transition: transform 1000ms cubic-bezier(0.165, 0.84, 0.44, 1) 0.2s, transform 0.5s cubic-bezier(0.165, 0.84, 0.44, 1) 0.2s;
  transition-delay: 0.15s;
  transform: scale(1);
}</code>```

   <link
  rel="stylesheet"
  href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.4.2/css/swiper.css"
/>

                      Audiovisual

                      Design

                       Video Installation

                      Exhibition

                      Design

                       Multimedia Exhibition

                      Texts and

                      Images

                       website + Print Magazine

                      Material and

                      Light

                       Short Video

                      Dimension

                      Design

                       Rendered Image

                      App

                      Design

                       Sustainability App

```

Body:
This slider has 3 slides per view and also has a full-width background image. Whenever the slider changes, the background image will change according to the slider index. I tried animating it like the site https://stinna-it.nl/alle-projecten. Not only did I try to animate it, I tried to create exactly this slider using Swiper.js. For the animation, I used GSAP but I can only use autoAlpha for now; if I try to use other things like scale(0) to scale(1), it gets messed up.

  const imgs = document.querySelectorAll(".prjctbg");

  var swiper = new Swiper(".swiper-container", {
    pagination: {
      el: ".swiper-pagination",
      clickable: true,
    },
    spaceBetween: 1,
    slidesPerView: 2.5,
    centeredSlides: true,
    roundLengths: true,
    loop: true,
    loopAdditionalSlides: 30,
    navigation: {
      nextEl: ".swiper-button-next",
      prevEl: ".swiper-button-prev",
    },
    on: {
      slideChangeTransitionStart: function () {
        // Get the current slide index
        var slideIndex = this.realIndex;
         // console.log(slideIndex);
        imgs.forEach((img) => {
          const index = img.getAttribute("data-index");
          if (index == slideIndex) {
            img.classList.add("activeBG");
          } else {
            img.classList.remove("activeBG");
          }
        });
        gsap.fromTo(
          ".activeBG",
          1,
          {
            autoAlpha: 0,
            scale: 1.2,
          },
          {
            autoAlpha: 1,
            scale: 1,
          }
        );
      },
    },
    breakpoints: {
      768: {
        slidesPerView: 1,
      },
    },
  });

@import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,300;0,400;0,500;0,600;1,200&display=swap');
* {
  margin: 0;
  padding: 0;
font-family: 'Poppins', sans-serif;
  box-sizing: border-box;
}

body a {
  text-decoration: none;
  color: #ffffff;
}

.projectSlider {
  width: 100vw;
  height: 100vh;
  position: relative;
}
.projectSlider .swiper-pagination-fraction,
.projectSlider .swiper-pagination-custom,
.projectSlider .swiper-container-horizontal > .swiper-pagination-bullets {
  bottom: 26px;
}
.projectSlider .swiper-slide.swiper-slide-prev {
  display: flex;
  justify-content: flex-end;
}
.projectSlider .swiper-slide.swiper-slide-next {
  display: flex;
  justify-content: flex-start;
}
.projectSlider .swiper-button-prev,
.projectSlider .swiper-container-rtl .swiper-button-next {
  background-image: url("../images/icons/prev.svg");
  left: inherit;
  right: 100px;
}
.projectSlider .swiper-button-next,
.projectSlider .swiper-container-rtl .swiper-button-prev {
  background-image: url("../images/icons/next.svg");
  right: 35px;
  left: auto;
}
.projectSlider .swiper-button-prev,
.projectSlider .swiper-button-next {
  top: 94%;
  width: 50px;
  height: 50px;
  background-size: contain;
  background-position: center;
}
.projectSlider .container {
  width: 100%;
  height: 100%;
}
.projectSlider .prjctbg {
  position: absolute;
  width: 100%;
  height: 100%;
  -o-object-fit: cover;
     object-fit: cover;
  filter: blur(8px);
  -webkit-filter: blur(8px);
}
.projectSlider .prjctbg.activeBG {
  z-index: 1;
  transition: transform 1000ms cubic-bezier(0.165, 0.84, 0.44, 1) 0.2s, transform 0.5s cubic-bezier(0.165, 0.84, 0.44, 1) 0.2s;
}

.swiper-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.swiper-slide {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 200ms cubic-bezier(0.165, 0.84, 0.44, 1);
  transform: scale(0.8);
  text-align: center;
}
.swiper-slide p {
  overflow: hidden;
  color: #fff;
  font-size: 1em;
}
.swiper-slide p span {
  transform: translateY(100px);
  transition: transform 1000ms cubic-bezier(0.165, 0.84, 0.44, 1) 0.2s, transform 0.5s cubic-bezier(0.165, 0.84, 0.44, 1) 0.2s;
  display: block;
}
.swiper-slide h1 {
  color: #fff;
  font-size: 3.8em;
  line-height: 100%;
  transition: transform 1000ms cubic-bezier(0.165, 0.84, 0.44, 1) 0.2s, transform 0.5s cubic-bezier(0.165, 0.84, 0.44, 1) 0.2s;
  margin: 0px 0px 30px 0px;
  transform: scale(0.5);
  font-weight: 600;
}
.swiper-slide.swiper-slide-active {
  transform: scale(1);
}
.swiper-slide.swiper-slide-active p {
  opacity: 1;
  transition-delay: 0.5s;
}
.swiper-slide.swiper-slide-active p span {
  transition: transform 1000ms cubic-bezier(0.165, 0.84, 0.44, 1) 0.2s, transform 0.5s cubic-bezier(0.165, 0.84, 0.44, 1) 0.2s;
  transform: translateY(0px);
  display: block;
}
.swiper-slide.swiper-slide-active h1 {
  transition: transform 1000ms cubic-bezier(0.165, 0.84, 0.44, 1) 0.2s, transform 0.5s cubic-bezier(0.165, 0.84, 0.44, 1) 0.2s;
  transition-delay: 0.15s;
  transform: scale(1);
}

   <link
  rel="stylesheet"
  href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.4.2/css/swiper.css"
/>

                      Audiovisual

                      Design

                       Video Installation

                      Exhibition

                      Design

                       Multimedia Exhibition

                      Texts and

                      Images

                       website + Print Magazine

                      Material and

                      Light

                       Short Video

                      Dimension

                      Design

                       Rendered Image

                      App

                      Design

                       Sustainability App


问:
Unity, Mobile, Saving UI prefab and the text within
First time asking a question. Please be patient.

I'm making a dice roller that keeps track of the player's saves, skills, and etc.
I made a UI game object for the player's weapon that contains two scripts for attack and damage. I pass in the values (int) that the scripts need from textboxes attached to the game object. The player clicks a button to add a new weapon.

I was wondering how I can save the weapons list and the values each weapon have.

Building with Unity for android.

At the moment I saved the weapon roller as a prefab. I was thinking I need to make a weapon class so I can save. I never tried to make a mobile app. I "know" that playerprefs work for android, but I don't think I can use playerprefs to save a game object with values.

Any help to lift my fog of confusion would be appreciated.


问:
Swagger - same route, both GET method, swagger 2.0 not supported
Hiiiiiii.

I have 2 methods with the form show below:

Swagger showed me 500 error. Not supported.

```<code>[System.Web.Http.AllowAnonymous]
    [System.Web.Http.HttpGet]
    [System.Web.Http.Route("api/some/saveTemplate/1.1/action")]
    public async Task<IHttpActionResult> SaveSomething(string param1, string param2)
    {
        //some.code();

        return Ok(json);
    }

    [System.Web.Http.AllowAnonymous]
    [System.Web.Http.HttpGet]
    [System.Web.Http.Route("api/some/saveTemplate/1.1/action")]
    public async Task<IHttpActionResult> SaveSomething(string param1, string param2, int param3)
    {
        //some.code();

        return Ok(json);
    }
</code>```

As you can see above, i just have an overload on the method.

How can i get the solution? I cannot change any from my endpoints/routes. I am supporting a system in production, but I need to generate documentation.

can i generate any type of exclusion to swagger get the first method as a "GET 1" an the second as a "GET 2" or similar?

thank you very much

Body:
Hiiiiiii.

I have 2 methods with the form show below:

Swagger showed me 500 error. Not supported.

[System.Web.Http.AllowAnonymous]
    [System.Web.Http.HttpGet]
    [System.Web.Http.Route("api/some/saveTemplate/1.1/action")]
    public async Task<IHttpActionResult> SaveSomething(string param1, string param2)
    {
        //some.code();

        return Ok(json);
    }

    [System.Web.Http.AllowAnonymous]
    [System.Web.Http.HttpGet]
    [System.Web.Http.Route("api/some/saveTemplate/1.1/action")]
    public async Task<IHttpActionResult> SaveSomething(string param1, string param2, int param3)
    {
        //some.code();

        return Ok(json);
    }

As you can see above, i just have an overload on the method.

How can i get the solution? I cannot change any from my endpoints/routes. I am supporting a system in production, but I need to generate documentation.

can i generate any type of exclusion to swagger get the first method as a "GET 1" an the second as a "GET 2" or similar?

thank you very much


问:
How do I test DataDog RUM's custom actions using Jest?
I have the following MWE [1], and I want to test the DataDog's custom actions triggered by the click events using Jest.

import React from 'react';
import { datadogRum } from '@datadog/browser-rum';

export function App(props) {
  return (

       { datadogRum.addAction("user went to mars", {}) }}>Let's go to Mars!
       { datadogRum.addAction("user went to earth", {}) }}>Let's go to Earth!

  );
}
```

[1]: Assume that I've setup DataDog's browser SDK properly, and user actions logs are already being sent to DataDog.

Body:
I have the following MWE [1], and I want to test the DataDog's custom actions triggered by the click events using Jest.

import React from 'react';
import { datadogRum } from '@datadog/browser-rum';

export function App(props) {
  return (

       { datadogRum.addAction("user went to mars", {}) }}>Let's go to Mars!
       { datadogRum.addAction("user went to earth", {}) }}>Let's go to Earth!

  );
}

[1]: Assume that I've setup DataDog's browser SDK properly, and user actions logs are already being sent to DataDog.


问:
Google Cloud Deploy with Npm issues
pretty new to GCP and deployment in general, want to ask some question .

i've been deploying fine since the last 2 years using GCP and cloud repo with github and suddenly got into this error when try to deploy again (npm install and build runs fine, but got into this error when performing GCP app deploy) , nothing has changed, not even related to the material ui core libraries, i've tried removing the library just to test things out and same result, i think something is wrong with the GCP deployment.

I hope some pros can help me out with this issue :D thanks

Already have image (with digest): gcr.io/cloud-builders/gcloud
Services to deploy:

descriptor:                  [/workspace/app.yaml]
source:                      [/workspace]
target project:

target service:              [default]
target version:

target url:

target service account:      [App Engine default service account]

Do you want to continue (Y/n)?

Beginning deployment of service [default]...
╔════════════════════════════════════════════════════════════╗
╠═ Uploading 2 files to Google Cloud Storage                ═╣
╚════════════════════════════════════════════════════════════╝
File upload done.
Updating service [default]...
..............................................................................................................................................................................................................................failed.
ERROR: (gcloud.app.deploy) Error Response: [9] Cloud build f91f8114-8daf-4b41-b172-c6d04048e44e status: FAILURE
npm ERR! Cannot read property '@material-ui/core' of undefined

npm ERR! A complete log of this run can be found in:
npm ERR!     /www-data-home/.npm/_logs/2022-12-16T17_05_33_030Z-debug.log

thought it was a problem related to specific libraries i use, even though libraries are not changed compared to my previous deployment, but got the same result when i deleted the library, tried other libraries , same result

Title: Google Cloud Deploy with Npm issues


问:
Axios call to AWS API gateway is returning status code of 0 when using a token authorizer
I am using the AWS API gateway to call my Lambda function. For authorization I am using a custom authorizer like so:

```<code>const MyCustomJwt = require("customPackages");
const warmer = require("lambda-warmer");

exports.handler = async (event, context, callback) => {

    if (await warmer(event)) {
        console.log("Warming");
        return 'warmed';
    }

    try {
        let token = extractTokenFromHeader(event) || '';
        const webAuth = new MyCustomJwt();
        await webAuth.authenticateWebToken(token);

        callback(null, generatePolicy('user', 'Allow', event.methodArn));

    }
    catch (e) {
        console.log(e);
      return callback(null, generatePolicy('user', 'Deny', event.methodArn));
      }
};

function extractTokenFromHeader(e) {
    if (e.authorizationToken && e.authorizationToken.split(' ')[0] === 'Bearer') {
        return e.authorizationToken.split(' ')[1];
    }
    else {
        return e.authorizationToken;
    }
}

// Help function to generate an IAM policy
function generatePolicy(principalId, effect, resource) {
    var authResponse = {};
    authResponse.principalId = principalId;
    if (effect && resource) {
        var policyDocument = {};
        policyDocument.Version = '2012-10-17';
        policyDocument.Statement = [];
        var statementOne = {};
        statementOne.Action = 'execute-api:Invoke';
        statementOne.Effect = effect;
        statementOne.Resource = resource;
        policyDocument.Statement[0] = statementOne;
        authResponse.policyDocument = policyDocument;
    }
    return authResponse;
}

</code>```

I am then calling the api gateway from my angular application, using Axios:

```<code>public getData(dataType: string, filters: any) {
  try {
    axios.defaults.headers.post['Content-Type'] = 'application/json';
    axios.defaults.headers.post['Authorization'] = localStorage.getItem('token') || '';

    return axios.post('https://myendpoint.com/web-data-api', {
      dataType,
      filters
    }).then((response) => {
      return decompress(response.data).data;
    }).catch(error => {
      // this.alertService.openAlert('error', 'Please check your details and try again');
      console.log(error.response.status);
      return;
    })
  } catch (e) {
    // this.alertService.openAlert('error', 'An Error Occurred');
    // return;
    return;
  }
}
</code>```

When I send the request with a invalid token I get the status returned as 0. But in the console it shows auth error followed by 403 like in the attached image:

Example

Body:
I am using the AWS API gateway to call my Lambda function. For authorization I am using a custom authorizer like so:

const MyCustomJwt = require("customPackages");
const warmer = require("lambda-warmer");

exports.handler = async (event, context, callback) => {

    if (await warmer(event)) {
        console.log("Warming");
        return 'warmed';
    }

    try {
        let token = extractTokenFromHeader(event) || '';
        const webAuth = new MyCustomJwt();
        await webAuth.authenticateWebToken(token);

        callback(null, generatePolicy('user', 'Allow', event.methodArn));

    }
    catch (e) {
        console.log(e);
      return callback(null, generatePolicy('user', 'Deny', event.methodArn));
      }
};

function extractTokenFromHeader(e) {
    if (e.authorizationToken && e.authorizationToken.split(' ')[0] === 'Bearer') {
        return e.authorizationToken.split(' ')[1];
    }
    else {
        return e.authorizationToken;
    }
}

// Help function to generate an IAM policy
function generatePolicy(principalId, effect, resource) {
    var authResponse = {};
    authResponse.principalId = principalId;
    if (effect && resource) {
        var policyDocument = {};
        policyDocument.Version = '2012-10-17';
        policyDocument.Statement = [];
        var statementOne = {};
        statementOne.Action = 'execute-api:Invoke';
        statementOne.Effect = effect;
        statementOne.Resource = resource;
        policyDocument.Statement[0] = statementOne;
        authResponse.policyDocument = policyDocument;
    }
    return authResponse;
}

I am then calling the api gateway from my angular application, using Axios:

public getData(dataType: string, filters: any) {
  try {
    axios.defaults.headers.post['Content-Type'] = 'application/json';
    axios.defaults.headers.post['Authorization'] = localStorage.getItem('token') || '';

    return axios.post('https://myendpoint.com/web-data-api', {
      dataType,
      filters
    }).then((response) => {
      return decompress(response.data).data;
    }).catch(error => {
      // this.alertService.openAlert('error', 'Please check your details and try again');
      console.log(error.response.status);
      return;
    })
  } catch (e) {
    // this.alertService.openAlert('error', 'An Error Occurred');
    // return;
    return;
  }
}

When I send the request with a invalid token I get the status returned as 0. But in the console it shows auth error followed by 403 like in the attached image:

Example


问:
Create Color Data using RGB
My data include pictures of some products that I manage to extract their major RGB colors into four columns as displayed in the table below ("product ID", "R", "G", "B"). Now, I want to create the fifth column "color code" to display the actual color from the RGB code. Please see the demonstration here.

I plan to use this "color code" column as a filter. I will show this column as a pallet or a drop-down list so that my users can select the color(s) that they want to see the products or other information. The platform to build the report with the filter will be BI tools (PowerBI/QuickSight) or Excel. Note that my product pictures are currently stored in AWS S3.

My initial plan is to create an image, like a square filled with the color for each product, using its RGB code. Then store those images in the data warehouse and call them for filter later.

Can you please recommend the best way to create the type of color data as described for speed and efficiency?

Title: Create Color Data using RGB


问:
Can i run jpa crud without application properties file ? i want to use config class instead of application.properties file
I want to use a config class instead of an application's properties file, and if you have any ideas about it, please share them!

I attempted to set the configuration in the class file, but it returned an error, and I'm at a loss for what to do.


问:
Writing spatial file to Oracle database using R?
I'm trying to write a spatial file to an Oracle database using R, but I keep getting an error. The error message doesn't provide much information, so I'm not clear what the issue is. I'm not even too sure if this is possible. However, I am able to create an empty table in the database with a SDO_GEOMETRY field type using sqlDeveloper, so it seems like it is possible.

Sample code of what I have tried:

```<code>library(DBI)
library(odbc)
library(tigris)

    sf_state <- states(year = 2021, cb = FALSE)

    dbWriteTable(conn        = db_conn,
                 value       = sf_state,
                 name        = "TEST_TABLE",
                 field.types = c(geometry = "SDO_GEOMETRY"))
</code>```

Body:
I'm trying to write a spatial file to an Oracle database using R, but I keep getting an error. The error message doesn't provide much information, so I'm not clear what the issue is. I'm not even too sure if this is possible. However, I am able to create an empty table in the database with a SDO_GEOMETRY field type using sqlDeveloper, so it seems like it is possible.

Sample code of what I have tried:

library(DBI)
library(odbc)
library(tigris)

    sf_state <- states(year = 2021, cb = FALSE)

    dbWriteTable(conn        = db_conn,
                 value       = sf_state,
                 name        = "TEST_TABLE",
                 field.types = c(geometry = "SDO_GEOMETRY"))


问:
date format not showing correctly for effective/experiation
when we click on the above grid data should be shown below the textbox it going perfectly but date textbox not showing the date correctly

here my date showing perfectly but when we select and bind using the help of ajax it not showing the actual date (https://i.stack.imgur.com/3HRS8.png)here is an image where I got the date format incorrect


问:
Run Spark on GKE vs Dataproc on GKE
We are planning to move our Spark Structured Streaming jobs from Cloudera to GCP. My question is similar to the one asked here. But since it has been a while that the question is active, we are wondering if there are any advantages of running DataProc on GKE? And are there production deployments that installs and manages Spark directly on GKE without Dataproc.

Cost is of a concern (like most places :)) and the assumption is that it would be cheaper to run Spark on GKE with out Dataproc.

PS: We have other applications and datastores running on GKE.

Title: Run Spark on GKE vs Dataproc on GKE


问:
Run script as root every 5 minutes with crontab
I have a shell script which I want to execute every 5 minutes as user root.

curl http://localhost/external_ip.php
HOSTNAME=pi.marvinkleinmusic.de
LOGFILE=/var/update-dns/log.txt

Current_IP=$(host $HOSTNAME | cut -f4 -d' ')

if [ $LOGFILE = "" ] ; then
  ufw allow from $Current_IP
  echo $Current_IP > $LOGFILE
else

  Old_IP=$(cat $LOGFILE)

  if [ "$Current_IP" = "$Old_IP" ] ; then
    echo IP address has not changed
  else
    sudo ufw delete allow from $Old_IP
    sudo ufw allow from $Current_IP

    echo $Current_IP > $LOGFILE
    echo firewall has been updated
  fi
fi
```
<p>To achive this I have entered the following commands:</p>
```sudo -i
crontab -e
```
<p>Within crontab I specified a new cronjob with this line:</p>
```5/5 * * * * ./var/update-dns/updateDNS.sh
```

However the script does not get executed. When I call ./var/update-dns/updateDNS.sh from the root of my Raspberry PI, everythings works as it should.

What do I'll need to change to get this working? Do I'll need to enable crontab somehow?

Also is there any way to see if this task has been executed by my raspberry pi?

Body:
I have a shell script which I want to execute every 5 minutes as user root.

curl http://localhost/external_ip.php
HOSTNAME=pi.marvinkleinmusic.de
LOGFILE=/var/update-dns/log.txt

Current_IP=$(host $HOSTNAME | cut -f4 -d' ')

if [ $LOGFILE = "" ] ; then
  ufw allow from $Current_IP
  echo $Current_IP > $LOGFILE
else

  Old_IP=$(cat $LOGFILE)

  if [ "$Current_IP" = "$Old_IP" ] ; then
    echo IP address has not changed
  else
    sudo ufw delete allow from $Old_IP
    sudo ufw allow from $Current_IP

    echo $Current_IP > $LOGFILE
    echo firewall has been updated
  fi
fi

To achive this I have entered the following commands:

sudo -i
crontab -e

Within crontab I specified a new cronjob with this line:

5/5 * * * * ./var/update-dns/updateDNS.sh

However the script does not get executed. When I call ./var/update-dns/updateDNS.sh from the root of my Raspberry PI, everythings works as it should.

What do I'll need to change to get this working? Do I'll need to enable crontab somehow?

Also is there any way to see if this task has been executed by my raspberry pi?


问:
Im trying to put my discord bot online bit it comes up with an error
So here is the error it comes up with when i do node . or node main.js:

```<code> throw new DiscordjsRangeError(ErrorCodes.BitFieldInvalid, bit);
    ^

RangeError [BitFieldInvalid]: Invalid bitfield flag or number: GUILDS.
    at IntentsBitField.resolve (C:\Users\Kaydin Cain\Desktop\DiscordBot\node_modules\discord.js\src\util\BitField.js:168:11)
    at C:\Users\Kaydin Cain\Desktop\DiscordBot\node_modules\discord.js\src\util\BitField.js:163:54
    at Array.map (<anonymous>)
    at IntentsBitField.resolve (C:\Users\Kaydin Cain\Desktop\DiscordBot\node_modules\discord.js\src\util\BitField.js:163:40)
    at new BitField (C:\Users\Kaydin Cain\Desktop\DiscordBot\node_modules\discord.js\src\util\BitField.js:33:38)
    at new IntentsBitField (C:\Users\Kaydin Cain\Desktop\DiscordBot\node_modules\discord.js\src\util\IntentsBitField.js:9:1)
    at Client._validateOptions (C:\Users\Kaydin Cain\Desktop\DiscordBot\node_modules\discord.js\src\client\Client.js:491:25)
    at new Client (C:\Users\Kaydin Cain\Desktop\DiscordBot\node_modules\discord.js\src\client\Client.js:78:10)
    at Object.<anonymous> (C:\Users\Kaydin Cain\Desktop\DiscordBot\main.js:4:16)
    at Module._compile (node:internal/modules/cjs/loader:1159:14) {
  code: 'BitFieldInvalid'
}

Node.js v18.12.1
</code>```

Can anyone help?

I tried many things and nothing worked unless there is something wrong with  my code or im doing a command wrong then i have no idea.

Body:
So here is the error it comes up with when i do node . or node main.js:

 throw new DiscordjsRangeError(ErrorCodes.BitFieldInvalid, bit);
    ^

RangeError [BitFieldInvalid]: Invalid bitfield flag or number: GUILDS.
    at IntentsBitField.resolve (C:\Users\Kaydin Cain\Desktop\DiscordBot\node_modules\discord.js\src\util\BitField.js:168:11)
    at C:\Users\Kaydin Cain\Desktop\DiscordBot\node_modules\discord.js\src\util\BitField.js:163:54
    at Array.map (<anonymous>)
    at IntentsBitField.resolve (C:\Users\Kaydin Cain\Desktop\DiscordBot\node_modules\discord.js\src\util\BitField.js:163:40)
    at new BitField (C:\Users\Kaydin Cain\Desktop\DiscordBot\node_modules\discord.js\src\util\BitField.js:33:38)
    at new IntentsBitField (C:\Users\Kaydin Cain\Desktop\DiscordBot\node_modules\discord.js\src\util\IntentsBitField.js:9:1)
    at Client._validateOptions (C:\Users\Kaydin Cain\Desktop\DiscordBot\node_modules\discord.js\src\client\Client.js:491:25)
    at new Client (C:\Users\Kaydin Cain\Desktop\DiscordBot\node_modules\discord.js\src\client\Client.js:78:10)
    at Object.<anonymous> (C:\Users\Kaydin Cain\Desktop\DiscordBot\main.js:4:16)
    at Module._compile (node:internal/modules/cjs/loader:1159:14) {
  code: 'BitFieldInvalid'
}

Node.js v18.12.1

Can anyone help?

I tried many things and nothing worked unless there is something wrong with  my code or im doing a command wrong then i have no idea.


问:
How to cancel webdriver.Remote() as early as possible if max_sessions have been reached?
My goal is to use Selenium with a python app.

The problem is, the python app will restart at some time without the ability to call driver.quit(). By the time the python app restarted, it can't reconnect to Selenium.

The other alternative that I could think of is to kick session if the max_sessions have been reached but I can't find option to do that.

The code

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--disable-infobars")
chrome_options.add_argument("--start-maximized")
chrome_options.add_argument("--disable-notifications")
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')

driver = webdriver.Remote(options=chrome_options)
</code>```

The selenium

```<code>docker run -d -p 4444:4444 -m=300m -e SE_NODE_SESSION_TIMEOUT=172800 seleniarm/standalone-chromium
</code>```

Body:
My goal is to use Selenium with a python app.

The problem is, the python app will restart at some time without the ability to call driver.quit(). By the time the python app restarted, it can't reconnect to Selenium.

The other alternative that I could think of is to kick session if the max_sessions have been reached but I can't find option to do that.

The code

from selenium import webdriver
from selenium.webdriver.common.by import By

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--disable-infobars")
chrome_options.add_argument("--start-maximized")
chrome_options.add_argument("--disable-notifications")
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')

driver = webdriver.Remote(options=chrome_options)

The selenium

docker run -d -p 4444:4444 -m=300m -e SE_NODE_SESSION_TIMEOUT=172800 seleniarm/standalone-chromium


问:
req.session not available in another route
when tryin to access the req.session.user value in another route it returns undefinded

`

```<code>const router = require("express").Router();
const newUser = require("../models/newUser");

router.post("/", async (req, res) => {
    const { email, password } = req.body;
    const findUser = await newUser.findOne({ email, password });

    if (!findUser) {
        res.send("user not found");
    }
    else {
        res.sendStatus(200);
        req.session.user = "authenticated";
    }
})

router.post("/authorization", (req, res, next) => {
    const auth = req.session.user

    if (!auth) {
        res.sendStatus(403)
    }
    else {
        next()
    }
})

module.exports = router;
</code>```

`

I tried sending a response after the cookie was set. I have moved my middleware around (routes come after my cookie )

Body:
when tryin to access the req.session.user value in another route it returns undefinded

`

const router = require("express").Router();
const newUser = require("../models/newUser");

router.post("/", async (req, res) => {
    const { email, password } = req.body;
    const findUser = await newUser.findOne({ email, password });

    if (!findUser) {
        res.send("user not found");
    }
    else {
        res.sendStatus(200);
        req.session.user = "authenticated";
    }
})

router.post("/authorization", (req, res, next) => {
    const auth = req.session.user

    if (!auth) {
        res.sendStatus(403)
    }
    else {
        next()
    }
})

module.exports = router;

`

I tried sending a response after the cookie was set. I have moved my middleware around (routes come after my cookie )


问:
The Django serializer for MongoDB does not display data correctly
So, I have 2 models, Flow and Step.I want when the Flows to be displayed, and the Steps corresponding to this Flow should also be displayed, something that doesn't happen even though it should(I want to specify that before switching to Mongo, I was using another library for the serializer and everything was working perfectly, now not, and I need it this way).

Flow model:

class Flow(BaseModel):
     class BrowserInstance(Enum):
         CHROME = 'chrome'
         FIREFOX = 'firefox'

     name = StringField()
     url = URLField()

     browser = StringField(choices=list(item.value for item in BrowserInstance), default=BrowserInstance.CHROME.value)
     scheduling = StringField()
     next_schedule = DateTimeField(default=timezone.now, null=True)
     is_active = BooleanField(default=False)
     user = ReferenceField(User, reverse_delete_rule=CASCADE, null=False)
```
<p><strong>Step model:</strong></p>
<pre class="lang-py prettyprint-override"><code>class Step(BaseModel):
     class Action(Enum):
         CLICK = 'click'
         TAPPING = 'tapping'
         SUBMIT = 'submit'
         CLEAR = 'clear'
         ENTER = 'enter'

     step_number = IntField()
     action = StringField(choices=list(item.value for item in Action), default=Action.CLICK.value)
     selector_xpath = StringField(max_length=254)
     content = StringField(max_length=254, blank=True)
     flow = ReferenceField(Flow, reverse_delete_rule=CASCADE, related_name='steps')
</code>```

StepSerializer:

class StepSerializer(DocumentSerializer):
     class Meta:
         pattern = Step
         fields = ('id', 'step_number', 'action', 'selector_xpath', 'content')
```
<p><strong>FlowSerializer:</strong></p>
<pre class="lang-py prettyprint-override"><code>class FlowSerializer(DocumentSerializer):
     steps = StepSerializer(many=True, required=False, allow_null=True)

     class Meta:
         model = Flow
         fields = "__all__"
</code>```

When I execute the get/retrieve endpoint, next to the steps I receive the value null (if I accept it) and nothing if not.
The Steps are created correctly and correspond to the Flow for which they were created.

What can be the problem? I tried several methods and they don't work

Clarification: I need the most optimal method, so SerializerMethod /property or to_representation can be canceled, the team lead forbade me these options.

Body:
So, I have 2 models, Flow and Step.I want when the Flows to be displayed, and the Steps corresponding to this Flow should also be displayed, something that doesn't happen even though it should(I want to specify that before switching to Mongo, I was using another library for the serializer and everything was working perfectly, now not, and I need it this way).

Flow model:

class Flow(BaseModel):
     class BrowserInstance(Enum):
         CHROME = 'chrome'
         FIREFOX = 'firefox'

     name = StringField()
     url = URLField()

     browser = StringField(choices=list(item.value for item in BrowserInstance), default=BrowserInstance.CHROME.value)
     scheduling = StringField()
     next_schedule = DateTimeField(default=timezone.now, null=True)
     is_active = BooleanField(default=False)
     user = ReferenceField(User, reverse_delete_rule=CASCADE, null=False)

Step model:

class Step(BaseModel):
     class Action(Enum):
         CLICK = 'click'
         TAPPING = 'tapping'
         SUBMIT = 'submit'
         CLEAR = 'clear'
         ENTER = 'enter'

     step_number = IntField()
     action = StringField(choices=list(item.value for item in Action), default=Action.CLICK.value)
     selector_xpath = StringField(max_length=254)
     content = StringField(max_length=254, blank=True)
     flow = ReferenceField(Flow, reverse_delete_rule=CASCADE, related_name='steps')

StepSerializer:

class StepSerializer(DocumentSerializer):
     class Meta:
         pattern = Step
         fields = ('id', 'step_number', 'action', 'selector_xpath', 'content')

FlowSerializer:

class FlowSerializer(DocumentSerializer):
     steps = StepSerializer(many=True, required=False, allow_null=True)

     class Meta:
         model = Flow
         fields = "__all__"

When I execute the get/retrieve endpoint, next to the steps I receive the value null (if I accept it) and nothing if not.
The Steps are created correctly and correspond to the Flow for which they were created.

What can be the problem? I tried several methods and they don't work

Clarification: I need the most optimal method, so SerializerMethod /property or to_representation can be canceled, the team lead forbade me these options.


问:
Where to place resources, like drawables so Cordova (v11) CLI prepare picks them up?
I have a PNG I added as a drawable via Android Studio, which places it at

/platforms/android/app/src/main/res/drawable/foo.png

If I understand correctly, this folder is only a "build artifact" and will be recreated whole cloth when I do cordova platform add android; /platforms/ being .gitignored supports this assumption.

So, where do I put assets/resources, other than splash.png and icon.png, so they're placed in platforms when I do cordova prepare?

I've only found contradicting and outdated information (e.g. /res being deprecated).

Are there Android and iOS quirks?

I'm using Cordova 11.0.0.


Title: Python - Calclulating angles of triangle with coordinates

Body:
I would like to create a 'triangle-mesh proofing skript', which would be able to find all angles in triangles, which are smaller than 10°.

The grafic example of the triangle mesh:

As my imput data i have list of element (triangles) with IDs of nodes which create them and nodes with their coordinates.

Elements [E3T element_id node_id node_id node_id]:

E3T 1540636 808597 808596 807843 1
E3T 1540637 808597 807843 807844 1
E3T 1540638 808597 807844 808598 1
E3T 1540639 807844 807845 808598 1
E3T 1540640 807845 807846 808598 1
E3T 1540641 808599 807846 807847 1
E3T 1540642 807846 808599 808598 1

And nodes [ND node_id x y z]

ND 778832 6.72399110e+005 5.33328776e+006 5.55937900e+002
ND 778833 6.72408176e+005 5.33328965e+006 5.55924300e+002
ND 778834 6.72404065e+005 5.33328561e+006 5.55974000e+002
ND 778835 6.72396071e+005 5.33329296e+006 5.56330400e+002
ND 778836 6.72394000e+005 5.33329700e+006 5.57010000e+002
ND 778837 6.72393587e+005 5.33329863e+006 5.57028500e+002
ND 778838 6.72409000e+005 5.33329600e+006 5.55550000e+002
ND 778839 6.72389548e+005 5.33329571e+006 5.56683100e+002

I would appreciate any suggestions for the quickest way to:

Find all elements with angles <10°

Find the node which creates the largest angle in the triangle.

Thank you.


问:
Springboot based framework Each classes has different methods or test. the probelm class b running first instead of class A
This is class A where I have one method which need to run before class B</p>
```<code>class test_a {
@Test(enabled = true, priority = 1)
public void Verify_Code_Email_Registration() {
System.out.println("Verify_Code_Email_Registration");
}

}
This is class b.This should run after class A
class Test_b {
@Test(enabled = true, priority = 1)
public void Generate_Code_PHONE() {
System.out.println("Generate_Code_phone");
}
}
</code>```

Body:
This is class A where I have one method which need to run before class B

class test_a {
@Test(enabled = true, priority = 1)
public void Verify_Code_Email_Registration() {
System.out.println("Verify_Code_Email_Registration");
}

}
This is class b.This should run after class A
class Test_b {
@Test(enabled = true, priority = 1)
public void Generate_Code_PHONE() {
System.out.println("Generate_Code_phone");
}
}


问:
Checking a database to see if an email is there before login in in Android Studio
So I am logging in to a database. I want to check to see if the email is actually inside the database before logging into the app.

API Response

```<code>data class LoginResponse(
    @SerializedName("data") val data: List<DataInfo>,
    @SerializedName("status") val status: Int,
    @SerializedName("message") var message: String
){
    override fun toString(): String {
        return "\n" +
                "List of Data: $data" +
                "Status: $status" +
                "Message:$message"
    }
}

data class DataInfo(
    @SerializedName("Id") val id: Int,
    @SerializedName("CustomerId") val customerId: String,
    @SerializedName("UserAttributeId") val userAttributeId: Int,
    @SerializedName("Enabled") val enabled: Boolean
){

    override fun toString(): String {
        return "\n" +
                "Id: $id" +
                "CustomerId: $customerId" +
                "UserAttributeId: $userAttributeId" +
                "Enabled: $enabled"
    }

}
</code>```

Where the logging action takes place

```<code>@Composable
fun MMRLoginScreen(navController: NavController, loginViewModel: LoginViewModel = hiltViewModel()){

    val login by loginViewModel.loginResponse.observeAsState()
    val context = LocalContext.current

    Surface(modifier = Modifier
        .fillMaxSize()
        .padding(top = 65.dp)
    ) {
        Column(
            verticalArrangement = Arrangement.Top,
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {
            Image(
                painter = painterResource(id = R.drawable.parabit_logo_orange_blue),
                contentDescription = stringResource(R.string.company_logo_string),
                contentScale = ContentScale.Fit,
                modifier = Modifier
                    .width(225.dp)
                    .height(95.dp)
                    .padding(top = 43.dp)
                )

            Text(
                text = "MMR Bluetooth Access Control",
                color = Color(0xFFF47B20),
                fontWeight = Bold,
                fontSize = 18.sp,
            )
            Spacer(modifier = Modifier.height(10.dp))

            LoginField(loading = false){
                when(login){
                    is Resource.Success ->{
                        Toast.makeText(context, it, Toast.LENGTH_LONG).show()
                    }
                    is Resource.Failure -> {
                        Toast.makeText(context, "Login Failure", Toast.LENGTH_LONG).show()
                    }
                }
                loginViewModel.login(email = it, mobileMake = "Android ${Build.MODEL}")
                navController.navigate(MMRScreens.MainScreen.name)
            }

        }
    }

}

//@Composable
//fun ValidationComposable(){
//    var email by remember { mutableStateOf("") }
//    val emailTextUpdate = { data: String ->
//        email = data
//    }
//}

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun LoginField(
    loading: Boolean = false,
    onDone: (String) -> Unit = { email ->}
){
    val email = rememberSaveable { mutableStateOf("") }
    val keyboardController = LocalSoftwareKeyboardController.current
    val valid = remember(email.value){
        email.value.trim().isNotEmpty()
    }
    val context = LocalContext.current

    Column(
        modifier = Modifier,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        EmailInput(
            emailState = email,
        )

        SubmitButton(
            textId = "Login",
            loading = loading,
            validInputs = valid
        ){
            if (!email.value.contains("@parabit.com")){
                Toast.makeText(context, "Please enter a valid Parabit email", Toast.LENGTH_LONG).show()
            }
            else{
                onDone(email.value.trim())
                keyboardController?.hide()
            }
        }
    }
}
</code>```

A simple check to make sure that the input the user made is inside the database is the objective here. Any suggestions will be appreciated. Thank you.

Body:
So I am logging in to a database. I want to check to see if the email is actually inside the database before logging into the app.

API Response

data class LoginResponse(
    @SerializedName("data") val data: List<DataInfo>,
    @SerializedName("status") val status: Int,
    @SerializedName("message") var message: String
){
    override fun toString(): String {
        return "\n" +
                "List of Data: $data" +
                "Status: $status" +
                "Message:$message"
    }
}

data class DataInfo(
    @SerializedName("Id") val id: Int,
    @SerializedName("CustomerId") val customerId: String,
    @SerializedName("UserAttributeId") val userAttributeId: Int,
    @SerializedName("Enabled") val enabled: Boolean
){

    override fun toString(): String {
        return "\n" +
                "Id: $id" +
                "CustomerId: $customerId" +
                "UserAttributeId: $userAttributeId" +
                "Enabled: $enabled"
    }

}

Where the logging action takes place

@Composable
fun MMRLoginScreen(navController: NavController, loginViewModel: LoginViewModel = hiltViewModel()){

    val login by loginViewModel.loginResponse.observeAsState()
    val context = LocalContext.current

    Surface(modifier = Modifier
        .fillMaxSize()
        .padding(top = 65.dp)
    ) {
        Column(
            verticalArrangement = Arrangement.Top,
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {
            Image(
                painter = painterResource(id = R.drawable.parabit_logo_orange_blue),
                contentDescription = stringResource(R.string.company_logo_string),
                contentScale = ContentScale.Fit,
                modifier = Modifier
                    .width(225.dp)
                    .height(95.dp)
                    .padding(top = 43.dp)
                )

            Text(
                text = "MMR Bluetooth Access Control",
                color = Color(0xFFF47B20),
                fontWeight = Bold,
                fontSize = 18.sp,
            )
            Spacer(modifier = Modifier.height(10.dp))

            LoginField(loading = false){
                when(login){
                    is Resource.Success ->{
                        Toast.makeText(context, it, Toast.LENGTH_LONG).show()
                    }
                    is Resource.Failure -> {
                        Toast.makeText(context, "Login Failure", Toast.LENGTH_LONG).show()
                    }
                }
                loginViewModel.login(email = it, mobileMake = "Android ${Build.MODEL}")
                navController.navigate(MMRScreens.MainScreen.name)
            }

        }
    }

}

//@Composable
//fun ValidationComposable(){
//    var email by remember { mutableStateOf("") }
//    val emailTextUpdate = { data: String ->
//        email = data
//    }
//}

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun LoginField(
    loading: Boolean = false,
    onDone: (String) -> Unit = { email ->}
){
    val email = rememberSaveable { mutableStateOf("") }
    val keyboardController = LocalSoftwareKeyboardController.current
    val valid = remember(email.value){
        email.value.trim().isNotEmpty()
    }
    val context = LocalContext.current

    Column(
        modifier = Modifier,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        EmailInput(
            emailState = email,
        )

        SubmitButton(
            textId = "Login",
            loading = loading,
            validInputs = valid
        ){
            if (!email.value.contains("@parabit.com")){
                Toast.makeText(context, "Please enter a valid Parabit email", Toast.LENGTH_LONG).show()
            }
            else{
                onDone(email.value.trim())
                keyboardController?.hide()
            }
        }
    }
}

A simple check to make sure that the input the user made is inside the database is the objective here. Any suggestions will be appreciated. Thank you.


问:
How to resolve 'Request header is too large' error in Spring Boot 3.0.0
I am getting the following error when doing a simple GET request to an endpoint. After running the app I just hit http://localhost:8080/api/user.

```<code>java.lang.IllegalArgumentException: Request header is too large
    org.apache.coyote.http11.Http11InputBuffer.fill(Http11InputBuffer.java:790)
    org.apache.coyote.http11.Http11InputBuffer.parseHeader(Http11InputBuffer.java:975)
    org.apache.coyote.http11.Http11InputBuffer.parseHeaders(Http11InputBuffer.java:604)
    org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:295)
    org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1739)
    org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
    org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.base/java.lang.Thread.run(Thread.java:833)
</code>```

The embedded tomcat core version is 10.1.1 and java version is 17.

I know we can specify the max header size in server.max-http-header-size inside application properties but in Spring Boot 3.0.0 that are deprecated and will be removed soon. So, I don't want to use that for resolving this issue.

If anybody knows how to solve this issue in latest release if spring boot (3.x.x) that would be a great help for me. Thanks in advance.

Body:
I am getting the following error when doing a simple GET request to an endpoint. After running the app I just hit http://localhost:8080/api/user.

java.lang.IllegalArgumentException: Request header is too large
    org.apache.coyote.http11.Http11InputBuffer.fill(Http11InputBuffer.java:790)
    org.apache.coyote.http11.Http11InputBuffer.parseHeader(Http11InputBuffer.java:975)
    org.apache.coyote.http11.Http11InputBuffer.parseHeaders(Http11InputBuffer.java:604)
    org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:295)
    org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1739)
    org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
    org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.base/java.lang.Thread.run(Thread.java:833)

The embedded tomcat core version is 10.1.1 and java version is 17.

I know we can specify the max header size in server.max-http-header-size inside application properties but in Spring Boot 3.0.0 that are deprecated and will be removed soon. So, I don't want to use that for resolving this issue.

If anybody knows how to solve this issue in latest release if spring boot (3.x.x) that would be a great help for me. Thanks in advance.


问:
Annotations for Google Cloud Monitoring charts
I'd like to add annotations to Google Cloud Monitoring charts in the same manner that I can for Grafana charts.  Is that possible?</p>


问:
Why is Foundation media queries not working when i use a breakpoint name?
I have tested other js components like accordions and they work fine. For some reason media queries are not working as expected.

Any hints on what going on?

For example:

```<code>.header-first, .header-second {
     @include breakpoint(medium) {
         background: $cerulean;
    }
}
</code>```

compiles to the below where the name of the breakpoint is added but not the size of 640px as in the _settings.scss:

```<code>@media (min-width: medium) {
     .header .header-first, .header .header-second {
         background: #0098db;
    }
}
</code>```

I have tested that _settings.scss is working by customizing other components. I have also tested that the js is working with:
console.log('Current: ' + Foundation.MediaQuery.current)

Body:
I have tested other js components like accordions and they work fine. For some reason media queries are not working as expected.

Any hints on what going on?

For example:

.header-first, .header-second {
     @include breakpoint(medium) {
         background: $cerulean;
    }
}

compiles to the below where the name of the breakpoint is added but not the size of 640px as in the _settings.scss:

@media (min-width: medium) {
     .header .header-first, .header .header-second {
         background: #0098db;
    }
}

I have tested that _settings.scss is working by customizing other components. I have also tested that the js is working with:
console.log('Current: ' + Foundation.MediaQuery.current)


问:
Cannot download a PDF in Flutter and show error
I am trying to develop an app that downloads files from URLs, such as images, pdf, videos and etc,
I am using Android 12 for Mobile device and  these Plugin :

```<code>  path_provider_android: ^2.0.12
  flutter_downloader: ^1.7.3
  permission_handler: ^9.2.0
  device_info_plus: ^3.2.3
  path_provider: ^2.0.9
</code>```

This is the main.dart file

```<code>import 'package:download_file_app/my_download.dart';
import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';

const debug = true;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await FlutterDownloader.initialize(
      debug: debug // optional: set false to disable printing logs to console
       );
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final platform = Theme.of(context).platform;
    return  MaterialApp(
      title: 'Flutter Demo',
      theme:   ThemeData(
        primarySwatch: Colors.blue,
      ),
      home:  MyDownload(
        platform: platform,
      ),
    );
  }
}
</code>```

And this is the MyDownload Class

```<code>class MyDownload extends StatefulWidget {
  final TargetPlatform? platform;

  MyDownload({this.platform});

  @override
  _MyDownloadState createState() => _MyDownloadState();
}

class _MyDownloadState extends State<MyDownload> {
  ReceivePort _port = ReceivePort();
  late bool _isLoading;
  late bool _permissionReady;
  late String _localPath;

  final _documents = [
    {
      'name': 'Learning Android Studio',
      'link': 'http://barbra-coco.dyndns.org/student/learning_android_studio.pdf'
    },
    {
      'name': 'Canyonlands National Park',
      'link': 'https://upload.wikimedia.org/wikipedia/commons/7/78/Canyonlands_National_Park%E2%80%A6Needles_area_%286294480744%29.jpg'
    },
    {
      'name': 'Big Buck Bunny',
      'link':
      'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4'
    },
  ];

  late List<MyItem> itemsList;

  @override
  void initState() {
    super.initState();
    _bindBackgroundIsolate();
    FlutterDownloader.registerCallback(downloadCallback);
    _isLoading = true;
    _permissionReady = false;
    _prepare();
  }

  void _bindBackgroundIsolate() {
    bool isSuccess = IsolateNameServer.registerPortWithName(
        _port.sendPort, 'downloader_send_port');
    if (!isSuccess) {
      _unbindBackgroundIsolate();
      _bindBackgroundIsolate();
      return;
    }
    _port.listen((dynamic data) {
      if (debug) {
        print('UI Isolate Callback: $data');
      }
      /*
       Update UI with the latest progress
       */
      String? id = data[0];
      DownloadTaskStatus? status = data[1];
      int progress = data[2];

      if (itemsList.isNotEmpty ) {
        final item = itemsList.firstWhere((it) => it.itemID == id);
        setState(() {
          item.status = status;
          item.progress = progress;
        });
      }
    });
  }

  void _unbindBackgroundIsolate() {
    IsolateNameServer.removePortNameMapping('downloader_send_port');
  }

  static void downloadCallback(String id, DownloadTaskStatus status,
      int progress) {
    if (debug) {
      print(
          'Background Isolate Callback: task ($id) is in status ($status) and process ($progress)');
    }
    final SendPort send =
    IsolateNameServer.lookupPortByName('downloader_send_port')!;
    send.send([id, status, progress]);
  }

  Future<Null> _prepare() async {

    itemsList = [];
    itemsList.addAll(
        _documents.map((doc) => MyItem(name: doc['name'].toString(),
            url: doc['link'].toString())
        )
    );
    _permissionReady = await _checkPermission();

    if (_permissionReady) {
      await _prepareSaveDir();
    }

    setState(() {
      _isLoading = false;
    });
  }

  Future<bool> _checkPermission() async {
    if (Platform.isIOS) return true;

    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
    if (widget.platform == TargetPlatform.android )
        // && androidInfo.version.sdkInt! <= 28)
    {
      final status = await Permission.storage.status;
      if (status != PermissionStatus.granted) {
        final result = await Permission.storage.request();
        if (result == PermissionStatus.granted) {
          return true;
        }
      } else {
        return true;
      }
    } else {
      return true;
    }
    return false;
  }

  Future<void> _prepareSaveDir() async {
    _localPath = (await _findLocalPath())!;
    final savedDir = Directory(_localPath);
    bool hasExisted = await savedDir.exists();
    if (!hasExisted) {
      savedDir.create();
    }
  }

  Future<String?> _findLocalPath() async {
    var externalStorageDirPath;
    if (Platform.isAndroid) {
      try {
        externalStorageDirPath = await PathProviderAndroid().getDownloadsPath(); //AndroidPathProvider.downloadsPath;
      } catch (e) {
        final directory = await getExternalStorageDirectory();
        externalStorageDirPath = directory?.path;
      }
    } else if (Platform.isIOS) {
      externalStorageDirPath =
          (await getApplicationDocumentsDirectory()).absolute.path;
    }
    return externalStorageDirPath;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Download File App'),
        ),
        body: Builder(
            builder: (context) =>
            _isLoading
                ?  Center(child: new CircularProgressIndicator(),)
                : _permissionReady ?
                Center(child:
                ListView(
                  children: itemsList.map((it) =>
                      DownloadITem(
                            myItem: it,
                            openItem: (myItem)
                            {
                              _openDownloadedFile(myItem).then((success) {
                                if (!success) {
                                  Scaffold.of(context).showSnackBar(SnackBar(
                                      content: Text('Cannot open this file')));
                                }
                              });
                            },
                            onActionClick: (myItem)async {
                              if (myItem.status == DownloadTaskStatus.undefined) {
                                myItem.itemID = await FlutterDownloader.enqueue(
                                  url: myItem.url,
                                  savedDir: _localPath,
                                  showNotification: true,
                                  openFileFromNotification: true,
                                  saveInPublicStorage: true,
                                );
                                //_requestDownload(myItem);
                              }
                              else if (myItem.status == DownloadTaskStatus.running) {
                                await FlutterDownloader.pause(taskId: myItem.itemID!);
                                //    _pauseDownload(myItem);
                              }
                              else if (myItem.status == DownloadTaskStatus.paused) {
                                String? newTaskId = await FlutterDownloader.resume(taskId: myItem.itemID!);
                                myItem.itemID = newTaskId;
                                //_resumeDownload(myItem);
                              }
                              else if (myItem.status == DownloadTaskStatus.complete) {
                                await FlutterDownloader.remove(
                                    taskId: myItem.itemID!, shouldDeleteContent: true);
                                await _prepare();
                                setState(() {});
                               // _delete(myItem);
                              }
                              else if (myItem.status == DownloadTaskStatus.failed) {
                                String? newTaskId = await FlutterDownloader.retry(taskId: myItem.itemID!);
                                myItem.itemID = newTaskId;

                                //_retryDownload(myItem);
                              }
                            }
                            ),).toList()),)
                :
            Container(),
        ));
  }

  Future<bool> _openDownloadedFile(MyItem item) {
    if (item != null) {
      return FlutterDownloader.open(taskId: item.itemID!);
    } else {
      return Future.value(false);
    }
  }

  void _requestDownload(MyItem item) async {
    item.itemID = await FlutterDownloader.enqueue(
      url: item.url,
      savedDir: _localPath,
      showNotification: true,
      openFileFromNotification: true,
      saveInPublicStorage: true,
    );
  }

  void _pauseDownload(MyItem item) async {
    await FlutterDownloader.pause(taskId: item.itemID!);
  }

  void _retryDownload(MyItem item) async {
    String? newTaskId = await FlutterDownloader.retry(taskId: item.itemID!);
    item.itemID = newTaskId;
  }

  void _resumeDownload(MyItem item) async {
    String? newTaskId = await FlutterDownloader.resume(taskId: item.itemID!);
    item.itemID = newTaskId;
  }
  void _delete(MyItem item) async {
    await FlutterDownloader.remove(
        taskId: item.itemID!, shouldDeleteContent: true);
    await _prepare();
    setState(() {});
  }

  @override
  void dispose() {
    _unbindBackgroundIsolate();
    super.dispose();
  }
}
class DownloadITem extends StatelessWidget {
  final MyItem myItem;
  final Function(MyItem) openItem;
  final Function(MyItem) onActionClick;
  DownloadITem(
      {required this.myItem,
      required this.openItem,
      required this.onActionClick});

  @override
  Widget build(BuildContext context) {
    return Container(
      //color: Colors.pink[50],
      padding: const EdgeInsets.only(left: 16.0, right: 8.0),
      child: InkWell(
        onTap: myItem.status == DownloadTaskStatus.complete
            ? () {
                openItem(myItem);
              }
            : null,
        child:
        Stack(
          children: <Widget>[
            Container(
              width: double.infinity,
              height: 64.0,
            //  color: Colors.amber,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Expanded(
                    child: Text(myItem.name,),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 8.0),
                    child: _buildActionForTask(myItem),
                  ),
                ],
              ),
            ),
        Positioned(
                    left: 0.0,
                    right: 0.0,
                    bottom: 0.0,
                    child: LinearProgressIndicator(
                      value: myItem.progress / 100,
                    ),
                  )
                //: Container()
          ].toList(),
        ),
      ),
    );
  }

  Widget? _buildActionForTask(MyItem item) {
    if (item.status == DownloadTaskStatus.undefined) {
      return RawMaterialButton(
        onPressed: () {
          onActionClick(item);
        },
        child: Icon(Icons.file_download),
        shape: CircleBorder(),
        constraints: BoxConstraints(minHeight: 32.0, minWidth: 32.0),
      );
    }
    else if (item.status == DownloadTaskStatus.running) {
      return RawMaterialButton(
        onPressed: () {
          onActionClick(item);
        },
        child: Icon(
          Icons.pause,
          color: Colors.red,
        ),
        shape: CircleBorder(),
        constraints: BoxConstraints(minHeight: 32.0, minWidth: 32.0),
      );
    }
    else if (item.status == DownloadTaskStatus.paused) {
      return RawMaterialButton(
        onPressed: () {
          onActionClick(item);
        },
        child: Icon(
          Icons.play_arrow,
          color: Colors.green,
        ),
        shape: CircleBorder(),
        constraints: BoxConstraints(minHeight: 32.0, minWidth: 32.0),
      );
    }
    else if (item.status == DownloadTaskStatus.complete) {
      return Row(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Text(
            'Ready',
            style: TextStyle(color: Colors.green),
          ),
          RawMaterialButton(
            onPressed: () {
              onActionClick(item);
            },
            child: Icon(
              Icons.delete_forever,
              color: Colors.red,
            ),
            shape: CircleBorder(),
            constraints: BoxConstraints(minHeight: 32.0, minWidth: 32.0),
          )
        ],
      );
    }

    else if (item.status == DownloadTaskStatus.failed) {
      return Row(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Text('Failed', style: TextStyle(color: Colors.red)),
          RawMaterialButton(
            onPressed: () {
              onActionClick(item);
            },
            child: Icon(
              Icons.refresh,
              color: Colors.green,
            ),
            shape: CircleBorder(),
            constraints: BoxConstraints(minHeight: 32.0, minWidth: 32.0),
          )
        ],
      );
    }
    // else if (item.status == DownloadTaskStatus.canceled) {
    //   return Text('Canceled', style: TextStyle(color: Colors.red));
    // }

    // else if (item.status == DownloadTaskStatus.enqueued) {
    //   return Text('Pending', style: TextStyle(color: Colors.orange));
    // }
    else {
      return null;
    }
  }
}
</code>```

the source code is on GitHub

https://github.com/sunaarun/Download_files_Flutter

And these are the messages shown on the Console
it show that there is exception

```<code>Expecting binder but got null!
</code>```

Please Help

Body:
I am trying to develop an app that downloads files from URLs, such as images, pdf, videos and etc,
I am using Android 12 for Mobile device and  these Plugin :

  path_provider_android: ^2.0.12
  flutter_downloader: ^1.7.3
  permission_handler: ^9.2.0
  device_info_plus: ^3.2.3
  path_provider: ^2.0.9

This is the main.dart file

import 'package:download_file_app/my_download.dart';
import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';

const debug = true;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await FlutterDownloader.initialize(
      debug: debug // optional: set false to disable printing logs to console
       );
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final platform = Theme.of(context).platform;
    return  MaterialApp(
      title: 'Flutter Demo',
      theme:   ThemeData(
        primarySwatch: Colors.blue,
      ),
      home:  MyDownload(
        platform: platform,
      ),
    );
  }
}

And this is the MyDownload Class

class MyDownload extends StatefulWidget {
  final TargetPlatform? platform;

  MyDownload({this.platform});

  @override
  _MyDownloadState createState() => _MyDownloadState();
}

class _MyDownloadState extends State<MyDownload> {
  ReceivePort _port = ReceivePort();
  late bool _isLoading;
  late bool _permissionReady;
  late String _localPath;

  final _documents = [
    {
      'name': 'Learning Android Studio',
      'link': 'http://barbra-coco.dyndns.org/student/learning_android_studio.pdf'
    },
    {
      'name': 'Canyonlands National Park',
      'link': 'https://upload.wikimedia.org/wikipedia/commons/7/78/Canyonlands_National_Park%E2%80%A6Needles_area_%286294480744%29.jpg'
    },
    {
      'name': 'Big Buck Bunny',
      'link':
      'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4'
    },
  ];

  late List<MyItem> itemsList;

  @override
  void initState() {
    super.initState();
    _bindBackgroundIsolate();
    FlutterDownloader.registerCallback(downloadCallback);
    _isLoading = true;
    _permissionReady = false;
    _prepare();
  }

  void _bindBackgroundIsolate() {
    bool isSuccess = IsolateNameServer.registerPortWithName(
        _port.sendPort, 'downloader_send_port');
    if (!isSuccess) {
      _unbindBackgroundIsolate();
      _bindBackgroundIsolate();
      return;
    }
    _port.listen((dynamic data) {
      if (debug) {
        print('UI Isolate Callback: $data');
      }
      /*
       Update UI with the latest progress
       */
      String? id = data[0];
      DownloadTaskStatus? status = data[1];
      int progress = data[2];

      if (itemsList.isNotEmpty ) {
        final item = itemsList.firstWhere((it) => it.itemID == id);
        setState(() {
          item.status = status;
          item.progress = progress;
        });
      }
    });
  }

  void _unbindBackgroundIsolate() {
    IsolateNameServer.removePortNameMapping('downloader_send_port');
  }

  static void downloadCallback(String id, DownloadTaskStatus status,
      int progress) {
    if (debug) {
      print(
          'Background Isolate Callback: task ($id) is in status ($status) and process ($progress)');
    }
    final SendPort send =
    IsolateNameServer.lookupPortByName('downloader_send_port')!;
    send.send([id, status, progress]);
  }

  Future<Null> _prepare() async {

    itemsList = [];
    itemsList.addAll(
        _documents.map((doc) => MyItem(name: doc['name'].toString(),
            url: doc['link'].toString())
        )
    );
    _permissionReady = await _checkPermission();

    if (_permissionReady) {
      await _prepareSaveDir();
    }

    setState(() {
      _isLoading = false;
    });
  }

  Future<bool> _checkPermission() async {
    if (Platform.isIOS) return true;

    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
    if (widget.platform == TargetPlatform.android )
        // && androidInfo.version.sdkInt! <= 28)
    {
      final status = await Permission.storage.status;
      if (status != PermissionStatus.granted) {
        final result = await Permission.storage.request();
        if (result == PermissionStatus.granted) {
          return true;
        }
      } else {
        return true;
      }
    } else {
      return true;
    }
    return false;
  }

  Future<void> _prepareSaveDir() async {
    _localPath = (await _findLocalPath())!;
    final savedDir = Directory(_localPath);
    bool hasExisted = await savedDir.exists();
    if (!hasExisted) {
      savedDir.create();
    }
  }

  Future<String?> _findLocalPath() async {
    var externalStorageDirPath;
    if (Platform.isAndroid) {
      try {
        externalStorageDirPath = await PathProviderAndroid().getDownloadsPath(); //AndroidPathProvider.downloadsPath;
      } catch (e) {
        final directory = await getExternalStorageDirectory();
        externalStorageDirPath = directory?.path;
      }
    } else if (Platform.isIOS) {
      externalStorageDirPath =
          (await getApplicationDocumentsDirectory()).absolute.path;
    }
    return externalStorageDirPath;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Download File App'),
        ),
        body: Builder(
            builder: (context) =>
            _isLoading
                ?  Center(child: new CircularProgressIndicator(),)
                : _permissionReady ?
                Center(child:
                ListView(
                  children: itemsList.map((it) =>
                      DownloadITem(
                            myItem: it,
                            openItem: (myItem)
                            {
                              _openDownloadedFile(myItem).then((success) {
                                if (!success) {
                                  Scaffold.of(context).showSnackBar(SnackBar(
                                      content: Text('Cannot open this file')));
                                }
                              });
                            },
                            onActionClick: (myItem)async {
                              if (myItem.status == DownloadTaskStatus.undefined) {
                                myItem.itemID = await FlutterDownloader.enqueue(
                                  url: myItem.url,
                                  savedDir: _localPath,
                                  showNotification: true,
                                  openFileFromNotification: true,
                                  saveInPublicStorage: true,
                                );
                                //_requestDownload(myItem);
                              }
                              else if (myItem.status == DownloadTaskStatus.running) {
                                await FlutterDownloader.pause(taskId: myItem.itemID!);
                                //    _pauseDownload(myItem);
                              }
                              else if (myItem.status == DownloadTaskStatus.paused) {
                                String? newTaskId = await FlutterDownloader.resume(taskId: myItem.itemID!);
                                myItem.itemID = newTaskId;
                                //_resumeDownload(myItem);
                              }
                              else if (myItem.status == DownloadTaskStatus.complete) {
                                await FlutterDownloader.remove(
                                    taskId: myItem.itemID!, shouldDeleteContent: true);
                                await _prepare();
                                setState(() {});
                               // _delete(myItem);
                              }
                              else if (myItem.status == DownloadTaskStatus.failed) {
                                String? newTaskId = await FlutterDownloader.retry(taskId: myItem.itemID!);
                                myItem.itemID = newTaskId;

                                //_retryDownload(myItem);
                              }
                            }
                            ),).toList()),)
                :
            Container(),
        ));
  }

  Future<bool> _openDownloadedFile(MyItem item) {
    if (item != null) {
      return FlutterDownloader.open(taskId: item.itemID!);
    } else {
      return Future.value(false);
    }
  }

  void _requestDownload(MyItem item) async {
    item.itemID = await FlutterDownloader.enqueue(
      url: item.url,
      savedDir: _localPath,
      showNotification: true,
      openFileFromNotification: true,
      saveInPublicStorage: true,
    );
  }

  void _pauseDownload(MyItem item) async {
    await FlutterDownloader.pause(taskId: item.itemID!);
  }

  void _retryDownload(MyItem item) async {
    String? newTaskId = await FlutterDownloader.retry(taskId: item.itemID!);
    item.itemID = newTaskId;
  }

  void _resumeDownload(MyItem item) async {
    String? newTaskId = await FlutterDownloader.resume(taskId: item.itemID!);
    item.itemID = newTaskId;
  }
  void _delete(MyItem item) async {
    await FlutterDownloader.remove(
        taskId: item.itemID!, shouldDeleteContent: true);
    await _prepare();
    setState(() {});
  }

  @override
  void dispose() {
    _unbindBackgroundIsolate();
    super.dispose();
  }
}
class DownloadITem extends StatelessWidget {
  final MyItem myItem;
  final Function(MyItem) openItem;
  final Function(MyItem) onActionClick;
  DownloadITem(
      {required this.myItem,
      required this.openItem,
      required this.onActionClick});

  @override
  Widget build(BuildContext context) {
    return Container(
      //color: Colors.pink[50],
      padding: const EdgeInsets.only(left: 16.0, right: 8.0),
      child: InkWell(
        onTap: myItem.status == DownloadTaskStatus.complete
            ? () {
                openItem(myItem);
              }
            : null,
        child:
        Stack(
          children: <Widget>[
            Container(
              width: double.infinity,
              height: 64.0,
            //  color: Colors.amber,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Expanded(
                    child: Text(myItem.name,),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 8.0),
                    child: _buildActionForTask(myItem),
                  ),
                ],
              ),
            ),
        Positioned(
                    left: 0.0,
                    right: 0.0,
                    bottom: 0.0,
                    child: LinearProgressIndicator(
                      value: myItem.progress / 100,
                    ),
                  )
                //: Container()
          ].toList(),
        ),
      ),
    );
  }

  Widget? _buildActionForTask(MyItem item) {
    if (item.status == DownloadTaskStatus.undefined) {
      return RawMaterialButton(
        onPressed: () {
          onActionClick(item);
        },
        child: Icon(Icons.file_download),
        shape: CircleBorder(),
        constraints: BoxConstraints(minHeight: 32.0, minWidth: 32.0),
      );
    }
    else if (item.status == DownloadTaskStatus.running) {
      return RawMaterialButton(
        onPressed: () {
          onActionClick(item);
        },
        child: Icon(
          Icons.pause,
          color: Colors.red,
        ),
        shape: CircleBorder(),
        constraints: BoxConstraints(minHeight: 32.0, minWidth: 32.0),
      );
    }
    else if (item.status == DownloadTaskStatus.paused) {
      return RawMaterialButton(
        onPressed: () {
          onActionClick(item);
        },
        child: Icon(
          Icons.play_arrow,
          color: Colors.green,
        ),
        shape: CircleBorder(),
        constraints: BoxConstraints(minHeight: 32.0, minWidth: 32.0),
      );
    }
    else if (item.status == DownloadTaskStatus.complete) {
      return Row(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Text(
            'Ready',
            style: TextStyle(color: Colors.green),
          ),
          RawMaterialButton(
            onPressed: () {
              onActionClick(item);
            },
            child: Icon(
              Icons.delete_forever,
              color: Colors.red,
            ),
            shape: CircleBorder(),
            constraints: BoxConstraints(minHeight: 32.0, minWidth: 32.0),
          )
        ],
      );
    }

    else if (item.status == DownloadTaskStatus.failed) {
      return Row(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Text('Failed', style: TextStyle(color: Colors.red)),
          RawMaterialButton(
            onPressed: () {
              onActionClick(item);
            },
            child: Icon(
              Icons.refresh,
              color: Colors.green,
            ),
            shape: CircleBorder(),
            constraints: BoxConstraints(minHeight: 32.0, minWidth: 32.0),
          )
        ],
      );
    }
    // else if (item.status == DownloadTaskStatus.canceled) {
    //   return Text('Canceled', style: TextStyle(color: Colors.red));
    // }

    // else if (item.status == DownloadTaskStatus.enqueued) {
    //   return Text('Pending', style: TextStyle(color: Colors.orange));
    // }
    else {
      return null;
    }
  }
}

the source code is on GitHub

https://github.com/sunaarun/Download_files_Flutter

And these are the messages shown on the Console
it show that there is exception

Expecting binder but got null!

Please Help


问:
How to create a wordpress dropdown menu with multi-level sub-items programmatically?
I have a list of all categories (products) with the following structure:

[term_id] => 40
[name] => This category
[slug] => this-category
[term_group] => 0
[term_taxonomy_id] => 40
[taxonomy] => product_cat
[description] =>
[this_category_parent_id] => 56
[count] => 0
[filter] => raw
```
<p>Now I want to have the structure of the product categories in my menu:</p>
<p>example :</p>
```Category 1
    Category 1-1
    Category 1-2
        Category 1-2-1
            Category 1-2-1-1
        Category 1-2-2
    Category 1-3
Category 2
    Category 2-1
    Category 2-2
        Category 2-2-1
        Category 2-2-2
Category 3
...

```
<pre class="lang-php prettyprint-override"><code>
# Create menu and retrieve its id
$menu_id = wp_create_nav_menu( "My Menu Name" );

foreach ($all_products_categories as $category) {
    wp_update_nav_menu_item($menu_id, 0, array(
        'menu-item-object-id'       => $category->term_id,
        'menu-item-object'          => 'product_cat',

        'menu-item-title'           => $category->name,
        'menu-item-parent-id'       => $category->this_category_parent_id,
        'menu-item-classes'         => $category->slug,
        'menu-item-url'             => get_category_link($category->term_id),
        'menu-item-status'          => 'publish',
    ));

    if ( $category->parent <= 0 ) {
        wp_set_object_terms($category->term_id, $category->this_category_parent_id, 'nav_menu');
    }
}

</code>```

When I execute this code, the menu is created but I have no structure. There are no sub-items.

Body:
I have a list of all categories (products) with the following structure:

[term_id] => 40
[name] => This category
[slug] => this-category
[term_group] => 0
[term_taxonomy_id] => 40
[taxonomy] => product_cat
[description] =>
[this_category_parent_id] => 56
[count] => 0
[filter] => raw

Now I want to have the structure of the product categories in my menu:

example :

Category 1
    Category 1-1
    Category 1-2
        Category 1-2-1
            Category 1-2-1-1
        Category 1-2-2
    Category 1-3
Category 2
    Category 2-1
    Category 2-2
        Category 2-2-1
        Category 2-2-2
Category 3
...

# Create menu and retrieve its id
$menu_id = wp_create_nav_menu( "My Menu Name" );

foreach ($all_products_categories as $category) {
    wp_update_nav_menu_item($menu_id, 0, array(
        'menu-item-object-id'       => $category->term_id,
        'menu-item-object'          => 'product_cat',

        'menu-item-title'           => $category->name,
        'menu-item-parent-id'       => $category->this_category_parent_id,
        'menu-item-classes'         => $category->slug,
        'menu-item-url'             => get_category_link($category->term_id),
        'menu-item-status'          => 'publish',
    ));

    if ( $category->parent <= 0 ) {
        wp_set_object_terms($category->term_id, $category->this_category_parent_id, 'nav_menu');
    }
}

When I execute this code, the menu is created but I have no structure. There are no sub-items.