问:
discord.py throws error with on_member_join
I'm trying to make an on_member_join function for a discord.py bot that sends a welcome message when someone joins my server.

This is the code I have for the function:

```<code>@client.event
async def on_member_join(member):
    print(f"{member.name} JOINED!")
    welkomChannel = client.get_channel(channel id)
    await welkomChannel.send(f"Hello!")
</code>```

When I join the server with an alt account, it throws this error: discord.errors.PrivilegedIntentsRequired. I went to discord.com/developers/applications and turned on the SERVER MEMBERS intent;

And I added these lines to my code after the imports:

```<code>intents = discord.Intents.default()
intents.members = True

client = commands.Bot(command_prefix="!", intents=intents)
</code>```

So if I have enabled it on the website and I put the intents in the code, why does it still throw the error?

答:
intents = discord.Intents()
intents.members = True
```

intents.Default basically includes presence, member, so you need to activate presence intents or change to Intents().

docs

Body:
I'm trying to make an on_member_join function for a discord.py bot that sends a welcome message when someone joins my server.

This is the code I have for the function:

@client.event
async def on_member_join(member):
    print(f"{member.name} JOINED!")
    welkomChannel = client.get_channel(channel id)
    await welkomChannel.send(f"Hello!")

When I join the server with an alt account, it throws this error: discord.errors.PrivilegedIntentsRequired. I went to discord.com/developers/applications and turned on the SERVER MEMBERS intent;

And I added these lines to my code after the imports:

intents = discord.Intents.default()
intents.members = True

client = commands.Bot(command_prefix="!", intents=intents)

So if I have enabled it on the website and I put the intents in the code, why does it still throw the error?

Body:
intents = discord.Intents()
intents.members = True

intents.Default basically includes presence, member, so you need to activate presence intents or change to Intents().

docs


来源: stackexchange

问:
Material-ui drawer width issue
I'm facing an issue with material-ui drawer. I've changed the width of the drawer container which causes a a problem . The drawer remains a little inside the page and visible but I don't want to make it visible on the page while I haven't clicked the button. It might be having an issue with the transform attribute now.

So I changed it to transform: translate(350px, 0px) but then I'm getting another issue, that is if I am clicking the button the drawer is not showing up. Any help on this thing ??

I have got the solution and edited the code.

I've created a Demo here => Have a look

Also shared the code below:

index.js

```<code>import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import Drawer from 'material-ui/Drawer';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';

class App extends Component {
  constructor() {
    super();
    this.state = {
      openDrawer: false
    };
  }

  toggleDrawer() {
    this.setState({
      openDrawer: !this.state.openDrawer
    });
  }

  render() {
    return (
      <MuiThemeProvider>
      <div>
        <button onClick={this.toggleDrawer.bind(this)}> Toggle Drawer</button>
        <Drawer
                  open={this.state.openDrawer}
                  containerClassName={!this.state.openDrawer? "hide-drawer": "show-drawer" }
                  openSecondary={true}
                  docked={true}
                >
                    <div className="drawer-title-div">
                        <h4 className="drawer-title-text">It's my drawer</h4>
                    </div>
                </Drawer>
      </div>
      </MuiThemeProvider>
    );
  }
}

render(<App />, document.getElementById('root'));
</code>```

style.css

```<code>h1, p {

font-family: Lato;
}

.show-drawer {
  top: 47px !important;
  text-align: left !important;
  width: 80% !important;
  transform: translate(0%, 0px) !important;
}

.hide-drawer {
  top: 47px !important;
  text-align: left !important;
  width: 80% !important;
  transform: translate(100%, 0px) !important;
}

/* .drawer-side-drawer:focus {
  top: 47px !important;
  text-align: left !important;
  width: 350px !important;
  transform: translate(0px, 0px) !important;
} */

.drawer-title-div {
  display: inline-block;
  width: 100%;
  background: #F2F8FB;
  box-shadow: 0 1px 3px 0 rgba(0,0,0,0.24);
}

.drawer-title-text {
  display: inline-block;
  margin-left: 16px;
  margin-top: 16px;
  margin-bottom: 16px;
  color: #484848;
  font-family: Muli;
  font-size: 16px;
  font-weight: 600;
}
</code>```

答:
I had the same problem.

you just have to add the PaperProps to your drawer

ContentLicense: CC BY-SA 3.0

Title: Material-ui drawer width issue

Body:
I'm facing an issue with material-ui drawer. I've changed the width of the drawer container which causes a a problem . The drawer remains a little inside the page and visible but I don't want to make it visible on the page while I haven't clicked the button. It might be having an issue with the transform attribute now.

So I changed it to transform: translate(350px, 0px) but then I'm getting another issue, that is if I am clicking the button the drawer is not showing up. Any help on this thing ??

I have got the solution and edited the code.

I've created a Demo here => Have a look

Also shared the code below:

index.js

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import Drawer from 'material-ui/Drawer';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';

class App extends Component {
  constructor() {
    super();
    this.state = {
      openDrawer: false
    };
  }

  toggleDrawer() {
    this.setState({
      openDrawer: !this.state.openDrawer
    });
  }

  render() {
    return (
      <MuiThemeProvider>

        <button onClick={this.toggleDrawer.bind(this)}> Toggle Drawer</button>
        <Drawer
                  open={this.state.openDrawer}
                  containerClassName={!this.state.openDrawer? "hide-drawer": "show-drawer" }
                  openSecondary={true}
                  docked={true}
                >

It's my drawer

                </Drawer>

      </MuiThemeProvider>
    );
  }
}

render(<App />, document.getElementById('root'));

style.css

h1, p {

font-family: Lato;
}

.show-drawer {
  top: 47px !important;
  text-align: left !important;
  width: 80% !important;
  transform: translate(0%, 0px) !important;
}

.hide-drawer {
  top: 47px !important;
  text-align: left !important;
  width: 80% !important;
  transform: translate(100%, 0px) !important;
}

/* .drawer-side-drawer:focus {
  top: 47px !important;
  text-align: left !important;
  width: 350px !important;
  transform: translate(0px, 0px) !important;
} */

.drawer-title-div {
  display: inline-block;
  width: 100%;
  background: #F2F8FB;
  box-shadow: 0 1px 3px 0 rgba(0,0,0,0.24);
}

.drawer-title-text {
  display: inline-block;
  margin-left: 16px;
  margin-top: 16px;
  margin-bottom: 16px;
  color: #484848;
  font-family: Muli;
  font-size: 16px;
  font-weight: 600;
}

ContentLicense: CC BY-SA 4.0


问:
Toggling Chrome Pages on Mac
On Windows, each browser page was a separate application. This made it very easy to flexibly toggle between a specific pair of Chrome browser pages with Ctrl (Cmd) + Tab. I was wondering if there was a way to set this up on Mac. As of now, cmd + ` cycles between ALL pages, which is not what I want.

For example, let's say I have 4 (separate) Chrome pages open: A, B, C, and D. Pages A and B correspond to one task and C and D to another. I want to be able to toggle between pages A and B for a while (Ctrl-Tab). Then, afterwards, without closing pages A and B, I want to Ctrl-Tab between pages C and D for a while. Windows made this process very easy: I'd just have to access the two pages I want to toggle between once, and ctrl-tab simply allowed switching between the two pages since each page was a separate application.

Is there a way I can do or set up a way to do this on Mac?

答:
There is not a feature which could set the behavior you described above, the Command + Tab, Command and press Shift+ Tab and Command + ` are the only shortcut currently available for this kind of tasks. I have searched in the apple support also but I was not able to find anything that may help

cheers

Title: Toggling Chrome Pages on Mac


问:
Hibernate with Maven and Java 11 gives org.hibernate.persister.entity.SingleTableEntityPersister
I am struggling building a simple Hibernate with or without JPA, Maven and Java 11 project. This is a javafX project and shouldn't hinder using Hibernate.

I couldn't find any project example with the latest versions and I could not use older version because it would give the same error.

Here is the dependency tree of my pom.xml.

```<code><dependencies>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>11.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-fxml</artifactId>
            <version>11.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-web</artifactId>
            <version>11.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.controlsfx</groupId>
            <artifactId>controlsfx</artifactId>
            <version>11.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.dlsc.formsfx</groupId>
            <artifactId>formsfx-core</artifactId>
            <version>11.3.2</version>
            <exclusions>
                <exclusion>
                    <groupId>org.openjfx</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>net.synedra</groupId>
            <artifactId>validatorfx</artifactId>
            <version>0.1.13</version>
            <exclusions>
                <exclusion>
                    <groupId>org.openjfx</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.kordamp.ikonli</groupId>
            <artifactId>ikonli-javafx</artifactId>
            <version>12.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.kordamp.bootstrapfx</groupId>
            <artifactId>bootstrapfx-core</artifactId>
            <version>0.4.0</version>
        </dependency>
        <dependency>
            <groupId>eu.hansolo</groupId>
            <artifactId>tilesfx</artifactId>
            <version>11.48</version>
            <exclusions>
                <exclusion>
                    <groupId>org.openjfx</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.27</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.6.3.Final</version>
        </dependency>

        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct-processor</artifactId>
            <version>1.3.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.6.4.Final</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
            <version>2.3.0.1</version>
        </dependency>
    </dependencies>
</code>```

HibernateUtil.java

```<code>public class HibernateUtil {
    private static SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            if (sessionFactory == null) {

                Configuration config = new Configuration().configure(HibernateUtil.class.getResource("/hibernate.cfg.xml"));
                config.addAnnotatedClass(Customer.class);
                StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
                serviceRegistryBuilder.applySettings(config.getProperties());
                ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
                sessionFactory = config.buildSessionFactory(serviceRegistry);

            }

            return sessionFactory;
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        getSessionFactory().close();
    }
}
</code>```

hibernate.cfg.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/zuseDB?useSSL=false</property>
        <property name="connection.username">root</property>
        <property name="connection.password">admin</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">create</property>
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
    </session-factory>
</hibernate-configuration>
</code>```

Main function

```<code>public static void main(String[] args) {

        Customer customer = new Customer(
                "BPG", "Zubeir", "Mohamed", "mail", "112"
        );

        session.beginTransaction();
        session.save(customer);
        session.getTransaction().commit();

        HibernateUtil.shutdown();

        // launch();
    }
</code>```

Model class

```<code>@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long id;
    public String companyName;
    public String firstName;
    public String lastName;
    public String email;
    public String phone;
    @CreationTimestamp
    public Timestamp createdAt;

    public Customer(String companyName, String firstName, String lastName, String email, String phone) {
        this.companyName = companyName;
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.phone = phone;
    }

    public Customer() {}
...etc.
</code>```

