问:
flyaway not puck up the last version
i create a version 13 and 14 and when i run the flayway it take just for v13 i have write the sql statement correct and i add the correct number of version and then when the flayway did not take the v14 i try to run it so this is the rest of details belwo

```<code>public class V13__createLessonsThumbnalisTables extends BAmanMigration{
    @Override
    public List<String> getMigrations() {

        return Arrays.asList("create table mst_thumbnails_lessons\n" +
                "(\n" +
                "    id                 bigserial not null,\n" +
                "    thumbnail_name     varchar(255) not null,\n" +
                "    creation_date      timestamp,\n" +
                "    updated_date       timestamp,\n" +
                "    is_active          boolean default true,\n" +
                "    is_enabled         boolean default true not null,\n" +
                "    created_by         int8,\n" +
                "    updated_by         int8,\n" +
                "    thumbnail_id       int8 constraint fk_thumbnail_id references mst_media,\n" +
                "    primary key (id)\n" +
                ");");
    }
}

public class V14__uploadThumbnailIntoThumbnailLessonTable extends BAmanMigration{

    private final LessonRepository LessonRepository;

    public V14__uploadThumbnailIntoThumbnailLessonTable(LessonRepository lessonRepository) {
        LessonRepository = lessonRepository;
    }
    ArrayList<String> migrations =  new ArrayList<>();
    @Override
    public List<String> getMigrations() {

        List<LessonsEntity> lessons = LessonRepository.findAll();

        for (LessonsEntity lesson : lessons) {
            String mediaUrl = lesson.getThumbnail().getMediaUrl();

            // extract the file name from the url
            String fileName = mediaUrl.substring(mediaUrl.lastIndexOf("/") + 1).toLowerCase();

            migrations.add("INSERT INTO mst_thumbnails_lessons (thumbnail_name, creation_date, updated_date, is_active, is_enabled, thumbnail_id)" +
                    " VALUES ( '"+fileName+"', now(), now(), true, true, (select id from mst_media where media_url LIKE '%" + fileName +"% '))");
        }
        return migrations;
    }
}
</code>```

but the flayway not puck up the last version 14 just take 13 and when i try to run v14 using this command

```<code>flyway migrate -target=14 -X
</code>```

i get

```<code>DEBUG: AWS SDK available: false
DEBUG: Google Cloud Storage available: true
DEBUG: Scanning for filesystem resources at 'sql'
ERROR: Skipping filesystem location: sql (not found)
DEBUG: Loading config file: /home/yazan/flyway-9.8.1/conf/flyway.conf
DEBUG: Unable to load config file: /home/yazan/flyway.conf
DEBUG: Unable to load config file: /home/yazan/IdeaProjects/baman-api/flyway.conf
DEBUG: Using configuration:
DEBUG: flyway.jarDirs -> /home/yazan/flyway-9.8.1/jars
DEBUG: flyway.locations -> filesystem:sql
DEBUG: flyway.password -> *****
DEBUG: flyway.target -> 14
DEBUG: flyway.url -> jdbc:postgresql://localhost:5554/baman
DEBUG: flyway.user -> baman
DEBUG: Multiple databases found that handle url 'jdbc:postgresql://localhost:5554/baman': YugabyteDB, CockroachDB, PostgreSQL
DEBUG: Scanning for classpath resources at 'classpath:db/callback' ...
DEBUG: Determining location urls for classpath:db/callback using ClassLoader java.net.URLClassLoader@4a3e3e8b ...
DEBUG: Unable to resolve location classpath:db/callback.
Database: jdbc:postgresql://localhost:5554/baman (PostgreSQL 14.5)
DEBUG: Driver  : PostgreSQL JDBC Driver 42.4.1
DEBUG: DDL Transactions Supported: true
DEBUG: Schemas:
DEBUG: Default schema: null
DEBUG: Scanning for SQL callbacks ...
DEBUG: Validating migrations ...
DEBUG: Rolling back transaction...
DEBUG: Transaction rolled back
DEBUG: Memory usage: 42 of 250M
ERROR: Unexpected error
org.flywaydb.core.api.FlywayException: No migration with a target version 14 could be found. Ensure target is specified correctly and the migration exists.
        at org.flywaydb.core.internal.info.MigrationInfoServiceImpl.validateTarget(MigrationInfoServiceImpl.java:251)
        at org.flywaydb.core.internal.info.MigrationInfoServiceImpl.refresh(MigrationInfoServiceImpl.java:120)
        at org.flywaydb.core.internal.command.DbValidate.lambda$validate$0(DbValidate.java:108)
        at org.flywaydb.core.internal.jdbc.TransactionalExecutionTemplate.execute(TransactionalExecutionTemplate.java:55)
        at org.flywaydb.core.internal.command.DbValidate.validate(DbValidate.java:101)
        at org.flywaydb.core.Flyway.doValidate(Flyway.java:358)
        at org.flywaydb.core.Flyway.lambda$migrate$0(Flyway.java:132)
        at org.flywaydb.core.FlywayExecutor.execute(FlywayExecutor.java:204)
        at org.flywaydb.core.Flyway.migrate(Flyway.java:128)
        at org.flywaydb.commandline.Main.executeOperation(Main.java:275)
        at org.flywaydb.commandline.Main.main(Main.java:179)
</code>```

Title: flyaway not puck up the last version

Body:
i create a version 13 and 14 and when i run the flayway it take just for v13 i have write the sql statement correct and i add the correct number of version and then when the flayway did not take the v14 i try to run it so this is the rest of details belwo

public class V13__createLessonsThumbnalisTables extends BAmanMigration{
    @Override
    public List<String> getMigrations() {

        return Arrays.asList("create table mst_thumbnails_lessons\n" +
                "(\n" +
                "    id                 bigserial not null,\n" +
                "    thumbnail_name     varchar(255) not null,\n" +
                "    creation_date      timestamp,\n" +
                "    updated_date       timestamp,\n" +
                "    is_active          boolean default true,\n" +
                "    is_enabled         boolean default true not null,\n" +
                "    created_by         int8,\n" +
                "    updated_by         int8,\n" +
                "    thumbnail_id       int8 constraint fk_thumbnail_id references mst_media,\n" +
                "    primary key (id)\n" +
                ");");
    }
}

public class V14__uploadThumbnailIntoThumbnailLessonTable extends BAmanMigration{

    private final LessonRepository LessonRepository;

    public V14__uploadThumbnailIntoThumbnailLessonTable(LessonRepository lessonRepository) {
        LessonRepository = lessonRepository;
    }
    ArrayList<String> migrations =  new ArrayList<>();
    @Override
    public List<String> getMigrations() {

        List<LessonsEntity> lessons = LessonRepository.findAll();

        for (LessonsEntity lesson : lessons) {
            String mediaUrl = lesson.getThumbnail().getMediaUrl();

            // extract the file name from the url
            String fileName = mediaUrl.substring(mediaUrl.lastIndexOf("/") + 1).toLowerCase();

            migrations.add("INSERT INTO mst_thumbnails_lessons (thumbnail_name, creation_date, updated_date, is_active, is_enabled, thumbnail_id)" +
                    " VALUES ( '"+fileName+"', now(), now(), true, true, (select id from mst_media where media_url LIKE '%" + fileName +"% '))");
        }
        return migrations;
    }
}

but the flayway not puck up the last version 14 just take 13 and when i try to run v14 using this command

flyway migrate -target=14 -X

i get

DEBUG: AWS SDK available: false
DEBUG: Google Cloud Storage available: true
DEBUG: Scanning for filesystem resources at 'sql'
ERROR: Skipping filesystem location: sql (not found)
DEBUG: Loading config file: /home/yazan/flyway-9.8.1/conf/flyway.conf
DEBUG: Unable to load config file: /home/yazan/flyway.conf
DEBUG: Unable to load config file: /home/yazan/IdeaProjects/baman-api/flyway.conf
DEBUG: Using configuration:
DEBUG: flyway.jarDirs -> /home/yazan/flyway-9.8.1/jars
DEBUG: flyway.locations -> filesystem:sql
DEBUG: flyway.password -> *****
DEBUG: flyway.target -> 14
DEBUG: flyway.url -> jdbc:postgresql://localhost:5554/baman
DEBUG: flyway.user -> baman
DEBUG: Multiple databases found that handle url 'jdbc:postgresql://localhost:5554/baman': YugabyteDB, CockroachDB, PostgreSQL
DEBUG: Scanning for classpath resources at 'classpath:db/callback' ...
DEBUG: Determining location urls for classpath:db/callback using ClassLoader java.net.URLClassLoader@4a3e3e8b ...
DEBUG: Unable to resolve location classpath:db/callback.
Database: jdbc:postgresql://localhost:5554/baman (PostgreSQL 14.5)
DEBUG: Driver  : PostgreSQL JDBC Driver 42.4.1
DEBUG: DDL Transactions Supported: true
DEBUG: Schemas:
DEBUG: Default schema: null
DEBUG: Scanning for SQL callbacks ...
DEBUG: Validating migrations ...
DEBUG: Rolling back transaction...
DEBUG: Transaction rolled back
DEBUG: Memory usage: 42 of 250M
ERROR: Unexpected error
org.flywaydb.core.api.FlywayException: No migration with a target version 14 could be found. Ensure target is specified correctly and the migration exists.
        at org.flywaydb.core.internal.info.MigrationInfoServiceImpl.validateTarget(MigrationInfoServiceImpl.java:251)
        at org.flywaydb.core.internal.info.MigrationInfoServiceImpl.refresh(MigrationInfoServiceImpl.java:120)
        at org.flywaydb.core.internal.command.DbValidate.lambda$validate$0(DbValidate.java:108)
        at org.flywaydb.core.internal.jdbc.TransactionalExecutionTemplate.execute(TransactionalExecutionTemplate.java:55)
        at org.flywaydb.core.internal.command.DbValidate.validate(DbValidate.java:101)
        at org.flywaydb.core.Flyway.doValidate(Flyway.java:358)
        at org.flywaydb.core.Flyway.lambda$migrate$0(Flyway.java:132)
        at org.flywaydb.core.FlywayExecutor.execute(FlywayExecutor.java:204)
        at org.flywaydb.core.Flyway.migrate(Flyway.java:128)
        at org.flywaydb.commandline.Main.executeOperation(Main.java:275)
        at org.flywaydb.commandline.Main.main(Main.java:179)


来源: stackexchange

问:
Testing if element is removed when a prop changes is not working in React Testing Library
I'm trying to test if a Material UI component is removed when a button is clicked and can't seem to get the test to provide a reliable answer.  Here is the (simplified) React component I'm testing:

```<code>import Snackbar from '@mui/material/Snackbar';
import MuiAlert from '@mui/material/Alert';
import IconButton from '@mui/material/IconButton';
import CloseIcon from '@mui/icons-material/Close';

const ResultMessage = (props) => {

  const handleClose = () => {
    props.onClose();
  };

  return (
    <Snackbar
      open={props.open}
      onClose={handleClose}
      action={
    <IconButton role='button'>
        <CloseIcon />
      </IconButton>
      }>
      <MuiAlert onClose={handleClose}>
        {props.message}
      </MuiAlert>
    </Snackbar>
  );
}

export default ResultMessage;
</code>```

And here is the contents of my test file:

```<code>import { render, screen, fireEvent } from "@testing-library/react";
import { unmountComponentAtNode } from "react-dom";
import userEvent from "@testing-library/user-event";
import ResultMessage from "../ResultMessage";

let container = null;

beforeEach(() => {
  container = document.createElement('div');
  document.body.appendChild(container);
});

afterEach(() => {
  unmountComponentAtNode(container);
  container.remove();
  container = null;
});

describe('Tests ResultMessage Component', () => {

  it('should confirm message is removed when close button is clicked', () => {

    let show = true;
    const handleClose = () => { show = false }

    const {rerender} = render(<ResultMessage
      open={show}
      onClose={handleClose} />, container);

    expect(screen.getByRole('presentation')).toBeInTheDocument();
    expect(screen.getByRole('button')).toBeInTheDocument();

    fireEvent.click(screen.getByRole('button'));
    // userEvent.click(screen.getByRole('button'));

    rerender(<ResultMessage
      open={show}
      onClose={handleClose} />, container);

    setTimeout(() => {
      expect(screen.queryByRole('presentation')).toBeNull();
      expect(screen.getByRole('presentation')).toBeInTheDocument();
    }, 0);
  });
});
</code>```

I'm attempting to use a variable to control showing and hiding of the Snackbar component. That component has an open property that either shows or hides the component if the value is true or false.  In my actual app, I use useState to control this functionality but as far as I can tell, I can't use React Hooks in my tests. Perhaps this is related to the problem.

The idea here is that I want to initially render the component and display it by setting the 'show' variable to true.  I confirm that the snackbar with a role of 'presentation' and the button are present.  All good so far.

I then trigger a button click (either with fireEvent or userEvent) that changes the value of the 'show' variable to false.  I then attempt to remove the snackbar by "rerender"-ing the same component as stated in the RTL documentation, but this time with the hope that the 'show' variable will be false and therefore the component should be removed. (that is how it works in React at any rate).

Where it gets weird is the expectations at the bottom of the code - both should be the opposite of one another - somehow they both succeed when I run the test.  Not sure how I could test for the component to be null and in the document at the same time and it succeed.  I've inserted that logic into setTimeouts thinking that perhaps the problem might be related to the state change not being performed immediately. If I remove the setTimeouts the null check fails implying it's still there.  I've also tried 'waitFor' with no success.

My current thought is maybe a new component is being generated instead of updating the state of the initially created component and therefore the test has two components to test and returning that odd result I mentioned.  If so, I cannot figure out how to generate only one component and update that props state. Thank you for any help you can provide!

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to test if a Material UI component is removed when a button is clicked and can't seem to get the test to provide a reliable answer.  Here is the (simplified) React component I'm testing:

import Snackbar from '@mui/material/Snackbar';
import MuiAlert from '@mui/material/Alert';
import IconButton from '@mui/material/IconButton';
import CloseIcon from '@mui/icons-material/Close';

const ResultMessage = (props) => {

  const handleClose = () => {
    props.onClose();
  };

  return (
    <Snackbar
      open={props.open}
      onClose={handleClose}
      action={
    <IconButton role='button'>
        <CloseIcon />
      </IconButton>
      }>
      <MuiAlert onClose={handleClose}>
        {props.message}
      </MuiAlert>
    </Snackbar>
  );
}

export default ResultMessage;

And here is the contents of my test file:

import { render, screen, fireEvent } from "@testing-library/react";
import { unmountComponentAtNode } from "react-dom";
import userEvent from "@testing-library/user-event";
import ResultMessage from "../ResultMessage";

let container = null;

beforeEach(() => {
  container = document.createElement('div');
  document.body.appendChild(container);
});

afterEach(() => {
  unmountComponentAtNode(container);
  container.remove();
  container = null;
});

describe('Tests ResultMessage Component', () => {

  it('should confirm message is removed when close button is clicked', () => {

    let show = true;
    const handleClose = () => { show = false }

    const {rerender} = render(<ResultMessage
      open={show}
      onClose={handleClose} />, container);

    expect(screen.getByRole('presentation')).toBeInTheDocument();
    expect(screen.getByRole('button')).toBeInTheDocument();

    fireEvent.click(screen.getByRole('button'));
    // userEvent.click(screen.getByRole('button'));

    rerender(<ResultMessage
      open={show}
      onClose={handleClose} />, container);

    setTimeout(() => {
      expect(screen.queryByRole('presentation')).toBeNull();
      expect(screen.getByRole('presentation')).toBeInTheDocument();
    }, 0);
  });
});

I'm attempting to use a variable to control showing and hiding of the Snackbar component. That component has an open property that either shows or hides the component if the value is true or false.  In my actual app, I use useState to control this functionality but as far as I can tell, I can't use React Hooks in my tests. Perhaps this is related to the problem.

The idea here is that I want to initially render the component and display it by setting the 'show' variable to true.  I confirm that the snackbar with a role of 'presentation' and the button are present.  All good so far.

I then trigger a button click (either with fireEvent or userEvent) that changes the value of the 'show' variable to false.  I then attempt to remove the snackbar by "rerender"-ing the same component as stated in the RTL documentation, but this time with the hope that the 'show' variable will be false and therefore the component should be removed. (that is how it works in React at any rate).

Where it gets weird is the expectations at the bottom of the code - both should be the opposite of one another - somehow they both succeed when I run the test.  Not sure how I could test for the component to be null and in the document at the same time and it succeed.  I've inserted that logic into setTimeouts thinking that perhaps the problem might be related to the state change not being performed immediately. If I remove the setTimeouts the null check fails implying it's still there.  I've also tried 'waitFor' with no success.

My current thought is maybe a new component is being generated instead of updating the state of the initially created component and therefore the test has two components to test and returning that odd result I mentioned.  If so, I cannot figure out how to generate only one component and update that props state. Thank you for any help you can provide!


问:
Flutter error crash showing on Crashlytics, but no idea what class it relates to - is it framework error?
I can see the following error on my console but no context is there to which class/view of mine is throwing it. It is only showing flutter framework classes. I am copying the text from the Firebase console below...

Can someone help me understand what is happening please so I can fix it?

It is happening on Samsung and LG devices only.

Error:

```<code>Fatal Exception: io.flutter.plugins.firebase.crashlytics.FlutterError: Null check operator used on a null value. Error thrown null.
       at TextPainter.getPositionForOffset(text_painter.dart:976)
       at RenderParagraph.hitTestChildren(paragraph.dart:581)
       at RenderBox.hitTest(box.dart:2511)
       at RenderBoxContainerDefaultsMixin.defaultHitTestChildren.<fn>(box.dart:2879)
       at BoxHitTestResult.addWithPaintOffset(box.dart:805)
       at RenderBoxContainerDefaultsMixin.defaultHitTestChildren(box.dart:2874)
       at RenderFlex.hitTestChildren(flex.dart:1082)
       at RenderBox.hitTest(box.dart:2511)
       at RenderShiftedBox.hitTestChildren.<fn>(shifted_box.dart:97)
       at BoxHitTestResult.addWithPaintOffset(box.dart:805)
       at RenderShiftedBox.hitTestChildren(shifted_box.dart:92)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderProxyBoxWithHitTestBehavior.hitTest(proxy_box.dart:183)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at RenderBoxContainerDefaultsMixin.defaultHitTestChildren.<fn>(box.dart:2879)
       at BoxHitTestResult.addWithPaintOffset(box.dart:805)
       at RenderBoxContainerDefaultsMixin.defaultHitTestChildren(box.dart:2874)
       at RenderFlex.hitTestChildren(flex.dart:1082)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at RenderShiftedBox.hitTestChildren.<fn>(shifted_box.dart:97)
       at BoxHitTestResult.addWithPaintOffset(box.dart:805)
       at RenderShiftedBox.hitTestChildren(shifted_box.dart:92)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderProxyBoxWithHitTestBehavior.hitTest(proxy_box.dart:183)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderProxyBoxWithHitTestBehavior.hitTest(proxy_box.dart:183)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at RenderSliverHelpers.hitTestBoxChild.<fn>(sliver.dart:1669)
       at BoxHitTestResult.addWithOutOfBandPosition(box.dart:902)
       at RenderSliverHelpers.hitTestBoxChild(sliver.dart:1666)
       at RenderSliverMultiBoxAdaptor.hitTestChildren(sliver_multi_box_adaptor.dart:564)
       at RenderSliver.hitTest(sliver.dart:1287)
       at SliverHitTestResult.addWithAxisOffset(sliver.dart:858)
       at RenderSliverEdgeInsetsPadding.hitTestChildren(sliver_padding.dart:231)
       at RenderSliver.hitTest(sliver.dart:1287)
       at RenderViewportBase.hitTestChildren.<fn>(viewport.dart:735)
       at BoxHitTestResult.addWithOutOfBandPosition(box.dart:902)
       at RenderViewportBase.hitTestChildren(viewport.dart:732)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at RenderOffstage.hitTest(proxy_box.dart:3743)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderProxyBoxWithHitTestBehavior.hitTest(proxy_box.dart:183)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderProxyBoxWithHitTestBehavior.hitTest(proxy_box.dart:183)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderProxyBoxWithHitTestBehavior.hitTest(proxy_box.dart:183)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderFollowerLayer.hitTestChildren.<fn>(proxy_box.dart:4914)
       at BoxHitTestResult.addWithRawTransform(box.dart:844)
       at BoxHitTestResult.addWithPaintTransform(box.dart:769)
       at RenderTransform.hitTestChildren(proxy_box.dart:2586)
       at RenderTransform.hitTest(proxy_box.dart:2580)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at RenderClipRect.hitTest(proxy_box.dart:1546)
       at RenderBoxContainerDefaultsMixin.defaultHitTestChildren.<fn>(box.dart:2879)
       at BoxHitTestResult.addWithPaintOffset(box.dart:805)
       at RenderBoxContainerDefaultsMixin.defaultHitTestChildren(box.dart:2874)
       at RenderCustomMultiChildLayoutBox.hitTestChildren(custom_layout.dart:420)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at RenderPhysicalModel.hitTest(proxy_box.dart:2030)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at RenderOffstage.hitTest(proxy_box.dart:3743)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderFollowerLayer.hitTestChildren.<fn>(proxy_box.dart:4914)
       at BoxHitTestResult.addWithRawTransform(box.dart:844)
       at BoxHitTestResult.addWithPaintTransform(box.dart:769)
       at RenderTransform.hitTestChildren(proxy_box.dart:2586)
       at RenderTransform.hitTest(proxy_box.dart:2580)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderFollowerLayer.hitTestChildren.<fn>(proxy_box.dart:4914)
       at BoxHitTestResult.addWithRawTransform(box.dart:844)
       at BoxHitTestResult.addWithPaintTransform(box.dart:769)
       at RenderTransform.hitTestChildren(proxy_box.dart:2586)
       at RenderTransform.hitTest(proxy_box.dart:2580)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderProxyBoxWithHitTestBehavior.hitTest(proxy_box.dart:183)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderFollowerLayer.hitTestChildren.<fn>(proxy_box.dart:4914)
       at BoxHitTestResult.addWithRawTransform(box.dart:844)
       at BoxHitTestResult.addWithPaintTransform(box.dart:769)
       at RenderTransform.hitTestChildren(proxy_box.dart:2586)
       at RenderTransform.hitTest(proxy_box.dart:2580)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderFollowerLayer.hitTestChildren.<fn>(proxy_box.dart:4914)
       at BoxHitTestResult.addWithRawTransform(box.dart:844)
       at BoxHitTestResult.addWithPaintTransform(box.dart:769)
       at RenderTransform.hitTestChildren(proxy_box.dart:2586)
       at RenderTransform.hitTest(proxy_box.dart:2580)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderProxyBoxWithHitTestBehavior.hitTest(proxy_box.dart:183)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at _RenderFocusTrap.hitTest(routes.dart:2217)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at RenderOffstage.hitTest(proxy_box.dart:3743)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderTheatre.hitTestChildren.<fn>(overlay.dart:826)
       at BoxHitTestResult.addWithPaintOffset(box.dart:805)
       at _RenderTheatre.hitTestChildren(overlay.dart:821)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at RenderAbsorbPointer.hitTest(proxy_box.dart:3854)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderProxyBoxWithHitTestBehavior.hitTest(proxy_box.dart:183)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at RenderView.hitTest(view.dart:186)
       at RendererBinding.hitTest(binding.dart:547)
       at GestureBinding._handlePointerEventImmediately(binding.dart:365)
       at GestureBinding.handlePointerEvent(binding.dart:357)
       at GestureBinding._flushPointerEventQueue(binding.dart:314)
       at GestureBinding._handlePointerDataPacket(binding.dart:295)
</code>```

