问:
Enabling Role-Based Access Control Using XACML - Error occurred while evaluating the policy
I followed the Enabling Role-Based Access Control Using XACML. I could setup all with out any issue. But when invoking the API it responds with below error.

```<code><am:fault xmlns:am="http://wso2.org/apimanager"><am:code>0</am:code><am:type>Status report</am:type><am:message>Runtime Error</am:message><am:description>Error occurred while evaluating the policy</am:description></am:fault>
</code>```

And in the APIM log I can see the below error. I'm running the APIM 2.6 and IS 5.3 in the same machine with offset of 2 in AM. It seems the issue is with the remoteServiceUrl="https://127.0.0.1:9443/services" url in EntitlementMediator.xml mentioned in the step 14 of the Given Guide.

[2019-05-28 12:33:05,162]  INFO - HTTPSender Unable to sendViaPost to
  url[https://127.0.0.1:9443/services/EntitlementService]
  javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated  at
  sun.security.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:431)
    at
  org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.verifyHostName(SSLProtocolSocketFactory.java:276)
    at
  org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.createSocket(SSLProtocolSocketFactory.java:186)
    at
  org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707)
    at
  org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.open(MultiThreadedHttpConnectionManager.java:1361)
    at
  org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387)
    at
  org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
    at
  org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
    at
  org.apache.axis2.transport.http.AbstractHTTPSender.executeMethod(AbstractHTTPSender.java:704)
    at
  org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:199)
    at
  org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:81)
    at
  org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:459)
    at
  org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:286)
    at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:442)     at
  org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:441)
    at
  org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:227)
    at
  org.apache.axis2.client.OperationClient.execute(OperationClient.java:149)
    at
  org.wso2.carbon.identity.entitlement.stub.EntitlementServiceStub.getDecision(EntitlementServiceStub.java:836)
    at
  org.wso2.carbon.identity.entitlement.proxy.soap.basicAuth.BasicAuthEntitlementServiceClient.getDecision(BasicAuthEntitlementServiceClient.java:259)
    at
  org.wso2.carbon.identity.entitlement.proxy.soap.basicAuth.BasicAuthEntitlementServiceClient.getDecision(BasicAuthEntitlementServiceClient.java:123)
    at
  org.wso2.carbon.identity.entitlement.proxy.PEPProxy.getDecision(PEPProxy.java:94)
    at
  org.wso2.carbon.identity.entitlement.proxy.PEPProxy.getDecision(PEPProxy.java:66)
    at
  org.wso2.carbon.identity.entitlement.mediator.EntitlementMediator.mediate(EntitlementMediator.java:203)
    at
  org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:108)
    at
  org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:70)
    at
  org.apache.synapse.mediators.base.SequenceMediator.mediate(SequenceMediator.java:158)
    at
  org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler.mediate(APIManagerExtensionHandler.java:66)
    at
  org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler.handleRequest(APIManagerExtensionHandler.java:75)
    at org.apache.synapse.rest.API.process(API.java:325)    at
  org.apache.synapse.rest.RESTRequestHandler.apiProcessNonDefaultStrategy(RESTRequestHandler.java:149)
    at
  org.apache.synapse.rest.RESTRequestHandler.dispatchToAPI(RESTRequestHandler.java:95)
    at
  org.apache.synapse.rest.RESTRequestHandler.process(RESTRequestHandler.java:71)
    at
  org.apache.synapse.core.axis2.Axis2SynapseEnvironment.injectMessage(Axis2SynapseEnvironment.java:303)
    at
  org.apache.synapse.core.axis2.SynapseMessageReceiver.receive(SynapseMessageReceiver.java:92)
    at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180)
    at
  org.apache.synapse.transport.passthru.ServerWorker.processNonEntityEnclosingRESTHandler(ServerWorker.java:337)
    at
  org.apache.synapse.transport.passthru.ServerWorker.run(ServerWorker.java:158)
    at
  org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745) [2019-05-28 12:33:05,164]
  ERROR - EntitlementMediator Error occurred while evaluating the policy
  org.apache.axis2.AxisFault: peer not authenticated    at
  org.apache.axis2.AxisFault.makeFault(AxisFault.java:430)  at
  org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:203)
    at
  org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:81)
    at
  org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:459)
    at
  org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:286)
    at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:442)     at
  org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:441)
    at
  org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:227)
    at
  org.apache.axis2.client.OperationClient.execute(OperationClient.java:149)
    at
  org.wso2.carbon.identity.entitlement.stub.EntitlementServiceStub.getDecision(EntitlementServiceStub.java:836)
    at
  org.wso2.carbon.identity.entitlement.proxy.soap.basicAuth.BasicAuthEntitlementServiceClient.getDecision(BasicAuthEntitlementServiceClient.java:259)
    at
  org.wso2.carbon.identity.entitlement.proxy.soap.basicAuth.BasicAuthEntitlementServiceClient.getDecision(BasicAuthEntitlementServiceClient.java:123)
    at
  org.wso2.carbon.identity.entitlement.proxy.PEPProxy.getDecision(PEPProxy.java:94)
    at
  org.wso2.carbon.identity.entitlement.proxy.PEPProxy.getDecision(PEPProxy.java:66)
    at
  org.wso2.carbon.identity.entitlement.mediator.EntitlementMediator.mediate(EntitlementMediator.java:203)
    at
  org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:108)
    at
  org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:70)
    at
  org.apache.synapse.mediators.base.SequenceMediator.mediate(SequenceMediator.java:158)
    at
  org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler.mediate(APIManagerExtensionHandler.java:66)
    at
  org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler.handleRequest(APIManagerExtensionHandler.java:75)
    at org.apache.synapse.rest.API.process(API.java:325)    at
  org.apache.synapse.rest.RESTRequestHandler.apiProcessNonDefaultStrategy(RESTRequestHandler.java:149)
    at
  org.apache.synapse.rest.RESTRequestHandler.dispatchToAPI(RESTRequestHandler.java:95)
    at
  org.apache.synapse.rest.RESTRequestHandler.process(RESTRequestHandler.java:71)
    at
  org.apache.synapse.core.axis2.Axis2SynapseEnvironment.injectMessage(Axis2SynapseEnvironment.java:303)
    at
  org.apache.synapse.core.axis2.SynapseMessageReceiver.receive(SynapseMessageReceiver.java:92)
    at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180)
    at
  org.apache.synapse.transport.passthru.ServerWorker.processNonEntityEnclosingRESTHandler(ServerWorker.java:337)
    at
  org.apache.synapse.transport.passthru.ServerWorker.run(ServerWorker.java:158)
    at
  org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745) Caused by:
  javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated  at
  sun.security.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:431)
    at
  org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.verifyHostName(SSLProtocolSocketFactory.java:276)
    at
  org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.createSocket(SSLProtocolSocketFactory.java:186)
    at
  org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707)
    at
  org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.open(MultiThreadedHttpConnectionManager.java:1361)
    at
  org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387)
    at
  org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
    at
  org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
    at
  org.apache.axis2.transport.http.AbstractHTTPSender.executeMethod(AbstractHTTPSender.java:704)
    at
  org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:199)
    ... 31 more [2019-05-28 12:33:05,172]  INFO - LogMediator STATUS =
  Executing default 'fault' sequence, ERROR_CODE = 0, ERROR_MESSAGE =
  Error occurred while evaluating the policy

答:
There is a host name verification issue when entitlement mediator try to invoke EntitlementService exposed by WSO2 IS.

You need to correctly export public cert from APIM and import to WSO2 IS trust store. In public cert CN value should be equal to hostname or IP address.

As I can remember primary key store key length is different in APIM 2.6.0 and IS 5.3.0. However above step should resolve your issue.

Further more this should work out of the box if you have used later version of WSO2 IS than 5.3.0 with default host names and default public certs.

Body:
I followed the Enabling Role-Based Access Control Using XACML. I could setup all with out any issue. But when invoking the API it responds with below error.

<am:fault xmlns:am="http://wso2.org/apimanager"><am:code>0</am:code><am:type>Status report</am:type><am:message>Runtime Error</am:message><am:description>Error occurred while evaluating the policy</am:description></am:fault>

And in the APIM log I can see the below error. I'm running the APIM 2.6 and IS 5.3 in the same machine with offset of 2 in AM. It seems the issue is with the remoteServiceUrl="https://127.0.0.1:9443/services" url in EntitlementMediator.xml mentioned in the step 14 of the Given Guide.

