问:
404 error while implementing async function
detail.html

```<code>{% if request.user.is_authenticated %}
<form class="like-forms d-inline" data-book-id="{{ book.pk }}" data-review-id="{{ review.pk }}">
 {% csrf_token %}
  <h4>
 {% if request.user in review.like_users.all %}
 <button type="submit" id="btn-like-{{ review.pk }}" class="btn-none bi bi-emoji-heart-eyes"></button>
 {% else %}
 <button type="submit" id="btn-like-{{ review.pk }}" class="btn-none bi bi-emoji-angry"></button>
 {% endif %}
  </h4>
</form>
{% endif %}

<!-js-->
    <script>
      const likeForms = document.querySelectorAll('.like-forms')
      const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value
      likeForms.forEach((form) => {
        form.addEventListener('submit', function (event) {
          event.preventDefault()
          const reviewId = event.target.dataset.reviewId
          const bookId = event.target.dataset.bookId

          axios({

            method: 'post',
            url: `/detail/${bookId}/like/${reviewId}/`,
            headers: {'X-CSRFToken': csrfToken},

          })

          .then(response => {
            const isLiked = response.data.isLiked
            const likeBtn = document.querySelector(`#btn-like-${reviewId}`)
            console.log(isLiked)
            if (isLiked === true) {
              likeBtn.classList.add('bi-emoji-heart-eyes')
              likeBtn.classList.remove('bi-emoji-angry')

            } else {
              likeBtn.classList.add('bi-emoji-angry')
              likeBtn.classList.remove('bi-emoji-heart-eyes')

            }
          })
          .catch(error => {
            console.log(error)
          })
        })
      })
      </script>
</code>```

urls.py

```<code>path("detail/<int:book_pk>", views.detail, name="detail"),
path("detail/<int:book_pk>/like/<int:review_pk>", views.like, name="like"),
.....
</code>```

views.py

```<code>def detail(request, book_pk):
    reviews = Review.objects.order_by("-pk")
    book = Book.objects.get(pk=book_pk)

    context = {
        "reviews": reviews,
        "book": book,
    }
    return render(request, "review/detail.html", context)

def like(request, book_pk, review_pk):
    review = Review.objects.get(pk=review_pk)
    book = Book.objects.get(pk=book_pk)

    if review.like_users.filter(pk=request.user.pk).exists():
        review.like_users.remove(request.user)
        is_liked = False
    else:
        review.like_users.add(request.user)
        is_liked = True

    data = {
        "isLiked": is_liked,
    }

    return JsonResponse(data)
</code>```

I got a 404 not found error while writing code for a "like" async function.

data-book-id="{{ book.pk }}" data-review-id="{{ review.pk }} in the form

I seem to get pk values for books and book reviews, but I don't know what causes the 404 error.

Console error message : POST http://localhost:8000/detail/1/like/2/ 404 (Not Found)

I am running this on localhost (http://localhost:8000/)

Thanks for reading..!

Body:
detail.html

{% if request.user.is_authenticated %}
<form class="like-forms d-inline" data-book-id="{{ book.pk }}" data-review-id="{{ review.pk }}">
 {% csrf_token %}

 {% if request.user in review.like_users.all %}
 <button type="submit" id="btn-like-{{ review.pk }}" class="btn-none bi bi-emoji-heart-eyes"></button>
 {% else %}
 <button type="submit" id="btn-like-{{ review.pk }}" class="btn-none bi bi-emoji-angry"></button>
 {% endif %}

</form>
{% endif %}

<!-js-->

urls.py

path("detail/<int:book_pk>", views.detail, name="detail"),
path("detail/<int:book_pk>/like/<int:review_pk>", views.like, name="like"),
.....

views.py

def detail(request, book_pk):
    reviews = Review.objects.order_by("-pk")
    book = Book.objects.get(pk=book_pk)

    context = {
        "reviews": reviews,
        "book": book,
    }
    return render(request, "review/detail.html", context)

def like(request, book_pk, review_pk):
    review = Review.objects.get(pk=review_pk)
    book = Book.objects.get(pk=book_pk)

    if review.like_users.filter(pk=request.user.pk).exists():
        review.like_users.remove(request.user)
        is_liked = False
    else:
        review.like_users.add(request.user)
        is_liked = True

    data = {
        "isLiked": is_liked,
    }

    return JsonResponse(data)

I got a 404 not found error while writing code for a "like" async function.

data-book-id="{{ book.pk }}" data-review-id="{{ review.pk }} in the form

I seem to get pk values for books and book reviews, but I don't know what causes the 404 error.

Console error message : POST http://localhost:8000/detail/1/like/2/ 404 (Not Found)

I am running this on localhost (http://localhost:8000/)

Thanks for reading..!


来源: stackexchange

问:
React Components - How can I control which siblings re-render?
I have a main component which displays a list of wands through a wand component, and a sibling component which displays the the wands that have been checked.

The problem is when I set the state of wands checked in the Wand when a checkbox is checked, because it sets the state in the parent Wands component, it causes all of the components to re-render.

This is an issue because the checked wand is deselected, because all of the wands are re-rendered.

Ideally I would like to track and pass the list of checked wands when each is clicked from the Wand component, to display all those that have been checked in the WandsChecked component, without causing a mass re-render.

I've been working on this problem on my own for awhile while learning React, and could really use some advice from the community at this point.

Thanks for the advice!

Component Setup:

Wands

--Wand

--WandsChecked

```<code>
import { useState, useCallback } from 'react';
import WandsChecked from './WandsChecked';

function Wands ({wands}) {
  console.log('Wands re-rendering');
  const [wandsChecked, setWandsChecked]     = useState([]);

return (<>

    <main>
      <div className='grid gap-4 grid-cols-3 grid-rows-3'>
        {wands && wands.map((item => <Wand setWandsChecked={setWandsChecked} someprop={item} />))}
      </div>
      <div className='grid gap-4 grid-cols-3 grid-rows-3'>
          <WandsChecked WandsToCompare={wandsChecked}/>
      </div>
    </main>
</>)

function Wand({setWandsChecked, wand}) {
  console.log('Car re-rendering');

  //FIRED WHEN THE CHECKBOX IS CLICKED
  const asyncfunc = useCallback(async (veh, isChecked) => {
    //SET THE WANDS CHECKED
    //THIS CAUSES ALL THE COMPONENTS TO RERENDER
    setWandsChecked([...wandsChecked, veh]);
  }, []);

  return (<>
    <div className='wand-wrapper basis-1/4'>
      <div className='wand-banner'><input type="checkbox" id={wand.name} value={wand.isChecked} onClick={(e) => asyncfunc(wand, e.target.checked)}/>Check</div>
    </div>

  </>)
}

}

export default Wands;
</code>```

The way in which I have this setup it is currently causing all components to re-render when I set the state after the checkbox is checked.

ContentLicense: CC BY-SA 4.0

Body:
I have a main component which displays a list of wands through a wand component, and a sibling component which displays the the wands that have been checked.

The problem is when I set the state of wands checked in the Wand when a checkbox is checked, because it sets the state in the parent Wands component, it causes all of the components to re-render.

This is an issue because the checked wand is deselected, because all of the wands are re-rendered.

Ideally I would like to track and pass the list of checked wands when each is clicked from the Wand component, to display all those that have been checked in the WandsChecked component, without causing a mass re-render.

I've been working on this problem on my own for awhile while learning React, and could really use some advice from the community at this point.

Thanks for the advice!

Component Setup:

Wands

--Wand

--WandsChecked

import { useState, useCallback } from 'react';
import WandsChecked from './WandsChecked';

function Wands ({wands}) {
  console.log('Wands re-rendering');
  const [wandsChecked, setWandsChecked]     = useState([]);

return (<>

        {wands && wands.map((item => <Wand setWandsChecked={setWandsChecked} someprop={item} />))}

          <WandsChecked WandsToCompare={wandsChecked}/>

</>)

function Wand({setWandsChecked, wand}) {
  console.log('Car re-rendering');

  //FIRED WHEN THE CHECKBOX IS CLICKED
  const asyncfunc = useCallback(async (veh, isChecked) => {
    //SET THE WANDS CHECKED
    //THIS CAUSES ALL THE COMPONENTS TO RERENDER
    setWandsChecked([...wandsChecked, veh]);
  }, []);

  return (<>

<input type="checkbox" id={wand.name} value={wand.isChecked} onClick={(e) => asyncfunc(wand, e.target.checked)}/>Check

  </>)
}

}

export default Wands;

The way in which I have this setup it is currently causing all components to re-render when I set the state after the checkbox is checked.


问:
Changing the UI/UX of the Authentication package
I used the AWS Authentication package in Flutter, but I want to change the UI/UX. How do I alter the custom sign-in, sign-up, forgot password and sign-out forms in the package?</p>


问:
Blending the rendering of DataTableView and a standard view in Django
I'm pretty new to django and have been experimenting with some of the code

I want to build a form that starts with a parent record, lists the children of that record, and then when I click on a child (or a button in the row of that child) shows the children under that in a datatableview object.  phew  It should look a little like this:

So the dataset is the primary object into the view, and the tables are a datatables filtered by the dataset id, which all works fine... but how do I get the {{ datatable }} to render in context?

The current view code is pretty basic - this is initially all just for display.

```<code>def datasetview(request, datasetid):
    dataset = get_object_or_404(DataSet, pk=datasetid)

    context = {
        'dataset': dataset,
    }
    return render(request, 'data/dataset_view.html', context)
</code>```

within the html template, I render the table  list with:

```<code>                        {% for datatable in dataset.datatables.all %}
                            {% if not datatable.deleted %}
                                <tr>
                                    <td class="p-1 align-middle">{{ datatable.tablename }}</td>
                                    <td class="p-1 align-middle"><button type="button" class="btn btn-outline-primary" onclick="fill_attribute_table({{ datatable.datatableid }})">Edit</button></td>
                                </tr>
                            {% endif %}
                        {% endfor %}
