问:
Thread starvation on Tomcat java application - all threads in WAITING for c3p0 BasicResourcePool.awaitAvailable
our java web application is currently experiencing random (and never experienced before) block issues caused by a sudden spike in threads created and the subsequent exhaustion of the max number of threads that out Tomcat can create (the default = 200).

The last spike saw the creation of 120 new threads in 10 minutes, taking the count from 80 to 200, and blocking out application. The usual count in threads is 70-80.

Doing a thread dump all those threads are in WAITING state and seems that all are waiting for a new Connection to the DBMS from c3p0.

This is an example stack:

```<code>"http-nio-8443-exec-77  Waiting Thread ID: 10016","1"

"java.lang.Object.wait(long)","2"
"com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(long) BasicResourcePool.java:1414","2"
"com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(long) BasicResourcePool.java:606","2"
"com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(long) BasicResourcePool.java:526","2"
"com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutAndMarkConnectionInUse() C3P0PooledConnectionPool.java:755","2"
"com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection() C3P0PooledConnectionPool.java:682","2"
"com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection() AbstractPoolBackedDataSource.java:140","2"
"org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource.getConnection() AbstractRoutingDataSource.java:164","2"
"org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection() DatasourceConnectionProviderImpl.java:139","2"
"org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection() AbstractSessionImpl.java:380","2"
"org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection() LogicalConnectionImpl.java:228","2"
"org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection() LogicalConnectionImpl.java:171","2"
"org.hibernate.internal.SessionImpl.connection() SessionImpl.java:450","2"
"org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(Object, TransactionDefinition) HibernateTransactionManager.java:450","2"
"org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(TransactionDefinition) AbstractPlatformTransactionManager.java:373","2"
"org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(PlatformTransactionManager, TransactionAttribute, String) TransactionAspectSupport.java:463","2"
"org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(Method, Class, TransactionAspectSupport$InvocationCallback) TransactionAspectSupport.java:276","2"
"org.springframework.transaction.interceptor.TransactionInterceptor.invoke(MethodInvocation) TransactionInterceptor.java:96","2"
"org.springframework.aop.framework.ReflectiveMethodInvocation.proceed() ReflectiveMethodInvocation.java:179","2"
"org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(MethodInvocation) ExposeInvocationInterceptor.java:92","2"
"org.springframework.aop.framework.ReflectiveMethodInvocation.proceed() ReflectiveMethodInvocation.java:179","2"
"org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(Object, Method, Object[], MethodProxy) CglibAopProxy.java:653","2"
</code>```

This is our c3p0 configuration for this DataSource:

```<code><property name="maxIdleTime" value="600" />
<property name="maxPoolSize" value="300" />
<property name="maxStatements" value="200" />
<property name="maxStatementsPerConnection" value="10" />
<property name="minPoolSize" value="15" />
<property name="idleConnectionTestPeriod" value="100" />
<property name="acquireIncrement" value="3" />
<property name="numHelperThreads" value="20" />
</code>```

I'm currently trying to add a timout parameter to help me debug those cases

<property name="checkoutTimeout" value="30" />

I read that I should use debugUnreturnedConnectionStackTraces and unreturnedConnectionTimeout to debug bettere those kind of problems, but I'm currently not understanding them very well and afraid to use them in production.

Is there any other kind of configuration I could try to help me debug the problem? Some other timeout configuration?

Stack:

DBMS: Sql Server 2014

c3p0: 0.9.2.1

Hibernate: 4.3.5

Spring: 4.1.6

EDIT (CHECKOUT TIMEOUT TEST)

I tried to put on the database in question the parameter checkoutTimeout:

<property name="checkoutTimeout" value="30" />

This property should force all the threads that are waiting for the checkout of a Connection from c3p0, to give up after 30 seconds in case the pool is exhausted, with the throw of a SqlException.

Not too after putting this property in production we started logging this kind of errors:

```<code>Caused by: org.hibernate.exception.GenericJDBCException: Could not open connection

    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)

    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)

    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)

    at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:235)

    at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:171)

    at org.hibernate.internal.SessionImpl.connection(SessionImpl.java:450)

    at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:450)

    ... 119 more

Caused by: java.sql.SQLException: An attempt by a client to checkout a Connection has timed out.

    at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:118)

    at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:77)

    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:687)

    at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:140)

    at org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource.getConnection(AbstractRoutingDataSource.java:164)

    at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:139)

    at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:380)

    at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:228)

    ... 122 more

Caused by: com.mchange.v2.resourcepool.TimeoutException: A client timed out while waiting to acquire a resource from com.mchange.v2.resourcepool.BasicResourcePool@14e83e8f -- timeout at awaitAvailable()

    at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1416)

    at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:606)

    at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:526)

    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutAndMarkConnectionInUse(C3P0PooledConnectionPool.java:755)

    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:682)

    ... 127 more
</code>```

So I guess this is a proof that out pool got exhausted (the maxPoolSize is 300). Is that correct?

EDIT 2: QUESTION SOLVED, LOOK AT MY ANSWER

答: You can ask your Sql Server DBA's to provide some statistic regarding the number of seesions bound to your application during a particualr period, the time spent in executing SQL, etc.</p>

Body:
our java web application is currently experiencing random (and never experienced before) block issues caused by a sudden spike in threads created and the subsequent exhaustion of the max number of threads that out Tomcat can create (the default = 200).

The last spike saw the creation of 120 new threads in 10 minutes, taking the count from 80 to 200, and blocking out application. The usual count in threads is 70-80.

Doing a thread dump all those threads are in WAITING state and seems that all are waiting for a new Connection to the DBMS from c3p0.

This is an example stack:

"http-nio-8443-exec-77  Waiting Thread ID: 10016","1"

"java.lang.Object.wait(long)","2"
"com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(long) BasicResourcePool.java:1414","2"
"com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(long) BasicResourcePool.java:606","2"
"com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(long) BasicResourcePool.java:526","2"
"com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutAndMarkConnectionInUse() C3P0PooledConnectionPool.java:755","2"
"com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection() C3P0PooledConnectionPool.java:682","2"
"com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection() AbstractPoolBackedDataSource.java:140","2"
"org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource.getConnection() AbstractRoutingDataSource.java:164","2"
"org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection() DatasourceConnectionProviderImpl.java:139","2"
"org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection() AbstractSessionImpl.java:380","2"
"org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection() LogicalConnectionImpl.java:228","2"
"org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection() LogicalConnectionImpl.java:171","2"
"org.hibernate.internal.SessionImpl.connection() SessionImpl.java:450","2"
"org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(Object, TransactionDefinition) HibernateTransactionManager.java:450","2"
"org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(TransactionDefinition) AbstractPlatformTransactionManager.java:373","2"
"org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(PlatformTransactionManager, TransactionAttribute, String) TransactionAspectSupport.java:463","2"
"org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(Method, Class, TransactionAspectSupport$InvocationCallback) TransactionAspectSupport.java:276","2"
"org.springframework.transaction.interceptor.TransactionInterceptor.invoke(MethodInvocation) TransactionInterceptor.java:96","2"
"org.springframework.aop.framework.ReflectiveMethodInvocation.proceed() ReflectiveMethodInvocation.java:179","2"
"org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(MethodInvocation) ExposeInvocationInterceptor.java:92","2"
"org.springframework.aop.framework.ReflectiveMethodInvocation.proceed() ReflectiveMethodInvocation.java:179","2"
"org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(Object, Method, Object[], MethodProxy) CglibAopProxy.java:653","2"

This is our c3p0 configuration for this DataSource:

<property name="maxIdleTime" value="600" />
<property name="maxPoolSize" value="300" />
<property name="maxStatements" value="200" />
<property name="maxStatementsPerConnection" value="10" />
<property name="minPoolSize" value="15" />
<property name="idleConnectionTestPeriod" value="100" />
<property name="acquireIncrement" value="3" />
<property name="numHelperThreads" value="20" />

I'm currently trying to add a timout parameter to help me debug those cases

<property name="checkoutTimeout" value="30" />

I read that I should use debugUnreturnedConnectionStackTraces and unreturnedConnectionTimeout to debug bettere those kind of problems, but I'm currently not understanding them very well and afraid to use them in production.

Is there any other kind of configuration I could try to help me debug the problem? Some other timeout configuration?

Stack:

DBMS: Sql Server 2014

c3p0: 0.9.2.1

Hibernate: 4.3.5

Spring: 4.1.6

EDIT (CHECKOUT TIMEOUT TEST)

I tried to put on the database in question the parameter checkoutTimeout:

<property name="checkoutTimeout" value="30" />

This property should force all the threads that are waiting for the checkout of a Connection from c3p0, to give up after 30 seconds in case the pool is exhausted, with the throw of a SqlException.

Not too after putting this property in production we started logging this kind of errors:

Caused by: org.hibernate.exception.GenericJDBCException: Could not open connection

    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)

    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)

    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)

    at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:235)

    at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:171)

    at org.hibernate.internal.SessionImpl.connection(SessionImpl.java:450)

    at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:450)

    ... 119 more

Caused by: java.sql.SQLException: An attempt by a client to checkout a Connection has timed out.

    at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:118)

    at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:77)

    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:687)

    at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:140)

    at org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource.getConnection(AbstractRoutingDataSource.java:164)

    at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:139)

    at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:380)

    at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:228)

    ... 122 more

Caused by: com.mchange.v2.resourcepool.TimeoutException: A client timed out while waiting to acquire a resource from com.mchange.v2.resourcepool.BasicResourcePool@14e83e8f -- timeout at awaitAvailable()

    at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1416)

    at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:606)

    at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:526)

    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutAndMarkConnectionInUse(C3P0PooledConnectionPool.java:755)

    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:682)

    ... 127 more

So I guess this is a proof that out pool got exhausted (the maxPoolSize is 300). Is that correct?

EDIT 2: QUESTION SOLVED, LOOK AT MY ANSWER


来源: stackexchange

问:
Restrict user to select business process flow stage manually
I am trying to restrict user from manually selecting the business process stage.

I have already hidden all buttons (Next Stage, Finish, Previous Stage etc), using following,

```<code>document.getElementById("processActionsContainer");
</code>```

Now I also want to restrict manual selection of stages of BPF. How can I achieve that?

答:
This is not how you restrict buttons in Dynamics.
In fact document.getElementById is not allowed in dynamics itself. It is deprecated.