[2019-05-28 12:33:05,162]  INFO - HTTPSender Unable to sendViaPost to
  url[https://127.0.0.1:9443/services/EntitlementService]
  javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated  at
  sun.security.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:431)
    at
  org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.verifyHostName(SSLProtocolSocketFactory.java:276)
    at
  org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.createSocket(SSLProtocolSocketFactory.java:186)
    at
  org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707)
    at
  org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.open(MultiThreadedHttpConnectionManager.java:1361)
    at
  org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387)
    at
  org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
    at
  org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
    at
  org.apache.axis2.transport.http.AbstractHTTPSender.executeMethod(AbstractHTTPSender.java:704)
    at
  org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:199)
    at
  org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:81)
    at
  org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:459)
    at
  org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:286)
    at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:442)     at
  org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:441)
    at
  org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:227)
    at
  org.apache.axis2.client.OperationClient.execute(OperationClient.java:149)
    at
  org.wso2.carbon.identity.entitlement.stub.EntitlementServiceStub.getDecision(EntitlementServiceStub.java:836)
    at
  org.wso2.carbon.identity.entitlement.proxy.soap.basicAuth.BasicAuthEntitlementServiceClient.getDecision(BasicAuthEntitlementServiceClient.java:259)
    at
  org.wso2.carbon.identity.entitlement.proxy.soap.basicAuth.BasicAuthEntitlementServiceClient.getDecision(BasicAuthEntitlementServiceClient.java:123)
    at
  org.wso2.carbon.identity.entitlement.proxy.PEPProxy.getDecision(PEPProxy.java:94)
    at
  org.wso2.carbon.identity.entitlement.proxy.PEPProxy.getDecision(PEPProxy.java:66)
    at
  org.wso2.carbon.identity.entitlement.mediator.EntitlementMediator.mediate(EntitlementMediator.java:203)
    at
  org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:108)
    at
  org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:70)
    at
  org.apache.synapse.mediators.base.SequenceMediator.mediate(SequenceMediator.java:158)
    at
  org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler.mediate(APIManagerExtensionHandler.java:66)
    at
  org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler.handleRequest(APIManagerExtensionHandler.java:75)
    at org.apache.synapse.rest.API.process(API.java:325)    at
  org.apache.synapse.rest.RESTRequestHandler.apiProcessNonDefaultStrategy(RESTRequestHandler.java:149)
    at
  org.apache.synapse.rest.RESTRequestHandler.dispatchToAPI(RESTRequestHandler.java:95)
    at
  org.apache.synapse.rest.RESTRequestHandler.process(RESTRequestHandler.java:71)
    at
  org.apache.synapse.core.axis2.Axis2SynapseEnvironment.injectMessage(Axis2SynapseEnvironment.java:303)
    at
  org.apache.synapse.core.axis2.SynapseMessageReceiver.receive(SynapseMessageReceiver.java:92)
    at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180)
    at
  org.apache.synapse.transport.passthru.ServerWorker.processNonEntityEnclosingRESTHandler(ServerWorker.java:337)
    at
  org.apache.synapse.transport.passthru.ServerWorker.run(ServerWorker.java:158)
    at
  org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745) [2019-05-28 12:33:05,164]
  ERROR - EntitlementMediator Error occurred while evaluating the policy
  org.apache.axis2.AxisFault: peer not authenticated    at
  org.apache.axis2.AxisFault.makeFault(AxisFault.java:430)  at
  org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:203)
    at
  org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:81)
    at
  org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:459)
    at
  org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:286)
    at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:442)     at
  org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:441)
    at
  org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:227)
    at
  org.apache.axis2.client.OperationClient.execute(OperationClient.java:149)
    at
  org.wso2.carbon.identity.entitlement.stub.EntitlementServiceStub.getDecision(EntitlementServiceStub.java:836)
    at
  org.wso2.carbon.identity.entitlement.proxy.soap.basicAuth.BasicAuthEntitlementServiceClient.getDecision(BasicAuthEntitlementServiceClient.java:259)
    at
  org.wso2.carbon.identity.entitlement.proxy.soap.basicAuth.BasicAuthEntitlementServiceClient.getDecision(BasicAuthEntitlementServiceClient.java:123)
    at
  org.wso2.carbon.identity.entitlement.proxy.PEPProxy.getDecision(PEPProxy.java:94)
    at
  org.wso2.carbon.identity.entitlement.proxy.PEPProxy.getDecision(PEPProxy.java:66)
    at
  org.wso2.carbon.identity.entitlement.mediator.EntitlementMediator.mediate(EntitlementMediator.java:203)
    at
  org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:108)
    at
  org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:70)
    at
  org.apache.synapse.mediators.base.SequenceMediator.mediate(SequenceMediator.java:158)
    at
  org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler.mediate(APIManagerExtensionHandler.java:66)
    at
  org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler.handleRequest(APIManagerExtensionHandler.java:75)
    at org.apache.synapse.rest.API.process(API.java:325)    at
  org.apache.synapse.rest.RESTRequestHandler.apiProcessNonDefaultStrategy(RESTRequestHandler.java:149)
    at
  org.apache.synapse.rest.RESTRequestHandler.dispatchToAPI(RESTRequestHandler.java:95)
    at
  org.apache.synapse.rest.RESTRequestHandler.process(RESTRequestHandler.java:71)
    at
  org.apache.synapse.core.axis2.Axis2SynapseEnvironment.injectMessage(Axis2SynapseEnvironment.java:303)
    at
  org.apache.synapse.core.axis2.SynapseMessageReceiver.receive(SynapseMessageReceiver.java:92)
    at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180)
    at
  org.apache.synapse.transport.passthru.ServerWorker.processNonEntityEnclosingRESTHandler(ServerWorker.java:337)
    at
  org.apache.synapse.transport.passthru.ServerWorker.run(ServerWorker.java:158)
    at
  org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745) Caused by:
  javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated  at
  sun.security.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:431)
    at
  org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.verifyHostName(SSLProtocolSocketFactory.java:276)
    at
  org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.createSocket(SSLProtocolSocketFactory.java:186)
    at
  org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707)
    at
  org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.open(MultiThreadedHttpConnectionManager.java:1361)
    at
  org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387)
    at
  org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
    at
  org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
    at
  org.apache.axis2.transport.http.AbstractHTTPSender.executeMethod(AbstractHTTPSender.java:704)
    at
  org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:199)
    ... 31 more [2019-05-28 12:33:05,172]  INFO - LogMediator STATUS =
  Executing default 'fault' sequence, ERROR_CODE = 0, ERROR_MESSAGE =
  Error occurred while evaluating the policy


来源: stackexchange

问:
SQLZOO- using GROUPBY to find the largest country in a continent; is this possible?
I'm working on a practice problem from SQLZOO, and am not sure why the solution I'm trying doesn't work as it makes sense to me.

This is the format of the table::

```<code> -------------------------------------------------------------
|     name      continent    area    population       gdp     |
|-------------------------------------------------------------|
| Afghanistan     Asia      652230    25500100    20343000000 |
| .                                                           |
| .                                                           |
| .                                                           |
|                                                             |
 -------------------------------------------------------------
</code>```

The question is the following:

Find the largest country (by area) in each continent, show the continent, the name and the area.

Here is the way I was thinking to solve it:

```<code>SELECT continent, name, area
  FROM world
 WHERE name IN (SELECT continent, name, MAX(area)
                  FROM world
                 GROUP BY continent);
</code>```

I know this doesn't work, but why not? It seems like the nested SELECT statement is finding the country with the MAX area per continent, is it not?

The actual solution for this is something like follows:

```<code>SELECT continent, name, area
  FROM world x
 WHERE area >= ALL
    (SELECT area
       FROM world y
      WHERE y.continent=x.continent
        AND area>0)
</code>```

But this seems like a complicated way of coming up with it;; is this way makes the most sense? Any ideas are appreciated

Thank you in advance!!

答:
```<code>select A.continent, W.name, A.area
from
(select continent, max(area) as area from world group by continent)A, world W
where
A.continent = W.continent
and
A.area = W.area
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm working on a practice problem from SQLZOO, and am not sure why the solution I'm trying doesn't work as it makes sense to me.

This is the format of the table::

 -------------------------------------------------------------
|     name      continent    area    population       gdp     |
|-------------------------------------------------------------|
| Afghanistan     Asia      652230    25500100    20343000000 |
| .                                                           |
| .                                                           |
| .                                                           |
|                                                             |
 -------------------------------------------------------------

The question is the following:

Find the largest country (by area) in each continent, show the continent, the name and the area.

Here is the way I was thinking to solve it:

SELECT continent, name, area
  FROM world
 WHERE name IN (SELECT continent, name, MAX(area)
                  FROM world
                 GROUP BY continent);

I know this doesn't work, but why not? It seems like the nested SELECT statement is finding the country with the MAX area per continent, is it not?

The actual solution for this is something like follows:

SELECT continent, name, area
  FROM world x
 WHERE area >= ALL
    (SELECT area
       FROM world y
      WHERE y.continent=x.continent
        AND area>0)

But this seems like a complicated way of coming up with it;; is this way makes the most sense? Any ideas are appreciated

Thank you in advance!!


问:
E/SQLiteLog: (283) recovered frames from WAL file
I get an error every time I launch my application.

```<code>E/SQLiteLog: (283) recovered 22 frames from WAL file /data/data/com.dmitrysimakov.kilogram/databases/androidx.work.workdb-wal
</code>```

The application is working fine, but I want to know why this error occurs. databases/androidx.work.workdb-wal it is a Worker's journal. I use Worker to prepopulate my database.

```<code>Room.databaseBuilder(app, KilogramDb::class.java, "kilogram.db")
            .addCallback(object : RoomDatabase.Callback() {
                override fun onCreate(db: SupportSQLiteDatabase) {
                    super.onCreate(db)
                    val request = OneTimeWorkRequestBuilder<SeedDatabaseWorker>().build()
                    WorkManager.getInstance().enqueue(request)
                }
            })
            .fallbackToDestructiveMigration()
            .build()
</code>```

答:
I am using a bound service to connect to room database, so I use this code in my RoomService.onDestroy() method:

```<code>  @Override
  public final void
  onDestroy()
  {
    super
    .onDestroy();

    if(roomDatabase != null)
    {
      if(roomDatabase
         .isOpen())
      {
        roomDatabase
        .close();
      }
    }
  }
</code>```

If you create your RoomDatabase instance in your Application singleton or in your Activity, you may do the same thing there (in corresponding onDestroy() method).

For convenience here is the code I use in my MainActivity class to close database in bound service:

```<code>  @Override
  protected final void
  onDestroy()
  {
    super.onDestroy();

    if(isFinishing())
    {
      if(mainViewModel != null)
      {
        mainViewModel
        .onDestroy();
      }
    }
  }
</code>```

In MainViewModel.onDestroy() I send a message to bound service to close roomDatabase and then I unbind roomService:

```<code>  public final void
  onDestroy()
  {
    if(contextWeakReference != null)
    {
      final Context
      context =
      contextWeakReference
      .get();

      if(context != null)
      {
        if(roomServiceConnection != null)
        {
          if(boundToRoomService)
          {
            sendDBCloseMessageToRoomService();

            context
            .unbindService
            (roomServiceConnection);
          }
        }
      }
    }
  }

  private void
  sendDBCloseMessageToRoomService()
  {
    try
    {
      final Message message =
      Message.obtain
      (null, MSG_DB_CLOSE);

      if(message != null)
      {
        if(messengerToRoomService != null)
        {
          messengerToRoomService
          .send(message);
        }
      }
    }
    catch(final RemoteException e)
    {
      e.printStackTrace();
    }
  }
