问:
Unsupported bean type: UNRESOLVED_TYPE_VARIABLE, K When using generics
I'm trying my first Quarkus application and are moving from Spring to Quarkus.

In Spring I gererated an helper library where I defined an generic standardservice.

The Service class looks like this:

```<code>public abstract class AbstractService<M extends AbstractModel, K extends Serializable, R extends JpaRepository<M, K>> {

protected R repository;

public AbstractService() {

}

public Optional<M> get(K id) {
    return repository.findById(id);
}

public Optional<M> exists(M model) {
    return repository.findOne(Example.of(model));
}

public List<M> getAll() {
    return repository.findAll();
}

public M addNew(M newModel) {
    return repository.saveAndFlush(newModel);
}

public boolean delete(K id) {
    try {
        repository.deleteById(id);
        return true;
    } catch (Exception ex) {
        return false;
    }
}

public Optional<M> update(M updateModel) {

    Optional<M> mOptional = repository.findById(updateModel.getId());

    if (mOptional.isPresent())
        repository.saveAndFlush(updateModel);

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

The model class looks like this:

```<code>@Getter
@Setter
@MappedSuperclass
@NoArgsConstructor
@AllArgsConstructor
public abstract class AbstractModel {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private K id;
}
</code>```

This is the controller:

```<code>@Slf4j
@RestController
@RequestMapping("service.api.name")
public abstract class AbstractController<M extends AbstractModel, S extends AbstractService<M, K, R>, K extends Serializable, AMA extends AbstractModelAssembler<M, K>, R extends JpaRepository<M, K>> {

@Value("service.api.name")
protected String apiName;

protected S service;

protected AMA assembler;

public AbstractController() {

}

@GetMapping("/{id}")
@ResponseBody
public Response get(@Context UriInfo uriInfo, @PathVariable(value = "id") K id) {

    Optional<M> optionalModel = service.get(id);

    if (optionalModel.isPresent()) {
        return assembler.singleObject(uriInfo, optionalModel.get(), Response.Status.OK);
    } else {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
}

@GetMapping("/getall")
@ResponseBody
public Response getall(@Context UriInfo uriInfo) {
    return assembler.collection(uriInfo, service.getAll(), Response.Status.OK);
}

@PostMapping("/addNew")
@ResponseBody
public Response addNew(@Context UriInfo uriInfo, @RequestBody M newModel) {

    Optional<M> tmpModel = service.exists(newModel);

    if (tmpModel.isPresent()) {
        return assembler.singleObject(uriInfo, tmpModel.get(), Response.Status.SEE_OTHER);
    } else {
        M model = service.addNew(newModel);
        return assembler.singleObject(uriInfo, model, Response.Status.CREATED);
    }
}

@DeleteMapping("/{id}")
@ResponseBody
public Response delete(@PathVariable(value = "id") K id) {
    if (service.delete(id))
        return Response.noContent().build();
    else
        return Response.status(Response.Status.NOT_FOUND).build();
}

@PutMapping("/update")
@ResponseBody
public Response update(@Context UriInfo uriInfo, @RequestBody M updateModel) {

    Optional<M> mOptional = service.update(updateModel);

    if (mOptional.isPresent()) {
        return assembler.singleObject(uriInfo, mOptional.get(), Response.Status.OK);
    } else {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
}
}
</code>```

and this is my Assembler:

```<code>@Component
public abstract class AbstractModelAssembler<M extends AbstractModel, K extends Serializable> {

@value("service.api.name")
protected String apiName;

public Response singleObject(@context UriInfo uriInfo, M model, Response.Status status) {

List<Link> links = initLinks(model, uriInfo);

GenericEntity<M> genericEntity =
    new GenericEntity<>(model) {
    };

Link self = Link.fromUriBuilder(uriInfo.getAbsolutePathBuilder())
    .rel("self").build();

return Response.status(status).entity(genericEntity).links(self).build();
}

public Response collection(@context UriInfo uriInfo, List models, Response.Status status) {

List<Link> links = new ArrayList<>();
models.forEach(m -> links.addAll(initLinks(m, uriInfo)));

GenericEntity<List<M>> genericEntity =
    new GenericEntity<>(models) {
    };

Link self = Link.fromUriBuilder(uriInfo.getAbsolutePathBuilder())
    .rel("self").build();

return Response.status(status).entity(genericEntity).links(self).build();
}

private List initLinks(M model, UriInfo uriInfo) {
UriBuilder uriBuilder = uriInfo.getRequestUriBuilder();
uriBuilder = uriBuilder.path(model.getId().toString());
Link.Builder linkBuilder = Link.fromUriBuilder(uriBuilder);
Link selfLink = linkBuilder.rel("self").build();//.toString().replace("${application.api.name}", apiName);
return Arrays.asList(selfLink);
//model.setLinks(Arrays.asList(selfLink));
}
}
</code>```

When trying to build the native executable, I get this message:

[INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 9.984 s [INFO] Finished at: 2020-05-29T10:52:22+02:00 [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal io.quarkus:quarkus-maven-plugin:1.5.0.Final:build (default) on project QuarkusTemplatePlugin: Failed to build quarkus application: io.quarkus.builder.BuildException: Build failure: Build failed due to errors [ERROR] [error]: Build step io.quarkus.arc.deployment.ArcProcessor#generateResources threw an exception: java.lang.IllegalArgumentException: Unsupported bean type: UNRESOLVED_TYPE_VARIABLE, K [ERROR] at io.quarkus.arc.processor.Types.getTypeHandle(Types.java:141) [ERROR] at io.quarkus.arc.processor.Types.getTypeHandle(Types.java:91) [ERROR] at io.quarkus.arc.processor.Types.getTypeHandle(Types.java:77) [ERROR] at io.quarkus.arc.processor.Types.getTypeHandle(Types.java:91) [ERROR] at io.quarkus.arc.processor.BeanGenerator.initConstructor(BeanGenerator.java:657) [ERROR] at io.quarkus.arc.processor.BeanGenerator.createConstructor(BeanGenerator.java:555) [ERROR] at io.quarkus.arc.processor.BeanGenerator.generateClassBean(BeanGenerator.java:297) [ERROR] at io.quarkus.arc.processor.BeanGenerator.generate(BeanGenerator.java:116) [ERROR] at io.quarkus.arc.processor.BeanProcessor.generateResources(BeanProcessor.java:199) [ERROR] at io.quarkus.arc.deployment.ArcProcessor.generateResources(ArcProcessor.java:393) [ERROR] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [ERROR] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) [ERROR] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [ERROR] at java.base/java.lang.reflect.Method.invoke(Method.java:566) [ERROR] at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:932) [ERROR] at io.quarkus.builder.BuildContext.run(BuildContext.java:277) [ERROR] at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35) [ERROR] at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:2046) [ERROR] at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1578) [ERROR] at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1452) [ERROR] at java.base/java.lang.Thread.run(Thread.java:834) [ERROR] at org.jboss.threads.JBossThread.run(JBossThread.java:479) [ERROR] -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

Am I missing something inside my code or is this a limitation of Quarkus? In Spring I can compile and use it inside services.

答: Rule of thumb when working with native mode in Quarkus: every type that the class/bean needs to use must be accounted for upfront. That said, AbstractModel is missing the type declaration for K. This won't even compile in JVM mode, let alone native.

Body:
I'm trying my first Quarkus application and are moving from Spring to Quarkus.

In Spring I gererated an helper library where I defined an generic standardservice.

The Service class looks like this:

public abstract class AbstractService<M extends AbstractModel, K extends Serializable, R extends JpaRepository<M, K>> {

protected R repository;

public AbstractService() {

}

public Optional<M> get(K id) {
    return repository.findById(id);
}

public Optional<M> exists(M model) {
    return repository.findOne(Example.of(model));
}

public List<M> getAll() {
    return repository.findAll();
}

public M addNew(M newModel) {
    return repository.saveAndFlush(newModel);
}

public boolean delete(K id) {
    try {
        repository.deleteById(id);
        return true;
    } catch (Exception ex) {
        return false;
    }
}

public Optional<M> update(M updateModel) {

    Optional<M> mOptional = repository.findById(updateModel.getId());

    if (mOptional.isPresent())
        repository.saveAndFlush(updateModel);

    return mOptional;
}
}

The model class looks like this:

@Getter
@Setter
@MappedSuperclass
@NoArgsConstructor
@AllArgsConstructor
public abstract class AbstractModel {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private K id;
}

This is the controller:

@Slf4j
@RestController
@RequestMapping("service.api.name")
public abstract class AbstractController<M extends AbstractModel, S extends AbstractService<M, K, R>, K extends Serializable, AMA extends AbstractModelAssembler<M, K>, R extends JpaRepository<M, K>> {

@Value("service.api.name")
protected String apiName;

protected S service;

protected AMA assembler;

public AbstractController() {

}

@GetMapping("/{id}")
@ResponseBody
public Response get(@Context UriInfo uriInfo, @PathVariable(value = "id") K id) {

    Optional<M> optionalModel = service.get(id);

    if (optionalModel.isPresent()) {
        return assembler.singleObject(uriInfo, optionalModel.get(), Response.Status.OK);
    } else {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
}

@GetMapping("/getall")
@ResponseBody
public Response getall(@Context UriInfo uriInfo) {
    return assembler.collection(uriInfo, service.getAll(), Response.Status.OK);
}

@PostMapping("/addNew")
@ResponseBody
public Response addNew(@Context UriInfo uriInfo, @RequestBody M newModel) {

    Optional<M> tmpModel = service.exists(newModel);

    if (tmpModel.isPresent()) {
        return assembler.singleObject(uriInfo, tmpModel.get(), Response.Status.SEE_OTHER);
    } else {
        M model = service.addNew(newModel);
        return assembler.singleObject(uriInfo, model, Response.Status.CREATED);
    }
}

@DeleteMapping("/{id}")
@ResponseBody
public Response delete(@PathVariable(value = "id") K id) {
    if (service.delete(id))
        return Response.noContent().build();
    else
        return Response.status(Response.Status.NOT_FOUND).build();
}

@PutMapping("/update")
@ResponseBody
public Response update(@Context UriInfo uriInfo, @RequestBody M updateModel) {

    Optional<M> mOptional = service.update(updateModel);

    if (mOptional.isPresent()) {
        return assembler.singleObject(uriInfo, mOptional.get(), Response.Status.OK);
    } else {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
}
}

and this is my Assembler:

@Component
public abstract class AbstractModelAssembler<M extends AbstractModel, K extends Serializable> {

@value("service.api.name")
protected String apiName;

public Response singleObject(@context UriInfo uriInfo, M model, Response.Status status) {

List<Link> links = initLinks(model, uriInfo);

GenericEntity<M> genericEntity =
    new GenericEntity<>(model) {
    };

Link self = Link.fromUriBuilder(uriInfo.getAbsolutePathBuilder())
    .rel("self").build();

return Response.status(status).entity(genericEntity).links(self).build();
}

public Response collection(@context UriInfo uriInfo, List models, Response.Status status) {

List<Link> links = new ArrayList<>();
models.forEach(m -> links.addAll(initLinks(m, uriInfo)));

GenericEntity<List<M>> genericEntity =
    new GenericEntity<>(models) {
    };

Link self = Link.fromUriBuilder(uriInfo.getAbsolutePathBuilder())
    .rel("self").build();

return Response.status(status).entity(genericEntity).links(self).build();
}

private List initLinks(M model, UriInfo uriInfo) {
UriBuilder uriBuilder = uriInfo.getRequestUriBuilder();
uriBuilder = uriBuilder.path(model.getId().toString());
Link.Builder linkBuilder = Link.fromUriBuilder(uriBuilder);
Link selfLink = linkBuilder.rel("self").build();//.toString().replace("${application.api.name}", apiName);
return Arrays.asList(selfLink);
//model.setLinks(Arrays.asList(selfLink));
}
}

When trying to build the native executable, I get this message:

[INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 9.984 s [INFO] Finished at: 2020-05-29T10:52:22+02:00 [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal io.quarkus:quarkus-maven-plugin:1.5.0.Final:build (default) on project QuarkusTemplatePlugin: Failed to build quarkus application: io.quarkus.builder.BuildException: Build failure: Build failed due to errors [ERROR] [error]: Build step io.quarkus.arc.deployment.ArcProcessor#generateResources threw an exception: java.lang.IllegalArgumentException: Unsupported bean type: UNRESOLVED_TYPE_VARIABLE, K [ERROR] at io.quarkus.arc.processor.Types.getTypeHandle(Types.java:141) [ERROR] at io.quarkus.arc.processor.Types.getTypeHandle(Types.java:91) [ERROR] at io.quarkus.arc.processor.Types.getTypeHandle(Types.java:77) [ERROR] at io.quarkus.arc.processor.Types.getTypeHandle(Types.java:91) [ERROR] at io.quarkus.arc.processor.BeanGenerator.initConstructor(BeanGenerator.java:657) [ERROR] at io.quarkus.arc.processor.BeanGenerator.createConstructor(BeanGenerator.java:555) [ERROR] at io.quarkus.arc.processor.BeanGenerator.generateClassBean(BeanGenerator.java:297) [ERROR] at io.quarkus.arc.processor.BeanGenerator.generate(BeanGenerator.java:116) [ERROR] at io.quarkus.arc.processor.BeanProcessor.generateResources(BeanProcessor.java:199) [ERROR] at io.quarkus.arc.deployment.ArcProcessor.generateResources(ArcProcessor.java:393) [ERROR] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [ERROR] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) [ERROR] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [ERROR] at java.base/java.lang.reflect.Method.invoke(Method.java:566) [ERROR] at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:932) [ERROR] at io.quarkus.builder.BuildContext.run(BuildContext.java:277) [ERROR] at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35) [ERROR] at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:2046) [ERROR] at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1578) [ERROR] at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1452) [ERROR] at java.base/java.lang.Thread.run(Thread.java:834) [ERROR] at org.jboss.threads.JBossThread.run(JBossThread.java:479) [ERROR] -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

Am I missing something inside my code or is this a limitation of Quarkus? In Spring I can compile and use it inside services.


来源: stackexchange

问:
Making a Windows shortcut start relative to where the folder is?
I have a game that uses this file structure:

```<code>GAME FOLDER
->data
->data->run.bat
</code>```

I want to put a shortcut to run.bat in GAME FOLDER, but if I move it, or someone else installs it it won't work, because the target is wrong. Is there a way to make the target and "start in" relative to GAME FOLDER?

答:
The method that proposed by 'leoj' does not allow passing parameters with spaces.
Us it:

```<code>    cmd.exe /v /c %CD:~0,2%"%CD:~2%\bat\bat\run.bat" "Par1-1 Par1-2" Par2
</code>```

Which will be similar double quote written as in path

```<code>    C:"\Program Files\anyProgram.exe" "Par1-1 Par1-2" Par2
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a game that uses this file structure:

GAME FOLDER
->data
->data->run.bat

I want to put a shortcut to run.bat in GAME FOLDER, but if I move it, or someone else installs it it won't work, because the target is wrong. Is there a way to make the target and "start in" relative to GAME FOLDER?

Body:
The method that proposed by 'leoj' does not allow passing parameters with spaces.
Us it:

    cmd.exe /v /c %CD:~0,2%"%CD:~2%\bat\bat\run.bat" "Par1-1 Par1-2" Par2

Which will be similar double quote written as in path

    C:"\Program Files\anyProgram.exe" "Par1-1 Par1-2" Par2

ContentLicense: CC BY-SA 4.0


问:
Classifier.predict In Python
I have this code in Python:

```<code>def plot_decision_regions(X, y, classifier, resolution = 0.02):

    markers = ('s', 'x', 'o', '^','v')
    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
    cmap = ListedColormap(colors[:len(np.unique(y))])

    x1_min, x1_max = X[:, 0].min() -1, X[:,0].max() + 1
    x2_min, x2_max = X[:, 1].min() -1, X[:,1].max() + 1
   xx1, xx2= np.meshgrid (np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution))
    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
    Z = Z.reshape(xx1.shape)
    plt.contourf(xx1, xx2, Z, alpha= 0.3, cmap = cmap)
    plt.xlim(xx1.min(), xx1.max())
    plt.ylim(xx2.min(), xx2.max())

for idx, cl in enumerate (np.unique(y)):
    plt.scatter (x=X[y == cl, 0], y= X[y == cl, 1], alpha=0.8, c=colors[idx], marker= markers [idx], label = cl, edgecolor = 'black')
</code>```

Where X is a 100x2 vector with normal data (sepal and petla length for 2 kinds of flowers) , y is a  100x1 vector with only -1 and 1 values (class label vector) and Classifier = Perceptron . I don't know why I need to calculate the transpose

```<code>Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
</code>```

What does

```<code>classifier.predict
</code>```

and

```<code>x=X[y == cl, 0], y= X[y == cl, 1]
</code>```

in

```<code>plt.scatter (x=X[y == cl, 0], y= X[y == cl, 1], alpha=0.8, c=colors[idx], marker= markers [idx], label = cl, edgecolor = 'black')
</code>```

do?

I previously load a dataframe, define my predict method, define X and y

```<code>def predict(self,X):
    '''Return class label after unit step'''
    return np.where(self.net_input(X) >= 0.0, 1, -1)
</code>```

And my class = Perceptron contains the w_ (weights) that are adjusted when iterating. Sorry if my english is not perfect

```<code>y = df.iloc[0:100 , 4] .values
y= np.where (y == 'Iris-setosa', -1, 1)

X= df.iloc[0:100, [0,2]].values
</code>```

答:
Let's break this down, first:

```<code>np.array([xx1.ravel(), xx2.ravel()])
</code>```

.ravel() flattens the xx1 and xx2 arrays. xx1 and xx2 are just coordinates (for feature1 and feature2 respectively) arranged in a grid pattern. Idea is that xx1 and xx2 are coordinates at every resolution interval in the range of the feature-set. With enough of these coordinates, you can effectively know what regions are classified as what label by your classifier.

```<code>np.array([xx1.ravel(), xx2.ravel()]).T
</code>```

The reason you need the transpose is because the .predict() method expects as input an array of size [n_samples, n_features]. The result of the ravelled array will be of size [n_features, n_samples], which is why we need to transpose.

```<code>classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T
</code>```

This makes the predictions for each of the meshgrid points (which is then used to make a mask over the plot to show which regions are classified as what label by the classifier).

```<code>plt.scatter (x=X[y == cl, 0], y= X[y == cl, 1], alpha=0.8, c=colors[idx], marker= markers [idx], label = cl, edgecolor = 'black')
</code>```

Here, we plot our samples. We want to plot each class of samples seperately (in order to have them be different colors), so x=X[y == cl, 0] and y= X[y == cl, 1] are saying only plot the point at points where the label is equal to the current one we are inspecting (ie cl). cl will just be an iteration of all the unique possible labels.

It's easier to understand once you see what the result looks like (here's an example using a make_blobs dataset and an MLPClassifier:

```<code>import numpy as np
import matplotlib.pyplot as plt

from matplotlib.colors import ListedColormap
from sklearn.datasets import make_blobs
from sklearn.neural_network import MLPClassifier

def plot_decision_regions(X, y, classifier, resolution = 0.02):
    markers = ('s', 'x', 'o', '^','v')
    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
    cmap = ListedColormap(colors[:len(np.unique(y))])

    x1_min, x1_max = X[:, 0].min() -1, X[:,0].max() + 1
    x2_min, x2_max = X[:, 1].min() -1, X[:,1].max() + 1
    xx1, xx2= np.meshgrid (np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution))
    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
    Z = Z.reshape(xx1.shape)
    plt.contourf(xx1, xx2, Z, alpha= 0.3, cmap = cmap)
    plt.xlim(xx1.min(), xx1.max())
    plt.ylim(xx2.min(), xx2.max())

colors = ['red', 'blue', 'green']
X, y = make_blobs(n_features=2, centers=3)

for idx, cl in enumerate (np.unique(y)):
    plt.scatter (x=X[y == cl, 0], y= X[y == cl, 1], alpha=0.8, c=colors[idx], label = cl, edgecolor = 'black')

classifier = MLPClassifier()
classifier.fit(X, y)

plot_decision_regions(X, y, classifier, resolution = 0.02)
</code>```

You get:

Title: Classifier.predict In Python

Body:
I have this code in Python:

def plot_decision_regions(X, y, classifier, resolution = 0.02):

    markers = ('s', 'x', 'o', '^','v')
    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
    cmap = ListedColormap(colors[:len(np.unique(y))])

    x1_min, x1_max = X[:, 0].min() -1, X[:,0].max() + 1
    x2_min, x2_max = X[:, 1].min() -1, X[:,1].max() + 1
   xx1, xx2= np.meshgrid (np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution))
    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
    Z = Z.reshape(xx1.shape)
    plt.contourf(xx1, xx2, Z, alpha= 0.3, cmap = cmap)
    plt.xlim(xx1.min(), xx1.max())
    plt.ylim(xx2.min(), xx2.max())

for idx, cl in enumerate (np.unique(y)):
    plt.scatter (x=X[y == cl, 0], y= X[y == cl, 1], alpha=0.8, c=colors[idx], marker= markers [idx], label = cl, edgecolor = 'black')

Where X is a 100x2 vector with normal data (sepal and petla length for 2 kinds of flowers) , y is a  100x1 vector with only -1 and 1 values (class label vector) and Classifier = Perceptron . I don't know why I need to calculate the transpose

Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)