The error message

```<code>Exception in thread "main" java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.ExceptionInInitializerError
    at com.htwsaar.zuse/com.htwsaar.zuse.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:27)
    at com.htwsaar.zuse/com.htwsaar.zuse.util.HibernateUtil.<clinit>(HibernateUtil.java:10)
    at com.htwsaar.zuse/com.htwsaar.zuse.IndexApplication.<clinit>(IndexApplication.java:19)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
    ... 5 more
Caused by: org.hibernate.MappingException: Could not instantiate persister org.hibernate.persister.entity.SingleTableEntityPersister
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:112)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:77)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.metamodel.internal.MetamodelImpl.initialize(MetamodelImpl.java:181)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:319)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:471)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:728)
    at com.htwsaar.zuse/com.htwsaar.zuse.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:21)
    ... 13 more
Caused by: java.lang.reflect.InaccessibleObjectException: Unable to make field public long com.htwsaar.zuse.model.Customer.id accessible: module com.htwsaar.zuse does not "exports com.htwsaar.zuse.model" to module org.hibernate.orm.core
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:340)
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:280)
    at java.base/java.lang.reflect.Field.checkCanSetAccessible(Field.java:176)
    at java.base/java.lang.reflect.Field.setAccessible(Field.java:170)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.internal.util.ReflectHelper.ensureAccessibility(ReflectHelper.java:418)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.internal.util.ReflectHelper.findField(ReflectHelper.java:408)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.property.access.internal.PropertyAccessFieldImpl.<init>(PropertyAccessFieldImpl.java:34)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.property.access.internal.PropertyAccessStrategyFieldImpl.buildPropertyAccess(PropertyAccessStrategyFieldImpl.java:26)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.tuple.PropertyFactory.getGetter(PropertyFactory.java:341)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.tuple.PropertyFactory.buildIdentifierAttribute(PropertyFactory.java:67)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:142)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:613)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:126)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:96)
    ... 19 more
</code>```

答:
The solution here is the module-info. Make sure to open and export the right package to org.hibernate.orm.core inside the module info and export it

opens com.htwsaar.zuse.model to org.hibernate.orm.core; exports com.htwsaar.zuse.model;

That should work.

Body:
I am struggling building a simple Hibernate with or without JPA, Maven and Java 11 project. This is a javafX project and shouldn't hinder using Hibernate.

I couldn't find any project example with the latest versions and I could not use older version because it would give the same error.

Here is the dependency tree of my pom.xml.

<dependencies>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>11.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-fxml</artifactId>
            <version>11.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-web</artifactId>
            <version>11.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.controlsfx</groupId>
            <artifactId>controlsfx</artifactId>
            <version>11.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.dlsc.formsfx</groupId>
            <artifactId>formsfx-core</artifactId>
            <version>11.3.2</version>
            <exclusions>
                <exclusion>
                    <groupId>org.openjfx</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>net.synedra</groupId>
            <artifactId>validatorfx</artifactId>
            <version>0.1.13</version>
            <exclusions>
                <exclusion>
                    <groupId>org.openjfx</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.kordamp.ikonli</groupId>
            <artifactId>ikonli-javafx</artifactId>
            <version>12.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.kordamp.bootstrapfx</groupId>
            <artifactId>bootstrapfx-core</artifactId>
            <version>0.4.0</version>
        </dependency>
        <dependency>
            <groupId>eu.hansolo</groupId>
            <artifactId>tilesfx</artifactId>
            <version>11.48</version>
            <exclusions>
                <exclusion>
                    <groupId>org.openjfx</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.27</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.6.3.Final</version>
        </dependency>

        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct-processor</artifactId>
            <version>1.3.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.6.4.Final</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
            <version>2.3.0.1</version>
        </dependency>
    </dependencies>

HibernateUtil.java

public class HibernateUtil {
    private static SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            if (sessionFactory == null) {

                Configuration config = new Configuration().configure(HibernateUtil.class.getResource("/hibernate.cfg.xml"));
                config.addAnnotatedClass(Customer.class);
                StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
                serviceRegistryBuilder.applySettings(config.getProperties());
                ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
                sessionFactory = config.buildSessionFactory(serviceRegistry);

            }

            return sessionFactory;
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        getSessionFactory().close();
    }
}

hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/zuseDB?useSSL=false</property>
        <property name="connection.username">root</property>
        <property name="connection.password">admin</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">create</property>
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
    </session-factory>
</hibernate-configuration>

Main function

public static void main(String[] args) {

        Customer customer = new Customer(
                "BPG", "Zubeir", "Mohamed", "mail", "112"
        );

        session.beginTransaction();
        session.save(customer);
        session.getTransaction().commit();

        HibernateUtil.shutdown();

        // launch();
    }

Model class

@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long id;
    public String companyName;
    public String firstName;
    public String lastName;
    public String email;
    public String phone;
    @CreationTimestamp
    public Timestamp createdAt;

    public Customer(String companyName, String firstName, String lastName, String email, String phone) {
        this.companyName = companyName;
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.phone = phone;
    }

    public Customer() {}
...etc.

The error message

Exception in thread "main" java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.ExceptionInInitializerError
    at com.htwsaar.zuse/com.htwsaar.zuse.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:27)
    at com.htwsaar.zuse/com.htwsaar.zuse.util.HibernateUtil.<clinit>(HibernateUtil.java:10)
    at com.htwsaar.zuse/com.htwsaar.zuse.IndexApplication.<clinit>(IndexApplication.java:19)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
    ... 5 more
Caused by: org.hibernate.MappingException: Could not instantiate persister org.hibernate.persister.entity.SingleTableEntityPersister
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:112)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:77)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.metamodel.internal.MetamodelImpl.initialize(MetamodelImpl.java:181)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:319)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:471)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:728)
    at com.htwsaar.zuse/com.htwsaar.zuse.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:21)
    ... 13 more
Caused by: java.lang.reflect.InaccessibleObjectException: Unable to make field public long com.htwsaar.zuse.model.Customer.id accessible: module com.htwsaar.zuse does not "exports com.htwsaar.zuse.model" to module org.hibernate.orm.core
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:340)
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:280)
    at java.base/java.lang.reflect.Field.checkCanSetAccessible(Field.java:176)
    at java.base/java.lang.reflect.Field.setAccessible(Field.java:170)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.internal.util.ReflectHelper.ensureAccessibility(ReflectHelper.java:418)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.internal.util.ReflectHelper.findField(ReflectHelper.java:408)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.property.access.internal.PropertyAccessFieldImpl.<init>(PropertyAccessFieldImpl.java:34)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.property.access.internal.PropertyAccessStrategyFieldImpl.buildPropertyAccess(PropertyAccessStrategyFieldImpl.java:26)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.tuple.PropertyFactory.getGetter(PropertyFactory.java:341)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.tuple.PropertyFactory.buildIdentifierAttribute(PropertyFactory.java:67)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:142)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:613)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:126)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
    at org.hibernate.orm.core@5.6.3.Final/org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:96)
    ... 19 more


问:
How do I make my NW.js application *start* in fullscreen?
I know how to enter fullscreen once it's already loaded in a window. This causes an ugly effect where, when I click its icon, briefly flashes a windowed window which immediately goes fullscreen. I hate that effect.

How do I make it actually start, right away, in fullscreen, without ever being in windowed mode even for a split second?

答:
If you want more info go to https://www.w3schools.com/howto/howto_js_fullscreen.asp#:~:text=To%20open%20an%20element%20in%20fullscreen%2C%20we%20use,fullscreen%20mode%20%28a%20video%20in%20this%20example%29%3A%20%2A%2F
this would work if youre making an website

function openFullscreen() {
  if (elem.requestFullscreen) {
    elem.requestFullscreen();
  } else if (elem.webkitRequestFullscreen) { /* Safari */
    elem.webkitRequestFullscreen();
  } else if (elem.msRequestFullscreen) { /* IE11 */
    elem.msRequestFullscreen();
  }
}

/* Close fullscreen */
function closeFullscreen() {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.webkitExitFullscreen) { /* Safari */
    document.webkitExitFullscreen();
  } else if (document.msExitFullscreen) { /* IE11 */
    document.msExitFullscreen();
  }
}
```


问:
How to run multi parameter function with if, elif and else?
So, I tried to make a function that adds one to a variable depending on the input, but there's an error.</p>
```<code>def food_ch(i, a, b, c, d):
    if a in i.lower():
        first += 1
    elif b in i.lower():
        second += + 1
    elif c in i.lower():
        third += 1
    elif d in i.lower():
        fourth += 1
    else:
        hungry += 1

print ("What cuisine do you like the most?: Italian, Chinese, Japanese or Mexican?")
food = input("I like ")

first = 0
second = 0
third = 0
fourth = 0
hungry = 0

food_ch(food, "italian", "chinese", "japanese", "mexican")

print (first, second, third, fourth, hungry)
</code>```

答:
Your function is attempting to update global variables defined outside of its scope.

To do this kind of thing, you should use a single variable (list or dictionary) to store your counts.  This would allow your function to manipulate the data generically without so many if.

A dictionary is probably the best option:

```<code>counts = { "italian":0, "chinese":0, "japanese":0, "mexican":0, "hungry":0 }

print ("What cuisine do you like the most?: Italian, Chinese, Japanese or Mexican?")

food = input("I like ").lower()

if food not in counts:
   food = "hungry"
counts[food] += 1