The way you are trying to limit stage change is not possible.

But the alternate way to achieve this is with Workflow.
For a Process to move from A to B will only happen when some fields are fields or some data is entered or some condition is matched.
Have a look at these articles which will give you more idea to perform your task.

Link 1

Link 2

Link 3

ContentLicense: CC BY-SA 4.0

Body:
I am trying to restrict user from manually selecting the business process stage.

I have already hidden all buttons (Next Stage, Finish, Previous Stage etc), using following,

document.getElementById("processActionsContainer");

Now I also want to restrict manual selection of stages of BPF. How can I achieve that?


问:
How to get all the class name of an element in jquery?
I have some li's

```<code> li class="views-row views-row-2 views-row-even"
 li class="views-row views-row-3 views-row-odd"
 li class="views-row views-row-4 views-row-even"
 li class="views-row views-row-5 views-row-odd"
</code>```

Now on hover i am adding a class selected to corresponding li. Suppose i hover on first li element, selected classes get added to this li. So i will have

li class="views-row views-row-2 views-row-even selected". Now how do i get the views-row-2 class of this selected li.Similarly if second li is selected i need views-row-3 class and so on. Please help

答:
You haven't mentioned what's special about the view-rows-2 class:

Do you already know which class you want?

Will it always be this class?

With what information you've given, here are my suggestions:

You might want to check out .hasClass()

If you want all classes for an element, see Get class list for element with jQuery