What does

classifier.predict

and

x=X[y == cl, 0], y= X[y == cl, 1]

in

plt.scatter (x=X[y == cl, 0], y= X[y == cl, 1], alpha=0.8, c=colors[idx], marker= markers [idx], label = cl, edgecolor = 'black')

do?

I previously load a dataframe, define my predict method, define X and y

def predict(self,X):
    '''Return class label after unit step'''
    return np.where(self.net_input(X) >= 0.0, 1, -1)

And my class = Perceptron contains the w_ (weights) that are adjusted when iterating. Sorry if my english is not perfect

y = df.iloc[0:100 , 4] .values
y= np.where (y == 'Iris-setosa', -1, 1)

X= df.iloc[0:100, [0,2]].values

Body:
Let's break this down, first:

np.array([xx1.ravel(), xx2.ravel()])

.ravel() flattens the xx1 and xx2 arrays. xx1 and xx2 are just coordinates (for feature1 and feature2 respectively) arranged in a grid pattern. Idea is that xx1 and xx2 are coordinates at every resolution interval in the range of the feature-set. With enough of these coordinates, you can effectively know what regions are classified as what label by your classifier.

np.array([xx1.ravel(), xx2.ravel()]).T

The reason you need the transpose is because the .predict() method expects as input an array of size [n_samples, n_features]. The result of the ravelled array will be of size [n_features, n_samples], which is why we need to transpose.

classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T

This makes the predictions for each of the meshgrid points (which is then used to make a mask over the plot to show which regions are classified as what label by the classifier).

plt.scatter (x=X[y == cl, 0], y= X[y == cl, 1], alpha=0.8, c=colors[idx], marker= markers [idx], label = cl, edgecolor = 'black')

Here, we plot our samples. We want to plot each class of samples seperately (in order to have them be different colors), so x=X[y == cl, 0] and y= X[y == cl, 1] are saying only plot the point at points where the label is equal to the current one we are inspecting (ie cl). cl will just be an iteration of all the unique possible labels.

It's easier to understand once you see what the result looks like (here's an example using a make_blobs dataset and an MLPClassifier:

import numpy as np
import matplotlib.pyplot as plt

from matplotlib.colors import ListedColormap
from sklearn.datasets import make_blobs
from sklearn.neural_network import MLPClassifier