Body:
I can see the following error on my console but no context is there to which class/view of mine is throwing it. It is only showing flutter framework classes. I am copying the text from the Firebase console below...

Can someone help me understand what is happening please so I can fix it?

It is happening on Samsung and LG devices only.

Error:

Fatal Exception: io.flutter.plugins.firebase.crashlytics.FlutterError: Null check operator used on a null value. Error thrown null.
       at TextPainter.getPositionForOffset(text_painter.dart:976)
       at RenderParagraph.hitTestChildren(paragraph.dart:581)
       at RenderBox.hitTest(box.dart:2511)
       at RenderBoxContainerDefaultsMixin.defaultHitTestChildren.<fn>(box.dart:2879)
       at BoxHitTestResult.addWithPaintOffset(box.dart:805)
       at RenderBoxContainerDefaultsMixin.defaultHitTestChildren(box.dart:2874)
       at RenderFlex.hitTestChildren(flex.dart:1082)
       at RenderBox.hitTest(box.dart:2511)
       at RenderShiftedBox.hitTestChildren.<fn>(shifted_box.dart:97)
       at BoxHitTestResult.addWithPaintOffset(box.dart:805)
       at RenderShiftedBox.hitTestChildren(shifted_box.dart:92)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderProxyBoxWithHitTestBehavior.hitTest(proxy_box.dart:183)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at RenderBoxContainerDefaultsMixin.defaultHitTestChildren.<fn>(box.dart:2879)
       at BoxHitTestResult.addWithPaintOffset(box.dart:805)
       at RenderBoxContainerDefaultsMixin.defaultHitTestChildren(box.dart:2874)
       at RenderFlex.hitTestChildren(flex.dart:1082)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at RenderShiftedBox.hitTestChildren.<fn>(shifted_box.dart:97)
       at BoxHitTestResult.addWithPaintOffset(box.dart:805)
       at RenderShiftedBox.hitTestChildren(shifted_box.dart:92)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderProxyBoxWithHitTestBehavior.hitTest(proxy_box.dart:183)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderProxyBoxWithHitTestBehavior.hitTest(proxy_box.dart:183)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at RenderSliverHelpers.hitTestBoxChild.<fn>(sliver.dart:1669)
       at BoxHitTestResult.addWithOutOfBandPosition(box.dart:902)
       at RenderSliverHelpers.hitTestBoxChild(sliver.dart:1666)
       at RenderSliverMultiBoxAdaptor.hitTestChildren(sliver_multi_box_adaptor.dart:564)
       at RenderSliver.hitTest(sliver.dart:1287)
       at SliverHitTestResult.addWithAxisOffset(sliver.dart:858)
       at RenderSliverEdgeInsetsPadding.hitTestChildren(sliver_padding.dart:231)
       at RenderSliver.hitTest(sliver.dart:1287)
       at RenderViewportBase.hitTestChildren.<fn>(viewport.dart:735)
       at BoxHitTestResult.addWithOutOfBandPosition(box.dart:902)
       at RenderViewportBase.hitTestChildren(viewport.dart:732)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at RenderOffstage.hitTest(proxy_box.dart:3743)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderProxyBoxWithHitTestBehavior.hitTest(proxy_box.dart:183)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderProxyBoxWithHitTestBehavior.hitTest(proxy_box.dart:183)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderProxyBoxWithHitTestBehavior.hitTest(proxy_box.dart:183)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderFollowerLayer.hitTestChildren.<fn>(proxy_box.dart:4914)
       at BoxHitTestResult.addWithRawTransform(box.dart:844)
       at BoxHitTestResult.addWithPaintTransform(box.dart:769)
       at RenderTransform.hitTestChildren(proxy_box.dart:2586)
       at RenderTransform.hitTest(proxy_box.dart:2580)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at RenderClipRect.hitTest(proxy_box.dart:1546)
       at RenderBoxContainerDefaultsMixin.defaultHitTestChildren.<fn>(box.dart:2879)
       at BoxHitTestResult.addWithPaintOffset(box.dart:805)
       at RenderBoxContainerDefaultsMixin.defaultHitTestChildren(box.dart:2874)
       at RenderCustomMultiChildLayoutBox.hitTestChildren(custom_layout.dart:420)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at RenderPhysicalModel.hitTest(proxy_box.dart:2030)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at RenderOffstage.hitTest(proxy_box.dart:3743)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderFollowerLayer.hitTestChildren.<fn>(proxy_box.dart:4914)
       at BoxHitTestResult.addWithRawTransform(box.dart:844)
       at BoxHitTestResult.addWithPaintTransform(box.dart:769)
       at RenderTransform.hitTestChildren(proxy_box.dart:2586)
       at RenderTransform.hitTest(proxy_box.dart:2580)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderFollowerLayer.hitTestChildren.<fn>(proxy_box.dart:4914)
       at BoxHitTestResult.addWithRawTransform(box.dart:844)
       at BoxHitTestResult.addWithPaintTransform(box.dart:769)
       at RenderTransform.hitTestChildren(proxy_box.dart:2586)
       at RenderTransform.hitTest(proxy_box.dart:2580)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderProxyBoxWithHitTestBehavior.hitTest(proxy_box.dart:183)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderFollowerLayer.hitTestChildren.<fn>(proxy_box.dart:4914)
       at BoxHitTestResult.addWithRawTransform(box.dart:844)
       at BoxHitTestResult.addWithPaintTransform(box.dart:769)
       at RenderTransform.hitTestChildren(proxy_box.dart:2586)
       at RenderTransform.hitTest(proxy_box.dart:2580)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderFollowerLayer.hitTestChildren.<fn>(proxy_box.dart:4914)
       at BoxHitTestResult.addWithRawTransform(box.dart:844)
       at BoxHitTestResult.addWithPaintTransform(box.dart:769)
       at RenderTransform.hitTestChildren(proxy_box.dart:2586)
       at RenderTransform.hitTest(proxy_box.dart:2580)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderProxyBoxWithHitTestBehavior.hitTest(proxy_box.dart:183)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at _RenderFocusTrap.hitTest(routes.dart:2217)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at RenderOffstage.hitTest(proxy_box.dart:3743)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderTheatre.hitTestChildren.<fn>(overlay.dart:826)
       at BoxHitTestResult.addWithPaintOffset(box.dart:805)
       at _RenderTheatre.hitTestChildren(overlay.dart:821)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at RenderAbsorbPointer.hitTest(proxy_box.dart:3854)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderProxyBoxWithHitTestBehavior.hitTest(proxy_box.dart:183)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at _RenderLayoutBuilder.hitTestChildren(layout_builder.dart:335)
       at RenderBox.hitTest(box.dart:2511)
       at RenderView.hitTest(view.dart:186)
       at RendererBinding.hitTest(binding.dart:547)
       at GestureBinding._handlePointerEventImmediately(binding.dart:365)
       at GestureBinding.handlePointerEvent(binding.dart:357)
       at GestureBinding._flushPointerEventQueue(binding.dart:314)
       at GestureBinding._handlePointerDataPacket(binding.dart:295)


问:
setTimeout() only working intermittently in my React/Gatsby application...?
I've got an email sign-up modal that I am supressing until after a required OneTrust cookie banner is closed. I'm using a MutationObserver to watch the banner, and when the 'display' attribute changes to 'none', I allow the modal component to render via a state change.

I've provided the code below. Any help would be greatly appreciated:

```<code>const ModalBase: FC<ModalBaseProps> = props => {
  const { components: C, ...rest } = props;

  const [isCookieBannerPresent, setIsCookieBannerPresent] = useState<boolean>(true);

  useEffect(() => {
    const cookieBanner = document.getElementById('onetrust-banner-sdk');
    if (cookieBanner?.style.display !== 'none') {
      console.log('cookie banner is present');
    }
    // Select the node that will be observed for mutations
    const targetNode = cookieBanner;

    // Options for the observer (which mutations to observe)
    const config = { attributes: true, attributeFilter: ['style'], childList: false, subtree: false };

    // Callback function to execute when mutations are observed
    // @ts-ignore
    const callback = function (mutationsList: any, observer) {
      // Use traditional 'for loops' for IE 11
      for (const mutation of mutationsList) {
        var newIndex = mutation.target.style.display;
        if (newIndex == 'none') {
          console.log('cookie banner is hidden');
          setTimeout(() => {
            setIsCookieBannerPresent(false);
            console.log('cookie banner is hidden');
          }, 3000);
        }
      }
    };

    // Create an observer instance linked to the callback function
    const observer = targetNode && new MutationObserver(callback);

    // @ts-ignore
    targetNode && observer.observe(targetNode, config);

  }, []);

  return isCookieBannerPresent ? null : (
    <C.Wrapper {...rest}>
      <C.Overlay {...rest} />
      <C.Modal {...rest}>
        <C.Header {...rest}>
          <C.CloseButton {...rest} />
        </C.Header>
        <C.ModalContent />
      </C.Modal>
    </C.Wrapper>
  );
};
</code>```

I've added a setTimeout() to wait a few seconds after closing the banner, but for some reason it only seemed to do so every few refreshes (I specifically used an incognito window/cleared the cookies to test this). In most cases, it simply never displays.

I should mention that this delay works without issue on a local dev server, but when I push to a staging ENV, that's when the inconsistent behavior begins.

I've tried watching for ANY attribute change on the target element, but that simply starts the 3000ms countdown on page load.

I've tried using a custom useTimeout() hook that I found online, but I'm running into all sorts of conflicts trying to run it inside of the MutationObserver's callback function.

Body:
I've got an email sign-up modal that I am supressing until after a required OneTrust cookie banner is closed. I'm using a MutationObserver to watch the banner, and when the 'display' attribute changes to 'none', I allow the modal component to render via a state change.

I've provided the code below. Any help would be greatly appreciated:

const ModalBase: FC<ModalBaseProps> = props => {
  const { components: C, ...rest } = props;

  const [isCookieBannerPresent, setIsCookieBannerPresent] = useState<boolean>(true);

  useEffect(() => {
    const cookieBanner = document.getElementById('onetrust-banner-sdk');
    if (cookieBanner?.style.display !== 'none') {
      console.log('cookie banner is present');
    }
    // Select the node that will be observed for mutations
    const targetNode = cookieBanner;

    // Options for the observer (which mutations to observe)
    const config = { attributes: true, attributeFilter: ['style'], childList: false, subtree: false };

    // Callback function to execute when mutations are observed
    // @ts-ignore
    const callback = function (mutationsList: any, observer) {
      // Use traditional 'for loops' for IE 11
      for (const mutation of mutationsList) {
        var newIndex = mutation.target.style.display;
        if (newIndex == 'none') {
          console.log('cookie banner is hidden');
          setTimeout(() => {
            setIsCookieBannerPresent(false);
            console.log('cookie banner is hidden');
          }, 3000);
        }
      }
    };

    // Create an observer instance linked to the callback function
    const observer = targetNode && new MutationObserver(callback);

    // @ts-ignore
    targetNode && observer.observe(targetNode, config);

  }, []);

  return isCookieBannerPresent ? null : (
    <C.Wrapper {...rest}>
      <C.Overlay {...rest} />
      <C.Modal {...rest}>
        <C.Header {...rest}>
          <C.CloseButton {...rest} />
        </C.Header>
        <C.ModalContent />
      </C.Modal>
    </C.Wrapper>
  );
};

I've added a setTimeout() to wait a few seconds after closing the banner, but for some reason it only seemed to do so every few refreshes (I specifically used an incognito window/cleared the cookies to test this). In most cases, it simply never displays.

I should mention that this delay works without issue on a local dev server, but when I push to a staging ENV, that's when the inconsistent behavior begins.

I've tried watching for ANY attribute change on the target element, but that simply starts the 3000ms countdown on page load.

I've tried using a custom useTimeout() hook that I found online, but I'm running into all sorts of conflicts trying to run it inside of the MutationObserver's callback function.


问:
Using a custom model for Django Admin
I have a custom user model, which an admin model inherits:

```<code>class User(AbstractBaseUser, PermissionsMixin):
    ...
class Staff(User):
    is_staff = models.BooleanField(
        _("staff status"),
        default=True,
        help_text=_("Designates whether the user is staff"),
    )
...

class Admin(Staff):
    is_admin = models.BooleanField(
        _("staff status"),
        default=True,
        help_text=_("Designates whether the user can log into this admin site."),
    )
...

</code>```

As well as a custom backend for authorization

```<code>class AdminBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        if username is None:
            username = kwargs.get(Admin.USERNAME_FIELD)
        if username is None or password is None:
            return
        try:
            user = Admin._default_manager.get_by_natural_key(username)
        except Admin.DoesNotExist:
            # Run the default password hasher once to reduce the timing
            # difference between an existing and a nonexistent user (#20760).
            Admin().set_password(password)
        else:
            if user.check_password(password) and self.user_can_authenticate(user):
                return user

...
</code>```

However, I am unable to log in due to has_permission in admin/sites.py

Is there a way to avoid registering a custom site, as that will increase complexity?

Title: Using a custom model for Django Admin

Body:
I have a custom user model, which an admin model inherits:

class User(AbstractBaseUser, PermissionsMixin):
    ...
class Staff(User):
    is_staff = models.BooleanField(
        _("staff status"),
        default=True,
        help_text=_("Designates whether the user is staff"),
    )
...

class Admin(Staff):
    is_admin = models.BooleanField(
        _("staff status"),
        default=True,
        help_text=_("Designates whether the user can log into this admin site."),
    )
...

As well as a custom backend for authorization

class AdminBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        if username is None:
            username = kwargs.get(Admin.USERNAME_FIELD)
        if username is None or password is None:
            return
        try:
            user = Admin._default_manager.get_by_natural_key(username)
        except Admin.DoesNotExist:
            # Run the default password hasher once to reduce the timing
            # difference between an existing and a nonexistent user (#20760).
            Admin().set_password(password)
        else:
            if user.check_password(password) and self.user_can_authenticate(user):
                return user

...

However, I am unable to log in due to has_permission in admin/sites.py

Is there a way to avoid registering a custom site, as that will increase complexity?


问:
Convolutional Neural Network keeps predicting the same class, are there any conventional problems that it may have?
The programs supposed to train on images of ten fruits and learn to classify them. For the xtest data set it does just fine, with. perfect accuracy but when it comes to me handing it 1 random image to predict, it keeps guessing avacado.

```<code>def sorted_correctly(add = list):
    try:
        add.remove(".DS_Store")
    except:
        pass
    finally:
        convert = lambda text: int(text) if text.isdigit() else text
        aplhanum_key = lambda key: [convert(c) for c in re.split("([0-9]+)",key)]
        return sorted(add ,key=aplhanum_key)

names = ["apple","avocado","banana","cherry","kiwi","mango","orange","pineapple","strawberries","watermelon"]
num_classes = len(names)

def create_data(Dir):
    global names
    img_data_list = []
    fruits = sorted_correctly(os.listdir(Dir))
    labels = []
    unexpected = []
    for fruit in fruits:
        img_list = sorted_correctly(os.listdir(Dir + "/" + fruit))
        for img in img_list:
            try:
                input_img = cv2.imread(Dir + "/" +  fruit + "/" + img)
                input_img_resize = cv2.resize(input_img,(IMG_COLS,IMG_ROWS))
            except Exception as e:
                unexpected.append(img)
            else:
                img_data_list.append(input_img_resize)
                labels.append(names.index(fruit))

    img_data = np.array(img_data_list)
    img_data = img_data.astype('float32')
    img_data /= 255
    labels = np.ones((len(img_data)),dtype='int64') #delete if problems arise
    y = np_utils.to_categorical(labels,len(names))
    return img_data,y

def create_prediction_data(Dir):
    img_list = sorted_correctly(os.listdir(Dir))
    img_data_list = []
    for image in img_list:
        try:
            input_img = cv2.imread(Dir +"/" + image)
            input_img_resize = cv2.resize(input_img,(IMG_COLS,IMG_ROWS))
        except:
            pass
        else:
            img_data_list.append(input_img_resize)
    img_data = np.array(img_data_list)
    imgs = img_data
    img_data = img_data.astype("float32")
    img_data /= 255
    return img_data,imgs

def randomize(x,y):
    temp = list(zip(x,y))
    shuffle(temp)
    x,y = zip(*temp)
    return x,y

def unison_shuffled_copies(a, b):
    assert len(a) == len(b)
    p = np.random.permutation(len(a))
    return a[p], b[p]
</code>```

create_data goes through a local directory and creates numpy array, create_prediction_data has a similar function.

```<code>print("Train:")
print(x_train.shape)
print("Test:")
print(x_test.shape)
model = Sequential()
model.add(Conv2D(32,(3,3),activation='relu',input_shape=(128,128,3)))
model.add(MaxPooling2D((2,2)))
model.add(Conv2D(32,(3,3),activation="relu"))
model.add(MaxPooling2D((2,2)))
model.add(Conv2D(64,(3,3),activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Flatten())
model.add(Dense(128,activation="relu"))
model.add(Dropout(0.5))
model.add(Dense(len(names),activation="softmax"))

model.compile(optimizer='adadelta',
              loss='categorical_crossentropy', #https://stats.stackexchange.com/questions/326065/cross-entropy-vs-sparse-cross-entropy-when-to-use-one-over-the-other
              metrics=['accuracy'])
history = model.fit(x_train,y_train,epochs=5,batch_size=8,validation_data=(x_test,y_test))

loss_train = history.history["loss"]
loss_val = history.history["val_loss"]

score = model.evaluate([x_test],y_test,batch_size=32)
print("Evaluated.")
print("Test lost:", score[0])
print("Test accuracy:", score[1])
prediction_images,m = create_prediction_data(PREDICTION_DIRECTION)
for i in range(len(prediction_images)):
    img = Image.fromarray(m[i],"RGB")
    img.show()
    img = prediction_images[i]
    img = np.reshape(img,(1,128,128,3))
    prediction = np.argmax(model.predict(img))
    print(names[prediction])
</code>```

Test accuracy is 1.

I've tried arbitrary pictures like a blank screen but it keeps predicting avocados. I've noticed that when I transform the pictures to an array and use the arrays to show them, they slightly turn bluish, may that be it? The number the pictures for each fruit is the same in x_train.

Also, img_data = img_data.astype('float32') if I show the image, it turns completely unrecognizable, may that be a problem? This is my first CNN.