print(counts)
</code>```

Sample run:

```<code>What cuisine do you like the most?: Italian, Chinese, Japanese or Mexican?
I like Chinese
{'italian': 0, 'chinese': 1, 'japanese': 0, 'mexican': 0, 'hungry': 0}
</code>```

Body:
So, I tried to make a function that adds one to a variable depending on the input, but there's an error.

def food_ch(i, a, b, c, d):
    if a in i.lower():
        first += 1
    elif b in i.lower():
        second += + 1
    elif c in i.lower():
        third += 1
    elif d in i.lower():
        fourth += 1
    else:
        hungry += 1

print ("What cuisine do you like the most?: Italian, Chinese, Japanese or Mexican?")
food = input("I like ")

first = 0
second = 0
third = 0
fourth = 0
hungry = 0

food_ch(food, "italian", "chinese", "japanese", "mexican")

print (first, second, third, fourth, hungry)

Body:
Your function is attempting to update global variables defined outside of its scope.

To do this kind of thing, you should use a single variable (list or dictionary) to store your counts.  This would allow your function to manipulate the data generically without so many if.

A dictionary is probably the best option:

counts = { "italian":0, "chinese":0, "japanese":0, "mexican":0, "hungry":0 }

print ("What cuisine do you like the most?: Italian, Chinese, Japanese or Mexican?")

food = input("I like ").lower()

if food not in counts:
   food = "hungry"
counts[food] += 1

print(counts)

Sample run:

What cuisine do you like the most?: Italian, Chinese, Japanese or Mexican?
I like Chinese
{'italian': 0, 'chinese': 1, 'japanese': 0, 'mexican': 0, 'hungry': 0}


问:
Saving variable from drop down menu command with lambda function in Tkinter
I want to extract the selected data from a drop down menu in Tkinter. The drop down menu changes based on a previous drop down menu selection.

Basically, how do I save a variable from a lambda function?

I've tried declaring a global variable, and dictionary value but the problem still is that I am overwriting the original drop down menu in my function and the code is still reading the value of the original drop down. Ideally, the code would just update the actual drop down list and not overwrite the original one. Apologies for my clunky, un-pythonic code.

```<code>import tkinter as tk

HEIGHT = 500
WIDTH = 500

root = tk.Tk()

canvas = tk.Canvas(root, height = HEIGHT, width = WIDTH)
canvas.pack()

subframe = tk.Frame(root, bg = 'gray', bd = 10)
subframe.place(relx = 0.05, rely = 0.05, relwidth = 0.9, relheight = 0.9)

subframe.rowconfigure(tuple(range(4)), weight = 1)
subframe.columnconfigure(tuple(range(4)), weight = 1)

inputs = {}  ### dictionary for saved label *** I know there HAS to be a better way

### --- dropdown1 Input
label10 = tk.Label(subframe, text = 'Label 1', font = ('Century', 12), bg = 'gray', fg = 'white')
label10.grid(row = 1, column = 0, sticky = 'ew', padx = 5, pady = 5)

dropdown1_ID_series = ['A', 'B', 'C']

#global dropdown2_ID_var

def update_test_data_dropdown(dropdown1ID):
    if dropdown1ID == 'C':
        dropdown2_ID_series = ['1', '2', '3']
        dropdown2_ID_var = tk.StringVar(root)
        dropdown2_ID_var.set(dropdown2_ID_series[0])
        dropdown2_ID_entry = tk.OptionMenu(subframe, dropdown2_ID_var, *dropdown2_ID_series)
        dropdown2_ID_entry.config(width=10)
        dropdown2_ID_entry.grid(row = 2, column = 1, sticky = 'ew', padx = 5, pady = 5)
        inputs['dropdown2'] = dropdown2_ID_var.get()
        print (inputs['dropdown2'])
    else:
        dropdown2_ID_series = ['4', '5','6']
        dropdown2_ID_var = tk.StringVar(root)
        dropdown2_ID_var.set(dropdown2_ID_series[0])
        dropdown2_ID_entry = tk.OptionMenu(subframe, dropdown2_ID_var, *dropdown2_ID_series)
        dropdown2_ID_entry.config(width=10)
        dropdown2_ID_entry.grid(row = 2, column = 1, sticky = 'ew', padx = 5, pady = 5)
        inputs['dropdown2'] = dropdown2_ID_var.get()
    return dropdown2_ID_var  ## need to figure out how to export dropdown2_ID_var

dropdown1_ID_var = tk.StringVar(root)
dropdown1_ID_var.set(dropdown1_ID_series[0])
dropdown1_ID_entry = tk.OptionMenu(subframe, dropdown1_ID_var, *dropdown1_ID_series, command = lambda x: update_test_data_dropdown(x))
dropdown1_ID_entry.config(width=10)
dropdown1_ID_entry.grid(row = 1, column = 1, sticky = 'ew', padx = 5, pady = 5)

### --- dropdown 2 input
label20 = tk.Label(subframe, text = 'Label 2', font = ('Century', 12), bg = 'gray', fg = 'white')
label20.grid(row = 2, column = 0, sticky = 'ew', padx = 5, pady = 5)

dropdown2_ID_series = ['D', 'E', 'F']

dropdown2_ID_var = tk.StringVar(root)
dropdown2_ID_var.set(dropdown2_ID_series[0])
dropdown2_ID_entry = tk.OptionMenu(subframe, dropdown2_ID_var, *dropdown2_ID_series)
dropdown2_ID_entry.config(width=10)
dropdown2_ID_entry.grid(row = 2, column = 1, sticky = 'ew', padx = 5, pady = 5)

inputs['dropdown2'] = dropdown2_ID_var.get()
print (inputs['dropdown2'])

def submit():
    label11 = tk.Label(subframe, text = dropdown1_ID_var.get(), font = ('Century', 12), bg = 'gray', fg = 'white')
    # label22 = tk.Label(subframe, text = dropdown2_ID_var.get(), font = ('Century', 12), bg = 'gray', fg = 'white')
    label22 = tk.Label(subframe, text = inputs['dropdown2'], font = ('Century', 12), bg = 'gray', fg = 'white')
    label11.grid(row = 1, column = 3, padx = 5, pady = 5)
    label22.grid(row = 2, column = 3, padx = 5, pady = 5)

### --- RUN BUTTON
button = tk.Button(subframe, text = 'SUBMIT', font = ('Century', 12, 'bold'), command = lambda: submit())
button.grid(row = 3, column = 3, ipadx = 20, padx = 5, pady = 15)

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

When hitting SUBMIT on the above code, I want the selected value in the dropdowns to print next to the drop down.

答:
I think the following does what you want. It uses the textvariable= option Labels accept so they will automatically update themselves when the associated StringVar's value is changed. It also shows how the change the options associated with an existing OptionMenu widget (addressing the "how do I save a variable from a lambda command" part of your question).

Note I also reformatted your code per the PEP 8 - Style Guide for Python Code guidelines to make it more readable.

```<code>import tkinter as tk

HEIGHT = 500
WIDTH = 500

root = tk.Tk()

canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()

subframe = tk.Frame(root, bg='gray', bd=10)
subframe.place(relx=0.05, rely=0.05, relwidth=0.9, relheight=0.9)

subframe.rowconfigure(tuple(range(4)), weight=1)
subframe.columnconfigure(tuple(range(4)), weight=1)

### --- dropdown1 Input
label10 = tk.Label(subframe, text='Label 1', font=('Century', 12), bg='gray', fg='white')
label10.grid(row=1, column=0, sticky='ew', padx=5, pady=5)

dropdown1_ID_series = ['A', 'B', 'C']

def set_menu(entry, values, default=None):
    """Utility to change OptionMenu widget choices and associated StringVar."""
    varname = entry.cget('textvariable')  # Get name associated with StringVar.
    variable = tk.StringVar(name=varname)  # Get reference to it.
    menu = entry['menu']
    menu.delete(0, 'end')
    for value in values:
        menu.add_command(label=value, command=lambda val=value: variable.set(val))
    variable.set('' if default is None else default)

def update_test_data_dropdown(dropdown1ID):
    label11.grid_remove()  # Hide.
    label22.grid_remove()  # Hide.

    dropdown2_ID_series[:] = (['1', '2', '3'] if dropdown1ID == 'C'
                                else ['4', '5', '6'])
    # Change second OptionMenu.
    set_menu(dropdown2_ID_entry, dropdown2_ID_series, default=dropdown2_ID_series[0])

dropdown1_ID_var = tk.StringVar(root)
dropdown1_ID_var.set(dropdown1_ID_series[0])
dropdown1_ID_entry = tk.OptionMenu(subframe, dropdown1_ID_var, *dropdown1_ID_series,
                                   command=update_test_data_dropdown)
dropdown1_ID_entry.config(width=10)
dropdown1_ID_entry.grid(row=1, column=1, sticky='ew', padx=5, pady=5)

### --- dropdown 2 input
label20 = tk.Label(subframe, text='Label 2', font=('Century', 12),
                   bg='gray', fg='white')
label20.grid(row=2, column=0, sticky='ew', padx=5, pady=5)

dropdown2_ID_series = ['D', 'E', 'F']
dropdown2_ID_var = tk.StringVar(root)
dropdown2_ID_var.set(dropdown2_ID_series[0])
dropdown2_ID_entry = tk.OptionMenu(subframe, dropdown2_ID_var, *dropdown2_ID_series,
                                   command=update_test_data_dropdown)
dropdown2_ID_entry.config(width=10)
dropdown2_ID_entry.grid(row=2, column=1, sticky='ew', padx=5, pady=5)

label11 = tk.Label(subframe, textvariable=dropdown1_ID_var, font=('Century', 12),
                   bg='gray', fg='white')
label11.grid(row=1, column=3, padx=5, pady=5)
label11.grid_remove()  # Initially hidden (but remembers grid location).

label22 = tk.Label(subframe, textvariable=dropdown2_ID_var, font=('Century', 12),
                   bg='gray', fg='white')
label22.grid(row=2, column=3, padx=5, pady=5)
label22.grid_remove()  # Initially hidden (but remembers grid location).

def submit():
    label11.grid()  # Unhide.
    label22.grid()  # Unhide.

### --- Run Button
button = tk.Button(subframe, text='SUBMIT', font=('Century', 12, 'bold'), command=submit)
button.grid(row=3, column=3, ipadx=20, padx=5, pady=15)

root.mainloop()

</code>```

Body:
I want to extract the selected data from a drop down menu in Tkinter. The drop down menu changes based on a previous drop down menu selection.

Basically, how do I save a variable from a lambda function?

I've tried declaring a global variable, and dictionary value but the problem still is that I am overwriting the original drop down menu in my function and the code is still reading the value of the original drop down. Ideally, the code would just update the actual drop down list and not overwrite the original one. Apologies for my clunky, un-pythonic code.

import tkinter as tk

HEIGHT = 500
WIDTH = 500

root = tk.Tk()

canvas = tk.Canvas(root, height = HEIGHT, width = WIDTH)
canvas.pack()

subframe = tk.Frame(root, bg = 'gray', bd = 10)
subframe.place(relx = 0.05, rely = 0.05, relwidth = 0.9, relheight = 0.9)

subframe.rowconfigure(tuple(range(4)), weight = 1)
subframe.columnconfigure(tuple(range(4)), weight = 1)

inputs = {}  ### dictionary for saved label *** I know there HAS to be a better way