</code>```

I've been able to render the dataviewtable as a generic page using the demo code provided at  pypi.org/project/django-datatable-view (that's how I produced the hacky screen image above) but have no idea how to blend the results here together or pass the datatableid that I can easily attach to the row of tables (the edit button currently throws up an alert with the relevant id...

Body:
I'm pretty new to django and have been experimenting with some of the code

I want to build a form that starts with a parent record, lists the children of that record, and then when I click on a child (or a button in the row of that child) shows the children under that in a datatableview object.  phew  It should look a little like this:

So the dataset is the primary object into the view, and the tables are a datatables filtered by the dataset id, which all works fine... but how do I get the {{ datatable }} to render in context?

The current view code is pretty basic - this is initially all just for display.

def datasetview(request, datasetid):
    dataset = get_object_or_404(DataSet, pk=datasetid)

    context = {
        'dataset': dataset,
    }
    return render(request, 'data/dataset_view.html', context)

within the html template, I render the table  list with:

                        {% for datatable in dataset.datatables.all %}
                            {% if not datatable.deleted %}

                                    {{ datatable.tablename }}
                                    <button type="button" class="btn btn-outline-primary" onclick="fill_attribute_table({{ datatable.datatableid }})">Edit</button>

                            {% endif %}
                        {% endfor %}

I've been able to render the dataviewtable as a generic page using the demo code provided at  pypi.org/project/django-datatable-view (that's how I produced the hacky screen image above) but have no idea how to blend the results here together or pass the datatableid that I can easily attach to the row of tables (the edit button currently throws up an alert with the relevant id...


问:
EOFException: null occurs when uploading a large file
An error occurred when uploading a file exceeding 2G using the Java interface,even after modifying many tomcat parameters

Below is the error log

```<code>ERROR 19593 --- [io-18073-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Failed to parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.impl.IOFileUploadException: Processing of multipart/form-data request failed. java.io.EOFException] with root cause

java.io.EOFException: null
    at org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper.fillReadBuffer(NioEndpoint.java:1294) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper.read(NioEndpoint.java:1206) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.coyote.http11.Http11InputBuffer.fill(Http11InputBuffer.java:805) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.coyote.http11.Http11InputBuffer.access$400(Http11InputBuffer.java:42) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.coyote.http11.Http11InputBuffer$SocketInputBuffer.doRead(Http11InputBuffer.java:1172) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.coyote.http11.filters.IdentityInputFilter.doRead(IdentityInputFilter.java:101) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.coyote.http11.Http11InputBuffer.doRead(Http11InputBuffer.java:249) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.coyote.Request.doRead(Request.java:640) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.connector.InputBuffer.realReadBytes(InputBuffer.java:317) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.connector.InputBuffer.checkByteBufferEof(InputBuffer.java:600) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.connector.InputBuffer.read(InputBuffer.java:340) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:132) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.tomcat.util.http.fileupload.MultipartStream$ItemInputStream.makeAvailable(MultipartStream.java:975) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.tomcat.util.http.fileupload.MultipartStream$ItemInputStream.read(MultipartStream.java:879) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at java.io.InputStream.read(InputStream.java:101) ~[na:1.8.0_181]
    at org.apache.tomcat.util.http.fileupload.util.Streams.copy(Streams.java:97) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.tomcat.util.http.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:288) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.connector.Request.parseParts(Request.java:2921) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.connector.Request.getParts(Request.java:2823) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.connector.RequestFacade.getParts(RequestFacade.java:1098) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.parseRequest(StandardMultipartHttpServletRequest.java:95) ~[spring-web-5.3.12.jar!/:5.3.12]
    at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.<init>(StandardMultipartHttpServletRequest.java:88) ~[spring-web-5.3.12.jar!/:5.3.12]
    at org.springframework.web.multipart.support.StandardServletMultipartResolver.resolveMultipart(StandardServletMultipartResolver.java:122) ~[spring-web-5.3.12.jar!/:5.3.12]
    at org.springframework.web.servlet.DispatcherServlet.checkMultipart(DispatcherServlet.java:1205) ~[spring-webmvc-5.3.12.jar!/:5.3.12]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039) ~[spring-webmvc-5.3.12.jar!/:5.3.12]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.12.jar!/:5.3.12]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.12.jar!/:5.3.12]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.3.12.jar!/:5.3.12]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:681) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.12.jar!/:5.3.12]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.54.jar!/:na]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at com.alibaba.druid.support.http.WebStatFilter.doFilter(WebStatFilter.java:124) ~[druid-1.2.3.jar!/:1.2.3]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.12.jar!/:5.3.12]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.12.jar!/:5.3.12]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.12.jar!/:5.3.12]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.12.jar!/:5.3.12]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.12.jar!/:5.3.12]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.12.jar!/:5.3.12]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.54.jar!/:na]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_181]
</code>```

The following is the parameter information

```<code>@Configuration
@Slf4j
public class EmbeddedTomcatConfig implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {

    @Override
    public void customize(ConfigurableServletWebServerFactory factory) {
        log.info("Init EmbeddedTomcatConfig...");
        ((TomcatServletWebServerFactory)factory).addConnectorCustomizers(new TomcatConnectorCustomizer() {
            @Override
            public void customize(Connector connector) {
                Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
                protocol.setMaxConnections(3000);
                protocol.setMaxThreads(800);
                protocol.setAcceptCount(200);
                protocol.setSelectorTimeout(30000);
                protocol.setSessionTimeout(60000 * 2);
                protocol.setConnectionTimeout(60000 * 5);
                protocol.setDisableUploadTimeout(false);
                protocol.setConnectionUploadTimeout(60000 * 10);
            }
        });
    }
}

</code>```
```<code>spring.servlet.multipart.max-request-size=-1
spring.servlet.multipart.max-file-size=-1
server.tomcat.max-swallow-size=-1
server.tomcat.max-http-form-post-size=-1

</code>```

control layer

```<code>    @ResponseBody
    @RequestMapping(value = "/FilesUpload",method = RequestMethod.POST)
    public BaseResponse uploadFiles(
            @RequestParam(required = true) MultipartFile files,
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        try {
            return BaseResponse.initSuccessBaseResponse(fileExecuteService.uploadFiles(files,request), "SUCCESS!");
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            return BaseResponse.initErrorBaseResponse(e.getMessage());
        }
    }

</code>```

I have adjusted almost all relevant parameters, but files over 2G still cannot be uploaded through the service interface

Body:
An error occurred when uploading a file exceeding 2G using the Java interface,even after modifying many tomcat parameters

Below is the error log

ERROR 19593 --- [io-18073-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Failed to parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.impl.IOFileUploadException: Processing of multipart/form-data request failed. java.io.EOFException] with root cause

java.io.EOFException: null
    at org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper.fillReadBuffer(NioEndpoint.java:1294) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper.read(NioEndpoint.java:1206) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.coyote.http11.Http11InputBuffer.fill(Http11InputBuffer.java:805) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.coyote.http11.Http11InputBuffer.access$400(Http11InputBuffer.java:42) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.coyote.http11.Http11InputBuffer$SocketInputBuffer.doRead(Http11InputBuffer.java:1172) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.coyote.http11.filters.IdentityInputFilter.doRead(IdentityInputFilter.java:101) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.coyote.http11.Http11InputBuffer.doRead(Http11InputBuffer.java:249) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.coyote.Request.doRead(Request.java:640) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.connector.InputBuffer.realReadBytes(InputBuffer.java:317) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.connector.InputBuffer.checkByteBufferEof(InputBuffer.java:600) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.connector.InputBuffer.read(InputBuffer.java:340) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:132) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.tomcat.util.http.fileupload.MultipartStream$ItemInputStream.makeAvailable(MultipartStream.java:975) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.tomcat.util.http.fileupload.MultipartStream$ItemInputStream.read(MultipartStream.java:879) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at java.io.InputStream.read(InputStream.java:101) ~[na:1.8.0_181]
    at org.apache.tomcat.util.http.fileupload.util.Streams.copy(Streams.java:97) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.tomcat.util.http.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:288) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.connector.Request.parseParts(Request.java:2921) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.connector.Request.getParts(Request.java:2823) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.connector.RequestFacade.getParts(RequestFacade.java:1098) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.parseRequest(StandardMultipartHttpServletRequest.java:95) ~[spring-web-5.3.12.jar!/:5.3.12]
    at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.<init>(StandardMultipartHttpServletRequest.java:88) ~[spring-web-5.3.12.jar!/:5.3.12]
    at org.springframework.web.multipart.support.StandardServletMultipartResolver.resolveMultipart(StandardServletMultipartResolver.java:122) ~[spring-web-5.3.12.jar!/:5.3.12]
    at org.springframework.web.servlet.DispatcherServlet.checkMultipart(DispatcherServlet.java:1205) ~[spring-webmvc-5.3.12.jar!/:5.3.12]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039) ~[spring-webmvc-5.3.12.jar!/:5.3.12]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.12.jar!/:5.3.12]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.12.jar!/:5.3.12]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.3.12.jar!/:5.3.12]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:681) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.12.jar!/:5.3.12]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.54.jar!/:na]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at com.alibaba.druid.support.http.WebStatFilter.doFilter(WebStatFilter.java:124) ~[druid-1.2.3.jar!/:1.2.3]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.12.jar!/:5.3.12]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.12.jar!/:5.3.12]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.12.jar!/:5.3.12]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.12.jar!/:5.3.12]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.12.jar!/:5.3.12]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.12.jar!/:5.3.12]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) [tomcat-embed-core-9.0.54.jar!/:na]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.54.jar!/:na]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_181]

The following is the parameter information

@Configuration
@Slf4j
public class EmbeddedTomcatConfig implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {

    @Override
    public void customize(ConfigurableServletWebServerFactory factory) {
        log.info("Init EmbeddedTomcatConfig...");
        ((TomcatServletWebServerFactory)factory).addConnectorCustomizers(new TomcatConnectorCustomizer() {
            @Override
            public void customize(Connector connector) {
                Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
                protocol.setMaxConnections(3000);
                protocol.setMaxThreads(800);
                protocol.setAcceptCount(200);
                protocol.setSelectorTimeout(30000);
                protocol.setSessionTimeout(60000 * 2);
                protocol.setConnectionTimeout(60000 * 5);
                protocol.setDisableUploadTimeout(false);
                protocol.setConnectionUploadTimeout(60000 * 10);
            }
        });
    }
}

spring.servlet.multipart.max-request-size=-1
spring.servlet.multipart.max-file-size=-1
server.tomcat.max-swallow-size=-1
server.tomcat.max-http-form-post-size=-1

control layer

    @ResponseBody
    @RequestMapping(value = "/FilesUpload",method = RequestMethod.POST)
    public BaseResponse uploadFiles(
            @RequestParam(required = true) MultipartFile files,
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        try {
            return BaseResponse.initSuccessBaseResponse(fileExecuteService.uploadFiles(files,request), "SUCCESS!");
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            return BaseResponse.initErrorBaseResponse(e.getMessage());
        }
    }

I have adjusted almost all relevant parameters, but files over 2G still cannot be uploaded through the service interface


问:
How to correctly implement busboy
My goal is to try and upload files to a google cloud bucket. However, I am trying to just take it step by step because I struggle with handling files. Right now I'm just trying to send files through formdata and then parse that formdata with busboy.

I know how to send the file once I have it I'm just not sure how to do it with busboy so any help would be great. I'm currently getting the error node:events:498 throw er and Unexpected end of form at Multipart._final. Below is my code and just a side note I am getting my acceptedFiles array from just a react-dropzone component.

I'm more than happy to provide any clarification.

Client-side

```<code>const sendFile = async() =>{
  if(acceptedFiles.length > 0){
    for(let filePos = 0;filePos < acceptedFiles.length;filePos++){
      await sendToFireBase(acceptedFiles[filePos])
    }
  }else{
    window.alert("No files have been selected to be uploaded")
  }
}
</code>```

Endpoint

```<code>export default async function UploadToFireStorage(file){

    try{

        const formData = new FormData();
        formData.append(file.name,file);

        const response = await fetch(`http://localhost:5000/uploadNewFiles`,{
            method:"POST",
            body: formData
        })

        const jsonData = await response.json()

        console.log(jsonData)

    }catch(error){

        console.log(error)

    }

  }