Body:
The programs supposed to train on images of ten fruits and learn to classify them. For the xtest data set it does just fine, with. perfect accuracy but when it comes to me handing it 1 random image to predict, it keeps guessing avacado.

def sorted_correctly(add = list):
    try:
        add.remove(".DS_Store")
    except:
        pass
    finally:
        convert = lambda text: int(text) if text.isdigit() else text
        aplhanum_key = lambda key: [convert(c) for c in re.split("([0-9]+)",key)]
        return sorted(add ,key=aplhanum_key)

names = ["apple","avocado","banana","cherry","kiwi","mango","orange","pineapple","strawberries","watermelon"]
num_classes = len(names)

def create_data(Dir):
    global names
    img_data_list = []
    fruits = sorted_correctly(os.listdir(Dir))
    labels = []
    unexpected = []
    for fruit in fruits:
        img_list = sorted_correctly(os.listdir(Dir + "/" + fruit))
        for img in img_list:
            try:
                input_img = cv2.imread(Dir + "/" +  fruit + "/" + img)
                input_img_resize = cv2.resize(input_img,(IMG_COLS,IMG_ROWS))
            except Exception as e:
                unexpected.append(img)
            else:
                img_data_list.append(input_img_resize)
                labels.append(names.index(fruit))

    img_data = np.array(img_data_list)
    img_data = img_data.astype('float32')
    img_data /= 255
    labels = np.ones((len(img_data)),dtype='int64') #delete if problems arise
    y = np_utils.to_categorical(labels,len(names))
    return img_data,y

def create_prediction_data(Dir):
    img_list = sorted_correctly(os.listdir(Dir))
    img_data_list = []
    for image in img_list:
        try:
            input_img = cv2.imread(Dir +"/" + image)
            input_img_resize = cv2.resize(input_img,(IMG_COLS,IMG_ROWS))
        except:
            pass
        else:
            img_data_list.append(input_img_resize)
    img_data = np.array(img_data_list)
    imgs = img_data
    img_data = img_data.astype("float32")
    img_data /= 255
    return img_data,imgs

def randomize(x,y):
    temp = list(zip(x,y))
    shuffle(temp)
    x,y = zip(*temp)
    return x,y

def unison_shuffled_copies(a, b):
    assert len(a) == len(b)
    p = np.random.permutation(len(a))
    return a[p], b[p]

create_data goes through a local directory and creates numpy array, create_prediction_data has a similar function.