def plot_decision_regions(X, y, classifier, resolution = 0.02):
    markers = ('s', 'x', 'o', '^','v')
    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
    cmap = ListedColormap(colors[:len(np.unique(y))])

    x1_min, x1_max = X[:, 0].min() -1, X[:,0].max() + 1
    x2_min, x2_max = X[:, 1].min() -1, X[:,1].max() + 1
    xx1, xx2= np.meshgrid (np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution))
    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
    Z = Z.reshape(xx1.shape)
    plt.contourf(xx1, xx2, Z, alpha= 0.3, cmap = cmap)
    plt.xlim(xx1.min(), xx1.max())
    plt.ylim(xx2.min(), xx2.max())

colors = ['red', 'blue', 'green']
X, y = make_blobs(n_features=2, centers=3)

for idx, cl in enumerate (np.unique(y)):
    plt.scatter (x=X[y == cl, 0], y= X[y == cl, 1], alpha=0.8, c=colors[idx], label = cl, edgecolor = 'black')

classifier = MLPClassifier()
classifier.fit(X, y)

plot_decision_regions(X, y, classifier, resolution = 0.02)

You get:


问:
How do I concatenate symbol-by-symbol two arrays
Im have 2 arrays, for example: [1, 2, 3] and [4, 5, 6] How do i merge them into 1 array?: [1, 4, 2, 5, 3, 6] ? help please </p>

答:
If the order is not important can just use +:

```<code>a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
</code>```

Otherwise you can do something like this:

```<code>a = [1, 2, 3]
b = [4, 5, 6]
c = []
for i, j in zip(a, b):
    c += [i, j]
</code>```

Body:
If the order is not important can just use +:

a = [1, 2, 3]
b = [4, 5, 6]
c = a + b

Otherwise you can do something like this:

a = [1, 2, 3]
b = [4, 5, 6]
c = []
for i, j in zip(a, b):
    c += [i, j]


问:
Dependency injection for Stripe.Net classes
I created a service that allowed me to utilize the Stripe.Net classes (I called it a handler) but it wasn't really testable because in the methods I would instantiate the class. For example:

```<code>public Customer CreateCustomer(string email)
{
    var service = new CustomerService();

    return service.Create(new CustomerCreateOptions
    {
        Email = email
    });
}
</code>```

which it's great when trying to create a test. So I figured I could just use the classes in Stripe.net instead of creating a handler. So I have tried doing this:

```<code>private static void AddTransients(IServiceCollection services)
{
    services.AddTransient<Service<IStripeEntity>>();
    services.AddTransient<ICreatable<IStripeEntity, BaseOptions>>();, BaseOptions));
}
</code>```

Which I through would allow me to pass the classes around my controllers like any other injected class. But when I launch my application I get this error:

Cannot instantiate implementation type 'Stripe.IStripeEntity' for service type 'Stripe.IStripeEntity'.

So I tried registering the classes as generic like this:

```<code>private static void AddTransients(IServiceCollection services)
{
    services.AddTransient(typeof(Service<>));
    services.AddTransient(typeof(ICreatable<,>));
}
</code>```

But when I run that, I get the same error. Does anyone know what I can do to get this to work?

答:
I solved it by creating wrapper classes. Not the most ideal, but it works:</p>

```<code>public class StripeCustomerService : IStripeCustomerService
{
    private readonly CustomerService _customerService;
    public StripeCustomerService() => _customerService = new CustomerService();

    public Customer Create(string email)
    {
        return _customerService.Create(new CustomerCreateOptions
        {
            Email = email
        });
    }

    public async Task<Customer> GetAsync(string id, CancellationToken cancellationToken) =>
        await _customerService.GetAsync(id, cancellationToken: cancellationToken);
}
</code>```

Body:
I created a service that allowed me to utilize the Stripe.Net classes (I called it a handler) but it wasn't really testable because in the methods I would instantiate the class. For example:

public Customer CreateCustomer(string email)
{
    var service = new CustomerService();

    return service.Create(new CustomerCreateOptions
    {
        Email = email
    });
}

which it's great when trying to create a test. So I figured I could just use the classes in Stripe.net instead of creating a handler. So I have tried doing this:

private static void AddTransients(IServiceCollection services)
{
    services.AddTransient<Service<IStripeEntity>>();
    services.AddTransient<ICreatable<IStripeEntity, BaseOptions>>();, BaseOptions));
}

Which I through would allow me to pass the classes around my controllers like any other injected class. But when I launch my application I get this error:

Cannot instantiate implementation type 'Stripe.IStripeEntity' for service type 'Stripe.IStripeEntity'.

So I tried registering the classes as generic like this:

private static void AddTransients(IServiceCollection services)
{
    services.AddTransient(typeof(Service<>));
    services.AddTransient(typeof(ICreatable<,>));
}

But when I run that, I get the same error. Does anyone know what I can do to get this to work?

Body:
I solved it by creating wrapper classes. Not the most ideal, but it works:

public class StripeCustomerService : IStripeCustomerService
{
    private readonly CustomerService _customerService;
    public StripeCustomerService() => _customerService = new CustomerService();

    public Customer Create(string email)
    {
        return _customerService.Create(new CustomerCreateOptions
        {
            Email = email
        });
    }

    public async Task<Customer> GetAsync(string id, CancellationToken cancellationToken) =>
        await _customerService.GetAsync(id, cancellationToken: cancellationToken);
}


问:
com.networknt json-schema-validator not checking Unknown keywords in json
I am using json-schema-validator for validating the requests. It is validating fine.

But, Request contains some invalid objects, it not throwing any error.

Schema

```<code>{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "Product",
    "description": "A product from Acme's catalog",
    "type": "object",
    "properties": {
        "id": {
            "description": "The unique identifier for a product",
            "type": "integer"
        },
        "name": {
            "description": "Name of the product",
            "type": "string"
        },
        "price": {
            "type": "number",
            "minimum": 0,
            "exclusiveMinimum": true
        },
        "tags": {
            "type": "array",
            "items": {
                "type": "string"
            },
            "minItems": 1,
            "uniqueItems": true
        }
    },
    "required": ["id", "name", "price"]
}
</code>```

JSON

```<code>{
    "id": 1,
    "name": "A green door",
    "price": 12.50,
    "tags": ["home", "green"],
    "errorKey":"Invalid JSON"

}
</code>```

"errorKey" is Unknown keywords in the schema, But, this json-schema-validator is not throwing any error.

Is there any way to validate this ?

Dependencies

```<code><dependency>
    <groupId>com.networknt</groupId>
    <artifactId>json-schema-validator</artifactId>
    <version>1.0.40</version>
</dependency>
</code>```

答:
Answer is "additionalProperties":false should be added in schema.

```<code>{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "title": "Product",
    "description": "A product from Acme's catalog",
    "type": "object",
    "properties": {
        "id": {
            "description": "The unique identifier for a product",
            "type": "integer"
        },
        "name": {
            "description": "Name of the product",
            "type": "string"
        },
        "price": {
            "type": "number",
            "minimum": 0
        },
        "tags": {
            "type": "array",
            "items": {
                "type": "string"
            },
            "minItems": 1,
            "uniqueItems": true
        }
    },
    "required": ["id", "name", "price"],
    "additionalProperties":false
}
</code>```

Sample Code:

```<code>public class App {

    public static void main(String arg[]) throws JsonMappingException, JsonProcessingException {

        System.out.println("Test in progress");
        JsonSchemaFactory jsonSchemaFacory = JsonSchemaFactory.getInstance(VersionFlag.V7);
        String schema = "{\r\n" +
                "    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\r\n" +
                "    \"title\": \"Product\",\r\n" +
                "    \"description\": \"A product from Acme's catalog\",\r\n" +
                "    \"type\": \"object\",\r\n" +
                "    \"properties\": {\r\n" +
                "        \"id\": {\r\n" +
                "            \"description\": \"The unique identifier for a product\",\r\n" +
                "            \"type\": \"integer\"\r\n" +
                "        },\r\n" +
                "        \"name\": {\r\n" +
                "            \"description\": \"Name of the product\",\r\n" +
                "            \"type\": \"string\"\r\n" +
                "        },\r\n" +
                "        \"price\": {\r\n" +
                "            \"type\": \"number\",\r\n" +
                "            \"minimum\": 0\r\n" +
                "        },\r\n" +
                "        \"tags\": {\r\n" +
                "            \"type\": \"array\",\r\n" +
                "            \"items\": {\r\n" +
                "                \"type\": \"string\"\r\n" +
                "            },\r\n" +
                "            \"minItems\": 1,\r\n" +
                "            \"uniqueItems\": true\r\n" +
                "        }\r\n" +
                "    },\r\n" +
                "    \"required\": [\"id\", \"name\", \"price\"],\r\n" +
                "   \"additionalProperties\":false\r\n" +
                "   \r\n" +
                "}  ";

        String value = "{\r\n" + "    \"id\": 1,\r\n" + "    \"name\": \"A green door\",\r\n"
                + "    \"price\": 12.50,\r\n" + "    \"tags\": [\"home\", \"green\"],\r\n"
                + "    \"errorKey\":\"Invalid JSON\"\r\n" + "\r\n" + "}";

        ObjectMapper objectMapper = new ObjectMapper();

        JsonNode schemaNode = objectMapper.readTree(schema);
        JsonNode validationFor = objectMapper.readTree(value);
        JsonSchema jsonSchema = jsonSchemaFacory.getSchema(schemaNode);
        Set<ValidationMessage> errorMessage = jsonSchema.validate(validationFor);
        for (ValidationMessage error: errorMessage)
        {
            System.out.println(error.getMessage());
        }

    }

}
</code>```

Output

```<code>$.errorKey: is not defined in the schema and the schema does not allow additional properties
</code>```

Body:
I am using json-schema-validator for validating the requests. It is validating fine.

But, Request contains some invalid objects, it not throwing any error.

Schema

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "Product",
    "description": "A product from Acme's catalog",
    "type": "object",
    "properties": {
        "id": {
            "description": "The unique identifier for a product",
            "type": "integer"
        },
        "name": {
            "description": "Name of the product",
            "type": "string"
        },
        "price": {
            "type": "number",
            "minimum": 0,
            "exclusiveMinimum": true
        },
        "tags": {
            "type": "array",
            "items": {
                "type": "string"
            },
            "minItems": 1,
            "uniqueItems": true
        }
    },
    "required": ["id", "name", "price"]
}

JSON

{
    "id": 1,
    "name": "A green door",
    "price": 12.50,
    "tags": ["home", "green"],
    "errorKey":"Invalid JSON"

}

"errorKey" is Unknown keywords in the schema, But, this json-schema-validator is not throwing any error.

Is there any way to validate this ?

Dependencies

<dependency>
    <groupId>com.networknt</groupId>
    <artifactId>json-schema-validator</artifactId>
    <version>1.0.40</version>
</dependency>

Body:
Answer is "additionalProperties":false should be added in schema.

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "title": "Product",
    "description": "A product from Acme's catalog",
    "type": "object",
    "properties": {
        "id": {
            "description": "The unique identifier for a product",
            "type": "integer"
        },
        "name": {
            "description": "Name of the product",
            "type": "string"
        },
        "price": {
            "type": "number",
            "minimum": 0
        },
        "tags": {
            "type": "array",
            "items": {
                "type": "string"
            },
            "minItems": 1,
            "uniqueItems": true
        }
    },
    "required": ["id", "name", "price"],
    "additionalProperties":false
}

Sample Code:

public class App {