</code>```

Server-Side

```<code>app.post('/uploadNewFiles',async(req,res)=>{

    console.log('made it to upload')

    try{

        if (req.method === 'POST') {
            const busboy = Busboy({ headers: req.headers });

            // This callback will be invoked for each file uploaded.
            busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
                try{
                    console.log('got the file');
                    res.json('File made it');
                }catch(error){
                    res.json('F')
                }
            });

            busboy.end(req.rawBody);
        } else {
            res.json('Not Post');
        }

    }catch(error){
        res.json("error: " + error)
        console.log(error)
    }

})
</code>```

Title: How to correctly implement busboy

Body:
My goal is to try and upload files to a google cloud bucket. However, I am trying to just take it step by step because I struggle with handling files. Right now I'm just trying to send files through formdata and then parse that formdata with busboy.

I know how to send the file once I have it I'm just not sure how to do it with busboy so any help would be great. I'm currently getting the error node:events:498 throw er and Unexpected end of form at Multipart._final. Below is my code and just a side note I am getting my acceptedFiles array from just a react-dropzone component.

I'm more than happy to provide any clarification.

Client-side

const sendFile = async() =>{
  if(acceptedFiles.length > 0){
    for(let filePos = 0;filePos < acceptedFiles.length;filePos++){
      await sendToFireBase(acceptedFiles[filePos])
    }
  }else{
    window.alert("No files have been selected to be uploaded")
  }
}

Endpoint

export default async function UploadToFireStorage(file){

    try{

        const formData = new FormData();
        formData.append(file.name,file);

        const response = await fetch(`http://localhost:5000/uploadNewFiles`,{
            method:"POST",
            body: formData
        })

        const jsonData = await response.json()

        console.log(jsonData)

    }catch(error){

        console.log(error)

    }

  }

Server-Side

app.post('/uploadNewFiles',async(req,res)=>{

    console.log('made it to upload')

    try{

        if (req.method === 'POST') {
            const busboy = Busboy({ headers: req.headers });

            // This callback will be invoked for each file uploaded.
            busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
                try{
                    console.log('got the file');
                    res.json('File made it');
                }catch(error){
                    res.json('F')
                }
            });

            busboy.end(req.rawBody);
        } else {
            res.json('Not Post');
        }

    }catch(error){
        res.json("error: " + error)
        console.log(error)
    }

})


问:
Create image in azure with packer
I have already created the resource with the azure cli, and I have verified that the resource is in the azure portal.
I have this error:

```<code>Build 'azure-arm' errored after 1 second 668 milliseconds: Cannot locate the managed image resource group packerResourceGroup.
</code>```

I'm using an institutional account, will it have something to do with it?

Title: Create image in azure with packer

Body:
I have already created the resource with the azure cli, and I have verified that the resource is in the azure portal.
I have this error:

Build 'azure-arm' errored after 1 second 668 milliseconds: Cannot locate the managed image resource group packerResourceGroup.

I'm using an institutional account, will it have something to do with it?


问:
TLS communication between ingress and auth microservice fails in k8s
Currently if i try to hit a microservice which has https rest endpoint in my local(mac) with a created ssl certifacte i get proper output. During creation of local machine ssl certificate i have used CN(common name) as localhost. I used openssl.

For k8s case, we have ingress which will communicate to that microservice using forwardauth through https, there i have used different ssl certificate where tried to use DNS name (sample-domain1-lb.sample-domain1-ns.svc.cluster.local) as using CN name gives error in traefik ingress.

Now i am getting 500 response from traefik ingress .
But if I use tls.insecureSkipVerify: true in middleware forwardauth config then it will work, where microservice url is https://sample-domain1-lb.sample-domain1-ns.svc.cluster.local:8080/auth

Any help is highly appreciated

traefike ingress Debug log:

```<code>"time="2022-12-08T13:08:09Z" level=debug msg="Error calling https://sample-domain1-lb.sample-domain1-ns.svc.cluster.local:8080/auth. Cause: Get \"https://sample-domain1-lb.sample-domain1-ns.svc.cluster.local:8080/auth\": x509: certificate is not valid for any names, but wanted to match sample-domain1-lb.sample-domain1-ns.svc.cluster.local" middlewareName=sample-domain1-ns-test-auth@kubernetescrd middlewareType=ForwardedAuthType"
</code>```

Openssl cmds used:

```<code>openssl genrsa -out key.pem 2048 -config openssl.cnf
#Generate a Certificate Signing Request:
openssl req -new -sha256 -key key.pem -out csr.csrz -config openssl.cnf
#Generate a self-signed x509 certificate suitable for use on web servers.
openssl req -x509 -sha256 -days 365 -key key.pem -in csr.csrz -out certificate.pem
#Create SSL identity file in PKCS12 as mentioned here
openssl pkcs12 -export -out client-identity.p12 -inkey key.pem -in certificate.pem
</code>```

Openssl config file:

```<code>
[ req ]
default_bits       = 2048
distinguished_name = req_distinguished_name
req_extensions     = req_ext
[ req_distinguished_name ]
countryName                 = Country Name (2 letter code)
stateOrProvinceName         = State or Province Name (full name)
localityName               = Locality Name (eg, city)
organizationName           = Organization Name (eg, company)
[ req_ext ]
keyUsage = keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1   = sample-domain1-lb.sample-domain1-ns.svc.cluster.local
DNS.2   = sample-domain1-lb.sample-domain1-ns.svc.cluster.local.com

</code>```

openssl data output:

```<code>Country Name (2 letter code) []:US
State or Province Name (full name) []:VA
Locality Name (eg, city) []:SomeCity
Organization Name (eg, company) []:MyCompany
</code>```

Body:
Currently if i try to hit a microservice which has https rest endpoint in my local(mac) with a created ssl certifacte i get proper output. During creation of local machine ssl certificate i have used CN(common name) as localhost. I used openssl.

For k8s case, we have ingress which will communicate to that microservice using forwardauth through https, there i have used different ssl certificate where tried to use DNS name (sample-domain1-lb.sample-domain1-ns.svc.cluster.local) as using CN name gives error in traefik ingress.

Now i am getting 500 response from traefik ingress .
But if I use tls.insecureSkipVerify: true in middleware forwardauth config then it will work, where microservice url is https://sample-domain1-lb.sample-domain1-ns.svc.cluster.local:8080/auth

Any help is highly appreciated

traefike ingress Debug log:

"time="2022-12-08T13:08:09Z" level=debug msg="Error calling https://sample-domain1-lb.sample-domain1-ns.svc.cluster.local:8080/auth. Cause: Get \"https://sample-domain1-lb.sample-domain1-ns.svc.cluster.local:8080/auth\": x509: certificate is not valid for any names, but wanted to match sample-domain1-lb.sample-domain1-ns.svc.cluster.local" middlewareName=sample-domain1-ns-test-auth@kubernetescrd middlewareType=ForwardedAuthType"

Openssl cmds used:

openssl genrsa -out key.pem 2048 -config openssl.cnf
#Generate a Certificate Signing Request:
openssl req -new -sha256 -key key.pem -out csr.csrz -config openssl.cnf
#Generate a self-signed x509 certificate suitable for use on web servers.
openssl req -x509 -sha256 -days 365 -key key.pem -in csr.csrz -out certificate.pem
#Create SSL identity file in PKCS12 as mentioned here
openssl pkcs12 -export -out client-identity.p12 -inkey key.pem -in certificate.pem

Openssl config file:

[ req ]
default_bits       = 2048
distinguished_name = req_distinguished_name
req_extensions     = req_ext
[ req_distinguished_name ]
countryName                 = Country Name (2 letter code)
stateOrProvinceName         = State or Province Name (full name)
localityName               = Locality Name (eg, city)
organizationName           = Organization Name (eg, company)
[ req_ext ]
keyUsage = keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1   = sample-domain1-lb.sample-domain1-ns.svc.cluster.local
DNS.2   = sample-domain1-lb.sample-domain1-ns.svc.cluster.local.com

openssl data output:

Country Name (2 letter code) []:US
State or Province Name (full name) []:VA
Locality Name (eg, city) []:SomeCity
Organization Name (eg, company) []:MyCompany


问:
Better understanding of the vmcore collection process
I need to modify the kernel vmcore collection process, but I can not seem to understant few things:

What is that "core_collector" thing referenced to here? is it a script or a binary or what?

Where are the sources for the crash-dump-capture kernel?

Much like /sbin/makedumpfile is added into crash-dump-capture kernel environment, how can I add another script and make sure it is ran before makedumpfile.

I use Rocky Linux.


问:
The same file's coverage of entire project not equal to run itself only
I've publish a tool which based on jest to test my code and collect coverage.

I found the same file's coverage in entire coverage report can't match single one file coverage report since I use v8 coverage provider.

This is my coverage of entire project.

It can't match the result that I run jest in single one file.

I think it maybe v8 coverage problem and also try out babel coverage, It seems OK.

So, the problems is that I can't remember why I use v8 instead of babel becuase leave on a warnning in my tool.

Is there any problems if I switch v8 to babel?


问:
React Native and Typescript - Need an approach to create a flexible table component
I'm trying to create a table component that can display its cells flexibly. Every cells on a column displays the same cell component. The table component take an array of object as initial data and an array of column properties. Table should looks like this:

```<code>interface MyTableProps {
    columns: ColumnProps[];
    initialData: Array<any>; // Should array of object
    callbackTableDataChanged: (newData) => void; // being used to send modified table data back to MyTable's father components.
}

interface ColumnProps {
    label: string;
    objectPropertyName: string; // (*)
    renderCell: "cell-type-1" | "cell-type-2" | "cell-type-3" | ... // (**)
}

const MyTable: React.FC<MyTableProps> = tableProps => {
    // The table should have its own a copy of initial data, because of many reasons
    const [tableData, setTableData] = useState(tableProps.initialData);

    const handleDataChange = (thePropertyName: string, rowIndex: number, newValue: any) => {
        // This function changes the table data array,
        // whenever the cell component (MyCellComp1, MyCellComp2, ...) on a column make a change of value.
        // For example: MyCellComp1 is a time picker, whenever a new timestamp selected,
        // it will send new time value through a callback, to its father component (aka MyTable).
        // Then, this func will do the changes to the corresponding "place" in the data array object of this MyTable.
    }

    const renderRows = (column: ColumnProps, rowIndex: number) => {
        switch (column.renderCell) {
            case cell-type-1: return <CellComp1 ... onDataChanged={cellData => handleDataChange(column.objectPropertyName, rowIndex, cellData)}/>
            case cell-type-2: return <CellComp2 ... onDataChanged={cellData => handleDataChange(column.objectPropertyName, rowIndex, cellData)}/>
            ...
        }
    }

    return (
        {renderColumnLabels}
        <Flatlist data={tableData} renderItem={({col, index}) => renderRows(col, index)}/>
    )
}
</code>```

(*): "objectPropertyName" is a string that has value which is a name of one of the properties of initial object data. Forgive my awkward grammar!

(**): I use "renderCell" to tell the table what it should render at specific column. All cells on a column have the same component type.

The table should be used like this:

```<code>    const initialData = [
        {id: "123", name: "Tom"}, {id: "456", name: "Jerry"}, ...
    ]
    const columns: ColumnProps[] = [
        {label: "The ID", objectPropertyName: "id", renderCell: "cell-type-1"},
        {label: "The name", objectPropertyName: "name", renderCell: "cell-type-2"},
        ...
    ];

    <MyTable columns={columns} initialData={initialData} ... />

// This is how table looks like:
//                 column 1              column 2
// labels row:     The ID                The name
// row 1     :     <CellComp1 />         <CellComp2 />
// row 2     :     <CellComp1 />         <CellComp2 />
// ...
</code>```

The problem is that with above approach, with the way I declared how cells on a column should be rendered, it limits the variety of cell component that MyTable could display. I declare 3 values for ColumnProps.rendercell, columns can display only 3 kinds of cell components.

My solution is that ColumnProps will have a new props which is a function that return a component:

```<code>    interface ColumnProps {
    label: string;
    objectPropertyName: string; // (*)
    renderCell: "cell-type-1" | "cell-type-2" | "cell-type-3" | ... // (**)
    renderCellComponent?: () => JSX.Element
}
</code>```

The new "renderCellComponent" prop will replace default cell components with whatever it returns.

However, with is method, I cant change the data array of MyTable with its function "handleDataChange".

For example:

```<code>    const initialData = [
        {id: "123", name: "Tom"}, {id: "456", name: "Jerry"}, ...
    ]
    const columns: ColumnProps[] = [
        {label: "The ID", objectPropertyName: "id", renderCell: "cell-type-1", renderCellComponent: () => <NewCellComp1 ... />},
        {label: "The name", objectPropertyName: "name", renderCell: "cell-type-2", renderCellComponent: () => <NewCellComp2 ... />},
        ...
    ];

    <MyTable columns={columns} initialData={initialData} ... />
</code>```

As you can see, NewCellComp1 and NewCellComp2 need to access the function "handleDataChange" of MyTable just like the way CellComp1 and CellComp2 did. In order to do that, I tried to use React.forwardRef and useImperativeHandle to MyTable:

```<code>const MyTable: React.FC<MyTableProps> = React.forwardRef((tableProps, ref) => {
    ...
    useImperativeHandle(ref, () => {
        refFuncHandleDataChange(objectPropertyName: string, rowIndex, newValue) {
            handleDataChange(objectPropertyName, rowIndex, newValue);
        }
    })

    return ...
})
</code>```

Now, MyTable should be used like this:

```<code>    const initialData = [
        {id: "123", name: "Tom"}, {id: "456", name: "Jerry"}, ...
    ]
    const columns: ColumnProps[] = [
        {...other props, objectPropertyName: "id", renderCellComponent: () => <NewCellComp1 onDataChanged={data => refTable.current?.refFuncHandleDataChange("id", ..., data)} />},
        {...other props, objectPropertyName: "name", renderCellComponent: () => <NewCellComp2 onDataChanged={data => refTable.current?.refFuncHandleDataChange("name", ..., data)} />},
        ...
    ];

    const refTable = useRef();

    <MyTable ref={refTable} columns={columns} initialData={initialData} ... />
</code>```

As you can see, with this approach, I still lack the row index of the cell component that make a change of data. When cell rendering is declared inside MyTable, I can access to row index easily thanks to Flatlist, but outside MyTable does not offer that luxury, because "renderCellComponent" function of ColumnProps is a declaration for all cells on a column. This is where I'm stuck.

In conclusion, I want to create a table component that be able to display every kind of components on its cells. Also, keep its properties as "simple" as possible. You can see that I'm currently must declare only data and columns props. But my approach seems to be impossible to do that.

Can you share me an improvement for what I did or an entirely new approach for this problem. Thank you!

Body:
I'm trying to create a table component that can display its cells flexibly. Every cells on a column displays the same cell component. The table component take an array of object as initial data and an array of column properties. Table should looks like this:

interface MyTableProps {
    columns: ColumnProps[];
    initialData: Array<any>; // Should array of object
    callbackTableDataChanged: (newData) => void; // being used to send modified table data back to MyTable's father components.
}

interface ColumnProps {
    label: string;
    objectPropertyName: string; // (*)
    renderCell: "cell-type-1" | "cell-type-2" | "cell-type-3" | ... // (**)
}

const MyTable: React.FC<MyTableProps> = tableProps => {
    // The table should have its own a copy of initial data, because of many reasons
    const [tableData, setTableData] = useState(tableProps.initialData);

    const handleDataChange = (thePropertyName: string, rowIndex: number, newValue: any) => {
        // This function changes the table data array,
        // whenever the cell component (MyCellComp1, MyCellComp2, ...) on a column make a change of value.
        // For example: MyCellComp1 is a time picker, whenever a new timestamp selected,
        // it will send new time value through a callback, to its father component (aka MyTable).
        // Then, this func will do the changes to the corresponding "place" in the data array object of this MyTable.
    }

    const renderRows = (column: ColumnProps, rowIndex: number) => {
        switch (column.renderCell) {
            case cell-type-1: return <CellComp1 ... onDataChanged={cellData => handleDataChange(column.objectPropertyName, rowIndex, cellData)}/>
            case cell-type-2: return <CellComp2 ... onDataChanged={cellData => handleDataChange(column.objectPropertyName, rowIndex, cellData)}/>
            ...
        }
    }

    return (
        {renderColumnLabels}
        <Flatlist data={tableData} renderItem={({col, index}) => renderRows(col, index)}/>
    )
}

(*): "objectPropertyName" is a string that has value which is a name of one of the properties of initial object data. Forgive my awkward grammar!

(**): I use "renderCell" to tell the table what it should render at specific column. All cells on a column have the same component type.