</code>```

In RoomService I catch the message to close roomDatabase:

```<code>  public class RoomService
  extends Service
  {
    @NonNull @NonNls public static final
    String DATABASE_NAME = "room_database";

    public static final int MSG_DB_CLOSE = 108;

    @Nullable public RoomDatabase roomDatabase;

    private final IBinder roomBinder = new Binder();
    private WeakReference<Context> contextWeakReference;

    @Nullable public Messenger messengerFromRoomService;
    @Nullable public Messenger messengerToRoomService;

    private static class RoomServiceHandler
    extends Handler
    {
      @Nullable private final
      WeakReference<RoomService> roomServiceWeakReference;

      RoomServiceHandler
      (@Nullable final
       RoomService service)
      {
        if(service != null)
        {
          roomServiceWeakReference =
          new WeakReference<RoomService>
          (service);
        }
        else
        {
          roomServiceWeakReference = null;
        }
      }

      @Override
      public final void
      handleMessage
      (@Nullable final
      Message message)
      {
        if(message != null)
        {
          final int what =
          message.what;

          switch(what)
          {
            case MSG_DB_CLOSE:
            {
              handleDBCloseMessage
              (message);
              break;
            }
          }
        }
      }

      private void
      handleDBCloseMessage
      (@Nullable final
       Message message)
      {
        if(message != null)
        {
          final RoomService
          service =
          roomServiceWeakReference
          .get();

          if(service != null)
          {
            if(service
               .roomDatabase != null)
            {
              if(service
                 .roomDatabase
                 .isOpen())
              {
                service
                .roomDatabase
                .close();
              }
            }
          }
        }
      }
    }

    @Override
    public final void
    onCreate()
    {
      super.onCreate();

      // initialize application context weak reference
      final Context
      applicationContext =
      getApplicationContext();

      if(applicationContext != null)
      {
        contextWeakReference =
        new WeakReference<Context>
        (applicationContext);

        // initialize database
        roomDatabase =
        Room
        .databaseBuilder
        (applicationContext,
        MyRoomDatabase.class,
        DATABASE_NAME)
        .build();

        if(roomDatabase != null)
        {
          // initialise your DAO here
          yourDao =
          roomDatabase
          .yourDao();
        }
      }

      final RoomServiceHandler
      roomServiceHandler =
      new RoomServiceHandler(this);

      if(roomServiceHandler != null)
      {
        messengerToRoomService =
        new Messenger(roomServiceHandler);
      }
    }

    @Nullable
    @Override
    public final IBinder
    onBind
    (@Nullable final
    Intent intent)
    {
      IBinder result = null;

      if(messengerToRoomService != null)
      {
        final IBinder
        roomBinder =
        messengerToRoomService
        .getBinder();

        if(roomBinder != null)
        {
          result = roomBinder;
        }
      }
      return result;
    }
  }
</code>```

Body:
I get an error every time I launch my application.

E/SQLiteLog: (283) recovered 22 frames from WAL file /data/data/com.dmitrysimakov.kilogram/databases/androidx.work.workdb-wal

The application is working fine, but I want to know why this error occurs. databases/androidx.work.workdb-wal it is a Worker's journal. I use Worker to prepopulate my database.

Room.databaseBuilder(app, KilogramDb::class.java, "kilogram.db")
            .addCallback(object : RoomDatabase.Callback() {
                override fun onCreate(db: SupportSQLiteDatabase) {
                    super.onCreate(db)
                    val request = OneTimeWorkRequestBuilder<SeedDatabaseWorker>().build()
                    WorkManager.getInstance().enqueue(request)
                }
            })
            .fallbackToDestructiveMigration()
            .build()

Body:
I am using a bound service to connect to room database, so I use this code in my RoomService.onDestroy() method:

  @Override
  public final void
  onDestroy()
  {
    super
    .onDestroy();

    if(roomDatabase != null)
    {
      if(roomDatabase
         .isOpen())
      {
        roomDatabase
        .close();
      }
    }
  }

If you create your RoomDatabase instance in your Application singleton or in your Activity, you may do the same thing there (in corresponding onDestroy() method).

For convenience here is the code I use in my MainActivity class to close database in bound service:

  @Override
  protected final void
  onDestroy()
  {
    super.onDestroy();

    if(isFinishing())
    {
      if(mainViewModel != null)
      {
        mainViewModel
        .onDestroy();
      }
    }
  }

In MainViewModel.onDestroy() I send a message to bound service to close roomDatabase and then I unbind roomService:

  public final void
  onDestroy()
  {
    if(contextWeakReference != null)
    {
      final Context
      context =
      contextWeakReference
      .get();

      if(context != null)
      {
        if(roomServiceConnection != null)
        {
          if(boundToRoomService)
          {
            sendDBCloseMessageToRoomService();

            context
            .unbindService
            (roomServiceConnection);
          }
        }
      }
    }
  }

  private void
  sendDBCloseMessageToRoomService()
  {
    try
    {
      final Message message =
      Message.obtain
      (null, MSG_DB_CLOSE);

      if(message != null)
      {
        if(messengerToRoomService != null)
        {
          messengerToRoomService
          .send(message);
        }
      }
    }
    catch(final RemoteException e)
    {
      e.printStackTrace();
    }
  }

In RoomService I catch the message to close roomDatabase:

  public class RoomService
  extends Service
  {
    @NonNull @NonNls public static final
    String DATABASE_NAME = "room_database";

    public static final int MSG_DB_CLOSE = 108;

    @Nullable public RoomDatabase roomDatabase;

    private final IBinder roomBinder = new Binder();
    private WeakReference<Context> contextWeakReference;

    @Nullable public Messenger messengerFromRoomService;
    @Nullable public Messenger messengerToRoomService;

    private static class RoomServiceHandler
    extends Handler
    {
      @Nullable private final
      WeakReference<RoomService> roomServiceWeakReference;

      RoomServiceHandler
      (@Nullable final
       RoomService service)
      {
        if(service != null)
        {
          roomServiceWeakReference =
          new WeakReference<RoomService>
          (service);
        }
        else
        {
          roomServiceWeakReference = null;
        }
      }

      @Override
      public final void
      handleMessage
      (@Nullable final
      Message message)
      {
        if(message != null)
        {
          final int what =
          message.what;

          switch(what)
          {
            case MSG_DB_CLOSE:
            {
              handleDBCloseMessage
              (message);
              break;
            }
          }
        }
      }

      private void
      handleDBCloseMessage
      (@Nullable final
       Message message)
      {
        if(message != null)
        {
          final RoomService
          service =
          roomServiceWeakReference
          .get();

          if(service != null)
          {
            if(service
               .roomDatabase != null)
            {
              if(service
                 .roomDatabase
                 .isOpen())
              {
                service
                .roomDatabase
                .close();
              }
            }
          }
        }
      }
    }

    @Override
    public final void
    onCreate()
    {
      super.onCreate();

      // initialize application context weak reference
      final Context
      applicationContext =
      getApplicationContext();

      if(applicationContext != null)
      {
        contextWeakReference =
        new WeakReference<Context>
        (applicationContext);

        // initialize database
        roomDatabase =
        Room
        .databaseBuilder
        (applicationContext,
        MyRoomDatabase.class,
        DATABASE_NAME)
        .build();

        if(roomDatabase != null)
        {
          // initialise your DAO here
          yourDao =
          roomDatabase
          .yourDao();
        }
      }

      final RoomServiceHandler
      roomServiceHandler =
      new RoomServiceHandler(this);

      if(roomServiceHandler != null)
      {
        messengerToRoomService =
        new Messenger(roomServiceHandler);
      }
    }

    @Nullable
    @Override
    public final IBinder
    onBind
    (@Nullable final
    Intent intent)
    {
      IBinder result = null;

      if(messengerToRoomService != null)
      {
        final IBinder
        roomBinder =
        messengerToRoomService
        .getBinder();

        if(roomBinder != null)
        {
          result = roomBinder;
        }
      }
      return result;
    }
  }


问:
How to clear the field after i set ComboBox value as null?
I have a ComboBox  called projectRequirementComboBox that is dependent from projectComboBox, from where I get the list to show in the dropdown in projectRequirementComboBox, but I want to do something like: when a user changes the project I want to empty projectRequirementComboBox, to be more clear none of the item will not be selected I am doing this right now but still my projectRequirementComboBox  has the old value, I don't know what am I missing .I am using vaadin.version 8.0.7 .

```<code>private void refreshProjectRequirementCombobox()
{
    List<ProjectRequirement> projectRequirements = new ArrayList<>();
    if (projectComboBox.getValue() != null)
    {
        projectRequirements = projectRequirementService.findCurrentProjectRequirements(projectComboBox.getValue().getProjectId());
    }
    projectRequirementComboBox.setItems(projectRequirements);
    projectRequirementComboBox.setValue(null);

}

private void loadProjectRequirement(Project project)
{
    List<ProjectRequirement> projectRequirements = new ArrayList<>();
    if (project != null)
    {
        projectRequirements = projectRequirementService.findCurrentProjectRequirements(project.getProjectId());
    }
    projectRequirementComboBox.setItems(projectRequirements);
}
</code>```

I call refreshProjectRequirementCombobox here.

```<code> projectComboBox.addValueChangeListener(event ->
            {
                refreshProjectRequirementCombobox();
                loadRejectReason();
            });