    public static void main(String arg[]) throws JsonMappingException, JsonProcessingException {

        System.out.println("Test in progress");
        JsonSchemaFactory jsonSchemaFacory = JsonSchemaFactory.getInstance(VersionFlag.V7);
        String schema = "{\r\n" +
                "    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\r\n" +
                "    \"title\": \"Product\",\r\n" +
                "    \"description\": \"A product from Acme's catalog\",\r\n" +
                "    \"type\": \"object\",\r\n" +
                "    \"properties\": {\r\n" +
                "        \"id\": {\r\n" +
                "            \"description\": \"The unique identifier for a product\",\r\n" +
                "            \"type\": \"integer\"\r\n" +
                "        },\r\n" +
                "        \"name\": {\r\n" +
                "            \"description\": \"Name of the product\",\r\n" +
                "            \"type\": \"string\"\r\n" +
                "        },\r\n" +
                "        \"price\": {\r\n" +
                "            \"type\": \"number\",\r\n" +
                "            \"minimum\": 0\r\n" +
                "        },\r\n" +
                "        \"tags\": {\r\n" +
                "            \"type\": \"array\",\r\n" +
                "            \"items\": {\r\n" +
                "                \"type\": \"string\"\r\n" +
                "            },\r\n" +
                "            \"minItems\": 1,\r\n" +
                "            \"uniqueItems\": true\r\n" +
                "        }\r\n" +
                "    },\r\n" +
                "    \"required\": [\"id\", \"name\", \"price\"],\r\n" +
                "   \"additionalProperties\":false\r\n" +
                "   \r\n" +
                "}  ";

        String value = "{\r\n" + "    \"id\": 1,\r\n" + "    \"name\": \"A green door\",\r\n"
                + "    \"price\": 12.50,\r\n" + "    \"tags\": [\"home\", \"green\"],\r\n"
                + "    \"errorKey\":\"Invalid JSON\"\r\n" + "\r\n" + "}";

        ObjectMapper objectMapper = new ObjectMapper();

        JsonNode schemaNode = objectMapper.readTree(schema);
        JsonNode validationFor = objectMapper.readTree(value);
        JsonSchema jsonSchema = jsonSchemaFacory.getSchema(schemaNode);
        Set<ValidationMessage> errorMessage = jsonSchema.validate(validationFor);
        for (ValidationMessage error: errorMessage)
        {
            System.out.println(error.getMessage());
        }

    }

}

Output

$.errorKey: is not defined in the schema and the schema does not allow additional properties


问:
html page ends half and doesn't scroll
I am new to html and css trying to build a reporting page directing to display different script output. unfortunately my page display only half with a scroller but I want the output to display in the main page without scroller. It would be great if someone can suggest what is wrong or missing.</p>

```<code>* {
          margin: 0;
          padding: 0;
}

html {
        background-color: #fff;
        color: #555;
        font-family: 'Lato', 'Arial', sans-serif;
        font-weight: 100;
        font-size: 13px;
        overflow-y: visible;
}

table { border-collapse: collapse; } td { font-family:Verdana; font-size:11; vertical-align:center; } th { height:7px;font-family:Verdana; font-si
ze:11; font-style:bold; background-color:#81DAF5 }

.firstsec {
        margin-left: auto;
        margin-right: auto;
        padding-top: 0;
        overflow-y: visible;
        max-width: 1140px;
        background-size: 650px;
        background-image: url(Backup_logo.jpg);
        background-position: center;
        height: 20vh;
}

.toptext  {
        border: 0;
        background-color: #5E10B1;
        color: white;
        width: 25%;
        height: 20vh;
        font-size: 14px;
        text-align: center;
        float: right;
}

.logo {
        margin: 5px;
        width: 22%;
        height: 40px;
        float: left;
}

.section {
        margin-left: auto;
        margin-right: auto;
        width: 1140px;
        overflow-y: visible;
        top: 0; right: 0; bottom: 0; left: 0;
</code>```

答: I got it resolved after updating the closing tag  in my html page.</p>

Title: html page ends half and doesn't scroll

Body:
I am new to html and css trying to build a reporting page directing to display different script output. unfortunately my page display only half with a scroller but I want the output to display in the main page without scroller. It would be great if someone can suggest what is wrong or missing.

* {
          margin: 0;
          padding: 0;
}

html {
        background-color: #fff;
        color: #555;
        font-family: 'Lato', 'Arial', sans-serif;
        font-weight: 100;
        font-size: 13px;
        overflow-y: visible;
}