So if you want to get classes based on a prefix (which in your case seems to be views-row-, you could use what's suggested in the answers to these SO question: jQuery - Get a element class based on a prefix and jQuery selector regular expressions

ContentLicense: CC BY-SA 3.0

Body:
I have some li's

 li class="views-row views-row-2 views-row-even"
 li class="views-row views-row-3 views-row-odd"
 li class="views-row views-row-4 views-row-even"
 li class="views-row views-row-5 views-row-odd"

Now on hover i am adding a class selected to corresponding li. Suppose i hover on first li element, selected classes get added to this li. So i will have

li class="views-row views-row-2 views-row-even selected". Now how do i get the views-row-2 class of this selected li.Similarly if second li is selected i need views-row-3 class and so on. Please help


问:
Is there any C function that can evalute a string expression defined in the standard library?
I am looking for a function that can evaluate a string expression into an integer, like f.e.:

```<code>10/2+4*3-(12+5); //Equals 0
</code>```

into an object of type int with the value of 0.

A function for complex operation would be preferable even though that's not the need of the hour:

```<code>2^(1/2)-99
</code>```

Is there any such definition defined in the standard C library (C89, C90, if it's compiled)?

Is there any non-standard library which has such an function?

The more the characters the expression supports the better it is.

But even basic operation like +,-,*,/,() would do.

答:
Is there any non-standard library which has such an function?

GNU bison has such an example. bison is a parser generator and is a free software tool generating C files.

You could also use and embed Lua in your application. It is open source, so you should study its source code. Lua is mostly coded in standard C99.

You could code your own recursive descent parser, quite simple to do.

You could consider embedding GNU Guile or Python in your application.

Of course, you should use a better operating system than the obsolete MS-DOS (or its FreeDOS alternative). Debian comes to mind.

You could use tinycc, it has a library (libtcc) similar to your needs and you can study its source code.

You need to read textbooks about parsing and compiling. The Dragon book comes to mind. Or at least read the wikipedia page on parsing and on lexing.

Body:
I am looking for a function that can evaluate a string expression into an integer, like f.e.:

10/2+4*3-(12+5); //Equals 0

into an object of type int with the value of 0.

A function for complex operation would be preferable even though that's not the need of the hour:

2^(1/2)-99

Is there any such definition defined in the standard C library (C89, C90, if it's compiled)?

Is there any non-standard library which has such an function?

The more the characters the expression supports the better it is.

But even basic operation like +,-,*,/,() would do.


问:
when I click a button in a list of buttons, it changes all of them instead of only one -Angular
I have a problem with changing the text inside a button when clicked

I have a list of buttons in my HTML displaying  a list of angular material:

  <ng-container matColumnDef="finishDate">
     Estimated Finish
     {{ element.finishDate | date: 'medium'}}
  </ng-container>

  <ng-container matColumnDef="buildId">
     Cancel

      <button mat-flat-button color="accent
 (click)="cancelBuildingImage(element.buildId); setCancelingText($event)">
            {{content}}
      </button>

  </ng-container>

```

<p>My <code>.ts</code></p>

<pre class="lang-js prettyprint-override"><code>export class BuildingImagesComponent implements OnInit, OnDestroy {
  buildingImageList: BuildingImage[];
  displayedColumns: string[] = ["tag", "created", "startedBuilding", "finishDate", "buildId"];

  content: string;

  constructor(private builderService: BuilderService, private snackMessageService: SnackMessageService) {
    this.content = "Cancel build"
  }
  setCancelingText($event) {
    this.content = "Canceling..."
  }

  private populateBuildingImageList(): void {
    this.builderService.getBuildingImageList().then(response => {
      this.buildingImageErrorMessage = null;
      this.buildingImageList = response;
      this.convertDurationToDate();
    }).catch(() => {
      this.buildingImageErrorMessage = "Oops, there was an error getting the company list.";
    });
  }

public cancelBuildingImage(buildId: string): void {
    console.log("button pressed")
    this.builderService.cancelBuildingImage(buildId).then(() => {
      this.snackMessageService.sendMessage("Build canceled.");
      this.populateBuildingImageList(); // No se si es necesario, porque ya se llama en el builder.service
    }).catch(() => {
      this.buildingImageErrorMessage = "Oops, there was an error canceling the image build."
    });
  }
</code>```

Clicking one button changes the text of all my button settings and the value is canceled.

How do I change only one-button text when clicked? The dataSource is an object with the keys displayed as columns (example: finishDate) and it doesn't allow me to interact with the text button.

答:
Within the function setCancelingText, this doesn't refer to the button or the event, but the class of the component you're currently operating in. Because of this, you're changing the text of the content-variable for all buttons.

My approach to correct this would work like this:

Within the model BuildingImage, add a property for the cancel-button's text:*

cancelButtonText?: string;

Change the populateBuildingImageList function to define the empty properties when they arrive in your component:

  private populateBuildingImageList(): void {
    this.builderService.getBuildingImageList().then(response => {
      this.buildingImageErrorMessage = null;

      for (let item of response) {
        item.cancelButtonText = "Cancel build";
      }

      this.buildingImageList = response;
      this.convertDurationToDate();
    }).catch(() => {
      this.buildingImageErrorMessage = "Oops, there was an error getting the company list.";
    });
  }
```

<p>Then change the button like this:</p>

<pre class="lang-html prettyprint-override"><code><button mat-flat-button color="accent"
        (click)="cancelBuildingImage(element.buildId); setCancelingText(element);">
  {{element.cancelButtonText}}
</button>
</code>```

Finally, change the setCancelingText-function to this:

setCancelingText(element) {
  element.cancelButtonText = "Canceling...";
}
```

Personally I would also include the changing of the cancel-button into the cancelBuildingImage function, but you didn't share what it does and whether the setCancelingText function is called from somewhere else, so I left it in place.

*) I assume here that BuildingImage is a class. If it is an interface, you'd need to add the text when you create the object.

Body:
I have a problem with changing the text inside a button when clicked

I have a list of buttons in my HTML displaying  a list of angular material:

  <ng-container matColumnDef="finishDate">
     Estimated Finish
     {{ element.finishDate | date: 'medium'}}
  </ng-container>

  <ng-container matColumnDef="buildId">
     Cancel

      <button mat-flat-button color="accent
 (click)="cancelBuildingImage(element.buildId); setCancelingText($event)">
            {{content}}
      </button>

  </ng-container>

My .ts

export class BuildingImagesComponent implements OnInit, OnDestroy {
  buildingImageList: BuildingImage[];
  displayedColumns: string[] = ["tag", "created", "startedBuilding", "finishDate", "buildId"];

  content: string;

  constructor(private builderService: BuilderService, private snackMessageService: SnackMessageService) {
    this.content = "Cancel build"
  }
  setCancelingText($event) {
    this.content = "Canceling..."
  }

  private populateBuildingImageList(): void {
    this.builderService.getBuildingImageList().then(response => {
      this.buildingImageErrorMessage = null;
      this.buildingImageList = response;
      this.convertDurationToDate();
    }).catch(() => {
      this.buildingImageErrorMessage = "Oops, there was an error getting the company list.";
    });
  }

public cancelBuildingImage(buildId: string): void {
    console.log("button pressed")
    this.builderService.cancelBuildingImage(buildId).then(() => {
      this.snackMessageService.sendMessage("Build canceled.");
      this.populateBuildingImageList(); // No se si es necesario, porque ya se llama en el builder.service
    }).catch(() => {
      this.buildingImageErrorMessage = "Oops, there was an error canceling the image build."
    });
  }

Clicking one button changes the text of all my button settings and the value is canceled.

How do I change only one-button text when clicked? The dataSource is an object with the keys displayed as columns (example: finishDate) and it doesn't allow me to interact with the text button.

Body:
Within the function setCancelingText, this doesn't refer to the button or the event, but the class of the component you're currently operating in. Because of this, you're changing the text of the content-variable for all buttons.

My approach to correct this would work like this:

Within the model BuildingImage, add a property for the cancel-button's text:*

cancelButtonText?: string;

Change the populateBuildingImageList function to define the empty properties when they arrive in your component:

  private populateBuildingImageList(): void {
    this.builderService.getBuildingImageList().then(response => {
      this.buildingImageErrorMessage = null;

      for (let item of response) {
        item.cancelButtonText = "Cancel build";
      }

      this.buildingImageList = response;
      this.convertDurationToDate();
    }).catch(() => {
      this.buildingImageErrorMessage = "Oops, there was an error getting the company list.";
    });
  }

Then change the button like this:

<button mat-flat-button color="accent"
        (click)="cancelBuildingImage(element.buildId); setCancelingText(element);">
  {{element.cancelButtonText}}
</button>

Finally, change the setCancelingText-function to this:

setCancelingText(element) {
  element.cancelButtonText = "Canceling...";
}

Personally I would also include the changing of the cancel-button into the cancelBuildingImage function, but you didn't share what it does and whether the setCancelingText function is called from somewhere else, so I left it in place.

*) I assume here that BuildingImage is a class. If it is an interface, you'd need to add the text when you create the object.


问:
How to get list of categories for a store
I have a Store Model that can have multiple products. Each product has a category.

What is the most optimal way to get the list of categories for products in a store?

For eg. Store A has Products A (Cat1), Product B(Cat1), Product C (Cat2)

I want Cat1, Cat2 when I pass the Store A's id.

答:
```<code>@store = Store.find(ID)
@categories = @store.products.map {|p| p.category }
</code>```


问:
How to execute psql interactive in its docker container?
I want to run a query in Postgres interactive shell. I'm using a docker container for this purpose as follows:

Here is the relevant piece of docker-compose:

```<code>  db_of_ivms:
    image: postgres:10
    restart: unless-stopped
    ports:
     - 5432:5432
    container_name: db_of_ivms
    environment:
      POSTGRES_PASSWORD: xxx
      POSTGRES_USER: ivms_usr
      POSTGRES_DB: ivms_db
</code>```

Nevertheless, I'm dealing with this error:

docker exec -it -u 0 db_of_ivms bash

```<code># psql

psql: FATAL:  role "root" does not exist
</code>```

答:
I've found an alternative approach through Django shell:

$ python manage.py shell

from django.db import connection

cursor = connection.cursor()
cursor.execute("DELETE FROM django_migrations WHERE app='settings'")
```

Body:
I want to run a query in Postgres interactive shell. I'm using a docker container for this purpose as follows:

Here is the relevant piece of docker-compose:

  db_of_ivms:
    image: postgres:10
    restart: unless-stopped
    ports:
     - 5432:5432
    container_name: db_of_ivms
    environment:
      POSTGRES_PASSWORD: xxx
      POSTGRES_USER: ivms_usr
      POSTGRES_DB: ivms_db

Nevertheless, I'm dealing with this error:

docker exec -it -u 0 db_of_ivms bash

# psql

psql: FATAL:  role "root" does not exist


问:
How to make Laravel Session Array Push?
I want to keep the records added in the last 20 seconds in the session. I check this with Ajax. But the most recent record is constantly being added. I can't write on it. I'm trying session :: pull this time, {} sounds empty this way.

Here is the sample code;

```<code>$crm = \GuzzleHttp\json_decode($guzzle->getBody()->getContents(), true);

foreach($crm['list'] as $row) {
      if(Carbon::create($row['createdAt'])->add(2, 'minutes')->diffInSeconds() < 20) {
             Session::put('data', [$row]);
       }
 }

 return response()->json(Session::get('data'));
</code>```

答:
When you use Session::put you are overriding that key in the session, so you will always end up with the last record in a single-item array in the session.

If you want to keep all the entries in the session, you should prepare the data, and then put it in the session.

```<code>$data = [];

foreach($crm['list'] as $row) {
    if (Carbon::create($row['createdAt'])->add(2, 'minutes')->diffInSeconds() < 20) {
        $data[] =  $row;
    }
}

Session::put('data', $data);

return response()->json($data);
</code>```

About using session

As Dilip Hirapara suggested, if you aren't using this information in another place, you may not need to rely on session, and just return an array.

Title: How to make Laravel Session Array Push?

Body:
I want to keep the records added in the last 20 seconds in the session. I check this with Ajax. But the most recent record is constantly being added. I can't write on it. I'm trying session :: pull this time, {} sounds empty this way.

Here is the sample code;

$crm = \GuzzleHttp\json_decode($guzzle->getBody()->getContents(), true);

foreach($crm['list'] as $row) {
      if(Carbon::create($row['createdAt'])->add(2, 'minutes')->diffInSeconds() < 20) {
             Session::put('data', [$row]);
       }
 }

 return response()->json(Session::get('data'));

Body:
When you use Session::put you are overriding that key in the session, so you will always end up with the last record in a single-item array in the session.

If you want to keep all the entries in the session, you should prepare the data, and then put it in the session.

$data = [];

foreach($crm['list'] as $row) {
    if (Carbon::create($row['createdAt'])->add(2, 'minutes')->diffInSeconds() < 20) {
        $data[] =  $row;
    }
}

Session::put('data', $data);

return response()->json($data);

About using session

As Dilip Hirapara suggested, if you aren't using this information in another place, you may not need to rely on session, and just return an array.


问:
Polymorphic association with id and type in separate tables
I have a polymorphic relation in my application for custom fields similar to this:

```<code>class CustomFieldValue < ApplicationRecord
  belongs_to :custom_field_type
  belongs_to :custom_field_valuable, polymorphic: true
end
</code>```

```<code>class CustomFieldType < ApplicationRecord
  has_many :custom_field_values
end
</code>```

Basically the custom_field_type table holds a few details about the field type (selection, checkbox etc) as well as a 'model_type' column for the model the custom field belongs to.

The custom_field_value table has the expected polymorphic columns 'custom_field_valuable_type' and 'custom_field_valuable_id' which works fine but seeing as custom_field_value belongs to custom_field_type which already has the model_type stored, I was wondering if there was a way I can do away with the custom_field_valuable_type?

I've tried redefining 'custom_field_valuable_type' with

```<code>def custom_field_valuabkle_type
  self.custom_field_type.model_type
end
</code>```

But that doesn't work as there is no column to query.

答:
I was wondering if there was a way I can do away with the
custom_field_valuable_type?

No. Polymorphic associations expect a association_name_type column to exist on the table with the association. Putting the type column another table is not possible AFAIK and would be really over-complicated.

Polymorphic associations are already a hacky solution to the Object-relational impedance mismatch problem and you're going from saying that the foreign key is constructed from two columns to the foreign key is constructed of from columns on different tables! That doesn't improve anything and just increases the mismatch.

Your approach is not going to work as the join queries are done in the database and don't call your getter method.

I think you're also confusing two completely different concepts. What you are doing is just a variation on the Entity Attribute Value (EAV) pattern. What your CustomFieldType provides to the setup is normalization of the attributes - so that your not duplicating the definition of attributes with each value. This has nothing to do with linking Value -> Entity.

Body:
I have a polymorphic relation in my application for custom fields similar to this:

class CustomFieldValue < ApplicationRecord
  belongs_to :custom_field_type
  belongs_to :custom_field_valuable, polymorphic: true
end

class CustomFieldType < ApplicationRecord
  has_many :custom_field_values
end

Basically the custom_field_type table holds a few details about the field type (selection, checkbox etc) as well as a 'model_type' column for the model the custom field belongs to.

The custom_field_value table has the expected polymorphic columns 'custom_field_valuable_type' and 'custom_field_valuable_id' which works fine but seeing as custom_field_value belongs to custom_field_type which already has the model_type stored, I was wondering if there was a way I can do away with the custom_field_valuable_type?

I've tried redefining 'custom_field_valuable_type' with

def custom_field_valuabkle_type
  self.custom_field_type.model_type
end

But that doesn't work as there is no column to query.


问:
Kotlin SupervisorJob unexpected behaviour
I have the next code:

```<code>import kotlin.coroutines.*;
import kotlinx.coroutines.*;

val job = SupervisorJob()
val handler = CoroutineExceptionHandler { _, e ->
    println("Catch: $e")
}
val coroutineContext: CoroutineContext = Dispatchers.IO + job + handler

fun main() {
    val job1 = GlobalScope.launch(coroutineContext) {
        // supervisorScope {
        launch {
            println("Test0")
            for (i in 0..5) {
                println("Working! Iteration: $i")
                delay(1000)
            }
            println("Test0 end")
        }

        launch {
            println("Test1")
            delay(2000)
            throw IllegalAccessException()
        }

        launch {
            println("Test2")
            delay(3000)
            println("Test2 end")
        }

    }
    //}
    runBlocking { job1.join() }
    println("Test3")
}
</code>```

As You can see, I'm using SupervisorJob by passing it in coroutineContext into GlobalScope.launch to avoid canceling of any children on error if it happened anywhere and error must be handled in handler. The documetation says next about SupervisorJob:

```<code>Creates a supervisor job object in an active state. Children of a supervisor job can fail independently of each other.
</code>```

Based on this, I'm expecting something like that:

```<code>Test0
Working! Iteration: 0
Test1
Test2
Working! Iteration: 1
Catch: java.lang.IllegalAccessException
Working! Iteration: 2
Working! Iteration: 3
Test2 end
Working! Iteration: 4
Working! Iteration: 5
Test0 end
Test3
</code>```

But I get:

```<code>Test2
Test0
Working! Iteration: 0
Test1
Working! Iteration: 1
Catch: java.lang.IllegalAccessException
Test3
</code>```

The only that helps is uncomment supervisorScope in code above.

What I'm doing wrong? How I can set expected behaviour globaly in ViewModel, for example, to avoid wrapping every launch in supervisorScope?

Thanks in advance.

答:
As explained in this answer, you can't change the type of the job for a launched coroutine. The only thing under your control is its parent job. Since you first launch a top-level coroutine and then, as its children, launch those whose failure you don't want to influence the others, the best option is what you already discovered, opening an inner supervisorScope.

You cannot specify a global policy on how a given coroutine will behave upon the failure of its children.

Body:
I have the next code:

import kotlin.coroutines.*;
import kotlinx.coroutines.*;

val job = SupervisorJob()
val handler = CoroutineExceptionHandler { _, e ->
    println("Catch: $e")
}
val coroutineContext: CoroutineContext = Dispatchers.IO + job + handler

fun main() {
    val job1 = GlobalScope.launch(coroutineContext) {
        // supervisorScope {
        launch {
            println("Test0")
            for (i in 0..5) {
                println("Working! Iteration: $i")
                delay(1000)
            }
            println("Test0 end")
        }

        launch {
            println("Test1")
            delay(2000)
            throw IllegalAccessException()
        }

        launch {
            println("Test2")
            delay(3000)
            println("Test2 end")
        }

    }
    //}
    runBlocking { job1.join() }
    println("Test3")
}

As You can see, I'm using SupervisorJob by passing it in coroutineContext into GlobalScope.launch to avoid canceling of any children on error if it happened anywhere and error must be handled in handler. The documetation says next about SupervisorJob:

Creates a supervisor job object in an active state. Children of a supervisor job can fail independently of each other.

Based on this, I'm expecting something like that:

Test0
Working! Iteration: 0
Test1
Test2
Working! Iteration: 1
Catch: java.lang.IllegalAccessException
Working! Iteration: 2
Working! Iteration: 3
Test2 end
Working! Iteration: 4
Working! Iteration: 5
Test0 end
Test3

But I get:

Test2
Test0
Working! Iteration: 0
Test1
Working! Iteration: 1
Catch: java.lang.IllegalAccessException
Test3

The only that helps is uncomment supervisorScope in code above.

What I'm doing wrong? How I can set expected behaviour globaly in ViewModel, for example, to avoid wrapping every launch in supervisorScope?

Thanks in advance.


问:
how to get result with group by and count of fileds in MySql
my table

```<code>CNT_ID  REGION   GRADE  MAX-CAPACITY  TOTAL-CAPACITY LASTDATE

1001    TN       FOOD   97             100            2020-02-17
1001    BG       BEV    76              90            2020-02-17
1001    KA       IND    88              90            2020-02-17
1001    BG       FOOD   91             100            2020-02-17
1001    ER       IND    90             100            2020-02-15
1001    TN       FOOD   78              80            2020-02-17
1001    TN       BEV    95             100            2020-02-17
1001    TN       FOOD   92             100            2020-02-16
</code>```

I want to get result based on... list by REGIONS -> AND COUNT OF MaxCapacity of(FOOD, BEV, IND) AND ORDERED BY LASTDATE desc

result expected:

```<code>REGION  FOODGRADE   BEVGRADE    INDGRADE    TOTALCAPACITY   LEFT    LASTDATE
TN      267             95          0       380             18      2020-02-17
BG      91              76          0       190             23      2020-02-17
KA      0               0           88      90              2       2020-02-17
ER      0               0           90      100             10      2020-02-17
</code>```

I TRIED THE FOLLOWING... but no luck:

```<code>SELECT COUNT(IF(GRADE='FOOD',1,NULL)) 'Food', COUNT(IF(GRADE='BEV',1,NULL)) 'Beve', *
FROM txn_viewinfo
WHERE LASTDATE = (SELECT MAX(LASTDATE)
                  FROM txn_viewinfo )
ORDER BY LASTDATE DESC;
</code>```

答:
You can use GROUP BY as shown below:

```<code>select *
from (
  select
    region,
    sum(case when grade = 'FOOD' then max_capacity else 0 end) as foodgrade,
    sum(case when grade = 'BEV' then max_capacity else 0 end) as bevgrade,
    sum(case when grade = 'IND' then max_capacity else 0 end) as indgrade,
    sum(total_capacity) as totalcapacity,
    sum(total_capacity - max_capacity) as lft,
    max(lastdate) as lastdate
  from txn_viewinfo
  group by region
) x
order by lastdate
</code>```

Body:
my table

CNT_ID  REGION   GRADE  MAX-CAPACITY  TOTAL-CAPACITY LASTDATE

1001    TN       FOOD   97             100            2020-02-17
1001    BG       BEV    76              90            2020-02-17
1001    KA       IND    88              90            2020-02-17
1001    BG       FOOD   91             100            2020-02-17
1001    ER       IND    90             100            2020-02-15
1001    TN       FOOD   78              80            2020-02-17
1001    TN       BEV    95             100            2020-02-17
1001    TN       FOOD   92             100            2020-02-16

I want to get result based on... list by REGIONS -> AND COUNT OF MaxCapacity of(FOOD, BEV, IND) AND ORDERED BY LASTDATE desc

result expected:

REGION  FOODGRADE   BEVGRADE    INDGRADE    TOTALCAPACITY   LEFT    LASTDATE
TN      267             95          0       380             18      2020-02-17
BG      91              76          0       190             23      2020-02-17
KA      0               0           88      90              2       2020-02-17
ER      0               0           90      100             10      2020-02-17

I TRIED THE FOLLOWING... but no luck:

SELECT COUNT(IF(GRADE='FOOD',1,NULL)) 'Food', COUNT(IF(GRADE='BEV',1,NULL)) 'Beve', *
FROM txn_viewinfo
WHERE LASTDATE = (SELECT MAX(LASTDATE)
                  FROM txn_viewinfo )
ORDER BY LASTDATE DESC;

Body:
You can use GROUP BY as shown below:

select *
from (
  select
    region,
    sum(case when grade = 'FOOD' then max_capacity else 0 end) as foodgrade,
    sum(case when grade = 'BEV' then max_capacity else 0 end) as bevgrade,
    sum(case when grade = 'IND' then max_capacity else 0 end) as indgrade,
    sum(total_capacity) as totalcapacity,
    sum(total_capacity - max_capacity) as lft,
    max(lastdate) as lastdate
  from txn_viewinfo
  group by region
) x
order by lastdate


问:
Using a4j:support to update the model and view, ready for the next button/submit action

The Problem

We have a swing based front end for an enterprise application and now are implementing a (for now simpler) JSF/Seam/Richfaces front end for it.

Some of the pages include fields that, when edited, should cause other fields to change as a result. We need this change to be shown to the user immediately (i.e. they should not have to press a button or anything).

I have implemented this successfully using h:commandButton and by adding onchange="submit()" to the fields that cause other fields to change. That way, a form submit occurs when they edit the field, and the other fields are updated as a result.

This works fine functionally, but especially when the server is under significant load (which happens often) the form submits can take a long time and our users have been continuing to edit fields in the meantime which then get reverted when the responses to the onchange="submit()" requests are rendered.

To solve this problem, I was hoping to achieve something where:

Upon editing the field, if required, only that field is processed and only the fields it modifies are re-rendered (so that any other edits the user has made in the meantime do not get lost).

Upon pressing a button, all fields are processed and re-rendered as normal.

The (Unstable) Solution

Okay, I think it might be easiest to show a bit of my page first. Note that this is only an excerpt and that some pages will have many fields and many buttons.

```<code><a4j:form id="mainForm">
    ...
    <a4j:commandButton id="calculateButton" value="Calculate" action="#{illustrationManager.calculatePremium()}" reRender="mainForm" />
    ...
    <h:outputLabel for="firstName" value=" First Name" />
    <h:inputText id="firstName" value="#{life.firstName}" />
    ...
    <h:outputLabel for="age" value=" Age" />
    <h:inputText id="age" value="#{life.age}">
        <f:convertNumber type="number" integerOnly="true" />
        <a4j:support event="onchange" ajaxSingle="true" reRender="dob" />
    </h:inputText>
    <h:outputLabel for="dob" value=" DOB" />
    <h:inputText id="dob" value="#{life.dateOfBirth}" styleClass="date">
        <f:convertDateTime pattern="dd/MM/yyyy" timeZone="#{userPreference.timeZone}" />
        <a4j:support event="onchange" ajaxSingle="true" reRender="age,dob" />
    </h:inputText>
    ...
</a4j:form>
</code>```

Changing the value of age causes the value of dob to change in the model and vice versa. I use reRender="dob" and reRender="age,dob" to display the changed values from the model. This works fine.

I am also using the global queue to ensure ordering of AJAX requests.

However, the onchange event does not occur until I click somewhere else on the page or press tab or something. This causes problems when the user enters a value in say, age, and then presses calculateButton without clicking somewhere else on the page or pressing tab.

The onchange event does appear to occur first as I can see the value of dob change but the two values are then reverted when the calculateButton request is performed.

So, finally, to the question: Is there a way to ensure that the model and view are updated completely before the calculateButton request is made so that it does not revert them? Why is that not happening already since I am using the AJAX queue?

The Workarounds

There are two strategies to get around this limitation but they both require bloat in the facelet code which could be confusing to other developers and cause other problems.

Workaround 1: Using a4j:support

This strategy is as follows:

Add the ajaxSingle="true" attribute to calculateButton.

Add the a4j:support tag with the ajaxSingle="true" attribute to firstName.

The first step ensures that calculateButton does not overwrite the values in age or dob since it no longer processes them. Unfortunately it has the side effect that it no longer processes firstName either. The second step is added to counter this side effect by processing firstName before calculateButton is pressed.

Keep in mind though that there could be 20+ fields like firstName. A user filling out a form could then cause 20+ requests to the server! Like I mentioned before this is also bloat that may confuse other developers.

Workaround 2: Using the process list

Thanks to @DaveMaple and @MaxKatz for suggesting this strategy, it is as follows:

Add the ajaxSingle="true" attribute to calculateButton.

Add the process="firstName" attribute to calculateButton.

The first step achieves the same as it did in the first workaround but has the same side effect. This time the second step ensures that firstName is processed with calculateButton when it is pressed.

Again, keep in mind though that there could be 20+ fields like firstName to include in this list. Like I mentioned before this is also bloat that may confuse other developers, especially since the list must include some fields but not others.

Age and DOB Setters and Getters (just in case they are the cause of the issue)

```<code>public Number getAge() {
    Long age = null;

    if (dateOfBirth != null) {
        Calendar epochCalendar = Calendar.getInstance();
        epochCalendar.setTimeInMillis(0L);
        Calendar dobCalendar = Calendar.getInstance();
        dobCalendar.setTimeInMillis(new Date().getTime() - dateOfBirth.getTime());
        dobCalendar.add(Calendar.YEAR, epochCalendar.get(Calendar.YEAR) * -1);

        age = new Long(dobCalendar.get(Calendar.YEAR));
    }

    return (age);
}

public void setAge(Number age) {
    if (age != null) {
        // This only gives a rough date of birth at 1/1/<this year minus <age> years>.
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR) - age.intValue(), Calendar.JANUARY, 1, 0, 0, 0);

        setDateOfBirth(calendar.getTime());
    }
}

public Date getDateOfBirth() {
    return dateOfBirth;
}

public void setDateOfBirth(Date dateOfBirth) {
    if (notEqual(this.dateOfBirth, dateOfBirth)) {
        // If only two digits were entered for the year, provide useful defaults for the decade.
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateOfBirth);
        if (calendar.get(Calendar.YEAR) < 50) {
            // If the two digits entered are in the range 0-49, default the decade 2000.
            calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + 2000);
        } else if (calendar.get(Calendar.YEAR) < 100) {
            // If the two digits entered are in the range 50-99, default the decade 1900.
            calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + 1900);
        }
        dateOfBirth = calendar.getTime();

        this.dateOfBirth = dateOfBirth;
        changed = true;
    }
}
</code>```

答: What is the scope of your bean? When the button is executed, it's a new request and if your bean is in request scope, then previous values will be gone. </p>

Body:
The Problem

We have a swing based front end for an enterprise application and now are implementing a (for now simpler) JSF/Seam/Richfaces front end for it.

Some of the pages include fields that, when edited, should cause other fields to change as a result. We need this change to be shown to the user immediately (i.e. they should not have to press a button or anything).

I have implemented this successfully using h:commandButton and by adding onchange="submit()" to the fields that cause other fields to change. That way, a form submit occurs when they edit the field, and the other fields are updated as a result.

This works fine functionally, but especially when the server is under significant load (which happens often) the form submits can take a long time and our users have been continuing to edit fields in the meantime which then get reverted when the responses to the onchange="submit()" requests are rendered.

To solve this problem, I was hoping to achieve something where:

Upon editing the field, if required, only that field is processed and only the fields it modifies are re-rendered (so that any other edits the user has made in the meantime do not get lost).

Upon pressing a button, all fields are processed and re-rendered as normal.

The (Unstable) Solution

Okay, I think it might be easiest to show a bit of my page first. Note that this is only an excerpt and that some pages will have many fields and many buttons.

<a4j:form id="mainForm">
    ...
    <a4j:commandButton id="calculateButton" value="Calculate" action="#{illustrationManager.calculatePremium()}" reRender="mainForm" />
    ...
    <h:outputLabel for="firstName" value=" First Name" />
    <h:inputText id="firstName" value="#{life.firstName}" />
    ...
    <h:outputLabel for="age" value=" Age" />
    <h:inputText id="age" value="#{life.age}">
        <f:convertNumber type="number" integerOnly="true" />
        <a4j:support event="onchange" ajaxSingle="true" reRender="dob" />
    </h:inputText>
    <h:outputLabel for="dob" value=" DOB" />
    <h:inputText id="dob" value="#{life.dateOfBirth}" styleClass="date">
        <f:convertDateTime pattern="dd/MM/yyyy" timeZone="#{userPreference.timeZone}" />
        <a4j:support event="onchange" ajaxSingle="true" reRender="age,dob" />
    </h:inputText>
    ...
</a4j:form>

Changing the value of age causes the value of dob to change in the model and vice versa. I use reRender="dob" and reRender="age,dob" to display the changed values from the model. This works fine.

I am also using the global queue to ensure ordering of AJAX requests.

However, the onchange event does not occur until I click somewhere else on the page or press tab or something. This causes problems when the user enters a value in say, age, and then presses calculateButton without clicking somewhere else on the page or pressing tab.

The onchange event does appear to occur first as I can see the value of dob change but the two values are then reverted when the calculateButton request is performed.

So, finally, to the question: Is there a way to ensure that the model and view are updated completely before the calculateButton request is made so that it does not revert them? Why is that not happening already since I am using the AJAX queue?

The Workarounds

There are two strategies to get around this limitation but they both require bloat in the facelet code which could be confusing to other developers and cause other problems.

Workaround 1: Using a4j:support

This strategy is as follows:

Add the ajaxSingle="true" attribute to calculateButton.

Add the a4j:support tag with the ajaxSingle="true" attribute to firstName.

The first step ensures that calculateButton does not overwrite the values in age or dob since it no longer processes them. Unfortunately it has the side effect that it no longer processes firstName either. The second step is added to counter this side effect by processing firstName before calculateButton is pressed.

Keep in mind though that there could be 20+ fields like firstName. A user filling out a form could then cause 20+ requests to the server! Like I mentioned before this is also bloat that may confuse other developers.

Workaround 2: Using the process list

Thanks to @DaveMaple and @MaxKatz for suggesting this strategy, it is as follows:

Add the ajaxSingle="true" attribute to calculateButton.

Add the process="firstName" attribute to calculateButton.

The first step achieves the same as it did in the first workaround but has the same side effect. This time the second step ensures that firstName is processed with calculateButton when it is pressed.

Again, keep in mind though that there could be 20+ fields like firstName to include in this list. Like I mentioned before this is also bloat that may confuse other developers, especially since the list must include some fields but not others.

Age and DOB Setters and Getters (just in case they are the cause of the issue)

public Number getAge() {
    Long age = null;

    if (dateOfBirth != null) {
        Calendar epochCalendar = Calendar.getInstance();
        epochCalendar.setTimeInMillis(0L);
        Calendar dobCalendar = Calendar.getInstance();
        dobCalendar.setTimeInMillis(new Date().getTime() - dateOfBirth.getTime());
        dobCalendar.add(Calendar.YEAR, epochCalendar.get(Calendar.YEAR) * -1);

        age = new Long(dobCalendar.get(Calendar.YEAR));
    }

    return (age);
}

public void setAge(Number age) {
    if (age != null) {
        // This only gives a rough date of birth at 1/1/<this year minus <age> years>.
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR) - age.intValue(), Calendar.JANUARY, 1, 0, 0, 0);

        setDateOfBirth(calendar.getTime());
    }
}

public Date getDateOfBirth() {
    return dateOfBirth;
}

public void setDateOfBirth(Date dateOfBirth) {
    if (notEqual(this.dateOfBirth, dateOfBirth)) {
        // If only two digits were entered for the year, provide useful defaults for the decade.
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateOfBirth);
        if (calendar.get(Calendar.YEAR) < 50) {
            // If the two digits entered are in the range 0-49, default the decade 2000.
            calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + 2000);
        } else if (calendar.get(Calendar.YEAR) < 100) {
            // If the two digits entered are in the range 50-99, default the decade 1900.
            calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + 1900);
        }
        dateOfBirth = calendar.getTime();

        this.dateOfBirth = dateOfBirth;
        changed = true;
    }
}


