问:
SSL/TLS CA and CSR's common name field problem when setup local https server
I'm trying to setup local https server to test something.

```<code>➜  certs openssl req -new -x509 -days 365 -key ca.key -out ca.cert.pem
Country Name (2 letter code) []:.
State or Province Name (full name) []:.
Locality Name (eg, city) []:.
Organization Name (eg, company) []:.
Organizational Unit Name (eg, section) []:.
Common Name (eg, fully qualified host name) []:goose.local
Email Address []:.

➜  certs openssl req -new -sha256 -key goose.local.key -out goose.local.csr
Country Name (2 letter code) []:.
State or Province Name (full name) []:.
Locality Name (eg, city) []:.
Organization Name (eg, company) []:.
Organizational Unit Name (eg, section) []:.
Common Name (eg, fully qualified host name) []goose.local                                                          S Email Address []:.
</code>```

then i implement local https server as golang.

after installing CA to my device (laptop and iphone), when i access to my server (https://goose.local), it prompt NET::ERR_CERT_COMMON_NAME_INVALID.

how to set common name field in my case?

here is openssl s_client test for this.

```<code>➜  build openssl s_client -connect goose.local:443
CONNECTED(00000005)
depth=0 CN = goose.local
verify error:num=18:self signed certificate
verify return:1
depth=0 CN = goose.local
verify return:1
write W BLOCK
---
Certificate chain
 0 s:/CN=goose.local
   i:/CN=goose.local
---
Server certificate
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
subject=/CN=goose.local
issuer=/CN=goose.local
---
No client certificate CA names sent
Server Temp Key: ECDH, X25519, 253 bits
---
SSL handshake has read 2028 bytes and written 351 bytes
---
New, TLSv1/SSLv3, Cipher is AEAD-CHACHA20-POLY1305-SHA256
Server public key is 4096 bit
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.3
    Cipher    : AEAD-CHACHA20-POLY1305-SHA256
    Session-ID:
    Session-ID-ctx:
    Master-Key:
    Start Time: 1671011873
    Timeout   : 7200 (sec)
    Verify return code: 0 (ok)
---
</code>```

Body:
I'm trying to setup local https server to test something.

➜  certs openssl req -new -x509 -days 365 -key ca.key -out ca.cert.pem
Country Name (2 letter code) []:.
State or Province Name (full name) []:.
Locality Name (eg, city) []:.
Organization Name (eg, company) []:.
Organizational Unit Name (eg, section) []:.
Common Name (eg, fully qualified host name) []:goose.local
Email Address []:.

➜  certs openssl req -new -sha256 -key goose.local.key -out goose.local.csr
Country Name (2 letter code) []:.
State or Province Name (full name) []:.
Locality Name (eg, city) []:.
Organization Name (eg, company) []:.
Organizational Unit Name (eg, section) []:.
Common Name (eg, fully qualified host name) []goose.local                                                          S Email Address []:.

then i implement local https server as golang.

after installing CA to my device (laptop and iphone), when i access to my server (https://goose.local), it prompt NET::ERR_CERT_COMMON_NAME_INVALID.

how to set common name field in my case?

here is openssl s_client test for this.

➜  build openssl s_client -connect goose.local:443
CONNECTED(00000005)
depth=0 CN = goose.local
verify error:num=18:self signed certificate
verify return:1
depth=0 CN = goose.local
verify return:1
write W BLOCK
---
Certificate chain
 0 s:/CN=goose.local
   i:/CN=goose.local
---
Server certificate
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
subject=/CN=goose.local
issuer=/CN=goose.local
---
No client certificate CA names sent
Server Temp Key: ECDH, X25519, 253 bits
---
SSL handshake has read 2028 bytes and written 351 bytes
---
New, TLSv1/SSLv3, Cipher is AEAD-CHACHA20-POLY1305-SHA256
Server public key is 4096 bit
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.3
    Cipher    : AEAD-CHACHA20-POLY1305-SHA256
    Session-ID:
    Session-ID-ctx:
    Master-Key:
    Start Time: 1671011873
    Timeout   : 7200 (sec)
    Verify return code: 0 (ok)
---


来源: stackexchange

问:
how to call a function of another component in react js
I have a NavMenu component class like this:

import React, { Component } from "react";
import { Navbar, NavItem, NavLink, OffcanvasBody } from "reactstrap";
import "./styles/NavMenu.css";
import Offcanvas from "react-bootstrap/Offcanvas";

export class NavMenu extends Component {
  static displayName = NavMenu.name;
  constructor(props) {
    super(props);
    this.state = {
      showOffcanvas: false,
    };
    this.setShowOffcanvas = this.setShowOffcanvas.bind(this);
    this.setHideOffcanvas = this.setHideOffcanvas.bind(this);
  }

  setShowOffcanvas() {
    this.setState({ showOffcanvas: true });
  }

  setHideOffcanvas() {
    this.setState({ showOffcanvas: false });
  }
  render() {
    return (
      <>
        <Navbar className="sticky-top">

            <NavItem>
              <NavLink onClick={this.setShowOffcanvas} className="original">
                Open Offcanvas
              </NavLink>
            </NavItem>

        </Navbar>
        <Offcanvas
          className="offcanvasPlayer"
          show={this.state.showOffcanvas}
          onHide={this.setHideOffcanvas}
        >
          <NavLink
            className="text-white card-link close-btn"
            data-bs-dismiss="offcanvas"
            onClick={this.setHideOffcanvas}
          ></NavLink>
          <OffcanvasBody>{/* offcanvas body here */}</OffcanvasBody>
        </Offcanvas>
      </>
    );
  }
}

```
<p>then my navbar button to open offcanvas in another component like this :</p>
<pre class="lang-js prettyprint-override"><code>import React, { Component } from "react";
import { NavLink } from "reactstrap";
import "./styles/TopNavbar.css";

export class TopNavbar extends Component {
  static displayName = TopNavbar.name;
  constructor(props) {
    super(props);
    this.state = {
      showOffcanvas: false,
      showPlayer: false,
    };
    this.setShowOffcanvas = this.setShowOffcanvas.bind(this);
    this.setHideOffcanvas = this.setHideOffcanvas.bind(this);
  }

  setShowOffcanvas() {
    this.setState({ showOffcanvas: true });
  }

  setHideOffcanvas() {
    this.setState({ showOffcanvas: false });
  }

  render() {
    return (
      <>
        <NavLink className="item" onClick={this.setShowOffcanvas}>Opening Offcanvas NavMenu component</NavLink>
      </>
    );
  }
}

</code>```

but when i'm clicking on the (this.setShowOffcanvas), project show this error:

Uncaught TypeError: Cannot read properties of null (reading 'hide')
    at HTMLAnchorElement.<anonymous> (offcanvas.js:254:1)
    at HTMLDocument.handler (event-handler.js:118:1)
```

I swear to God, whatever I did didn't work

ContentLicense: CC BY-SA 4.0

Body:
I have a NavMenu component class like this:

import React, { Component } from "react";
import { Navbar, NavItem, NavLink, OffcanvasBody } from "reactstrap";
import "./styles/NavMenu.css";
import Offcanvas from "react-bootstrap/Offcanvas";

export class NavMenu extends Component {
  static displayName = NavMenu.name;
  constructor(props) {
    super(props);
    this.state = {
      showOffcanvas: false,
    };
    this.setShowOffcanvas = this.setShowOffcanvas.bind(this);
    this.setHideOffcanvas = this.setHideOffcanvas.bind(this);
  }

  setShowOffcanvas() {
    this.setState({ showOffcanvas: true });
  }

  setHideOffcanvas() {
    this.setState({ showOffcanvas: false });
  }
  render() {
    return (
      <>
        <Navbar className="sticky-top">

            <NavItem>
              <NavLink onClick={this.setShowOffcanvas} className="original">
                Open Offcanvas
              </NavLink>
            </NavItem>

        </Navbar>
        <Offcanvas
          className="offcanvasPlayer"
          show={this.state.showOffcanvas}
          onHide={this.setHideOffcanvas}
        >
          <NavLink
            className="text-white card-link close-btn"
            data-bs-dismiss="offcanvas"
            onClick={this.setHideOffcanvas}
          ></NavLink>
          <OffcanvasBody>{/* offcanvas body here */}</OffcanvasBody>
        </Offcanvas>
      </>
    );
  }
}

then my navbar button to open offcanvas in another component like this :

import React, { Component } from "react";
import { NavLink } from "reactstrap";
import "./styles/TopNavbar.css";

export class TopNavbar extends Component {
  static displayName = TopNavbar.name;
  constructor(props) {
    super(props);
    this.state = {
      showOffcanvas: false,
      showPlayer: false,
    };
    this.setShowOffcanvas = this.setShowOffcanvas.bind(this);
    this.setHideOffcanvas = this.setHideOffcanvas.bind(this);
  }

  setShowOffcanvas() {
    this.setState({ showOffcanvas: true });
  }

  setHideOffcanvas() {
    this.setState({ showOffcanvas: false });
  }

  render() {
    return (
      <>
        <NavLink className="item" onClick={this.setShowOffcanvas}>Opening Offcanvas NavMenu component</NavLink>
      </>
    );
  }
}

but when i'm clicking on the (this.setShowOffcanvas), project show this error:

Uncaught TypeError: Cannot read properties of null (reading 'hide')
    at HTMLAnchorElement.<anonymous> (offcanvas.js:254:1)
    at HTMLDocument.handler (event-handler.js:118:1)

I swear to God, whatever I did didn't work


问:
Spring Boot 3 and cross platform native-image creation with GraalVM
with Spring Boot 3 release there is lots of advertisement about GraalVM and native-images, so I decided experiment little bit..

With Spring Boot Initializer I quickly created a really simple gradle project (one single rest service that is doing nothing special). With the help of the gradle 'native-image' and JiB plugin, I could quickly get a running state with Spring Boot Application as a normal Java Applicaton and native-image Application (and seen the drastic startup time changes).

While JiB created a Docker Image for me, I tried to deploy the SB3 application to my minikube, there I got the first surprise, while I was working with MacOS M1, the image that I created (based on alpine) was complaining the wrong 'exec format' after little bit reading, I learned while my local GraalVM is MacOS based aarch64 it would not run in alpine and I have to create cross platform image and I have to create Docker images based on destination platform GraalVM (in this case linux/alpine) which I did, I bypassed the original problem and Spring Boot 3 application starts but encounters following problem in the stacktrace.

```<code>16:43:45.808 [main] ERROR org.springframework.boot.SpringApplication - Application
run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with
name 'resourceHandlerMapping': Instantiation of supplied bean failed
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.obtainInstan ceFromSupplier(AbstractAutowireCapableBeanFactory.java:1236)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.obtainFromSupplier(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1157)

Caused by: java.lang.IllegalStateException: No ServletContext set
at org.springframework.util.Assert.state(Assert.java:76)
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.resourceHandlerMapping(WebMvcConfigurationSupport.java:581)
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport__BeanDefinitions.lambda$getResourceHandlerMappingInstanceSupplier$7(WebMvcConfigurationSupport__BeanDefinitions.java:166)
at org.springframework.util.function.ThrowingBiFunction.apply(ThrowingBiFunction.java:68)
at org.springframework.util.function.ThrowingBiFunction.apply(ThrowingBiFunction.java:54)
</code>```

Now I tried to look as much as possible what 'native-image' plugin does (while native-image and Spring Boot 3 application runs on my Mac Book), I can't figure out what is the Delta. I think it has to do with 'reflection-config'. 'native-image' plugin created a 'reflect-config.json' and it contains the following lines.

```<code>   {
    "name": "resourceHandlerMapping",
    "parameterTypes": [
      "org.springframework.web.accept.ContentNegotiationManager",
      "org.springframework.format.support.FormattingConversionService",
      "org.springframework.web.servlet.resource.ResourceUrlProvider"
    ]
  }
</code>```

I think should be relevant for the problem, but this file is in the classpath and it is not changing the outcome(I can also see that 'WebMvcConfigurationSupport__BeanDefinitions.java' is also generated and is in the classpath).

One thing I have to say, while the shear number of dependencies Spring Boot needs, I didn't place the whole dependencies in the classpath but I created a fat jar (shadowJar plugin), which includes all my code and dependencies, may be this causing the problem.

'native-image' in my cross platform docker image, is able to create the application with this fat jar but it throws the above mentioned exception.

Anyway, can anybody give any tips to solve this problem.

Or how can diagnose such a problem in GraalVM and native-image?

Body:
with Spring Boot 3 release there is lots of advertisement about GraalVM and native-images, so I decided experiment little bit..

With Spring Boot Initializer I quickly created a really simple gradle project (one single rest service that is doing nothing special). With the help of the gradle 'native-image' and JiB plugin, I could quickly get a running state with Spring Boot Application as a normal Java Applicaton and native-image Application (and seen the drastic startup time changes).

While JiB created a Docker Image for me, I tried to deploy the SB3 application to my minikube, there I got the first surprise, while I was working with MacOS M1, the image that I created (based on alpine) was complaining the wrong 'exec format' after little bit reading, I learned while my local GraalVM is MacOS based aarch64 it would not run in alpine and I have to create cross platform image and I have to create Docker images based on destination platform GraalVM (in this case linux/alpine) which I did, I bypassed the original problem and Spring Boot 3 application starts but encounters following problem in the stacktrace.

16:43:45.808 [main] ERROR org.springframework.boot.SpringApplication - Application
run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with
name 'resourceHandlerMapping': Instantiation of supplied bean failed
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.obtainInstan ceFromSupplier(AbstractAutowireCapableBeanFactory.java:1236)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.obtainFromSupplier(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1157)

Caused by: java.lang.IllegalStateException: No ServletContext set
at org.springframework.util.Assert.state(Assert.java:76)
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.resourceHandlerMapping(WebMvcConfigurationSupport.java:581)
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport__BeanDefinitions.lambda$getResourceHandlerMappingInstanceSupplier$7(WebMvcConfigurationSupport__BeanDefinitions.java:166)
at org.springframework.util.function.ThrowingBiFunction.apply(ThrowingBiFunction.java:68)
at org.springframework.util.function.ThrowingBiFunction.apply(ThrowingBiFunction.java:54)

Now I tried to look as much as possible what 'native-image' plugin does (while native-image and Spring Boot 3 application runs on my Mac Book), I can't figure out what is the Delta. I think it has to do with 'reflection-config'. 'native-image' plugin created a 'reflect-config.json' and it contains the following lines.

   {
    "name": "resourceHandlerMapping",
    "parameterTypes": [
      "org.springframework.web.accept.ContentNegotiationManager",
      "org.springframework.format.support.FormattingConversionService",
      "org.springframework.web.servlet.resource.ResourceUrlProvider"
    ]
  }

I think should be relevant for the problem, but this file is in the classpath and it is not changing the outcome(I can also see that 'WebMvcConfigurationSupport__BeanDefinitions.java' is also generated and is in the classpath).

One thing I have to say, while the shear number of dependencies Spring Boot needs, I didn't place the whole dependencies in the classpath but I created a fat jar (shadowJar plugin), which includes all my code and dependencies, may be this causing the problem.

'native-image' in my cross platform docker image, is able to create the application with this fat jar but it throws the above mentioned exception.

Anyway, can anybody give any tips to solve this problem.

Or how can diagnose such a problem in GraalVM and native-image?


问:
How to filter items in Fluent UI groupedList component
I want to use Fluent UI groupedList, but there are 2 things I didn't understand.

1st) I always see items have a parent group/s. Is it possible to write items in groups level?

-- Group 1

--- Group 2

---- Group 3

--- Item

As seen above, Item is on the level of Group 2. How can I implement something like this?

2nd) I couldn't filter items by groups. For example, I want some items to belong to Group 2, and some other to Group 3. But as I see on the component examples, we have counts and whatever count we give, the component shows us that much item.

Fluent UI groupedList component:
https://developer.microsoft.com/en-us/fluentui#/controls/web/groupedlist

I also have this codepen:
https://codepen.io/ozan-bilgi/pen/mdKZqNG?editors=0010

```<code>const { GroupedList, IGroup, IColumn, DetailsRow, Selection, SelectionMode, SelectionZone, Toggle, IToggleStyles, ThemeProvider, initializeIcons } = window.FluentUIReact;
const { useBoolean, useConst } = window.FluentUIReactHooks;
const { createListItems, createGroups, IExampleItem } = window.FluentUIExampleData;

// Initialize icons in case this example uses them
initializeIcons();

const toggleStyles: Partial<IToggleStyles> = { root: { marginBottom: '20px' } };

const items = [
  {
    color: "red",
    description: "Lorem ipsum",
    height: 212,
    key: "group0",
    location: "portland",
    name: "www",
    shape: "square",
    thumbnail: "AAAA",
    width: 212
  },
  {
    color: "red",
    description: "Lorem ipsum",
    height: 212,
    key: "group1",
    location: "portland",
    name: "eee",
    shape: "square",
    thumbnail: "AAAA",
    width: 212
  },{
    color: "red",
    description: "Lorem ipsum",
    height: 212,
    key: "group2",
    location: "portland",
    name: "rrr",
    shape: "square",
    thumbnail: "AAAA",
    width: 212
  },{
    color: "red",
    description: "Lorem ipsum",
    height: 212,
    key: "group3",
    location: "portland",
    name: "nnn",
    shape: "square",
    thumbnail: "AAAA",
    width: 212
  },{
    color: "red",
    description: "Lorem ipsum",
    height: 212,
    key: "group4",
    location: "portland",
    name: "bbb",
    shape: "square",
    thumbnail: "AAAA",
    width: 212
  },{
    color: "red",
    description: "Lorem ipsum",
    height: 212,
    key: "group5",
    location: "portland",
    name: "vvv",
    shape: "square",
    thumbnail: "AAAA",
    width: 212
  },{
    color: "red",
    description: "Lorem ipsum",
    height: 212,
    key: "group6",
    location: "portland",
    name: "lorem",
    shape: "square",
    thumbnail: "AAAA",
    width: 212
  },{
    color: "red",
    description: "Lorem ipsum",
    height: 212,
    key: "group7",
    location: "portland",
    name: "aaa",
    shape: "square",
    thumbnail: "AAAA",
    width: 212
  },
]

const columns =  [
      { key: 'group0', name: 'Title', fieldName: 'name', minWidth: 100, maxWidth: 200, isResizable: true },
      { key: 'business', name: 'Business', fieldName: 'business', minWidth: 100, maxWidth: 200, isResizable: true },
      { key: 'initialAssessment', name: 'Initial Assessment', fieldName: 'initialAssessment', minWidth: 100, maxWidth: 200, isResizable: true },
    ];
//const groups = createGroups(groupCount, groupDepth, 0, groupCount);

const groups = [
  {
    children: [{
      children: [],
      count: 3,
      isCollapsed: undefined,
      key: "group0-0-0",
      level: 1,
      name: "group0-0-0",
      startIndex: 0
    }],
    count: 2,
    isCollapsed: undefined,
    key: "group0",
    level: 0,
    name: "First Group",
    startIndex: 0
  },
  {
    children: [{
      children: [],
      count: 2,
      isCollapsed: undefined,
      key: "group1",
      level: 1,
      name: "group0-0-0",
      startIndex: 0
    }],
    count: 1,
    isCollapsed: undefined,
    key: "group2",
    level: 0,
    name: "Second Group",
    startIndex: 0
  }
]

const GroupedListBasicExample: React.FunctionComponent = () => {

  const onRenderCell = (
    nestingDepth?: number,
    item?: IExampleItem,
    itemIndex?: number,
    group?: IGroup,
  ): React.ReactNode => {
    return item && typeof itemIndex === 'number' && itemIndex > -1 ? (
      <DetailsRow
        columns={columns}
        groupNestingDepth={nestingDepth}
        item={item}
        itemIndex={itemIndex}
        selectionMode={SelectionMode.multiple}
        group={group}
      />
    ) : null;
  };

  return (
    <div>
        <GroupedList
          items={items}
          // eslint-disable-next-line react/jsx-no-bind
          onRenderCell={onRenderCell}
          selectionMode={SelectionMode.multiple}
          groups={groups}
        />
    </div>
  );
};

const GroupedListBasicExampleWrapper = () => <ThemeProvider><GroupedListBasicExample /></ThemeProvider>;
ReactDOM.render(<GroupedListBasicExampleWrapper />, document.getElementById('content'))
</code>```

Body:
I want to use Fluent UI groupedList, but there are 2 things I didn't understand.

1st) I always see items have a parent group/s. Is it possible to write items in groups level?

-- Group 1

--- Group 2

---- Group 3

--- Item

As seen above, Item is on the level of Group 2. How can I implement something like this?

2nd) I couldn't filter items by groups. For example, I want some items to belong to Group 2, and some other to Group 3. But as I see on the component examples, we have counts and whatever count we give, the component shows us that much item.

Fluent UI groupedList component:
https://developer.microsoft.com/en-us/fluentui#/controls/web/groupedlist

I also have this codepen:
https://codepen.io/ozan-bilgi/pen/mdKZqNG?editors=0010

const { GroupedList, IGroup, IColumn, DetailsRow, Selection, SelectionMode, SelectionZone, Toggle, IToggleStyles, ThemeProvider, initializeIcons } = window.FluentUIReact;
const { useBoolean, useConst } = window.FluentUIReactHooks;
const { createListItems, createGroups, IExampleItem } = window.FluentUIExampleData;

// Initialize icons in case this example uses them
initializeIcons();

const toggleStyles: Partial<IToggleStyles> = { root: { marginBottom: '20px' } };

const items = [
  {
    color: "red",
    description: "Lorem ipsum",
    height: 212,
    key: "group0",
    location: "portland",
    name: "www",
    shape: "square",
    thumbnail: "AAAA",
    width: 212
  },
  {
    color: "red",
    description: "Lorem ipsum",
    height: 212,
    key: "group1",
    location: "portland",
    name: "eee",
    shape: "square",
    thumbnail: "AAAA",
    width: 212
  },{
    color: "red",
    description: "Lorem ipsum",
    height: 212,
    key: "group2",
    location: "portland",
    name: "rrr",
    shape: "square",
    thumbnail: "AAAA",
    width: 212
  },{
    color: "red",
    description: "Lorem ipsum",
    height: 212,
    key: "group3",
    location: "portland",
    name: "nnn",
    shape: "square",
    thumbnail: "AAAA",
    width: 212
  },{
    color: "red",
    description: "Lorem ipsum",
    height: 212,
    key: "group4",
    location: "portland",
    name: "bbb",
    shape: "square",
    thumbnail: "AAAA",
    width: 212
  },{
    color: "red",
    description: "Lorem ipsum",
    height: 212,
    key: "group5",
    location: "portland",
    name: "vvv",
    shape: "square",
    thumbnail: "AAAA",
    width: 212
  },{
    color: "red",
    description: "Lorem ipsum",
    height: 212,
    key: "group6",
    location: "portland",
    name: "lorem",
    shape: "square",
    thumbnail: "AAAA",
    width: 212
  },{
    color: "red",
    description: "Lorem ipsum",
    height: 212,
    key: "group7",
    location: "portland",
    name: "aaa",
    shape: "square",
    thumbnail: "AAAA",
    width: 212
  },
]

const columns =  [
      { key: 'group0', name: 'Title', fieldName: 'name', minWidth: 100, maxWidth: 200, isResizable: true },
      { key: 'business', name: 'Business', fieldName: 'business', minWidth: 100, maxWidth: 200, isResizable: true },
      { key: 'initialAssessment', name: 'Initial Assessment', fieldName: 'initialAssessment', minWidth: 100, maxWidth: 200, isResizable: true },
    ];
//const groups = createGroups(groupCount, groupDepth, 0, groupCount);

const groups = [
  {
    children: [{
      children: [],
      count: 3,
      isCollapsed: undefined,
      key: "group0-0-0",
      level: 1,
      name: "group0-0-0",
      startIndex: 0
    }],
    count: 2,
    isCollapsed: undefined,
    key: "group0",
    level: 0,
    name: "First Group",
    startIndex: 0
  },
  {
    children: [{
      children: [],
      count: 2,
      isCollapsed: undefined,
      key: "group1",
      level: 1,
      name: "group0-0-0",
      startIndex: 0
    }],
    count: 1,
    isCollapsed: undefined,
    key: "group2",
    level: 0,
    name: "Second Group",
    startIndex: 0
  }
]

const GroupedListBasicExample: React.FunctionComponent = () => {

  const onRenderCell = (
    nestingDepth?: number,
    item?: IExampleItem,
    itemIndex?: number,
    group?: IGroup,
  ): React.ReactNode => {
    return item && typeof itemIndex === 'number' && itemIndex > -1 ? (
      <DetailsRow
        columns={columns}
        groupNestingDepth={nestingDepth}
        item={item}
        itemIndex={itemIndex}
        selectionMode={SelectionMode.multiple}
        group={group}
      />
    ) : null;
  };

  return (

        <GroupedList
          items={items}
          // eslint-disable-next-line react/jsx-no-bind
          onRenderCell={onRenderCell}
          selectionMode={SelectionMode.multiple}
          groups={groups}
        />

  );
};

const GroupedListBasicExampleWrapper = () => <ThemeProvider><GroupedListBasicExample /></ThemeProvider>;
ReactDOM.render(<GroupedListBasicExampleWrapper />, document.getElementById('content'))


问:
tcp connection sometimes can not reply to incoming request
i use centos 7 64 bit

for incoming tcp connection in port 443 we have a problem

packet only come in but centos can not send answer  to it

in this image you can see a normal response

in error time we see  win 65520, options [mss 1260,nop,wscale 8,nop,nop,sackOK], length 0 but in normal we see  win 516, length 0

can anyone help me?


问:
copy union cell to different sheet
I have this code

```<code>Sub try()

Sheet_a = "Aladin"
Sheet_b = "Elenco Sedi"

a = "22"

b = "11"

Sheets(Sheet_a).Select

Worksheets(Sheet_a).Activate

       Set RangeUnionCopy = Union(Cells(a, 2), Cells(a, 3), Cells(a, 4), Cells(a, 5), Cells(a, 6), Cells(a, 7), Cells(a, 11), Cells(a, 12))
       Set RangeUnionPaste = Union(Cells(b, 1), Cells(b, 2), Cells(b, 4), Cells(b, 5), Cells(b, 6), Cells(b, 7), Cells(b, 11), Cells(b, 12))
       RangeUnionCopy.Copy Destination:=Sheets(Sheet_b).Range(RangeUnionPaste.Address)

End Sub
</code>```

don't work.. the problem it's in row RangeUnionCopy.Copy Destination:=Sheets(Sheet_b).Range(RangeUnionPaste.Address)
why ??

please help me to resolve this script

Title: copy union cell to different sheet

Body:
I have this code

Sub try()

Sheet_a = "Aladin"
Sheet_b = "Elenco Sedi"

a = "22"

b = "11"

Sheets(Sheet_a).Select

Worksheets(Sheet_a).Activate

       Set RangeUnionCopy = Union(Cells(a, 2), Cells(a, 3), Cells(a, 4), Cells(a, 5), Cells(a, 6), Cells(a, 7), Cells(a, 11), Cells(a, 12))
       Set RangeUnionPaste = Union(Cells(b, 1), Cells(b, 2), Cells(b, 4), Cells(b, 5), Cells(b, 6), Cells(b, 7), Cells(b, 11), Cells(b, 12))
       RangeUnionCopy.Copy Destination:=Sheets(Sheet_b).Range(RangeUnionPaste.Address)

End Sub

don't work.. the problem it's in row RangeUnionCopy.Copy Destination:=Sheets(Sheet_b).Range(RangeUnionPaste.Address)
why ??

please help me to resolve this script


问:
How to config different npm packages dependencies on different platform in Electron?
I am building a new app that's based on electron.
I need publish it to multi platforms,like windows,mac,linux..
But in different platform, my app depends different npm packages.

example:
windows:

```<code>       npm-package-1
       npm-package-2
</code>```

linux:

```<code>       npm-package-1
       npm-package-3
</code>```

mac:

```<code>       npm-package-1
       npm-package-4
</code>```

How can i do this?

I want know how to config different dependencies on different platform.

Body:
I am building a new app that's based on electron.
I need publish it to multi platforms,like windows,mac,linux..
But in different platform, my app depends different npm packages.

example:
windows:

       npm-package-1
       npm-package-2

linux:

       npm-package-1
       npm-package-3

mac:

       npm-package-1
       npm-package-4

How can i do this?

I want know how to config different dependencies on different platform.


问:
TypeError : 'int' opject is not subscriptable in python tkinter
i try create a tkinter app with python and i made a button that can search but when i search i got this error

rows = db.search(self.selected_item[0], self.entry.get() , self.entry3.get(), self.entry2.get(), self.entry_iv.get())
^^^
TypeError: 'int' object is not subscriptable

this the app code

```<code>import sqlite3
from tkinter import *
from db import db

db = db("wikibook.db")

class root(Tk):
    def __init__(self):
        super().__init__()
        self.title("book info")
        self.minsize(500, 400)
        self.configure(background="gray")
        self.create_data()
        self.populate_list()
        self.selected_item = 0

    def create_data(self):

        #make title input

        self.title = StringVar()

        self.title_Entry = Label(self, text="title")
        self.title_Entry.place(x=41, y=10)

        self.entry = Entry(self, textvariable=self.title)
        self.entry.place(x=66, y=10)

        # make years input

        self.years = StringVar()

        self.years_Entry = Label(self, text="year")
        self.years_Entry.place(x=269, y=10)

        self.entry2 = Entry(self, textvariable=self.years)
        self.entry2.place(x=300.5, y=10.2)

        # make author input

        self.author = StringVar()

        self.author_Entry = Label(self, text="author")
        self.author_Entry.place(x=40, y=51)

        self.entry3 = Entry(self, textvariable=self.author)
        self.entry3.place(x=80, y=51)

        # make isbn input

        self.isbn = StringVar()

        self.isbn_Entry = Label(self, text="isbn")
        self.isbn_Entry.place(x=270, y=52)

        self.entry_iv = Entry(self, textvariable=self.isbn)
        self.entry_iv.place(x=297, y=52)

        # listbox

        self.list_box = Listbox(self, height=10, width=50)
        self.list_box.place(x=85, y=200)

        #select items

        self.list_box.bind('<<ListboxSelect>>', self.select_book)

        # buttons

        save_button = Button(self,text= "save", command = self.add_book)
        save_button.place(x=66, y=150)

        delete_button = Button(self, text="delete", command = self.remove_rows)
        delete_button.place(x=170, y=150)

        search_button = Button(self, text="search", command = self.search)
        search_button.place(x=275, y=150)

        update_button = Button(self, text="update", command = self.edit)
        update_button.place(x=400, y=150)

    def populate_list(self, rows=None):
        #clear list
        self.list_box.delete(0 , END)
        if rows == None :
            rows = db.fetch()
        for row in rows:
            self.list_box.insert(END, row)

    def add_book(self):

        #insert book to database

        db.insert(self.title.get() , self.years.get(), self.author.get(), self.isbn.get())

        #clear fields + populate list
        self.clear_fields()
        self.populate_list()

    def clear_fields(self):
        self.entry.delete(0, END)
        self.entry3.delete(0, END)
        self.entry2.delete(0, END)
        self.entry_iv.delete(0, END)

    def select_book(self, event):

        widget = event.widget
        self.selected_item=widget.get(ANCHOR)
        #add slscted item to enteries

        self.clear_fields()

        self.entry.insert(0, self.selected_item[1])
        self.entry2.insert(0, self.selected_item[2])
        self.entry3.insert(0, self.selected_item[3])
        self.entry_iv.insert(0, self.selected_item[4])

    def remove_rows(self):
        db.remove(self.selected_item[0])
        #clear fields + populate list
        self.clear_fields()
        self.populate_list()

    def search(self):

        rows = db.search(self.selected_item[0], self.entry.get() , self.entry3.get(), self.entry2.get(), self.entry_iv.get())

        self.populate_list(rows)

    def edit(self):

        db.update(self.selected_item[0], self.entry.get() , self.entry3.get(), self.entry2.get(), self.entry_iv.get())

        self.populate_list()

win = root()
win.mainloop()
</code>```

and this the databace code

```<code>import sqlite3

class db():

    def __init__(self, db):
        self.conn = sqlite3.connect(db)
        self.cur = self.conn.cursor()
        self.cur.execute("CREATE TABLE IF NOT EXISTS books (id INTEGER PRIMARY KEY, title TEXT, author TEXT, year TEXT, isbn TEXT)")
        self.conn.commit()

    def fetch(self):
        self.cur.execute("SELECT * FROM books")
        rows = self.cur.fetchall()
        return rows

    def insert(self, title, author, year, isbn):
        self.cur.execute("INSERT INTO books VALUES (NULL, ?, ?, ?, ?)" , (title, author, year, isbn))
        self.conn.commit()

    def remove(self, id):
        self.cur.execute("DELETE FROM books WHERE id=?" , (id,))
        self.conn.commit()

    def update(self, id, title, author, year, isbn):
        self.cur.execute("UPDATE books SET title=? , author=? , year=? , isbn=? WHERE id=?" , (title, author, year, isbn, id))
        self.conn.commit()

    def search(self, title, author, year, isbn):
        self.cur.execute("SELECT * FROM books WHERE title=? OR author=? OR year=? OR isbn=?", (title, author, year, isbn))
        rows = self.cur.fetchall()
        return rows

    def __del__(self):
        self.conn.close()

</code>```

how can i fix the error

................................................

Body:
i try create a tkinter app with python and i made a button that can search but when i search i got this error

rows = db.search(self.selected_item[0], self.entry.get() , self.entry3.get(), self.entry2.get(), self.entry_iv.get())
^^^
TypeError: 'int' object is not subscriptable

this the app code

import sqlite3
from tkinter import *
from db import db

db = db("wikibook.db")

class root(Tk):
    def __init__(self):
        super().__init__()
        self.title("book info")
        self.minsize(500, 400)
        self.configure(background="gray")
        self.create_data()
        self.populate_list()
        self.selected_item = 0

    def create_data(self):

        #make title input

        self.title = StringVar()

        self.title_Entry = Label(self, text="title")
        self.title_Entry.place(x=41, y=10)

        self.entry = Entry(self, textvariable=self.title)
        self.entry.place(x=66, y=10)

        # make years input

        self.years = StringVar()

        self.years_Entry = Label(self, text="year")
        self.years_Entry.place(x=269, y=10)

        self.entry2 = Entry(self, textvariable=self.years)
        self.entry2.place(x=300.5, y=10.2)

        # make author input

        self.author = StringVar()

        self.author_Entry = Label(self, text="author")
        self.author_Entry.place(x=40, y=51)

        self.entry3 = Entry(self, textvariable=self.author)
        self.entry3.place(x=80, y=51)

        # make isbn input

        self.isbn = StringVar()

        self.isbn_Entry = Label(self, text="isbn")
        self.isbn_Entry.place(x=270, y=52)

        self.entry_iv = Entry(self, textvariable=self.isbn)
        self.entry_iv.place(x=297, y=52)

        # listbox

        self.list_box = Listbox(self, height=10, width=50)
        self.list_box.place(x=85, y=200)

        #select items

        self.list_box.bind('<<ListboxSelect>>', self.select_book)

        # buttons

        save_button = Button(self,text= "save", command = self.add_book)
        save_button.place(x=66, y=150)

        delete_button = Button(self, text="delete", command = self.remove_rows)
        delete_button.place(x=170, y=150)

        search_button = Button(self, text="search", command = self.search)
        search_button.place(x=275, y=150)

        update_button = Button(self, text="update", command = self.edit)
        update_button.place(x=400, y=150)

    def populate_list(self, rows=None):
        #clear list
        self.list_box.delete(0 , END)
        if rows == None :
            rows = db.fetch()
        for row in rows:
            self.list_box.insert(END, row)

    def add_book(self):

        #insert book to database

        db.insert(self.title.get() , self.years.get(), self.author.get(), self.isbn.get())

        #clear fields + populate list
        self.clear_fields()
        self.populate_list()

    def clear_fields(self):
        self.entry.delete(0, END)
        self.entry3.delete(0, END)
        self.entry2.delete(0, END)
        self.entry_iv.delete(0, END)

    def select_book(self, event):

        widget = event.widget
        self.selected_item=widget.get(ANCHOR)
        #add slscted item to enteries

        self.clear_fields()

        self.entry.insert(0, self.selected_item[1])
        self.entry2.insert(0, self.selected_item[2])
        self.entry3.insert(0, self.selected_item[3])
        self.entry_iv.insert(0, self.selected_item[4])

    def remove_rows(self):
        db.remove(self.selected_item[0])
        #clear fields + populate list
        self.clear_fields()
        self.populate_list()

    def search(self):

        rows = db.search(self.selected_item[0], self.entry.get() , self.entry3.get(), self.entry2.get(), self.entry_iv.get())

        self.populate_list(rows)

    def edit(self):

        db.update(self.selected_item[0], self.entry.get() , self.entry3.get(), self.entry2.get(), self.entry_iv.get())

        self.populate_list()

win = root()
win.mainloop()

and this the databace code

import sqlite3

class db():

    def __init__(self, db):
        self.conn = sqlite3.connect(db)
        self.cur = self.conn.cursor()
        self.cur.execute("CREATE TABLE IF NOT EXISTS books (id INTEGER PRIMARY KEY, title TEXT, author TEXT, year TEXT, isbn TEXT)")
        self.conn.commit()

    def fetch(self):
        self.cur.execute("SELECT * FROM books")
        rows = self.cur.fetchall()
        return rows

    def insert(self, title, author, year, isbn):
        self.cur.execute("INSERT INTO books VALUES (NULL, ?, ?, ?, ?)" , (title, author, year, isbn))
        self.conn.commit()

    def remove(self, id):
        self.cur.execute("DELETE FROM books WHERE id=?" , (id,))
        self.conn.commit()

    def update(self, id, title, author, year, isbn):
        self.cur.execute("UPDATE books SET title=? , author=? , year=? , isbn=? WHERE id=?" , (title, author, year, isbn, id))
        self.conn.commit()

    def search(self, title, author, year, isbn):
        self.cur.execute("SELECT * FROM books WHERE title=? OR author=? OR year=? OR isbn=?", (title, author, year, isbn))
        rows = self.cur.fetchall()
        return rows

    def __del__(self):
        self.conn.close()

how can i fix the error

................................................


问:
Authorization/API key text box not appearing on Swagger Page
I have upgraded the dropwizard swagger version in my code. Now after upgrading the same I am not able to see the API_KEY textbox on swagger page.

I have changed the maven dependency From

```<code><dependencies>
    <dependency>
        <groupId>io.dropwizard</groupId>
        <artifactId>dropwizard-core</artifactId>
        <version>0.8.0</version>
    </dependency>
    <dependency>
        <groupId>io.federecio</groupId>
        <artifactId>dropwizard-swagger</artifactId>
        <version>0.7.0</version>
    </dependency>
</dependencies>
</code>```

Swagger Page Before

Swagger Page UI Before

To

```<code><dependency>
    <groupId>io.dropwizard</groupId>
    <artifactId>dropwizard-core</artifactId>
    <version>2.1.4</version>
</dependency>
<dependency>
    <groupId>com.smoketurner</groupId>
    <artifactId>dropwizard-swagger</artifactId>
    <version>2.0.12-1</version>
</dependency>
</code>```

Swagger Page After Upgrading the dropwizard version

Swagger UI Page after upgrade

I want the Swagger page should has some Authorize/ API token text box so I can provide the oauth token on the page.

Body:
I have upgraded the dropwizard swagger version in my code. Now after upgrading the same I am not able to see the API_KEY textbox on swagger page.

I have changed the maven dependency From

<dependencies>
    <dependency>
        <groupId>io.dropwizard</groupId>
        <artifactId>dropwizard-core</artifactId>
        <version>0.8.0</version>
    </dependency>
    <dependency>
        <groupId>io.federecio</groupId>
        <artifactId>dropwizard-swagger</artifactId>
        <version>0.7.0</version>
    </dependency>
</dependencies>

Swagger Page Before

Swagger Page UI Before

To

<dependency>
    <groupId>io.dropwizard</groupId>
    <artifactId>dropwizard-core</artifactId>
    <version>2.1.4</version>
</dependency>
<dependency>
    <groupId>com.smoketurner</groupId>
    <artifactId>dropwizard-swagger</artifactId>
    <version>2.0.12-1</version>
</dependency>

Swagger Page After Upgrading the dropwizard version

Swagger UI Page after upgrade

I want the Swagger page should has some Authorize/ API token text box so I can provide the oauth token on the page.


问:
User and Admin Login CodeIgniter 4
`

```<code>  public function loginAuth()
  {
    $session = session();
    $userModel = new UserModel();
    $email = $this->request->getVar('email');
    $password = $this->request->getVar('password');
    $data = $userModel->where('email', $email)->first();
    if($data)
    {
      $pass = $data['password'];
      $authenticatePassword = password_verify($password, $pass);
      if($authenticatePassword)
      {
        $ses_data = [
          'id' => $data['id'],
          'name' => $data['name'],
          'email' => $data['email'],
          'isLoggedIn' => TRUE
        ];
        $session->set($ses_data);
        return redirect()->to('/profile');
      }else{
        $session->setFlashdata('msg', 'Password is incorrect.');
        return redirect()->to('/signin');
      }
    }else{
      $session->setFlashdata('msg', 'Email does not exist.');
      return redirect()->to('/signin');
    }
  }
</code>```

`

When the user logs in, the profile page will be displayed, and when the admin logs in, it will display the admin page.

Title: User and Admin Login CodeIgniter 4

Body:
`

  public function loginAuth()
  {
    $session = session();
    $userModel = new UserModel();
    $email = $this->request->getVar('email');
    $password = $this->request->getVar('password');
    $data = $userModel->where('email', $email)->first();
    if($data)
    {
      $pass = $data['password'];
      $authenticatePassword = password_verify($password, $pass);
      if($authenticatePassword)
      {
        $ses_data = [
          'id' => $data['id'],
          'name' => $data['name'],
          'email' => $data['email'],
          'isLoggedIn' => TRUE
        ];
        $session->set($ses_data);
        return redirect()->to('/profile');
      }else{
        $session->setFlashdata('msg', 'Password is incorrect.');
        return redirect()->to('/signin');
      }
    }else{
      $session->setFlashdata('msg', 'Email does not exist.');
      return redirect()->to('/signin');
    }
  }

`

When the user logs in, the profile page will be displayed, and when the admin logs in, it will display the admin page.


问:
Running Kubernetes Job using Kubernetes Pod Operator in Airflow
I have a code which we want to run in n number of Pods simulataneously. When I was running manually I used to launch Kubernetes Job by giving Parallelism and Completetions in the yaml File.

```<code>apiVersion: batch/v1
kind: Job
metadata:
  annotations:
    eks.amazonaws.com/role-arn: "arn:aws:iam::{number}:role/{access_name}"
  name: test-job
  namespace: analytics
spec:
  completions: 1000
  parallelism: 1000
  template:

</code>```

Now I want to Automate this process with Airflow, however, airflow only has KubernetesPodOperator but no JobOperator. Is there any way I can achieve the same using KubernetesPodOperator.

Limitations:

We can't use any other library due to very strict restrictions, so need to get the Job done using the default available operators in Airflow

I have tried creating N number of KubernetesPodoperator resulting in N number of Tasks. However, the number of parallelisms is dynamic and if the parallelism that we want is very large (like 100K) creating that many tasks in Airflow is not feasible. So looking for a way to achieve this using only 1 single Task

Body:
I have a code which we want to run in n number of Pods simulataneously. When I was running manually I used to launch Kubernetes Job by giving Parallelism and Completetions in the yaml File.

apiVersion: batch/v1
kind: Job
metadata:
  annotations:
    eks.amazonaws.com/role-arn: "arn:aws:iam::{number}:role/{access_name}"
  name: test-job
  namespace: analytics
spec:
  completions: 1000
  parallelism: 1000
  template:

Now I want to Automate this process with Airflow, however, airflow only has KubernetesPodOperator but no JobOperator. Is there any way I can achieve the same using KubernetesPodOperator.

Limitations:

We can't use any other library due to very strict restrictions, so need to get the Job done using the default available operators in Airflow

I have tried creating N number of KubernetesPodoperator resulting in N number of Tasks. However, the number of parallelisms is dynamic and if the parallelism that we want is very large (like 100K) creating that many tasks in Airflow is not feasible. So looking for a way to achieve this using only 1 single Task


问:
python - performance issue on db inserts
I have a script that reads a file as

```<code>with open(filepath + filename, 'r') as inFile:
   for line in inFile:
      ...
</code>```

the above can read (and process) a 7gb file with its different columns in ~3mn.
My problem is in the inserts to the database, they are too slow.
I tried mimicking the way a dataflow in SSIS performs db inserts but I didn't succeed (idk what they use too). I tried with pyodbc (classic execute and executemany but they're too slow even with fast_executemany), I also used bcpandas (the equivalent of bulk inserts with ~5K rows/s but I have also a lack of performance because I have to convert my data to a dataframe which takes  half the time of the overall process or so. I also tried printing the data and running the script from ssis to use the inserts but the python prints is not meant for that and is too slow. I tried creating a new file to read in ssis but it takes a much time as an executemany.

Is there any other way of doing this that I missed? what is the way SSIS uses to perform dataflow inserts?
my db: mssql

```<code>import pyodbc # tested executemany()
import time
import pandas as pd
import bcpandas
import sqlalchemy

# start time
startTime = time.time()

## file parameters
filepath = "C:/"
filename = "file.txt"

alchemy_eng = sqlalchemy.create_engine('mssql+pyodbc:///?odbc_connect=DRIVER={ODBC Driver 17 for SQL Server};Server=localhost;Database=test;Trusted_Connection=yes;')
bcpandas_eng = bcpandas.SqlCreds.from_engine(alchemy_eng)

### process file
counter = 0
insert_params = []

with open(filepath + filename, 'r') as infile:
  for line in inFile:
      # temp table partial structure
      col1,col2,col3,.. = line.split('|')
      if col2 == "valueA":
        col2 = None
      # couple more ..
      col3 = col3.replace(',', '.')
      # couple more ..
      # commit every million not all to avoid memory crash
      if counter == 1000000:
        df = pd.DataFrame(insert_params)
        df.columns = ['col1',...]
        bcpandas.to_sql(df, 'table1', bcpandas_eng, if_exists="append")
        # reset
        insert_params = []
        counter = 0
        break
      if counter == 1:
        cursor.execute(insert_query, insert_params)
        break
      # list of elements
      insert_params.append((col1,col2,col3,..),)
      counter += 1

# end time
endTime = time.time()
# elapsed time
print("elapsed time", endTime - startTime)
</code>```

Body:
I have a script that reads a file as

with open(filepath + filename, 'r') as inFile:
   for line in inFile:
      ...

the above can read (and process) a 7gb file with its different columns in ~3mn.
My problem is in the inserts to the database, they are too slow.
I tried mimicking the way a dataflow in SSIS performs db inserts but I didn't succeed (idk what they use too). I tried with pyodbc (classic execute and executemany but they're too slow even with fast_executemany), I also used bcpandas (the equivalent of bulk inserts with ~5K rows/s but I have also a lack of performance because I have to convert my data to a dataframe which takes  half the time of the overall process or so. I also tried printing the data and running the script from ssis to use the inserts but the python prints is not meant for that and is too slow. I tried creating a new file to read in ssis but it takes a much time as an executemany.

Is there any other way of doing this that I missed? what is the way SSIS uses to perform dataflow inserts?
my db: mssql

import pyodbc # tested executemany()
import time
import pandas as pd
import bcpandas
import sqlalchemy

# start time
startTime = time.time()

## file parameters
filepath = "C:/"
filename = "file.txt"

alchemy_eng = sqlalchemy.create_engine('mssql+pyodbc:///?odbc_connect=DRIVER={ODBC Driver 17 for SQL Server};Server=localhost;Database=test;Trusted_Connection=yes;')
bcpandas_eng = bcpandas.SqlCreds.from_engine(alchemy_eng)

### process file
counter = 0
insert_params = []

with open(filepath + filename, 'r') as infile:
  for line in inFile:
      # temp table partial structure
      col1,col2,col3,.. = line.split('|')
      if col2 == "valueA":
        col2 = None
      # couple more ..
      col3 = col3.replace(',', '.')
      # couple more ..
      # commit every million not all to avoid memory crash
      if counter == 1000000:
        df = pd.DataFrame(insert_params)
        df.columns = ['col1',...]
        bcpandas.to_sql(df, 'table1', bcpandas_eng, if_exists="append")
        # reset
        insert_params = []
        counter = 0
        break
      if counter == 1:
        cursor.execute(insert_query, insert_params)
        break
      # list of elements
      insert_params.append((col1,col2,col3,..),)
      counter += 1

# end time
endTime = time.time()
# elapsed time
print("elapsed time", endTime - startTime)


问:
how to check and display if there are changes in Repo with respect to a cloned repo using GitPython
i am creating a file mounting system for gitlab projects and want to know how to check and display if there are any changes in my Repo and update the same in my cloned repo using GitPython

I tried is_dirty() from GitPython but no success


问:
How to remove arrow head of Refresh Indicator widget in flutter?
I'm a mobile developer and now I'm making an app by flutter.
I need to pull to refresh feature in my app and I found there is a widget called refresh indicator, which is just fit for my app.
But I also found there were some problems.

The first one is it seems I can't remove arrow head style. When I saw videos or even their official website, they look like they don't have arrow head yet. But for now, it has. I suspect that widget was updated, and got the arrow like head. But what if there is someone who don't want that change?

And the second thing is it seems I can't remove its shadow as it has by default as well.

Those seem like trivial, but I want to build my app as exactly what I designed.

If there's someone to solve these issues, would you help me? I hope there's a solution with Theme or anything.

Thank you for reading, and looking forward to your reply.


问:
TypeScript issue when using as prop from Emotion js in React app
I am using Emotion js and styled (Styled component) in my React and TypeScript project.

const MyButton = styled.buttoncolor: red;;

export default MyButton;

I need to use above styled component as a button but also as an anchor link.

I used as prop for this:

```<code> < MyButton
    as="a"
    href={url}
    target="_blank"
    rel="noopener noreferrer"
    title={title}
  >
    {icon}
  </MyButton >
</code>```

But I get a TypeScript error on href attribute:

Property 'href' does not exist on type 'IntrinsicAttributes & {
css?: Interpolation; } & { theme?: Theme | undefined; as?:
ElementType | undefined; } & Props & ClassAttributes<...> &
ButtonHTMLAttributes<...> & { ...; }'. Did you mean 'ref'?ts(2322)

Body:
I am using Emotion js and styled (Styled component) in my React and TypeScript project.

const MyButton = styled.buttoncolor: red;;

export default MyButton;

I need to use above styled component as a button but also as an anchor link.

I used as prop for this:

 < MyButton
    as="a"
    href={url}
    target="_blank"
    rel="noopener noreferrer"
    title={title}
  >
    {icon}
  </MyButton >

But I get a TypeScript error on href attribute:

Property 'href' does not exist on type 'IntrinsicAttributes & {
css?: Interpolation; } & { theme?: Theme | undefined; as?:
ElementType | undefined; } & Props & ClassAttributes<...> &
ButtonHTMLAttributes<...> & { ...; }'. Did you mean 'ref'?ts(2322)


问:
sklearn fit(x,y)-how can I use a list of x as x
we ofen use fit(x,y) to train ,x is one line of df,how can I use multi line of df as x to train,and x is time based, multi line is also time based,is it possible ,how can I do it?

I just don't know how to do it


问:
Can I use the Option() constructor if I get the data from PHP on load?
Seeing other posts here, I now understand that I should not use html to build <select> input elements.

What I mean is that until now I was receiving the list of options from the server and I was building them using PHP echo (Laravel Blade syntax):

```<code><select>
   @foreach($data as $row)
      <option value="{{ $row->value }}">{{ $row->value }}</option>
   @endforeach
</select>
</code>```

But that caused issues because the values I receive from the server may include single or double quotes and it breaks everything.

Then I saw I should probably use something like the Option() constructor: https://developer.mozilla.org/en-US/docs/Web/API/HTMLOptionElement/Option

But until now I was returning the data from the server when the page was loaded, so I do not have the list of options stored in the frontend.

then should I use AJAX to call the list of options every time the page loads instead of getting it from the backend with PHP on load? Or there is another way to do it?

Body:
Seeing other posts here, I now understand that I should not use html to build <select> input elements.

What I mean is that until now I was receiving the list of options from the server and I was building them using PHP echo (Laravel Blade syntax):

<select>
   @foreach($data as $row)
      <option value="{{ $row->value }}">{{ $row->value }}</option>
   @endforeach
</select>

But that caused issues because the values I receive from the server may include single or double quotes and it breaks everything.

Then I saw I should probably use something like the Option() constructor: https://developer.mozilla.org/en-US/docs/Web/API/HTMLOptionElement/Option

But until now I was returning the data from the server when the page was loaded, so I do not have the list of options stored in the frontend.

then should I use AJAX to call the list of options every time the page loads instead of getting it from the backend with PHP on load? Or there is another way to do it?


问:
Defining multiple generic types in function argument in Rust
I am trying to use generics in Rust and have encountered
a probem when trying to define a function.

Let a method get take in a Vector where its type is generic, for example

```<code>fn get<T1: serde::Serialize, T2: serde::Serialize>(input: Vec<T>)
where T can be either T1 or T2
</code>```

I am trying to define the function properly especially I am stuck at the point where I need to define T such that it can either be T1 or T2.

Is this possible in Rust?

Body:
I am trying to use generics in Rust and have encountered
a probem when trying to define a function.

Let a method get take in a Vector where its type is generic, for example

fn get<T1: serde::Serialize, T2: serde::Serialize>(input: Vec<T>)
where T can be either T1 or T2

I am trying to define the function properly especially I am stuck at the point where I need to define T such that it can either be T1 or T2.

Is this possible in Rust?


问:
Wildcard Importing State From Existing Resources In Terraform
I manage all my DNS records in CloudFlare using Terraform with a VCS flow running in Terraform Cloud. Since we've started doing this we've grown from a few records to a couple of thousand and the time has come to break the monolith into multiple directories and workspaces so we're not exhausting upstream API call rates.

Can this be done without writing a lot of code to support this (i.e. to manually import a state file and break out each object and mv it to the new project?). Ideally I'm looking for a hands-off wildcard import command that will notice that these resources exist, are managed in a different workspace and can import their state automatically.

Does this exist?


问:
Error trying to solve OpenAI's Taxi-v3 using the Monte Carlo method
I'm trying to solve OpenAI's Taxi-v3 using the Monte Carlo method in Python. I have the core code set up as the Monte Carlo method should be, but I get an error trying to run the code.

Error on this part of the code: np.argmax(Q_table[state,:]

The error:

IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices

```<code>#!pip install gym
#!pip install gym[toy_text]

import gym
import numpy as np

env = gym.make('Taxi-v3', render_mode='ansi')

TRAINING_EPISODES = 3000 # Amount of tranings episodes
LR                = 0.1 # ALpha / Learning rate
GAMMA             = 0.9 # Gamma / Discount factor

# Initialize the Q-table to all zeros
Q_table = np.zeros((500, 6))

# Loop through the episodes
for i in range(TRAINING_EPISODES):
  # Reset the environment at the start of each episode
  state = env.reset()

  # Initialize variables for the episode
  total_reward = 0
  done = False

  # Loop until the episode is done
  while not done:

    # Choose an action using the Monte Carlo method
    action = np.argmax(Q_table[state,:] + np.random.randn(1, env.action_space.n) * (1.0 / (i + 1)))

    # Take a step in the environment using the chosen action
    next_state, reward, done, _ = env.step(action)

    # Update the Q-table
    Q_table[state, action] = reward + GAMMA * np.max(Q_table[next_state])

    # Update the total reward
    total_reward += reward

    # Move to the next state
    state = next_state

  # Print the total reward for the episode
  print("Episode {} finished with reward {}".format(i, total_reward))

# Print the final Q-table
print(Q_table)
</code>```

Body:
I'm trying to solve OpenAI's Taxi-v3 using the Monte Carlo method in Python. I have the core code set up as the Monte Carlo method should be, but I get an error trying to run the code.

Error on this part of the code: np.argmax(Q_table[state,:]

The error:

IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices

#!pip install gym
#!pip install gym[toy_text]

import gym
import numpy as np

env = gym.make('Taxi-v3', render_mode='ansi')

TRAINING_EPISODES = 3000 # Amount of tranings episodes
LR                = 0.1 # ALpha / Learning rate
GAMMA             = 0.9 # Gamma / Discount factor

# Initialize the Q-table to all zeros
Q_table = np.zeros((500, 6))

# Loop through the episodes
for i in range(TRAINING_EPISODES):
  # Reset the environment at the start of each episode
  state = env.reset()

  # Initialize variables for the episode
  total_reward = 0
  done = False

  # Loop until the episode is done
  while not done:

    # Choose an action using the Monte Carlo method
    action = np.argmax(Q_table[state,:] + np.random.randn(1, env.action_space.n) * (1.0 / (i + 1)))

    # Take a step in the environment using the chosen action
    next_state, reward, done, _ = env.step(action)

    # Update the Q-table
    Q_table[state, action] = reward + GAMMA * np.max(Q_table[next_state])

    # Update the total reward
    total_reward += reward

    # Move to the next state
    state = next_state

  # Print the total reward for the episode
  print("Episode {} finished with reward {}".format(i, total_reward))

# Print the final Q-table
print(Q_table)


问:
Show and hide app on close click without terminating in cocoa app
I am working on macos swift project in which i am using red cross button to hide window and remain open in background (app doc icon with dot below)
i am facing an issue when i reopen it from dock icon app delegate function shows that app is in foreground but not showing app in foreground
Here is my code which am using in viewContoller with NSWindowDelegate Delegate=self
Thanks in advance

```<code>
</code>```

i am trying this to hide But dont know why when i click on dock app icon app is not opening again

```<code> func windowShouldClose(_ sender: NSWindow) -> Bool {
        NSApp.hide(nil)
    return true

    }
</code>```

Body:
I am working on macos swift project in which i am using red cross button to hide window and remain open in background (app doc icon with dot below)
i am facing an issue when i reopen it from dock icon app delegate function shows that app is in foreground but not showing app in foreground
Here is my code which am using in viewContoller with NSWindowDelegate Delegate=self
Thanks in advance

i am trying this to hide But dont know why when i click on dock app icon app is not opening again

 func windowShouldClose(_ sender: NSWindow) -> Bool {
        NSApp.hide(nil)
    return true

    }


问:
Turning functions into a class in Python
Hi Im trying to get my code to now come together in a class but am at this point a bit lost. Any pointers would be appreciated!

The current functions and queries are for a IMDB data base challenge. The queries gather data from a csv file with IMDB movies. Ive created a connection to the table and functions below.

```<code>import argparse
import sqlite3
from sqlite3 import Error
import pandas as pd

# Create Database
def create_connection(db_file):
    """ create a database connection to the SQLite database
        specified by db_file
    :param db_file: database file
    :return: Connection object or None
    """
    conn = None
    try:
        conn = sqlite3.connect(db_file)
        return conn
    except Error as e:
        print(e)

    return conn

# Create table
def create_table(conn, create_table_sql):
    """ create a table from the create_table_sql statement
    :param conn: Connection object
    :param create_table_sql: a CREATE TABLE statement
    :return:
    """
    try:
        c = conn.cursor()
        c.execute(create_table_sql)
    except Error as e:
        print(e)

# Top 10 movies based on IMDB rating
def select_top10_movies(conn, table):
    """
        parameter: Query all rows in the task table.
        return: The connection object.
    """
    cur = conn.cursor()
    cur.execute(f"SELECT Series_Title, Imdb_Rating FROM {table} GROUP BY Imdb_Rating "
                f"order by Imdb_Rating DESC LIMIT 10")

    rows = cur.fetchall()

    for row in rows:
        print(row)

# Top 10 lead actors (Star1 field) based on their movies average IMDB rating
def select_top10_leadactors(conn, table):
    """
        parameter: Query all rows in the task table.
        return: The connection object.
    """
    cur = conn.cursor()
    cur.execute(f"SELECT DISTINCT Star1, AVG(Imdb_rating) AS avg_imdb FROM {table} GROUP by Star1 ORDER BY avg_imdb "
                f"DESC LIMIT 10")

    rows = cur.fetchall()

    for row in rows:
        print(row)

# Given a user input value of a year (e.g. 1990) return all the movies from that year, sorted by IMDB rating
def select_year_imdb(conn, table):
    """
    parameter: Query all rows in the task table.
    return: The connection object.
    """
    cur = conn.cursor()
    cur.execute(f"SELECT DISTINCT Series_Title, IMDB_Rating FROM {table} WHERE Released_Year like '%1990%' ORDER BY "
                f"IMDB_rating DESC")

    rows = cur.fetchall()

    for row in rows:
        print(row)

# Given a user input value of a year (e.g. 2019) determine the longest running movie of the year and return it,
# along with its runtime in hours.
def select_longest_movie(conn, table):
    """
    parameter: Query all rows in the task table.
    return: The connection object.
    """
    cur = conn.cursor()
    cur.execute(f"SELECT DISTINCT Series_Title, Runtime FROM {table} WHERE Released_Year like '%2019%' ORDER BY "
                f"Runtime DESC LIMIT 1 OFFSET 2")

    rows = cur.fetchall()

    for row in rows:
        print(row)

# Determine the year that had the highest grossing movies and return it, along with the average gross of movies that
# year.
def select_highest_grossing_movie(conn, table):
    """
    parameter: Query all rows in the task table.
    return: The connection object.
    """
    cur = conn.cursor()
    cur.execute(f"SELECT Released_Year, AVG(Gross) FROM {table} GROUP BY Released_Year ORDER BY AVG(Gross) "
                f"DESC LIMIT 1")

    rows = cur.fetchall()

    for row in rows:
        print(row)

# Given a user input of part of a movie name (e.g. lord of the rings) return all matching movies and their IMDB rating
def find_movie(conn, table):
    """
    parameter: Query all rows in the task table.
    return: The connection object.
    """
    cur = conn.cursor()
    cur.execute(f"SELECT DISTINCT Series_Title, IMDB_Rating FROM {table} WHERE Series_Title like '%lord of the "
                f"rings%' ORDER BY "
                f"IMDB_Rating DESC")

    rows = cur.fetchall()

    for row in rows:
        print(row)

def main():
    # Read in command line arguments
    parser = argparse.ArgumentParser()
    parser.add_argument('--database', type=str, required=True)
    parser.add_argument('--table', type=str, required=True)
    parser.add_argument('--query', type=str, required=False)
    parser.add_argument('--seed', type=bool, required=False, default=False)
    parser.add_argument('--movie', type=str, required=False, default=None)
    parser.add_argument('--year', type=str, required=False, default=None)
    parser.add_argument('--min', type=int, required=False, default=None)
    args = parser.parse_args()
    database = args.database

    # Create database connection
    conn = create_connection(database)

    # 2 - 3: CSV import into database
    if args.seed:
        users = pd.read_csv('imdb_top_1000.csv')
        users.to_sql(args.table, conn, if_exists='append', index=False)
    else:
        pass

    # 4 - Queries
    query = args.query

    if query == "top_10_movies":
        print("Top 10 movies based on IMDB rating:")
        select_top10_movies(conn, args.table)
    elif query == "top_10_actors":
        print("Top 10 lead actors based on their movies average IMDB rating:")
        select_top10_leadactors(conn, args.table)
    elif query == "year":
        if args.movie is None:
            print("Error: Sorry buddy I need a --movie input please")
        select_year_imdb(conn, args.table)
    elif query == "longest_movie":
        if args.movie is None:
            print("Error: Sorry buddy I need a --movie input please")
        select_longest_movie(conn, args.table)
    elif query == "gross_year":
        print("The highest grossing movies for the year: ")
        select_highest_grossing_movie(conn, args.table)
    elif query == "find_movie":
        if args.movie is None:
            print("Error: Sorry buddy I need a --movie input please")
        print("Matching movies and their IMDB rating")
        find_movie(conn, args.table)

    else:
        print("Error: Unknown query")
    exit(1)

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

Body:
Hi Im trying to get my code to now come together in a class but am at this point a bit lost. Any pointers would be appreciated!

The current functions and queries are for a IMDB data base challenge. The queries gather data from a csv file with IMDB movies. Ive created a connection to the table and functions below.

import argparse
import sqlite3
from sqlite3 import Error
import pandas as pd

# Create Database
def create_connection(db_file):
    """ create a database connection to the SQLite database
        specified by db_file
    :param db_file: database file
    :return: Connection object or None
    """
    conn = None
    try:
        conn = sqlite3.connect(db_file)
        return conn
    except Error as e:
        print(e)

    return conn

# Create table
def create_table(conn, create_table_sql):
    """ create a table from the create_table_sql statement
    :param conn: Connection object
    :param create_table_sql: a CREATE TABLE statement
    :return:
    """
    try:
        c = conn.cursor()
        c.execute(create_table_sql)
    except Error as e:
        print(e)

# Top 10 movies based on IMDB rating
def select_top10_movies(conn, table):
    """
        parameter: Query all rows in the task table.
        return: The connection object.
    """
    cur = conn.cursor()
    cur.execute(f"SELECT Series_Title, Imdb_Rating FROM {table} GROUP BY Imdb_Rating "
                f"order by Imdb_Rating DESC LIMIT 10")

    rows = cur.fetchall()

    for row in rows:
        print(row)

# Top 10 lead actors (Star1 field) based on their movies average IMDB rating
def select_top10_leadactors(conn, table):
    """
        parameter: Query all rows in the task table.
        return: The connection object.
    """
    cur = conn.cursor()
    cur.execute(f"SELECT DISTINCT Star1, AVG(Imdb_rating) AS avg_imdb FROM {table} GROUP by Star1 ORDER BY avg_imdb "
                f"DESC LIMIT 10")

    rows = cur.fetchall()

    for row in rows:
        print(row)

# Given a user input value of a year (e.g. 1990) return all the movies from that year, sorted by IMDB rating
def select_year_imdb(conn, table):
    """
    parameter: Query all rows in the task table.
    return: The connection object.
    """
    cur = conn.cursor()
    cur.execute(f"SELECT DISTINCT Series_Title, IMDB_Rating FROM {table} WHERE Released_Year like '%1990%' ORDER BY "
                f"IMDB_rating DESC")

    rows = cur.fetchall()

    for row in rows:
        print(row)

# Given a user input value of a year (e.g. 2019) determine the longest running movie of the year and return it,
# along with its runtime in hours.
def select_longest_movie(conn, table):
    """
    parameter: Query all rows in the task table.
    return: The connection object.
    """
    cur = conn.cursor()
    cur.execute(f"SELECT DISTINCT Series_Title, Runtime FROM {table} WHERE Released_Year like '%2019%' ORDER BY "
                f"Runtime DESC LIMIT 1 OFFSET 2")

    rows = cur.fetchall()

    for row in rows:
        print(row)

# Determine the year that had the highest grossing movies and return it, along with the average gross of movies that
# year.
def select_highest_grossing_movie(conn, table):
    """
    parameter: Query all rows in the task table.
    return: The connection object.
    """
    cur = conn.cursor()
    cur.execute(f"SELECT Released_Year, AVG(Gross) FROM {table} GROUP BY Released_Year ORDER BY AVG(Gross) "
                f"DESC LIMIT 1")

    rows = cur.fetchall()

    for row in rows:
        print(row)

# Given a user input of part of a movie name (e.g. lord of the rings) return all matching movies and their IMDB rating
def find_movie(conn, table):
    """
    parameter: Query all rows in the task table.
    return: The connection object.
    """
    cur = conn.cursor()
    cur.execute(f"SELECT DISTINCT Series_Title, IMDB_Rating FROM {table} WHERE Series_Title like '%lord of the "
                f"rings%' ORDER BY "
                f"IMDB_Rating DESC")

    rows = cur.fetchall()

    for row in rows:
        print(row)

def main():
    # Read in command line arguments
    parser = argparse.ArgumentParser()
    parser.add_argument('--database', type=str, required=True)
    parser.add_argument('--table', type=str, required=True)
    parser.add_argument('--query', type=str, required=False)
    parser.add_argument('--seed', type=bool, required=False, default=False)
    parser.add_argument('--movie', type=str, required=False, default=None)
    parser.add_argument('--year', type=str, required=False, default=None)
    parser.add_argument('--min', type=int, required=False, default=None)
    args = parser.parse_args()
    database = args.database

    # Create database connection
    conn = create_connection(database)

    # 2 - 3: CSV import into database
    if args.seed:
        users = pd.read_csv('imdb_top_1000.csv')
        users.to_sql(args.table, conn, if_exists='append', index=False)
    else:
        pass

    # 4 - Queries
    query = args.query

    if query == "top_10_movies":
        print("Top 10 movies based on IMDB rating:")
        select_top10_movies(conn, args.table)
    elif query == "top_10_actors":
        print("Top 10 lead actors based on their movies average IMDB rating:")
        select_top10_leadactors(conn, args.table)
    elif query == "year":
        if args.movie is None:
            print("Error: Sorry buddy I need a --movie input please")
        select_year_imdb(conn, args.table)
    elif query == "longest_movie":
        if args.movie is None:
            print("Error: Sorry buddy I need a --movie input please")
        select_longest_movie(conn, args.table)
    elif query == "gross_year":
        print("The highest grossing movies for the year: ")
        select_highest_grossing_movie(conn, args.table)
    elif query == "find_movie":
        if args.movie is None:
            print("Error: Sorry buddy I need a --movie input please")
        print("Matching movies and their IMDB rating")
        find_movie(conn, args.table)

    else:
        print("Error: Unknown query")
    exit(1)

if __name__ == '__main__':
    main()


问:
How do I stub window.print() call from an iframe window?
I've a reactjs form, and on Save, it adds an iframe to the page.
The iframe src page has window.print() in its onload.

This is my code to Save the form.

```<code>cy.get('[test-id="save-patient-bill"]').trigger("click");

cy.wait('@saveForm').then(xhr =>{
     expect(xhr.response.statusCode).to.eq(201);
});
</code>```

When it runs the above code (in headed mode), the print prompt appears and waits to get it closed before moving to the rest of the tests.

How do I stub it?

Thanks.

Sample code to test.
cypress.html

```<code><!doctype html>
<html>
    <head>
        <script>
            function save(){
                document.getElementById('iframe').src='iframe.html';
            }
        </script>

    </head>
<body>
<h1>This is heading</h1>
<iframe id="iframe"></iframe>
<button onclick="save()">Save</button>
</body>
</html>
</code>```

iframe.html

```<code><!doctype html>
<html>
<body onload="window.print();">
<h1>This is an iframe</h1>
 <button onclick="window.print()">Print</button>
</body>
</html>
</code>```

Body:
I've a reactjs form, and on Save, it adds an iframe to the page.
The iframe src page has window.print() in its onload.

This is my code to Save the form.

cy.get('[test-id="save-patient-bill"]').trigger("click");

cy.wait('@saveForm').then(xhr =>{
     expect(xhr.response.statusCode).to.eq(201);
});

When it runs the above code (in headed mode), the print prompt appears and waits to get it closed before moving to the rest of the tests.

How do I stub it?

Thanks.

Sample code to test.
cypress.html

<!doctype html>

This is heading

<button onclick="save()">Save</button>

iframe.html

<!doctype html>

This is an iframe

 <button onclick="window.print()">Print</button>


问:
how can i Know if dhcp is enabled for ETH1 at runtime
Im logged to an Eaton XC-303 PLC, via codesys 3.5. I can run a plc shell command isdhcpenabled 1, and get ETH1: DHCP disabled.

I would like to do it at runtime via the iec code.

So, is there a way to execute plc shell command via iec code?

the executecommand2 object only works for Linux command...

the SysSockGetNextAdapterInfo dosent recognize the DHCP server.

A common Linux command will not do the job, since the requested command
Is an internal to the Eaton PLC. so configuring the sysProc file will not do.

That is the reazon why the executeCommand2 can not show the data.

I did find an Eaton liberary that should do the work (EA_Network 3.5.4.0), yet the existing function 'isDhcpEnabled' allways return false.
I will check it again today


问:
Jupyter Notebook external authentication for trino connection
I am connecting to a starburst server to perform a SQL query through the library "trino" in Python. I am doing this in a jupyter notebook and everytime I run a query I have to manually click on the URL that appears to open the a new tab in my browser to authenticate. A couple of months ago this tab was opened automatically by the notebook(without the necessity of me clicking on the URL) but then I updated something and now I always have to click on the URL to authenticate. Do you know how to let the jupyter notebook authenticate automatically?


问:
Changing the dupplicated name of the sequence generator in already existing entities
I had a JPA-entity Bar in which a sequence generator was declared com.foo.IdGenerator. Then I copied this entity, corrected it a bit and created a second Buzz entity. The problem is that I forgot to change the name of the generator in the second entity and now they duplicate each other in both entities. There were no problems with the work of the application. But in the log the following errors are issued

[WARN][main] 05 Dec 2022 09:09:09,992 [o.h.b.i.InFlightMetadataCollectorImpl] 242093 HHH000069: Duplicate generator name com.foo.IdGenerator

Now I want to rename these sequences to com.foo.bar.IdGenerator and com.foo.bar.Id Generator.

Will this somehow affect the work of my application with Hibernate and the database?

I only want to change the name of the sequence generator, not the name of the sequences themselves. The sequence names for both entities are unique.

```<code>@Entity
@Table(name = "Bar")
public class Bar {
    private static final String SEQUENCE_NAME = "bar_sequence";
    private static final String SEQUENCE_GENERATOR_NAME = "com.foo.IdGenerator"; // I want to change it to com.foo.bar.IdGenerator

    @Id
    @GeneratedValue(generator = SEQUENCE_GENERATOR_NAME, strategy = GenerationType.SEQUENCE)
    @SequenceGenerator(name = SEQUENCE_GENERATOR_NAME, sequenceName = SEQUENCE_NAME, allocationSize = 1)
    @Column(name = "id", nullable = false)
    private Long id;

    ...
}

@Entity
@Table(name = "Buzz")
public class Buzz {
    private static final String SEQUENCE_NAME = "buzz_sequence";
    private static final String SEQUENCE_GENERATOR_NAME = "com.foo.IdGenerator"; // I want to change it to com.foo.buzz.IdGenerator

    @Id
    @GeneratedValue(generator = SEQUENCE_GENERATOR_NAME, strategy = GenerationType.SEQUENCE)
    @SequenceGenerator(name = SEQUENCE_GENERATOR_NAME, sequenceName = SEQUENCE_NAME, allocationSize = 1)
    @Column(name = "id", nullable = false)
    private Long id;

    ...
}
</code>```

Body:
I had a JPA-entity Bar in which a sequence generator was declared com.foo.IdGenerator. Then I copied this entity, corrected it a bit and created a second Buzz entity. The problem is that I forgot to change the name of the generator in the second entity and now they duplicate each other in both entities. There were no problems with the work of the application. But in the log the following errors are issued

[WARN][main] 05 Dec 2022 09:09:09,992 [o.h.b.i.InFlightMetadataCollectorImpl] 242093 HHH000069: Duplicate generator name com.foo.IdGenerator

Now I want to rename these sequences to com.foo.bar.IdGenerator and com.foo.bar.Id Generator.

Will this somehow affect the work of my application with Hibernate and the database?

I only want to change the name of the sequence generator, not the name of the sequences themselves. The sequence names for both entities are unique.

@Entity
@Table(name = "Bar")
public class Bar {
    private static final String SEQUENCE_NAME = "bar_sequence";
    private static final String SEQUENCE_GENERATOR_NAME = "com.foo.IdGenerator"; // I want to change it to com.foo.bar.IdGenerator

    @Id
    @GeneratedValue(generator = SEQUENCE_GENERATOR_NAME, strategy = GenerationType.SEQUENCE)
    @SequenceGenerator(name = SEQUENCE_GENERATOR_NAME, sequenceName = SEQUENCE_NAME, allocationSize = 1)
    @Column(name = "id", nullable = false)
    private Long id;

    ...
}

@Entity
@Table(name = "Buzz")
public class Buzz {
    private static final String SEQUENCE_NAME = "buzz_sequence";
    private static final String SEQUENCE_GENERATOR_NAME = "com.foo.IdGenerator"; // I want to change it to com.foo.buzz.IdGenerator

    @Id
    @GeneratedValue(generator = SEQUENCE_GENERATOR_NAME, strategy = GenerationType.SEQUENCE)
    @SequenceGenerator(name = SEQUENCE_GENERATOR_NAME, sequenceName = SEQUENCE_NAME, allocationSize = 1)
    @Column(name = "id", nullable = false)
    private Long id;

    ...
}


问:
How do I visualize NetCDF files in Python using the Django framework?
How to visualize the netCDF files in python using Django Framework? I tried using Folium map, but it doesn't support JavaScript. JavaScript is required to interact with map, like on-click function, pagination, etc.

While using JavaScript, I need to go with conversion of netCDF File to GEOJSON file. But, it takes lots of storage space. Is there any alternate method to proceed with my requirement?


问:
HTTP 403 error on creating a conda environment using conda create -y -n pydata-book python=3.10
Conda Version is 22.11.1. I have tried following but it didn't work:
 conda config --set ssl_verify false**

**Error Message: **

'''
*CondaHTTPError: HTTP 403 FORBIDDEN for url https://conda.anaconda.org/conda-forge/win-64/libffi-3.4.2-h8ffe710_5.tar.bz2
Elapsed: 00:00.463337
An HTTP error occurred when trying to retrieve this URL.
HTTP errors are often intermittent, and a simple retry will get you on your way.
*'''


问:
How can I authorize AWS Cognito user when using In-app Purchase on IOS
I'm testing In-app Purchase (IAP) in my App with IOS's sandbox tester.
My app is using AWS Cognito to signup and login.

Step 1: User A successfully paid for an auto-renewable subscription.

Step 2: User B login to the App with the same IOS device.

Actual Result: User B is using the subscription that paid by user A.

I expect that User B cannot using the subscription that User A has paid.

How I can do that? Thanks in advance!


问:
FormulasNot updating - Apache poi "shiftCellsRight"/"shiftCellsLeft" operation
We are working on algorithm (JAVA) where it involves moving the row cells [ "shiftCellsRight"/"shiftCellsLeft"] (not workbook columns). After this operation the formulas depending on these cell are not getting updated.

Is this expected? Any work arounds?

Though "shiftColumns" operation works, it limits the purpose of algorithm.

Thanks!!


问:
How to safely cast array of char to type
I got some data coming in over an RS485 line. I store that data in a vector<char> and now I need to cast that to several types. Currently that is done by the following function:

template<typename To>
static std::size_t parseBinaryToType(const char* input, To& destination) {
    destination = *(reinterpret_cast<const To*>(input)); //FIXME
    return sizeof(destination);
}
//EXAMPLE
enum class SomeEnum: uint16_t {
  BAR,
  BAZ
}

class Foo {
  SomeEnum m_Enum;
  uint8_t m_Int;
  bool m_Bool;
public:
  static Foo deserializeFrom(const char* const buffer) {
    Foo result;
    offset = 0;
    offset+= parseBinaryToType(buffer + offset, result.m_Enum);
    offset+= parseBinaryToType(buffer + offset, result.m_Int);
    offset+= parseBinaryToType(buffer + offset, result.m_Bool);
    return result;
  }
}
```

But I find this very unsafe. Especially due to the reinterpret_cast and the fact that it doesn't check for endianness.. Is there a safe way to do this in cpp?

Note that I'm only trying to parse types like bool or int, not whole structs.

Body:
I got some data coming in over an RS485 line. I store that data in a vector<char> and now I need to cast that to several types. Currently that is done by the following function:

template<typename To>
static std::size_t parseBinaryToType(const char* input, To& destination) {
    destination = *(reinterpret_cast<const To*>(input)); //FIXME
    return sizeof(destination);
}
//EXAMPLE
enum class SomeEnum: uint16_t {
  BAR,
  BAZ
}

class Foo {
  SomeEnum m_Enum;
  uint8_t m_Int;
  bool m_Bool;
public:
  static Foo deserializeFrom(const char* const buffer) {
    Foo result;
    offset = 0;
    offset+= parseBinaryToType(buffer + offset, result.m_Enum);
    offset+= parseBinaryToType(buffer + offset, result.m_Int);
    offset+= parseBinaryToType(buffer + offset, result.m_Bool);
    return result;
  }
}

But I find this very unsafe. Especially due to the reinterpret_cast and the fact that it doesn't check for endianness.. Is there a safe way to do this in cpp?

Note that I'm only trying to parse types like bool or int, not whole structs.


问:
Snakemake rule does not regenerate output after input has changed
My Snakemake workflow includes rule compse:

```<code>rule compose:
input:
    manuscripts=[
        str(a)
        for a in Path(".").glob(f"./{config['series']}_*_*_*/tei/*.xml")
        if not (config["publication"] in str(a))
    ],
    assets=[str(a) for a in Path(".").glob(f"{config['series']}_*/assets/*.*")],
    script=expand("{dir}/other/compose.xsl", dir=config["transform"]),
output:
    touch("composed.flag"),
params:
    publication=config["publication"],
    saxon=config["saxon"],
run:
    SOMECODE (see below)
</code>```

It takes some xml files, images and a script and outputs a flag file that documents that it ran sucessfully. The input files are not generated by another rule but pre-exist the workflow, thus you could say the rule is isolated - it does not depend on others and does not produce output that other rules depend on.

When I call the rule from the cli like snakemake -p -c1 compose --config workdir="/home/lector/manuscripts/ends-of-humanities/eoh_01_mein_eoh" it generates the expected output.

When I change one of the inputs, I expect the rule to run again because the timestamp of these inputs is younger than the flag file. However, Snakemake does not run it again and claims:

```<code>Config file config/config.yaml is extended by additional config specified via the command line.
Building DAG of jobs...
Nothing to be done (all requested files are present and up to date).
</code>```

Even if I add the -f flag to force rerun it stops without regenerating the output.

If I compare the timestamp of the changed input file with the flag file it is nevertheless true that the input is younger than the output, so why does Snakemake pretend otherwise and refuses to run the rule?

code of the run: directive:

```<code>run:
    # Create publication, tei and assets folder
    (Path(".") / "tei/media/").mkdir(parents=True, exist_ok=True)
    (Path(".") / "assets/").mkdir(parents=True, exist_ok=True)
    # Create dummy docx file
    shell("touch {params.publication}.docx")
    # Copy article assets to volume assets / tei/media (cp without loop causes exception)
    for f in input.assets:
        shell("cp {f} assets/")
    shell("cp -rf assets/* tei/media/")
    # Copy transformation script
    shell("cp -a {input.script} tei/compose.xsl")
    # Generate list of manuscript files in intermediate xml file
    shell("echo '<collection/>' > tei/manuscripts.xml")
    for man in input.manuscripts:
        m = man.split("/")[-1].split(".")[0]
        shell(
            "xmlstarlet ed -L -s '/collection' -t elem -n 'doc' -v '' -i '/collection/doc[last()]' -t attr -n 'href' -v '../{m}/tei/{m}.xml' tei/manuscripts.xml"
        )
    # Transform collection file to final TEI-XML manuscript
    shell(
        "java -jar {params.saxon} -o:tei/{params.publication}.xml tei/manuscripts.xml tei/compose.xsl projectfolder={params.publication}"
    )
    # Clean-Up publication folder
    shell("rm -f tei/manuscripts.xml tei/compose.xsl")
</code>```

Body:
My Snakemake workflow includes rule compse:

rule compose:
input:
    manuscripts=[
        str(a)
        for a in Path(".").glob(f"./{config['series']}_*_*_*/tei/*.xml")
        if not (config["publication"] in str(a))
    ],
    assets=[str(a) for a in Path(".").glob(f"{config['series']}_*/assets/*.*")],
    script=expand("{dir}/other/compose.xsl", dir=config["transform"]),
output:
    touch("composed.flag"),
params:
    publication=config["publication"],
    saxon=config["saxon"],
run:
    SOMECODE (see below)

It takes some xml files, images and a script and outputs a flag file that documents that it ran sucessfully. The input files are not generated by another rule but pre-exist the workflow, thus you could say the rule is isolated - it does not depend on others and does not produce output that other rules depend on.

When I call the rule from the cli like snakemake -p -c1 compose --config workdir="/home/lector/manuscripts/ends-of-humanities/eoh_01_mein_eoh" it generates the expected output.

When I change one of the inputs, I expect the rule to run again because the timestamp of these inputs is younger than the flag file. However, Snakemake does not run it again and claims:

Config file config/config.yaml is extended by additional config specified via the command line.
Building DAG of jobs...
Nothing to be done (all requested files are present and up to date).

Even if I add the -f flag to force rerun it stops without regenerating the output.

If I compare the timestamp of the changed input file with the flag file it is nevertheless true that the input is younger than the output, so why does Snakemake pretend otherwise and refuses to run the rule?

code of the run: directive:

run:
    # Create publication, tei and assets folder
    (Path(".") / "tei/media/").mkdir(parents=True, exist_ok=True)
    (Path(".") / "assets/").mkdir(parents=True, exist_ok=True)
    # Create dummy docx file
    shell("touch {params.publication}.docx")
    # Copy article assets to volume assets / tei/media (cp without loop causes exception)
    for f in input.assets:
        shell("cp {f} assets/")
    shell("cp -rf assets/* tei/media/")
    # Copy transformation script
    shell("cp -a {input.script} tei/compose.xsl")
    # Generate list of manuscript files in intermediate xml file
    shell("echo '<collection/>' > tei/manuscripts.xml")
    for man in input.manuscripts:
        m = man.split("/")[-1].split(".")[0]
        shell(
            "xmlstarlet ed -L -s '/collection' -t elem -n 'doc' -v '' -i '/collection/doc[last()]' -t attr -n 'href' -v '../{m}/tei/{m}.xml' tei/manuscripts.xml"
        )
    # Transform collection file to final TEI-XML manuscript
    shell(
        "java -jar {params.saxon} -o:tei/{params.publication}.xml tei/manuscripts.xml tei/compose.xsl projectfolder={params.publication}"
    )
    # Clean-Up publication folder
    shell("rm -f tei/manuscripts.xml tei/compose.xsl")


问:
how to do type casting of DateType() column
I want to know how to do type casting date field, if i have date field like this(eg-12/12/2022) using pyspark data frame.
which type of type casting i need to do using pyspark</p>


问:
How to Truncate input stream in transformers pipline

I want to use the BERT model implemented via the Hugginface library. I use pipeline to do the job. here is a very sample code of how I do it.
```<code>from transformers import BertForMaskedLM, BertTokenizer, pipeline
model = BertForMaskedLM.from_pretrained('bert-base-uncased')
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
fill_sentence = pipeline('fill-mask', model=model, tokenizer=tokenizer)
long_sentence = ['This is very [MASK] sentence. This is very very long sentence.' * 40]
fill_sentence(long_sentence)
</code>```

The problem is that I get the following error in the very long sentences:

```<code>RuntimeError: The size of tensor a (522) must match the size of tensor b (512) at non-singleton dimension 1
</code>```

I know about the model max length and that I have to truncate long sentences. I am familiar with the concept but I can't seem to figure out how to truncate input data using the pipeline.

PS1: First I tried to create a Tokenizer with truncate set to True, but apparently truncate is determined when calling the tokenizer and not when initializing it. I know using the code below will truncate the input:

```<code>tokenizer(long_sentence, truncate=True, max_length=512)
</code>```

but I don't want to work directly with the model and tokenizer. my goal is to keep using the pipeline but I am not sure how to pass tokenizer call variables to the pipeline.

ps2: I have seen the following StackOverflow question and its answers but it doesn't work for me. I don't know if it is the old version or something I am doing wrong.

question link

I have been stuck on this problem for a week now and I have read the Hugginface documentation and searched for my answer on the web with no luck. so I really appreciate it if you could help me.
Thanks

Body:
I want to use the BERT model implemented via the Hugginface library. I use pipeline to do the job. here is a very sample code of how I do it.

from transformers import BertForMaskedLM, BertTokenizer, pipeline
model = BertForMaskedLM.from_pretrained('bert-base-uncased')
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
fill_sentence = pipeline('fill-mask', model=model, tokenizer=tokenizer)
long_sentence = ['This is very [MASK] sentence. This is very very long sentence.' * 40]
fill_sentence(long_sentence)

The problem is that I get the following error in the very long sentences:

RuntimeError: The size of tensor a (522) must match the size of tensor b (512) at non-singleton dimension 1

I know about the model max length and that I have to truncate long sentences. I am familiar with the concept but I can't seem to figure out how to truncate input data using the pipeline.

PS1: First I tried to create a Tokenizer with truncate set to True, but apparently truncate is determined when calling the tokenizer and not when initializing it. I know using the code below will truncate the input:

tokenizer(long_sentence, truncate=True, max_length=512)

but I don't want to work directly with the model and tokenizer. my goal is to keep using the pipeline but I am not sure how to pass tokenizer call variables to the pipeline.

ps2: I have seen the following StackOverflow question and its answers but it doesn't work for me. I don't know if it is the old version or something I am doing wrong.

question link

I have been stuck on this problem for a week now and I have read the Hugginface documentation and searched for my answer on the web with no luck. so I really appreciate it if you could help me.
Thanks