The table should be used like this:

    const initialData = [
        {id: "123", name: "Tom"}, {id: "456", name: "Jerry"}, ...
    ]
    const columns: ColumnProps[] = [
        {label: "The ID", objectPropertyName: "id", renderCell: "cell-type-1"},
        {label: "The name", objectPropertyName: "name", renderCell: "cell-type-2"},
        ...
    ];

    <MyTable columns={columns} initialData={initialData} ... />

// This is how table looks like:
//                 column 1              column 2
// labels row:     The ID                The name
// row 1     :     <CellComp1 />         <CellComp2 />
// row 2     :     <CellComp1 />         <CellComp2 />
// ...

The problem is that with above approach, with the way I declared how cells on a column should be rendered, it limits the variety of cell component that MyTable could display. I declare 3 values for ColumnProps.rendercell, columns can display only 3 kinds of cell components.

My solution is that ColumnProps will have a new props which is a function that return a component:

    interface ColumnProps {
    label: string;
    objectPropertyName: string; // (*)
    renderCell: "cell-type-1" | "cell-type-2" | "cell-type-3" | ... // (**)
    renderCellComponent?: () => JSX.Element
}

The new "renderCellComponent" prop will replace default cell components with whatever it returns.

However, with is method, I cant change the data array of MyTable with its function "handleDataChange".

For example:

    const initialData = [
        {id: "123", name: "Tom"}, {id: "456", name: "Jerry"}, ...
    ]
    const columns: ColumnProps[] = [
        {label: "The ID", objectPropertyName: "id", renderCell: "cell-type-1", renderCellComponent: () => <NewCellComp1 ... />},
        {label: "The name", objectPropertyName: "name", renderCell: "cell-type-2", renderCellComponent: () => <NewCellComp2 ... />},
        ...
    ];

    <MyTable columns={columns} initialData={initialData} ... />

As you can see, NewCellComp1 and NewCellComp2 need to access the function "handleDataChange" of MyTable just like the way CellComp1 and CellComp2 did. In order to do that, I tried to use React.forwardRef and useImperativeHandle to MyTable:

const MyTable: React.FC<MyTableProps> = React.forwardRef((tableProps, ref) => {
    ...
    useImperativeHandle(ref, () => {
        refFuncHandleDataChange(objectPropertyName: string, rowIndex, newValue) {
            handleDataChange(objectPropertyName, rowIndex, newValue);
        }
    })

    return ...
})

Now, MyTable should be used like this:

    const initialData = [
        {id: "123", name: "Tom"}, {id: "456", name: "Jerry"}, ...
    ]
    const columns: ColumnProps[] = [
        {...other props, objectPropertyName: "id", renderCellComponent: () => <NewCellComp1 onDataChanged={data => refTable.current?.refFuncHandleDataChange("id", ..., data)} />},
        {...other props, objectPropertyName: "name", renderCellComponent: () => <NewCellComp2 onDataChanged={data => refTable.current?.refFuncHandleDataChange("name", ..., data)} />},
        ...
    ];

    const refTable = useRef();

    <MyTable ref={refTable} columns={columns} initialData={initialData} ... />

As you can see, with this approach, I still lack the row index of the cell component that make a change of data. When cell rendering is declared inside MyTable, I can access to row index easily thanks to Flatlist, but outside MyTable does not offer that luxury, because "renderCellComponent" function of ColumnProps is a declaration for all cells on a column. This is where I'm stuck.

In conclusion, I want to create a table component that be able to display every kind of components on its cells. Also, keep its properties as "simple" as possible. You can see that I'm currently must declare only data and columns props. But my approach seems to be impossible to do that.

Can you share me an improvement for what I did or an entirely new approach for this problem. Thank you!


问:
Trying to Update Calendar, Getting Various Errors
I can add a new calendar to the user's calendars like this, using the saveCalendar(_:commit:) method:

```<code>let ekStore = EKEventStore()

func saveCalendar(calendar: EKCalendar) throws {
    try ekStore.saveCalendar(calendar, commit: true)
}
</code>```

and

```<code>let newList = EKCalendar(for: .reminder, eventStore: ekStore)

newList.source = ekStore.defaultCalendarForNewReminders()?.source
newList.title = newListName
newList.cgColor = listColor

do {

    try saveCalendar(calendar: newList)

} catch {

    print("Error adding list: \(error.localizedDescription)")

}
</code>```

I then store the calendar object.

When the user finishes editing a calendar (reminders list) in my app, I try to save it like this, using the stored calendar as a starting point:

```<code>let updatedList = existingCalendar

updatedList.title = newListName
updatedList.cgColor = listColor

do {

    try saveCalendar(calendar: updatedList)

} catch {

    print("Error saving list: \(error.localizedDescription)")

}
</code>```

But the calendar doesn't save and I get this error: That account does not support reminders..
I have also tried explicitly setting the calendar's source:

```<code>updatedList.source = ekStore.defaultCalendarForNewReminders()?.source
</code>```

but then I get this error: That calendar may not be moved to another account..

My Question: How do I update calendars (reminder lists) from my app?

Body:
I can add a new calendar to the user's calendars like this, using the saveCalendar(_:commit:) method:

let ekStore = EKEventStore()

func saveCalendar(calendar: EKCalendar) throws {
    try ekStore.saveCalendar(calendar, commit: true)
}

and

let newList = EKCalendar(for: .reminder, eventStore: ekStore)

newList.source = ekStore.defaultCalendarForNewReminders()?.source
newList.title = newListName
newList.cgColor = listColor

do {

    try saveCalendar(calendar: newList)

} catch {

    print("Error adding list: \(error.localizedDescription)")

}

I then store the calendar object.

When the user finishes editing a calendar (reminders list) in my app, I try to save it like this, using the stored calendar as a starting point:

let updatedList = existingCalendar

updatedList.title = newListName
updatedList.cgColor = listColor

do {

    try saveCalendar(calendar: updatedList)

} catch {

    print("Error saving list: \(error.localizedDescription)")

}

But the calendar doesn't save and I get this error: That account does not support reminders..
I have also tried explicitly setting the calendar's source:

updatedList.source = ekStore.defaultCalendarForNewReminders()?.source

but then I get this error: That calendar may not be moved to another account..

My Question: How do I update calendars (reminder lists) from my app?


问:
How to pass Network in OkhttpClient in socketFactory for network request in retorfit
```<code>@Provides
    @PerApplication
    @Named("SocketNetwork")
    fun providesSocketNetwork(context: Context): Network {
        var socketNetwork: Network? = null
        val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val request = NetworkRequest.Builder()
            .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
            .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
            .build()
            if (cm != null) {
                cm.requestNetwork(
                    request,
                    object : ConnectivityManager.NetworkCallback() {
                        @RequiresApi(Build.VERSION_CODES.M)
                        override fun onAvailable(network: Network) {
                            socketNetwork = network
                            cm.bindProcessToNetwork(network)
                        }
                    })
            }
        return socketNetwork!!
    }

    @Provides
@PerApplication
@Named("RoveR3OkHttpClient")
fun providesOkHttpClient(context: Context,@Named("SocketNetwork")socketNetwork: Network): OkHttpClient {
    val cacheSize = (5 * 1024 * 1024).toLong()
    val mCache = Cache(context.cacheDir, cacheSize)
    val interceptor = HttpLoggingInterceptor()
    interceptor.level = HttpLoggingInterceptor.Level.BODY
    val client = OkHttpClient.Builder()
        .cache(mCache)
        .socketFactory(socketNetwork.socketFactory)
        .addNetworkInterceptor(interceptor).addInterceptor(TimeHeaderInterceptor())
    return client.build()
}
</code>```

This my code i want to provide @Named("SocketNetwork")socketNetwork: Network) in this way so that it should return Network and that network i could pass in OkHttpClient so that i can do network request using that socket, but i am unable to synchronized onAvailable method in providesSocketNetwork method so its returning null can any one please help me or suggest me some other way  how to do this i am stuck in this issue for long time .

Thanks

Body:
@Provides
    @PerApplication
    @Named("SocketNetwork")
    fun providesSocketNetwork(context: Context): Network {
        var socketNetwork: Network? = null
        val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val request = NetworkRequest.Builder()
            .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
            .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
            .build()
            if (cm != null) {
                cm.requestNetwork(
                    request,
                    object : ConnectivityManager.NetworkCallback() {
                        @RequiresApi(Build.VERSION_CODES.M)
                        override fun onAvailable(network: Network) {
                            socketNetwork = network
                            cm.bindProcessToNetwork(network)
                        }
                    })
            }
        return socketNetwork!!
    }

    @Provides
@PerApplication
@Named("RoveR3OkHttpClient")
fun providesOkHttpClient(context: Context,@Named("SocketNetwork")socketNetwork: Network): OkHttpClient {
    val cacheSize = (5 * 1024 * 1024).toLong()
    val mCache = Cache(context.cacheDir, cacheSize)
    val interceptor = HttpLoggingInterceptor()
    interceptor.level = HttpLoggingInterceptor.Level.BODY
    val client = OkHttpClient.Builder()
        .cache(mCache)
        .socketFactory(socketNetwork.socketFactory)
        .addNetworkInterceptor(interceptor).addInterceptor(TimeHeaderInterceptor())
    return client.build()
}

This my code i want to provide @Named("SocketNetwork")socketNetwork: Network) in this way so that it should return Network and that network i could pass in OkHttpClient so that i can do network request using that socket, but i am unable to synchronized onAvailable method in providesSocketNetwork method so its returning null can any one please help me or suggest me some other way  how to do this i am stuck in this issue for long time .

Thanks


问:
Java Playwright with MutationObserver for HTML DOM manipulation
I have a requirement in QA automation using Microsoft playwright that needs to listen to the HTML DOM manipulation in the java playwright. I have seen different examples in node playwright but none in java playwright.