</code>```

答:
There is open issue in Vaadin  https://github.com/vaadin/framework/issues/9566 which refers to https://github.com/vaadin/framework/issues/2813

Going through the issue I found that by creating a custom combobox you can fix the issue:

```<code>public class ClearableComboBox<T> extends ComboBox<T> {
    public ClearableComboBox(String in) {
        super(in);
    }

    protected void setSelectedFromServer(T item) {
        String key = itemToKey(item);

        T oldSelection = getSelectedItem().orElse(getEmptyValue());
        doSetSelectedKey(key);

        fireEvent(new SingleSelectionEvent<>(ClearableComboBox.this, oldSelection, false));
    }
}
</code>```

Additionally, make sure to call setValue before calling setItems to clear items.

```<code>cmb.setValue(null);
cmb.setItems(aEmptyCollection);
</code>```

Body:
I have a ComboBox  called projectRequirementComboBox that is dependent from projectComboBox, from where I get the list to show in the dropdown in projectRequirementComboBox, but I want to do something like: when a user changes the project I want to empty projectRequirementComboBox, to be more clear none of the item will not be selected I am doing this right now but still my projectRequirementComboBox  has the old value, I don't know what am I missing .I am using vaadin.version 8.0.7 .

private void refreshProjectRequirementCombobox()
{
    List<ProjectRequirement> projectRequirements = new ArrayList<>();
    if (projectComboBox.getValue() != null)
    {
        projectRequirements = projectRequirementService.findCurrentProjectRequirements(projectComboBox.getValue().getProjectId());
    }
    projectRequirementComboBox.setItems(projectRequirements);
    projectRequirementComboBox.setValue(null);

}

private void loadProjectRequirement(Project project)
{
    List<ProjectRequirement> projectRequirements = new ArrayList<>();
    if (project != null)
    {
        projectRequirements = projectRequirementService.findCurrentProjectRequirements(project.getProjectId());
    }
    projectRequirementComboBox.setItems(projectRequirements);
}

I call refreshProjectRequirementCombobox here.

 projectComboBox.addValueChangeListener(event ->
            {
                refreshProjectRequirementCombobox();
                loadRejectReason();
            });

Body:
There is open issue in Vaadin  https://github.com/vaadin/framework/issues/9566 which refers to https://github.com/vaadin/framework/issues/2813

Going through the issue I found that by creating a custom combobox you can fix the issue:

public class ClearableComboBox<T> extends ComboBox<T> {
    public ClearableComboBox(String in) {
        super(in);
    }

    protected void setSelectedFromServer(T item) {
        String key = itemToKey(item);

        T oldSelection = getSelectedItem().orElse(getEmptyValue());
        doSetSelectedKey(key);

        fireEvent(new SingleSelectionEvent<>(ClearableComboBox.this, oldSelection, false));
    }
}

Additionally, make sure to call setValue before calling setItems to clear items.

cmb.setValue(null);
cmb.setItems(aEmptyCollection);


问:
Update Project version automatically in Maven 3.6.0
I am using Maven 3.6.0 in a project where the version of my project is set using a revision property as described in https://maven.apache.org/maven-ci-friendly.html and I want to automatically update the project's version in command line.

I tried to look on the side of maven release plugin (https://maven.apache.org/maven-release/maven-release-plugin/update-versions-mojo.html) using the release:update-versions command, which seems to work, but instead of updating the property revision it updates the version property.

Current setup :

    <version>${revision}</version>

    <properties>
        <revision>1.1-SNAPSHOT</revision>
    </properties>
```

<p>When running <code>mvn release:update-versions</code> :</p>

<pre class="lang-xml prettyprint-override"><code>    <version>1.2-SNAPSHOT</version>

    <properties>
        <revision>1.1-SNAPSHOT</revision>
    </properties>
</code>```

Expected:

    <version>${revision}</version>

    <properties>
        <revision>1.2-SNAPSHOT</revision>
    </properties>
```

答:
Finally, I achieved to get the same result by using maven versions plugin, but it's not using ${revision} tag.

mvn versions:set -DnextSnapshot=true

Versions plugin is much more flexible than release plugin for managing your project's version.

Body:
I am using Maven 3.6.0 in a project where the version of my project is set using a revision property as described in https://maven.apache.org/maven-ci-friendly.html and I want to automatically update the project's version in command line.