table { border-collapse: collapse; } td { font-family:Verdana; font-size:11; vertical-align:center; } th { height:7px;font-family:Verdana; font-si
ze:11; font-style:bold; background-color:#81DAF5 }

.firstsec {
        margin-left: auto;
        margin-right: auto;
        padding-top: 0;
        overflow-y: visible;
        max-width: 1140px;
        background-size: 650px;
        background-image: url(Backup_logo.jpg);
        background-position: center;
        height: 20vh;
}

.toptext  {
        border: 0;
        background-color: #5E10B1;
        color: white;
        width: 25%;
        height: 20vh;
        font-size: 14px;
        text-align: center;
        float: right;
}

.logo {
        margin: 5px;
        width: 22%;
        height: 40px;
        float: left;
}

.section {
        margin-left: auto;
        margin-right: auto;
        width: 1140px;
        overflow-y: visible;
        top: 0; right: 0; bottom: 0; left: 0;


问:
How do I overcome issues with MetaboAnalyst in R when trying to run pathway analysis?
I am using this code https://drive.google.com/file/d/1CXluzyYqNoPqu1DI3HwvDAmRVGMe825m/view in order to undertake a pathway analysis using MetaboAnalystR.

When I get to this stage

```<code> mSet<-CalculateOraScore(mSet, "rbc", "hyperg")
</code>```

I get this error

```<code>Loading files from server unsuccessful. Ensure curl is downloaded on your computer

Error in if (is_http) { : argument is of length zero
</code>```

I have gone through the FAQs and troubleshooting pages, and can't rectify this. I have gone through all of the installation steps on another computer ( Windows again unfortunately, and I get the same issue).

This is likely to be a curl problem on Windows. ( It is already installed for me on Windows 10, please see other question What else can I do to make sure that curl is working when I am using R ( MetaboAnalyst package) in Windows 10?).

The trouble shooting advice on https://github.com/xia-lab/MetaboAnalystR/blob/master/R/general_data_utils.R regarding curl issues also does not work for me.

EDIT 2: larger list of compounds

If possible, I would be very grateful if anybody would please be willing to run the below code, and get the graph of Pathway Impact vs -log(p), with a results output, so I can annotate the spots on the graph if neccessary. The code is as follows;

```<code>  library(MetaboAnalystR)
     tmp.vec <- c(tmp.vec <- c("Indole-3-carboxylic acid", "4-O-Methylgallic acid", "Hippuric acid", "Pyrocatechol", "Hydroquinone",
        "Aspartame", "trans-Ferulic acid", "2,6-Dimethoxyphenol", "2-Methylhippuric acid", "2-(Hydroxymethyl)benzoic acid",
        "3-(2-Hydroxyphenyl)propanoic acid", "1-Methyluric acid", "Dehydroisoandrosterone 3-glucuronide", "Ascorbic acid",
        "D-Tartaric acid", "Kynurenic acid", "Xanthine", "Vanillic acid", "Glyceraldehyde", "D-Lactic acid", "Pregnanediol",
        "7-Methylguanine", "Gluconic acid", "4-Aminophenol", "Caffeic acid", "Enterolactone", "Adipic acid",
        "1H-Indole-3-carboxaldehyde", "4-Hydroxybenzoic acid", "Creatinine", "2-Aminobenzoic acid", "Uric acid")

 mSet<-InitDataObjects("conc", "pathora", FALSE)
 mSet<-Setup.MapData(mSet, tmp.vec);
 mSet<-CrossReferencing(mSet, "name");
 mSet<-CreateMappingResultTable(mSet);

 ##4-O-Methylgallic acid and 2-Methylhippuric acid need correct kegg ID format

 mSet$dataSet$map.table[2,5] <- "C05616"
 mSet$dataSet$map.table[9,5] <- "C01586"

 mSet<-SetKEGG.PathLib(mSet, "hsa", "current")
 mSet<-SetMetabolomeFilter(mSet, F)
 mSet<-CalculateOraScore(mSet, "rbc", "hyperg")
 mSet<-PlotPathSummary(mSet, "path_view_0_", "png", 72, width=NA)
</code>```

答:
After spending at least 30 minutes installing dependencies from CRAN and Bioconductor, I was able to get the code to work.

If I had to guess your issue, you probably haven't installed all the dependency packages.

Follow the instructions here:

```<code>#install.packages("pacman")
library(pacman)
pacman::p_load(Rserve, ellipse, scatterplot3d, Cairo, randomForest,
               caTools, e1071, som, impute, pcaMethods, RJSONIO, ROCR,
               globaltest, GlobalAncova, Rgraphviz, preprocessCore, genefilter,
               pheatmap, SSPA, sva, Rcpp, pROC, data.table, limma, car, fitdistrplus,
               lars, Hmisc, magrittr, methods, xtable, pls, caret, lattice, igraph,
               gplots, KEGGgraph, reshape, RColorBrewer, tibble, siggenes, plotly,
               xcms, CAMERA, fgsea, MSnbase)
</code>```

For whatever reason, I had to install the following packages manually as well:

```<code>BiocManager::install("edgeR")
install.packages("crmn")
devtools::install_github("xia-lab/MetaboAnalystR")
</code>```

I ran the analysis on your data. See the output below.

```<code>library(MetaboAnalystR)
tmp.vec <- c("Indole-3-carboxylic acid", "4-O-Methylgallic acid", "Hippuric acid", "Pyrocatechol", "Hydroquinone",
        "Aspartame", "trans-Ferulic acid", "2,6-Dimethoxyphenol", "2-Methylhippuric acid", "2-(Hydroxymethyl)benzoic acid",
        "3-(2-Hydroxyphenyl)propanoic acid", "1-Methyluric acid", "Dehydroisoandrosterone 3-glucuronide", "Ascorbic acid",
        "D-Tartaric acid", "Kynurenic acid", "Xanthine", "Vanillic acid", "Glyceraldehyde", "D-Lactic acid", "Pregnanediol",
        "7-Methylguanine", "Gluconic acid", "4-Aminophenol", "Caffeic acid", "Enterolactone", "Adipic acid",
        "1H-Indole-3-carboxaldehyde", "4-Hydroxybenzoic acid", "Creatinine", "2-Aminobenzoic acid", "Uric acid")
mSet<-InitDataObjects("conc", "pathora", FALSE)
mSet<-Setup.MapData(mSet, tmp.vec)
mSet$dataSet$map.table
      Query                                  Match                                  HMDB          PubChem    KEGG        SMILES                                                                             Comment
 [1,] "Indole-3-carboxylic acid"             "Indole-3-carboxylic acid"             "HMDB0003320" "69867"    "C19837"    "C1=CC=C2C(=C1)C(=CN2)C(=O)O"                                                      "1"
 [2,] "4-O-Methylgallic acid"                "4-O-Methylgallic acid"                "HMDB0013198" "78016"    NA          "COC1=C(C=C(C=C1O)C(=O)O)O"                                                        "1"
 [3,] "Hippuric acid"                        "Hippuric acid"                        "HMDB0000714" "464"      "C01586"    "C1=CC=C(C=C1)C(=O)NCC(=O)O"                                                       "1"
 [4,] "Pyrocatechol"                         "Pyrocatechol"                         "HMDB0000957" "3390"     "C15571"    "C1=CC=C(C(=C1)O)O"                                                                "1"
 [5,] "Hydroquinone"                         "Hydroquinone"                         "HMDB0002434" "785"      "C00530"    "C1=CC(=CC=C1O)O"                                                                  "1"
 [6,] "Aspartame"                            "Aspartame"                            "HMDB0001894" "134601"   "C11045"    "COC(=O)[C@H](CC1=CC=CC=C1)NC(=O)[C@H](CC(=O)O)N"                                  "1"
 [7,] "trans-Ferulic acid"                   "trans-Ferulic acid"                   "HMDB0000954" "445858"   "C01494"    "COC1=C(C=CC(=C1)/C=C/C(=O)O)O"                                                    "1"
 [8,] "2,6-Dimethoxyphenol"                  "2,6-Dimethoxyphenol"                  "HMDB0034158" "7041"     "C10787"    "COC1=C(C(=CC=C1)OC)O"                                                             "1"
 [9,] "2-Methylhippuric acid"                "2-Methylhippuric acid"                "HMDB0011723" "91637"    "\t C01586" "CC1=CC=CC=C1C(=O)NCC(=O)O"                                                        "1"
[10,] "2-(Hydroxymethyl)benzoic acid"        "2-(Hydroxymethyl)benzoic acid"        "HMDB0032594" "11920"    "C10804"    "C1=CC=C(C(=C1)CO)C(=O)O"                                                          "1"
[11,] "3-(2-Hydroxyphenyl)propanoic acid"    "3-(2-Hydroxyphenyl)propanoic acid"    "HMDB0033752" "873"      "C01198"    "C1=CC=C(C(=C1)CCC(=O)O)O"                                                         "1"
[12,] "1-Methyluric acid"                    "1-Methyluric acid"                    "HMDB0003099" "69726"    "C16359"    "CN1C(=O)C2=C(NC(=O)N2)NC1=O"                                                      "1"
[13,] "Dehydroisoandrosterone 3-glucuronide" "Dehydroisoandrosterone 3-glucuronide" "HMDB0010327" "53480448" "C03033"    "CC12CCC3C(C1CCC2=O)CC=C4C3(CCC(C4)O[C@H]5[C@@H]([C@H]([C@@H](C(O5)C(=O)O)O)O)O)C" "1"
[14,] "Ascorbic acid"                        "Ascorbic acid"                        "HMDB0000044" "54670067" "C01041"    "C([C@@H]([C@@H]1C(=C(C(=O)O1)O)O)O)O"                                             "1"
[15,] "D-Tartaric acid"                      "D-Tartaric acid"                      "HMDB0029878" "439655"   "C02107"    "[C@H]([C@@H](C(=O)O)O)(C(=O)O)O"                                                  "1"
[16,] "Kynurenic acid"                       "Kynurenic acid"                       "HMDB0000715" "3845"     "C01717"    "C1=CC=C2C(=C1)C(=O)C=C(N2)C(=O)O"                                                 "1"
[17,] "Xanthine"                             "Xanthine"                             "HMDB0000292" "1188"     "C00385"    "C1=NC2=C(N1)C(=O)NC(=O)N2"                                                        "1"
[18,] "Vanillic acid"                        "Vanillic acid"                        "HMDB0000484" "8468"     "C06672"    "COC1=C(C=CC(=C1)C(=O)O)O"                                                         "1"
[19,] "Glyceraldehyde"                       "Glyceraldehyde"                       "HMDB0001051" "751"      "C02154"    "C(C(C=O)O)O"                                                                      "1"
[20,] "D-Lactic acid"                        "D-Lactic acid"                        "HMDB0001311" "61503"    "C00256"    "C[C@H](C(=O)O)O"                                                                  "1"
[21,] "Pregnanediol"                         "Pregnanediol"                         "HMDB0004025" "3032822"  "C05484"    "CC[C@H]1CC[C@@H]2[C@@]1(CC[C@H]3[C@H]2CCC4[C@@]3(CCC(C4)(O)O)C)C"                 "1"
[22,] "7-Methylguanine"                      "7-Methylguanine"                      "HMDB0000897" "11361"    "C02242"    "CN1C=NC2=C1C(=O)N=C(N2)N"                                                         "1"
[23,] "Gluconic acid"                        "Gluconic acid"                        "HMDB0000625" "10690"    "C00257"    "C([C@H]([C@H]([C@@H]([C@H](C(=O)O)O)O)O)O)O"                                      "1"
[24,] "4-Aminophenol"                        "4-Aminophenol"                        "HMDB0001169" "403"      "C02372"    "C1=CC(=CC=C1N)O"                                                                  "1"
[25,] "Caffeic acid"                         "Caffeic acid"                         "HMDB0001964" "1549111"  "C01481"    "C1=CC(=C(C=C1/C=C\\C(=O)O)O)O"                                                    "1"
[26,] "Enterolactone"                        "Enterolactone"                        "HMDB0006101" "123917"   "C18165"    "C1C(C(C(=O)O1)CC2=CC(=CC=C2)O)CC3=CC(=CC=C3)O"                                    "1"
[27,] "Adipic acid"                          "Adipic acid"                          "HMDB0000448" "196"      "C06104"    "C(CCC(=O)O)CC(=O)O"                                                               "1"
[28,] "1H-Indole-3-carboxaldehyde"           "1H-Indole-3-carboxaldehyde"           "HMDB0029737" "10256"    "C08493"    "C1=CC=C2C(=C1)C(=CN2)C=O"                                                         "1"
[29,] "4-Hydroxybenzoic acid"                "4-Hydroxybenzoic acid"                "HMDB0000500" "135"      "C00156"    "C1=CC(=CC=C1C(=O)O)O"                                                             "1"
[30,] "Creatinine"                           "Creatinine"                           "HMDB0000562" "588"      "C00791"    "CN1CC(=O)N=C1N"                                                                   "1"
[31,] "2-Aminobenzoic acid"                  "2-Aminobenzoic acid"                  "HMDB0001123" "227"      "C00108"    "C1=CC=C(C(=C1)C(=O)O)N"                                                           "1"
[32,] "Uric acid"                            "Uric acid"                            "HMDB0000289" "1175"     "C00366"    "C12=C(NC(=O)N1)NC(=O)NC2=O"                                                       "1"
</code>```

```<code>mSet$dataSet$map.table[2,5] <- "C05616"
mSet$dataSet$map.table[9,5] <- "C01586"
mSet<-SetKEGG.PathLib(mSet, "hsa", "current")
mSet<-SetMetabolomeFilter(mSet, F)
mSet<-CalculateOraScore(mSet, "rbc", "hyperg")
mSet$analSet$ora.mat
                                         Total Expected Hits   Raw p -log(p) Holm adjust FDR  Impact
Caffeine metabolism                         10     0.20    1 0.18341 1.69600           1   1 0.00000
Phenylalanine metabolism                    10     0.20    1 0.18341 1.69600           1   1 0.00000
Pentose and glucuronate interconversions    18     0.36    1 0.30627 1.18330           1   1 0.14062
Pentose phosphate pathway                   22     0.44    1 0.36079 1.01940           1   1 0.04712
Pyruvate metabolism                         22     0.44    1 0.36079 1.01940           1   1 0.08398
Purine metabolism                           65     1.30    2 0.37638 0.97717           1   1 0.01217
Tryptophan metabolism                       41     0.82    1 0.56799 0.56566           1   1 0.00202
</code>```

```<code>PlotPathSummary(mSet, "path_view_0_", "png", 300, width=NA)
</code>```

Body:
I am using this code https://drive.google.com/file/d/1CXluzyYqNoPqu1DI3HwvDAmRVGMe825m/view in order to undertake a pathway analysis using MetaboAnalystR.

When I get to this stage

 mSet<-CalculateOraScore(mSet, "rbc", "hyperg")

I get this error

Loading files from server unsuccessful. Ensure curl is downloaded on your computer

Error in if (is_http) { : argument is of length zero

I have gone through the FAQs and troubleshooting pages, and can't rectify this. I have gone through all of the installation steps on another computer ( Windows again unfortunately, and I get the same issue).

This is likely to be a curl problem on Windows. ( It is already installed for me on Windows 10, please see other question What else can I do to make sure that curl is working when I am using R ( MetaboAnalyst package) in Windows 10?).

The trouble shooting advice on https://github.com/xia-lab/MetaboAnalystR/blob/master/R/general_data_utils.R regarding curl issues also does not work for me.

EDIT 2: larger list of compounds

If possible, I would be very grateful if anybody would please be willing to run the below code, and get the graph of Pathway Impact vs -log(p), with a results output, so I can annotate the spots on the graph if neccessary. The code is as follows;

  library(MetaboAnalystR)
     tmp.vec <- c(tmp.vec <- c("Indole-3-carboxylic acid", "4-O-Methylgallic acid", "Hippuric acid", "Pyrocatechol", "Hydroquinone",
        "Aspartame", "trans-Ferulic acid", "2,6-Dimethoxyphenol", "2-Methylhippuric acid", "2-(Hydroxymethyl)benzoic acid",
        "3-(2-Hydroxyphenyl)propanoic acid", "1-Methyluric acid", "Dehydroisoandrosterone 3-glucuronide", "Ascorbic acid",
        "D-Tartaric acid", "Kynurenic acid", "Xanthine", "Vanillic acid", "Glyceraldehyde", "D-Lactic acid", "Pregnanediol",
        "7-Methylguanine", "Gluconic acid", "4-Aminophenol", "Caffeic acid", "Enterolactone", "Adipic acid",
        "1H-Indole-3-carboxaldehyde", "4-Hydroxybenzoic acid", "Creatinine", "2-Aminobenzoic acid", "Uric acid")

 mSet<-InitDataObjects("conc", "pathora", FALSE)
 mSet<-Setup.MapData(mSet, tmp.vec);
 mSet<-CrossReferencing(mSet, "name");
 mSet<-CreateMappingResultTable(mSet);

 ##4-O-Methylgallic acid and 2-Methylhippuric acid need correct kegg ID format

 mSet$dataSet$map.table[2,5] <- "C05616"
 mSet$dataSet$map.table[9,5] <- "C01586"

 mSet<-SetKEGG.PathLib(mSet, "hsa", "current")
 mSet<-SetMetabolomeFilter(mSet, F)
 mSet<-CalculateOraScore(mSet, "rbc", "hyperg")
 mSet<-PlotPathSummary(mSet, "path_view_0_", "png", 72, width=NA)

Body:
After spending at least 30 minutes installing dependencies from CRAN and Bioconductor, I was able to get the code to work.

If I had to guess your issue, you probably haven't installed all the dependency packages.

Follow the instructions here:

#install.packages("pacman")
library(pacman)
pacman::p_load(Rserve, ellipse, scatterplot3d, Cairo, randomForest,
               caTools, e1071, som, impute, pcaMethods, RJSONIO, ROCR,
               globaltest, GlobalAncova, Rgraphviz, preprocessCore, genefilter,
               pheatmap, SSPA, sva, Rcpp, pROC, data.table, limma, car, fitdistrplus,
               lars, Hmisc, magrittr, methods, xtable, pls, caret, lattice, igraph,
               gplots, KEGGgraph, reshape, RColorBrewer, tibble, siggenes, plotly,
               xcms, CAMERA, fgsea, MSnbase)

For whatever reason, I had to install the following packages manually as well:

BiocManager::install("edgeR")
install.packages("crmn")
devtools::install_github("xia-lab/MetaboAnalystR")

I ran the analysis on your data. See the output below.

library(MetaboAnalystR)
tmp.vec <- c("Indole-3-carboxylic acid", "4-O-Methylgallic acid", "Hippuric acid", "Pyrocatechol", "Hydroquinone",
        "Aspartame", "trans-Ferulic acid", "2,6-Dimethoxyphenol", "2-Methylhippuric acid", "2-(Hydroxymethyl)benzoic acid",
        "3-(2-Hydroxyphenyl)propanoic acid", "1-Methyluric acid", "Dehydroisoandrosterone 3-glucuronide", "Ascorbic acid",
        "D-Tartaric acid", "Kynurenic acid", "Xanthine", "Vanillic acid", "Glyceraldehyde", "D-Lactic acid", "Pregnanediol",
        "7-Methylguanine", "Gluconic acid", "4-Aminophenol", "Caffeic acid", "Enterolactone", "Adipic acid",
        "1H-Indole-3-carboxaldehyde", "4-Hydroxybenzoic acid", "Creatinine", "2-Aminobenzoic acid", "Uric acid")
mSet<-InitDataObjects("conc", "pathora", FALSE)
mSet<-Setup.MapData(mSet, tmp.vec)
mSet$dataSet$map.table
      Query                                  Match                                  HMDB          PubChem    KEGG        SMILES                                                                             Comment
 [1,] "Indole-3-carboxylic acid"             "Indole-3-carboxylic acid"             "HMDB0003320" "69867"    "C19837"    "C1=CC=C2C(=C1)C(=CN2)C(=O)O"                                                      "1"
 [2,] "4-O-Methylgallic acid"                "4-O-Methylgallic acid"                "HMDB0013198" "78016"    NA          "COC1=C(C=C(C=C1O)C(=O)O)O"                                                        "1"
 [3,] "Hippuric acid"                        "Hippuric acid"                        "HMDB0000714" "464"      "C01586"    "C1=CC=C(C=C1)C(=O)NCC(=O)O"                                                       "1"
 [4,] "Pyrocatechol"                         "Pyrocatechol"                         "HMDB0000957" "3390"     "C15571"    "C1=CC=C(C(=C1)O)O"                                                                "1"
 [5,] "Hydroquinone"                         "Hydroquinone"                         "HMDB0002434" "785"      "C00530"    "C1=CC(=CC=C1O)O"                                                                  "1"
 [6,] "Aspartame"                            "Aspartame"                            "HMDB0001894" "134601"   "C11045"    "COC(=O)[C@H](CC1=CC=CC=C1)NC(=O)[C@H](CC(=O)O)N"                                  "1"
 [7,] "trans-Ferulic acid"                   "trans-Ferulic acid"                   "HMDB0000954" "445858"   "C01494"    "COC1=C(C=CC(=C1)/C=C/C(=O)O)O"                                                    "1"
 [8,] "2,6-Dimethoxyphenol"                  "2,6-Dimethoxyphenol"                  "HMDB0034158" "7041"     "C10787"    "COC1=C(C(=CC=C1)OC)O"                                                             "1"
 [9,] "2-Methylhippuric acid"                "2-Methylhippuric acid"                "HMDB0011723" "91637"    "\t C01586" "CC1=CC=CC=C1C(=O)NCC(=O)O"                                                        "1"
[10,] "2-(Hydroxymethyl)benzoic acid"        "2-(Hydroxymethyl)benzoic acid"        "HMDB0032594" "11920"    "C10804"    "C1=CC=C(C(=C1)CO)C(=O)O"                                                          "1"
[11,] "3-(2-Hydroxyphenyl)propanoic acid"    "3-(2-Hydroxyphenyl)propanoic acid"    "HMDB0033752" "873"      "C01198"    "C1=CC=C(C(=C1)CCC(=O)O)O"                                                         "1"
[12,] "1-Methyluric acid"                    "1-Methyluric acid"                    "HMDB0003099" "69726"    "C16359"    "CN1C(=O)C2=C(NC(=O)N2)NC1=O"                                                      "1"
[13,] "Dehydroisoandrosterone 3-glucuronide" "Dehydroisoandrosterone 3-glucuronide" "HMDB0010327" "53480448" "C03033"    "CC12CCC3C(C1CCC2=O)CC=C4C3(CCC(C4)O[C@H]5[C@@H]([C@H]([C@@H](C(O5)C(=O)O)O)O)O)C" "1"
[14,] "Ascorbic acid"                        "Ascorbic acid"                        "HMDB0000044" "54670067" "C01041"    "C([C@@H]([C@@H]1C(=C(C(=O)O1)O)O)O)O"                                             "1"
[15,] "D-Tartaric acid"                      "D-Tartaric acid"                      "HMDB0029878" "439655"   "C02107"    "[C@H]([C@@H](C(=O)O)O)(C(=O)O)O"                                                  "1"
[16,] "Kynurenic acid"                       "Kynurenic acid"                       "HMDB0000715" "3845"     "C01717"    "C1=CC=C2C(=C1)C(=O)C=C(N2)C(=O)O"                                                 "1"
[17,] "Xanthine"                             "Xanthine"                             "HMDB0000292" "1188"     "C00385"    "C1=NC2=C(N1)C(=O)NC(=O)N2"                                                        "1"
[18,] "Vanillic acid"                        "Vanillic acid"                        "HMDB0000484" "8468"     "C06672"    "COC1=C(C=CC(=C1)C(=O)O)O"                                                         "1"
[19,] "Glyceraldehyde"                       "Glyceraldehyde"                       "HMDB0001051" "751"      "C02154"    "C(C(C=O)O)O"                                                                      "1"
[20,] "D-Lactic acid"                        "D-Lactic acid"                        "HMDB0001311" "61503"    "C00256"    "C[C@H](C(=O)O)O"                                                                  "1"
[21,] "Pregnanediol"                         "Pregnanediol"                         "HMDB0004025" "3032822"  "C05484"    "CC[C@H]1CC[C@@H]2[C@@]1(CC[C@H]3[C@H]2CCC4[C@@]3(CCC(C4)(O)O)C)C"                 "1"
[22,] "7-Methylguanine"                      "7-Methylguanine"                      "HMDB0000897" "11361"    "C02242"    "CN1C=NC2=C1C(=O)N=C(N2)N"                                                         "1"
[23,] "Gluconic acid"                        "Gluconic acid"                        "HMDB0000625" "10690"    "C00257"    "C([C@H]([C@H]([C@@H]([C@H](C(=O)O)O)O)O)O)O"                                      "1"
[24,] "4-Aminophenol"                        "4-Aminophenol"                        "HMDB0001169" "403"      "C02372"    "C1=CC(=CC=C1N)O"                                                                  "1"
[25,] "Caffeic acid"                         "Caffeic acid"                         "HMDB0001964" "1549111"  "C01481"    "C1=CC(=C(C=C1/C=C\\C(=O)O)O)O"                                                    "1"
[26,] "Enterolactone"                        "Enterolactone"                        "HMDB0006101" "123917"   "C18165"    "C1C(C(C(=O)O1)CC2=CC(=CC=C2)O)CC3=CC(=CC=C3)O"                                    "1"
[27,] "Adipic acid"                          "Adipic acid"                          "HMDB0000448" "196"      "C06104"    "C(CCC(=O)O)CC(=O)O"                                                               "1"
[28,] "1H-Indole-3-carboxaldehyde"           "1H-Indole-3-carboxaldehyde"           "HMDB0029737" "10256"    "C08493"    "C1=CC=C2C(=C1)C(=CN2)C=O"                                                         "1"
[29,] "4-Hydroxybenzoic acid"                "4-Hydroxybenzoic acid"                "HMDB0000500" "135"      "C00156"    "C1=CC(=CC=C1C(=O)O)O"                                                             "1"
[30,] "Creatinine"                           "Creatinine"                           "HMDB0000562" "588"      "C00791"    "CN1CC(=O)N=C1N"                                                                   "1"
[31,] "2-Aminobenzoic acid"                  "2-Aminobenzoic acid"                  "HMDB0001123" "227"      "C00108"    "C1=CC=C(C(=C1)C(=O)O)N"                                                           "1"
[32,] "Uric acid"                            "Uric acid"                            "HMDB0000289" "1175"     "C00366"    "C12=C(NC(=O)N1)NC(=O)NC2=O"                                                       "1"

mSet$dataSet$map.table[2,5] <- "C05616"
mSet$dataSet$map.table[9,5] <- "C01586"
mSet<-SetKEGG.PathLib(mSet, "hsa", "current")
mSet<-SetMetabolomeFilter(mSet, F)
mSet<-CalculateOraScore(mSet, "rbc", "hyperg")
mSet$analSet$ora.mat
                                         Total Expected Hits   Raw p -log(p) Holm adjust FDR  Impact
Caffeine metabolism                         10     0.20    1 0.18341 1.69600           1   1 0.00000
Phenylalanine metabolism                    10     0.20    1 0.18341 1.69600           1   1 0.00000
Pentose and glucuronate interconversions    18     0.36    1 0.30627 1.18330           1   1 0.14062
Pentose phosphate pathway                   22     0.44    1 0.36079 1.01940           1   1 0.04712
Pyruvate metabolism                         22     0.44    1 0.36079 1.01940           1   1 0.08398
Purine metabolism                           65     1.30    2 0.37638 0.97717           1   1 0.01217
Tryptophan metabolism                       41     0.82    1 0.56799 0.56566           1   1 0.00202

PlotPathSummary(mSet, "path_view_0_", "png", 300, width=NA)


问:
How to use flex parameter in Flexible widget in Flutter?
When there is excess space between widgets, the flex property works as expected.
As mentioned in the documentation, the formula to use is as follows

```<code>remainingSpace * (flex / totalOfAllFlexValues)
</code>```

But when you have to shrink the widgets, the flex property stops making sense.
Giving results like this.

Building on this, here the widgets overflow, so I use flex to shrink box 1 and 2

and while playing with the flex values, the following happens

```<code>class Caja extends StatelessWidget {

  Color color;
  int numero;
  double ancho;

  Caja(this.color, this.numero, this.ancho);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: this.ancho,
      height: this.ancho,
      color: this.color,
      child: Center(
        child: Text(
          this.numero.toString(),
          style: TextStyle(
            fontSize: 30.0
          ),
        ),
      ),
    );
  }
}
</code>```

I user Flexible widget below

```<code> Column(
      crossAxisAlignment: CrossAxisAlignment.start,

      children: <Widget>[
          Flexible(flex: 1, child: Caja(Colors.blue, 1, 200.0)),

          Flexible(flex: 6, child: Caja(Colors.red, 2, 200.0)),

          Caja(Colors.green, 4, 400.0),
      ],
 )
</code>```

Where does this new leftover space come from?
Can someone explain to me?

答:
I changed the flex value of the second box to 1 - there was no white space. Then to 2 - there was no white space either. From a flex value of 3 upwards, there appears a white space and it gets bigger and bigger.
The documentation states, that a

"..., Flexible does not require the child to fill the available space."

If you examine the source code of the Flexible, the comments say:

"If non-zero, the amount of space the child's can occupy in the main
  axis is determined by dividing the free space (after placing the
  inflexible children) according to the flex factors of the flexible
  children."

I think there might be a problem with the inflexible child - your green box. If you set the flex of your second box so high, you want your first box to be really small.  But the flexible children just take the free space up to the inflexible child into consideration and not the free space after it.

Body:
When there is excess space between widgets, the flex property works as expected.
As mentioned in the documentation, the formula to use is as follows

remainingSpace * (flex / totalOfAllFlexValues)

But when you have to shrink the widgets, the flex property stops making sense.
Giving results like this.

Building on this, here the widgets overflow, so I use flex to shrink box 1 and 2

and while playing with the flex values, the following happens

class Caja extends StatelessWidget {

  Color color;
  int numero;
  double ancho;

  Caja(this.color, this.numero, this.ancho);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: this.ancho,
      height: this.ancho,
      color: this.color,
      child: Center(
        child: Text(
          this.numero.toString(),
          style: TextStyle(
            fontSize: 30.0
          ),
        ),
      ),
    );
  }
}

I user Flexible widget below

 Column(
      crossAxisAlignment: CrossAxisAlignment.start,

      children: <Widget>[
          Flexible(flex: 1, child: Caja(Colors.blue, 1, 200.0)),

          Flexible(flex: 6, child: Caja(Colors.red, 2, 200.0)),

          Caja(Colors.green, 4, 400.0),
      ],
 )

Where does this new leftover space come from?
Can someone explain to me?


问:
Problem with list-style-type: none; in FireFox
For example, in that html code I add list-style-type: none; in external test.css. When FireFox loads that page, the dots (list-style-type without none) could be seen for about a second. Only inline css works

```<code><!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link href="test.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
        <div>TODO write content</div>
        <ul id="categories">
            <li><a>Test1</a></li>
            <li><a>Test2</a></li>
            <li><a>Test3</a></li>
        </ul>
    </body>
</html>
</code>```

ScreenShot

答:
I have just tried it on both Windows and Mac in Firefox, and both worked fine for me. Apparently, this Flash Of Unstyled Content (FOUC) doesn't happen on everyone's browser.

If you insist fixing this, you might think about using some workarounds, such as placing the <link> in body, using @import to import your css, or google it...

Body:
For example, in that html code I add list-style-type: none; in external test.css. When FireFox loads that page, the dots (list-style-type without none) could be seen for about a second. Only inline css works

<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link href="test.css" rel="stylesheet" type="text/css" />

TODO write content

Test1

Test2

Test3

ScreenShot


问:
Javascript empty validation not working before sending to database
For some reason my JavaScript validation function is not working before sending the info to the database, I tried my best to fix it but it just wont work here is my code:

<form name="myForm" action="connectform.php" onsubmit="return validateForm()" method="POST" required>

Contact Me

      First Name :
      <input type="text" name="firstName" id="firstName" placeholder="Enter Your First Name">

      Last Name :
      <input type="text" name="lastName"  placeholder="Enter Your Last Name">

      Email
      <input type="email" name="email" id="email" placeholder="Enter Your Email">

      Message :
      <input type="text" name="info" id="info">

    <input type="submit" id='validate' class="btn" />

</form>
```

<p>and here is my javascript code (i only did it once for testing it for the first name):</p>

<pre class="lang-js prettyprint-override"><code><script>
  function validateForm() {
    var x = document.forms["myForm"]["firstName"].value;
    if (x==null || x=="") {
      alert("First name must be filled out");
      return false;
    }
</script>
</code>```

Here is my PHP code:

<?php
  $firstName = $_POST['firstName'];
  $lastName = $_POST['lastName'];
  $email = $_POST['email'];
  $info = $_POST['info'];

  //Database Connection
  $conn = new mysqli('localhost', 'root', '', 'webpage_project');

  if ($conn->connect_error) {
      echo "$conn->connect_error";
  die("Connection Failed : ". $conn->connect_error);
  }
  else{
      $stmt = $conn->prepare("insert into contactme(firstName, lastName, email, info) values (?, ?, ?, ?)");
      $stmt->bind_param("ssss", $firstName, $lastName, $email, $info);
  $execval = $stmt->execute();
      $echo'Sent Sucessfully';
  $stmt->close();
  $conn->close();
  }
?>
```

答:
Use this code instead of your's one,

```<code><form
  name="myForm"
  action="connectform.php"
  onsubmit="validateForm()"
  method="POST"
  required
>
  <div class="contact-form">
    <h1>Contact Me</h1>
    <div class="txtb">
      <label for="firstName">First Name :</label>
      <input
        type="text"
        name="firstName"
        id="firstName"
        placeholder="Enter Your First Name"
      />
    </div>
    <input type="submit" id="validate" class="btn" />
  </div>
</form>
</code>```

and change your validateForm() function as,

```<code>validateForm() {
  const fname = document.forms["myForm"]["firstName"].value;
  if (fname) { /* this will cheak both conditions */
    alert("First name must be filled out");
    return false;
  }
},
</code>```

Body:
For some reason my JavaScript validation function is not working before sending the info to the database, I tried my best to fix it but it just wont work here is my code:

<form name="myForm" action="connectform.php" onsubmit="return validateForm()" method="POST" required>

Contact Me

      First Name :
      <input type="text" name="firstName" id="firstName" placeholder="Enter Your First Name">

      Last Name :
      <input type="text" name="lastName"  placeholder="Enter Your Last Name">

      Email
      <input type="email" name="email" id="email" placeholder="Enter Your Email">

      Message :
      <input type="text" name="info" id="info">

    <input type="submit" id='validate' class="btn" />

</form>

and here is my javascript code (i only did it once for testing it for the first name):

Here is my PHP code:

<?php
  $firstName = $_POST['firstName'];
  $lastName = $_POST['lastName'];
  $email = $_POST['email'];
  $info = $_POST['info'];

  //Database Connection
  $conn = new mysqli('localhost', 'root', '', 'webpage_project');

  if ($conn->connect_error) {
      echo "$conn->connect_error";
  die("Connection Failed : ". $conn->connect_error);
  }
  else{
      $stmt = $conn->prepare("insert into contactme(firstName, lastName, email, info) values (?, ?, ?, ?)");
      $stmt->bind_param("ssss", $firstName, $lastName, $email, $info);
  $execval = $stmt->execute();
      $echo'Sent Sucessfully';
  $stmt->close();
  $conn->close();
  }
?>

Body:
Use this code instead of your's one,

<form
  name="myForm"
  action="connectform.php"
  onsubmit="validateForm()"
  method="POST"
  required
>
  <div class="contact-form">
    <h1>Contact Me</h1>
    <div class="txtb">
      <label for="firstName">First Name :</label>
      <input
        type="text"
        name="firstName"
        id="firstName"
        placeholder="Enter Your First Name"
      />
    </div>
    <input type="submit" id="validate" class="btn" />
  </div>
</form>

and change your validateForm() function as,

validateForm() {
  const fname = document.forms["myForm"]["firstName"].value;
  if (fname) { /* this will cheak both conditions */
    alert("First name must be filled out");
    return false;
  }
},


问:
EXTRN function call issue is there a way to know what is causing it?

/* function supposed to allocate memory for in array and fill it (half with help of the function ;received in call and the other half with the help of external function rand*?

defining variables

```<code>.MODEL LARGE
.DATA
Parr DW ?
ParrS DW ?
len DW ?
getnum DW ?
getnumS DW ?
two DW 2
</code>```

declaring functions

```<code>.code
.386
PUBLIC _initarr
EXTRN _rand:NEAR
EXTRN _malloc:NEAR
_initarr PROC FAR
</code>```

saving non general registers in stack & extracting received values and addresses sent by c call int  >initarr(int**arr, int n, int (*initfunc)(int));

```<code>PUSH BP
MOV BP,SP
PUSH SI
PUSH DI
PUSH ES
MOV AX,[BP+6]

MOV Parr,AX
MOV AX,[BP+8]
MOV ParrS,AX
MOV AX,[BP+10]
MOV len,AX
MOV AX,[BP+12]
MOV getnum,AX
MOV AX,[BP+14]
MOV getnumS,AX
</code>```

getting parameter ready to send to malloc, calling malloc & checking allocation success

```<code>MOV AX,len
MUL two
PUSH AX ;sending parameter to malloc
CALL _malloc
ADD SP,2
CMP AX,0
JZ cont
MOV ES,ParrS
MOV SI,Parr
MOV [ES:SI],AX ;setting address returned by malloc in address sent by function call

cont:
POP ES ;retrieving old registers from stack
POP DI
POP SI
POP BP
RET ;return
_initarr ENDP
END
</code>```

getting a "fixup overlow" error , checked the syntax a couple times it's probably not that, tried searching it online but it can be caused by many different reasons, any help?

Error message: "Fixup overflow at init_TEXT:002D, target = _malloc in module init.ASM

Fixup overflow at init_TEXT:007B, target = _rand in module init.ASM

答: i had to change my memory model from large to small in order to fix the issue, i believe it's possible to define the external functions as  far instead, i tried it yet didn't work for some reason.</p>

Body:
/* function supposed to allocate memory for in array and fill it (half with help of the function ;received in call and the other half with the help of external function rand*?

defining variables

.MODEL LARGE
.DATA
Parr DW ?
ParrS DW ?
len DW ?
getnum DW ?
getnumS DW ?
two DW 2

declaring functions

.code
.386
PUBLIC _initarr
EXTRN _rand:NEAR
EXTRN _malloc:NEAR
_initarr PROC FAR

saving non general registers in stack & extracting received values and addresses sent by c call int  >initarr(int**arr, int n, int (*initfunc)(int));

PUSH BP
MOV BP,SP
PUSH SI
PUSH DI
PUSH ES
MOV AX,[BP+6]

MOV Parr,AX
MOV AX,[BP+8]
MOV ParrS,AX
MOV AX,[BP+10]
MOV len,AX
MOV AX,[BP+12]
MOV getnum,AX
MOV AX,[BP+14]
MOV getnumS,AX

getting parameter ready to send to malloc, calling malloc & checking allocation success

MOV AX,len
MUL two
PUSH AX ;sending parameter to malloc
CALL _malloc
ADD SP,2
CMP AX,0
JZ cont
MOV ES,ParrS
MOV SI,Parr
MOV [ES:SI],AX ;setting address returned by malloc in address sent by function call

cont:
POP ES ;retrieving old registers from stack
POP DI
POP SI
POP BP
RET ;return
_initarr ENDP
END

getting a "fixup overlow" error , checked the syntax a couple times it's probably not that, tried searching it online but it can be caused by many different reasons, any help?

Error message: "Fixup overflow at init_TEXT:002D, target = _malloc in module init.ASM

Fixup overflow at init_TEXT:007B, target = _rand in module init.ASM


问:
Turkish Vowel Letter Recognition
I would like to generate code;
When you enter sentence, the system will display only consonant letters for these sentence.

I generated code but the code does not recognize Special Turkish Vowel Letter
 like  İ,Ü,Ö as a Constant letter. Only recognize English Latin vowel letter.

How can I fix that?

```<code>#include <stdio.h>
#include <string.h>
#include <time.h>
#include <wchar.h>

int vowel (char);

int main ()
{
    setlocale(LC_ALL, "Turkish");
    char s[100], t[100];
    int c, d = 0;
    printf ("Enter sentence vowels will ve removed:\n");
    gets (s);
    for (c = 0; s[c] != '\0'; c++)
    {
        if (vowel (s[c]) == 0)
        {
            t[d] = s[c];
            d++;
        }
    }
    t[d] = '\0';
    strcpy (s, t);
    printf ("Letters without vowels: %s\n", s);
    return 0;
}

int vowel (char ch)
{
    if (ch == 'a' || ch == 'A'
     || ch == 'e' || ch == 'E'
     || ch == 'ı' || ch == 'I'
     || ch == 'i' || ch == 'İ'
     || ch == 'o' || ch == 'O'
     || ch == 'ö;' || ch == 'Ö'
     || ch == 'u' || ch == 'U'
     || ch == 'ü' || ch == 'Ü')
      return 1;
    else
      return 0;
}
</code>```

答:
I've rewritten it to use wchar_t instead of char.

Ascii characters are represented in a single byte (char). You may need to convert your code to use wchar_t.

```<code>#include <locale.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <wchar.h>

int vowel (wchar_t); // <---- accepts wchar_t instead of char

int main ()
{
    setlocale(LC_ALL, "Turkish");
    /* To get it to work on https://www.onlinegdb.com/
     * use setlocale(LC_ALL,"en_US.UTF-8");
     *
     */
    wchar_t s[100], t[100]; // <---- wchar_t instead of char
    int c, d = 0;
    printf ("Enter sentence vowels will ve removed:\n");

    // TODO : also check the return code. On error, it returns NULL.
    fgetws (s, 100, stdin); // <----- accepting wchar_t string

    for (c = 0; s[c] != '\0'; c++)
    {
        if (vowel (s[c]) == 0)
        {
            t[d] = s[c];
            d++;
        }
    }
    t[d] = '\0';
    // using memcpy instead of strcpy.
    // also see - http://www.cplusplus.com/reference/cwchar/wcscpy/
    memcpy (s, t, sizeof(t));
    printf ("Letters without vowels: ");
    for (c = 0; c < d; c++)
        putwchar(s[c]); // <---- print wchar_t character on terminal
    putwchar('\n');
    return 0;
}

int vowel (wchar_t ch)
{
    // I've prefixed an L - more than one byte.
    if (ch == L'a' || ch == L'A'
     || ch == L'e' || ch == L'E'
     || ch == L'ı' || ch == L'I'
     || ch == L'i' || ch == L'İ'
     || ch == L'o' || ch == L'O'
     || ch == L'ö' || ch == L'Ö'
     || ch == L'u' || ch == L'U'
     || ch == L'ü' || ch == L'Ü')
      return 1;
    else
      return 0;
}
</code>```

Sample output

```<code>$ gcc test.c
$ ./a.out
Enter sentence vowels will ve removed:
abcdxyÖÜ
Letters without vowels: bcdxy
</code>```

Title: Turkish Vowel Letter Recognition

Body:
I would like to generate code;
When you enter sentence, the system will display only consonant letters for these sentence.

I generated code but the code does not recognize Special Turkish Vowel Letter
 like  İ,Ü,Ö as a Constant letter. Only recognize English Latin vowel letter.

How can I fix that?

#include <stdio.h>
#include <string.h>
#include <time.h>
#include <wchar.h>

int vowel (char);

int main ()
{
    setlocale(LC_ALL, "Turkish");
    char s[100], t[100];
    int c, d = 0;
    printf ("Enter sentence vowels will ve removed:\n");
    gets (s);
    for (c = 0; s[c] != '\0'; c++)
    {
        if (vowel (s[c]) == 0)
        {
            t[d] = s[c];
            d++;
        }
    }
    t[d] = '\0';
    strcpy (s, t);
    printf ("Letters without vowels: %s\n", s);
    return 0;
}

int vowel (char ch)
{
    if (ch == 'a' || ch == 'A'
     || ch == 'e' || ch == 'E'
     || ch == 'ı' || ch == 'I'
     || ch == 'i' || ch == 'İ'
     || ch == 'o' || ch == 'O'
     || ch == 'ö;' || ch == 'Ö'
     || ch == 'u' || ch == 'U'
     || ch == 'ü' || ch == 'Ü')
      return 1;
    else
      return 0;
}

Body:
I've rewritten it to use wchar_t instead of char.

Ascii characters are represented in a single byte (char). You may need to convert your code to use wchar_t.

#include <locale.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <wchar.h>

int vowel (wchar_t); // <---- accepts wchar_t instead of char

int main ()
{
    setlocale(LC_ALL, "Turkish");
    /* To get it to work on https://www.onlinegdb.com/
     * use setlocale(LC_ALL,"en_US.UTF-8");
     *
     */
    wchar_t s[100], t[100]; // <---- wchar_t instead of char
    int c, d = 0;
    printf ("Enter sentence vowels will ve removed:\n");

    // TODO : also check the return code. On error, it returns NULL.
    fgetws (s, 100, stdin); // <----- accepting wchar_t string

    for (c = 0; s[c] != '\0'; c++)
    {
        if (vowel (s[c]) == 0)
        {
            t[d] = s[c];
            d++;
        }
    }
    t[d] = '\0';
    // using memcpy instead of strcpy.
    // also see - http://www.cplusplus.com/reference/cwchar/wcscpy/
    memcpy (s, t, sizeof(t));
    printf ("Letters without vowels: ");
    for (c = 0; c < d; c++)
        putwchar(s[c]); // <---- print wchar_t character on terminal
    putwchar('\n');
    return 0;
}

int vowel (wchar_t ch)
{
    // I've prefixed an L - more than one byte.
    if (ch == L'a' || ch == L'A'
     || ch == L'e' || ch == L'E'
     || ch == L'ı' || ch == L'I'
     || ch == L'i' || ch == L'İ'
     || ch == L'o' || ch == L'O'
     || ch == L'ö' || ch == L'Ö'
     || ch == L'u' || ch == L'U'
     || ch == L'ü' || ch == L'Ü')
      return 1;
    else
      return 0;
}

Sample output

$ gcc test.c
$ ./a.out
Enter sentence vowels will ve removed:
abcdxyÖÜ
Letters without vowels: bcdxy


问:
Performance for Mysql JOINs on VARCHAR columns with different collation
I could not easily find that information in the docs:

I started all my tables with utf8_bin, now I have one table with a column I would prefer to change to utf8_mb4_900_as_ci and consider utf8_mb4_900_ai_ci.

My question: Would this negatively affect JOINs with utf8_bin fields in terms of index use and performance ?

答:
If your change leads to a JOIN between two columns with different COLLATIONs, performance may suffer hugely.

If both columns are exactly the same character set and collation, the JOIN can use an INDEX on one or the other column.

If the columns differ in CHARACTER SET (and hence COLLATION), then one column may be convertible to the other.

(Please provide a specific example.)


问:
react native edit file after build
Is there any way to edit a json file after the app was build? I heard that an apk file can be unzipped, but how about IOS? My goal is to make an app that can be changed by a non-programmer, after it was finished. Adding assets would be also good, but I don't think I would be possible.</p>

答: I do not think this is possible as one would have to repackage it and sign it using the production certificate/keystore to be accepted by either Apple or Google. What you could do is include the Firebase Remote Config module which lets you define variables and their values on the Firebase console and retrieve them dynamically inside your app. This would allow the "non-programmers" to edit image URLs and other content you decide to make available. </p>

Title: react native edit file after build


问:
How to show the row or line number in powershell format-table
I'd like the data presented by format-table to include the line or row number of the items.
How can I achieve this?

some-command | ft

```<code>Line    Something       Else
----    ---------       ----
0       Item1           Property1
1       Item2           Property2
</code>```

答:
Here's my take.  Some of my osx processes have no name as a regular user.

```<code>get-process | where name |
  foreach { $line = 0 } { $line++; $_ } |
  ft @{n='line';e={$line}}, name, id

line Name              Id
---- ----              --
   1 accountsd        368
   2 AirPlayUIAgent   508
   3 akd             2415
   4 AMPDeviceDiscov  412
   5 AppleSpell      1937
</code>```

Take two:

```<code>ps | where name | select -first 5 |
  foreach { $line = 0 } { $_ | add-member -passthru line (++$line) } |
  select line,name,id

line Name              Id
---- ----              --
   1 accountsd        368
   2 AirPlayUIAgent   508
   3 akd             2415
   4 AMPDeviceDiscov  412
   5 AppleSpell      1937
</code>```

Body:
I'd like the data presented by format-table to include the line or row number of the items.
How can I achieve this?

some-command | ft

Line    Something       Else
----    ---------       ----
0       Item1           Property1
1       Item2           Property2

Body:
Here's my take.  Some of my osx processes have no name as a regular user.

get-process | where name |
  foreach { $line = 0 } { $line++; $_ } |
  ft @{n='line';e={$line}}, name, id

line Name              Id
---- ----              --
   1 accountsd        368
   2 AirPlayUIAgent   508
   3 akd             2415
   4 AMPDeviceDiscov  412
   5 AppleSpell      1937

Take two:

ps | where name | select -first 5 |
  foreach { $line = 0 } { $_ | add-member -passthru line (++$line) } |
  select line,name,id

line Name              Id
---- ----              --
   1 accountsd        368
   2 AirPlayUIAgent   508
   3 akd             2415
   4 AMPDeviceDiscov  412
   5 AppleSpell      1937


问:
db2 access on different systems
Hi
I am currently using db2 for some project work.The issue seems to be that we are a team of 4 and all of are working on the same database(not concurrently though).So ideally one of us create a backup of the database on one system and pass it others. We are able to connect to the database on other system,but not query it.I guess it is a issue with granting access. How do i solve this issue?</p>

答:
I am not sure what you mean by backing up the database and pass the backup to others. If you want the same database to be restored on other systems you can use redirected restore.
You can do this very easily on the current db with the command:
db2 restore database  taken at  redirect generate script

If you have problems with access it could be you are restoring the database on different systems with different users. Db2 primarily uses local (system) users for db access - apart from the instance owner/admin sysadmin users.

ContentLicense: CC BY-SA 2.5

Title: db2 access on different systems


问:
gnuplot not responsive when called from script file
I have a datafile "data.dat", say.

When I enter the gnuplot shell by typing 'gnuplot', and then run the command

```<code>plot 'data.dat' u 1:2 w l
</code>```

the plot appearing remains responsive, i.e, by right click of mouse I can zoom it or by arrow keys, I can move the plot up/down/side.

But when I try to do the same thing using a script file, I can no more use those right click zooming and all. My script file is named as p.plt, say and contains the following line -

```<code>plot 'data.dat' u 1:2 w l
</code>```

Now, when I execute it with the command gnuplot -p p.plt, it no longer responds to those right clicks or arrow keys. What should I do to make it work with script files?

I am using linux mint 19.3 cinnamon and gnuplot version gnuplot 5.2 patchlevel 2.

答:
The -p option ("persist") tells gnuplot to leave the plot showing on the screen when the program exits.  In this state, as you found, most mousing operations no longer work because the program is no longer there to respond to them.  So "persist" is not what you want.  Instead add a command to your script that tells the program to remain active until the plot window is closed:

```<code>  plot 'data.dat' u 1:2 w l
  pause mouse close
</code>```

Exactly what operation or signal is interpreted as "close" depends on your window manager, desktop setup, and operating system. Usually there is widget somewhere on the window border (maybe a little "x" in the top corner?) and probably a hot-key ("alt-F4" on my desktop) also.  You can supplement this by defining your own hotkey inside gnuplot:

```<code>  plot 'data.dat' u 1:2 w l
  bind all "alt-End" "exit gnuplot"
  pause mouse close
</code>```

Now typing <alt>+<End> while the mouse is over any gnuplot window should cause the program to exit.

Body:
I have a datafile "data.dat", say.

When I enter the gnuplot shell by typing 'gnuplot', and then run the command

plot 'data.dat' u 1:2 w l

the plot appearing remains responsive, i.e, by right click of mouse I can zoom it or by arrow keys, I can move the plot up/down/side.

But when I try to do the same thing using a script file, I can no more use those right click zooming and all. My script file is named as p.plt, say and contains the following line -

plot 'data.dat' u 1:2 w l

Now, when I execute it with the command gnuplot -p p.plt, it no longer responds to those right clicks or arrow keys. What should I do to make it work with script files?

I am using linux mint 19.3 cinnamon and gnuplot version gnuplot 5.2 patchlevel 2.

Body:
The -p option ("persist") tells gnuplot to leave the plot showing on the screen when the program exits.  In this state, as you found, most mousing operations no longer work because the program is no longer there to respond to them.  So "persist" is not what you want.  Instead add a command to your script that tells the program to remain active until the plot window is closed:

  plot 'data.dat' u 1:2 w l
  pause mouse close

Exactly what operation or signal is interpreted as "close" depends on your window manager, desktop setup, and operating system. Usually there is widget somewhere on the window border (maybe a little "x" in the top corner?) and probably a hot-key ("alt-F4" on my desktop) also.  You can supplement this by defining your own hotkey inside gnuplot:

  plot 'data.dat' u 1:2 w l
  bind all "alt-End" "exit gnuplot"
  pause mouse close

Now typing <alt>+<End> while the mouse is over any gnuplot window should cause the program to exit.


问:
What is the style of click onclicking?
I'm glad you can help me. I want to use css, html, and javascript to draw the text inside the p tag when the checkbox is checked.</p>

答:
Here is a working example for showing the checked and un-checked status of checkbox:

```<code><!DOCTYPE html>
<html>
    <head>
        <title>Checkbox demo</title>
    </head>
    <body>
        <span>Checkbox:</span>
        <input type="checkbox" id="my-checkbox" onclick="myFunction()">
        <p id="result">Page loaded</p>
        <script>
          function myFunction() {
            var checkBox = document.getElementById("my-checkbox");
            var result = document.getElementById("result");
            if (checkBox.checked == true){
              result.innerHTML = "Checkbox was checked"
            } else {
              result.innerHTML = "Checkbox was un-checked"
            }
          }
        </script>
  </body>
</html>
</code>```

Output:

More information:

https://www.w3schools.com/howto/howto_js_display_checkbox_text.asp

Title: What is the style of click onclicking?

Body:
Here is a working example for showing the checked and un-checked status of checkbox:

<!DOCTYPE html>
<html>
    <head>
        <title>Checkbox demo</title>
    </head>
    <body>
        <span>Checkbox:</span>
        <input type="checkbox" id="my-checkbox" onclick="myFunction()">
        <p id="result">Page loaded</p>
        <script>
          function myFunction() {
            var checkBox = document.getElementById("my-checkbox");
            var result = document.getElementById("result");
            if (checkBox.checked == true){
              result.innerHTML = "Checkbox was checked"
            } else {
              result.innerHTML = "Checkbox was un-checked"
            }
          }
        </script>
  </body>
</html>

Output:

More information:

https://www.w3schools.com/howto/howto_js_display_checkbox_text.asp