问:
Dependency prevents component scan in Spring Boot Application
I build a minimal example which shows the problem I faced the last days. In short, all dependencies of apereo CAS that I tried prevent my Spring Boot Application from auto configuration or from creating the components and beans. When no CAS dependency is present the application configures as expected. It doesn't matter whether I use any classes from that dependency or not, just to have the dependency present messes things up.

I created a demo project with the spring inizializr with Spring Boot version 2.5.9, Java 11, Maven and Spring Web dependency (see below).

Structure

```<code>demo/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com.example.demo/
│   │   │       ├── beans/
│   │   │       │   ├── BeanComponent.java
│   │   │       │   └── BeanWithoutComponent.java
│   │   │       ├── config/
│   │   │       │   └── DemoConfiguration.java
│   │   │       └── DemoApplication.java
│   │   └── resources/
│   │       ├── static/
│   │       ├── templates/
│   │       └── application.properties
│   └── test/
│       └── java/
│           └── com.example.demo/
│               └── DemoApplicationTests.java
└── pom.xml
</code>```

DemoApplication.java

@SpringBootApplication
public class DemoApplication {

    @Autowired
    private BeanWithoutComponent beanWithoutComponent;

    @Autowired
    private BeanComponent beanComponent;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
```
<p>BeanComponent.java</p>
<pre class="lang-java prettyprint-override"><code>@Component
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
public class BeanComponent {
    public BeanComponent() {
        System.out.println("BeanComponent created");
    }
}
</code>```

BeanWithoutComponent.java

public class BeanWithoutComponent {
    public BeanWithoutComponent() {
        System.out.println("BeanWithoutComponent created");
    }
}
```
<p>DemoConfiguration.java</p>
```@Configuration
public class DemoConfiguration {

    @Bean
    public BeanWithoutComponent beanWithoutComponent() {
        return new BeanWithoutComponent();
    }
}
```
<p>pom.xml</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.9</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <cas.version>6.4.5</cas.version>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.apereo.cas</groupId>
            <artifactId>cas-server-core-services</artifactId>
            <version>${cas.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

application.properties is empty.

When removing the org.apereo.cas dependency the app starts just fine and the beans are autowired as expected.

Is there anything that disables Spring Boot autoconfiguration / component scan? I don't want the dependencies to mess up my own configuration and would like to prevent this behaviour.

答:
Just looked at the sources for this dependency and there are a few configuration files.

You could attempt to exclude the configuration files which you do not want:

Example:

```<code>@SpringBootApplication(exclude = {
    CasCoreServicesConfiguration.class,
})
</code>```

Body:
I build a minimal example which shows the problem I faced the last days. In short, all dependencies of apereo CAS that I tried prevent my Spring Boot Application from auto configuration or from creating the components and beans. When no CAS dependency is present the application configures as expected. It doesn't matter whether I use any classes from that dependency or not, just to have the dependency present messes things up.

I created a demo project with the spring inizializr with Spring Boot version 2.5.9, Java 11, Maven and Spring Web dependency (see below).

Structure

demo/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com.example.demo/
│   │   │       ├── beans/
│   │   │       │   ├── BeanComponent.java
│   │   │       │   └── BeanWithoutComponent.java
│   │   │       ├── config/
│   │   │       │   └── DemoConfiguration.java
│   │   │       └── DemoApplication.java
│   │   └── resources/
│   │       ├── static/
│   │       ├── templates/
│   │       └── application.properties
│   └── test/
│       └── java/
│           └── com.example.demo/
│               └── DemoApplicationTests.java
└── pom.xml

DemoApplication.java

@SpringBootApplication
public class DemoApplication {

    @Autowired
    private BeanWithoutComponent beanWithoutComponent;

    @Autowired
    private BeanComponent beanComponent;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

BeanComponent.java

@Component
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
public class BeanComponent {
    public BeanComponent() {
        System.out.println("BeanComponent created");
    }
}

BeanWithoutComponent.java

public class BeanWithoutComponent {
    public BeanWithoutComponent() {
        System.out.println("BeanWithoutComponent created");
    }
}

DemoConfiguration.java

@Configuration
public class DemoConfiguration {

    @Bean
    public BeanWithoutComponent beanWithoutComponent() {
        return new BeanWithoutComponent();
    }
}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.9</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <cas.version>6.4.5</cas.version>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.apereo.cas</groupId>
            <artifactId>cas-server-core-services</artifactId>
            <version>${cas.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.properties is empty.

When removing the org.apereo.cas dependency the app starts just fine and the beans are autowired as expected.

Is there anything that disables Spring Boot autoconfiguration / component scan? I don't want the dependencies to mess up my own configuration and would like to prevent this behaviour.

Body:
Just looked at the sources for this dependency and there are a few configuration files.

You could attempt to exclude the configuration files which you do not want:

Example:

@SpringBootApplication(exclude = {
    CasCoreServicesConfiguration.class,
})


来源: stackexchange

问:
How to write a unit-test case when a boolean changes twice in jasmine-angular?
I have a basic function statement which changes boolean state of a variable when response comes in from httpClient.get observable

```<code>dataLoading:boolean;

testingFunction(){
  this.dataLoading=true;
  getRequest$.subscribe(result=>{
      this.dataLoading=false;
  })
}
</code>```

To test that I created a test case like below which doesn't work.

```<code>it('Should testingFunction set dataLoading false from true',()=>{
  component.testingFunction();
  expect(component.dataLoading).toBeTrue();
  expect(component.dataLoading).toBeFalse();
});
</code>```

How can I test this change successfully and properly?

答:
Your test doesn't work because it does not synchronize your expect calls with the subscription to getRequest$.

You can do something like:

```<code>// use a Subject so we can control emission from getRequest$
const getRequestSubject = new Subject<string>();

// there is probably a better way to wire this up, but unsure of your implementation
service.getRequest$ = getRequestSubject.asObservable();

service.testingFunction();

// getRequest$ hasn't emitted yet, so do the 'before' check
expect(service.dataLoading).toBeTrue();

// force it to emit
getRequestSubject.next('foo');

// now do the 'after' check
expect(service.dataLoading).toBeFalse();

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a basic function statement which changes boolean state of a variable when response comes in from httpClient.get observable

dataLoading:boolean;

testingFunction(){
  this.dataLoading=true;
  getRequest$.subscribe(result=>{
      this.dataLoading=false;
  })
}

To test that I created a test case like below which doesn't work.

it('Should testingFunction set dataLoading false from true',()=>{
  component.testingFunction();
  expect(component.dataLoading).toBeTrue();
  expect(component.dataLoading).toBeFalse();
});

How can I test this change successfully and properly?

Body:
Your test doesn't work because it does not synchronize your expect calls with the subscription to getRequest$.

You can do something like:

// use a Subject so we can control emission from getRequest$
const getRequestSubject = new Subject<string>();

// there is probably a better way to wire this up, but unsure of your implementation
service.getRequest$ = getRequestSubject.asObservable();

service.testingFunction();

// getRequest$ hasn't emitted yet, so do the 'before' check
expect(service.dataLoading).toBeTrue();

// force it to emit
getRequestSubject.next('foo');

// now do the 'after' check
expect(service.dataLoading).toBeFalse();


问:
How do I correctly override a statically typed method with multiple @overloads (ArgumentParser.parse_args)
I am trying to extend argparse.ArgumentParser.parse_args, but mypy tells me I am doing it wrong:

from argparse import ArgumentParser, Namespace
from typing import Sequence

class MyArgumentParser(ArgumentParser):

    def parse_args(
        self,
        args: Sequence[str] = None,
        namespace: Namespace = None,
    ) -> Namespace:
        parsed_args = super().parse_args(args, namespace)
        # process parsed_args
        return parsed_args
```
<p>I am getting these errors:</p>
```Signature of "parse_args" incompatible with supertype "ArgumentParser"
    Superclass:
        @overload
        def parse_args(self, args: Optional[Sequence[str]] = ...) -> Namespace
        @overload
        def parse_args(self, args: Optional[Sequence[str]], namespace: None) -> Namespace
        @overload
        def [_N] parse_args(self, args: Optional[Sequence[str]], namespace: _N) -> _N
        @overload
        def parse_args(self, *, namespace: None) -> Namespace
        @overload
        def [_N] parse_args(self, *, namespace: _N) -> _N
    Subclass:
        def parse_args(self, args: Optional[Sequence[str]] = ..., namespace: Optional[Namespace] = ...) -> Namespace
```

I have read https://mypy.readthedocs.io/en/stable/class_basics.html#overriding-statically-typed-methods, but still, a number of things are unclear to me:

Where are these five different method signatures coming from? I can only find a single relevant implementation, here:
https://github.com/python/cpython/blob/f20ca766fe404a20daea29230f161a0eb71bb489/Lib/argparse.py#L1843

Do I have to match one of these signatures, or all of them (using some kind of  superset)?

Why is namespace not optional for all of the signatures, although it clearly is in the above implementation?

What is _N?

答:
After learning

that the five @overloads are coming from typeshed, not from argparse itself,

that _N is a placeholder allowing multiple use of an (unknown) variable type (e.g., output type dependent on input type),

that an optional argument does not have to be optional in each of the @overloads, and

that it is not sufficient to match just some superset of all overloads, but that one needs to reproduce the smallest set of constraints (thanks, @hussic),

I had still hoped that the following works:

from argparse import ArgumentParser, Namespace
from typing import Sequence, TypeVar

_N = TypeVar("_N")

class MyArgumentParser(ArgumentParser):
    def parse_args(
        self, args: Sequence[str] = None, namespace: _N = None
    ) -> _N | Namespace:
        return super().parse_args(args, namespace)
```
<p>but of course it does not (see below).</p>
```Signature of "parse_args" incompatible with supertype "ArgumentParser"
    Superclass:
        @overload
        def parse_args(self, args: Optional[Sequence[str]] = ...) -> Namespace
        @overload
        def parse_args(self, args: Optional[Sequence[str]], namespace: None) -> Namespace
        @overload
        def [_N] parse_args(self, args: Optional[Sequence[str]], namespace: _N) -> _N
        @overload
        def parse_args(self, *, namespace: None) -> Namespace
        @overload
        def [_N] parse_args(self, *, namespace: _N) -> _N
    Subclass:
        def [_N] parse_args(self, args: Optional[Sequence[str]] = ..., namespace: Optional[_N] = ...) -> Union[_N, Namespace]
```
<p>What does work is this:</p>
<pre class="lang-py prettyprint-override"><code>from argparse import ArgumentParser, Namespace
from typing import Sequence, TypeVar, overload

_N = TypeVar("_N")

class MyArgumentParser(ArgumentParser):
    # https://github.com/python/typeshed/blob/494481a0/stdlib/argparse.pyi#L128-L137
    @overload
    def parse_args(self, args: Sequence[str] | None = ...) -> Namespace:
        ...