问:
What is the following C++ code used for -> "#define idiv(a, b) (((a) + (b) / 2) / (b))"?
I'm working with the code that frequently uses some nontrivial optimizations.
What is the

#define idiv(a, b) (((a) + (b) / 2) / (b))
```

<p>used for? Why not simply</p>

<pre class="lang-c prettyprint-override"><code>#define idiv(a, b) ((a)/(b) + 0.5)
</code>```

Is it integer division overflow protection or something else?

答:
Integer division truncates towards zero. Assuming (from the name of the macro, idiv) your arguments are of integer type, ((a)/(b) + 0.5) would be truncated before you got to the + 0.5, so you would always round down regardless.

(((a) + (b) / 2) / (b)) rounds up results greater than x.5, without using floating-point arithmetics.

Note: You tagged your question C++. In C++, you shouldn't "macro" anything, really. Check Marek's answer for a template solution (but also the caveat that it doesn't really work for negative values).

Body:
I'm working with the code that frequently uses some nontrivial optimizations.
What is the

#define idiv(a, b) (((a) + (b) / 2) / (b))

used for? Why not simply

#define idiv(a, b) ((a)/(b) + 0.5)

Is it integer division overflow protection or something else?


问:
How to implement google authenticator for 2 factor authentication with WSO2 identity server 5.7?
I want to use Google Authenticator for 2-factor authentication with WSO2 identity server 5.7.0. The Google Authenticator should provide a One-Time Password which is valid only for a very short duration. Using the email id, password and OTP (generated from Google Authenticator) a user should be allowed to sign in into an application.

I cannot find how to implement google authenticator in the link mentioned below WSO2 Identity Server Authenticators and Connectors Documentation

Can anyone provide some steps in the direction to implement Google Authenticator with WSO2?

Note: I am not referring to using Google as a federated authenticator.

答:
As for me for your use case you don't need google authenticator you need email otp[1]. You can configure your email otp to generate from google. You can enable it as a second factor in authentication. So the first user will login using user name and password then user will be asked for the otp that generated from google. That will be sent to the user email account.

If you want to use the google authenticator to get the otp not the email then you should use wso2 totp. [2]

[1]. https://docs.wso2.com/display/IS570/Configuring+Email+OTP
[2].https://docs.wso2.com/display/ISCONNECTORS/Configuring+TOTP+Authenticator


问:
Issue with loading a button based on the loggedin state
I am trying different ways to display a conditional button based on the athtentication state, but i keep getting into trouble. I have an app.js that defines the stacknavigator, which adds a button to the header giving the option to log out if authenticated.

I wrote a handleLogout function that should perform this.

```<code>import React from 'react';
import { Button, Image, View, Text } from 'react-native';
import firebase from 'react-native-firebase';
import Loading from './Loading';
import SignUp from './SignUp';
import Login from './Login';
import Main from './Main';
import {createAppContainer} from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';
import { useNavigation } from '@react-navigation/native';

// eslint-disable-next-line no-undef
handleLogOut = () => {
  const navigation = useNavigation();
  firebase
    .auth()
    .signOut()
    .then(() => this.props.navigation.navigate('Login'))
    .catch(error => this.setState({errorMessage: error.message}));
};

const AppNavigator = createStackNavigator(
  {
    Loading: Loading,
    SignUp: SignUp,
    Login: Login,
    Main: Main,
  },
  {
    initialRouteName: 'Loading',

    defaultNavigationOptions: {
      headerLeft: null,
      headerRight: () => {
          let button = this.loggedIn? (
          <Button
          onPress={this.handleLogOut}
          title="Log-out"
          color="#fff"
          />
        )
        :
        (
          <Button
          onPress={() => alert('Please log in')}
          title="Log-in"
          color="#fff"
          />
        )
          return button;
      },

      headerStyle: {
        backgroundColor: '#c6f1e7',
      },
      headerTintColor: '#59616e',
      headerTitleStyle: {
        fontFamily: 'Raleway-Regular',
        fontWeight: '400',
      },
    },
  },
);

export default createAppContainer(AppNavigator);
</code>```

App.js calls on loading.js where the value for loggedin is declared, based on the authentciation state and then loads either main.js or sign-up. in this case the main page is loaded, which means that someone is authenticated:

```<code>// Loading.js
import React from 'react';
import {View, ActivityIndicator, StyleSheet} from 'react-native';
import firebase from 'react-native-firebase';

export default class Loading extends React.Component {
  componentDidMount() {
    firebase.auth().onAuthStateChanged(user => {
      if (user) {
        this.setState({ loggedIn: true })
        this.props.navigation.navigate(user ? 'Main' : 'SignUp');
      } else {
        this.setState({ loggedIn: false })
      }
    });
  }
  render() {
    return (
      <View style={styles.container}>
        <ActivityIndicator size="large" />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#c6f1e7',
  },
});
</code>```

Now the page redirects to main and shows the welcome message, which indicates that the user is logged in, but the button in the header is saying 'log-in' as well, which means the button is not chosen well. I assume that this is because the loggedin value is not read and it automatically sets it on loggedin: false.

Here is the code for main.js

```<code>// Main.js
import React from 'react';
import { View, Text, StyleSheet, Button } from 'react-native';
import firebase from 'react-native-firebase';
import { createAppContainer } from 'react-navigation';
import { createBottomTabNavigator } from 'react-navigation-tabs';
import Kowops from './Kowops';
import Scan from './Scan';
import Wallet from './Wallet';

export class Main extends React.Component {
  state = { currentUser: null }
  componentDidMount() {
    const { currentUser } = firebase.auth()
    this.setState({ currentUser })
}
  render() {
    const { currentUser } = this.state

  return (
      <View style={styles.container}>
        <Text>
          Hidiho {currentUser && currentUser.email}!
        </Text>
      </View>
    )
  }
}
 const bottomTabNavigator = createBottomTabNavigator(
  {
    Main: {screen: Main},
    Kowops: {screen:Kowops},
    Scan: {screen:Scan},
    Wallet: {screen:Wallet},
  },
  {
    //initialRouteName: 'Main',
    tabBarOptions: {
      initialRouteName: 'Main',
      activeTintColor: '#59616e',
      inactiveTintColor: '#a9a9a9',
      style: {
        backgroundColor: '#c6f1e7',
     }
    },
  });

export default createAppContainer(bottomTabNavigator);

const styles = StyleSheet.create({
    container: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
    }
  })
</code>```

So I need to figure out how to ensure that the value of isloggedin is read properly and the script loads the right button.

Does anyone have a clue?

Thanks in advance!!

Tim

答:
The key here is that you can't use state across different components without passing them as props or through navigation params in this case. You can't use the useNavigation hook outside of a functional component so you should pass the navigation object around when you need it outside of a component (handleLogout is not a component).

Here are some alterations I would make, however I would suggest that you will need to make further changes based on the idea that you can use navigation params to pass information between screens. See more here https://reactnavigation.org/docs/en/params.html.

App.js

DefaultNavigationOptions can be a function which has a navigation prop, this is the navigation object you can use to get params or navigate in the context of the router.

remove that eslint exception because you don't need it, just properly declare the variable. Remove the "this" from you handleLogout function call because it is not a class attribute. Use navigation.getParam to get the isLoggedIn variable which you can pass in the navigate function call.

```<code>const handleLogout = navigation => {
    firebase
        .auth()
        .signOut()
        .then(() => navigation.navigate('Login'))
        .catch(error => this.setState({errorMessage: error.message}));
}

...

defaultNavigationOptions: ({navigation}) => ({
    headerRight: () => {

        const isLoggedIn = navigation.getParam('isLoggedIn', false);
        let button = isLoggedIn ? (
          <Button
            onPress={() => handleLogOut(navigation)}
            title="Log-out"
            color="#fff"
          />
        ) : ...
    } ...
</code>```

Now Loading.js
Here you need to add a navigation param to your navigate call which can then be used in the header

```<code> ...
 firebase.auth().onAuthStateChanged(user => {
  if (user) {

    this.props.navigation.navigate('Main', {isLoggedIn: true});
  } else {
    this.props.navigation.navigate('SignUp', {isLoggedIn: false});
  }
});
</code>```

here is a modified version of your code in snack that you can see will get the logged in param and show the logout button https://snack.expo.io/@dannyhw/intrigued-graham-crackers
You will need to make further changes to fix other functionality because I only changed the minimum to show that you can use the navigation param.

Body:
I am trying different ways to display a conditional button based on the athtentication state, but i keep getting into trouble. I have an app.js that defines the stacknavigator, which adds a button to the header giving the option to log out if authenticated.

I wrote a handleLogout function that should perform this.

import React from 'react';
import { Button, Image, View, Text } from 'react-native';
import firebase from 'react-native-firebase';
import Loading from './Loading';
import SignUp from './SignUp';
import Login from './Login';
import Main from './Main';
import {createAppContainer} from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';
import { useNavigation } from '@react-navigation/native';

// eslint-disable-next-line no-undef
handleLogOut = () => {
  const navigation = useNavigation();
  firebase
    .auth()
    .signOut()
    .then(() => this.props.navigation.navigate('Login'))
    .catch(error => this.setState({errorMessage: error.message}));
};

const AppNavigator = createStackNavigator(
  {
    Loading: Loading,
    SignUp: SignUp,
    Login: Login,
    Main: Main,
  },
  {
    initialRouteName: 'Loading',

    defaultNavigationOptions: {
      headerLeft: null,
      headerRight: () => {
          let button = this.loggedIn? (
          <Button
          onPress={this.handleLogOut}
          title="Log-out"
          color="#fff"
          />
        )
        :
        (
          <Button
          onPress={() => alert('Please log in')}
          title="Log-in"
          color="#fff"
          />
        )
          return button;
      },

      headerStyle: {
        backgroundColor: '#c6f1e7',
      },
      headerTintColor: '#59616e',
      headerTitleStyle: {
        fontFamily: 'Raleway-Regular',
        fontWeight: '400',
      },
    },
  },
);

export default createAppContainer(AppNavigator);

App.js calls on loading.js where the value for loggedin is declared, based on the authentciation state and then loads either main.js or sign-up. in this case the main page is loaded, which means that someone is authenticated:

// Loading.js
import React from 'react';
import {View, ActivityIndicator, StyleSheet} from 'react-native';
import firebase from 'react-native-firebase';

export default class Loading extends React.Component {
  componentDidMount() {
    firebase.auth().onAuthStateChanged(user => {
      if (user) {
        this.setState({ loggedIn: true })
        this.props.navigation.navigate(user ? 'Main' : 'SignUp');
      } else {
        this.setState({ loggedIn: false })
      }
    });
  }
  render() {
    return (
      <View style={styles.container}>
        <ActivityIndicator size="large" />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#c6f1e7',
  },
});

Now the page redirects to main and shows the welcome message, which indicates that the user is logged in, but the button in the header is saying 'log-in' as well, which means the button is not chosen well. I assume that this is because the loggedin value is not read and it automatically sets it on loggedin: false.

Here is the code for main.js

// Main.js
import React from 'react';
import { View, Text, StyleSheet, Button } from 'react-native';
import firebase from 'react-native-firebase';
import { createAppContainer } from 'react-navigation';
import { createBottomTabNavigator } from 'react-navigation-tabs';
import Kowops from './Kowops';
import Scan from './Scan';
import Wallet from './Wallet';

export class Main extends React.Component {
  state = { currentUser: null }
  componentDidMount() {
    const { currentUser } = firebase.auth()
    this.setState({ currentUser })
}
  render() {
    const { currentUser } = this.state

  return (
      <View style={styles.container}>
        <Text>
          Hidiho {currentUser && currentUser.email}!
        </Text>
      </View>
    )
  }
}
 const bottomTabNavigator = createBottomTabNavigator(
  {
    Main: {screen: Main},
    Kowops: {screen:Kowops},
    Scan: {screen:Scan},
    Wallet: {screen:Wallet},
  },
  {
    //initialRouteName: 'Main',
    tabBarOptions: {
      initialRouteName: 'Main',
      activeTintColor: '#59616e',
      inactiveTintColor: '#a9a9a9',
      style: {
        backgroundColor: '#c6f1e7',
     }
    },
  });

export default createAppContainer(bottomTabNavigator);

const styles = StyleSheet.create({
    container: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
    }
  })