I tried to look on the side of maven release plugin (https://maven.apache.org/maven-release/maven-release-plugin/update-versions-mojo.html) using the release:update-versions command, which seems to work, but instead of updating the property revision it updates the version property.

Current setup :

    <version>${revision}</version>

    <properties>
        <revision>1.1-SNAPSHOT</revision>
    </properties>

When running mvn release:update-versions :

    <version>1.2-SNAPSHOT</version>

    <properties>
        <revision>1.1-SNAPSHOT</revision>
    </properties>

Expected:

    <version>${revision}</version>

    <properties>
        <revision>1.2-SNAPSHOT</revision>
    </properties>


问:
Why does OnCollisionEnter not get triggered?
I have got two objects:

Object A (SteamVR Camera):

Has a Rigidbody with "Is Kinematic" enabled.

Has a Box Collider with "Is Trigger" enabled.

Has the Script with the "OnCollisionEnter" method.

Object B (Globe model):

Has a Sphere Collider with "Is Trigger" enabled.

I made sure that the collider ranges are correctly, but somehow the OnCollisionEnter method does not get triggered.

The code that I am using for OnCollisionEnter looks like below:

```<code>private void OnCollisionEnter(Collision collision)
{
    Debug.Log("Collision entered");
}
</code>```

Could someone provide me some insight/advice?

Thanks in forward.

答:
ISSUE: there's no collision between any object with a Trigger

To understand how collision works you need first to identify which objects are colliding, because very few objects may trigger OnCollisionEnter.

From your description we can identify 2 types of objects.

Object A: Kinematic Rigidbody Trigger Collider

  Object B: Static Trigger Collider

If you check the Collision Matrix there could be no collision with anything that has a Trigger (both Object A and Object B), so OnCollisionEnter won't fire.

I repeat: a Trigger does not collide with anything no matter what the other object is.

SOLUTION: Use OnTriggerEnter instead of OnCollisionEnter

If you want to get the event from a collision with a trigger objects (or 2 of them, like in your case) you can use OnTriggerEnter.

Consider that in this case the parameter of the method will be Collider other that is a Collider instead of a Collision, but in your case I think you won't need the collision at all.

private void OnTriggerEnter(Collider other)
    => Debug.Log("entered");
```

INSIGHTS about Unity collisions

The collisions depend on the rigidbody and collider setup objects. I can show a few examples based on your situation.

The first element to consider is that Static Collider is not an usual Object set as Static (this was a source of confusion in the comments below).

From Unity Manual

STATIC COLLIDER

  This is a GameObject that has a Collider but no Rigidbody. Static
  colliders are used for level geometry which always stays at the same
  place and never moves around. Incoming rigidbody objects will collide
  with the static collider but will not move it.

Consider also that you want to use a trigger (that makes your STATIC COLLDER into a STATIC TRIGGER COLLIDER).

Basically the idea behind trigger is:
"Use triggers when you want to catch the event but you don't want the gameobject interacting with Physics forces."

Triggers

The scripting system can detect when collisions occur and initiate
  actions using the OnCollisionEnter function. However, you can also use
  the physics engine simply to detect when one collider enters the space
  of another without creating a collision. A collider configured as a
  Trigger (using the Is Trigger property) does not behave as a solid
  object and will simply allow other colliders to pass through. When a
  collider enters its space, a trigger will call the OnTriggerEnter
  function on the trigger object’s scripts

Body:
I have got two objects:

Object A (SteamVR Camera):

Has a Rigidbody with "Is Kinematic" enabled.

Has a Box Collider with "Is Trigger" enabled.

Has the Script with the "OnCollisionEnter" method.

Object B (Globe model):

Has a Sphere Collider with "Is Trigger" enabled.

I made sure that the collider ranges are correctly, but somehow the OnCollisionEnter method does not get triggered.

The code that I am using for OnCollisionEnter looks like below:

private void OnCollisionEnter(Collision collision)
{
    Debug.Log("Collision entered");
}

Could someone provide me some insight/advice?

Thanks in forward.

Body:
ISSUE: there's no collision between any object with a Trigger

To understand how collision works you need first to identify which objects are colliding, because very few objects may trigger OnCollisionEnter.

From your description we can identify 2 types of objects.

Object A: Kinematic Rigidbody Trigger Collider

  Object B: Static Trigger Collider

If you check the Collision Matrix there could be no collision with anything that has a Trigger (both Object A and Object B), so OnCollisionEnter won't fire.

I repeat: a Trigger does not collide with anything no matter what the other object is.

SOLUTION: Use OnTriggerEnter instead of OnCollisionEnter

If you want to get the event from a collision with a trigger objects (or 2 of them, like in your case) you can use OnTriggerEnter.

Consider that in this case the parameter of the method will be Collider other that is a Collider instead of a Collision, but in your case I think you won't need the collision at all.

private void OnTriggerEnter(Collider other)
    => Debug.Log("entered");

INSIGHTS about Unity collisions

The collisions depend on the rigidbody and collider setup objects. I can show a few examples based on your situation.

The first element to consider is that Static Collider is not an usual Object set as Static (this was a source of confusion in the comments below).

From Unity Manual

STATIC COLLIDER

  This is a GameObject that has a Collider but no Rigidbody. Static
  colliders are used for level geometry which always stays at the same
  place and never moves around. Incoming rigidbody objects will collide
  with the static collider but will not move it.

Consider also that you want to use a trigger (that makes your STATIC COLLDER into a STATIC TRIGGER COLLIDER).

Basically the idea behind trigger is:
"Use triggers when you want to catch the event but you don't want the gameobject interacting with Physics forces."

Triggers

The scripting system can detect when collisions occur and initiate
  actions using the OnCollisionEnter function. However, you can also use
  the physics engine simply to detect when one collider enters the space
  of another without creating a collision. A collider configured as a
  Trigger (using the Is Trigger property) does not behave as a solid
  object and will simply allow other colliders to pass through. When a
  collider enters its space, a trigger will call the OnTriggerEnter
  function on the trigger object’s scripts


问:
After Post Method There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'DepartmentId'
The Drop Down List is generated perfectly on HttpGet Method for Create Action.
But when it comes to HttpPost Action Create it compiles this error:

There is no ViewData item of type 'IEnumerable' that
  has the key 'DepartmentId'.

I Know that this question has been asked multiple of times.
I have truly tried most of the methods like:

changing the name of the list .

Put the Select List in a View Data instead of ViewBag

Cast The ViewBag.Departments in my view to IEnumerable or SelectList

None of these trials fixed my problem. Here is my Code:

```<code>[HttpGet]
[ActionName("Create")]
public ActionResult Create_Get()
{
    using (MyConnectionString _context = new MyConnectionString())
    {
        var list = (from d in _context.Departments
                    select new
                    {
                        d.DepartmentId,
                        d.DepartmentName
                    }).ToList();
        SelectList dList = new SelectList(list, "DepartmentId", "DepartmentName");
        ViewBag.DepartmentId = dList;
    }

    Employee employee = new Employee();
    return View(employee);
}

[HttpPost]
[ActionName("Create")]
public ActionResult Create_Post()
{
    if (ModelState.IsValid)
    {
        Employee employee = new Employee();
        TryUpdateModel(employee);
        if (ModelState.IsValid)
        {
            using (MyConnectionString _context = new MyConnectionString())
            {
                _context.Employees.Add(employee);
                _context.SaveChanges();
            }
            return RedirectToAction("Index");
        }

    }
    return View();
}
</code>```

View:

```<code> @Html.DropDownList("DepartmentId", ViewBag.DepartmentId as IEnumerable<SelectListItem>, new { @class = "form-control" })
</code>```

答:
Just as the error states, the ViewBag has no such data.  Note how you set this value in your [HttpGet] action:

```<code>ViewBag.DepartmentId = dList;
</code>```

So when you return the view, that value is available to the view.  Your [HttpPost] action returns the same view.  But it returns it without any model and, specifically to regarding this error, without ever setting anything in the ViewBag.

Before you return the view, set the ViewBag values you need in your controller action.  Exactly as you already do in your [HttpGet] action.

(Since the functionality would be repeated, you are of course encouraged to extract it into a common method rather than just copying/pasting all of the same code.  You're also encouraged to use a model instead of relying on ViewBag, but that may just come down to a matter of personal preference.)

Edit: As requested in a comment below, an example:

For example, notice how you set your ViewBag value in your [HttpGet] action:

```<code>using (MyConnectionString _context = new MyConnectionString())
{
    var list = (from d in _context.Departments
                select new
                {
                    d.DepartmentId,
                    d.DepartmentName
                }).ToList();
    SelectList dList = new SelectList(list, "DepartmentId", "DepartmentName");
    ViewBag.DepartmentId = dList;
}
</code>```

If you want to set the exact same value in your [HttpPost] action, then simply do the exact same thing:

```<code>if (ModelState.IsValid)
{
    // ... the code you have in here is unchanged
}

using (MyConnectionString _context = new MyConnectionString())
{
    var list = (from d in _context.Departments
                select new
                {
                    d.DepartmentId,
                    d.DepartmentName
                }).ToList();
    SelectList dList = new SelectList(list, "DepartmentId", "DepartmentName");
    ViewBag.DepartmentId = dList;
}
return View();
</code>```

Body:
The Drop Down List is generated perfectly on HttpGet Method for Create Action.
But when it comes to HttpPost Action Create it compiles this error:

There is no ViewData item of type 'IEnumerable' that
  has the key 'DepartmentId'.

I Know that this question has been asked multiple of times.
I have truly tried most of the methods like:

changing the name of the list .

Put the Select List in a View Data instead of ViewBag

Cast The ViewBag.Departments in my view to IEnumerable or SelectList

None of these trials fixed my problem. Here is my Code:

[HttpGet]
[ActionName("Create")]
public ActionResult Create_Get()
{
    using (MyConnectionString _context = new MyConnectionString())
    {
        var list = (from d in _context.Departments
                    select new
                    {
                        d.DepartmentId,
                        d.DepartmentName
                    }).ToList();
        SelectList dList = new SelectList(list, "DepartmentId", "DepartmentName");
        ViewBag.DepartmentId = dList;
    }

    Employee employee = new Employee();
    return View(employee);
}

[HttpPost]
[ActionName("Create")]
public ActionResult Create_Post()
{
    if (ModelState.IsValid)
    {
        Employee employee = new Employee();
        TryUpdateModel(employee);
        if (ModelState.IsValid)
        {
            using (MyConnectionString _context = new MyConnectionString())
            {
                _context.Employees.Add(employee);
                _context.SaveChanges();
            }
            return RedirectToAction("Index");
        }

    }
    return View();
}

View:

 @Html.DropDownList("DepartmentId", ViewBag.DepartmentId as IEnumerable<SelectListItem>, new { @class = "form-control" })

Body:
Just as the error states, the ViewBag has no such data.  Note how you set this value in your [HttpGet] action:

ViewBag.DepartmentId = dList;

So when you return the view, that value is available to the view.  Your [HttpPost] action returns the same view.  But it returns it without any model and, specifically to regarding this error, without ever setting anything in the ViewBag.

Before you return the view, set the ViewBag values you need in your controller action.  Exactly as you already do in your [HttpGet] action.

(Since the functionality would be repeated, you are of course encouraged to extract it into a common method rather than just copying/pasting all of the same code.  You're also encouraged to use a model instead of relying on ViewBag, but that may just come down to a matter of personal preference.)

Edit: As requested in a comment below, an example:

For example, notice how you set your ViewBag value in your [HttpGet] action:

using (MyConnectionString _context = new MyConnectionString())
{
    var list = (from d in _context.Departments
                select new
                {
                    d.DepartmentId,
                    d.DepartmentName
                }).ToList();
    SelectList dList = new SelectList(list, "DepartmentId", "DepartmentName");
    ViewBag.DepartmentId = dList;
}

If you want to set the exact same value in your [HttpPost] action, then simply do the exact same thing:

if (ModelState.IsValid)
{
    // ... the code you have in here is unchanged
}

using (MyConnectionString _context = new MyConnectionString())
{
    var list = (from d in _context.Departments
                select new
                {
                    d.DepartmentId,
                    d.DepartmentName
                }).ToList();
    SelectList dList = new SelectList(list, "DepartmentId", "DepartmentName");
    ViewBag.DepartmentId = dList;
}
return View();


问:
Passing client-side JSON to back-end using ajax
I'm trying to connect the behavior of 2-3 APIs based on JSON responses from one or another API. I'm using ASP.NET MVC and vanilla JS.

The goal is to use a places API (Algolia) so a user can choose a place from an autocomplete input box and after choosing pass the name variable from the JSON to the next API which is a weather API (DarkSky).

The Algolia API is completely JS based and running on the client-side using the following html elements and scripts provided by Algolia:

<input type="search" id="address-input" placeholder="Search for a place.." />
```

<pre class="lang-html prettyprint-override"><code><script>
    var placesAutocomplete = places({
        appId: "my-app-id",
        apiKey: "my-api-key",
        container: document.querySelector('#address-input')
    });
</script>
</code>```

```

<p>After selecting a place the API returns the following JSON structure:</p>

```{
"query": "new york",
"suggestion": {
"name": "New York",
"country": "United States of America",
...},
...
}
```

<p>I want to use the name attribute i.e. "New York" and pass it to my back-end API client so I can use it for the GET request towards the DarkSky API.</p>

<p>I made a AJAX script for posting that value back to my MVC Controller but after a lot of trial and error I still don't know how to setup the Controller action to receive the data and and make it available to the rest of the back-end.</p>

<p>Here is the ajax script:</p>

<pre class="lang-html prettyprint-override"><code><script>
placesAutocomplete.on('change', function resultSelected(e) {
        var place = e.suggestion.name || '';
        $.ajax({
            type: 'POST',
            url: 'Ajax', //name of the action in the Home controller
            data: { place }
        })
    });
</script>
</code>```

Could you please guide me how my action should look like and is my ajax script ok.

Thank you!

答:
the url parameter in the ajax call should be of the format baseUrl+"controllerName/actionName" where 'baseUrl' is the definitive part of the URL which tells you the domain name. For example - 'http://localhost:23456/api'

Something like this:

url: baseUrl + "home/actionName"  //here 'home' is the controller name as mentioned in the question

Body:
I'm trying to connect the behavior of 2-3 APIs based on JSON responses from one or another API. I'm using ASP.NET MVC and vanilla JS.

The goal is to use a places API (Algolia) so a user can choose a place from an autocomplete input box and after choosing pass the name variable from the JSON to the next API which is a weather API (DarkSky).

The Algolia API is completely JS based and running on the client-side using the following html elements and scripts provided by Algolia:

<input type="search" id="address-input" placeholder="Search for a place.." />

After selecting a place the API returns the following JSON structure:

{
"query": "new york",
"suggestion": {
"name": "New York",
"country": "United States of America",
...},
...
}

I want to use the name attribute i.e. "New York" and pass it to my back-end API client so I can use it for the GET request towards the DarkSky API.

I made a AJAX script for posting that value back to my MVC Controller but after a lot of trial and error I still don't know how to setup the Controller action to receive the data and and make it available to the rest of the back-end.

Here is the ajax script:

Could you please guide me how my action should look like and is my ajax script ok.

Thank you!


问:
iOS 12 won't display .svg file as an overlay Google Maps iOS API
So basically I want to use an SVG file I drew as an overlay for the Google Maps iOS API 3. Whenever I use a .jpg file it seems to work fine. I'm using iOS 12

I've tried switching file names and it still only seems to work with JPEGS, not sure about PNGS.

This is my code:

```<code>let camera = GMSCameraPosition.camera(withLatitude: 47.457925, longitude: 8.548466, zoom: 16.0)

        let southWest = CLLocationCoordinate2D(latitude: 47.444561, longitude: 8.534752)
        let northEast = CLLocationCoordinate2D(latitude: 47.483037, longitude: 8.575470)

        let overlayBounds = GMSCoordinateBounds(coordinate: southWest, coordinate: northEast)

        let icon = UIImage(named: "lszh-int-lv-main.svg")

        let overlay = GMSGroundOverlay(bounds: overlayBounds, icon: icon)

        overlay.bearing = 0
        overlay.map = mapView

        mapView.camera = camera
        mapView.animate(to: camera)
</code>```

I'm not getting any error messages with the SVG, it's just not showing up. Is it impossible to even show SVGs as overlays? Thank you for your help!

答:
Preserve Vector Data

Xcode 9 changes this situation by allowing you to choose to treat the image as a vector at runtime. This means the image can smoothly
  scale to arbitrary sizes. The only change you need to make is to tick
  Preserve Vector Data for the PDF image in the asset catalog.

You need to export your vector as an pdf and add it into asset catalog. For more info :
Link 1 Link 2

Body:
So basically I want to use an SVG file I drew as an overlay for the Google Maps iOS API 3. Whenever I use a .jpg file it seems to work fine. I'm using iOS 12

I've tried switching file names and it still only seems to work with JPEGS, not sure about PNGS.

This is my code:

let camera = GMSCameraPosition.camera(withLatitude: 47.457925, longitude: 8.548466, zoom: 16.0)

        let southWest = CLLocationCoordinate2D(latitude: 47.444561, longitude: 8.534752)
        let northEast = CLLocationCoordinate2D(latitude: 47.483037, longitude: 8.575470)

        let overlayBounds = GMSCoordinateBounds(coordinate: southWest, coordinate: northEast)

        let icon = UIImage(named: "lszh-int-lv-main.svg")

        let overlay = GMSGroundOverlay(bounds: overlayBounds, icon: icon)

        overlay.bearing = 0
        overlay.map = mapView

        mapView.camera = camera
        mapView.animate(to: camera)

I'm not getting any error messages with the SVG, it's just not showing up. Is it impossible to even show SVGs as overlays? Thank you for your help!


问:
Easiest way to make complex div with waves
I would like to create divs with complex waves, I'm coming across a lot of tutorials and I tried a lot of things but I can not do it. What is the best way to make waves and the background goes around and stops at the wave? What is the best/simplest way, I heard about the SVG but no skill with that. Is it complicated to realize? I wish I could draw curves and change the background accordingly as on this WordPress theme:
https://www.elegantthemes.com/blog/theme-releases/shape-dividers

I wish I could do that:
http://www.zupimages.net/viewer.php?id=19/22/jr0r.png

I have to learn SVG ? or use illustrator, too complicated directly in CSS if I have several waves. A software like an illustrator to do that for free with SVG exist?

and then do the rest of my style with bootstrap 4 etc? ...thank you

答: I tried this before, just by using an image as border. You can create an image with a wavy border and play with transparency so you get the effect you need.</p>


问:
Is there a C# code in unity to identify when a Button is pressed and when it is released?
I'm currently trying to set up a code in C# that identifies when a certain button is pressed and when it is released

I'm trying to make this certain button scale down when pressed and scale up when released

```<code>public class clickshake : MonoBehaviour
{
    public GameObject click;
    public void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
           transform.localScale += new Vector3(-0.1F, -0.1f, 0);
        }
        if (Input.GetMouseButtonUp(0))
        {
           transform.localScale += new Vector3(0.1F, 0.1f, 0);
        }
    }
}
</code>```

by making this script exclusive to the button in its On Click command
it only grew the button in size and didn't shrink it down

答:
Input.GetMouseButtonDown(0) is triggered when the button is pressed, since you call it when the button is already pressed, it doesn't trigger.

Input.GetMouseButtonDown

Returns true during the frame the user pressed the given mouse button.

https://docs.unity3d.com/ScriptReference/Input.GetMouseButtonDown.html

try tu use Input.GetMouseButton(0) instead.

Or call it elsewhere than in the OnClick().

But be aware that Input.GetMouseButton(0) if in a loop, will trigger multiple time since its detects when the button is held down.

EDIT
By trigger I mean that its returns True so it triggers your if

Body:
I'm currently trying to set up a code in C# that identifies when a certain button is pressed and when it is released

I'm trying to make this certain button scale down when pressed and scale up when released

public class clickshake : MonoBehaviour
{
    public GameObject click;
    public void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
           transform.localScale += new Vector3(-0.1F, -0.1f, 0);
        }
        if (Input.GetMouseButtonUp(0))
        {
           transform.localScale += new Vector3(0.1F, 0.1f, 0);
        }
    }
}

by making this script exclusive to the button in its On Click command
it only grew the button in size and didn't shrink it down


问:
Android: use entity class in view
I'm building an android project, I have a database and I create many entity classes (which has all sorts of annotations like @id, @Nullable). Now I need to show the data in my view.

I'm wondering if it's ok to use directly entity classes in the view (e.g. adapter), or it's better to convert them first in VO object? How to organise things in a clearer way ? Do I need to create a converter for each entity ?

Thanks.

答:
Maybe the MVVM pattern is what you are looking for. Your entity classes (Models) are "wrapped" by ViewModels. The ViewModels expose the data to your UI and accept user input.

There's no need for a 1:1 mapping between Models and ViewModels. Your ViewModel (e.g. for a whole screen) can hold several different Models and interact with them.

Title: Android: use entity class in view


问:
Zero an array in C code

Possible Duplicates:

  How to initialize an array to something in C without a loop?

  How to initialize an array in C

How can I zero a known size of an array without using a for or any other loop ?

For example:

```<code>arr[20] = 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0;
</code>```

This is the long way... I need it the short way.

答:
Using memset:

```<code>int something[20];
memset(something, 0, 20 * sizeof(int));
</code>```

ContentLicense: CC BY-SA 3.0

Title: Zero an array in C code

Body:
Possible Duplicates:

  How to initialize an array to something in C without a loop?

  How to initialize an array in C

How can I zero a known size of an array without using a for or any other loop ?

For example:

arr[20] = 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0;

This is the long way... I need it the short way.

Body:
Using memset:

int something[20];
memset(something, 0, 20 * sizeof(int));


问:
One controller with action inside action
I would like to use a Controller with an Action after two slashes, as if it were an action within an action.

Example: .../Administration/Institution/Register/Id

I was using the solution: .../Administration/InstitutionRegister/Id

But I find an ugly solution, if I could use as in the first example would be better.

It is possible?
Thank you!

答:
You can use Attribute routing in order to create a specific URL for an action :

```<code>[Route("Administration/Institution/Register")]
public IActionResult Index()
{
   return View();
}
</code>```

Hope it helps !

Body:
You can use Attribute routing in order to create a specific URL for an action :

[Route("Administration/Institution/Register")]
public IActionResult Index()
{
   return View();
}

Hope it helps !


问:
disable checkbox after being checked
Please I need help on disabling a checkbox from being checked again after being checked first.

This is what I have done so far.

```<code><label class="checkbox-inline"><input type="checkbox" id="checked" onclick="check();"></label>

        <script type="text/javascript">
        function check() {
          if($("#checked").is(":checked")){
             alert("Thanks for Attending");
            $(this).attr('disabled','disabled');
            }
          }
    }
    </script>