    @overload
    def parse_args(self, args: Sequence[str] | None, namespace: None) -> Namespace:  # type: ignore[misc]
        ...

    @overload
    def parse_args(self, args: Sequence[str] | None, namespace: _N) -> _N:
        ...

    @overload
    def parse_args(self, *, namespace: None) -> Namespace:  # type: ignore[misc]
        ...

    @overload
    def parse_args(self, *, namespace: _N) -> _N:
        ...

    def parse_args(
        self, args: Sequence[str] = None, namespace: _N = None
    ) -> _N | Namespace:
        return super().parse_args(args, namespace)
</code>```

which I find just a tiny bit too verbose, though.

I wonder if there are solutions where I don't have to repeat all @overloads.

To see why the first solution does not work, consider

"""Demonstrate bug."""
from typing import Any, TypeVar, overload

_N = TypeVar("_N", int, float)

class Base:
    """Base class."""

    @overload
    def fun(self, var: None) -> str:
        ...

    @overload
    def fun(self, var: _N) -> _N:
        ...

    def fun(self, var: _N = None) -> _N | str:
        """Return var or "NaN"."""
        if var is None:
            return "NaN"
        return var

class Class1(Base):
    """My class."""

    def fun(self, var: _N = None) -> _N | str:
        """Return var or "None"."""
        return super().fun(var)

class Class2(Base):
    """My class."""

    @overload
    def fun(self, var: None) -> str:
        ...

    @overload
    def fun(self, var: _N) -> _N:
        ...

    def fun(self, var: _N = None) -> _N | str:
        """Return var or "None"."""
        return super().fun(var)

class Class3(Base):
    """My class."""

    def fun(self, var: Any = None) -> Any:
        """Return var or "None"."""
        return super().fun(var)
```

While it is clear that Base.fun returns str only if var is None, the same cannot be said from the signature of Class1.fun. So it seems one needs to replicate the complete set of @overloads such as in Class2.fun, unless one finds a smarter solution (compare @hussic's TypeVar("T", int, str) example) - in which case this should probably be merged into the corresponding package/typeshed directly. Class3.fun is another workaround that somewhat always works.

Body:
I am trying to extend argparse.ArgumentParser.parse_args, but mypy tells me I am doing it wrong:

from argparse import ArgumentParser, Namespace
from typing import Sequence

class MyArgumentParser(ArgumentParser):

    def parse_args(
        self,
        args: Sequence[str] = None,
        namespace: Namespace = None,
    ) -> Namespace:
        parsed_args = super().parse_args(args, namespace)
        # process parsed_args
        return parsed_args

I am getting these errors:

Signature of "parse_args" incompatible with supertype "ArgumentParser"
    Superclass:
        @overload
        def parse_args(self, args: Optional[Sequence[str]] = ...) -> Namespace
        @overload
        def parse_args(self, args: Optional[Sequence[str]], namespace: None) -> Namespace
        @overload
        def [_N] parse_args(self, args: Optional[Sequence[str]], namespace: _N) -> _N
        @overload
        def parse_args(self, *, namespace: None) -> Namespace
        @overload
        def [_N] parse_args(self, *, namespace: _N) -> _N
    Subclass:
        def parse_args(self, args: Optional[Sequence[str]] = ..., namespace: Optional[Namespace] = ...) -> Namespace

I have read https://mypy.readthedocs.io/en/stable/class_basics.html#overriding-statically-typed-methods, but still, a number of things are unclear to me:

Where are these five different method signatures coming from? I can only find a single relevant implementation, here:
https://github.com/python/cpython/blob/f20ca766fe404a20daea29230f161a0eb71bb489/Lib/argparse.py#L1843

Do I have to match one of these signatures, or all of them (using some kind of  superset)?

Why is namespace not optional for all of the signatures, although it clearly is in the above implementation?

What is _N?

Body:
After learning

that the five @overloads are coming from typeshed, not from argparse itself,

that _N is a placeholder allowing multiple use of an (unknown) variable type (e.g., output type dependent on input type),

that an optional argument does not have to be optional in each of the @overloads, and

that it is not sufficient to match just some superset of all overloads, but that one needs to reproduce the smallest set of constraints (thanks, @hussic),

I had still hoped that the following works:

from argparse import ArgumentParser, Namespace
from typing import Sequence, TypeVar

_N = TypeVar("_N")

class MyArgumentParser(ArgumentParser):
    def parse_args(
        self, args: Sequence[str] = None, namespace: _N = None
    ) -> _N | Namespace:
        return super().parse_args(args, namespace)

but of course it does not (see below).

Signature of "parse_args" incompatible with supertype "ArgumentParser"
    Superclass:
        @overload
        def parse_args(self, args: Optional[Sequence[str]] = ...) -> Namespace
        @overload
        def parse_args(self, args: Optional[Sequence[str]], namespace: None) -> Namespace
        @overload
        def [_N] parse_args(self, args: Optional[Sequence[str]], namespace: _N) -> _N
        @overload
        def parse_args(self, *, namespace: None) -> Namespace
        @overload
        def [_N] parse_args(self, *, namespace: _N) -> _N
    Subclass:
        def [_N] parse_args(self, args: Optional[Sequence[str]] = ..., namespace: Optional[_N] = ...) -> Union[_N, Namespace]

What does work is this:

from argparse import ArgumentParser, Namespace
from typing import Sequence, TypeVar, overload

_N = TypeVar("_N")

class MyArgumentParser(ArgumentParser):
    # https://github.com/python/typeshed/blob/494481a0/stdlib/argparse.pyi#L128-L137
    @overload
    def parse_args(self, args: Sequence[str] | None = ...) -> Namespace:
        ...

    @overload
    def parse_args(self, args: Sequence[str] | None, namespace: None) -> Namespace:  # type: ignore[misc]
        ...

    @overload
    def parse_args(self, args: Sequence[str] | None, namespace: _N) -> _N:
        ...

    @overload
    def parse_args(self, *, namespace: None) -> Namespace:  # type: ignore[misc]
        ...

    @overload
    def parse_args(self, *, namespace: _N) -> _N:
        ...

    def parse_args(
        self, args: Sequence[str] = None, namespace: _N = None
    ) -> _N | Namespace:
        return super().parse_args(args, namespace)

which I find just a tiny bit too verbose, though.

I wonder if there are solutions where I don't have to repeat all @overloads.

To see why the first solution does not work, consider

"""Demonstrate bug."""
from typing import Any, TypeVar, overload

_N = TypeVar("_N", int, float)

class Base:
    """Base class."""

    @overload
    def fun(self, var: None) -> str:
        ...

    @overload
    def fun(self, var: _N) -> _N:
        ...

    def fun(self, var: _N = None) -> _N | str:
        """Return var or "NaN"."""
        if var is None:
            return "NaN"
        return var

class Class1(Base):
    """My class."""

    def fun(self, var: _N = None) -> _N | str:
        """Return var or "None"."""
        return super().fun(var)

class Class2(Base):
    """My class."""

    @overload
    def fun(self, var: None) -> str:
        ...

    @overload
    def fun(self, var: _N) -> _N:
        ...

    def fun(self, var: _N = None) -> _N | str:
        """Return var or "None"."""
        return super().fun(var)

class Class3(Base):
    """My class."""

    def fun(self, var: Any = None) -> Any:
        """Return var or "None"."""
        return super().fun(var)

While it is clear that Base.fun returns str only if var is None, the same cannot be said from the signature of Class1.fun. So it seems one needs to replicate the complete set of @overloads such as in Class2.fun, unless one finds a smarter solution (compare @hussic's TypeVar("T", int, str) example) - in which case this should probably be merged into the corresponding package/typeshed directly. Class3.fun is another workaround that somewhat always works.


问:
Npm error 403 when downloading dependencies from Artifactory
I am trying to run a job with a Node.js project. One of the steps is rtnpminstall which runs the npm install command. The rtnpminstall command is run by the Artifactory plugin on Jenkins. The error says.

```<code>npm ERR! code E403
npm ERR! 403 403 Forbidden - GET
 https://<artifactoryurl>/artifactory/api/npm/<npm registry>/<dependency name>
npm ERR! 403 In most cases, you or one of your dependencies are requesting
npm ERR! 403 a package version that is forbidden by your security policy.
</code>```

But when I run using npm install -g, it works fine.

When I can click on the dependency link in the jenkins job log, it downloads fine.

I am trying to see what could be the issue as we do not want to use -g option.

My guess is there night be no write permission on project folder on jenkins agent.

答: In my case, I work bebind the company's proxy and also got this problem. After go throught so many workaround and sill got stuck, I figured out that I've changed my password => _auth value in .npmrc file has changed. That why I couldn't access package files</p>

Body:
I am trying to run a job with a Node.js project. One of the steps is rtnpminstall which runs the npm install command. The rtnpminstall command is run by the Artifactory plugin on Jenkins. The error says.

npm ERR! code E403
npm ERR! 403 403 Forbidden - GET
 https://<artifactoryurl>/artifactory/api/npm/<npm registry>/<dependency name>
npm ERR! 403 In most cases, you or one of your dependencies are requesting
npm ERR! 403 a package version that is forbidden by your security policy.

But when I run using npm install -g, it works fine.

When I can click on the dependency link in the jenkins job log, it downloads fine.

I am trying to see what could be the issue as we do not want to use -g option.

My guess is there night be no write permission on project folder on jenkins agent.


问:
using python I'm trying to insert ADMIN_ID as None in to a database in SQL and my date_time that converted into a suitable format into a table
this works but i cant seem to get the other format to work

```<code>conn=sqlite3.connect("Jakson.db")
("Database Opened successfully")

conn.execute('INSERT INTO SMITH(EXPIRE) VALUES (?)',  [date_time])
</code>```

i know that the date_time will work becasue ive already tested it on its own in a another database but i can seem to get this one to work

```<code>#conn=sqlite3.connect("Jakson.db")
#print("Database Opened successfully")
#conn.execute("""
#CREATE TABLE SMITH(
#ADMIN_ID INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL ,
#EXPIRE DATE
#)
#""")
import datetime
import pytz
import sqlite3

today = datetime.datetime.now()
date_time = today.strftime("%m/%d/%Y")

conn=sqlite3.connect("Jakson.db")
("Database Opened successfully")

conn.execute('INSERT INTO SMITH VALUES (:ADMIN_ID, :EXPIRE)',
         {
         'ADMIN_ID': None,
         'EXPIRE':[date_time]
          })
</code>```

InterfaceError: Error binding parameter :EXPIRE - probably unsupported type.

答:
Use the following:

```<code>conn.execute('INSERT INTO SMITH VALUES (:ADMIN_ID, :EXPIRE)',
             {
             'ADMIN_ID': None,
             'EXPIRE': date_time
              })
</code>```

[date_time] should be without brackets.

Body:
this works but i cant seem to get the other format to work

conn=sqlite3.connect("Jakson.db")
("Database Opened successfully")

conn.execute('INSERT INTO SMITH(EXPIRE) VALUES (?)',  [date_time])

i know that the date_time will work becasue ive already tested it on its own in a another database but i can seem to get this one to work

#conn=sqlite3.connect("Jakson.db")
#print("Database Opened successfully")
#conn.execute("""
#CREATE TABLE SMITH(
#ADMIN_ID INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL ,
#EXPIRE DATE
#)
#""")
import datetime
import pytz
import sqlite3

today = datetime.datetime.now()
date_time = today.strftime("%m/%d/%Y")

conn=sqlite3.connect("Jakson.db")
("Database Opened successfully")

conn.execute('INSERT INTO SMITH VALUES (:ADMIN_ID, :EXPIRE)',
         {
         'ADMIN_ID': None,
         'EXPIRE':[date_time]
          })

InterfaceError: Error binding parameter :EXPIRE - probably unsupported type.

Body:
Use the following:

conn.execute('INSERT INTO SMITH VALUES (:ADMIN_ID, :EXPIRE)',
             {
             'ADMIN_ID': None,
             'EXPIRE': date_time
              })

[date_time] should be without brackets.


问:
Convert JSON to CSV Python - Command Line
I'm a novice at coding, so forgive me but sometimes I need a step-by-step walkthrough. I have a large JSON file (544 MB) that I need to convert to CSV. I have code from another forum to run in VS Code (below). But now I'm not sure what to type in Terminal to actually do the conversion for multiple similar files I need to convert.

Here's the code I have, json-convert.py:

```<code>from copy import deepcopy
import pandas
import json

def cross_join(left, right):
    new_rows = [] if right else left
    for left_row in left:
        for right_row in right:
            temp_row = deepcopy(left_row)
            for key, value in right_row.items():
                temp_row[key] = value
            new_rows.append(deepcopy(temp_row))
    return new_rows

def flatten_list(data):
    for elem in data:
        if isinstance(elem, list):
            yield from flatten_list(elem)
        else:
            yield elem

def json_to_dataframe(data_in):
    def flatten_json(data, prev_heading=''):
        if isinstance(data, dict):
            rows = [{}]
            for key, value in data.items():
                rows = cross_join(rows, flatten_json(value, prev_heading + '.' + key))
        elif isinstance(data, list):
            rows = []
            for i in range(len(data)):
                [rows.append(elem) for elem in flatten_list(flatten_json(data[i], prev_heading))]
        else:
            rows = [{prev_heading[1:]: data}]
        return rows

    return pandas.DataFrame(flatten_json(data_in))

if __name__ == '__main__':
    f = open('pretty-202009.json')
    json_data = json.load(f)
    df = json_to_dataframe(json_data)
    df.to_csv("flight_csv.csv", sep=',', encoding='utf-8')

    # run  in terminal for conversion to csv
</code>```

答:
I will presume that your functions are correct because this isn't the question you asked.

If you have a list of the multiple files why don't you do a for loop over them? Something like:

⋮
if __name__ == '__main__':
    files_to_process = ('pretty-202009.json', 'pretty-202010.json', 'pretty-202011.json')
    for order, current_file_name in enumerate(files_to_process):
        with open(current_file_name) as current_file:
            json_data = json.load(current_file)
            df = json_to_dataframe(json_data)
            df.to_csv(f'flight{order}_csv', sep=',', encoding='utf-8')
```

Body:
I'm a novice at coding, so forgive me but sometimes I need a step-by-step walkthrough. I have a large JSON file (544 MB) that I need to convert to CSV. I have code from another forum to run in VS Code (below). But now I'm not sure what to type in Terminal to actually do the conversion for multiple similar files I need to convert.

Here's the code I have, json-convert.py:

from copy import deepcopy
import pandas
import json

def cross_join(left, right):
    new_rows = [] if right else left
    for left_row in left:
        for right_row in right:
            temp_row = deepcopy(left_row)
            for key, value in right_row.items():
                temp_row[key] = value
            new_rows.append(deepcopy(temp_row))
    return new_rows

def flatten_list(data):
    for elem in data:
        if isinstance(elem, list):
            yield from flatten_list(elem)
        else:
            yield elem

def json_to_dataframe(data_in):
    def flatten_json(data, prev_heading=''):
        if isinstance(data, dict):
            rows = [{}]
            for key, value in data.items():
                rows = cross_join(rows, flatten_json(value, prev_heading + '.' + key))
        elif isinstance(data, list):
            rows = []
            for i in range(len(data)):
                [rows.append(elem) for elem in flatten_list(flatten_json(data[i], prev_heading))]
        else:
            rows = [{prev_heading[1:]: data}]
        return rows

    return pandas.DataFrame(flatten_json(data_in))

if __name__ == '__main__':
    f = open('pretty-202009.json')
    json_data = json.load(f)
    df = json_to_dataframe(json_data)
    df.to_csv("flight_csv.csv", sep=',', encoding='utf-8')

    # run  in terminal for conversion to csv


问:
Install SCOM ( System Center Operation Manager ) on Azure VM with ARM Template
Does anyone have a sample ARM Template to install SCOM agent on an Azure VM ?

I searched through Microsoft docs but couldn't find an example.

Also, What are the other critic points during operating this task?
Could you go through the steps?

Any help is appreciated.

Thanks

答:
•   You can surely install SCOM agent through custom script extension in an ARM template as below. Use a SAS token to download the SCOM agent installation package, viz., MOMAgent.msi in the Azure VM during deployment itself and then use a powershell script to invoke the silent install of SCOM agent.

ARM Template: -

Using the default quickstart template for deploying an Azure VM through ARM template as given in this link : -
https://learn.microsoft.com/en-us/azure/virtual-machines/windows/quick-create-template?toc=/azure/azure-resource-manager/templates/toc.json

In this template, you must add the below custom script extension installation content in ‘resources’ section in the above ARM template. Please check the formatting of the ARM template code correctly, i.e., commas, curly brackets, square brackets, etc. Also, ensure to open HTTPS port 443 inbound also as below. Please ensure that the required ports for successful communication between SCOM Management Server and the SCOM agent installed on the Azure VM are opened as below through the addition of various security rules: -

```<code>"securityRules": [
      {
        "name": "default-allow-3389",
        "properties": {
          "priority": 1000,
          "access": "Allow",
          "direction": "Inbound",
          "destinationPortRange": "3389",
          "protocol": "Tcp",
          "sourcePortRange": "*",
          "sourceAddressPrefix": "*",
          "destinationAddressPrefix": "*"
        }
      },
      {
        "name": "AllowHTTPSInBound",
        "properties": {
          "priority": 1010,
          "access": "Allow",
          "direction": "Inbound",
          "destinationPortRange": "443",
          "protocol": "Tcp",
          "sourcePortRange": "*",
          "sourceAddressPrefix": "*",
          "destinationAddressPrefix": "*"
        }
      }
]
</code>```

For including the custom script extension in your Azure VM deployment, kindly add the below ARM template commands as stated above.

```<code>   {
          "type": "Microsoft.Compute/virtualMachines/extensions",
          "apiVersion": "2021-04-01",
          "name": "[concat(parameters('vmName'),'/', 'InstallWebServer')]",
          "location": "[parameters('location')]",
          "dependsOn": [
            "[concat('Microsoft.Compute/virtualMachines/',parameters('vmName'))]"
          ],
        "properties": {
        "publisher": "Microsoft.Compute",
        "type": "CustomScriptExtension",
        "typeHandlerVersion": "1.7",
        "autoUpgradeMinorVersion": true,
        "protectedSettings": {
          "storageAccountName": "SCOM",
          "storageAccountKey": "EN6iUzOfVe8Ht0xvyxnqK/iXEGTEunznASsumuz0FR4SCvc2mFFHUJfbMy1/GSK7gXk0MB38MMo7+AStoKxC/w==",
          "fileUris": [
            "https://SCOM.blob.core.windows.net/SCOMAgent/Testdemo2.ps1"
          ],
          "commandToExecute": "powershell.exe -ExecutionPolicy Unrestricted -File Testdemo2.ps1"
        }
      }
    }
</code>```

Also, please note that you need to provision a storage account container already for storing the powershell script and the application package in it so that you can use that storage account’s key, its name and the powershell script’s blob URI in place of the same as requested above. Also, please change the name of the powershell script to be executed through the extension in ‘commandToExecute’ section. I have used the name of the script as ‘Testdemo2.ps1’ so have entered the blob URI of that script and its name accordingly in the ARM template above.

Once the above has been done, please ensure the successful execution of silent installation commands for the SCOM agent to be installed locally so that they can be accordingly modified in the powershell script. Please find my powershell script as below. Ensure that this script and the MOMAgent.msi is uploaded beforehand, and the access level of the container is set to ‘Anonymous and public access’: -

```<code> Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
 Install-Module -Name Az.Storage -AllowClobber -Force
 Import-Module -Name Az.Storage -Force
 $StorageAccountName = "SCOM"
 $ContainerName = "SCOMAgent"
 $Blob1Name = "MOMAgent.msi"
 $TargetFolderPath = "C:\"
 $context = New-AzStorageContext -StorageAccountName $StorageAccountName -SASToken "sp=r&st=2022-02-10T08:40:34Z&se=2022-02-10T16:40:34Z&spr=https&sv=2020-08-04&sr=b&sig=DRDulljKTJiRbVPAXAJkTHi8QlnlbjPpVR3aueEf9xU%3D"
 Get-AzStorageBlobContent -Blob $Blob1Name -Container $ContainerName -Context $context -Destination $TargetFolderPath
 $arg="/I C:\MOMAgent.msi /QN USE_SETTINGS_FROM_AD=1 MANAGEMENT_GROUP=MGname MANAGEMENT_SERVER_DNS=MSname SECURE_PORT=PortNumber ACTIONS_USE_COMPUTER_ACCOUNT=0 ACTIONSUSER=UserName ACTIONSDOMAIN=DomainName ACTIONSPASSWORD=Password INSTALLDIR=C:\ProgramFiles\ AcceptEndUserLicenseAgreement=1"
 Start-Process msiexec.exe -Wait -ArgumentList $arg ’
</code>```

If you intend to modify the above arguments as stated by me for SCOM agent installation on the Azure VM, please refer to the documentation link below. It clearly explains the various command line arguments to be passed for SCOM agent installation. Please note that these arguments depend on your existing SCOM Server setup and configuration settings so accordingly ensure to open/modify the port settings accordingly for Azure VM as well as for other components in the SCOM setup.

https://learn.microsoft.com/en-us/system-center/scom/manage-deploy-windows-agent-manually?view=sc-om-2019#to-deploy-the-operations-manager-agent-from-the-command-line

Then edit the parameters file with the desired values in ‘adminUsername’, ‘adminPassword’ and ‘location’ and save it in the same location where template file is stored and execute the commands below from powershell console with elevated privileges locally, i.e., through the path where these ARM template files are stored by browsing to that path in powershell itself.

```<code>az login
az deployment group create -n <name of the deployment> -g <name of the resource group> --template-file "azuredeployVM.json" --parameters "azuredeployVM.parameters.json" ’
</code>```

Thus, after successful deployment, you will be able to see the SCOM agent installed during the VM creation itself. In this way, you can install the SCOM agent in Azure VM through ARM template with storage account provisioning.

Body:
•   You can surely install SCOM agent through custom script extension in an ARM template as below. Use a SAS token to download the SCOM agent installation package, viz., MOMAgent.msi in the Azure VM during deployment itself and then use a powershell script to invoke the silent install of SCOM agent.

ARM Template: -

Using the default quickstart template for deploying an Azure VM through ARM template as given in this link : -
https://learn.microsoft.com/en-us/azure/virtual-machines/windows/quick-create-template?toc=/azure/azure-resource-manager/templates/toc.json

In this template, you must add the below custom script extension installation content in ‘resources’ section in the above ARM template. Please check the formatting of the ARM template code correctly, i.e., commas, curly brackets, square brackets, etc. Also, ensure to open HTTPS port 443 inbound also as below. Please ensure that the required ports for successful communication between SCOM Management Server and the SCOM agent installed on the Azure VM are opened as below through the addition of various security rules: -

"securityRules": [
      {
        "name": "default-allow-3389",
        "properties": {
          "priority": 1000,
          "access": "Allow",
          "direction": "Inbound",
          "destinationPortRange": "3389",
          "protocol": "Tcp",
          "sourcePortRange": "*",
          "sourceAddressPrefix": "*",
          "destinationAddressPrefix": "*"
        }
      },
      {
        "name": "AllowHTTPSInBound",
        "properties": {
          "priority": 1010,
          "access": "Allow",
          "direction": "Inbound",
          "destinationPortRange": "443",
          "protocol": "Tcp",
          "sourcePortRange": "*",
          "sourceAddressPrefix": "*",
          "destinationAddressPrefix": "*"
        }
      }
]

For including the custom script extension in your Azure VM deployment, kindly add the below ARM template commands as stated above.

   {
          "type": "Microsoft.Compute/virtualMachines/extensions",
          "apiVersion": "2021-04-01",
          "name": "[concat(parameters('vmName'),'/', 'InstallWebServer')]",
          "location": "[parameters('location')]",
          "dependsOn": [
            "[concat('Microsoft.Compute/virtualMachines/',parameters('vmName'))]"
          ],
        "properties": {
        "publisher": "Microsoft.Compute",
        "type": "CustomScriptExtension",
        "typeHandlerVersion": "1.7",
        "autoUpgradeMinorVersion": true,
        "protectedSettings": {
          "storageAccountName": "SCOM",
          "storageAccountKey": "EN6iUzOfVe8Ht0xvyxnqK/iXEGTEunznASsumuz0FR4SCvc2mFFHUJfbMy1/GSK7gXk0MB38MMo7+AStoKxC/w==",
          "fileUris": [
            "https://SCOM.blob.core.windows.net/SCOMAgent/Testdemo2.ps1"
          ],
          "commandToExecute": "powershell.exe -ExecutionPolicy Unrestricted -File Testdemo2.ps1"
        }
      }
    }

Also, please note that you need to provision a storage account container already for storing the powershell script and the application package in it so that you can use that storage account’s key, its name and the powershell script’s blob URI in place of the same as requested above. Also, please change the name of the powershell script to be executed through the extension in ‘commandToExecute’ section. I have used the name of the script as ‘Testdemo2.ps1’ so have entered the blob URI of that script and its name accordingly in the ARM template above.

Once the above has been done, please ensure the successful execution of silent installation commands for the SCOM agent to be installed locally so that they can be accordingly modified in the powershell script. Please find my powershell script as below. Ensure that this script and the MOMAgent.msi is uploaded beforehand, and the access level of the container is set to ‘Anonymous and public access’: -

 Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
 Install-Module -Name Az.Storage -AllowClobber -Force
 Import-Module -Name Az.Storage -Force
 $StorageAccountName = "SCOM"
 $ContainerName = "SCOMAgent"
 $Blob1Name = "MOMAgent.msi"
 $TargetFolderPath = "C:\"
 $context = New-AzStorageContext -StorageAccountName $StorageAccountName -SASToken "sp=r&st=2022-02-10T08:40:34Z&se=2022-02-10T16:40:34Z&spr=https&sv=2020-08-04&sr=b&sig=DRDulljKTJiRbVPAXAJkTHi8QlnlbjPpVR3aueEf9xU%3D"
 Get-AzStorageBlobContent -Blob $Blob1Name -Container $ContainerName -Context $context -Destination $TargetFolderPath
 $arg="/I C:\MOMAgent.msi /QN USE_SETTINGS_FROM_AD=1 MANAGEMENT_GROUP=MGname MANAGEMENT_SERVER_DNS=MSname SECURE_PORT=PortNumber ACTIONS_USE_COMPUTER_ACCOUNT=0 ACTIONSUSER=UserName ACTIONSDOMAIN=DomainName ACTIONSPASSWORD=Password INSTALLDIR=C:\ProgramFiles\ AcceptEndUserLicenseAgreement=1"
 Start-Process msiexec.exe -Wait -ArgumentList $arg ’

If you intend to modify the above arguments as stated by me for SCOM agent installation on the Azure VM, please refer to the documentation link below. It clearly explains the various command line arguments to be passed for SCOM agent installation. Please note that these arguments depend on your existing SCOM Server setup and configuration settings so accordingly ensure to open/modify the port settings accordingly for Azure VM as well as for other components in the SCOM setup.

https://learn.microsoft.com/en-us/system-center/scom/manage-deploy-windows-agent-manually?view=sc-om-2019#to-deploy-the-operations-manager-agent-from-the-command-line

Then edit the parameters file with the desired values in ‘adminUsername’, ‘adminPassword’ and ‘location’ and save it in the same location where template file is stored and execute the commands below from powershell console with elevated privileges locally, i.e., through the path where these ARM template files are stored by browsing to that path in powershell itself.

az login
az deployment group create -n <name of the deployment> -g <name of the resource group> --template-file "azuredeployVM.json" --parameters "azuredeployVM.parameters.json" ’

Thus, after successful deployment, you will be able to see the SCOM agent installed during the VM creation itself. In this way, you can install the SCOM agent in Azure VM through ARM template with storage account provisioning.


问:
Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor'
I am trying to build simple search tab with thymeleaf and Spring boot.
Here is my codes and html files.

scCountry.html

```<code>  <form class="form-inline" action="#"  th:action="@{/search}" modelAttribute="sInput" th:object="${sInput}" method="post">
                <input class="form-control mr-sm-2" type="text" placeholder="Search" th:field="*{keyWord}">
                <input type="submit" value="Submit" />
      <!--      <button class="btn btn-success" type="Submit" value="Submit">Search</button> -->
            </form>
</code>```

Controller.class

```<code> @GetMapping(value="/search")
    public String SearchForm(Model model) {

         SearchInput sInput = new SearchInput();
        model.addAttribute("sInput",sInput);

        return "scCountry";
    }

    @PostMapping(value="/search")
    public String SearchResult(@ModelAttribute("sInput") SearchInput sInput, BindingResult bindingResult, Model model) {
        if (bindingResult.hasErrors()) {
            return "scCountry";
        }

        SearchVO searchVO = null;
        try {
            searchVO = webServices.searchAll(sInput.getKeyWord());
        } catch (TwitterException e) {
            e.printStackTrace();
        }

        model.addAttribute("searchVO",searchVO);

        return "scSearch";
    }
</code>```

Modal Class

```<code>public class SearchInput {

    private String keyWord;
    public String getKeyWord() {
        return keyWord;
    }
    public void setKeyWord(String keyWord) {
        this.keyWord = keyWord;
    }
    public SearchInput() {
    }
    public SearchInput(String keyWord) {
        this.keyWord = keyWord;
    }
}
</code>```

Log

```<code>         :[Ljava.lang.Byte;@3929bes             :[Ljava.lang.Byte;@1995b82018-12-13 20:45:53.989 ERROR 6400 --- [nio-8080-exec-1] org.thymeleaf.TemplateEngine             : [THYMELEAF][http-nio-8080-exec-1] Exception processing template "scCountry": Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "scCountry" - line 31, col 86)
</code>```

org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "scCountry" - line 31, col 86)
at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:117) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.engine.ProcessorTemplateHandler.handleStandaloneElement(ProcessorTemplateHandler.java:918) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.engine.StandaloneElementTag.beHandled(StandaloneElementTag.java:228) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.engine.TemplateModel.process(TemplateModel.java:136) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:661) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098) [thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1072) [thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.spring5.view.ThymeleafView.renderFragment(ThymeleafView.java:354) [thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) [tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468) [tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.31.jar:8.5.31]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_121]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_121]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.31.jar:8.5.31]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_121]
Caused by: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'sInput' available as request attribute
at org.springframework.web.servlet.support.BindStatus.(BindStatus.java:153) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:903) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.thymeleaf.spring5.context.webmvc.SpringWebMvcThymeleafRequestContext.getBindStatus(SpringWebMvcThymeleafRequestContext.java:227) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.spring5.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:305) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:252) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:226) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.spring5.processor.AbstractSpringFieldTagProcessor.doProcess(AbstractSpringFieldTagProcessor.java:174) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
... 56 common frames omitted

2018-12-13 20:45:54.002

ERROR 6400 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "scCountry" - line 31, col 86)] with root cause java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'sInput' available as request attribute at org.springframework.web.servlet.support.BindStatus.

(BindStatus.java:153) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:903) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.thymeleaf.spring5.context.webmvc.SpringWebMvcThymeleafRequestContext.getBindStatus(SpringWebMvcThymeleafRequestContext.java:227) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.spring5.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:305) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:252) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:226) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.spring5.processor.AbstractSpringFieldTagProcessor.doProcess(AbstractSpringFieldTagProcessor.java:174) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.engine.ProcessorTemplateHandler.handleStandaloneElement(ProcessorTemplateHandler.java:918) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.engine.StandaloneElementTag.beHandled(StandaloneElementTag.java:228) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.engine.TemplateModel.process(TemplateModel.java:136) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:661) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]

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

I am getting the error : Neither BindingResult nor plain target object for bean name 'sInput' available as request attribute

I tried the solutions in below which is answered in this platform:

html form validation using thymeleaf not working spring boot

Thymeleaf registration page - Error during execution of processor 'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor'

Spring Thymeleaf TemplateProcessingException in SpringInputGeneralFieldTagProcessor

using search functionality in thymeleaf with request parameters

If I use the form like below,It is working.

```<code><form class="form-inline"   action="/search" method="post">
                <input class="form-control mr-sm-2" type="text"  id="keyWord" name="keyWord" value=""  placeholder="Search" >
                <input type="submit" value="Submit" />
      <!--      <button class="btn btn-success" type="Submit" value="Submit">Search</button> -->
            </form>
</code>```

But I wondering what i am missing for two days?

Could anyone help me ?

I want to know why th:object="${sInput} in the scCountry.html is not fetching the object in the model which i put it in model with the same name?

答:
A was have the same proplem. That helped me. Old code -

```<code>@PostMapping()
public String create(@Valid AdditionalContact additionalContact, BindingResult bindingResult, BindingResult bindingResultForId, Model model) {
   if (bindingResult.hasErrors() || bindingResultForId.hasErrors())
        model.addAttribute("contacts", additionalContact.getAll());
    return "additionalContact/create";
    additionalContactService.save(additionalContact);
    return "redirect:contacts";
    }
</code>```

new code

```<code>@PostMapping()
public String create(@Valid @ModelAttribute("contact") AdditionalContact additionalContact, BindingResult bindingResult,
                         BindingResult bindingResultForId) {

if (bindingResult.hasErrors() || bindingResultForId.hasErrors())
return "additionalContact/create";

additionalContactService.save(additionalContact);
return "redirect:contacts";
}
</code>```

Body:
I am trying to build simple search tab with thymeleaf and Spring boot.
Here is my codes and html files.

scCountry.html

  <form class="form-inline" action="#"  th:action="@{/search}" modelAttribute="sInput" th:object="${sInput}" method="post">
                <input class="form-control mr-sm-2" type="text" placeholder="Search" th:field="*{keyWord}">
                <input type="submit" value="Submit" />

            </form>

Controller.class

 @GetMapping(value="/search")
    public String SearchForm(Model model) {

         SearchInput sInput = new SearchInput();
        model.addAttribute("sInput",sInput);

        return "scCountry";
    }

    @PostMapping(value="/search")
    public String SearchResult(@ModelAttribute("sInput") SearchInput sInput, BindingResult bindingResult, Model model) {
        if (bindingResult.hasErrors()) {
            return "scCountry";
        }

        SearchVO searchVO = null;
        try {
            searchVO = webServices.searchAll(sInput.getKeyWord());
        } catch (TwitterException e) {
            e.printStackTrace();
        }

        model.addAttribute("searchVO",searchVO);

        return "scSearch";
    }

Modal Class

public class SearchInput {

    private String keyWord;
    public String getKeyWord() {
        return keyWord;
    }
    public void setKeyWord(String keyWord) {
        this.keyWord = keyWord;
    }
    public SearchInput() {
    }
    public SearchInput(String keyWord) {
        this.keyWord = keyWord;
    }
}

Log

         :[Ljava.lang.Byte;@3929bes             :[Ljava.lang.Byte;@1995b82018-12-13 20:45:53.989 ERROR 6400 --- [nio-8080-exec-1] org.thymeleaf.TemplateEngine             : [THYMELEAF][http-nio-8080-exec-1] Exception processing template "scCountry": Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "scCountry" - line 31, col 86)

org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "scCountry" - line 31, col 86)
at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:117) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.engine.ProcessorTemplateHandler.handleStandaloneElement(ProcessorTemplateHandler.java:918) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.engine.StandaloneElementTag.beHandled(StandaloneElementTag.java:228) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.engine.TemplateModel.process(TemplateModel.java:136) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:661) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098) [thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1072) [thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.spring5.view.ThymeleafView.renderFragment(ThymeleafView.java:354) [thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) [tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468) [tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.31.jar:8.5.31]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_121]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_121]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.31.jar:8.5.31]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_121]
Caused by: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'sInput' available as request attribute
at org.springframework.web.servlet.support.BindStatus.(BindStatus.java:153) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:903) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.thymeleaf.spring5.context.webmvc.SpringWebMvcThymeleafRequestContext.getBindStatus(SpringWebMvcThymeleafRequestContext.java:227) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.spring5.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:305) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:252) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:226) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.spring5.processor.AbstractSpringFieldTagProcessor.doProcess(AbstractSpringFieldTagProcessor.java:174) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
... 56 common frames omitted

2018-12-13 20:45:54.002

ERROR 6400 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "scCountry" - line 31, col 86)] with root cause java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'sInput' available as request attribute at org.springframework.web.servlet.support.BindStatus.

(BindStatus.java:153) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:903) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.thymeleaf.spring5.context.webmvc.SpringWebMvcThymeleafRequestContext.getBindStatus(SpringWebMvcThymeleafRequestContext.java:227) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.spring5.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:305) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:252) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:226) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.spring5.processor.AbstractSpringFieldTagProcessor.doProcess(AbstractSpringFieldTagProcessor.java:174) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.engine.ProcessorTemplateHandler.handleStandaloneElement(ProcessorTemplateHandler.java:918) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.engine.StandaloneElementTag.beHandled(StandaloneElementTag.java:228) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.engine.TemplateModel.process(TemplateModel.java:136) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:661) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]

...

I am getting the error : Neither BindingResult nor plain target object for bean name 'sInput' available as request attribute

I tried the solutions in below which is answered in this platform:

html form validation using thymeleaf not working spring boot

Thymeleaf registration page - Error during execution of processor 'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor'

Spring Thymeleaf TemplateProcessingException in SpringInputGeneralFieldTagProcessor

using search functionality in thymeleaf with request parameters

If I use the form like below,It is working.

<form class="form-inline"   action="/search" method="post">
                <input class="form-control mr-sm-2" type="text"  id="keyWord" name="keyWord" value=""  placeholder="Search" >
                <input type="submit" value="Submit" />

            </form>

But I wondering what i am missing for two days?

Could anyone help me ?

I want to know why th:object="${sInput} in the scCountry.html is not fetching the object in the model which i put it in model with the same name?

Body:
A was have the same proplem. That helped me. Old code -

@PostMapping()
public String create(@Valid AdditionalContact additionalContact, BindingResult bindingResult, BindingResult bindingResultForId, Model model) {
   if (bindingResult.hasErrors() || bindingResultForId.hasErrors())
        model.addAttribute("contacts", additionalContact.getAll());
    return "additionalContact/create";
    additionalContactService.save(additionalContact);
    return "redirect:contacts";
    }

new code

@PostMapping()
public String create(@Valid @ModelAttribute("contact") AdditionalContact additionalContact, BindingResult bindingResult,
                         BindingResult bindingResultForId) {

if (bindingResult.hasErrors() || bindingResultForId.hasErrors())
return "additionalContact/create";

additionalContactService.save(additionalContact);
return "redirect:contacts";
}


问:
Select the filtered option from the dropdown using Cypress
I have a dropdown, kind of lookup, to test. I have to type a value and based on the value, the options will be filtered. And, I have to chose the option I want.

For example, some of the options filtered based on the value provided will be in the below format:

```<code>ENG 101 English-Read and Write
ENG 101 English-Speaking
ENG 101 English-Listening
MAT 201 Mathematics-Algebra
CSC 301 JAVA-Programming
CSC 301 CSharp-Programming
</code>```

I can only type the values in the first column - 'ENG' or 'MAT' or 'CSC' in the field to filter the options.

Now, if I provide value 'MAT' in the field then only one option will be filtered. No issue with selecting the option 'Mathematics-Algebra'.

If I provide value as 'ENG' to filter then multiple options are filtered. Now, I have to select the option 'English-Listening'. This is where I have the problem.

```<code>cy.get('app-screen').find('#paper-description').type('ENG'); // this is for providing input 'ENG'
cy.get('.overlay-pane').find('mat-option span:nth-child(3)').should('have.text', 'English-Listening'); // this is for selecting the required filtered option.
</code>```

When the above statement is executed, I am getting the below Assertion Error.

```<code>Timed out retrying after 4000ms: expected '[ <span.col-3>, 2 more... ]' to have text English-Listening, but the text was English-Read and WriteEnglish-SpeakingEnglish-Listenting
</code>```

The html structure would be in the below format:

```<code><div class='overlay-pane'>
    <mat-option>
        <span class='.col-1>ENG</span>
        <span class='.col-2>101</span>
        <span class='.col-3>English-Read and Write</span>
    </mat-option>
    <mat-option>
        <span class='.col-1>ENG</span>
        <span class='.col-2>101</span>
        <span class='.col-3>English-Speaking</span>
    </mat-option>
    <mat-option>
        <span class='.col-1>ENG</span>
        <span class='.col-2>101</span>
        <span class='.col-3>English-Listening</span>
    </mat-option>
</div>
</code>```

The option to be selected this time may be 'English-Listening'. Next time, it could be 'English-Speaking' or some other option. How to select the required option out of multiple filtered items from lookup?

答:
You can use within for this:

cy.get('app-screen').find('#paper-description').type('ENG')

cy.get('.overlay-pane')
  .find('mat-option')
  .eq(2)
  .within(() => {
    cy.get('.col-3').should('have.text', 'English-Listening').click()
  })
```
<p>You can also use <code>contains</code> if you don't know the exact position of the texts coming in the suggested list:</p>
<pre class="lang-js prettyprint-override"><code>cy.get('app-screen').find('#paper-description').type('ENG')
cy.contains('span', 'English-Listening').should('be.visible').click()
</code>```

Body:
I have a dropdown, kind of lookup, to test. I have to type a value and based on the value, the options will be filtered. And, I have to chose the option I want.

For example, some of the options filtered based on the value provided will be in the below format:

ENG 101 English-Read and Write
ENG 101 English-Speaking
ENG 101 English-Listening
MAT 201 Mathematics-Algebra
CSC 301 JAVA-Programming
CSC 301 CSharp-Programming

I can only type the values in the first column - 'ENG' or 'MAT' or 'CSC' in the field to filter the options.

Now, if I provide value 'MAT' in the field then only one option will be filtered. No issue with selecting the option 'Mathematics-Algebra'.

If I provide value as 'ENG' to filter then multiple options are filtered. Now, I have to select the option 'English-Listening'. This is where I have the problem.

cy.get('app-screen').find('#paper-description').type('ENG'); // this is for providing input 'ENG'
cy.get('.overlay-pane').find('mat-option span:nth-child(3)').should('have.text', 'English-Listening'); // this is for selecting the required filtered option.

When the above statement is executed, I am getting the below Assertion Error.

Timed out retrying after 4000ms: expected '[ , 2 more... ]' to have text English-Listening, but the text was English-Read and WriteEnglish-SpeakingEnglish-Listenting

The html structure would be in the below format:

    <mat-option>
        ENG
        101
        English-Read and Write
    </mat-option>
    <mat-option>
        ENG
        101
        English-Speaking
    </mat-option>
    <mat-option>
        ENG
        101
        English-Listening
    </mat-option>

The option to be selected this time may be 'English-Listening'. Next time, it could be 'English-Speaking' or some other option. How to select the required option out of multiple filtered items from lookup?

Body:
You can use within for this:

cy.get('app-screen').find('#paper-description').type('ENG')

cy.get('.overlay-pane')
  .find('mat-option')
  .eq(2)
  .within(() => {
    cy.get('.col-3').should('have.text', 'English-Listening').click()
  })

You can also use contains if you don't know the exact position of the texts coming in the suggested list:

cy.get('app-screen').find('#paper-description').type('ENG')
cy.contains('span', 'English-Listening').should('be.visible').click()


问:
How to Initialize a Min Heap?
I'm trying to figure out how I can initialize a min heap using an array. So far my function looks like this:

```<code>    def start_heap(self,n):
        # None positions to be filled with Nodes
        arr = [none][] * n
        for i in arr:
            heapify(i)

    def heapify(self):
        start = self.parent(len(self) - 1) # Start at parent of last leaf
        for j in range(start, -1, -1):      # going to and including the root.
            self.heapify_down(j)

 def heapify_down(self, i):
        n = len(self._pq)
        left, right = self.left(i), self.right(i)
        if left < n:
            child = left
            if right < n and self.pq[right] < self.pq[left]:
                child = right
            if self.pq[child] < self.pq[i]:
                self.swap(i, child)
                self.heapify_down(child)

</code>```

Heapify Down Pseudocode:

```<code>Heapify-down(H,i): Let n = length(H) If 2i>n then
Terminate with H unchanged Else if 2i<n then
Let left=2i, and right=2i+1
Let j be the index that minimizes key[H[left]] and key[H[right]] Else if 2i=n then
Let j=2i Endif
If key[H[j]] < key[H[i]] then
swap the array entries H[i] and H[j] Heapify-down(H , j)
Endif
</code>```

I'm going to build a simple node class that just holds data but I'm not sure how to actually get the start_heap function working. Keep in mind n is the maximum number of elements that can be stored.

答:
Some remarks on the code you provided (not on the code you didn't provide):

arr is a local variable, so whatever you do with it, once the function returns, that arr will be out of scope... and lost. You need an attribute or else subclass list

It is not common practice to "allocate" the array and fill it with None. In Python lists are dynamic, so you don't need to reserve slots ahead of time. You just need an empty list to start with.

There is no need to call heapify when the heap is empty.

There is certainly no need to call heapify many times in a loop. All the logic for heapifying is already present in that method, so no need to call it on each index individually. But as stated in the previous point: no need to call it on an empty list -- there is nothing to move.

So the correction is quite basic:

```<code>    def start_heap(self, max_size):
        self.max_size = max_size
        self._pq = []
</code>```

Then, in many of your other methods, you will have to work with self._pq and self.max_size.

For instance, it could have a method that indicates whether the heap is full:

```<code>    def is_full(self):
        return len(self._pq) >= self.max_size
</code>```

If you have an add method, it would first check if there is still room:

```<code>   def add(self, node):
       if is_full(self):
           raise ValueError("Cannot add value to the heap: it is full")
       # ... rest of your code ...
</code>```

Title: How to Initialize a Min Heap?

Body:
I'm trying to figure out how I can initialize a min heap using an array. So far my function looks like this:

    def start_heap(self,n):
        # None positions to be filled with Nodes
        arr = [none][] * n
        for i in arr:
            heapify(i)

    def heapify(self):
        start = self.parent(len(self) - 1) # Start at parent of last leaf
        for j in range(start, -1, -1):      # going to and including the root.
            self.heapify_down(j)

 def heapify_down(self, i):
        n = len(self._pq)
        left, right = self.left(i), self.right(i)
        if left < n:
            child = left
            if right < n and self.pq[right] < self.pq[left]:
                child = right
            if self.pq[child] < self.pq[i]:
                self.swap(i, child)
                self.heapify_down(child)

Heapify Down Pseudocode:

Heapify-down(H,i): Let n = length(H) If 2i>n then
Terminate with H unchanged Else if 2i<n then
Let left=2i, and right=2i+1
Let j be the index that minimizes key[H[left]] and key[H[right]] Else if 2i=n then
Let j=2i Endif
If key[H[j]] < key[H[i]] then
swap the array entries H[i] and H[j] Heapify-down(H , j)
Endif

I'm going to build a simple node class that just holds data but I'm not sure how to actually get the start_heap function working. Keep in mind n is the maximum number of elements that can be stored.

Body:
Some remarks on the code you provided (not on the code you didn't provide):

arr is a local variable, so whatever you do with it, once the function returns, that arr will be out of scope... and lost. You need an attribute or else subclass list

It is not common practice to "allocate" the array and fill it with None. In Python lists are dynamic, so you don't need to reserve slots ahead of time. You just need an empty list to start with.

There is no need to call heapify when the heap is empty.

There is certainly no need to call heapify many times in a loop. All the logic for heapifying is already present in that method, so no need to call it on each index individually. But as stated in the previous point: no need to call it on an empty list -- there is nothing to move.

So the correction is quite basic:

    def start_heap(self, max_size):
        self.max_size = max_size
        self._pq = []

Then, in many of your other methods, you will have to work with self._pq and self.max_size.

For instance, it could have a method that indicates whether the heap is full:

    def is_full(self):
        return len(self._pq) >= self.max_size

If you have an add method, it would first check if there is still room:

   def add(self, node):
       if is_full(self):
           raise ValueError("Cannot add value to the heap: it is full")
       # ... rest of your code ...


问:
Resuming an s3 bucket listing via boto
I'm iterating over 2 million objects thusly: -

```<code>conn = boto.connect_s3('xxx','xxx')
bucket = conn.lookup('bucket_name')

for key in bucket.list():
  somefunction(key.name)
</code>```

Say it fails at the millionth object, how would I go about resuming this operation from that point?

答:
I figured it out by looking at the boto source.

```<code>def list(self, prefix='', delimiter='', marker='', headers=None):
</code>```

Passing key.name to marker will allow you to resume your operation from that point.

ContentLicense: CC BY-SA 3.0

Title: Resuming an s3 bucket listing via boto

Body:
I'm iterating over 2 million objects thusly: -

conn = boto.connect_s3('xxx','xxx')
bucket = conn.lookup('bucket_name')

for key in bucket.list():
  somefunction(key.name)

Say it fails at the millionth object, how would I go about resuming this operation from that point?

Body:
I figured it out by looking at the boto source.

def list(self, prefix='', delimiter='', marker='', headers=None):

Passing key.name to marker will allow you to resume your operation from that point.


问:
other option beside document.body.innerHTML
this is my code

```<code>  const printDiv = () => {
    const printContents = document.getElementById('id').innerHTML;
    const originalContents = document.body.innerHTML;
    document.body.innerHTML = printContents;
    window.print();
    document.body.innerHTML = originalContents;

    return false;
  };
</code>```

i know when i using innerHTML gives me a string representation of the HTML within an element so i can't handle button or something like that.

actually, i can handle it with reload, but what is the best way? is there any option without reload which make me back to the same page?

答:
```<code>const printContents = document.getElementById('id')
const win = window.open();
win.document.title ="some title";
win.document.body.innerHTML = printContents.innerHTML;

/* if content contains images that needs loading*/
const images = win.document.getElementsByTagName('img');
/*wait for them to load*/

win.print();
</code>```

Body:
this is my code

  const printDiv = () => {
    const printContents = document.getElementById('id').innerHTML;
    const originalContents = document.body.innerHTML;
    document.body.innerHTML = printContents;
    window.print();
    document.body.innerHTML = originalContents;

    return false;
  };

i know when i using innerHTML gives me a string representation of the HTML within an element so i can't handle button or something like that.

actually, i can handle it with reload, but what is the best way? is there any option without reload which make me back to the same page?


问:
Convert part of the values in rows in a data frame
I have a data frame which looks like this:

df

```<code>colA colB
0     0
1     1
0     1
0     1
0     1
1     0
0     0
1     1
0     1
</code>```

I would like to convert a certain proportion of the 0 in colA to NA and a certain proportion of 1 in colB to NA

if I do this:

```<code>df["colA"][df["colA"] == 0] <- NA
</code>```

all the 0 in columns A will be converted to NA, however I just want half of them to be converted

Similarly, for colB I want only 1/3 of the 1 to be converted:

```<code>df["colB"][df["colB"] == 1] <- NA
</code>```

Expected output:

```<code>   colA colB
    0     0
    1     1
    NA    1
    0     1
    NA    1
    1     0
    0     0
    1     NA
    NA    NA
</code>```

答:
I'll contribute a tidyverse approach here.

```<code>library(tidyverse)

df %>% mutate(id_colA = ifelse(colA == 1,  NA, 1:n()),
              colA = ifelse(id_colA %in% sample(na.omit(id_colA), sum(!is.na(id_colA))/2), NA, colA),
              id_colB = ifelse(colB == 0, NA, 1:n()),
              colB = ifelse(id_colB %in% sample(na.omit(id_colB), sum(!is.na(id_colB))/3), NA, colB)) %>%
  select(-starts_with("id_"))
</code>```

Body:
I have a data frame which looks like this:

df

colA colB
0     0
1     1
0     1
0     1
0     1
1     0
0     0
1     1
0     1

I would like to convert a certain proportion of the 0 in colA to NA and a certain proportion of 1 in colB to NA

if I do this:

df["colA"][df["colA"] == 0] <- NA

all the 0 in columns A will be converted to NA, however I just want half of them to be converted

Similarly, for colB I want only 1/3 of the 1 to be converted:

df["colB"][df["colB"] == 1] <- NA

Expected output:

   colA colB
    0     0
    1     1
    NA    1
    0     1
    NA    1
    1     0
    0     0
    1     NA
    NA    NA

Body:
I'll contribute a tidyverse approach here.

library(tidyverse)

df %>% mutate(id_colA = ifelse(colA == 1,  NA, 1:n()),
              colA = ifelse(id_colA %in% sample(na.omit(id_colA), sum(!is.na(id_colA))/2), NA, colA),
              id_colB = ifelse(colB == 0, NA, 1:n()),
              colB = ifelse(id_colB %in% sample(na.omit(id_colB), sum(!is.na(id_colB))/3), NA, colB)) %>%
  select(-starts_with("id_"))


问:
Looping through a nested list and summing all elements of each internal list in python
My problem is as follows: I have a list of lists named 'All_slips.' I would like to loop through each of the lists within the list and sum all of its elements, and then append these sums to a new list called 'Summed_list.' As such my desired output/solution would be a 'Summed_list' = [10,16,19]. A minimum reproducible program is provided below:

```<code>All_slips = [[1,2,3,4],[1,3,5,7],[1,2,7,9]]
Summed_list = []

for j in All_slips[j][] :
    counter = 0
    for i in All_slips[j][i] :
        counter += i
    Summed_list.insert(len(Summed_list),counter)

print (Summed_list)
</code>```

I am new to python and i obtain a syntax error on line 4: 'for j in All_slips[j][]:'. What is the proper syntax to achieve what I stated above - I could not find another post that described this problem. Thanks in advance for your help.

答:
if you want to go with functional programming way, here is one solution

```<code>>>> All_slips = [[1,2,3,4],[1,3,5,7],[1,2,7,9]]
>>> summed_list= list(map(sum , All_slips))
>>> summed_list
[10, 16, 19]
</code>```

otherwise, below would be easy list compreghension one solution

```<code>summed_list = [sum(sub_list) for sub_list in All_slips]
</code>```

if you want to go with for loop, then store sum of a sublist in a varibale for a single iteration and then save this in summed_list

```<code>suumed_list = []
for sub_list in All_slips:
    sublist_sum = 0
    for val in sub_list:
        sublist_sum+= val
    summed_list.append(sublist_sum)
</code>```

Body:
My problem is as follows: I have a list of lists named 'All_slips.' I would like to loop through each of the lists within the list and sum all of its elements, and then append these sums to a new list called 'Summed_list.' As such my desired output/solution would be a 'Summed_list' = [10,16,19]. A minimum reproducible program is provided below:

All_slips = [[1,2,3,4],[1,3,5,7],[1,2,7,9]]
Summed_list = []

for j in All_slips[j][] :
    counter = 0
    for i in All_slips[j][i] :
        counter += i
    Summed_list.insert(len(Summed_list),counter)

print (Summed_list)

I am new to python and i obtain a syntax error on line 4: 'for j in All_slips[j][]:'. What is the proper syntax to achieve what I stated above - I could not find another post that described this problem. Thanks in advance for your help.

Body:
if you want to go with functional programming way, here is one solution

>>> All_slips = [[1,2,3,4],[1,3,5,7],[1,2,7,9]]
>>> summed_list= list(map(sum , All_slips))
>>> summed_list
[10, 16, 19]

otherwise, below would be easy list compreghension one solution

summed_list = [sum(sub_list) for sub_list in All_slips]

if you want to go with for loop, then store sum of a sublist in a varibale for a single iteration and then save this in summed_list

suumed_list = []
for sub_list in All_slips:
    sublist_sum = 0
    for val in sub_list:
        sublist_sum+= val
    summed_list.append(sublist_sum)


问:
C# - using ColorDialog across forms
I have a windows form application.  On the main form a user will enter a number of item, etc and then click a button which will open a new form (either a small form or a large form depending on a checkbox).  Now on my main application I have a file menu - under which is settings - change background colour.  This opens the colordialog.  If a user does not pick anything the background colours will stay default.  However if they change it on the main entry form i change the background of a few textboxes - code below.

```<code>private void warning1ToolStripMenuItem_Click(object sender, EventArgs e)
{
    colorDialog1.ShowDialog();
    Warn1Color = colorDialog1.Color.ToString();
    if (Warn1Color != null)
    {
        tbWarn1Hrs.BackColor = colorDialog1.Color;
        tbWarn1Mins.BackColor = colorDialog1.Color;
        tbWarn1Secs.BackColor = colorDialog1.Color;
        tbWarn1Msg.BackColor = colorDialog1.Color;
    }
}
</code>```

Now my problem is how to I get this to then change the background in the other form that opens.  I was hoping I could pass the string across in the new form constructor as i do with a number of other values.

i.e - here is my code in the new form....(note - string Warn1Color was passed across in constructor and then made = to the string _Warn1Color.  If it is null then background will be default yellow but it cant convert type string to system.drawing.color.  Does anyone see an easy solution to this or what I could do to get this working easily.

```<code>if (_Warn1Color == null)
{
    this.BackColor = System.Drawing.Color.Yellow;
}
else
    this.BackColor = _Warn1Color;
</code>```

答:
I assume you used a string because you wanted to be able to pass null, and System.Drawing.Color being a struct can not be null.

In which case either use Nullable ( http://msdn.microsoft.com/en-us/library/b3h38hb0%28v=vs.80%29.aspx ) which can be null or you can consider some other value as "default", say alpha=0.

To pass a value in your constructor simply go to the code file for the form (the one where you code the stuff for the events) and find the constructor function (has the same name as the form) e.g.:

```<code>namespace MyApp
{
    public partial class MyForm : Form
    {
        public MyForm()
        {
            InitializeComponent();
        }
        ...
</code>```

And add the parameters to it:

```<code>namespace MyApp
{
    public partial class MyForm : Form
    {
        public MyForm(System.drawing.color background)
        {
            InitializeComponent();
            ...do whatever you want with background...
        }
        ...
</code>```

Of course you also need to edit the places you create this form, e.g. change

```<code>form = new MyForm();
form.Show();
</code>```

to

```<code>form = new MyForm(backgroundColour);
form.Show();
</code>```

Title: C# - using ColorDialog across forms

Body:
I have a windows form application.  On the main form a user will enter a number of item, etc and then click a button which will open a new form (either a small form or a large form depending on a checkbox).  Now on my main application I have a file menu - under which is settings - change background colour.  This opens the colordialog.  If a user does not pick anything the background colours will stay default.  However if they change it on the main entry form i change the background of a few textboxes - code below.

private void warning1ToolStripMenuItem_Click(object sender, EventArgs e)
{
    colorDialog1.ShowDialog();
    Warn1Color = colorDialog1.Color.ToString();
    if (Warn1Color != null)
    {
        tbWarn1Hrs.BackColor = colorDialog1.Color;
        tbWarn1Mins.BackColor = colorDialog1.Color;
        tbWarn1Secs.BackColor = colorDialog1.Color;
        tbWarn1Msg.BackColor = colorDialog1.Color;
    }
}

Now my problem is how to I get this to then change the background in the other form that opens.  I was hoping I could pass the string across in the new form constructor as i do with a number of other values.

i.e - here is my code in the new form....(note - string Warn1Color was passed across in constructor and then made = to the string _Warn1Color.  If it is null then background will be default yellow but it cant convert type string to system.drawing.color.  Does anyone see an easy solution to this or what I could do to get this working easily.

if (_Warn1Color == null)
{
    this.BackColor = System.Drawing.Color.Yellow;
}
else
    this.BackColor = _Warn1Color;

Body:
I assume you used a string because you wanted to be able to pass null, and System.Drawing.Color being a struct can not be null.

In which case either use Nullable ( http://msdn.microsoft.com/en-us/library/b3h38hb0%28v=vs.80%29.aspx ) which can be null or you can consider some other value as "default", say alpha=0.

To pass a value in your constructor simply go to the code file for the form (the one where you code the stuff for the events) and find the constructor function (has the same name as the form) e.g.:

namespace MyApp
{
    public partial class MyForm : Form
    {
        public MyForm()
        {
            InitializeComponent();
        }
        ...

And add the parameters to it:

namespace MyApp
{
    public partial class MyForm : Form
    {
        public MyForm(System.drawing.color background)
        {
            InitializeComponent();
            ...do whatever you want with background...
        }
        ...

Of course you also need to edit the places you create this form, e.g. change

form = new MyForm();
form.Show();

to

form = new MyForm(backgroundColour);
form.Show();


问:
Split row into multiple rows to limit length of array in column (spark / scala)
I have a dataframe that looks like this:

+--------------+--------------------+
|id            |           items    |
+--------------+--------------------+
|             1|[a, b, .... x, y, z]|
+--------------+--------------------+
|             1|[q, z, .... x, b, 5]|
+--------------+--------------------+
|             2|[q, z, .... x, b, 5]|
+--------------+--------------------+
```
<p>I want to split the rows so that the array in the <code>items</code> column is at most length 20. If an array has length greater than 20, I would want to make new rows and split the array up so that each array is of length 20 or less. So for the first row in my example dataframe, if we assume the length is 10 and I want at most length 3 for each row, I would like for it to be split like this:</p>
<pre class="lang-none prettyprint-override"><code>+--------------+--------------------+
|id            |           items    |
+--------------+--------------------+
|             1|[a, b, c]           |
+--------------+--------------------+
|             1|[z, y, z]           |
+--------------+--------------------+
|             1|[e, f, g]           |
+--------------+--------------------+
|             1|[q]                 |
+--------------+--------------------+
</code>```

Ideally, all rows should be of length 3 except the last row if the length of the array is not evenly divisible by the max desired length. Note - the id column is not unique

答:
Using higher-order functions transform + filter along with slice, you can split the array into sub arrays of size 20 then explode it:

val l = 20

val df1 = df.withColumn(
  "items",
  explode(
    expr(
      s"filter(transform(items, (x,i)-> IF(i%$l=0, slice(items,i+1,$l), null)), x-> x is not null)"
    )
  )
)
```

Body:
I have a dataframe that looks like this:

+--------------+--------------------+
|id            |           items    |
+--------------+--------------------+
|             1|[a, b, .... x, y, z]|
+--------------+--------------------+
|             1|[q, z, .... x, b, 5]|
+--------------+--------------------+
|             2|[q, z, .... x, b, 5]|
+--------------+--------------------+

I want to split the rows so that the array in the items column is at most length 20. If an array has length greater than 20, I would want to make new rows and split the array up so that each array is of length 20 or less. So for the first row in my example dataframe, if we assume the length is 10 and I want at most length 3 for each row, I would like for it to be split like this:

+--------------+--------------------+
|id            |           items    |
+--------------+--------------------+
|             1|[a, b, c]           |
+--------------+--------------------+
|             1|[z, y, z]           |
+--------------+--------------------+
|             1|[e, f, g]           |
+--------------+--------------------+
|             1|[q]                 |
+--------------+--------------------+

Ideally, all rows should be of length 3 except the last row if the length of the array is not evenly divisible by the max desired length. Note - the id column is not unique


问:
Difference between lightweight checkout and shallow clone in Jenkins
In the pipeline SCM configuration of Jenkins job builder, we have two options- lightweight checkout and shallow clone. What is the difference between these options and when do we use each option?</p>

答:
From the documentation:

Shallow clone.

Perform a shallow clone, so that git will not download the history of the project, saving time and disk space when you just want to access the latest version of a repository.

Lightweight checkout.

If selected, try to obtain the Pipeline script contents directly from the SCM without performing a full checkout. The advantage of this mode is its efficiency; however, you will not get any changelogs or polling based on the SCM. (If you use checkout scm during the build, this will populate the changelog and initialize polling.) Also build parameters will not be substituted into SCM configuration in this mode. Only selected SCM plugins support this mode.

To sum up:

Shallow Clone is the Git feature that lets you pull down just the latest commits, not the entire repo history. So if your project has years of history, or history from thousands of commits, you can select a particular depth to pull.

Lightweight checkout is a Jenkins capability that enables to pull a specific file from the repo, as opposed to the entire repo. So it is useful for example when fetching the Jenkinsfile from a repo because you you need only the specific file and Don't care about other SCM information.