### --- dropdown1 Input
label10 = tk.Label(subframe, text = 'Label 1', font = ('Century', 12), bg = 'gray', fg = 'white')
label10.grid(row = 1, column = 0, sticky = 'ew', padx = 5, pady = 5)

dropdown1_ID_series = ['A', 'B', 'C']

#global dropdown2_ID_var

def update_test_data_dropdown(dropdown1ID):
    if dropdown1ID == 'C':
        dropdown2_ID_series = ['1', '2', '3']
        dropdown2_ID_var = tk.StringVar(root)
        dropdown2_ID_var.set(dropdown2_ID_series[0])
        dropdown2_ID_entry = tk.OptionMenu(subframe, dropdown2_ID_var, *dropdown2_ID_series)
        dropdown2_ID_entry.config(width=10)
        dropdown2_ID_entry.grid(row = 2, column = 1, sticky = 'ew', padx = 5, pady = 5)
        inputs['dropdown2'] = dropdown2_ID_var.get()
        print (inputs['dropdown2'])
    else:
        dropdown2_ID_series = ['4', '5','6']
        dropdown2_ID_var = tk.StringVar(root)
        dropdown2_ID_var.set(dropdown2_ID_series[0])
        dropdown2_ID_entry = tk.OptionMenu(subframe, dropdown2_ID_var, *dropdown2_ID_series)
        dropdown2_ID_entry.config(width=10)
        dropdown2_ID_entry.grid(row = 2, column = 1, sticky = 'ew', padx = 5, pady = 5)
        inputs['dropdown2'] = dropdown2_ID_var.get()
    return dropdown2_ID_var  ## need to figure out how to export dropdown2_ID_var

dropdown1_ID_var = tk.StringVar(root)
dropdown1_ID_var.set(dropdown1_ID_series[0])
dropdown1_ID_entry = tk.OptionMenu(subframe, dropdown1_ID_var, *dropdown1_ID_series, command = lambda x: update_test_data_dropdown(x))
dropdown1_ID_entry.config(width=10)
dropdown1_ID_entry.grid(row = 1, column = 1, sticky = 'ew', padx = 5, pady = 5)

### --- dropdown 2 input
label20 = tk.Label(subframe, text = 'Label 2', font = ('Century', 12), bg = 'gray', fg = 'white')
label20.grid(row = 2, column = 0, sticky = 'ew', padx = 5, pady = 5)

dropdown2_ID_series = ['D', 'E', 'F']

dropdown2_ID_var = tk.StringVar(root)
dropdown2_ID_var.set(dropdown2_ID_series[0])
dropdown2_ID_entry = tk.OptionMenu(subframe, dropdown2_ID_var, *dropdown2_ID_series)
dropdown2_ID_entry.config(width=10)
dropdown2_ID_entry.grid(row = 2, column = 1, sticky = 'ew', padx = 5, pady = 5)

inputs['dropdown2'] = dropdown2_ID_var.get()
print (inputs['dropdown2'])

def submit():
    label11 = tk.Label(subframe, text = dropdown1_ID_var.get(), font = ('Century', 12), bg = 'gray', fg = 'white')
    # label22 = tk.Label(subframe, text = dropdown2_ID_var.get(), font = ('Century', 12), bg = 'gray', fg = 'white')
    label22 = tk.Label(subframe, text = inputs['dropdown2'], font = ('Century', 12), bg = 'gray', fg = 'white')
    label11.grid(row = 1, column = 3, padx = 5, pady = 5)
    label22.grid(row = 2, column = 3, padx = 5, pady = 5)

### --- RUN BUTTON
button = tk.Button(subframe, text = 'SUBMIT', font = ('Century', 12, 'bold'), command = lambda: submit())
button.grid(row = 3, column = 3, ipadx = 20, padx = 5, pady = 15)

root.mainloop()

When hitting SUBMIT on the above code, I want the selected value in the dropdowns to print next to the drop down.

Body:
I think the following does what you want. It uses the textvariable= option Labels accept so they will automatically update themselves when the associated StringVar's value is changed. It also shows how the change the options associated with an existing OptionMenu widget (addressing the "how do I save a variable from a lambda command" part of your question).

Note I also reformatted your code per the PEP 8 - Style Guide for Python Code guidelines to make it more readable.

import tkinter as tk

HEIGHT = 500
WIDTH = 500

root = tk.Tk()

canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()

subframe = tk.Frame(root, bg='gray', bd=10)
subframe.place(relx=0.05, rely=0.05, relwidth=0.9, relheight=0.9)

subframe.rowconfigure(tuple(range(4)), weight=1)
subframe.columnconfigure(tuple(range(4)), weight=1)

### --- dropdown1 Input
label10 = tk.Label(subframe, text='Label 1', font=('Century', 12), bg='gray', fg='white')
label10.grid(row=1, column=0, sticky='ew', padx=5, pady=5)

dropdown1_ID_series = ['A', 'B', 'C']

def set_menu(entry, values, default=None):
    """Utility to change OptionMenu widget choices and associated StringVar."""
    varname = entry.cget('textvariable')  # Get name associated with StringVar.
    variable = tk.StringVar(name=varname)  # Get reference to it.
    menu = entry['menu']
    menu.delete(0, 'end')
    for value in values:
        menu.add_command(label=value, command=lambda val=value: variable.set(val))
    variable.set('' if default is None else default)

def update_test_data_dropdown(dropdown1ID):
    label11.grid_remove()  # Hide.
    label22.grid_remove()  # Hide.

    dropdown2_ID_series[:] = (['1', '2', '3'] if dropdown1ID == 'C'
                                else ['4', '5', '6'])
    # Change second OptionMenu.
    set_menu(dropdown2_ID_entry, dropdown2_ID_series, default=dropdown2_ID_series[0])

dropdown1_ID_var = tk.StringVar(root)
dropdown1_ID_var.set(dropdown1_ID_series[0])
dropdown1_ID_entry = tk.OptionMenu(subframe, dropdown1_ID_var, *dropdown1_ID_series,
                                   command=update_test_data_dropdown)
dropdown1_ID_entry.config(width=10)
dropdown1_ID_entry.grid(row=1, column=1, sticky='ew', padx=5, pady=5)

### --- dropdown 2 input
label20 = tk.Label(subframe, text='Label 2', font=('Century', 12),
                   bg='gray', fg='white')
label20.grid(row=2, column=0, sticky='ew', padx=5, pady=5)

dropdown2_ID_series = ['D', 'E', 'F']
dropdown2_ID_var = tk.StringVar(root)
dropdown2_ID_var.set(dropdown2_ID_series[0])
dropdown2_ID_entry = tk.OptionMenu(subframe, dropdown2_ID_var, *dropdown2_ID_series,
                                   command=update_test_data_dropdown)
dropdown2_ID_entry.config(width=10)
dropdown2_ID_entry.grid(row=2, column=1, sticky='ew', padx=5, pady=5)

label11 = tk.Label(subframe, textvariable=dropdown1_ID_var, font=('Century', 12),
                   bg='gray', fg='white')
label11.grid(row=1, column=3, padx=5, pady=5)
label11.grid_remove()  # Initially hidden (but remembers grid location).

label22 = tk.Label(subframe, textvariable=dropdown2_ID_var, font=('Century', 12),
                   bg='gray', fg='white')
label22.grid(row=2, column=3, padx=5, pady=5)
label22.grid_remove()  # Initially hidden (but remembers grid location).

def submit():
    label11.grid()  # Unhide.
    label22.grid()  # Unhide.

### --- Run Button
button = tk.Button(subframe, text='SUBMIT', font=('Century', 12, 'bold'), command=submit)
button.grid(row=3, column=3, ipadx=20, padx=5, pady=15)

root.mainloop()


问:
How to jump to the next line when defining a function in Python?
I am using a Mac terminal to learn Python basics at the moment and I can't figure out how to write a new line when defining a function, because whenever I hit "Enter", it just throws an error.</p>
```<code>        >>> def f():
        ... a = 10
          File "<stdin>", line 2
            a = 10
            ^
        IndentationError: expected an indented block after function definition on line 1
        >>>
</code>```

答:
Indentation indicates where blocks begin and end.  Everything inside a function definition is indented:

```<code>>>> def f():
...     a = 10
...     print(a)
...
>>> f()
10
</code>```

The first line that is not indented indicates the function is over.

Body:
I am using a Mac terminal to learn Python basics at the moment and I can't figure out how to write a new line when defining a function, because whenever I hit "Enter", it just throws an error.

        >>> def f():
        ... a = 10
          File "<stdin>", line 2
            a = 10
            ^
        IndentationError: expected an indented block after function definition on line 1
        >>>

Body:
Indentation indicates where blocks begin and end.  Everything inside a function definition is indented:

>>> def f():
...     a = 10
...     print(a)
...
>>> f()
10

The first line that is not indented indicates the function is over.


问:
Shopify Store Refresh cart content. AJAX request
I have product page on which I have shop now btn. When user clicks on this button, page opens cart drawer with custom ajax template content.

I rewrited click event with my own logic. I use AJAX and send request for adding product by myself. Products are adding but is not showing in the cart drawer. Only after reloading page it is appearing.

Question is to can I refresh cart content? I'm trying to past content template via inner html. But it is looks like not liquid format.

Here is the template