So I need to figure out how to ensure that the value of isloggedin is read properly and the script loads the right button.

Does anyone have a clue?

Thanks in advance!!

Tim

Body:
The key here is that you can't use state across different components without passing them as props or through navigation params in this case. You can't use the useNavigation hook outside of a functional component so you should pass the navigation object around when you need it outside of a component (handleLogout is not a component).

Here are some alterations I would make, however I would suggest that you will need to make further changes based on the idea that you can use navigation params to pass information between screens. See more here https://reactnavigation.org/docs/en/params.html.

App.js

DefaultNavigationOptions can be a function which has a navigation prop, this is the navigation object you can use to get params or navigate in the context of the router.

remove that eslint exception because you don't need it, just properly declare the variable. Remove the "this" from you handleLogout function call because it is not a class attribute. Use navigation.getParam to get the isLoggedIn variable which you can pass in the navigate function call.

const handleLogout = navigation => {
    firebase
        .auth()
        .signOut()
        .then(() => navigation.navigate('Login'))
        .catch(error => this.setState({errorMessage: error.message}));
}

...

defaultNavigationOptions: ({navigation}) => ({
    headerRight: () => {

        const isLoggedIn = navigation.getParam('isLoggedIn', false);
        let button = isLoggedIn ? (
          <Button
            onPress={() => handleLogOut(navigation)}
            title="Log-out"
            color="#fff"
          />
        ) : ...
    } ...

Now Loading.js
Here you need to add a navigation param to your navigate call which can then be used in the header

 ...
 firebase.auth().onAuthStateChanged(user => {
  if (user) {

    this.props.navigation.navigate('Main', {isLoggedIn: true});
  } else {
    this.props.navigation.navigate('SignUp', {isLoggedIn: false});
  }
});

here is a modified version of your code in snack that you can see will get the logged in param and show the logout button https://snack.expo.io/@dannyhw/intrigued-graham-crackers
You will need to make further changes to fix other functionality because I only changed the minimum to show that you can use the navigation param.


问:
Changing value of a an object of Integer class
How to change value of a an object of Integer class ex: here I have declared the values of objects x and y to 5 and 6 respectively and I want to swap the value stored in the objects i.e x.intValue() should be 6 and y.intValue() should be 5. Please help.</p>

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

        System.out.println(In1.a);
        Integer x = new Integer(5);
        Integer y = new Integer(6);
        System.out.println(x.equals(y));
        System.out.println(x.intValue());

    }
}
</code>```

答:
Adding a different answer without using a temporary variable </p>

```<code>Integer x = 10;
Integer y = 5;
x = x + y;
y = x - y;  //y contains 10
x = x - y;  //x contains 5