print("Train:")
print(x_train.shape)
print("Test:")
print(x_test.shape)
model = Sequential()
model.add(Conv2D(32,(3,3),activation='relu',input_shape=(128,128,3)))
model.add(MaxPooling2D((2,2)))
model.add(Conv2D(32,(3,3),activation="relu"))
model.add(MaxPooling2D((2,2)))
model.add(Conv2D(64,(3,3),activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Flatten())
model.add(Dense(128,activation="relu"))
model.add(Dropout(0.5))
model.add(Dense(len(names),activation="softmax"))

model.compile(optimizer='adadelta',
              loss='categorical_crossentropy', #https://stats.stackexchange.com/questions/326065/cross-entropy-vs-sparse-cross-entropy-when-to-use-one-over-the-other
              metrics=['accuracy'])
history = model.fit(x_train,y_train,epochs=5,batch_size=8,validation_data=(x_test,y_test))

loss_train = history.history["loss"]
loss_val = history.history["val_loss"]

score = model.evaluate([x_test],y_test,batch_size=32)
print("Evaluated.")
print("Test lost:", score[0])
print("Test accuracy:", score[1])
prediction_images,m = create_prediction_data(PREDICTION_DIRECTION)
for i in range(len(prediction_images)):
    img = Image.fromarray(m[i],"RGB")
    img.show()
    img = prediction_images[i]
    img = np.reshape(img,(1,128,128,3))
    prediction = np.argmax(model.predict(img))
    print(names[prediction])

Test accuracy is 1.

I've tried arbitrary pictures like a blank screen but it keeps predicting avocados. I've noticed that when I transform the pictures to an array and use the arrays to show them, they slightly turn bluish, may that be it? The number the pictures for each fruit is the same in x_train.

Also, img_data = img_data.astype('float32') if I show the image, it turns completely unrecognizable, may that be a problem? This is my first CNN.


问:
how would i make this class for polygons faster
im currently working a 3d engine in python but my biggest issue is speed. while doing some profiling i found that texturedQuadronFunc.drawQuad() takes about 5s to render and gives 0fps in the renderer when givin a 500x500 surface.

requirements:

```<code>import pygame
</code>```

func drawQuad():

```<code>drawQuad(
    <surface to draw on>,
    <pair of four 2d cords>,
    <surface> )
</code>```

is there any possible way to speed this proccess up, if so can i get a solution

thanks in advance

```<code>class texturedQuadronFunc:
    def lerp( p1, p2, f ):
        return p1 + f * (p2 - p1)

    def lerp2d( p1, p2, f ):
        return tuple( texturedQuadronFunc.lerp( p1[i], p2[i], f ) for i in range(2) )

    def drawQuad(surface, quad, img ):

        points = dict()

        for i in range( img.get_size()[1]+1 ):
            b = texturedQuadronFunc.lerp2d( quad[1], quad[2], i/img.get_size()[1] )
            c = texturedQuadronFunc.lerp2d( quad[0], quad[3], i/img.get_size()[1] )
            for u in range( img.get_size()[0]+1 ):
                a = texturedQuadronFunc.lerp2d( c, b, u/img.get_size()[0] )
                points[ (u,i) ] = a

        for x in range( img.get_size()[0] ):
            for y in range( img.get_size()[1] ):
                pygame.draw.polygon(surface,img.get_at((x,y)),[ points[ (a,b) ] for a, b in [ (x,y), (x,y+1), (x+1,y+1), (x+1,y) ] ] )
</code>```

Body:
im currently working a 3d engine in python but my biggest issue is speed. while doing some profiling i found that texturedQuadronFunc.drawQuad() takes about 5s to render and gives 0fps in the renderer when givin a 500x500 surface.

requirements:

import pygame

func drawQuad():

drawQuad(
    <surface to draw on>,
    <pair of four 2d cords>,
    <surface> )

is there any possible way to speed this proccess up, if so can i get a solution

thanks in advance

class texturedQuadronFunc:
    def lerp( p1, p2, f ):
        return p1 + f * (p2 - p1)

    def lerp2d( p1, p2, f ):
        return tuple( texturedQuadronFunc.lerp( p1[i], p2[i], f ) for i in range(2) )

    def drawQuad(surface, quad, img ):

        points = dict()

        for i in range( img.get_size()[1]+1 ):
            b = texturedQuadronFunc.lerp2d( quad[1], quad[2], i/img.get_size()[1] )
            c = texturedQuadronFunc.lerp2d( quad[0], quad[3], i/img.get_size()[1] )
            for u in range( img.get_size()[0]+1 ):
                a = texturedQuadronFunc.lerp2d( c, b, u/img.get_size()[0] )
                points[ (u,i) ] = a

        for x in range( img.get_size()[0] ):
            for y in range( img.get_size()[1] ):
                pygame.draw.polygon(surface,img.get_at((x,y)),[ points[ (a,b) ] for a, b in [ (x,y), (x,y+1), (x+1,y+1), (x+1,y) ] ] )


问:
AddEventListener updating value for global scope
Introduction

I have select box for user to choose how much data he want to see in visualisation , this data is array of possitive unique numbers randomly choosen. I need to change this data length to put it into d3.js to drawVisualistion there

Problem

When i select some option from select box my application start laggy that i need to close the tab. This is the code i used.

```<code>import generateData from "./generateData";

const dataSizeSelect = document.getElementById(
  "data-size"
) as HTMLSelectElement;
let data:number[] = [];

dataSizeSelect.addEventListener("change", () => {
  const dataSize = parseInt(dataSizeSelect.value, 10);
  data = generateData(dataSize)
});

console.log(data);
export {};
</code>```

Then i tried in diffrent method but only gives zero , after some reading about how it is done in addEventListener function i read that it always be zero becouse code i have is asonchronus:

```<code>import generateData from "./generateData";

const dataSizeSelect = document.getElementById(
  "data-size"
) as HTMLSelectElement;
let dataSize: number = 0;

dataSizeSelect.addEventListener("change", () => {
  dataSize = parseInt(dataSizeSelect.value, 10);
});

const data = generateData(dataSize);
export {};
</code>```

And this is the generateData func:

```<code>const generateData = (numPoints: number): number[] => {
  const data = new Set();
  while (data.size < numPoints) {
    const randomNumber = Math.floor(Math.random() * 100);
    if (randomNumber > 0) {
      data.add(randomNumber);
    }
  }
  return [...data] as number[];
};

export default generateData;
</code>```

Body:
Introduction

I have select box for user to choose how much data he want to see in visualisation , this data is array of possitive unique numbers randomly choosen. I need to change this data length to put it into d3.js to drawVisualistion there

Problem

When i select some option from select box my application start laggy that i need to close the tab. This is the code i used.

import generateData from "./generateData";

const dataSizeSelect = document.getElementById(
  "data-size"
) as HTMLSelectElement;
let data:number[] = [];

dataSizeSelect.addEventListener("change", () => {
  const dataSize = parseInt(dataSizeSelect.value, 10);
  data = generateData(dataSize)
});

console.log(data);
export {};

Then i tried in diffrent method but only gives zero , after some reading about how it is done in addEventListener function i read that it always be zero becouse code i have is asonchronus:

import generateData from "./generateData";

const dataSizeSelect = document.getElementById(
  "data-size"
) as HTMLSelectElement;
let dataSize: number = 0;

dataSizeSelect.addEventListener("change", () => {
  dataSize = parseInt(dataSizeSelect.value, 10);
});

const data = generateData(dataSize);
export {};

And this is the generateData func:

const generateData = (numPoints: number): number[] => {
  const data = new Set();
  while (data.size < numPoints) {
    const randomNumber = Math.floor(Math.random() * 100);
    if (randomNumber > 0) {
      data.add(randomNumber);
    }
  }
  return [...data] as number[];
};

export default generateData;


问:
Excel internal expression of fractional format numbers
I have been trying to apply some conditional formatting to numbers which are formatted externally as fractions with a mask ???/???. In trying to test whether the fraction has a numerator of 1, I apply the formula = =MOD(1/G62,0)<>0, which divides 1 by the fraction itself, which ought to divide with no remainder if it has a numerator of 1, and return 0. If it returns something else then it has a numerator other than 1.

The rule is satisfied when it should not be. To test what is going on, I deconstruct the formula.
The fraction 1/28 is divided into 1 to give 28 and this is correctly displayed. I then populate another cell using the formula =MOD(H62,1) to 28 and it gives 0, as it should. I do the same thing for 1/14 and the result is 1. In other words the MOD of 14, 1 is 1! When I look at the decimal representation of the 2 fractions( I imagine the fractions are actually the representations of the decimal numbers, which themselves will be binary or hex numbers internally), I see the following.

1/28  0.0357142857142856
1/14  0.0714285714285716

When the decimal for 1/28 is subtracted from the decimal for 1/14, the result is 0.035714285714286.
As 1/28 can probably never be accurately represented in decimal, it looks like some rounding down has taken place. Most probably when MOD is applied to the decimal representation of 1/28 with 1, that decimal representation of 1/14 does not divide equally into 1, and this discrepancy is disclosed by the subtraction above.

I am using excel 2016. Maybe this is no longer a problem.

What I am trying to do is test to see if the lowest numerator of a fractional number is 1. Perhaps there is another way to do this in Excel. If so, let me know.


问:
How to specify a column field in a calculated field formula when you have the same value evaluated as a count and a sum?
I am using a pivot table to summarize our status of completion of a project. The first value of the pivot table gives me a count of the entries in the spreadsheet column that have a value greater than 0. The next value of the pivot table gives me a count of the total estimated quantities from the spreadsheet. The third value gives me the sum of the entries from the same column of the spreadsheet that the first value uses in the pivot table. The final value of the pivot table is a sum of the total estimated quantities from the same column from the spreadsheet the second values uses for the pivot table.
My current working formula will only evaluate the SUM columns in the pivot table and is the following:

```<code>=iferror('Quantities Complete'/'Total Est Quantities',0)
</code>```

This gives me a percent complete based on the SUM of those two columns from the spreadsheet. These values can differ because the first is a real value and the second is an estimated value. What I want is the below formula which I will put how the data is summarized in parenthesis for simplicity of understanding.

```<code>=if('Quantities Complete'(COUNT)='Total Est Quantities'(COUNT),1,iferror('Quantities Complete'(SUM)/'Total Est Quantities'(SUM),0))
</code>```

This formula would allow me to evaluate if the count of complete items matches the total estimated items, if so the calculated field value is 100% regardless of actual sum values. Otherwise, it gives a percent complete based on sum value which is more accurate because each item can have vastly different values.
How can I refer to the 2 different uses of the columns in a calculated field formula?

I have tried the renaming the column headers to 'Items Complete' and 'Item Values' but the formula does not accept those and gave a parse error. I have tried using the "COUNTA of" or "SUM of" prefix for the column fields. I also tried typing the name as shown when I hover over the value field in the edit window which I tried in these methods: 'Quantities Complete' (Items Complete) and 'Quantities Complete (Items Complete)'. All of these yielded a parse error. I can't share my spreadsheet due to confidentiality requirements, but all I need to know is how to refer to the two different column headers that have the same name from what I can tell.

Body:
I am using a pivot table to summarize our status of completion of a project. The first value of the pivot table gives me a count of the entries in the spreadsheet column that have a value greater than 0. The next value of the pivot table gives me a count of the total estimated quantities from the spreadsheet. The third value gives me the sum of the entries from the same column of the spreadsheet that the first value uses in the pivot table. The final value of the pivot table is a sum of the total estimated quantities from the same column from the spreadsheet the second values uses for the pivot table.
My current working formula will only evaluate the SUM columns in the pivot table and is the following:

=iferror('Quantities Complete'/'Total Est Quantities',0)

This gives me a percent complete based on the SUM of those two columns from the spreadsheet. These values can differ because the first is a real value and the second is an estimated value. What I want is the below formula which I will put how the data is summarized in parenthesis for simplicity of understanding.

=if('Quantities Complete'(COUNT)='Total Est Quantities'(COUNT),1,iferror('Quantities Complete'(SUM)/'Total Est Quantities'(SUM),0))

This formula would allow me to evaluate if the count of complete items matches the total estimated items, if so the calculated field value is 100% regardless of actual sum values. Otherwise, it gives a percent complete based on sum value which is more accurate because each item can have vastly different values.
How can I refer to the 2 different uses of the columns in a calculated field formula?

I have tried the renaming the column headers to 'Items Complete' and 'Item Values' but the formula does not accept those and gave a parse error. I have tried using the "COUNTA of" or "SUM of" prefix for the column fields. I also tried typing the name as shown when I hover over the value field in the edit window which I tried in these methods: 'Quantities Complete' (Items Complete) and 'Quantities Complete (Items Complete)'. All of these yielded a parse error. I can't share my spreadsheet due to confidentiality requirements, but all I need to know is how to refer to the two different column headers that have the same name from what I can tell.


问:
Is it possible to make a function return another function in React Native?
For example, im in this code that at some point an onPress calls a function:
onpress={function1}  and i function1 has to work like this:

```<code>function function1(){
    if(x){
        return Alert.alert("Alert!");
    }
    else{
        return function2;
    }
}
</code>```

So basically when i press it, if the condition is followed it should show the alert but if its not, it should run the other function.

Is it possible? Ive been trying to do this but i couldnt find a way.

Body:
For example, im in this code that at some point an onPress calls a function:
onpress={function1}  and i function1 has to work like this:

function function1(){
    if(x){
        return Alert.alert("Alert!");
    }
    else{
        return function2;
    }
}

So basically when i press it, if the condition is followed it should show the alert but if its not, it should run the other function.

Is it possible? Ive been trying to do this but i couldnt find a way.


问:
R shiny: put output text in UI after analysis finishes
I made an R shiny app where the user enters some parameters and clicks a button (input$DoAnalysis) to analyse the uploaded data. The analysis can take a while, and after it's finished I'd like to put some summary results as text in the UI. How can I do this?

I think the answer is simple, but I can't get it working. Setting a reactive value within observeEvent(input$DoAnalysis, ... ) and using that to trigger the text doesn't seem to work.


问:
I've written code that takes geojson array and translates it into Vector3, but it isn't showing up
The plan is for it to draw borders using GeoJSON coords. Also when I write coordinates directly into the same file it works normally and I've noticed that my fbih variable doesn't get the fbih: THREE.Vector3 when hovered over. I'm using ViteJS + ThreeJS, Here's the code:

```<code>import './style.css'

import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { Vector3 } from 'three';

const scene = new THREE.Scene();

const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

const renderer = new THREE.WebGLRenderer({
  canvas: document.querySelector("#bg")
});

renderer.setPixelRatio (window.devicePixelRatio);
renderer.setSize( window.innerWidth, window.innerHeight);
camera.position.setZ(20);
renderer.render(scene,camera);

const teksturazemlje = new THREE.TextureLoader().load('slike/zemlja.png')

const zemlja = new THREE.Mesh (
  new THREE.SphereGeometry(16, 500, 500 ),
  new THREE.MeshStandardMaterial({
    map:teksturazemlje,
  })
);
scene.add(zemlja)

function koordinate([lon,lat]){
  var phi   = (90-lat)*(Math.PI/180);
  var theta = (lon+180)*(Math.PI/180);

  var x = -((16) * Math.sin(phi)*Math.cos(theta));
  var z = ((16) * Math.sin(phi)*Math.sin(theta));
  var y = ((16) * Math.cos(phi));

  return new THREE.Vector3(x,y,z)
}

const boja = new THREE.MeshBasicMaterial({
    color: 0xff00cc,
  side : THREE.DoubleSide,
});

var fbih = [];

fetch ('granice/bih.json')
  .then (res => res.json())
  .then (data => {
    for (let element of data.features[0].geometry.coordinates[0][0]) {
      fbih.push(koordinate(element))
    }
});

console.log(fbih)

const linije = new THREE.BufferGeometry().setFromPoints(fbih)

const line = new THREE.Line(linije,boja)

scene.add(line);

const ambientlight= new THREE.AmbientLight(0xffffff);
scene.add(ambientlight)

const controls = new OrbitControls(camera, renderer.domElement);

function animate(){
  requestAnimationFrame(animate);
  controls.update();

  renderer.render (scene, camera);
}

controls.enableDamping = true;
controls.dampingFactor = 0.04;
controls.rotateSpeed = 0.07;
controls.maxDistance = 20;
controls.minDistance = 16.5;
controls.enablePan = false;
controls.zoomSpeed = 0.30;

animate()
</code>```

It displays Vector3 array in console.log but it isn't displayed through BufferGeometry. Sorry if there are grammatical errors, English isn't my first language.

Body:
The plan is for it to draw borders using GeoJSON coords. Also when I write coordinates directly into the same file it works normally and I've noticed that my fbih variable doesn't get the fbih: THREE.Vector3 when hovered over. I'm using ViteJS + ThreeJS, Here's the code:

import './style.css'

import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { Vector3 } from 'three';

const scene = new THREE.Scene();

const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

const renderer = new THREE.WebGLRenderer({
  canvas: document.querySelector("#bg")
});

renderer.setPixelRatio (window.devicePixelRatio);
renderer.setSize( window.innerWidth, window.innerHeight);
camera.position.setZ(20);
renderer.render(scene,camera);

const teksturazemlje = new THREE.TextureLoader().load('slike/zemlja.png')

const zemlja = new THREE.Mesh (
  new THREE.SphereGeometry(16, 500, 500 ),
  new THREE.MeshStandardMaterial({
    map:teksturazemlje,
  })
);
scene.add(zemlja)

function koordinate([lon,lat]){
  var phi   = (90-lat)*(Math.PI/180);
  var theta = (lon+180)*(Math.PI/180);

  var x = -((16) * Math.sin(phi)*Math.cos(theta));
  var z = ((16) * Math.sin(phi)*Math.sin(theta));
  var y = ((16) * Math.cos(phi));

  return new THREE.Vector3(x,y,z)
}

const boja = new THREE.MeshBasicMaterial({
    color: 0xff00cc,
  side : THREE.DoubleSide,
});

var fbih = [];

fetch ('granice/bih.json')
  .then (res => res.json())
  .then (data => {
    for (let element of data.features[0].geometry.coordinates[0][0]) {
      fbih.push(koordinate(element))
    }
});

console.log(fbih)

const linije = new THREE.BufferGeometry().setFromPoints(fbih)

const line = new THREE.Line(linije,boja)

scene.add(line);

const ambientlight= new THREE.AmbientLight(0xffffff);
scene.add(ambientlight)

const controls = new OrbitControls(camera, renderer.domElement);

function animate(){
  requestAnimationFrame(animate);
  controls.update();

  renderer.render (scene, camera);
}

controls.enableDamping = true;
controls.dampingFactor = 0.04;
controls.rotateSpeed = 0.07;
controls.maxDistance = 20;
controls.minDistance = 16.5;
controls.enablePan = false;
controls.zoomSpeed = 0.30;

animate()

It displays Vector3 array in console.log but it isn't displayed through BufferGeometry. Sorry if there are grammatical errors, English isn't my first language.


问:
Integration and data upload - MuleSoft CloudHub to Tableau Server
I am using MuleSoft CloudHub with Runtime v4.4 to upload CSV data to Tableau Server. The documentation page https://docs.mulesoft.com/tableau-specialist-connector/1.1/ confirms that its not possible to use Hyper Configuration and its operations in CloudHub because CloudHub does not allow executing external code due to security reasons. That is why I am trying to use REST configurations and it's available operations.

With all my attempts, I am able to connect to Tableau server and successfully perform simple operations like Initial file upload, Query project, Append to file upload, etc. But, these operations does not help to publish my CSV content to Tableau. Publish workbook operation also requires file content in *.twbx format, and I am not sure how to convert CSV/JSON/XML to TWBX content type.

I have referred some websites and MuleSoft technical videos where HTTPS connection can be used to upload data to Tableau but those examples are using *.hyper file from classpath.

So, basically I am stuck at 2 different paths:

How can I transform CSV content to hyper file content in Mule flow. If this transform is possible then I can use HTTPS connection to Tableau and upload my data.

Using MuleSoft Tableau connector v1.1 and with REST configurations, is it possible to upload data to Tableau?

If there is any other solution, then I am happy to change my implementation strategy. Please can somebody guide me to correct direction?


问:
How do I pass a NULL into SQL server via an Access VBA statement?
Both Table A and Table B have a field called [Expiration Date] where the data type is datetime and allow NULLs. My goal is to read Table A, get the value of this field, and write it to Table B.

I read the field value likes this, this part is fine:

```<code>strSQL = "SELECT a.*, b.[Model Number], b.CleaningCode, b.[Type] " & _
            "FROM wReceiveLabel AS a " & _
            "LEFT OUTER JOIN [Item Master] AS b ON a.Part = b.[AP Part Number] " & _
            "WHERE a.Workstation = '" & UniqueID() & "' " & _
            "AND a.Received > 0"
rs.Open strSQL, con, adOpenStatic, adLockReadOnly
</code>```

Then, I try to write the value into Table B, but this doesn't work:

```<code>Dim dateExpirationDate As Variant
dateExpirationDate = rs![Expiration Date]

strSQL = "INSERT INTO [PO Receipts] ([Lot Number], [Date Received], [Part Number], [Rev], [Purchase Order], POLine, [Vendor Code], " & _
                  "[Total Received], [Sample ID Only], [Sample Level S], [Sample Level I], [Sample Level II], [Sample Level III], " & _
                  "[Accept Quantity], [Reject Quantity], Inspector, Remarks, [Type], PackList, FAI, [Expiration Date], [Heat Code]) VALUES (" & _
                  "'" & strLot & "', '" & [Receive Date] & "', '" & rs!Part & "', '" & rs!Rev & "', '" & rs!PurchaseOrder & "', '" & rs!Line & "', " & _
                  "'" & [Vendor Code] & "', " & rs!Received & ", " & Format(CInt(rs!IDOnly)) & ", " & rs!LevelS & ", " & _
                  rs!LevelI & ", " & rs!LevelII & ", " & rs!LevelIII & ", " & _
                  rs!Accepted & ", " & rs!Rejected & ", '" & [Inspector] & "', '" & rs!Remarks & "', '1', '" & [cboPL] & "', " & rs!FAI & ", " & dateExpirationDate & ", '" & rs![Heat Code] & "')"
con.Execute strSQL, , adCmdText + adExecuteNoRecords
</code>```

It gives an error that says Incorrect syntax near ','

Body:
Both Table A and Table B have a field called [Expiration Date] where the data type is datetime and allow NULLs. My goal is to read Table A, get the value of this field, and write it to Table B.

I read the field value likes this, this part is fine:

strSQL = "SELECT a.*, b.[Model Number], b.CleaningCode, b.[Type] " & _
            "FROM wReceiveLabel AS a " & _
            "LEFT OUTER JOIN [Item Master] AS b ON a.Part = b.[AP Part Number] " & _
            "WHERE a.Workstation = '" & UniqueID() & "' " & _
            "AND a.Received > 0"
rs.Open strSQL, con, adOpenStatic, adLockReadOnly

Then, I try to write the value into Table B, but this doesn't work:

Dim dateExpirationDate As Variant
dateExpirationDate = rs![Expiration Date]

strSQL = "INSERT INTO [PO Receipts] ([Lot Number], [Date Received], [Part Number], [Rev], [Purchase Order], POLine, [Vendor Code], " & _
                  "[Total Received], [Sample ID Only], [Sample Level S], [Sample Level I], [Sample Level II], [Sample Level III], " & _
                  "[Accept Quantity], [Reject Quantity], Inspector, Remarks, [Type], PackList, FAI, [Expiration Date], [Heat Code]) VALUES (" & _
                  "'" & strLot & "', '" & [Receive Date] & "', '" & rs!Part & "', '" & rs!Rev & "', '" & rs!PurchaseOrder & "', '" & rs!Line & "', " & _
                  "'" & [Vendor Code] & "', " & rs!Received & ", " & Format(CInt(rs!IDOnly)) & ", " & rs!LevelS & ", " & _
                  rs!LevelI & ", " & rs!LevelII & ", " & rs!LevelIII & ", " & _
                  rs!Accepted & ", " & rs!Rejected & ", '" & [Inspector] & "', '" & rs!Remarks & "', '1', '" & [cboPL] & "', " & rs!FAI & ", " & dateExpirationDate & ", '" & rs![Heat Code] & "')"
con.Execute strSQL, , adCmdText + adExecuteNoRecords

It gives an error that says Incorrect syntax near ','


问:
how to return the clone from github selection menu? vscode
that's how it was

that's how it is now

I thought it was connected to ssh - it turned out not to be

The web version works, but not on desktop.

Please help to return it as it was. I've been racking my brain all day. I think it's somewhere in the vscode settings, but I can't find it


问:
should a docker swarm manager be the strongest or the weakest machine?
i have a swarm with  5 machines. 1 vm on proxmox 16Gb and 4 cores allocated. and 4 pi’s which are doing some switching (as in relay on /off) stuff in house.
at first instinct i’d chose the strongest machine as manager, but that one should get all cpu heavy services and it’s probably going to get the most experimental development on it which ,might  lead to reboots . shouldn’t i let the weaker pi’s act as manager since they only get light tasks (like npm and mqtt)</p>


问:
IndexError: index 35 is out of bounds for axis 1 with size 10
Problem
I am working on a neural network in Python and had this error come up. Now I don't see any problems since it worked before with a different dataset. Now I get the following error:

...
File "e:\PWS Bart\initiate model.py", line 550, in forward
correct_confidences = y_pred_clipped[range(samples), y_true]
IndexError: index 35 is out of bounds for axis 1 with size 10

The code on line 550 is:

```<code>    # Forward pass
    def forward(self, y_pred, y_true):

        # Number of samples in a batch
        samples = len(y_pred)

        # Clip data to prevent division by 0
        # Clip both sides to not drag mean towards any value
        y_pred_clipped = np.clip(y_pred, 1e-7, 1 - 1e-7)

        # Probabilities for target values -
        # only if categorical labels
        if len(y_true.shape) == 1:
            correct_confidences = y_pred_clipped[
                range(samples),
                y_true
            ]

        # Mask values - only for one-hot encoded labels
        elif len(y_true.shape) == 2:
            correct_confidences = np.sum(
                y_pred_clipped * y_true,
                axis=1
            )

        # Losses
        negative_log_likelihoods = -np.log(correct_confidences)
        return negative_log_likelihoods
</code>```

Edit: The code on line 550 is the one that defines correct_confidences

The value of y_pred:

```<code>    [[0.09999657 0.10003116 0.09997115 ... 0.09980713 0.09992861 0.09994321]
     [0.10006691 0.10000683 0.10005932 ... 0.0998411  0.09988077 0.09978568]
     [0.09997768 0.10003725 0.09997757 ... 0.09985325 0.10000801 0.09984406]
     ...
     [0.09993309 0.10008678 0.10013765 ... 0.09980296 0.09991061 0.09999865]
     [0.09991049 0.09992879 0.09992588 ... 0.09985736 0.10001095 0.0999448 ]
     [0.10004579 0.10000289 0.10012186 ... 0.09978612 0.09996389 0.09980298]]
</code>```

The value of y_true:

```<code>[35  5 15 23  6 25 33  8 27  0  8 17 45 43 33  8 43 39 21 28 20 31 30  1
 45  9  3 36 35 44 30 30  6 32 12 41 46 11  7 41 29 46 23 46 20 12 31 31
 22 46  5 33  2 20  8  0  0 17  0  4 20 43 45 14 17 45 20 46 18  6  8 32
 41 27  4 28  8 33  8 22 32 10 23 15 43 46 43 45 23 37 30 10 21  6 42  4
  0 43 36 43  8 41 37 38  2  0 32 40  1 39  1 18  0 15 29 33  6  0 18 40
 45 32 23  2 44 32 10 14]
</code>```

The value of samples:
128

The value of y_true.shape:
(128,)

Question:
Is there someone here that knows how I would go about solving this?

Body:
Problem
I am working on a neural network in Python and had this error come up. Now I don't see any problems since it worked before with a different dataset. Now I get the following error:

...
File "e:\PWS Bart\initiate model.py", line 550, in forward
correct_confidences = y_pred_clipped[range(samples), y_true]
IndexError: index 35 is out of bounds for axis 1 with size 10

The code on line 550 is:

    # Forward pass
    def forward(self, y_pred, y_true):

        # Number of samples in a batch
        samples = len(y_pred)

        # Clip data to prevent division by 0
        # Clip both sides to not drag mean towards any value
        y_pred_clipped = np.clip(y_pred, 1e-7, 1 - 1e-7)

        # Probabilities for target values -
        # only if categorical labels
        if len(y_true.shape) == 1:
            correct_confidences = y_pred_clipped[
                range(samples),
                y_true
            ]

        # Mask values - only for one-hot encoded labels
        elif len(y_true.shape) == 2:
            correct_confidences = np.sum(
                y_pred_clipped * y_true,
                axis=1
            )

        # Losses
        negative_log_likelihoods = -np.log(correct_confidences)
        return negative_log_likelihoods

Edit: The code on line 550 is the one that defines correct_confidences

The value of y_pred:

    [[0.09999657 0.10003116 0.09997115 ... 0.09980713 0.09992861 0.09994321]
     [0.10006691 0.10000683 0.10005932 ... 0.0998411  0.09988077 0.09978568]
     [0.09997768 0.10003725 0.09997757 ... 0.09985325 0.10000801 0.09984406]
     ...
     [0.09993309 0.10008678 0.10013765 ... 0.09980296 0.09991061 0.09999865]
     [0.09991049 0.09992879 0.09992588 ... 0.09985736 0.10001095 0.0999448 ]
     [0.10004579 0.10000289 0.10012186 ... 0.09978612 0.09996389 0.09980298]]

The value of y_true:

[35  5 15 23  6 25 33  8 27  0  8 17 45 43 33  8 43 39 21 28 20 31 30  1
 45  9  3 36 35 44 30 30  6 32 12 41 46 11  7 41 29 46 23 46 20 12 31 31
 22 46  5 33  2 20  8  0  0 17  0  4 20 43 45 14 17 45 20 46 18  6  8 32
 41 27  4 28  8 33  8 22 32 10 23 15 43 46 43 45 23 37 30 10 21  6 42  4
  0 43 36 43  8 41 37 38  2  0 32 40  1 39  1 18  0 15 29 33  6  0 18 40
 45 32 23  2 44 32 10 14]

The value of samples:
128

The value of y_true.shape:
(128,)

Question:
Is there someone here that knows how I would go about solving this?


问:
Creating clock background using flutter
Guys i am creating a clock background app, a background and in the center of it a text showing the hour, you need to open the app the see the clock background but i want it to be displayed at the lockscreen of the phone always, i don't know how to display the clock at the lock screen of the phone, i searched but i didn't find yet a helpfull answer.

The question is how can i put this clock in the lock screen of the phone, whenever i open the phone will be displayed at first, any idea how to do it with flutter.

Title: Creating clock background using flutter


问:
How to resolve a type generic from the service collection based on the requesting type (similar to ILogger/Logger<TCategory>)?
Lets say I have

public interface IService { }

public interface IService<TCategory> : IService { }

public class Service<TCategory> : IService<TCategory> { }
```
<p>How do I get <code>ServiceCollection</code> to provide me <code>Service<MyClass></code> and <code>Service<OtherClass></code> when I resolve it like so?</p>
<pre class="lang-cs prettyprint-override"><code>public class MyClass
{
    public MyClass(IService service) => Service = service;

    IService Service { get; } // Should be set to Service<MyClass>
}

public class OtherClass
{
    public OtherClass(IService service) => Service = service;

    IService Service { get; } // Should be set to Service<OtherClass>
}
</code>```

I DO NOT want to register in the collection like so, such that it requires me to specify for the classes the specific type in the constructor.

serviceCollection.AddSingleton(typeof(IService<>), typeof(Service<>));

public class MyClass
{
    public MyClass(IService<MyClass> service) => Service = service;

    IService Service { get; }
}

public class OtherClass
{
    public OtherClass(IService<OtherClass> service) => Service = service;

    IService Service { get; }
}
```
<p>I do not want to have to redundantly restate the class I'm already within as part of the type in the constructor. I basically want it to work similar/same as <code>ILogger</code>/<code>Logger<TCategory></code></p>
<p>I was hoping to find an extension method that accepted a delegate of <code>Func<IServiceProvider, type, object></code>, but have had no luck.</p>
<p>EDIT:</p>
<p>I'll some additional context here to better illustrate. For instance, what I'm asking for is possible in other containers, such as SimpleInjector. This is how is it done.</p>
<pre class="lang-cs prettyprint-override"><code>container.RegisterConditional(typeof(ILogger),
                              _ => typeof(Logger<>).MakeGenericType(_.Consumer!.ImplementationType),
                              Lifestyle.Singleton,
                              _ => true);
</code>```

I'm just trying to find the equivalent means of accomplishing this in Microsoft's IServiceCollection

Body:
Lets say I have

public interface IService { }

public interface IService<TCategory> : IService { }

public class Service<TCategory> : IService<TCategory> { }

How do I get ServiceCollection to provide me Service<MyClass> and Service<OtherClass> when I resolve it like so?

public class MyClass
{
    public MyClass(IService service) => Service = service;

    IService Service { get; } // Should be set to Service<MyClass>
}

public class OtherClass
{
    public OtherClass(IService service) => Service = service;

    IService Service { get; } // Should be set to Service<OtherClass>
}

I DO NOT want to register in the collection like so, such that it requires me to specify for the classes the specific type in the constructor.

serviceCollection.AddSingleton(typeof(IService<>), typeof(Service<>));

public class MyClass
{
    public MyClass(IService<MyClass> service) => Service = service;

    IService Service { get; }
}

public class OtherClass
{
    public OtherClass(IService<OtherClass> service) => Service = service;

    IService Service { get; }
}

I do not want to have to redundantly restate the class I'm already within as part of the type in the constructor. I basically want it to work similar/same as ILogger/Logger<TCategory>

I was hoping to find an extension method that accepted a delegate of Func<IServiceProvider, type, object>, but have had no luck.

EDIT:

I'll some additional context here to better illustrate. For instance, what I'm asking for is possible in other containers, such as SimpleInjector. This is how is it done.

container.RegisterConditional(typeof(ILogger),
                              _ => typeof(Logger<>).MakeGenericType(_.Consumer!.ImplementationType),
                              Lifestyle.Singleton,
                              _ => true);

I'm just trying to find the equivalent means of accomplishing this in Microsoft's IServiceCollection


问:
How to set fontweight?
I'm writing a simple application in c# .net core 6 and winform to "assemble" some pngs and write some text on it.
This is the Photoshop output. The Title "Baldur the invincible" is wrote in Diablo Light when i'm writing it with DrawString with Font("Diablo", 30, FontStyle.Regular)

and this is my output with the Font.

In photoshop i used Diablo Light font but in the list of system fonts, from C# code, i see just Diablo Regular.. and the result is different.
How i can set the fontweight ?

here some code:

```<code>        // ---------------------------------------------------------------------------------------------- +
        // All TEXT ------------------------------------------------------------------------------------- +
        // ---------------------------------------------------------------------------------------------- +
        {
            //string familyName;
            //string familyList = "";
            //FontFamily[] fontFamilies;
            //InstalledFontCollection installedFontCollection = new InstalledFontCollection();
            //fontFamilies = installedFontCollection.Families;

            Font title_font = new Font("Diablo", 30, FontStyle.Regular);
            Font sub_font = new Font("Diablo", 25, FontStyle.Regular);
            List<Font> list_fonts = new List<Font>();
            list_fonts.Add(title_font);
            list_fonts.Add(sub_font);

            RectangleF tit_rect = new RectangleF(165, 70, w - (165 * 2), h);
            //RectangleF sub_rect = new RectangleF(165, 82 + 30, w - (165 * 2), h);
            var v = m_dict_titles["Title"];
            string curr_string = tabbed_value[v].ToUpper();
            float offsety = WriteTitleTextf2(map_back, 0, TL(curr_string, false), tit_rect, list_fonts, StringAlignment.Near, 5);
        }

    public void WriteOnBitmapf(Bitmap bmp, int col, Font font, String text, RectangleF rectf, StringAlignment st_align, float stringi = 0.0f)
    {
        float size = font.Size;
        Graphics g = Graphics.FromImage(bmp);
        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;
        g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

        StringFormat format = new StringFormat()
        {
            Alignment = st_align,
            LineAlignment = StringAlignment.Near
        };

        Brush br = col == 0 ? new SolidBrush(Color.FromArgb(0, 0, 0)) : new SolidBrush(Color.FromArgb(255, 255, 255));
        g.DrawString(text, font, br, rectf, format);
        g.Flush();
    }
</code>```

Title: How to set fontweight?

Body:
I'm writing a simple application in c# .net core 6 and winform to "assemble" some pngs and write some text on it.
This is the Photoshop output. The Title "Baldur the invincible" is wrote in Diablo Light when i'm writing it with DrawString with Font("Diablo", 30, FontStyle.Regular)

and this is my output with the Font.

In photoshop i used Diablo Light font but in the list of system fonts, from C# code, i see just Diablo Regular.. and the result is different.
How i can set the fontweight ?

here some code:

        // ---------------------------------------------------------------------------------------------- +
        // All TEXT ------------------------------------------------------------------------------------- +
        // ---------------------------------------------------------------------------------------------- +
        {
            //string familyName;
            //string familyList = "";
            //FontFamily[] fontFamilies;
            //InstalledFontCollection installedFontCollection = new InstalledFontCollection();
            //fontFamilies = installedFontCollection.Families;

            Font title_font = new Font("Diablo", 30, FontStyle.Regular);
            Font sub_font = new Font("Diablo", 25, FontStyle.Regular);
            List list_fonts = new List();
            list_fonts.Add(title_font);
            list_fonts.Add(sub_font);

            RectangleF tit_rect = new RectangleF(165, 70, w - (165 * 2), h);
            //RectangleF sub_rect = new RectangleF(165, 82 + 30, w - (165 * 2), h);
            var v = m_dict_titles["Title"];
            string curr_string = tabbed_value[v].ToUpper();
            float offsety = WriteTitleTextf2(map_back, 0, TL(curr_string, false), tit_rect, list_fonts, StringAlignment.Near, 5);
        }

    public void WriteOnBitmapf(Bitmap bmp, int col, Font font, String text, RectangleF rectf, StringAlignment st_align, float stringi = 0.0f)
    {
        float size = font.Size;
        Graphics g = Graphics.FromImage(bmp);
        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;
        g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

        StringFormat format = new StringFormat()
        {
            Alignment = st_align,
            LineAlignment = StringAlignment.Near
        };

        Brush br = col == 0 ? new SolidBrush(Color.FromArgb(0, 0, 0)) : new SolidBrush(Color.FromArgb(255, 255, 255));
        g.DrawString(text, font, br, rectf, format);
        g.Flush();
    }


问:
Please introduce me a WordPress plugin
I need a page to redirect users. Usually, these pages are used to download free files so that the users has to view advertisements. I would like to make this page with a plugin because I am not a programmer .But I can put codes in the header, footer and body with the help of the WordPress template (Jannah template).

The page should be in such a way that users wait for some time after entering this page, for example 30 seconds. After that, the download button will be displayed for them.

Note: I'm know redirecting users and I'm familiar with plugins like Yost, I need a page, a page that can redirect users.

Sample: https://weadown.com/get/down=06EheQIs9D0ICD9MS4cy9OwdV

Please help me friends.

I didn't try anything because no matter what I searched I couldn't find a plugin for this.

Title: Please introduce me a WordPress plugin