```<code> <script id="CartTemplate" type="text/template">
{% render 'banana-stand-cart-top-container' %}
{% raw %}
<div class="drawer__scrollable">
  {{#items}}
  <div class="ajaxcart__product appear-animation appear-delay-{{animationRow}}">
  <div class="ajaxcart__row">
    <div class="grid">
      <div class="grid__item one-third">
        <a href="{{url}}" class="ajaxcart__product-image"><img src="{{img}}" alt="{{name}}"></a>
      </div>
      <div class="grid__item two-thirds">
        <div class="ajaxcart__product-name--wrapper">
          <a href="{{url}}" class="ajaxcart__product-name">{{{name}}}</a>
          {{#if variation}}
            <div class="ajaxcart__product-meta">{{variation}}</div>
          {{/if}}
          {{#if selling_plan_name}}
            <div class="ajaxcart__product-meta">{{selling_plan_name}}</div>
          {{/if}}
          {{#properties}}
            {{#each this}}
              {{#if this}}
                <span class="ajaxcart__product-meta">{{@key}}: {{this}}</span>
              {{/if}}
            {{/each}}
          {{/properties}}
        </div>

        <div class="grid grid--full display-table">
          <div class="grid__item display-table-cell one-half">
            <label for="updates_{{key}}" class="visually-hidden">{% endraw %}{{ 'products.product.quantity' | t }}{% raw %}</label>
            <div class="js-qty__wrapper">
              <input type="text" id="updates_{{key}}"
                class="js-qty__num"
                value="{{itemQty}}"
                data-id="{{key}}"
                min="0"
                aria-label="quantity"
                pattern="[0-9]*"
                name="updates[]">
              <button type="button"
                class="js-qty__adjust js-qty__adjust--minus"
                aria-label="{% endraw %}{{ 'cart.general.reduce_quantity' | t }}{% raw %}">
                  {% endraw %}<svg aria-hidden="true" focusable="false" role="presentation" class="icon icon-minus" viewBox="0 0 20 20"><path fill="#444" d="M17.543 11.029H2.1A1.032 1.032 0 0 1 1.071 10c0-.566.463-1.029 1.029-1.029h15.443c.566 0 1.029.463 1.029 1.029 0 .566-.463 1.029-1.029 1.029z"/></svg>{% raw %}
                  <span class="icon__fallback-text" aria-hidden="true">−</span>
              </button>
              <button type="button"
                class="js-qty__adjust js-qty__adjust--plus"
                aria-label="{% endraw %}{{ 'cart.general.increase_quantity' | t }}{% raw %}">
                  {% endraw %}<svg aria-hidden="true" focusable="false" role="presentation" class="icon icon-plus" viewBox="0 0 20 20"><path fill="#444" d="M17.409 8.929h-6.695V2.258c0-.566-.506-1.029-1.071-1.029s-1.071.463-1.071 1.029v6.671H1.967C1.401 8.929.938 9.435.938 10s.463 1.071 1.029 1.071h6.605V17.7c0 .566.506 1.029 1.071 1.029s1.071-.463 1.071-1.029v-6.629h6.695c.566 0 1.029-.506 1.029-1.071s-.463-1.071-1.029-1.071z"/></svg>{% raw %}
                  <span class="icon__fallback-text" aria-hidden="true">+</span>
              </button>
            </div>
          </div>
          <div class="grid__item display-table-cell one-half text-right">
            {{#if discountsApplied}}
              <small class="cart__price--strikethrough">{{{price}}}</small>
              <span class="ajaxcart__price">
                {{{discountedPrice}}}
              </span>
            {{else}}
              <span class="ajaxcart__price">
                {{{price}}}
              </span>
            {{/if}}
          </div>
        </div>
        <div class="grid grid--full display-table">
          {{#if discountsApplied}}
            <div class="grid__item text-right">
              {{#each discounts}}
                <small class="ajaxcart__discount cart__discount">
                  {{this.discount_application.title}} (-{{{this.formattedAmount}}})
                </small>
              {{/each}}
            </div>
          {{/if}}

          {{#if unitBase}}
            <div class="grid__item text-right">
              <div class="product__unit-price">
                {{{ unitPrice }}}/{{{ unitBase }}}
              </div>
            </div>
          {{/if}}
        </div>
      </div>
    </div>
  </div>
</div>
{{/items}}

  {% endraw %}{% if settings.cart_notes_enable %}{% raw %}
  <div class="appear-animation appear-delay-{{lastAnimationRow}}">
    <label for="CartSpecialInstructions" class="ajaxcart__note">{% endraw %}{{ 'cart.general.note' | t }}{% raw %}</label>
    <textarea name="note" class="input-full cart-notes" id="CartSpecialInstructions">{{note}}</textarea>
  </div>
{% endraw %}{% endif %}{% raw %}
   </div>
    <div class="drawer__footer appear-animation appear-delay-{{lastAnimationRow}}">
   {{#if cartDiscounts }}
    <div class="grid grid--full">
     <div class="grid__item one-half">
      <p class="ajaxcart__subtotal">{% endraw %}{{ 'cart.general.discounts' | t }}{% raw %}</p>
    </div>
      <div class="grid__item one-half text-right">
      {{#each cartDiscounts}}
        <p class="ajaxcart__price cart__discount">
          {{this.title}} (-{{{this.formattedAmount}}})
        </p>
      {{/each}}
    </div>
  </div>
{{/if}}
<div class="grid grid--full">
  <div class="grid__item one-half">
    <p class="ajaxcart__subtotal">{% endraw %}{{ 'cart.general.subtotal' | t }}{% raw %}</p>
  </div>
  <div class="grid__item one-half text-right">
    <p class="ajaxcart__price"><span class="tdf-cart-total-parent">{{totalPrice}}</span></p>
  </div>
</div>
<p class="ajaxcart__note">
  {% endraw %}{{ 'cart.general.shipping_at_checkout' | t }}{% raw %}
</p>
{% endraw %}{% if settings.cart_terms_conditions_enable %}
  <p class="ajaxcart__note ajaxcart__note--terms">
    <input type="checkbox" id="CartAgree" />
    <label for="CartAgree">
      {% if settings.cart_terms_conditions_link != blank %}
        {{ 'cart.general.terms_html' | t: url: settings.cart_terms_conditions_link }}
      {% else %}
        {{ 'cart.general.terms' | t }}
      {% endif %}
    </label>
  </p>
   {% endif %}{% raw %}
   {% endraw %}
   {% if additional_checkout_buttons and settings.cart_additional_buttons %}
      <div class="additional-checkout-buttons additional-checkout-buttons--vertical">{{ content_for_additional_checkout_buttons }}</div>
   {% endif %}
  {% raw %}
  <button type="submit" class="btn btn--full cart__checkout{% endraw %}{% if settings.cart_terms_conditions_enable %}{% raw %} cart__checkout--ajax{% endraw %}{% endif %}{% raw %}" name="checkout">
  {% endraw %}{{ 'cart.general.checkout' | t }}{% raw %}
</button>
</div>
{% endraw %}
</code>```

答:
Usually, there is some way (js-function) that allows you to rebuild the cart with new items.
You need to check the js-code that is responsible for showing the drawer-cart</p>


问:
Detect when a view controller goes to background and gets resumed
I'm implementing a ViewController with the following requirement: If the user returns to the app after 15 minutes, the view should reload the data.

I was thinking on using viewDidDisappear to save the timestamp when the app went to background and viewDidAppear for checking previously saved values and refresh if needed, but this methods are not getting called when switching between apps.

How can I solve this in a easy way?

答:
Objective-C

```<code>- (void)viewDidLoad {
     [[NSNotificationCenter defaultCenter] addObserver:self
   selector:@selector(appMovedToBackground:)
       name:UIApplicationDidEnterBackgroundNotification
     object:nil];

     [[NSNotificationCenter defaultCenter] addObserver:self
   selector:@selector(appBecomeActive:)
       name:UIApplicationDidBecomeActiveNotification
     object:nil];
}

- (void)appMovedToBackground:(NSNotification *) notification  {
    NSLog(@"App Moved To Background");
}

- (void)appBecomeActive:(NSNotification *) notification {
    NSLog(@"App become active");
}
</code>```

Don't forget to clear notifications when view gets disappear

Body:
Objective-C

- (void)viewDidLoad {
     [[NSNotificationCenter defaultCenter] addObserver:self
   selector:@selector(appMovedToBackground:)
       name:UIApplicationDidEnterBackgroundNotification
     object:nil];

     [[NSNotificationCenter defaultCenter] addObserver:self
   selector:@selector(appBecomeActive:)
       name:UIApplicationDidBecomeActiveNotification
     object:nil];
}

- (void)appMovedToBackground:(NSNotification *) notification  {
    NSLog(@"App Moved To Background");
}

- (void)appBecomeActive:(NSNotification *) notification {
    NSLog(@"App become active");
}

Don't forget to clear notifications when view gets disappear


问:
Sharing data across processes on linux
In my application, I have a process which forks off a child, say child1, and this child process writes a huge binary file on the disk and exits. The parent process then forks off another child process, child2, which reads in this huge file to do further processing.

The file dumping and re-loading is making my application slow and I'm thinking of possible
ways of avoiding disk I/O completely. Possible ways I have identified are ram-disk or tmpfs.
Can I somehow implement ram-disk or tmpfs from within my application? Or is there any other
way by which I can avoid disk I/O completely and send data across processes reliably.

答: A named pipe is exactly what you want. You can write data into it and read data from it like it was a file, but there's no need to store it on disk.</p>

Title: Sharing data across processes on linux


问:
Rasterize polygons based on maximum overlap (using R packages terra or stars)
I have a question concerning rasterization of polygons by maximum overlap, i.e assign the value of the polygon that has the highst area overlap with the raster cell.

The real world exercise is to rasterize polygons of soil-IDs in R, in order to produce relatively low resolution maps of soil properties as model inputs.