</code>```

Body:
How to change value of a an object of Integer class ex: here I have declared the values of objects x and y to 5 and 6 respectively and I want to swap the value stored in the objects i.e x.intValue() should be 6 and y.intValue() should be 5. Please help.

class second{
    public static void main(String[] args) {

        System.out.println(In1.a);
        Integer x = new Integer(5);
        Integer y = new Integer(6);
        System.out.println(x.equals(y));
        System.out.println(x.intValue());

    }
}

Body:
Adding a different answer without using a temporary variable

Integer x = 10;
Integer y = 5;
x = x + y;
y = x - y;  //y contains 10
x = x - y;  //x contains 5


问:
Check single elements in a list of dictionaries with python
You have a list of dictionaries like this one:

```<code>groups = {"1":["Susanne", "Laura", "Anna"],
    "2":["Kim", "Lisa", "Kevin"];
    "3": ["Donald", "Hans", "Jack"],
    }
</code>```

How can u check the single elements, like for example: How many of the names are starting with an "A"
I tried everything, but I always get errors...

答:
You can flatten the inner lists and take check how many satisfy the condition in a list comnprehension:

```<code>sum(i.startswith('A') for i in [s for l in groups.values() for s in l])
# 1
</code>```

The above would be equivalent to the following for loop:

```<code>c = 0
for l in groups.values():
    for s in l:
           if s.startswith('A'):
                c += 1