</code>```

答:
```<code><html>
<head>
<title>JqueryCheckboxChekedDisableCheckbox</title>
<style>
input[type=text] {
  width: 100%;
  height:10%;
  padding: 6px;
  border: 1px solid #ccc;
  border-radius: 4px;
}
label {
  padding: 12px 12px 12px 0;
  display: inline-block;
  font-family:sans-serif;
}
input[type=submit] {
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 6px 20px;
  text-decoration: none;
  margin: 4px 2px;
  cursor: pointer;
}
.error{
color:red;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

</head>
<fieldset style="margin-left:20%;margin-right:20%;font-family:sans-serif;padding:15px;border-radius:5px;background:#f2f2f2;border:5px solid #1F497D">
<legend style="background:#1F497D;color:#fff;padding:5px 10px;font-size:22px;border-radius:5px;margin-left:20px;box-shadow:0 0 0 5px #ddd">JqueryCheckboxChekedDisableCheckbox</legend>
<table>
    <tr><td>Subjects:</td><td><input type="checkbox" name="subject" value="java"/>Java<input type="checkbox" name="subject" value="hibernate"/>Hibernate<input type="checkbox" name="subject" value="spring"/>Spring</td></tr>
    <tr><td></td><td><input type="submit" value="Submit" id="send"/></td></tr>
</table>
</fieldset>
</html>
<script>
$('#send').on('click',function(){
    $("input[name='subject']").each(function(){
        if ($(this).is(":checked")) {
            $(this).prop("disabled",true);
        }
    });
});
</script>
</code>```

Title: disable checkbox after being checked

Body:
Please I need help on disabling a checkbox from being checked again after being checked first.

This is what I have done so far.

<input type="checkbox" id="checked" onclick="check();">


问:
Error when trying to install second flutter app on the emulator
I created a simple flutter app and run it on android emulator. It worked Ok. Now I created another one and when I'm trying to run it on the emulator I'm getting:

```<code> Error: ADB exited with exit code 1
adb: failed to install /Users/Admin/Development/flutter/flutter_app_test/build/app/outputs/apk/app.apk: Failure [INSTALL_FAILED_INSUFFICIENT_STORAGE]
Error launching application on Android SDK built for x86.
</code>```

Once I delete the first app from emulator I'm able to install the second one and run it successfully.

So anytime I have one flutter app installed on the emulator installing another one will lead to the same error.

Is there a way to overcome this limitation? Or this is a bug?

答:
Open AVD Manager

Wipe Data (delete datas from emulator)

Open emulator

Try to run app

Body:
I created a simple flutter app and run it on android emulator. It worked Ok. Now I created another one and when I'm trying to run it on the emulator I'm getting:

 Error: ADB exited with exit code 1
adb: failed to install /Users/Admin/Development/flutter/flutter_app_test/build/app/outputs/apk/app.apk: Failure [INSTALL_FAILED_INSUFFICIENT_STORAGE]
Error launching application on Android SDK built for x86.

Once I delete the first app from emulator I'm able to install the second one and run it successfully.

So anytime I have one flutter app installed on the emulator installing another one will lead to the same error.

Is there a way to overcome this limitation? Or this is a bug?


问:
What is the difference between run process and start process in robot framework
I have been reading up on the robot framework documentation but i am still  not very sure about the difference between start process and run process.

Do i need to use start process first then run it? Or i can just run process?

For start process

When i tried to run the following, the result was 1. It seems like it was calculating the number of process that has already started.

But i needed the result generated from calculation.robot.

```<code>${result} =     Start Process       calculation.robot       shell=True
</code>```

For run process

Running something like this will generate error - permission denied

```<code>${result} =     Run Process     ${CURDIR}/calculation.robot
</code>```

So i was just wondering what's the difference between the two.

Thank you!

Referenced to: https://robotframework.org/robotframework/latest/libraries/Process.html

答:
Start Process does not return "results", this run process in the background so it returns identifier to running process.

As opposite to Start Process the Run Process is waiting until process is completed.

So this difference cannot cause 'permission denied' and in the first case you will not see this error. And if you will use Get Process Result with handle that is returned by Start Process you will see the same error.

Body:
I have been reading up on the robot framework documentation but i am still  not very sure about the difference between start process and run process.

Do i need to use start process first then run it? Or i can just run process?

For start process

When i tried to run the following, the result was 1. It seems like it was calculating the number of process that has already started.

But i needed the result generated from calculation.robot.

${result} =     Start Process       calculation.robot       shell=True

For run process

Running something like this will generate error - permission denied

${result} =     Run Process     ${CURDIR}/calculation.robot

So i was just wondering what's the difference between the two.

Thank you!

Referenced to: https://robotframework.org/robotframework/latest/libraries/Process.html


问:
grails rollback db operation on some error

I have a service where to save a lot of data to db.
Using MYSQL
I have used like this

```<code>Domain1.withTransaction {text->
            def domain1=//Create my domain object to save
             if(!domain1.save()){
               domain1.errors.each {
                      println it
               }
               throw new RuntimeException('unable to save domain1')
        }
        Domain2.withTransaction {text->
            def domain2=//Create my domain object to save
             if(!domain2.save()){
               domain2.errors.each {
                      println it
               }
               throw new RuntimeException('unable to save domain2')
        }
</code>```

My problem if there occurred any problem in saving domain2 i need to roll back domain1 save also.

I need to remove domain1 from db.

答:
Put that Domain2.withTransaction closure inside Domain1.withTransaction closure, so error in Domain2 transaction will rollback both Domain1 and Domain2 transaction

Like this

```<code>Domain1.withTransaction {
      //....
      Domain2.withTransaction {
           //....
      }
}
</code>```

Body:
I have a service where to save a lot of data to db.
Using MYSQL
I have used like this

Domain1.withTransaction {text->
            def domain1=//Create my domain object to save
             if(!domain1.save()){
               domain1.errors.each {
                      println it
               }
               throw new RuntimeException('unable to save domain1')
        }
        Domain2.withTransaction {text->
            def domain2=//Create my domain object to save
             if(!domain2.save()){
               domain2.errors.each {
                      println it
               }
               throw new RuntimeException('unable to save domain2')
        }

My problem if there occurred any problem in saving domain2 i need to roll back domain1 save also.

I need to remove domain1 from db.

Body:
Put that Domain2.withTransaction closure inside Domain1.withTransaction closure, so error in Domain2 transaction will rollback both Domain1 and Domain2 transaction

Like this

Domain1.withTransaction {
      //....
      Domain2.withTransaction {
           //....
      }
}


问:
Converting AI to EPS / JPEG without "Use artboards"
I'm trying to read(preview) AI (adobe illustrator) file in my web application. my web app is on Linux machine and mainly uses Python.

I couldn't find any native python code that can preview AI file, so I continued to search for solution and found ghostscript, which gives the option to convert AI to JPG/PNG and I these format I have no problem previewing.
The issue I have is that I need the preview to include the whole document and not just the artboard, in illustrator it's possible when removing the checkbox from "use artboards" when saving, see screenshot: https://helpx.adobe.com/content/dam/help/en/illustrator/how-to/export-svg/_jcr_content/main-pars/image0/5286-export-svg-fig1.jpg

but when I try to export from ghostscript, I can't make it work...
from my understanding, it's best to try and first convert to EPS and then from that to JPG/PNG, but I failed doing that as well and the items that are outside the artboard are not showing.

on linux, these are the commands I basically tried , after installing ghostscript:

gs -dNOPAUSE -dBATCH -sDEVICE=eps2write -sOutputFile=out.eps input.ai

gs -dNOPAUSE -dBATCH -sDEVICE=jpeg -r300 -sOutputFile=out.jpeg input.ai

gs -dNOPAUSE -dBATCH -sDEVICE=pngalpha -r300 -sOutputFile=out.png input.ai

if it's not possible with ghostscript and I need imagemagick instead, I don't mind using it... I tried it for 10 minute and just got bunch of errors so I left it....

AI file for example: https://drive.google.com/open?id=1UgyLG_-nEUL5FLTtD3Dl281YVYzv0mUy

Jpeg example of the output I want: https://drive.google.com/open?id=1tLT2Uj1pp1gKRnJ8BojPZJxMFRn6LJoM

Thank you

答:
Firstly, Adobe Illustrator native files are not technically supported by Ghostscript at all. They might work, because they are normally either PostScript or PDF files with custom bits that can be ignored for the purposes of drawing the content. But it's not a guarantee.

Secondly; no, do not multiply convert the files! That's a piece of cargo-cult mythology that's been doing the rounds for ages. There are sometimes reasons for doing so but in general this will simply magnify problems, not solve them. Really, don't do that.

You haven't quoted the errors you are getting and you haven't supplied any files to look at, so it's not really possible to tell what your problem is. I have no clue what an 'artboard' is, and a picture of the Illustrator dialog doesn't help.

Perhaps if you could supply an example file, and maybe a picture of what you expect, it might be possible to figure it out. My guess is that your '.ai' file is a PDF file, and that it has a MediaBox (which is what Ghostscript uses by default) and an ArtBox which is what you actually want to use. Or something like that. Hard to say without more information.

Edit

Well, I'm afraid the answer here is that you can't easily get what you want from that file without using Illustrator.

The file is a PDF file (if you rename input.ai to input.pdf then you can open it with a PDF reader). But Illustrator doesn't use most of the PDF file when it opens it. Instead the PDF file contains a '/PieceInfo' key, which is a key in the Page dictionary. That points to a dictionary which has a /Private key, which (finally!) points to a dictionary with a bunch of Illustrator stuff:

```<code>52 0 obj
<<
  /AIMetaData 53 0 R
  /AIPrivateData1 54 0 R
  /AIPrivateData10 55 0 R
  /AIPrivateData11 56 0 R
  /AIPrivateData2 57 0 R
  /AIPrivateData3 58 0 R
  /AIPrivateData4 59 0 R
  /AIPrivateData5 60 0 R
  /AIPrivateData6 61 0 R
  /AIPrivateData7 62 0 R
  /AIPrivateData8 63 0 R
  /AIPrivateData9 64 0 R
  /ContainerVersion 11
  /CreatorVersion 23
  /NumBlock 11
  /RoundtripStreamType 1
  /RoundtripVersion 17
>>
endobj
</code>```

That's the actual saved file format of the Illustrator file. You can think of the PDF file as a 'preview' wrapped around the Illustrator native file. Illustrator reads the PDF file to find its own data, then throws the PDF file away and uses the native file format stored within it instead.

The problem is that the PDF part of the file simply doesn't contain the content you want to see. That's stored in the Illustrator native data. Ghostscript just renders what's in the PDF file, it doesn't look at the Illustrator native file.

Looking at the Illustrator private data, some of it is uncompressed, but most is compressed, it doesn't say how it is compressed but applying the FlateDecode filter produces a good old-fashioned Illustrator PostScript file, one that will work with Ghostscript.

But you would have to manually parse the PDF file, extract all the compressed AIPrivateData streams, concatenate them together, apply the FlateDecode filter to decompress them, and only then send the resulting output to Ghostscript with the -dEPSCrop switch set. That will result in the output you want.

But neither Ghostscript nor ImageMagick (which generally uses Ghostscript to render PDF files) will do any of that for you, you would have to do it all yourself.

Body:
Firstly, Adobe Illustrator native files are not technically supported by Ghostscript at all. They might work, because they are normally either PostScript or PDF files with custom bits that can be ignored for the purposes of drawing the content. But it's not a guarantee.

Secondly; no, do not multiply convert the files! That's a piece of cargo-cult mythology that's been doing the rounds for ages. There are sometimes reasons for doing so but in general this will simply magnify problems, not solve them. Really, don't do that.

You haven't quoted the errors you are getting and you haven't supplied any files to look at, so it's not really possible to tell what your problem is. I have no clue what an 'artboard' is, and a picture of the Illustrator dialog doesn't help.

Perhaps if you could supply an example file, and maybe a picture of what you expect, it might be possible to figure it out. My guess is that your '.ai' file is a PDF file, and that it has a MediaBox (which is what Ghostscript uses by default) and an ArtBox which is what you actually want to use. Or something like that. Hard to say without more information.

Edit

Well, I'm afraid the answer here is that you can't easily get what you want from that file without using Illustrator.

The file is a PDF file (if you rename input.ai to input.pdf then you can open it with a PDF reader). But Illustrator doesn't use most of the PDF file when it opens it. Instead the PDF file contains a '/PieceInfo' key, which is a key in the Page dictionary. That points to a dictionary which has a /Private key, which (finally!) points to a dictionary with a bunch of Illustrator stuff:

52 0 obj
<<
  /AIMetaData 53 0 R
  /AIPrivateData1 54 0 R
  /AIPrivateData10 55 0 R
  /AIPrivateData11 56 0 R
  /AIPrivateData2 57 0 R
  /AIPrivateData3 58 0 R
  /AIPrivateData4 59 0 R
  /AIPrivateData5 60 0 R
  /AIPrivateData6 61 0 R
  /AIPrivateData7 62 0 R
  /AIPrivateData8 63 0 R
  /AIPrivateData9 64 0 R
  /ContainerVersion 11
  /CreatorVersion 23
  /NumBlock 11
  /RoundtripStreamType 1
  /RoundtripVersion 17
>>
endobj

That's the actual saved file format of the Illustrator file. You can think of the PDF file as a 'preview' wrapped around the Illustrator native file. Illustrator reads the PDF file to find its own data, then throws the PDF file away and uses the native file format stored within it instead.

The problem is that the PDF part of the file simply doesn't contain the content you want to see. That's stored in the Illustrator native data. Ghostscript just renders what's in the PDF file, it doesn't look at the Illustrator native file.

Looking at the Illustrator private data, some of it is uncompressed, but most is compressed, it doesn't say how it is compressed but applying the FlateDecode filter produces a good old-fashioned Illustrator PostScript file, one that will work with Ghostscript.

But you would have to manually parse the PDF file, extract all the compressed AIPrivateData streams, concatenate them together, apply the FlateDecode filter to decompress them, and only then send the resulting output to Ghostscript with the -dEPSCrop switch set. That will result in the output you want.

But neither Ghostscript nor ImageMagick (which generally uses Ghostscript to render PDF files) will do any of that for you, you would have to do it all yourself.


问:
php artisan queue not showing anything
I'm using laravel 5.0 and trying to set a queue for sending an email, I have created it and wrote code like.
Queue::pushOn('emails', new SendEmail($user));

It's adding a row in the jobs table, then I'm running the following command

$ php artisan queue:listen

But it is not showing anything and not sending emails too.

答:
Check out that you have in config/queue.php a connection with the name of emails because you are pushing to this queue with the method pushOn().
As a alternative, only push in the default queue using:

Queue::push(new SendEmail($user));
```

Title: php artisan queue not showing anything


问:
Why my app gets wrong strings from resources for localization?
I have created three files for localisation: "en","ru","uk" and I saw problem app can get some strings right and some string wrong. What it means? For example one layout during its working can contain several locales instead one single and it is wrong. I saw that some users solved this problem via adding some lines of code to buil.gradle but maybe we have another solution and why did it worked well several weeks ago when my project was in Java. I'm sure that it can't be caused by moving from one language to another. At recyclerView I can see similar problem. At activity I can set my current language like this:

```<code>sp = this.getSharedPreferences("app_data", 0)
        val lang = sp!!.getString("language", Locale.getDefault().language)
        val locale = Locale(lang)
        Locale.setDefault(locale)
        val config = Configuration()
        config.setLocale(locale)

        resources.updateConfiguration(
                config, resources.displayMetrics
        )
</code>```

but updateConfiguration is deprecated and I looked for some new variants which will work. Then I found this question but it didn't help me. I need to set language at RV items, activities and fragments, but I can't do it. Why does it happen and how I can solve this problem?

答:
You have to refresh your activity when language change : please look the demo code for language selection. Hope this will help you!</p>

```<code>public class ChangeLangDemo extends AppCompatActivity {
        private static final String TAG = ChangeLangDemo.class.getSimpleName();
        private String[] languages = {"Select Language", "English", "Hindi", "Gujarati"};
        private TextView textView;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_change_lang_demo);

            AppCompatSpinner spinner = findViewById(R.id.language_spinner);
            textView = findViewById(R.id.text);

            loadLocale();

            ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, languages);
            spinner.setAdapter(adapter);

            spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                    String lang = "en";
                    switch (position) {
                        case 0:
                            break;
                        case 1:
                            lang = "en";
                            break;
                        case 2:
                            lang = "hi";
                            break;
                        case 3:
                            lang = "gu";
                            break;
                        default:
                            break;
                    }

                    changeLang(lang);
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }

            });

        }

        public void saveLocale(String lang) {
            String langPref = "Language";
            SharedPreferences prefs = getSharedPreferences("CommonPrefs", Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString(langPref, lang);
            editor.apply();
        }

        public void loadLocale() {
            String langPref = "Language";
            SharedPreferences prefs = getSharedPreferences("CommonPrefs", Activity.MODE_PRIVATE);
            String language = prefs.getString(langPref, "");
            changeLang(language);
        }

        public void changeLang(String lang) {
            if (lang.equalsIgnoreCase(""))
                return;
            Locale locale = new Locale(lang);
            saveLocale(lang);
            Locale.setDefault(locale);
            android.content.res.Configuration config = new android.content.res.Configuration();
            config.locale = locale;
            getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
            updateTexts();
        }

        private void updateTexts() {
            textView.setText(getResources().getText(R.string.text));
        }
    }
</code>```

Body:
I have created three files for localisation: "en","ru","uk" and I saw problem app can get some strings right and some string wrong. What it means? For example one layout during its working can contain several locales instead one single and it is wrong. I saw that some users solved this problem via adding some lines of code to buil.gradle but maybe we have another solution and why did it worked well several weeks ago when my project was in Java. I'm sure that it can't be caused by moving from one language to another. At recyclerView I can see similar problem. At activity I can set my current language like this:

sp = this.getSharedPreferences("app_data", 0)
        val lang = sp!!.getString("language", Locale.getDefault().language)
        val locale = Locale(lang)
        Locale.setDefault(locale)
        val config = Configuration()
        config.setLocale(locale)

        resources.updateConfiguration(
                config, resources.displayMetrics
        )

but updateConfiguration is deprecated and I looked for some new variants which will work. Then I found this question but it didn't help me. I need to set language at RV items, activities and fragments, but I can't do it. Why does it happen and how I can solve this problem?

Body:
You have to refresh your activity when language change : please look the demo code for language selection. Hope this will help you!

public class ChangeLangDemo extends AppCompatActivity {
        private static final String TAG = ChangeLangDemo.class.getSimpleName();
        private String[] languages = {"Select Language", "English", "Hindi", "Gujarati"};
        private TextView textView;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_change_lang_demo);

            AppCompatSpinner spinner = findViewById(R.id.language_spinner);
            textView = findViewById(R.id.text);

            loadLocale();

            ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, languages);
            spinner.setAdapter(adapter);

            spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                    String lang = "en";
                    switch (position) {
                        case 0:
                            break;
                        case 1:
                            lang = "en";
                            break;
                        case 2:
                            lang = "hi";
                            break;
                        case 3:
                            lang = "gu";
                            break;
                        default:
                            break;
                    }

                    changeLang(lang);
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }

            });

        }

        public void saveLocale(String lang) {
            String langPref = "Language";
            SharedPreferences prefs = getSharedPreferences("CommonPrefs", Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString(langPref, lang);
            editor.apply();
        }

        public void loadLocale() {
            String langPref = "Language";
            SharedPreferences prefs = getSharedPreferences("CommonPrefs", Activity.MODE_PRIVATE);
            String language = prefs.getString(langPref, "");
            changeLang(language);
        }

        public void changeLang(String lang) {
            if (lang.equalsIgnoreCase(""))
                return;
            Locale locale = new Locale(lang);
            saveLocale(lang);
            Locale.setDefault(locale);
            android.content.res.Configuration config = new android.content.res.Configuration();
            config.locale = locale;
            getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
            updateTexts();
        }

        private void updateTexts() {
            textView.setText(getResources().getText(R.string.text));
        }
    }