The problem is that the rasterize() function of the terra package (and similar stars' st_rasterize()) assigns the cell value from the polygon that contains the cell midpoint. If a raster cell contains multiple polygons, I would rather like to select the value of the polygon (soil-ID), which has the highest aerea cover in a raster cell.

Here is a small self-contained example that visualizes my problem, using terra.

```<code>library(terra)

f <- system.file("ex/lux.shp", package="terra")
v <- vect(f)
r <- rast(v, ncols = 3, nrow = 3)
rcc <- vect(xyFromCell(r, cell = 1:ncell(r)))

x <- rasterize(v, r, field = "NAME_2")
plot(x)
lines(r, col = "light gray")
lines(v)
points(rcc)
</code>```

Mostly, the polygons that contain the cell center also seem to have the highest area share. However, in some cases (top row, 3rd cell), this is not the case.
The problem appears to get worse the bigger the cells are compared with the polygons. I could therefore start with high resolution raster, and than resample to the desired (lower) resolution, using an aggregation function (e.g. the mode). But, maybe someone has a more efficient idea?

Thank you for your help!

答:
You could do that like this:

```<code>#Example data
library(terra)
f <- system.file("ex/lux.shp", package="terra")
v <- vect(f)
r <- rast(v, ncols = 3, nrow = 3)

n <- 10
r <- disagg(r, n)
r <- rasterize(v, r, "ID_2")
x <- aggregate(r, n, "modal")

plot(x)
lines(x)
lines(v, lwd=2)
text(v, col="red", halo=T)
text(x, col="blue", halo=T)
</code>```

Another way, probably less efficient (especially if you have many IDs):

```<code>z <- lapply(1:nrow(v), \(i) rasterize(v[i,], r, cover=TRUE))
z <- which.max(rast(z))
</code>```

But you could replace rasterize with exactextractr::coverage_fraction if you want very high precision

Even less efficient, I suppose:

```<code>r <- rast(v, ncols = 3, nrow = 3)
values(r) <- 1:ncell(r)
# get weights
e <- extract(r, v, weights=TRUE)
e <- as.matrix(e)
head(e)
#    ID lyr.1 weight
#[1,]  1     1   0.38
#[2,]  1     2   0.49
#[3,]  2     2   0.06
#[4,]  2     4   0.05
#[5,]  2     5   0.52
#[6,]  2     6   0.06

# find cell with max weight (you can use dplyr or data.table intead)
x <- sapply(unique(e[,2]), function(i) {
    d <- e[e[,2] == i, ,drop=FALSE]
    d[which.max(d[,3]), 2:1]
})

# remove values
r <- rast(r)
# assign ID to cells
r[x[1,]] <- x[2,]
</code>```

You could achieve the same with using polygon intersection, but that does not scale well to large rasters

```<code>r <- rast(v, ncols = 3, nrow = 3)
values(r) <- 1:9
v$ID <- 1:nrow(v)
i <- intersect(v[,"ID"], as.polygons(r))
i$area <- expanse(i)
i <- data.frame(i)
x <- sapply(split(i, i[,2]),
    \(x) { x[which.max(x[,3]), 2:1] |> unlist()}
)
r <- rast(r)
r[x[1,]] <- x[2,]
</code>```

(perhaps not as elegant as st_join proposed by lovalery)

Body:
I have a question concerning rasterization of polygons by maximum overlap, i.e assign the value of the polygon that has the highst area overlap with the raster cell.

The real world exercise is to rasterize polygons of soil-IDs in R, in order to produce relatively low resolution maps of soil properties as model inputs.

The problem is that the rasterize() function of the terra package (and similar stars' st_rasterize()) assigns the cell value from the polygon that contains the cell midpoint. If a raster cell contains multiple polygons, I would rather like to select the value of the polygon (soil-ID), which has the highest aerea cover in a raster cell.

Here is a small self-contained example that visualizes my problem, using terra.

library(terra)

f <- system.file("ex/lux.shp", package="terra")
v <- vect(f)
r <- rast(v, ncols = 3, nrow = 3)
rcc <- vect(xyFromCell(r, cell = 1:ncell(r)))

x <- rasterize(v, r, field = "NAME_2")
plot(x)
lines(r, col = "light gray")
lines(v)
points(rcc)

Mostly, the polygons that contain the cell center also seem to have the highest area share. However, in some cases (top row, 3rd cell), this is not the case.
The problem appears to get worse the bigger the cells are compared with the polygons. I could therefore start with high resolution raster, and than resample to the desired (lower) resolution, using an aggregation function (e.g. the mode). But, maybe someone has a more efficient idea?

Thank you for your help!

Body:
You could do that like this:

#Example data
library(terra)
f <- system.file("ex/lux.shp", package="terra")
v <- vect(f)
r <- rast(v, ncols = 3, nrow = 3)

n <- 10
r <- disagg(r, n)
r <- rasterize(v, r, "ID_2")
x <- aggregate(r, n, "modal")

plot(x)
lines(x)
lines(v, lwd=2)
text(v, col="red", halo=T)
text(x, col="blue", halo=T)

Another way, probably less efficient (especially if you have many IDs):

z <- lapply(1:nrow(v), \(i) rasterize(v[i,], r, cover=TRUE))
z <- which.max(rast(z))

But you could replace rasterize with exactextractr::coverage_fraction if you want very high precision

Even less efficient, I suppose:

r <- rast(v, ncols = 3, nrow = 3)
values(r) <- 1:ncell(r)
# get weights
e <- extract(r, v, weights=TRUE)
e <- as.matrix(e)
head(e)
#    ID lyr.1 weight
#[1,]  1     1   0.38
#[2,]  1     2   0.49
#[3,]  2     2   0.06
#[4,]  2     4   0.05
#[5,]  2     5   0.52
#[6,]  2     6   0.06

# find cell with max weight (you can use dplyr or data.table intead)
x <- sapply(unique(e[,2]), function(i) {
    d <- e[e[,2] == i, ,drop=FALSE]
    d[which.max(d[,3]), 2:1]
})

# remove values
r <- rast(r)
# assign ID to cells
r[x[1,]] <- x[2,]

You could achieve the same with using polygon intersection, but that does not scale well to large rasters

r <- rast(v, ncols = 3, nrow = 3)
values(r) <- 1:9
v$ID <- 1:nrow(v)
i <- intersect(v[,"ID"], as.polygons(r))
i$area <- expanse(i)
i <- data.frame(i)
x <- sapply(split(i, i[,2]),
    \(x) { x[which.max(x[,3]), 2:1] |> unlist()}
)
r <- rast(r)
r[x[1,]] <- x[2,]

(perhaps not as elegant as st_join proposed by lovalery)


问:
My Discord.js bot is not generating invite link
I just started working on discord.js and I don't know a lot of things. I added a code to the bot that should generate a link to invite it to the server and send it to the console. But instead of a link, the following error is issued:

```<code>D:\Discord Shield\node_modules\discord.js\src\client\Client.js:488
      throw new TypeError('INVITE_MISSING_SCOPES');
      ^

TypeError [INVITE_MISSING_SCOPES]: At least one valid scope must be provided for the invite
    at Client.generateInvite (D:\Discord Shield\node_modules\discord.js\src\client\Client.js:488:13)
    at Client.<anonymous> (D:\Discord Shield\index.js:11:9)
    at Client.emit (node:events:390:28)
    at WebSocketManager.triggerClientReady (D:\Discord Shield\node_modules\discord.js\src\client\websocket\WebSocketManager.js:383:17)
    at WebSocketManager.checkShardsReady (D:\Discord Shield\node_modules\discord.js\src\client\websocket\WebSocketManager.js:366:10)
    at WebSocketShard.<anonymous> (D:\Discord Shield\node_modules\discord.js\src\client\websocket\WebSocketManager.js:188:14)
    at WebSocketShard.emit (node:events:390:28)
    at WebSocketShard.checkReady (D:\Discord Shield\node_modules\discord.js\src\client\websocket\WebSocketShard.js:474:12)
    at WebSocketShard.onPacket (D:\Discord Shield\node_modules\discord.js\src\client\websocket\WebSocketShard.js:446:16)
    at WebSocketShard.onMessage (D:\Discord Shield\node_modules\discord.js\src\client\websocket\WebSocketShard.js:300:10) {
  [Symbol(code)]: 'INVITE_MISSING_SCOPES'
}

Node.js v17.0.1
</code>```

Here is my code:

```<code>const Discord = require('discord.js');
const bot = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
bot.commands = new Discord.Collection();
const fs = require('fs')
let config = require('./botconfig.json');
let token = config.token;
let prefix = config.prefix;

bot.on('ready', () => {
    console.log(`Bot connected. Logged as ${bot.user.username}`);
    bot.generateInvite({
        permissions: ['ANDMINISTRATOR'],
    })
        .then(link => console.log(`Generated bot invite link: ${link}`))
        .catch(console.error);
});

bot.login(token)
</code>```

答:
I know that v12 is fetchInvites() and v13 is invites.fetch() but is not finding the code and the inviter in v13..

```<code>```
client.on("ready", async () => {

      client.memberLogs = client.guilds.cache.get('788488117404303390').channels.cache.get('899659530894471220')
      invites = await client.guilds.cache.get('788488117404303390').fetchInvites(); // v13 invites.fetch()

    });

    let invites;
    client.on('guildMemberAdd', async member => {
      member.guild.fetchInvites().then(async guildInvites => {
        const ei = invites;
        invites = guildInvites;
        const invite = guildInvites.find(i => ei.get(i.code).uses < i.uses);
        let embed = new discord.MessageEmbed()
     .setAuthor(member.user.tag, member.user.avatarURL())
        .setDescription("Joined!")
        .setTimestamp()
        .setFooter(member.guild.name)
            .addField("__Members__", member.guild.memberCount);
        if (invite) {
          embed.addField("__Invite Code__", invite.code, true);
          let inviter = client.users.cache.get(invite.inviter.id);
          if (inviter)
            embed.addField("__Invited by__", inviter.tag, true);
          else
            embed.addField("__Invited By__", "Unknown", true);// this is what i get in v13
          const doc = client.invites.get(inviter.id.toString());
          if (doc && doc.invites.length !== 0)
            embed.addField("__The User Have__", (doc.invites.length + 1) + "Invites")
          else
            embed.addField("The User has", "1 invite")
        } else {
            embed.addField("__Invite Code__", "Unknown", true); // this is what i get in v13
            embed.addField("__Invite Code__", "Unknown", true); // this is what i get in v13
        }
        client.memberLogs.send(embed);
        (await client.memberLogs.send(member.toString() + invite.inviter.toString())).delete();
        let doc = client.invites.get(invite.inviter.id.toString())
        if (!doc)
          doc = {
            id: invite.inviter.id.toString()
          };
        if (!doc.invites)
          doc.invites = [];
        doc.invites.push(member.id.toString())
        client.invites.set(invite.inviter.id.toString(), doc);
      });
    })

    client.on('guildMemberRemove', async member => {
      const all = client.invites.all().map(i => JSON.parse(i.data));
      for (let one of all) {
        if (one.invites && one.invites.includes(member.id.toString())) {
          one.invites = one.invites.filter(user => user != member.id.toString());
          client.invites.set(one.id, one);
        }
      }
    })
```
please help me thank you
</code>```

Body:
I just started working on discord.js and I don't know a lot of things. I added a code to the bot that should generate a link to invite it to the server and send it to the console. But instead of a link, the following error is issued:

D:\Discord Shield\node_modules\discord.js\src\client\Client.js:488
      throw new TypeError('INVITE_MISSING_SCOPES');
      ^

TypeError [INVITE_MISSING_SCOPES]: At least one valid scope must be provided for the invite
    at Client.generateInvite (D:\Discord Shield\node_modules\discord.js\src\client\Client.js:488:13)
    at Client.<anonymous> (D:\Discord Shield\index.js:11:9)
    at Client.emit (node:events:390:28)
    at WebSocketManager.triggerClientReady (D:\Discord Shield\node_modules\discord.js\src\client\websocket\WebSocketManager.js:383:17)
    at WebSocketManager.checkShardsReady (D:\Discord Shield\node_modules\discord.js\src\client\websocket\WebSocketManager.js:366:10)
    at WebSocketShard.<anonymous> (D:\Discord Shield\node_modules\discord.js\src\client\websocket\WebSocketManager.js:188:14)
    at WebSocketShard.emit (node:events:390:28)
    at WebSocketShard.checkReady (D:\Discord Shield\node_modules\discord.js\src\client\websocket\WebSocketShard.js:474:12)
    at WebSocketShard.onPacket (D:\Discord Shield\node_modules\discord.js\src\client\websocket\WebSocketShard.js:446:16)
    at WebSocketShard.onMessage (D:\Discord Shield\node_modules\discord.js\src\client\websocket\WebSocketShard.js:300:10) {
  [Symbol(code)]: 'INVITE_MISSING_SCOPES'
}

Node.js v17.0.1

Here is my code:

const Discord = require('discord.js');
const bot = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
bot.commands = new Discord.Collection();
const fs = require('fs')
let config = require('./botconfig.json');
let token = config.token;
let prefix = config.prefix;

bot.on('ready', () => {
    console.log(`Bot connected. Logged as ${bot.user.username}`);
    bot.generateInvite({
        permissions: ['ANDMINISTRATOR'],
    })
        .then(link => console.log(`Generated bot invite link: ${link}`))
        .catch(console.error);
});

bot.login(token)

Body:
I know that v12 is fetchInvites() and v13 is invites.fetch() but is not finding the code and the inviter in v13..

```
client.on("ready", async () => {

      client.memberLogs = client.guilds.cache.get('788488117404303390').channels.cache.get('899659530894471220')
      invites = await client.guilds.cache.get('788488117404303390').fetchInvites(); // v13 invites.fetch()

    });

    let invites;
    client.on('guildMemberAdd', async member => {
      member.guild.fetchInvites().then(async guildInvites => {
        const ei = invites;
        invites = guildInvites;
        const invite = guildInvites.find(i => ei.get(i.code).uses < i.uses);
        let embed = new discord.MessageEmbed()
     .setAuthor(member.user.tag, member.user.avatarURL())
        .setDescription("Joined!")
        .setTimestamp()
        .setFooter(member.guild.name)
            .addField("__Members__", member.guild.memberCount);
        if (invite) {
          embed.addField("__Invite Code__", invite.code, true);
          let inviter = client.users.cache.get(invite.inviter.id);
          if (inviter)
            embed.addField("__Invited by__", inviter.tag, true);
          else
            embed.addField("__Invited By__", "Unknown", true);// this is what i get in v13
          const doc = client.invites.get(inviter.id.toString());
          if (doc && doc.invites.length !== 0)
            embed.addField("__The User Have__", (doc.invites.length + 1) + "Invites")
          else
            embed.addField("The User has", "1 invite")
        } else {
            embed.addField("__Invite Code__", "Unknown", true); // this is what i get in v13
            embed.addField("__Invite Code__", "Unknown", true); // this is what i get in v13
        }
        client.memberLogs.send(embed);
        (await client.memberLogs.send(member.toString() + invite.inviter.toString())).delete();
        let doc = client.invites.get(invite.inviter.id.toString())
        if (!doc)
          doc = {
            id: invite.inviter.id.toString()
          };
        if (!doc.invites)
          doc.invites = [];
        doc.invites.push(member.id.toString())
        client.invites.set(invite.inviter.id.toString(), doc);
      });
    })

    client.on('guildMemberRemove', async member => {
      const all = client.invites.all().map(i => JSON.parse(i.data));
      for (let one of all) {
        if (one.invites && one.invites.includes(member.id.toString())) {
          one.invites = one.invites.filter(user => user != member.id.toString());
          client.invites.set(one.id, one);
        }
      }
    })
```
please help me thank you


问:
DIV Refresh on a Object File
I've created a DIV that loads a text file. The goal is to update the text file and have the output correctly displayed in the browser. It works; however, when I update the text file, the contents do not display in the browser until I do a ctrl-F5 to hard refresh the page.

```<code><div id="outage"><object width=475 data="outage.txt"></object></div>
</code>```

How can I refresh the DIV or OBJECT to correctly display the data in the text file?

答:
I think that's what you mean? Ajax can be used in this process.
If you want what has been written in the file to be moved to the 'div' immediately after the 'save' then I don't think it's possible to do it except by back-end</p>
```<code><div id="outage">
  <object width=475 data="outage.txt"></object>
</div>
<button class="bttn">Update</button>

<script>

   document.querySelector(".bttn").addEventListener("click", (e) => {
      e.preventDefault()
      document.querySelector('#outage').innerHTML = "";
      document.querySelector('#outage').innerHTML = `<object width=475
      data="outage.txt"></object>`;
   });

</script>
</code>```

Title: DIV Refresh on a Object File

Body:
I've created a DIV that loads a text file. The goal is to update the text file and have the output correctly displayed in the browser. It works; however, when I update the text file, the contents do not display in the browser until I do a ctrl-F5 to hard refresh the page.

<object width=475 data="outage.txt"></object>

How can I refresh the DIV or OBJECT to correctly display the data in the text file?

Body:
I think that's what you mean? Ajax can be used in this process.
If you want what has been written in the file to be moved to the 'div' immediately after the 'save' then I don't think it's possible to do it except by back-end

<div id="outage">
  <object width=475 data="outage.txt"></object>
</div>
<button class="bttn">Update</button>

<script>

   document.querySelector(".bttn").addEventListener("click", (e) => {
      e.preventDefault()
      document.querySelector('#outage').innerHTML = "";
      document.querySelector('#outage').innerHTML = `<object width=475
      data="outage.txt"></object>`;
   });

</script>


问:
Invalid frame dimension (negative or non-finite)
I'm new to this platform but swift is giving me a headache it is seeming to have a problem with the value (Infinity) although what should I put instead?</p>
```<code> .bold()
 .frame(width: .infinity, height: 20, alignment: .topLeading)
 Text(course.type)
 .font(.system(size: 15, weight: .light))
 .frame(width: .infinity, height: 10, alignment: .topLeading )
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
                Button {
                    openURL(URL(string: course.link)!)
                       }
            label: {
                Text("GET").bold()
                    .frame(width: 35, height: 1)

                    .padding()
                    .foregroundColor(Color(.white))
                    .background(Color(.orange))

                    .cornerRadius(25)
}
}.frame(width: .infinity, height: .infinity)
.padding()
</code>```

答: Try only setting a frame when you have to, and use .none instead of .infinity.

Body:
I'm new to this platform but swift is giving me a headache it is seeming to have a problem with the value (Infinity) although what should I put instead?

 .bold()
 .frame(width: .infinity, height: 20, alignment: .topLeading)
 Text(course.type)
 .font(.system(size: 15, weight: .light))
 .frame(width: .infinity, height: 10, alignment: .topLeading )
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
                Button {
                    openURL(URL(string: course.link)!)
                       }
            label: {
                Text("GET").bold()
                    .frame(width: 35, height: 1)

                    .padding()
                    .foregroundColor(Color(.white))
                    .background(Color(.orange))

                    .cornerRadius(25)
}
}.frame(width: .infinity, height: .infinity)
.padding()


问:
Avoid multiple DOCTYPE and html tags when using ui:include
we are using several ui:include tags in the "main" page. The page that is to be included looks like this:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns=".." xmlns:ui="..." ...>
    <ui:fragment rendered="${foo}">
       some html code
    </ui:fragement>
    <ui:fragment rendered="${!foo || bar}">
       some more html code
    </ui:fragement>
</html>
</code>```

Using the ui:include for templating results in repeating the DOCTYPE and html tag several times in the source code, which is pretty ugly. (Sure, the user doesn't see, but I'm a fan of tidy html)

However, if I remove the DOCTYPE and html tag from the to-be-included-xhtml, the Faces Servlet throws an exception stating that the prefix ui for ui:fragment is not bound.

Does anybody know, how I can include another XHTML page without the multiple DOCTYPEs and htmls?

答:
You should take a look at the ui:composition tag.
We also use ui:include to include jsf2 pages, and to solve the problem you have I believe you could alter your included page by adding the ui:composition tag as follows:</p>

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns=".." xmlns:ui="..." ...>
    <ui:composition>
    <ui:fragment rendered="${foo}">
       some html code
    </ui:fragement>
    <ui:fragment rendered="${!foo || bar}">
       some more html code
    </ui:fragement>
    </ui:composition>
</html>
</code>```

Body:
we are using several ui:include tags in the "main" page. The page that is to be included looks like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <ui:fragment rendered="${foo}">
       some html code
    </ui:fragement>
    <ui:fragment rendered="${!foo || bar}">
       some more html code
    </ui:fragement>

Using the ui:include for templating results in repeating the DOCTYPE and html tag several times in the source code, which is pretty ugly. (Sure, the user doesn't see, but I'm a fan of tidy html)

However, if I remove the DOCTYPE and html tag from the to-be-included-xhtml, the Faces Servlet throws an exception stating that the prefix ui for ui:fragment is not bound.

Does anybody know, how I can include another XHTML page without the multiple DOCTYPEs and htmls?

Body:
You should take a look at the ui:composition tag.
We also use ui:include to include jsf2 pages, and to solve the problem you have I believe you could alter your included page by adding the ui:composition tag as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns=".." xmlns:ui="..." ...>
    <ui:composition>
    <ui:fragment rendered="${foo}">
       some html code
    </ui:fragement>
    <ui:fragment rendered="${!foo || bar}">
       some more html code
    </ui:fragement>
    </ui:composition>
</html>


问:
FATAL ERROR: v8::Object::SetInternalField() Internal field out of bounds on Node js using node-cache
I have a api export with a lot of data so I tried to used the node-cache so the api will be faster since take more than 2 min to get the data, I am new on this so I found the follow code:
Notes: env node js/express

```<code>const NodeCache = require("node-cache");
const axios = require('axios');
const myCache = new NodeCache({stdTTL:100000})
 axios.get('http://localhost:5000/test/example)
        .then(function (response) {
            console.log(response)
            myCache.set("exampleCache",response,10000);
            res.send(response)
</code>```

Any suggestion or recommend will be great!

答: The solution was using a buffer but since we had to many data, the increase the memory from the db was the solution</p>

Body:
I have a api export with a lot of data so I tried to used the node-cache so the api will be faster since take more than 2 min to get the data, I am new on this so I found the follow code:
Notes: env node js/express

const NodeCache = require("node-cache");
const axios = require('axios');
const myCache = new NodeCache({stdTTL:100000})
 axios.get('http://localhost:5000/test/example)
        .then(function (response) {
            console.log(response)
            myCache.set("exampleCache",response,10000);
            res.send(response)

Any suggestion or recommend will be great!


问:
fetch() unexpected end of input
I am using fetch() to grab data from api server. My error looks like this:

```<code>Uncaught (in promise) SyntaxError: Unexpected end of input at
  fetch.then.blob.
</code>```

Can you please tell me what am I doing wrong.

```<code>const weatherAPi ='https://www.metaweather.com/api/location/523920';
fetch(weatherAPi, {
  mode: 'no-cors'
}).then(blob => blob.json())
  .then(data => console.log(data))
</code>```

答:
Adding to Pibo's answer...

I dont know how this happened, but I solved it just by changing

return fetch(url, {
        mode: "no-cors" // <----------------
    })
    .then((res)=>{
        return res.text();
    })
    .then((data)=>{
        console.log(data);
        return new Promise((resolve, reject)=>{
            resolve(data ? JSON.parse(data) : {})
        })
    })
```
<p>to</p>
<pre class="lang-js prettyprint-override"><code>return fetch(url, {
        mode: "cors" // <----------------
    })
    .then((res)=>{
        return res.text();
    })
    .then((data)=>{
        console.log(data);
        return new Promise((resolve, reject)=>{
            resolve(data ? JSON.parse(data) : {})
        })
    })

</code>```

Title: fetch() unexpected end of input

Body:
I am using fetch() to grab data from api server. My error looks like this:

Uncaught (in promise) SyntaxError: Unexpected end of input at
  fetch.then.blob.

Can you please tell me what am I doing wrong.

const weatherAPi ='https://www.metaweather.com/api/location/523920';
fetch(weatherAPi, {
  mode: 'no-cors'
}).then(blob => blob.json())
  .then(data => console.log(data))

Body:
Adding to Pibo's answer...

I dont know how this happened, but I solved it just by changing

return fetch(url, {
        mode: "no-cors" // <----------------
    })
    .then((res)=>{
        return res.text();
    })
    .then((data)=>{
        console.log(data);
        return new Promise((resolve, reject)=>{
            resolve(data ? JSON.parse(data) : {})
        })
    })

to

return fetch(url, {
        mode: "cors" // <----------------
    })
    .then((res)=>{
        return res.text();
    })
    .then((data)=>{
        console.log(data);
        return new Promise((resolve, reject)=>{
            resolve(data ? JSON.parse(data) : {})
        })
    })


问:
Is it necessary to stop/close SignalR stream with CancelationToken.Cancel()?
I have concern about how to properly stop/close SignalR stream. It is server-to-client streaming.

I'll try to explain the context of streaming. We have web service that connects to IP camera and opens stream with it. Later in service we biometrically process that images(frames) and than stream  that biometrically processed images to clients that are connected to SignalR stream. There aren't many connected client, maybe few 2, 3 or 4 max.

So, my concern is, if one of that client wants to disconnect from stream, does it need to call CancelationToken.Cancel() or we could just let him break from while(true) loop on server? When that client disconnects from stream, stream should continue to work as other clients are still connected.

Some brief example on how could client break from while(true) loop.

```<code>public async IAsyncEnumerable<PreviewImage> StartStreamingPreviewImages(string deviceID, [EnumeratorCancellation] CancellationToken cancellationToken)
{
    while(true)
    {
        if(client.WantToLeaveStream)
        {
            break;
        }
    }

...
</code>```

or

```<code>public async IAsyncEnumerable<PreviewImage> StartStreamingPreviewImages(string deviceID, [EnumeratorCancellation] CancellationToken cancellationToken)
{
    while(true)
    {
        if(cancellationToken.IsCancellationRequested)
        {
            cancellationToken.ThrowIfCancellationRequested();
        }
    }

...
</code>```

I went through docs on Microsoft site SignalR stream, and they say that we should use CancelationToken to stop stream, but i also tried stopping it by just leaving while(true) loop and nothing bad happened, stream just stopped. Is that ok? :/

答: Breaking the loop is fine. The method is the one producing stream items, or more specifically the one providing stream items to SignalR, so if you break the loop, you stop producing the items from SignalRs perspective. The docs mention the token because the client can disconnect or cancel listening to the stream and your server probably wants to stop doing extra work in that case.</p>

Body:
I have concern about how to properly stop/close SignalR stream. It is server-to-client streaming.

I'll try to explain the context of streaming. We have web service that connects to IP camera and opens stream with it. Later in service we biometrically process that images(frames) and than stream  that biometrically processed images to clients that are connected to SignalR stream. There aren't many connected client, maybe few 2, 3 or 4 max.

So, my concern is, if one of that client wants to disconnect from stream, does it need to call CancelationToken.Cancel() or we could just let him break from while(true) loop on server? When that client disconnects from stream, stream should continue to work as other clients are still connected.

Some brief example on how could client break from while(true) loop.

public async IAsyncEnumerable<PreviewImage> StartStreamingPreviewImages(string deviceID, [EnumeratorCancellation] CancellationToken cancellationToken)
{
    while(true)
    {
        if(client.WantToLeaveStream)
        {
            break;
        }
    }

...

or

public async IAsyncEnumerable<PreviewImage> StartStreamingPreviewImages(string deviceID, [EnumeratorCancellation] CancellationToken cancellationToken)
{
    while(true)
    {
        if(cancellationToken.IsCancellationRequested)
        {
            cancellationToken.ThrowIfCancellationRequested();
        }
    }

...

I went through docs on Microsoft site SignalR stream, and they say that we should use CancelationToken to stop stream, but i also tried stopping it by just leaving while(true) loop and nothing bad happened, stream just stopped. Is that ok? :/


问:
Using PowerShell to send space character to desktop - to wake screen from sleep
I know the following 2 line PowerShell script sends a space character to a new "shell" object it creates.
Which does bring my sleeping screen out of its slumber.
But that opens, momentarily, a PowerShell window.  So, if the screen is truly asleep-not a problem.

But, there are times of the day when this will run when the screen isn't in a sleeping slumber.  Hence, when that happens, the user sees a very short annoying flash of the created Wscript.Shell

I'd like to just send the space keystroke to the desktop - to wake the sleeping screen.  Without the momentary opening and closing of the Wscript.Shell
i.e., send the " " character to "the desktop" and not to a new shell object.
Is this possible?
I know nothing (obviously) about writing PowerShell.

```<code>$myshell=New-Object -com "Wscript.Shell"
$myshell.sendkeys(" ")
</code>```

Perhaps there is a way the PowerShell script could know if the screen and/or computer is not in a sleep state, and therefore this could all just be avoided from running in that situation?
Any help is much appreciated.

答:
I found my answer. Since I am using AutoHotKey, the following code will use PowerShell to create a new task in task scheduler.  By using the cmd /c start /min "" powershell ... style of command, the pop-up window does not display - but the computer and screen wake up.

```<code>WakeUp:= A_Now
EnvAdd WakeUp, 10, Minutes       ; wake 10 minutes from now
UTC_Delta-= A_NowUTC, Seconds    ; Seconds is more accurate due to rounding issue
UTC_Delta:= Round(-UTC_Delta/60) ; Round to nearest minute to ensure accuracy
WakeUp   += UTC_Delta, Minutes   ; Apply offset to convert to UTC
FormatTime, WakeTime,% WakeUp, "yyyy-MM-ddTHH:mm:ssZ"
psScript =
(
$action = New-ScheduledTaskAction -Execute cmd -Argument '/c start /min "" powershell -WindowStyle Hidden -ExecutionPolicy Bypass -command {$myshell=New-Object -com "Wscript.Shell" $myshell.sendkeys(" ")}'
$settings = New-ScheduledTaskSettingsSet -WakeToRun
$trigger = New-ScheduledTaskTrigger -Once -At %WakeTime%
Register-ScheduledTask -TaskName wakeup -Action $action -Settings $settings -Trigger $trigger -Force
)
RunWait PowerShell.exe -Command &{%psScript%} ,, hide
;use the following if you want to see PowerShell output
;Run PowerShell.exe -NoExit -Command &{%psScript%}
</code>```

Body:
I know the following 2 line PowerShell script sends a space character to a new "shell" object it creates.
Which does bring my sleeping screen out of its slumber.
But that opens, momentarily, a PowerShell window.  So, if the screen is truly asleep-not a problem.

But, there are times of the day when this will run when the screen isn't in a sleeping slumber.  Hence, when that happens, the user sees a very short annoying flash of the created Wscript.Shell

I'd like to just send the space keystroke to the desktop - to wake the sleeping screen.  Without the momentary opening and closing of the Wscript.Shell
i.e., send the " " character to "the desktop" and not to a new shell object.
Is this possible?
I know nothing (obviously) about writing PowerShell.

$myshell=New-Object -com "Wscript.Shell"
$myshell.sendkeys(" ")

Perhaps there is a way the PowerShell script could know if the screen and/or computer is not in a sleep state, and therefore this could all just be avoided from running in that situation?
Any help is much appreciated.

Body:
I found my answer. Since I am using AutoHotKey, the following code will use PowerShell to create a new task in task scheduler.  By using the cmd /c start /min "" powershell ... style of command, the pop-up window does not display - but the computer and screen wake up.

WakeUp:= A_Now
EnvAdd WakeUp, 10, Minutes       ; wake 10 minutes from now
UTC_Delta-= A_NowUTC, Seconds    ; Seconds is more accurate due to rounding issue
UTC_Delta:= Round(-UTC_Delta/60) ; Round to nearest minute to ensure accuracy
WakeUp   += UTC_Delta, Minutes   ; Apply offset to convert to UTC
FormatTime, WakeTime,% WakeUp, "yyyy-MM-ddTHH:mm:ssZ"
psScript =
(
$action = New-ScheduledTaskAction -Execute cmd -Argument '/c start /min "" powershell -WindowStyle Hidden -ExecutionPolicy Bypass -command {$myshell=New-Object -com "Wscript.Shell" $myshell.sendkeys(" ")}'
$settings = New-ScheduledTaskSettingsSet -WakeToRun
$trigger = New-ScheduledTaskTrigger -Once -At %WakeTime%
Register-ScheduledTask -TaskName wakeup -Action $action -Settings $settings -Trigger $trigger -Force
)
RunWait PowerShell.exe -Command &{%psScript%} ,, hide
;use the following if you want to see PowerShell output
;Run PowerShell.exe -NoExit -Command &{%psScript%}