</code>```

Body:
You have a list of dictionaries like this one:

groups = {"1":["Susanne", "Laura", "Anna"],
    "2":["Kim", "Lisa", "Kevin"];
    "3": ["Donald", "Hans", "Jack"],
    }

How can u check the single elements, like for example: How many of the names are starting with an "A"
I tried everything, but I always get errors...

Body:
You can flatten the inner lists and take check how many satisfy the condition in a list comnprehension:

sum(i.startswith('A') for i in [s for l in groups.values() for s in l])
# 1

The above would be equivalent to the following for loop:

c = 0
for l in groups.values():
    for s in l:
           if s.startswith('A'):
                c += 1


问:
Removing or adding the empty word from a DFA

The title is my interpretation of this question. Below is what I have attempted so far:

Case 1: Ɛ ∈ L(M)

L(M1) = L(M)

L(M2) = {Q2, Σ2, q20, F2, 2}

Q={q0, ... , qi}

Q2={q20, ... , q2i+1}

Σ2 = Σ

q2i+1 ∈ F2 iff qi ∈ F

2(q2i+1, a) = (qi, a)

Case 2: Ɛ ∉ L(M)

L(M2) = L(M)

L(M1) = {Q1, Σ1, q10, F1, 1}

...

答:
What you have so far looks good but incomplete. Here's a description of what's left; writing it out in symbols is left as an exercise.

In the first case, if the language already contains the empty string, we're done and can use the automaton for the language directly with no modification. If it does not contain the empty string already, we can add a new initial state and have it transition like the original initial state. If we leave all other transitions alone and make this new initial state accepting, we will accept the empty string as well as anything the original automaton accepted.

In the second case, if the language does not already contain the empty string, we're done and can use the automaton for the language directly with no modification. If it does contain the empty string already, we can add a new initial state and have it transition like the original initial state. If we leave all other transitions alone and don't make this new initial state accepting, we will not accept the empty string but will continue to accept everything else.

This is the best that can be done, in general. However, specific languages might have smaller automata than these constructed after adding or removing the empty string. For instance, the language consisting of only the empty string has a DFA with two states, but a minimal DFA for that language with the empty string removed has one state. Similarly, the language of all non-empty strings has a DFA with two states, but adding the empty string to that language means there's a one-state DFA for that language. So this construction does not always give the smallest DFA possible, but it is guaranteed to work for all cases, including those where there is no smaller DFA for the language (e.g., adding the empty string to the empty language forces the addition of a new state).


问:
SVN Could not open password file
I installed VisualSVN Server and added 1 Repo as a test. When I try to Checkout on my local machine I get this error

```<code>Command: Checkout from ..../svn/testtt/trunk, revision HEAD, Fully recursive, Externals included
Error: Unable to connect to a repository at URL
Error:  '.../svn/testtt/trunk'
Error: Unexpected server error 500 'Internal Server Error' on '/svn/testtt/trunk'
</code>```

When I opened the log file I found this error

```<code>AH01620: Could not open password file: .../Repo/htpasswd
(OS 5) Access is denied.
[client 53.248.242.196]
</code>```

Although the htpasswd contains the user I've created.

答:
The error is Access is denied., and it means that the account that runs the VisualSVNServer service (HTTP service) does not have permissions to the htpasswd file.

By default, VisualSVN Server services run under Network Service account, so you should ensure that it has all the necessary permissions to read and modify your repositories folder. See the article KB37: Permissions required to run VisualSVN Server for general information on the required permission configuration.

Title: SVN Could not open password file

Body:
I installed VisualSVN Server and added 1 Repo as a test. When I try to Checkout on my local machine I get this error

Command: Checkout from ..../svn/testtt/trunk, revision HEAD, Fully recursive, Externals included
Error: Unable to connect to a repository at URL
Error:  '.../svn/testtt/trunk'
Error: Unexpected server error 500 'Internal Server Error' on '/svn/testtt/trunk'

When I opened the log file I found this error

AH01620: Could not open password file: .../Repo/htpasswd
(OS 5) Access is denied.
[client 53.248.242.196]

Although the htpasswd contains the user I've created.


问:
How can I fail on first syntax error in a python ANTLR generated parser while keeping the error message?
I'm using the antlr.error.ErrorStrategy.BailErrorStrategy for my parser. Sometimes (depending on the input) it will report a human readable version of the syntax error (like line 2:3: mismatched input XXX expecting YYY) and sometimes it won't (just an exception with no line 2:3:  some message):

```<code>import pytest
import json
import sys
from antlr4 import *
from antlr4.error.ErrorStrategy import DefaultErrorStrategy, BailErrorStrategy

from sqliteparser.SQLiteLexer import SQLiteLexer
from sqliteparser.SQLiteParser import SQLiteParser

def test_create_table():
    input_stream = InputStream("\nCREATE OR REPLACE VIEW APPDELETIONS as (\n")
    lexer = SQLiteLexer(input_stream)
    def recover(self,re):
        raise re
    lexer.recover = recover
    stream = CommonTokenStream(lexer)
    parser = SQLiteParser(stream)
    parser._errHandler = BailErrorStrategy()
    tree = parser.parse()
</code>```

Is there a way to get the an error strategy that always reports a textual representation of the  syntax error?

答:
It's possible to subclass BailErrorStrategy and call reportError:

```<code>class MyErrorStrategy(BailErrorStrategy):
    def recover(self, recognizer:Parser, e:RecognitionException):
        recognizer._errHandler.reportError(recognizer,e)
        super().recover(recognizer,e)
</code>```

then simply call parser._errHandler = MyErrorStrategy().

This will ensure that the actual syntax error (e.g. line 2:18 mismatched input 'VIEW' expecting K_TABLE)  will be printed to the console. You can add other error listeners via parser.addErrorListener(...).

Body:
I'm using the antlr.error.ErrorStrategy.BailErrorStrategy for my parser. Sometimes (depending on the input) it will report a human readable version of the syntax error (like line 2:3: mismatched input XXX expecting YYY) and sometimes it won't (just an exception with no line 2:3:  some message):

import pytest
import json
import sys
from antlr4 import *
from antlr4.error.ErrorStrategy import DefaultErrorStrategy, BailErrorStrategy

from sqliteparser.SQLiteLexer import SQLiteLexer
from sqliteparser.SQLiteParser import SQLiteParser

def test_create_table():
    input_stream = InputStream("\nCREATE OR REPLACE VIEW APPDELETIONS as (\n")
    lexer = SQLiteLexer(input_stream)
    def recover(self,re):
        raise re
    lexer.recover = recover
    stream = CommonTokenStream(lexer)
    parser = SQLiteParser(stream)
    parser._errHandler = BailErrorStrategy()
    tree = parser.parse()

Is there a way to get the an error strategy that always reports a textual representation of the  syntax error?

Body:
It's possible to subclass BailErrorStrategy and call reportError:

class MyErrorStrategy(BailErrorStrategy):
    def recover(self, recognizer:Parser, e:RecognitionException):
        recognizer._errHandler.reportError(recognizer,e)
        super().recover(recognizer,e)

then simply call parser._errHandler = MyErrorStrategy().

This will ensure that the actual syntax error (e.g. line 2:18 mismatched input 'VIEW' expecting K_TABLE)  will be printed to the console. You can add other error listeners via parser.addErrorListener(...).


答:
You can use a third variable.</p>

```<code>public static void main(String[] args){
    Integer a = new Integer(6);
    Integer b = new Integer(3);
    Integer temp = a;
    a = b;
    b = temp;
}
</code>```

Title: Changing value of a an object of Integer class

Body:
You can use a third variable.

public static void main(String[] args){
    Integer a = new Integer(6);
    Integer b = new Integer(3);
    Integer temp = a;
    a = b;
    b = temp;
}


问:
Node JS POST request returning undefined body
Quite new to Node JS and I am trying to post to a specific URL and retrieve the data.

I am using postman to do this but every time I post to it the response data is undefined but the status code is 200.

I have added body-parse as suggested but still no joy.

I will post my server code and request below.

```<code>const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const port = process.env.PORT || 5000;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/api/hello', (req, res) => {
    res.send({ express: 'Hello From Express' });
});

app.post('/api/save-json', (req, res) => {
    console.log(req);
    res.send(
        `I received your POST request. This is what you sent me: ${req.body.json}`,
    );
});

app.listen(port, () => console.log(`Listening on port ${port}`));

</code>```

My postman request is:

```<code>{
    "body" :
    {
        "json": "some data"
    }
}
</code>```

Any ideas?

答: body is the property in the req object containing the HTTP request body (which is set by body-parser), since you're sending in an object called body you'll need to access it like this: req.body.body.json

Body:
Quite new to Node JS and I am trying to post to a specific URL and retrieve the data.

I am using postman to do this but every time I post to it the response data is undefined but the status code is 200.

I have added body-parse as suggested but still no joy.

I will post my server code and request below.

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const port = process.env.PORT || 5000;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/api/hello', (req, res) => {
    res.send({ express: 'Hello From Express' });
});

app.post('/api/save-json', (req, res) => {
    console.log(req);
    res.send(
        `I received your POST request. This is what you sent me: ${req.body.json}`,
    );
});

app.listen(port, () => console.log(`Listening on port ${port}`));

My postman request is:

{
    "body" :
    {
        "json": "some data"
    }
}

Any ideas?


问:
Generate unique integer with 8 digits in java
I'm trying to figure how to approach with generating unique integer with 8 digits in java. The biggest problem is that it gives you a limited permutation, and also the clustered env. Any suggestion is welcome.

Regards

答:
If you only need a limited number of values, you could try Random:

```<code>byte[] rnd = new byte[1];
Random rndgen = new Random():