I tried using BrowserContext.exposeFunction callback but it doesn't call the exposed java method mutationRecord. and does not throw any error or exception.

The below code dumps the MutationRecord object in browser console, but the java method doesn't get called when there is a change in the HTML DOM. The expectation is when there a change in the HTML DOM the java method would be called to print some string on java console or to get an error/exception.

BrowserContext defaultContext = browserServer.contexts().get(0);

defaultContext.exposeFunction("mutationRecord", params ->{
    Object text = (Object) params[0];
    System.out.println(text.toString());
    return "";
});

String mutation = "var mutationObserver = new MutationObserver(function(mutations) {\n" +
" mutations.forEach(function(mutation) {\n" +
" console.log(mutation);\n" +
" window.mutationRecord(mutation);\n" +
" });\n" +
"});\n\n" +
"mutationObserver.observe(document.documentElement, {\n" +
" attributes: true,\n" +
" characterData: true,\n" +
" childList: true,\n" +
" subtree: true,\n" +
" attributeOldValue: true,\n" +
" characterDataOldValue: true\n" +
"});";

page.evaluate(mutation);
```
<p>I tried calling Java function from JavaScript using <code>context.exposeFunction</code>. The java method doesn't get called even if there is a html DOM manipulation. How can it be fixed?</p>
<hr />
<p>I have tried exposing and calling a different, simpler java method, which works perfectly fine. Here it is:</p>
<pre class="lang-java prettyprint-override"><code>import com.microsoft.playwright.*;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class Example {
  public static void main(String[] args) {
    try (Playwright playwright = Playwright.create()) {
      BrowserType webkit = playwright.webkit()
      Browser browser = webkit.launch(new BrowserType.LaunchOptions().setHeadless(false));
      context.exposeFunction("sha256", args -> {
        String text = (String) args[0];
        MessageDigest crypto;
        try {
          crypto = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
          return null;
        }
        byte[] token = crypto.digest(text.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(token);
      });
      Page page = context.newPage();
      page.setContent("<script>\n" +
        "  async function onClick() {\n" +
        "    document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');\n" +
        "  }\n" +
        "</script>\n" +
        "<button onclick=\"onClick()\">Click me</button>\n" +
        "<div></div>\n");
      page.getByRole("button").click();
    }
  }
}
</code>```

Body:
I have a requirement in QA automation using Microsoft playwright that needs to listen to the HTML DOM manipulation in the java playwright. I have seen different examples in node playwright but none in java playwright.

I tried using BrowserContext.exposeFunction callback but it doesn't call the exposed java method mutationRecord. and does not throw any error or exception.

The below code dumps the MutationRecord object in browser console, but the java method doesn't get called when there is a change in the HTML DOM. The expectation is when there a change in the HTML DOM the java method would be called to print some string on java console or to get an error/exception.

BrowserContext defaultContext = browserServer.contexts().get(0);

defaultContext.exposeFunction("mutationRecord", params ->{
    Object text = (Object) params[0];
    System.out.println(text.toString());
    return "";
});

String mutation = "var mutationObserver = new MutationObserver(function(mutations) {\n" +
" mutations.forEach(function(mutation) {\n" +
" console.log(mutation);\n" +
" window.mutationRecord(mutation);\n" +
" });\n" +
"});\n\n" +
"mutationObserver.observe(document.documentElement, {\n" +
" attributes: true,\n" +
" characterData: true,\n" +
" childList: true,\n" +
" subtree: true,\n" +
" attributeOldValue: true,\n" +
" characterDataOldValue: true\n" +
"});";

page.evaluate(mutation);

I tried calling Java function from JavaScript using context.exposeFunction. The java method doesn't get called even if there is a html DOM manipulation. How can it be fixed?

I have tried exposing and calling a different, simpler java method, which works perfectly fine. Here it is:

import com.microsoft.playwright.*;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class Example {
  public static void main(String[] args) {
    try (Playwright playwright = Playwright.create()) {
      BrowserType webkit = playwright.webkit()
      Browser browser = webkit.launch(new BrowserType.LaunchOptions().setHeadless(false));
      context.exposeFunction("sha256", args -> {
        String text = (String) args[0];
        MessageDigest crypto;
        try {
          crypto = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
          return null;
        }
        byte[] token = crypto.digest(text.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(token);
      });
      Page page = context.newPage();
      page.setContent("\n" +
        "<button onclick=\"onClick()\">Click me</button>\n" +
        "

\n");
      page.getByRole("button").click();
    }
  }
}


问:
Importing a tkinter program from another interface
I have created a simple password generator using the secret module and created a Tkinter interface for it.
This is the program:

```<code>from tkinter import *
import secrets
import string

def pwd_generator(alphabet, pwd_length):
    pwd = ''

    for i in range(pwd_length):
        pwd += ''.join(secrets.choice(alphabet))
    print(pwd)

    return pwd

def pwd_main():
    root = Tk()
    root.title("Password Generator")

    #Create labels and checkboxes:
    let_var = IntVar()
    Label(root, text="Letters").grid(row=0, column=0, sticky=E, padx=5, pady=5)
    Checkbutton(root, variable=let_var).grid(row=0, column=1, sticky=W, pady=5)

    dig_var = IntVar()
    Label(root, text="Digits").grid(row=1, column=0, sticky=E, padx=5, pady=5)
    Checkbutton(root, variable=dig_var).grid(row=1, column=1, sticky=W, pady=5)

    spc_var = IntVar()
    Label(root, text="Special Characters").grid(row=2, column=0, sticky=E, padx=5, pady=5)
    Checkbutton(root, variable=spc_var).grid(row=2, column=1, sticky=W, pady=5)

    #Create labels and text input:
    Label(root, text="Password Lenght").grid(row=0, column=2, sticky=E, padx=5, pady=5)
    pwd_length = Entry(root, width=10, justify="right")
    pwd_length.grid(row=0, column=3, sticky=E, padx=5, pady=5)

    #Create button:
    Button(root, text="Generate", width=8, command=lambda: display_pwd()).grid(row=1,column=3,sticky=E, padx=5, pady=5)

    #Create result display:
    display = Entry(root, justify="right")
    display.grid(row=2, column=2, columnspan=2, sticky=W+E, padx=5, pady=5)

    #Define variables:

    def get_instructions(let_var, dig_var, spc_var):
        letters = string.ascii_letters
        digits = string.digits
        special_chars = string.punctuation
        alphabet = ""

        if let_var == 1:
            alphabet += letters
        if dig_var == 1:
            alphabet += digits
        if spc_var == 1:
            alphabet += special_chars

        return alphabet

    def display_pwd():
        let_state = let_var.get()
        dig_state = dig_var.get()
        spc_state = spc_var.get()
        pwd_length_state = int(pwd_length.get())
        try:
            alphabet = get_instructions(let_state, dig_state, spc_state)
            pwd = pwd_generator(alphabet, pwd_length_state)
            clear_display()
            display.insert(0,pwd)
        except:
            clear_display()
            display.insert(0, 'Error')

    def clear_display():
        """It clears everything at the GUI display.
        Parameters: none
        Return: nothing
        """
        display.delete(0, END)

    root.mainloop()

if __name__ == "__main__":
    pwd_main()
</code>```

It works just fine, but, I have another program called main.py that is just a button, when you click it, it opens the password generator, but when I do it that way, it no longer works.

The main.py is as follows:

```<code>from tkinter import *
from pass_gen import pwd_main

def main():
    root = Tk()
    root.title("Main Menu")

    #Create buttons:
    Button(root, text="Password\nGenerator", command=pwd_main).grid(row=0,column=1,sticky=W, padx=5, pady=5)

    root.mainloop()

if __name__ == "__main__":
    main()
</code>```

I was expecting for the imported program to work, just as it does when I run it from the pass_gen.py

I don't know what's wrong. The error message says:

```<code>Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\jcamp\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "c:\Users\jcamp\OneDrive\Documentos\byui\cse_111_final_project\pass_gen.py", line 37, in <lambda>
    Button(root, text="Generate", width=8, command=lambda: display_pwd()).grid(row=1,column=3,sticky=E, padx=5, pady=5)
  File "c:\Users\jcamp\OneDrive\Documentos\byui\cse_111_final_project\pass_gen.py", line 68, in display_pwd
    pwd = pwd_generator(alphabet, pwd_length_state)
  File "c:\Users\jcamp\OneDrive\Documentos\byui\cse_111_final_project\pass_gen.py", line 9, in pwd_generator
    pwd += ''.join(secrets.choice(alphabet))
  File "C:\Users\jcamp\AppData\Local\Programs\Python\Python310\lib\random.py", line 378, in choice
    return seq[self._randbelow(len(seq))]
IndexError: string index out of range
</code>```

Body:
I have created a simple password generator using the secret module and created a Tkinter interface for it.
This is the program:

from tkinter import *
import secrets
import string

def pwd_generator(alphabet, pwd_length):
    pwd = ''

    for i in range(pwd_length):
        pwd += ''.join(secrets.choice(alphabet))
    print(pwd)

    return pwd

def pwd_main():
    root = Tk()
    root.title("Password Generator")

    #Create labels and checkboxes:
    let_var = IntVar()
    Label(root, text="Letters").grid(row=0, column=0, sticky=E, padx=5, pady=5)
    Checkbutton(root, variable=let_var).grid(row=0, column=1, sticky=W, pady=5)

    dig_var = IntVar()
    Label(root, text="Digits").grid(row=1, column=0, sticky=E, padx=5, pady=5)
    Checkbutton(root, variable=dig_var).grid(row=1, column=1, sticky=W, pady=5)

    spc_var = IntVar()
    Label(root, text="Special Characters").grid(row=2, column=0, sticky=E, padx=5, pady=5)
    Checkbutton(root, variable=spc_var).grid(row=2, column=1, sticky=W, pady=5)

    #Create labels and text input:
    Label(root, text="Password Lenght").grid(row=0, column=2, sticky=E, padx=5, pady=5)
    pwd_length = Entry(root, width=10, justify="right")
    pwd_length.grid(row=0, column=3, sticky=E, padx=5, pady=5)

    #Create button:
    Button(root, text="Generate", width=8, command=lambda: display_pwd()).grid(row=1,column=3,sticky=E, padx=5, pady=5)

    #Create result display:
    display = Entry(root, justify="right")
    display.grid(row=2, column=2, columnspan=2, sticky=W+E, padx=5, pady=5)

    #Define variables:

    def get_instructions(let_var, dig_var, spc_var):
        letters = string.ascii_letters
        digits = string.digits
        special_chars = string.punctuation
        alphabet = ""

        if let_var == 1:
            alphabet += letters
        if dig_var == 1:
            alphabet += digits
        if spc_var == 1:
            alphabet += special_chars

        return alphabet

    def display_pwd():
        let_state = let_var.get()
        dig_state = dig_var.get()
        spc_state = spc_var.get()
        pwd_length_state = int(pwd_length.get())
        try:
            alphabet = get_instructions(let_state, dig_state, spc_state)
            pwd = pwd_generator(alphabet, pwd_length_state)
            clear_display()
            display.insert(0,pwd)
        except:
            clear_display()
            display.insert(0, 'Error')

    def clear_display():
        """It clears everything at the GUI display.
        Parameters: none
        Return: nothing
        """
        display.delete(0, END)

    root.mainloop()

if __name__ == "__main__":
    pwd_main()

It works just fine, but, I have another program called main.py that is just a button, when you click it, it opens the password generator, but when I do it that way, it no longer works.

The main.py is as follows:

from tkinter import *
from pass_gen import pwd_main

def main():
    root = Tk()
    root.title("Main Menu")

    #Create buttons:
    Button(root, text="Password\nGenerator", command=pwd_main).grid(row=0,column=1,sticky=W, padx=5, pady=5)

    root.mainloop()

if __name__ == "__main__":
    main()

I was expecting for the imported program to work, just as it does when I run it from the pass_gen.py

I don't know what's wrong. The error message says:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\jcamp\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "c:\Users\jcamp\OneDrive\Documentos\byui\cse_111_final_project\pass_gen.py", line 37, in <lambda>
    Button(root, text="Generate", width=8, command=lambda: display_pwd()).grid(row=1,column=3,sticky=E, padx=5, pady=5)
  File "c:\Users\jcamp\OneDrive\Documentos\byui\cse_111_final_project\pass_gen.py", line 68, in display_pwd
    pwd = pwd_generator(alphabet, pwd_length_state)
  File "c:\Users\jcamp\OneDrive\Documentos\byui\cse_111_final_project\pass_gen.py", line 9, in pwd_generator
    pwd += ''.join(secrets.choice(alphabet))
  File "C:\Users\jcamp\AppData\Local\Programs\Python\Python310\lib\random.py", line 378, in choice
    return seq[self._randbelow(len(seq))]
IndexError: string index out of range


问:
How set JasperSoft Studio report direction to right to left?
I have JasperReports 6.8.0.
How set JasperSoft Studio report direction to right to left?

The question has been closed because some people say there are similar questions. One of those questions is talking about exporting to excel sheet and has no answer. The other is talking about PDF!
I need to change the direction of all formats, excel, html, pdf, etc... . Even when printing.


问:
How to use Angular Library directly from Github to another Angular Project without publishing the Angular Library to NPM
TL;DR - I'm looking for a solution that doesn't require publishing to NPM or using NPM symlink

I've created two demo repos in Github, one is for the Angular Library and one for an Angular application that will use the Angular Library. I'm not allowed to publish the Angular Library to NPM due to privacy and security reasons. So I would like to npm install the Angular Library directly into the Angular application.

I've created the Angulary Library using ng new my-lib --no-create-application and ng generate library my-lib, and the Angular application with just ng new my-app. I'm not sure how I'm going to install my-lib into my-app.

I tried to ng build and npm pack the dist of my-lib then push everything in Github. But when I installed my-lib in my-app by putting "my-lib": "git@github.com:<github_user>/my-lib.git" in package.json and doing npm install it says that cannot find module when I try to import in my app.module.ts.


问:
How to check existence of primary key of ORM model in table in SQLAlchemy
I'm attempting to check if the key of a particular entity (as defined with an ORM class) already exists in a database.

Note that it needs to work regardless of the names of the (key) attributes. It needs to work generically across all ORM models.

Here's the basic structure of what I need:

# User class definition using ORM
class Employee(Base):
    __tablename__ = 'User'
    USER_ID = Column(String(50), primary_key=True)
    ... # OTHER FIELDS EXIST HERE, NOT PART OF PRIMARY KEY

# We have a particular ORM instance
# We need to check if its PK exists in table
# Other fields may have any values
user_instance = User(USER_ID = 1)

# We have a session with DB
session = Session()

# ===

# Now, how do we check if User with USER_ID = 1 (dynamically - we might have different data)

# ===

```

I am aware of sqlalchemy.inspect but I'm not really sure how it would be applied in this case.

Any help is greatly appreciated.

Body:
I'm attempting to check if the key of a particular entity (as defined with an ORM class) already exists in a database.

Note that it needs to work regardless of the names of the (key) attributes. It needs to work generically across all ORM models.

Here's the basic structure of what I need:

# User class definition using ORM
class Employee(Base):
    __tablename__ = 'User'
    USER_ID = Column(String(50), primary_key=True)
    ... # OTHER FIELDS EXIST HERE, NOT PART OF PRIMARY KEY

# We have a particular ORM instance
# We need to check if its PK exists in table
# Other fields may have any values
user_instance = User(USER_ID = 1)

# We have a session with DB
session = Session()

# ===

# Now, how do we check if User with USER_ID = 1 (dynamically - we might have different data)

# ===

I am aware of sqlalchemy.inspect but I'm not really sure how it would be applied in this case.

Any help is greatly appreciated.


问:
Where does gcloud install kubectl command?
I am using this command gcloud components install kubectl to install kubectl in my laptop (Mac).

But I have an existing kubectl which was installed by brew. How can I know the full path of kubectl installed by gcloud? I can change PATH env var to point to this path.


问:
How to handle navigation to change component className in Nextjs?
Im trying to make some morphing modals with the help of this repo, usingo ne of its components to display different information as a modal popup, like cards.

I want to be able to close the modal with browser navigation (back). I managed to do it, but with some problems:

(I want to use it in a page with some sections and a navbar to jump to those sections)

If i go to any section previous to opening the modal, then when it closes returns to that section. (i want to avoid the scroll)

Once closed, i can go forward and the url changes to the hash (ex: /#card1) but the modal doesn't open again, so it would take an extra back action to really go back.

//the next one is updated

if i close with the modal close button, the url doesnt update, and the history doesnt go back a step.

Update: Instead of calling the close function when handling the back button, I used history.back(); on the close method, and moved the close logig to the navigation handle so everything works the same.

//----------------------

The perfect scenario would be that the back button closes the modal, and if there was a previous "forward" in the history (prior to opening the modal), be able to use that again as forward (I tried using replace on <Link>, but then when i use the back button to close the modal, it goes back to a previous page if no section was selected prior to that)

In short what i would need:

Close the modal with the back button, and consume the event so it doesnt go back in history. Or at least prevent the scrolling

Open the modal without affecting the forward history [this is less important]

This is the class (I trimmed irrelevant parts, here is the full original)

/* eslint-disable */
import React, { Component } from "react";
import PropTypes from "prop-types";
import Link from "next/link";

export default class MorphButtonModal extends Component {
  static propTypes = {
    id: PropTypes.number,
  };
  constructor(props) {
    super(props);
    this.state = { openDialog: false, };
    this.close = this._close.bind(this);
    this.open = this._open.bind(this);
    this.setButtonPos = this._setButtonPos.bind(this);
    this.handleNavigateBack = this.handleNavigateBack.bind(this);
  }

  componentDidMount() {
    window.addEventListener("popstate", this.handleNavigateBack);
  }
  componentWillUnmount() {
    window.removeEventListener("popstate", this.handleNavigateBack);
  }

  handleNavigateBack(event) {
    this.setState({ openDialog: false });
    event.stopPropagation();
  }

  _setButtonPos() {
    const buttonPos = this._button.getBoundingClientRect();
    this.setState({ buttonPos });
  }
  _open() {
    this.setButtonPos();
    setTimeout(() => {
      this.setState({ openDialog: true });
    }, 100);
  }

  // method called when navigation.Back, Close button, and click in background
  _close(event) {
    history.back();
    event.stopPropagation();
  }
  render() {
    return (
      <div className={`${openDialog ? `${styles.active} ${styles.open}` : ""}`}>
        <Link replace href={"/#" + label}>
          <button onClick={this.open} type="button" ref={(ref) => (this._button = ref)}>
            //{label}
          </button>
        </Link>
        <div onClick={this.close} className={`${styles.icon} ${styles.modalBack}`}>
          //background div

          //Content div

    );
  }
}
```


问:
Keystore operation fails after Biometric Operation despite success method called on callback
I am attempting to perform a signing operation with a secret key that can only be used after user authenticates with their device biometrics. I have the logic like this

```<code>            val mac = initMac(keyAlias)
            val biometricPrompt = createBiometricPrompt()

            biometricPrompt.authenticate(promptInfo, BiometricPrompt.CryptoObject(mac))
</code>```

The initMac function gets a Mac Crypto object to be used for the signing after successful authentication

```<code> private fun initMac(keyName: String): Mac {
    val keyStore = KeyStore.getInstance("AndroidKeyStore")
    keyStore.load(null)
    var secretKey = keyStore.getKey(keyName, null) as SecretKey?
    if(secretKey == null) {
        secretKey = generateKey(keyName, this)
    }
    val mac = Mac.getInstance("HmacSHA256")
    mac.init(secretKey)
    return mac
}
</code>```

The key generation itself looks like this

```<code>val keyGenerator =
            KeyGenerator.getInstance(KEY_ALGORITHM_HMAC_SHA256, "AndroidKeyStore")
keyGenerator.init(KeyGenParameterSpec.Builder(keyAlias, PURPOSE_SIGN)
.setUserAuthenticationRequired(true))
.build()
</code>```

When I run this I get the fingerprint dialog as expected and on fingerprint scanned the onAuthenticationSucceeded funtion in the callback gets triggered and the Mac object get's supplied as argument as expected. The problem though is that when I attempt to perform the signing with the Mac object I get a Keystore operation failed error even though I have successfully scanned my biometrics(which means authentication was successful). Here is the logic for the signing and the error I get.

```<code>object : BiometricPrompt.AuthenticationCallback() {
 override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
            super.onAuthenticationSucceeded(result)
            Log.d(TAG, "Authentication was successful")
            val fingerprint = result.cryptoObject?.mac?.doFinal(SALT.toByteArray())
        }
}
</code>```

The error

```<code> java.security.ProviderException: Keystore operation failed
    at android.security.keystore2.AndroidKeyStoreHmacSpi.engineDoFinal(AndroidKeyStoreHmacSpi.java:241)
    at javax.crypto.Mac.doFinal(Mac.java:667)
    at javax.crypto.Mac.doFinal(Mac.java:742)
     Caused by: android.security.KeyStoreException: Key user not authenticated (internal Keystore code: -26 message: In KeystoreOperation::finish

Caused by:
    0: In finish: KeyMint::finish failed.
    1: Error::Km(ErrorCode(-26))) (public error code: 2 internal Keystore code: -26)
    at android.security.KeyStore2.getKeyStoreException(KeyStore2.java:369)
    at android.security.KeyStoreOperation.handleExceptions(KeyStoreOperation.java:78)
    at android.security.KeyStoreOperation.finish(KeyStoreOperation.java:128)
    at android.security.keystore2.KeyStoreCryptoOperationChunkedStreamer$MainDataStream.finish(KeyStoreCryptoOperationChunkedStreamer.java:228)
    at android.security.keystore2.KeyStoreCryptoOperationChunkedStreamer.doFinal(KeyStoreCryptoOperationChunkedStreamer.java:181)
    at android.security.keystore2.AndroidKeyStoreHmacSpi.engineDoFinal(AndroidKeyStoreHmacSpi.java:237)
        ... 13 more
</code>```

Body:
I am attempting to perform a signing operation with a secret key that can only be used after user authenticates with their device biometrics. I have the logic like this

            val mac = initMac(keyAlias)
            val biometricPrompt = createBiometricPrompt()

            biometricPrompt.authenticate(promptInfo, BiometricPrompt.CryptoObject(mac))

The initMac function gets a Mac Crypto object to be used for the signing after successful authentication

 private fun initMac(keyName: String): Mac {
    val keyStore = KeyStore.getInstance("AndroidKeyStore")
    keyStore.load(null)
    var secretKey = keyStore.getKey(keyName, null) as SecretKey?
    if(secretKey == null) {
        secretKey = generateKey(keyName, this)
    }
    val mac = Mac.getInstance("HmacSHA256")
    mac.init(secretKey)
    return mac
}

The key generation itself looks like this

val keyGenerator =
            KeyGenerator.getInstance(KEY_ALGORITHM_HMAC_SHA256, "AndroidKeyStore")
keyGenerator.init(KeyGenParameterSpec.Builder(keyAlias, PURPOSE_SIGN)
.setUserAuthenticationRequired(true))
.build()

When I run this I get the fingerprint dialog as expected and on fingerprint scanned the onAuthenticationSucceeded funtion in the callback gets triggered and the Mac object get's supplied as argument as expected. The problem though is that when I attempt to perform the signing with the Mac object I get a Keystore operation failed error even though I have successfully scanned my biometrics(which means authentication was successful). Here is the logic for the signing and the error I get.

object : BiometricPrompt.AuthenticationCallback() {
 override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
            super.onAuthenticationSucceeded(result)
            Log.d(TAG, "Authentication was successful")
            val fingerprint = result.cryptoObject?.mac?.doFinal(SALT.toByteArray())
        }
}

The error

 java.security.ProviderException: Keystore operation failed
    at android.security.keystore2.AndroidKeyStoreHmacSpi.engineDoFinal(AndroidKeyStoreHmacSpi.java:241)
    at javax.crypto.Mac.doFinal(Mac.java:667)
    at javax.crypto.Mac.doFinal(Mac.java:742)
     Caused by: android.security.KeyStoreException: Key user not authenticated (internal Keystore code: -26 message: In KeystoreOperation::finish

Caused by:
    0: In finish: KeyMint::finish failed.
    1: Error::Km(ErrorCode(-26))) (public error code: 2 internal Keystore code: -26)
    at android.security.KeyStore2.getKeyStoreException(KeyStore2.java:369)
    at android.security.KeyStoreOperation.handleExceptions(KeyStoreOperation.java:78)
    at android.security.KeyStoreOperation.finish(KeyStoreOperation.java:128)
    at android.security.keystore2.KeyStoreCryptoOperationChunkedStreamer$MainDataStream.finish(KeyStoreCryptoOperationChunkedStreamer.java:228)
    at android.security.keystore2.KeyStoreCryptoOperationChunkedStreamer.doFinal(KeyStoreCryptoOperationChunkedStreamer.java:181)
    at android.security.keystore2.AndroidKeyStoreHmacSpi.engineDoFinal(AndroidKeyStoreHmacSpi.java:237)
        ... 13 more


问:
Understanding reSize() and add() for Vector classes
I am struggling with a java problem.

I am trying to understand how to assign value x to new elements added to a vector where the existing elements would remain unchanged, e.g. if it was resized from 3 to 5 then the 4th and 5th would have value x.

Additionally, in the next class I want to add another vector _v to the current vector. If this is bigger than the length of the current vector that reSize(int _size) is called. How do I write this?

```<code>public class Vector {
    private double[] doubElements;

    public Vector(double[] _elements) {
        this.doubElements = _elements;

    }

    public int getVectorSize() {

        return doubElements.length;
    }

    public Vector reSize(int _size) {
        if (_size == (doubElements.length - 1) || _size <= 0){
            return null;
        } else if (_size < (doubElements.length - 1)) {
            return new Vector(new double[]{doubElements[_size]});
        } else {
            return new Vector(new double[]{doubElements.add(-1.0)});
        }

    }

    public Vector add(Vector _v) {
        Vector.this.add(_v);
        if (getVectorSize(doubElements.length)) {
            reSize()...?
            return null;
        }
    }
</code>```

Body:
I am struggling with a java problem.

I am trying to understand how to assign value x to new elements added to a vector where the existing elements would remain unchanged, e.g. if it was resized from 3 to 5 then the 4th and 5th would have value x.

Additionally, in the next class I want to add another vector _v to the current vector. If this is bigger than the length of the current vector that reSize(int _size) is called. How do I write this?

public class Vector {
    private double[] doubElements;

    public Vector(double[] _elements) {
        this.doubElements = _elements;

    }

    public int getVectorSize() {

        return doubElements.length;
    }

    public Vector reSize(int _size) {
        if (_size == (doubElements.length - 1) || _size <= 0){
            return null;
        } else if (_size < (doubElements.length - 1)) {
            return new Vector(new double[]{doubElements[_size]});
        } else {
            return new Vector(new double[]{doubElements.add(-1.0)});
        }

    }

    public Vector add(Vector _v) {
        Vector.this.add(_v);
        if (getVectorSize(doubElements.length)) {
            reSize()...?
            return null;
        }
    }


问:
How to use Docker local-persist plugin as a systemd service on Ubuntu 22.04
I'm trying to create persistent docker volumes for a large application consisting of several dozen services (and around 35 volumes.) I came across the local-persist plugin at the Use Docker Engine Plugins page on the Docker website. I followed the author's README to install local-persist as a systemd service. Essentially:

curl -fsSL https://raw.githubusercontent.com/CWSpear/local-persist/master/scripts/install.sh | sudo bash
```
<p>The service has been installed and is running correctly on each node:</p>
<pre class="lang-bash prettyprint-override"><code>$ systemctl | grep pers
  docker-volume-local-persist.service       loaded active running   docker-volume-local-persist
$
</code>```

But when I try to use it from a docker-compose file (author instructions here, referenced in the README):

volumes:
  cache-perstnt-1-data:
    driver: local-persist
    driver_opts:
      mountpoint: /data/cache-perstnt-1-data
```

...Docker can't find the plugin.

Is there something else I need to do to let Docker know the plugin's available as a systemd service?

Body:
I'm trying to create persistent docker volumes for a large application consisting of several dozen services (and around 35 volumes.) I came across the local-persist plugin at the Use Docker Engine Plugins page on the Docker website. I followed the author's README to install local-persist as a systemd service. Essentially:

curl -fsSL https://raw.githubusercontent.com/CWSpear/local-persist/master/scripts/install.sh | sudo bash

The service has been installed and is running correctly on each node:

$ systemctl | grep pers
  docker-volume-local-persist.service       loaded active running   docker-volume-local-persist
$

But when I try to use it from a docker-compose file (author instructions here, referenced in the README):

volumes:
  cache-perstnt-1-data:
    driver: local-persist
    driver_opts:
      mountpoint: /data/cache-perstnt-1-data

...Docker can't find the plugin.

Is there something else I need to do to let Docker know the plugin's available as a systemd service?