问:
keywords with - and /
I need to search for keywords
containing - or /
for example: 2019-45 or 2019/1258
when I search for 2019-45 MySQL return two records containing:
2019-45 for the first and 2019/45 for the second (these two data do not mean the same thing for me).
In my request (in boolean mode) I use '"2019-45"'

match (title) against (mykeysword in mode)> 0

Apparently, even with double quotes the fulltext does not take into account the - or /

How to take into account - or / ?
thank you
Didier

thanks for yours answers

this is my code

CREATE DEFINER=devops_admin@% PROCEDURE sp_cherche(in f_texte VARCHAR(255)) BEGIN SELECT id_rech, titre, MATCH(titre) AGAINST(f_texte in boolean mode) as quotation FROM tab_references WHERE MATCH(titre) AGAINST(f_texte in boolean mode) >0 END

When I call :

sp_recherche('"2018-45"') ou sp_recherche('"2018/45"')

this two calls give the same result, in my exemple 2 answers.

It is not my MySQL server, it is a provider. Thaks you for the link, but I dont understant anything on the mapping (sorry) If y understand, need to say that - and / are caracters.

thanks

Didier

答:
The default characterset for MySQL Full Text Search does not recognize the - or / characters as "letters". To get those recognized as letters, the characterset can be modified, as documented here in the MySQL Reference Manual:

https://dev.mysql.com/doc/refman/5.7/en/fulltext-fine-tuning.html#fulltext-modify-character-set

Title: keywords with - and /


问:
Jquery/Javascript conflicts?
I just implemented a multi-language mod onto my website.

Problem is that there seems to be a conflict between the javascript files from the language mod and the javascript files that already were on the page.

```<code><!-- language files here -->
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/translationEngine.js"></script>
<script type="text/javascript" src="js/jquery.cookie.js"></script>
<script type="text/javascript" src="js/jquery.translate-1.3.9.min.js"></script>
<script>var browserlang = 'en';</script>

<!-- Javascript -->

<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery.pngFix.pack.js"></script>
<script type="text/javascript" src="js/jquery.flow.1.2.min.js"></script>
<script type="text/javascript" src="js/jquery.prettyPhoto.js"></script>
<script type="text/javascript" src="js/concept.js"></script>
</code>```

js/jquery-1.3.2.min.js is what makes the 3 image slider on the homepage work, but... it seems to also be interfering with the functions of the translator.

If u remove js/jquery-1.3.2.min.js from the page, the translator works fine, but the slider no longer works.

removing js/jquery-1.4.2.min.js from the page doesnt make the translator work either, in fact it seems to cause more errors in the back.

Can someone guide me in the right direction that would allow me to make the language translator and image slider both work?

http://filefx.com

Thanks :)

答:
I change all the .js file on the page used from below code:

```<code><script>
var K = jQuery.noConflict();
     alert(K);
     jQuery(document).ready(function () {

         alert("Bye");
     });
</script>
</code>```

It works fine now.

ContentLicense: CC BY-SA 2.5

Title: Jquery/Javascript conflicts?

Body:
I just implemented a multi-language mod onto my website.

Problem is that there seems to be a conflict between the javascript files from the language mod and the javascript files that already were on the page.

js/jquery-1.3.2.min.js is what makes the 3 image slider on the homepage work, but... it seems to also be interfering with the functions of the translator.

If u remove js/jquery-1.3.2.min.js from the page, the translator works fine, but the slider no longer works.

removing js/jquery-1.4.2.min.js from the page doesnt make the translator work either, in fact it seems to cause more errors in the back.

Can someone guide me in the right direction that would allow me to make the language translator and image slider both work?

http://filefx.com

Thanks :)

Body:
I change all the .js file on the page used from below code:

<script>
var K = jQuery.noConflict();
     alert(K);
     jQuery(document).ready(function () {

         alert("Bye");
     });
</script>

It works fine now.


问:
Adding pagination to index.html.erb in Ruby on Rails - Easy Question
I am new to rails so go easy. I have built my first blog and would like to set it up such that in the <% post.each do |post| %> render of the posts, I would like it to work such that it only displays 10 posts and then has a link to view the next 10. </p>

<p>I am hoping this is an easy question. Let me know if you would like me to post any code. </p>

答:
You can use the kaminari gem.

Very ease to use and highly customization friendly.

Body:
I am new to rails so go easy. I have built my first blog and would like to set it up such that in the <% post.each do |post| %> render of the posts, I would like it to work such that it only displays 10 posts and then has a link to view the next 10.

I am hoping this is an easy question. Let me know if you would like me to post any code.