for(...) {
    rndgen.nexbytes(rnd);
    ...
}
</code>```

But as one byte can only hold 256 different values the collision risk if high.

If you have one single emitter, just use the natural sequence

```<code>boolean first = true;
byte i = 0;
for(;;) {
    if(i == 0) {
        if (first):
            first = false;
        }
        else {
            break;
        }
    }
    // use i
    ...
    i +== 1;
}
</code>```

If you have a limited number of emitters, give each a subrange. For example for 4 nodes, each node will have a sequence of 64 values.

On a more complex use case, the only possible way is to dedicate a master that will manage the sequence 0-255: each node asks it for next value.

Body:
If you only need a limited number of values, you could try Random:

byte[] rnd = new byte[1];
Random rndgen = new Random():

for(...) {
    rndgen.nexbytes(rnd);
    ...
}

But as one byte can only hold 256 different values the collision risk if high.

If you have one single emitter, just use the natural sequence

boolean first = true;
byte i = 0;
for(;;) {
    if(i == 0) {
        if (first):
            first = false;
        }
        else {
            break;
        }
    }
    // use i
    ...
    i +== 1;
}

If you have a limited number of emitters, give each a subrange. For example for 4 nodes, each node will have a sequence of 64 values.

On a more complex use case, the only possible way is to dedicate a master that will manage the sequence 0-255: each node asks it for next value.


问:
Warning: Failed prop type: The prop `leads` is marked as required in `Leads`, but its value is `undefined`
I am trying this tutorial to display information into my table using React and Redux, but I keep on getting this error:

Warning: Failed prop type: The prop leads is marked as required in
  Leads, but its value is undefined   Uncaught Type Error: Cannot
  read property 'map' of undefined Leads.js:52

My code:

```<code>import React, { Component, Fragment } from "react";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import { getLeads } from "../../actions/leads";

export class Leads extends Component {

  static propTypes = {
    leads: PropTypes.array.isRequired,
  };

  componentDidMount() {
    this.props.getLeads();
  }

  render() {
    return (
      <Fragment>
        <h2>Leads</h2>
        <table className="table table-striped">
          <thead>
            <tr>
              <th>ID</th>
              <th>Name</th>
              <th>Email</th>
              <th>Message</th>
              <th />
            </tr>
          </thead>
          <tbody>
            {this.props.leads.map(lead => (
              <tr key={lead.id}>
                <td>{lead.id}</td>
                <td>{lead.name}</td>
                <td>{lead.email}</td>
                <td>{lead.message}</td>
                <td><button className="btn btn-danger btn-sm">Delete</button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Fragment>
    );
  }
}

const mapStateToProps = state => ({
  leads: state.leads.leads
});

export default connect(
  mapStateToProps,
  { getLeads }
)(Leads);
</code>```

What am I doing wrong?

答:
The issue is that you required the Prop leads

```<code>static propTypes = {
    leads: PropTypes.array.isRequired,
};
</code>```

You should pass a prop when it is called as so

```<code><Leads lead={[]} />
</code>```

or change the static propTypes by removing the isRequired as so

```<code> static propTypes = {
        leads: PropTypes.array,
    };
</code>```

Body:
I am trying this tutorial to display information into my table using React and Redux, but I keep on getting this error:

Warning: Failed prop type: The prop leads is marked as required in
  Leads, but its value is undefined   Uncaught Type Error: Cannot
  read property 'map' of undefined Leads.js:52

My code:

import React, { Component, Fragment } from "react";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import { getLeads } from "../../actions/leads";

export class Leads extends Component {

  static propTypes = {
    leads: PropTypes.array.isRequired,
  };

  componentDidMount() {
    this.props.getLeads();
  }

  render() {
    return (
      <Fragment>

Leads

              ID
              Name
              Email
              Message

            {this.props.leads.map(lead => (

                {lead.id}
                {lead.name}
                {lead.email}
                {lead.message}
                <button className="btn btn-danger btn-sm">Delete</button>

            ))}

      </Fragment>
    );
  }
}

const mapStateToProps = state => ({
  leads: state.leads.leads
});

export default connect(
  mapStateToProps,
  { getLeads }
)(Leads);

What am I doing wrong?

Body:
The issue is that you required the Prop leads

static propTypes = {
    leads: PropTypes.array.isRequired,
};

You should pass a prop when it is called as so

<Leads lead={[]} />

or change the static propTypes by removing the isRequired as so

 static propTypes = {
        leads: PropTypes.array,
    };


问:
iPhone event in "inactive" view firing
I'm pretty new to iPhone development.  I have my "root" view and it is implementing

```<code>- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
</code>```

This implementation is working just fine.  After a user pushes a button, I do a pushViewController to push a new view onto the stack.  If the user shakes the iPhone, the accelerometer fires even though the currently "popped" view is not implementing any accelerometer related methods.  It appears to me that the root view is still active even though a different view has been pushed onto the stack.  Why is a view that's not the active view still responding to accelerometer?

Thanks

Tom

答:
Actually the root view controller is not inactive in this case. It's just not visible. It is still alive and can receive events.

In your accelerometer delegate, have a flag to check if the root view is visible. Do any operations only if the root view is visible.

```<code>if (visible) {

    // Do operations
}
</code>```

Title: iPhone event in "inactive" view firing

Body:
I'm pretty new to iPhone development.  I have my "root" view and it is implementing

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration

This implementation is working just fine.  After a user pushes a button, I do a pushViewController to push a new view onto the stack.  If the user shakes the iPhone, the accelerometer fires even though the currently "popped" view is not implementing any accelerometer related methods.  It appears to me that the root view is still active even though a different view has been pushed onto the stack.  Why is a view that's not the active view still responding to accelerometer?

Thanks

Tom

Body:
Actually the root view controller is not inactive in this case. It's just not visible. It is still alive and can receive events.

In your accelerometer delegate, have a flag to check if the root view is visible. Do any operations only if the root view is visible.

if (visible) {

    // Do operations
}


问:
C# 8 Non-Null Reference Types for Database models with foreign key
I'am trying to implement non-null-reference-types in my project https://dev.to/integerman/safer-code-with-c-8-non-null-reference-types-4f2c. I like it, but have a question regarding database models and constraints.

Is there a way to say that value X is never NULL because it's not nullable in the database?

For example:

```<code>public class Person
{
      public int Id { get; set; };

      public string Name { get; set; } = "No name set";

      public IEnumerable<Dog> Dogs { get; set; } = new List<Dog>();
}
</code>```

Person.Name is nullable=false in the database. Is there a way I can say that this property is never null? Now I have to set a default value.

```<code>public class Dog
{
    public int Id { get; set; }

    public string Name { get; set; } = "Noname";

    public int PersonId {get; set; }

    public Person Person { get; set; }
}
</code>```

Here I wonder the same about Person from Dog. This is a foreign key constraint in the database, A Dog can't exist without an Person(owner). Is there a way to say that; I know that this value is never null trust me or something like that ?

[Update]

Is there a way to say that value X is never NULL because it's not nullable in the database?

Yes, see Pavel Anikhouski answer

Should you do it:

No, see TomTom s answer

The best solution I think is @canton7 last comment. He links to this; https://learn.microsoft.com/en-us/ef/core/miscellaneous/nullable-reference-types#non-nullable-properties-and-initialization

Another reason:

```<code>public IEnumerable<Dog> Dogs { get; set; } = new List<Dog>();
</code>```

If you are trying to get a Person like this:

```<code>var person = _dbcontext.persons.Single(x => x.Name == "John").ToList();
Console.log($"John has {person.Dogs.Count} dogs")
</code>```

This will output 0 everytime, because we forgot to .Include(x => x.dogs).
So it's wrong.

答:
No, and it makes no sense. Particularly in the area of database entities - you MUST allow null because otherwise you can not load the object without automatically loading the related object. Which ultimately will force you to load a lot of data that you may not want for a simple query.

Dogs CAN exist without Person. Not on db level, but I can ask for a list of all dogs and not be interested in the owners at this point.

Body:
I'am trying to implement non-null-reference-types in my project https://dev.to/integerman/safer-code-with-c-8-non-null-reference-types-4f2c. I like it, but have a question regarding database models and constraints.

Is there a way to say that value X is never NULL because it's not nullable in the database?

For example:

public class Person
{
      public int Id { get; set; };

      public string Name { get; set; } = "No name set";

      public IEnumerable<Dog> Dogs { get; set; } = new List<Dog>();
}

Person.Name is nullable=false in the database. Is there a way I can say that this property is never null? Now I have to set a default value.

public class Dog
{
    public int Id { get; set; }

    public string Name { get; set; } = "Noname";

    public int PersonId {get; set; }

    public Person Person { get; set; }
}

Here I wonder the same about Person from Dog. This is a foreign key constraint in the database, A Dog can't exist without an Person(owner). Is there a way to say that; I know that this value is never null trust me or something like that ?

[Update]

Is there a way to say that value X is never NULL because it's not nullable in the database?

Yes, see Pavel Anikhouski answer

Should you do it:

No, see TomTom s answer

The best solution I think is @canton7 last comment. He links to this; https://learn.microsoft.com/en-us/ef/core/miscellaneous/nullable-reference-types#non-nullable-properties-and-initialization

Another reason:

public IEnumerable<Dog> Dogs { get; set; } = new List<Dog>();

If you are trying to get a Person like this:

var person = _dbcontext.persons.Single(x => x.Name == "John").ToList();
Console.log($"John has {person.Dogs.Count} dogs")

This will output 0 everytime, because we forgot to .Include(x => x.dogs).
So it's wrong.


答:
You can use null forgiving operator ! for that

public Person Person { get; set; } = default!;
```

As it pointed in comments, you should carefully use it, since it works with any type (value or reference one) and you can use null! as well

Title: C# 8 Non-Null Reference Types for Database models with foreign key

Body:
You can use null forgiving operator ! for that

public Person Person { get; set; } = default!;

As it pointed in comments, you should carefully use it, since it works with any type (value or reference one) and you can use null! as well