问:
Getting null pointer exception while creating JSONRPCCLIENT object in bitcoind
Class for creation of JsonRpcClient object for connecting my application by bitcoin test net
already installed bitcoind and sync it with testnet as well from main network of bitcoin.
Trying to create unique wallet address but getting null pointer exception as i can observe values are not being used from application.properties file i m using spring tool suite and maven dependencywf.bitcoin
            bitcoin-rpc-client
            1.1.0

```<code>package bitcoin.utils;

import java.net.URL;
import java.util.Properties;

import javax.annotation.PostConstruct;
import javax.naming.CommunicationException;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import wf.bitcoin.javabitcoindrpcclient.BitcoinJSONRPCClient;
import wf.bitcoin.javabitcoindrpcclient.BitcoinRPCException;

@Configuration
@Component
public class ResourceUtils {

    private static final Logger logger = LoggerFactory.getLogger(ResourceUtils.class);

    @Value("${node.bitcoind.rpc.protocol}")
    private static String protocol;
    @Value("${node.bitcoind.rpc.host}")
    private static String host;
    @Value("${node.bitcoind.rpc.port}")
    private static String port;
    @Value("${node.bitcoind.rpc.user}")
    private static String user;
    @Value("${node.bitcoind.rpc.password}")
    private static String password;
    @Value("${node.bitcoind.http.auth_scheme}")
    private static String authScheme;

    private static Properties nodeConfig;

    @PostConstruct
    void init() {
        logger.info("in init {}", "in init");
        nodeConfig = new Properties();
        nodeConfig.setProperty("node.bitcoind.rpc.protocol", protocol);
        logger.debug("protocol==============================================={}", protocol);
        nodeConfig.setProperty("node.bitcoind.rpc.host", host);
        logger.debug("host==============================================={}", host);
        nodeConfig.setProperty("node.bitcoind.rpc.port", port);
        logger.debug("port==============================================={}", port);
        nodeConfig.setProperty("node.bitcoind.rpc.user", user);
        logger.debug("user==============================================={}", user);
        nodeConfig.setProperty("node.bitcoind.rpc.password", password);
        logger.debug("password==============================================={}", password);
        nodeConfig.setProperty("node.bitcoind.http.auth_scheme", authScheme);
        logger.debug("authScheme==============================================={}", authScheme);
    }

    public ResourceUtils() {

    }

    public static CloseableHttpClient getHttpProvider() {
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
        return HttpClients.custom().setConnectionManager(connManager).build();

    }

    public static BitcoinJSONRPCClient getBtcdProvider() throws BitcoinRPCException, CommunicationException {
        logger.info("getHttpProvider {}", getHttpProvider());
        logger.info("getNodeConfig {}", getNodeConfig());
        BitcoinJSONRPCClient bitcoinJsonRpcClient = null;
        try {
            URL url = new URL(protocol + "://" + user + ':' + password + "@" + host + ":" + port + "/");
            bitcoinJsonRpcClient = new BitcoinJSONRPCClient(url);
            logger.info("btcdClientt {}", bitcoinJsonRpcClient);
            // bitcoinJsonRpcClient.setTxFee(BigDecimal.valueOf(0.001));
        } catch (Exception e) {
            return bitcoinJsonRpcClient;
        }
        return bitcoinJsonRpcClient;
    }

    public static Properties getNodeConfig() {
        return nodeConfig;
    }
}

</code>```

Configuration File

```<code>node.bitcoind.rpc.protocol = http
node.bitcoind.rpc.host = 127.0.0.1
node.bitcoind.rpc.port = 8332
node.bitcoind.rpc.user = username
node.bitcoind.rpc.password = password
node.bitcoind.http.auth_scheme = Basic
</code>```

Bitcoin.config file

```<code>rpcuser=user
rpcpassword=password
testnet=1
rpcport=8332
rpcallowip=127.0.0.1
rpcallowip=195.154.11.93
server=1
</code>```

Methode for getting bitcoin wallet address

```<code>public String generateWalletAddress(String id) {
        try {
            BitcoinJSONRPCClient client = ResourceUtils.getBtcdProvider();
            return client.getNewAddress();
        } catch (CommunicationException c) {
            System.err.println(c);
            return null;
        }

    }

</code>```

Stack Trace

```<code>Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-02-12 11:50:45.205 ERROR 10991 --- [  restartedMain] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resourceUtils': Invocation of init method failed; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:160) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:416) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1788) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878) ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at bitcoin.BitcoinApplication.main(BitcoinApplication.java:10) [classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_242]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_242]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_242]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_242]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.2.4.RELEASE.jar:2.2.4.RELEASE]
Caused by: java.lang.NullPointerException: null
    at java.util.Hashtable.put(Hashtable.java:460) ~[na:1.8.0_242]
    at java.util.Properties.setProperty(Properties.java:166) ~[na:1.8.0_242]
    at bitcoin.utils.ResourceUtils.init(ResourceUtils.java:47) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_242]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_242]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_242]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_242]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:389) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:333) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:157) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    ... 23 common frames omitted

</code>```

答:
I got my solution actually the problem was of version i was using rpcport
which is changed to test.rpcport  for test net from bitcoind version 17.0
hence bean were not getting the connection from my localhost server causing null pointer exception.

Body:
Class for creation of JsonRpcClient object for connecting my application by bitcoin test net
already installed bitcoind and sync it with testnet as well from main network of bitcoin.
Trying to create unique wallet address but getting null pointer exception as i can observe values are not being used from application.properties file i m using spring tool suite and maven dependencywf.bitcoin
            bitcoin-rpc-client
            1.1.0

package bitcoin.utils;

import java.net.URL;
import java.util.Properties;

import javax.annotation.PostConstruct;
import javax.naming.CommunicationException;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import wf.bitcoin.javabitcoindrpcclient.BitcoinJSONRPCClient;
import wf.bitcoin.javabitcoindrpcclient.BitcoinRPCException;

@Configuration
@Component
public class ResourceUtils {

    private static final Logger logger = LoggerFactory.getLogger(ResourceUtils.class);

    @Value("${node.bitcoind.rpc.protocol}")
    private static String protocol;
    @Value("${node.bitcoind.rpc.host}")
    private static String host;
    @Value("${node.bitcoind.rpc.port}")
    private static String port;
    @Value("${node.bitcoind.rpc.user}")
    private static String user;
    @Value("${node.bitcoind.rpc.password}")
    private static String password;
    @Value("${node.bitcoind.http.auth_scheme}")
    private static String authScheme;

    private static Properties nodeConfig;

    @PostConstruct
    void init() {
        logger.info("in init {}", "in init");
        nodeConfig = new Properties();
        nodeConfig.setProperty("node.bitcoind.rpc.protocol", protocol);
        logger.debug("protocol==============================================={}", protocol);
        nodeConfig.setProperty("node.bitcoind.rpc.host", host);
        logger.debug("host==============================================={}", host);
        nodeConfig.setProperty("node.bitcoind.rpc.port", port);
        logger.debug("port==============================================={}", port);
        nodeConfig.setProperty("node.bitcoind.rpc.user", user);
        logger.debug("user==============================================={}", user);
        nodeConfig.setProperty("node.bitcoind.rpc.password", password);
        logger.debug("password==============================================={}", password);
        nodeConfig.setProperty("node.bitcoind.http.auth_scheme", authScheme);
        logger.debug("authScheme==============================================={}", authScheme);
    }

    public ResourceUtils() {

    }

    public static CloseableHttpClient getHttpProvider() {
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
        return HttpClients.custom().setConnectionManager(connManager).build();

    }

    public static BitcoinJSONRPCClient getBtcdProvider() throws BitcoinRPCException, CommunicationException {
        logger.info("getHttpProvider {}", getHttpProvider());
        logger.info("getNodeConfig {}", getNodeConfig());
        BitcoinJSONRPCClient bitcoinJsonRpcClient = null;
        try {
            URL url = new URL(protocol + "://" + user + ':' + password + "@" + host + ":" + port + "/");
            bitcoinJsonRpcClient = new BitcoinJSONRPCClient(url);
            logger.info("btcdClientt {}", bitcoinJsonRpcClient);
            // bitcoinJsonRpcClient.setTxFee(BigDecimal.valueOf(0.001));
        } catch (Exception e) {
            return bitcoinJsonRpcClient;
        }
        return bitcoinJsonRpcClient;
    }

    public static Properties getNodeConfig() {
        return nodeConfig;
    }
}

Configuration File

node.bitcoind.rpc.protocol = http
node.bitcoind.rpc.host = 127.0.0.1
node.bitcoind.rpc.port = 8332
node.bitcoind.rpc.user = username
node.bitcoind.rpc.password = password
node.bitcoind.http.auth_scheme = Basic

Bitcoin.config file

rpcuser=user
rpcpassword=password
testnet=1
rpcport=8332
rpcallowip=127.0.0.1
rpcallowip=195.154.11.93
server=1

Methode for getting bitcoin wallet address

public String generateWalletAddress(String id) {
        try {
            BitcoinJSONRPCClient client = ResourceUtils.getBtcdProvider();
            return client.getNewAddress();
        } catch (CommunicationException c) {
            System.err.println(c);
            return null;
        }

    }

Stack Trace

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-02-12 11:50:45.205 ERROR 10991 --- [  restartedMain] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resourceUtils': Invocation of init method failed; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:160) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:416) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1788) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878) ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at bitcoin.BitcoinApplication.main(BitcoinApplication.java:10) [classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_242]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_242]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_242]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_242]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.2.4.RELEASE.jar:2.2.4.RELEASE]
Caused by: java.lang.NullPointerException: null
    at java.util.Hashtable.put(Hashtable.java:460) ~[na:1.8.0_242]
    at java.util.Properties.setProperty(Properties.java:166) ~[na:1.8.0_242]
    at bitcoin.utils.ResourceUtils.init(ResourceUtils.java:47) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_242]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_242]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_242]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_242]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:389) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:333) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:157) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    ... 23 common frames omitted


来源: stackexchange

问:
convert month-day-year into day-month-year using javascript
I'm trying to convert a MM/DD/YYYY date to a long date. So for example, 02/16/2020 would convert to something like 16/02/2020.

Is there a way to make this date conversion accurately?

答:
check this. its work.

function formatDate(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return [day,month,year].join('/');
}
document.getElementById('res').innerHTML =  formatDate('02/16/2020') ;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="res">res</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
check this. its work.

function formatDate(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return [day,month,year].join('/');
}
document.getElementById('res').innerHTML =  formatDate('02/16/2020') ;

<div id="res">res</div>


问:
How do i create the rails 3.1 application using mysql
How to create a rails 3.1 application using mysql. The following command used to create the project with sqlite database.

```<code>rails new depot
</code>```

I'd like to use mysql then sqlite. So can anyone tell me how to create a project with mysql.

Thanks

答:
You should use:</p>

```<code>rails new depot -d mysql
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How to create a rails 3.1 application using mysql. The following command used to create the project with sqlite database.

rails new depot

I'd like to use mysql then sqlite. So can anyone tell me how to create a project with mysql.

Thanks

Body:
You should use:

rails new depot -d mysql


问:
oracle query taking more execution time in oracle when i m using AND condition
This below query taking more execution time when in filtering with AND Condition TD.A97 = '4408' ,and apart from them I m joining two table and two synonyms can u help me to reduce execution time  for this query.</p>

```<code>SELECT DISTINCT TC.CUS_ACNT_NBR ,
                TC.CUS_ACNT_ROLE_CD ,
                TD.F_DOCNUMBER,
                TD.A45,
                HD.SHPMNT_NBR,
                HD.SHPMNT_ID
FROM   TDOC_CUS_ACNT TC
       INNER JOIN TDOC TD ON TD.F_DOCNUMBER = TC.F_DOCNUMBER
       INNER JOIN DWH_SHIPMENT_DIM HD ON TD.A45 = HD.SHPMNT_NBR
       INNER JOIN DWH_INVOICE_CHARGE_FACT ICF ON HD.shpmnt_dim_key = ICF.shipment_dim_fk
WHERE  TC.CUS_ACNT_ROLE_CD in ('BILL','SHPR','THRD')
AND    TD.A97 = '4408' ;
</code>```

Body:
This below query taking more execution time when in filtering with AND Condition TD.A97 = '4408' ,and apart from them I m joining two table and two synonyms can u help me to reduce execution time  for this query.

SELECT DISTINCT TC.CUS_ACNT_NBR ,
                TC.CUS_ACNT_ROLE_CD ,
                TD.F_DOCNUMBER,
                TD.A45,
                HD.SHPMNT_NBR,
                HD.SHPMNT_ID
FROM   TDOC_CUS_ACNT TC
       INNER JOIN TDOC TD ON TD.F_DOCNUMBER = TC.F_DOCNUMBER
       INNER JOIN DWH_SHIPMENT_DIM HD ON TD.A45 = HD.SHPMNT_NBR
       INNER JOIN DWH_INVOICE_CHARGE_FACT ICF ON HD.shpmnt_dim_key = ICF.shipment_dim_fk
WHERE  TC.CUS_ACNT_ROLE_CD in ('BILL','SHPR','THRD')
AND    TD.A97 = '4408' ;

Body:
explain plan:below my explain plan with with AND condition.

PLAN_TABLE_OUTPUT

Plan hash value: 53520552

----------------------------------------------------------------------------------------------------------------------------------------------
| Id  | Operation                         | Name                | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     | TQ/Ins |IN-OUT| PQ Distrib |
----------------------------------------------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                  |                     |  1639K|   148M|       | 15382   (1)| 00:00:01 |        |      |            |
|   1 |  PX COORDINATOR                   |                     |       |       |       |            |          |        |      |            |
|   2 |   PX SEND QC (RANDOM)             | :TQ10007            |  1639K|   148M|       | 15382   (1)| 00:00:01 |  Q1,07 | P->S | QC (RAND)  |
|   3 |    HASH UNIQUE                    |                     |  1639K|   148M|   164M| 15382   (1)| 00:00:01 |  Q1,07 | PCWP |            |
|   4 |     PX RECEIVE                    |                     |  1639K|   148M|       | 15382   (1)| 00:00:01 |  Q1,07 | PCWP |            |
|   5 |      PX SEND HASH                 | :TQ10006            |  1639K|   148M|       | 15382   (1)| 00:00:01 |  Q1,06 | P->P | HASH       |
|   6 |       HASH UNIQUE                 |                     |  1639K|   148M|   164M| 15382   (1)| 00:00:01 |  Q1,06 | PCWP |            |
|*  7 |        HASH JOIN                  |                     |  1639K|   148M|       | 12902   (1)| 00:00:01 |  Q1,06 | PCWP |            |
|   8 |         PX RECEIVE                |                     |   434K|    33M|       |  8351   (1)| 00:00:01 |  Q1,06 | PCWP |            |
|   9 |          PX SEND HASH             | :TQ10005            |   434K|    33M|       |  8351   (1)| 00:00:01 |  Q1,05 | P->P | HASH       |
|* 10 |           HASH JOIN BUFFERED      |                     |   434K|    33M|       |  8351   (1)| 00:00:01 |  Q1,05 | PCWP |            |
|  11 |            BUFFER SORT            |                     |       |       |       |            |          |  Q1,05 | PCWC |            |
|  12 |             PX RECEIVE            |                     |   325K|  7636K|       |  2335   (1)| 00:00:01 |  Q1,05 | PCWP |            |
|  13 |              PX SEND HASH         | :TQ10001            |   325K|  7636K|       |  2335   (1)| 00:00:01 |        | S->P | HASH       |
|* 14 |               TABLE ACCESS FULL   | TDOC_CUS_ACNT       |   325K|  7636K|       |  2335   (1)| 00:00:01 |        |      |            |
|  15 |            PX RECEIVE             |                     |   272K|    15M|       |  6015   (1)| 00:00:01 |  Q1,05 | PCWP |            |
|  16 |             PX SEND HASH          | :TQ10004            |   272K|    15M|       |  6015   (1)| 00:00:01 |  Q1,04 | P->P | HASH       |
|* 17 |              HASH JOIN            |                     |   272K|    15M|       |  6015   (1)| 00:00:01 |  Q1,04 | PCWP |            |
|  18 |               PX RECEIVE          |                     |   268K|  5508K|       |   660   (1)| 00:00:01 |  Q1,04 | PCWP |            |
|  19 |                PX SEND HASH       | :TQ10003            |   268K|  5508K|       |   660   (1)| 00:00:01 |  Q1,03 | P->P | HASH       |
|  20 |                 PX BLOCK ITERATOR |                     |   268K|  5508K|       |   660   (1)| 00:00:01 |  Q1,03 | PCWC |            |
|* 21 |                  TABLE ACCESS FULL| TDOC                |   268K|  5508K|       |   660   (1)| 00:00:01 |  Q1,03 | PCWP |            |
|  22 |               BUFFER SORT         |                     |       |       |       |            |          |  Q1,04 | PCWC |            |
|  23 |                PX RECEIVE         |                     |  1769K|    62M|       |  5354   (1)| 00:00:01 |  Q1,04 | PCWP |            |
|  24 |                 PX SEND HASH      | :TQ10000            |  1769K|    62M|       |  5354   (1)| 00:00:01 |        | S->P | HASH       |
|  25 |                  REMOTE           | SHIPMENT_DIM        |  1769K|    62M|       |  5354   (1)| 00:00:01 |   TDIM | R->S |            |
|  26 |         BUFFER SORT               |                     |       |       |       |            |          |  Q1,06 | PCWC |            |
|  27 |          PX RECEIVE               |                     |  6677K|    82M|       |  4550   (1)| 00:00:01 |  Q1,06 | PCWP |            |
|  28 |           PX SEND HASH            | :TQ10002            |  6677K|    82M|       |  4550   (1)| 00:00:01 |        | S->P | HASH       |
|  29 |            REMOTE                 | INVOICE_CHARGE_FACT |  6677K|    82M|       |  4550   (1)| 00:00:01 |   TDIM | R->S |            |
----------------------------------------------------------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   7 - access("HD"."SHPMNT_DIM_KEY"="ICF"."SHIPMENT_DIM_FK")
  10 - access("TD"."F_DOCNUMBER"="TC"."F_DOCNUMBER")
  14 - filter("TC"."CUS_ACNT_ROLE_CD"='BILL' OR "TC"."CUS_ACNT_ROLE_CD"='SHPR' OR "TC"."CUS_ACNT_ROLE_CD"='THRD')
  17 - access("TD"."A45"="HD"."SHPMNT_NBR")
  21 - filter("TD"."A45" IS NOT NULL AND "TD"."A97"='4408')

Remote SQL Information (identified by operation id):
----------------------------------------------------

  25 - SELECT "SHPMNT_DIM_KEY","SHPMNT_NBR","SHPMNT_ID" FROM "DIM"."SHIPMENT_DIM" "HD" (accessing 'TDIM.WORLD' )

  29 - SELECT "SHIPMENT_DIM_FK" FROM "DIM"."INVOICE_CHARGE_FACT" "ICF" (accessing 'TDIM.WORLD' )

Note
-----
   - dynamic statistics used: dynamic sampling (level=5)
   - Degree of Parallelism is 16 because of table property


问:
Why is my Spark Mlib ALS collaborative filtering training model so slow?
I currently use the ALS collaborative filtering method for a content recommendation system in my App. It seems to work fine and the prediction part is quick but the training model part takes over 20 seconds. I need it to be at least 1 second or less, since i need almost real time recommendations. I currently use a spark cluster with 3 machines, each nodes has 17GB. I also use datastax but that shouldn't have any influence.

I don't really know why and how to improve this? Happy for any suggestions, thanks.

Here is the basic spark code:

```<code>from pyspark.mllib.recommendation import ALS, MatrixFactorizationModel, Rating

# Load and parse the data
data = sc.textFile("data/mllib/als/test.data")
ratings = data.map(lambda l: l.split(','))\
    .map(lambda l: Rating(int(l[0]), int(l[1]), float(l[2])))
</code>```

This part takes over 20 seconds but should only take less then 1.

```<code># Build the recommendation model using Alternating Least Squares
rank = 10
numIterations = 10
model = ALS.train(ratings, rank, numIterations)

# Evaluate the model on training data
testdata = ratings.map(lambda p: (p[0], p[1]))
predictions = model.predictAll(testdata).map(lambda r: ((r[0], r[1]), r[2]))
ratesAndPreds = ratings.map(lambda r: ((r[0], r[1]), r[2])).join(predictions)
MSE = ratesAndPreds.map(lambda r: (r[1][0] - r[1][1])**2).mean()
print("Mean Squared Error = " + str(MSE))

# Save and load model
model.save(sc, "target/tmp/myCollaborativeFilter")
sameModel = MatrixFactorizationModel.load(sc, "target/tmp/myCollaborativeFilter")
</code>```

答:
One of the reasons why it may take time is because of RDDs. For RDDs, there is no specific structure/schema. Hence those tend to be a little slow. when ALS.train() is called, Some operations such as flatmap, count, map which happens behind the scenes on RDD will have to consider nested structures, hence the slowness.

Instead, you can try the same using Dataframes instead of RDDs. Dataframe operations are optimal, since the schema/types are known. But for ALS to work on dataframes, you have to import ALS from "ml.recommendation". I too had the same problem and when I tried with dataframes instead of RDDs, it worked very well.

You can also try out checkpointing when your data becomes quite big.

Body:
I currently use the ALS collaborative filtering method for a content recommendation system in my App. It seems to work fine and the prediction part is quick but the training model part takes over 20 seconds. I need it to be at least 1 second or less, since i need almost real time recommendations. I currently use a spark cluster with 3 machines, each nodes has 17GB. I also use datastax but that shouldn't have any influence.

I don't really know why and how to improve this? Happy for any suggestions, thanks.

Here is the basic spark code:

from pyspark.mllib.recommendation import ALS, MatrixFactorizationModel, Rating

# Load and parse the data
data = sc.textFile("data/mllib/als/test.data")
ratings = data.map(lambda l: l.split(','))\
    .map(lambda l: Rating(int(l[0]), int(l[1]), float(l[2])))

This part takes over 20 seconds but should only take less then 1.

# Build the recommendation model using Alternating Least Squares
rank = 10
numIterations = 10
model = ALS.train(ratings, rank, numIterations)

# Evaluate the model on training data
testdata = ratings.map(lambda p: (p[0], p[1]))
predictions = model.predictAll(testdata).map(lambda r: ((r[0], r[1]), r[2]))
ratesAndPreds = ratings.map(lambda r: ((r[0], r[1]), r[2])).join(predictions)
MSE = ratesAndPreds.map(lambda r: (r[1][0] - r[1][1])**2).mean()
print("Mean Squared Error = " + str(MSE))

# Save and load model
model.save(sc, "target/tmp/myCollaborativeFilter")
sameModel = MatrixFactorizationModel.load(sc, "target/tmp/myCollaborativeFilter")


问:
ExtJS: grid 100% height
I have a structure of this type (Ext 3.3.1):

```<code>var page = new Ext.Viewport({
    layout: 'border',
    anchor:'100% 100%',
    renderTo: Ext.getBody(),
    items: [{
        region: 'north',
        height:'auto',
        items: [toolbar]
    },{
        region: 'center',
        layout:'fit',
        items: [gridCourses,gridExams]
    }]
});
</code>```

In the toolbar, I have two buttons, COURSES and EXAMS. I use these buttons to show/hide one of the two grid, so that only one is visible at a time. The code of the buttons I uses is something like this:

```<code>{
    text: 'Courses',
    iconCls: 'show-courses',
    handler: function(){
        gridCourses.store.reload();
        gridCourses.show();
        gridExams.hide();
    }
},{
    text: 'Exams',
    iconCls: 'show-exams',
    handler: function(){
        gridExams.store.reload();
        gridCourses.hide();
        gridExams.show();
    }
}
</code>```

The question is: how can I have the the displayed grid to fill the whole screen (especially in height?). I think I have to put something in the handler of the buttons or a listener to my grids, but I do not know what to put. Any hints?

答:
The fit Layout only supports one element otherwise it want work. You will need to wrap it all up.</p>

```<code>var page = new Ext.Viewport({
    layout: 'border',
    // anchor:'100% 100%', <- I don't think you need this, cause the Viewport is alsways bound to the fullscreen
    // renderTo: Ext.getBody(), <- Same here. The viewport is alsways rendered to the body
    items: [{
        region: 'north',
        height:'auto',
        items: [toolbar]
    },{
        region: 'center',
        layout:'fit',
        items: [
            {
                xtype: 'container',
                items: [
                    {
                        xtype: 'container'
                        layout: 'fit',
                        items: [Grid1]
                    },
                    {
                        xtype: 'container'
                        layout: 'fit',
                        items: [Grid1]
                    }
                ]
            }
        ]
    }]
});
</code>```

Title: ExtJS: grid 100% height

Body:
I have a structure of this type (Ext 3.3.1):

var page = new Ext.Viewport({
    layout: 'border',
    anchor:'100% 100%',
    renderTo: Ext.getBody(),
    items: [{
        region: 'north',
        height:'auto',
        items: [toolbar]
    },{
        region: 'center',
        layout:'fit',
        items: [gridCourses,gridExams]
    }]
});

In the toolbar, I have two buttons, COURSES and EXAMS. I use these buttons to show/hide one of the two grid, so that only one is visible at a time. The code of the buttons I uses is something like this:

{
    text: 'Courses',
    iconCls: 'show-courses',
    handler: function(){
        gridCourses.store.reload();
        gridCourses.show();
        gridExams.hide();
    }
},{
    text: 'Exams',
    iconCls: 'show-exams',
    handler: function(){
        gridExams.store.reload();
        gridCourses.hide();
        gridExams.show();
    }
}

The question is: how can I have the the displayed grid to fill the whole screen (especially in height?). I think I have to put something in the handler of the buttons or a listener to my grids, but I do not know what to put. Any hints?

Body:
The fit Layout only supports one element otherwise it want work. You will need to wrap it all up.

var page = new Ext.Viewport({
    layout: 'border',
    // anchor:'100% 100%', <- I don't think you need this, cause the Viewport is alsways bound to the fullscreen
    // renderTo: Ext.getBody(), <- Same here. The viewport is alsways rendered to the body
    items: [{
        region: 'north',
        height:'auto',
        items: [toolbar]
    },{
        region: 'center',
        layout:'fit',
        items: [
            {
                xtype: 'container',
                items: [
                    {
                        xtype: 'container'
                        layout: 'fit',
                        items: [Grid1]
                    },
                    {
                        xtype: 'container'
                        layout: 'fit',
                        items: [Grid1]
                    }
                ]
            }
        ]
    }]
});


问:
How to combine two csv files in python
I have two different csv sample files:

first.csv

```<code>name,school
Derrick, schoolA
Peter,schoolB
</code>```

second.csv

```<code>age  ,address
21,abc
22,sdc
</code>```

I need to combine the two csv files to one. So the result expected is :

combined.csv

```<code> name,school,age  ,address
    Derrick,schoolA, 21,abc
    Peter,schoolB, 22,sdc
</code>```

Is there a way I can achieve this using pandas?

答:
You can do something like this.

```<code>df1 = pd.read_csv('first.csv')
df2 = pd.read_csv('second.csv')

combined_df = pd.concat([df1, df2], axis=1)
</code>```

But you need to make sure that df1 and df2 have the same amount of rows. Hope that helps

Title: How to combine two csv files in python

Body:
I have two different csv sample files:

first.csv

name,school
Derrick, schoolA
Peter,schoolB

second.csv

age  ,address
21,abc
22,sdc

I need to combine the two csv files to one. So the result expected is :

combined.csv

 name,school,age  ,address
    Derrick,schoolA, 21,abc
    Peter,schoolB, 22,sdc

Is there a way I can achieve this using pandas?

Body:
You can do something like this.

df1 = pd.read_csv('first.csv')
df2 = pd.read_csv('second.csv')

combined_df = pd.concat([df1, df2], axis=1)

But you need to make sure that df1 and df2 have the same amount of rows. Hope that helps


问:
Limit Element Search to driver RFT
is there a way to limit the searching to a single process or driver in rational functional tester? If i have two instances up at the same time, it doesn't know which one to look at and crashes. </p>

答: IF you are using descriptive programming, you could lmit your serach based on the process ID. Have you tried that ?</p>

Title: Limit Element Search to driver RFT


问:
Timber Pagination: page.php / not showing up
In the Timber for Wordpress DOCs (link) they say

This will only work in a php file with an active query (like
  archive.php or home.php) (...)

By my understanding, what I have done, is an active query (?).
I need the pagination on one of my page.php sites however.

I can not get the pagination to display.

page.php

```<code>$context['blogposts'] = new Timber\PostQuery(array(
    'numberposts'   => -1,
    'posts_per_page'=> 2,
    'post_type'     => 'post',
    'order'         => 'DESC',
    'paged'         => (get_query_var('paged')) ? get_query_var('paged') : 1,
));
</code>```

page.twig

```<code><div id="blogposts-container">
    {% for post in blogposts %}
      {% include ['tease-'~post.post_type~'.twig', 'tease.twig'] %}
    {% endfor %}
  </div>

  {% include 'partial/pagination.twig' with { pagination: blogposts.pagination({show_all: false, mid_size: 3, end_size: 2}) } %}
</code>```

This pretty much exact logic works for the index + article pages (yes I tested it).
How can I get it to work for a page/custom page?

Dumping blogposts.pagination gives me the correct list of items.

答:
Turns out i should have shown the pagination.twig too.
In my case I had to:

```<code>{% set posts = blogposts %}
</code>```

for this partial to work.
Due to the partial using posts as the base object for displaying content.

Body:
In the Timber for Wordpress DOCs (link) they say

This will only work in a php file with an active query (like
  archive.php or home.php) (...)

By my understanding, what I have done, is an active query (?).
I need the pagination on one of my page.php sites however.

I can not get the pagination to display.

page.php

$context['blogposts'] = new Timber\PostQuery(array(
    'numberposts'   => -1,
    'posts_per_page'=> 2,
    'post_type'     => 'post',
    'order'         => 'DESC',
    'paged'         => (get_query_var('paged')) ? get_query_var('paged') : 1,
));

page.twig

    {% for post in blogposts %}
      {% include ['tease-'~post.post_type~'.twig', 'tease.twig'] %}
    {% endfor %}

  {% include 'partial/pagination.twig' with { pagination: blogposts.pagination({show_all: false, mid_size: 3, end_size: 2}) } %}

This pretty much exact logic works for the index + article pages (yes I tested it).
How can I get it to work for a page/custom page?

Dumping blogposts.pagination gives me the correct list of items.

Body:
Turns out i should have shown the pagination.twig too.
In my case I had to:

{% set posts = blogposts %}

for this partial to work.
Due to the partial using posts as the base object for displaying content.


问:
Rails: How to group by nested association?
I have a Follow model with user_id and track_id. The Track model has an artist_id field.

What I want to do is count which artists have the most followers, but since users follow "tracks" and not "artists", I need to figure out how to do a count through the tracks.

So, what I was thinking was to do some sort of group by on a nested association. i.e. Group the Follow records by "track -> artist_id", somehow.

Then I could count the number of users for each.

Is that even possible? Is there more info that would be useful here?

答:
You need to use has_many :through to establish the Artist <-> Tracks <-> User relationship.

```<code>class Artist < ApplicationRecord
  has_many :tracks
  has_many :users, through: :tracks
end

class Follow < ApplicationRecord
  belongs_to :user
  belongs_to :track
end

class Track < ApplicationRecord
  belongs_to :artist
  has_and_belongs_to_many :users, join_table: :follows
end

class User < ApplicationRecord
  has_and_belongs_to_many :tracks
  has_many :artists, through: :tracks, join_table: :follows
end
</code>```

Then Rails can take care of the joins between Artist and User.

```<code>Artist.includes(:users).group(:id).count("users.id")
</code>```

Body:
You need to use has_many :through to establish the Artist <-> Tracks <-> User relationship.

class Artist < ApplicationRecord
  has_many :tracks
  has_many :users, through: :tracks
end

class Follow < ApplicationRecord
  belongs_to :user
  belongs_to :track
end

class Track < ApplicationRecord
  belongs_to :artist
  has_and_belongs_to_many :users, join_table: :follows
end

class User < ApplicationRecord
  has_and_belongs_to_many :tracks
  has_many :artists, through: :tracks, join_table: :follows
end

Then Rails can take care of the joins between Artist and User.

Artist.includes(:users).group(:id).count("users.id")


问:
Calling Typescript function from Highcharts load event
I am trying to call typescript function openDialog() from the events.load of highcharts but I am not able to call it. Even though I am using arrow function I am not able to get it. Here is my code :

```<code>events: {
    load: () => {
       var chart : any = this;
      for (var j in chart.series) {
        var series = chart.series[j];
        for (var i in series.data) {
          ((i) =>{
            var point = series.data[i];
            if (point.graphic) {
              point.graphic.on('click',(e)=>this.openDialog(point.options,'all')
            );
            }
          })(i)
        }
      }
    }
  },

  public openDialog(option,type){
       //Do Something
  }
</code>```

EDIT

I have got one link where there are binding this with function.

Is there anything that I am missing ?

答:
Finally got it worked by this simple change

```<code>events: {
  load: function(e) {
   var chart : any = e.target; // to get the chart details
  for (var j in chart.series) {
    console.log(j)
    var series = chart.series[j];
    for (var i in series.data) {

      ((i) =>{
        console.log(i)
        var point = series.data[i];
        if (point.graphic) {
          point.graphic.on('click',(e)=>this.openDialog()
        );
        }
      })(i)
    }
  }
  }.bind(this) //binding the parent this to access openDialog function
},

public openDialog(option,type){
   //Do Something
}
</code>```

Here I had to bind this which does not comes from chart. So I have to bind this using .bint(this) to the load function. And to get the chart details I am using e.target. This way I am getting it worked.

Stackblitz Demo

Body:
I am trying to call typescript function openDialog() from the events.load of highcharts but I am not able to call it. Even though I am using arrow function I am not able to get it. Here is my code :

events: {
    load: () => {
       var chart : any = this;
      for (var j in chart.series) {
        var series = chart.series[j];
        for (var i in series.data) {
          ((i) =>{
            var point = series.data[i];
            if (point.graphic) {
              point.graphic.on('click',(e)=>this.openDialog(point.options,'all')
            );
            }
          })(i)
        }
      }
    }
  },

  public openDialog(option,type){
       //Do Something
  }

EDIT

I have got one link where there are binding this with function.

Is there anything that I am missing ?

Body:
Finally got it worked by this simple change

events: {
  load: function(e) {
   var chart : any = e.target; // to get the chart details
  for (var j in chart.series) {
    console.log(j)
    var series = chart.series[j];
    for (var i in series.data) {

      ((i) =>{
        console.log(i)
        var point = series.data[i];
        if (point.graphic) {
          point.graphic.on('click',(e)=>this.openDialog()
        );
        }
      })(i)
    }
  }
  }.bind(this) //binding the parent this to access openDialog function
},

public openDialog(option,type){
   //Do Something
}

Here I had to bind this which does not comes from chart. So I have to bind this using .bint(this) to the load function. And to get the chart details I am using e.target. This way I am getting it worked.

Stackblitz Demo


问:
zero to standard issue in any view's constraints
when I add constraints in Xcode add new constraints, all my 0 and negative 0 turns into standard and it gives some strange output when I set those constraints. How can I fix this?

Is this any new feature of Xcode or issue I don't know?

答:
This is an issue from Xcode and they will resolve it in the next update. Beta version of this update is available on the Apple's website

They have fixed a bug that prevented entering a 0 constant in the constraint popup editors. (54076090)


问:
python Diffie-Hellman standard library
Is there a standard library for python that implements Diffie-Hellman?
I've taken a look at openssl wrapper in python pyopenssl and it doesn't cover it.
I could not find it in NaCl or cryptography.io library either.</p>

答: another library, seems more up-to-date https://pypi.org/project/pyDH/ with latest commit in 2019</p>

Title: python Diffie-Hellman standard library


问:
How to avoid scrollbar space while its not appear in extjs grid pannel?
Hi in my java project we have extjs grid. while i increase data in grid pannel automatically vertical scrollbar will come.if the data is small amount the scrollbar will not appear. but the space of scrollbar is appeared in my grid. What i need is while data amount is small it shouldnot show scroll bar and scrollbar space, and when i incease the data it should allow the scrollbar to appaear. How can i achive it.

Thanks,

答:
May be this will help you</p>

```<code>new Ext.grid.GridPanel({
  ...
  view : new Ext.grid.GridView({
                forceFit    : true,
                scrollOffset: 0,
                getTotalWidth: function() {
                    return "auto";
                }
  })
  ...
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
May be this will help you

new Ext.grid.GridPanel({
  ...
  view : new Ext.grid.GridView({
                forceFit    : true,
                scrollOffset: 0,
                getTotalWidth: function() {
                    return "auto";
                }
  })
  ...
}


问:
By default, where does Spring Boot expect views to be stored?
I'm experimenting on re-writing my configuration-heavy, vanilla Spring MVC project using Spring Boot. I started a brand new Spring Boot project in IntelliJ using the Spring Boot Initiaizer and I'm going the route of minimal Java-based configuration. Lots of tutorials point out that the default main class generated is sufficient and that @SpringBootApplication has everything included. I got a sample REST Controller to work and return a serialized object as JSON, but it appears getting a view to show is proving difficult. My structure is as follows, with everything default other than the webapps directory which I created.

```<code>src
`-main
   `-java
   `-resources
     `-static
     `-templates
   `-webapp
     `-WEB-INF
        `-home.jsp
</code>```

The controller is plain simple.

```<code>@Controller
public class ViewMaster {
    @RequestMapping("/home")
    public String home() {
        return "home";
    }
}
</code>```

Without any configuration, I'd like to know where Spring Boot expects the views to be stored and with what extension (html?). I've also tried to include the following in application.properties but I still get a 404 error. Moving the WEB-INF directory or just the html file around in resources didn't help either.

```<code>spring.mvc.view.prefix=/WEB-INF/
spring.mvc.view.suffix=.jsp
</code>```

I've also tried including these dependencies in my pom.xml without any effect.

```<code><dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
</dependency>
</code>```

I must be missing something painfully obvious here so appreciate if someone can point that out!

答:
```<code><!-- Tomcat for JSP rendering -->
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>
</code>```

<p>Change Scope to "default" solved my problem </p>

Body:
I'm experimenting on re-writing my configuration-heavy, vanilla Spring MVC project using Spring Boot. I started a brand new Spring Boot project in IntelliJ using the Spring Boot Initiaizer and I'm going the route of minimal Java-based configuration. Lots of tutorials point out that the default main class generated is sufficient and that @SpringBootApplication has everything included. I got a sample REST Controller to work and return a serialized object as JSON, but it appears getting a view to show is proving difficult. My structure is as follows, with everything default other than the webapps directory which I created.

src
`-main
   `-java
   `-resources
     `-static
     `-templates
   `-webapp
     `-WEB-INF
        `-home.jsp

The controller is plain simple.

@Controller
public class ViewMaster {
    @RequestMapping("/home")
    public String home() {
        return "home";
    }
}

Without any configuration, I'd like to know where Spring Boot expects the views to be stored and with what extension (html?). I've also tried to include the following in application.properties but I still get a 404 error. Moving the WEB-INF directory or just the html file around in resources didn't help either.

spring.mvc.view.prefix=/WEB-INF/
spring.mvc.view.suffix=.jsp

I've also tried including these dependencies in my pom.xml without any effect.

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
</dependency>

I must be missing something painfully obvious here so appreciate if someone can point that out!

Body:
<!-- Tomcat for JSP rendering -->
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>

Change Scope to "default" solved my problem


问:
How to get a irrational number as a user input in python?
How to get a irrational number as a user input in python? Like squared root of 2

something like :

```<code>Irrational_Number = float(input("ENTER a Irrational Number : "))
   >>> ENTER a Irrational Number : (USER INPUT)
</code>```

and then user put a Number like N-th root of K (i mean the number in this format not the exactly this kind of String) " Pi " , " e " or " Phi " in command Line.

How User Can do this Directly in command line python (3.8)

I searched this question everywhere but there is nothing about that...

答:
Please find below code snippet:

```<code>import re
g = input("Enter your irrational number : ")
if g=='pi':
    g=math.pi
elif "root" in g:
    root=float(re.search('[0-9]+', g).group())
    number=float(re.search('(\d+)(?!.*\d)', g).group())
    g=number**(1/float(root))
print(g)
</code>```

Advantage of using this would be:

There is no manual value inserted

You can build it for every symbol present in math lib

Can be extended for other operations as well

Body:
How to get a irrational number as a user input in python? Like squared root of 2

something like :

Irrational_Number = float(input("ENTER a Irrational Number : "))
   >>> ENTER a Irrational Number : (USER INPUT)

and then user put a Number like N-th root of K (i mean the number in this format not the exactly this kind of String) " Pi " , " e " or " Phi " in command Line.

How User Can do this Directly in command line python (3.8)

I searched this question everywhere but there is nothing about that...

Body:
Please find below code snippet:

import re
g = input("Enter your irrational number : ")
if g=='pi':
    g=math.pi
elif "root" in g:
    root=float(re.search('[0-9]+', g).group())
    number=float(re.search('(\d+)(?!.*\d)', g).group())
    g=number**(1/float(root))
print(g)

Advantage of using this would be:

There is no manual value inserted

You can build it for every symbol present in math lib

Can be extended for other operations as well


问:
Force TemporaryFileUploadHandler on specific request
I need to process an uploaded file with GeoDjango. According to the documentation, I should use Datasource() constructor from GDAL.

Problem is that size of uploaded shapefiles can be less than 2.5 MB, so MemoryFileUploadHandler is used by default and thus I can't access to a filepath required by Datasource().

I decided to override request.upload_handlers for my specific view, with only "django.core.files.uploadhandler.TemporaryFileUploadHandler" because I don't need to create a subclass (for now), but I get the following error : You cannot set the upload handlers after the upload has been processed.

Here is my piece of code:

def home(request):
    request.upload_handlers = ["django.core.files.uploadhandler.TemporaryFileUploadHandler"]

    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
    else:
        form = UploadFileForm()
    return render(
        request,
        'app/index.html',
        {
            'title':'HOME',
            'form': form,
        }
    )
```

What am I doing wrong ? Also, should I create a subclass for a custom handler anyway ?

答:
the problem is when the function is called django already use the upload_handler so it's to late to change it.

I remember you might be able to still change it if you disable csrf for the function. (Also see: Where/how to replace default upload handler in Django CBV?)

Another possibility would be writing your own upload handler or maybe a middleware that changes the upload handler depending on the path.

Body:
I need to process an uploaded file with GeoDjango. According to the documentation, I should use Datasource() constructor from GDAL.

Problem is that size of uploaded shapefiles can be less than 2.5 MB, so MemoryFileUploadHandler is used by default and thus I can't access to a filepath required by Datasource().

I decided to override request.upload_handlers for my specific view, with only "django.core.files.uploadhandler.TemporaryFileUploadHandler" because I don't need to create a subclass (for now), but I get the following error : You cannot set the upload handlers after the upload has been processed.

Here is my piece of code:

def home(request):
    request.upload_handlers = ["django.core.files.uploadhandler.TemporaryFileUploadHandler"]

    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
    else:
        form = UploadFileForm()
    return render(
        request,
        'app/index.html',
        {
            'title':'HOME',
            'form': form,
        }
    )

What am I doing wrong ? Also, should I create a subclass for a custom handler anyway ?


问:
Problem in installing elasticsearch for Laravel
When I tried to install Elasticsearch for my Laravel instance using the following command:

```<code>composer require elasticsearch/elasticsearch
</code>```

I got this error:

Problem 1
      - elasticsearch/elasticsearch v7.6.0 requires guzzlehttp/ringphp dev-fork-elasticsearch -> no matching package found.
      - tamayo/laravel-scout-elastic 5.0.0 requires elasticsearch/elasticsearch ^5.0 -> satisfiable by
  elasticsearch/elasticsearch[5.0.x-dev].
      - tamayo/laravel-scout-elastic 5.0.0 requires elasticsearch/elasticsearch ^5.0 -> satisfiable by
  elasticsearch/elasticsearch[5.0.x-dev].
      - tamayo/laravel-scout-elastic 5.0.0 requires elasticsearch/elasticsearch ^5.0 -> satisfiable by
  elasticsearch/elasticsearch[5.0.x-dev].
      - Can only install one of: elasticsearch/elasticsearch[v7.6.1, 5.0.x-dev].
      - Installation request for elasticsearch/elasticsearch ^7.6 -> satisfiable by elasticsearch/elasticsearch[v7.6.0, v7.6.1].
      - Installation request for tamayo/laravel-scout-elastic ^5.0 -> satisfiable by tamayo/laravel-scout-elastic[5.0.0].

Potential causes:
   - A typo in the package name
   - The package is not available in a stable-enough version according to your minimum-stability setting    see
  https://getcomposer.org/doc/04-schema.md#minimum-stability for more
  details.
   - It's a private package and you forgot to add a custom repository to find it

Read https://getcomposer.org/doc/articles/troubleshooting.md for
  further common problems.

Installation failed, reverting ./composer.json to its original
  content.

then I tried to install the package mentioned in the error using the following command:

```<code>composer require guzzlehttp/ringphp
</code>```

and I got the following warning:

Package guzzlehttp/ringphp is abandoned, you should avoid using it. No
  replacement was suggested. Package guzzlehttp/streams is abandoned,
  you should avoid using it. No replacement was suggested

Then I tried to install it again, and I got the same error.

What can I do to address the problem?

答: Please simply try installing it again - according to Packagist, there is a version 7.6.1 available that does not depend on such packages any more. This is something you can also find on https://github.com/elastic/elasticsearch-php/releases</p>

Body:
When I tried to install Elasticsearch for my Laravel instance using the following command:

composer require elasticsearch/elasticsearch

I got this error:

Problem 1
      - elasticsearch/elasticsearch v7.6.0 requires guzzlehttp/ringphp dev-fork-elasticsearch -> no matching package found.
      - tamayo/laravel-scout-elastic 5.0.0 requires elasticsearch/elasticsearch ^5.0 -> satisfiable by
  elasticsearch/elasticsearch[5.0.x-dev].
      - tamayo/laravel-scout-elastic 5.0.0 requires elasticsearch/elasticsearch ^5.0 -> satisfiable by
  elasticsearch/elasticsearch[5.0.x-dev].
      - tamayo/laravel-scout-elastic 5.0.0 requires elasticsearch/elasticsearch ^5.0 -> satisfiable by
  elasticsearch/elasticsearch[5.0.x-dev].
      - Can only install one of: elasticsearch/elasticsearch[v7.6.1, 5.0.x-dev].
      - Installation request for elasticsearch/elasticsearch ^7.6 -> satisfiable by elasticsearch/elasticsearch[v7.6.0, v7.6.1].
      - Installation request for tamayo/laravel-scout-elastic ^5.0 -> satisfiable by tamayo/laravel-scout-elastic[5.0.0].

Potential causes:
   - A typo in the package name
   - The package is not available in a stable-enough version according to your minimum-stability setting    see
  https://getcomposer.org/doc/04-schema.md#minimum-stability for more
  details.
   - It's a private package and you forgot to add a custom repository to find it

Read https://getcomposer.org/doc/articles/troubleshooting.md for
  further common problems.

Installation failed, reverting ./composer.json to its original
  content.

then I tried to install the package mentioned in the error using the following command:

composer require guzzlehttp/ringphp

and I got the following warning:

Package guzzlehttp/ringphp is abandoned, you should avoid using it. No
  replacement was suggested. Package guzzlehttp/streams is abandoned,
  you should avoid using it. No replacement was suggested

Then I tried to install it again, and I got the same error.

What can I do to address the problem?


问:
How the RISC-V HW can determine the privilege level?
The RISC-V current SW privilege level is not set in any CSR. Nevertheless the spec states that "Attempts to access a CSR without appropriate privilege level ... raise illegal instruction". How can it be implemented then (in the HW)?</p>

答: The privilege level is reflected in the MPP bits of the mstatus register.</p>


问:
Where to get Flex - Java DS (Blaze) training material?
I was wondering if any of you out there knows where I can get really good training material (videos, examples, etc) on Flex - Java Data Services (BlazeDS would be ideal) besides the ones offered directly by Adobe. I'm thinking on something like David Tucker's blog</p>

答: Flex on Java covers BlazeDS in the chapter 5. I haven't read it through properly yet so I cannot tell how good the book is.</p>

OwnerDisplayName: Chepech

OwnerDisplayName: pepez


问:
Chinese text-to-speech problems on iOS
We try to use build-in iOS text-to-speech tool for reading Chinese words in the app.
It's good in reading texts. But got problems reading separate words.

For example, we have character 还. It could be pronounced like "hái" with meaning "also, in addition"; and could be pronounced like "huàn" with meaning "to return".
In phrase 我还要还钱 (wǒ hái yào huàn qián) it pronounce 还 in both ways (correct).

In case of separate "还" iOS prefer to read it only like "hái". How to make it pronounce characters in the way we need it (if possible)?

答: As a quick solution you can cut required words from longer files and play them as audio instead of using TTS</p>

Title: Chinese text-to-speech problems on iOS


问:
Redirect tomcat to https using apache server (Windows)
I need to integrate apache server with tomcat first and then redirect http request to https using apache in localhost.

Explaination:

I have a java web development project running on tomcat server. let the url be http://localhost:8080/myProject

I need to integrate my tomcat server with apache server such that http://localhost/myProject displays the page http://localhost:8080/myProject

I need to add security certificate and make it a https request i.e., if i type http://localhost/myProject it should direct to https://localhost/myProject and display the page shown in http://localhost:8080/myProject.

I am able to integrate the two servers successfully using mod_jk and i have installed the self signed security certificate using mod_rewrite and by specifying the certificate and key in httpd-ssl.conf file.
this is the file which i have included in httpd.conf:

```<code># Load mod_jk module
# Update this path to match your modules location
LoadModule jk_module "C:/Program Files/BitNami WAMPStack/apache2/modules/mod_jk.so"

# Where to find workers.properties
# Update this path to match your conf directory location
JkWorkersFile C:/softwares/apache-tomcat-7.0.42/conf/workers.properties

# Where to put jk logs
# Update this path to match your logs directory location
JkLogFile C:/MyProject/mod_jk.log

# Set the jk log level [debug/error/info]
JkLogLevel info

# Select the log format
JkLogStampFormat "[%a %b %d %H:%M:%S %Y]"

# JkOptions indicate to send SSL KEY SIZE,
JkOptions +ForwardKeySize +ForwardURICompat -ForwardDirectories

# JkRequestLogFormat set the request format
JkRequestLogFormat "%w %V %T"

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://localhost$1 [R,L]

# Send everything for context /myProject to worker ajp13
JkMount /myProject ajp13
JkMount /myProject/* ajp13
</code>```

Problem faced:
On removing the lines,

```<code>RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://localhost$1 [R,L]
</code>```

it successfully displays the page as an http request. But on adding the line, though it redirects to an https request it gives a "Not Found" error. I am not able to figure out how to correct this. I hope i am able to explain the problem. I am new to servers and apache modules so this may be a very lame question but please help me figure this out.

答:
These configurations are very simple. But,in all the websites one important part is missing. i.e Please map the servername defined in the virtualhosts file with the ipaddress in the hosts file C:/Program files x86/drivers/etc/hosts.
Eg. 127.0.0.1    localhost(if no virtual host)
127.0.0.1      proxyportal.company.com(if server name in  tag is proxyportal.company.com)

Body:
I need to integrate apache server with tomcat first and then redirect http request to https using apache in localhost.

Explaination:

I have a java web development project running on tomcat server. let the url be http://localhost:8080/myProject

I need to integrate my tomcat server with apache server such that http://localhost/myProject displays the page http://localhost:8080/myProject

I need to add security certificate and make it a https request i.e., if i type http://localhost/myProject it should direct to https://localhost/myProject and display the page shown in http://localhost:8080/myProject.

I am able to integrate the two servers successfully using mod_jk and i have installed the self signed security certificate using mod_rewrite and by specifying the certificate and key in httpd-ssl.conf file.
this is the file which i have included in httpd.conf:

# Load mod_jk module
# Update this path to match your modules location
LoadModule jk_module "C:/Program Files/BitNami WAMPStack/apache2/modules/mod_jk.so"

# Where to find workers.properties
# Update this path to match your conf directory location
JkWorkersFile C:/softwares/apache-tomcat-7.0.42/conf/workers.properties

# Where to put jk logs
# Update this path to match your logs directory location
JkLogFile C:/MyProject/mod_jk.log

# Set the jk log level [debug/error/info]
JkLogLevel info

# Select the log format
JkLogStampFormat "[%a %b %d %H:%M:%S %Y]"

# JkOptions indicate to send SSL KEY SIZE,
JkOptions +ForwardKeySize +ForwardURICompat -ForwardDirectories

# JkRequestLogFormat set the request format
JkRequestLogFormat "%w %V %T"

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://localhost$1 [R,L]

# Send everything for context /myProject to worker ajp13
JkMount /myProject ajp13
JkMount /myProject/* ajp13

Problem faced:
On removing the lines,

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://localhost$1 [R,L]

it successfully displays the page as an http request. But on adding the line, though it redirects to an https request it gives a "Not Found" error. I am not able to figure out how to correct this. I hope i am able to explain the problem. I am new to servers and apache modules so this may be a very lame question but please help me figure this out.


问:
Gridster2 grid not resizing items when toggling material sidebar
I have a grid using Gridster2 navigating from an item of a material sidebar. Sidebar is openned, but, whenever I toggle the sidebar (hide it) gridster is not resizing items until I force a refresh. Is there any way to have it "auto" refresh?

To reproduce it, just go to https://tiberiuzuld.github.io/angular-gridster2/ and inspect element and delete <mat-nav-list class="mat-nav-list mat-list-base" role="navigation"> and its content. It will not take full screen until you change the Grid Type.

Reference: https://github.com/tiberiuzuld/angular-gridster2/tree/master/src/app/sections/api

答:
I resolved the issue by below two steps:

Step1: by adding [ngStyle] to the <gridster>. It added responsive nature to grid-items:

```<code><gridster [options]="options" [ngStyle]="{'width': toggled ? '100%' : 'auto'}">
   <gridster-item [item]="item" *ngFor="let item of dashboard">
      <!-- your content here -->
   </gridster-item>
</gridster>
</code>```

Where toggled is a boolean value saying whether the side-bar toggled or not. Intial value is false.

Step2: To force items content(charts in my case) become responsive inside grid-items, I used the below code:

```<code>itemInitCallback: ((item: GridsterItem, itemComponent: GridsterItemComponentInterface) => {
    window.dispatchEvent(new Event('resize'));  // to reisize respective charts
})
</code>```

Where itemInitCallback is an inbuilt gridEvent callback method provided by angular-gridster2

Body:
I resolved the issue by below two steps:

Step1: by adding [ngStyle] to the <gridster>. It added responsive nature to grid-items:

<gridster [options]="options" [ngStyle]="{'width': toggled ? '100%' : 'auto'}">
   <gridster-item [item]="item" *ngFor="let item of dashboard">
      <!-- your content here -->
   </gridster-item>
</gridster>

Where toggled is a boolean value saying whether the side-bar toggled or not. Intial value is false.

Step2: To force items content(charts in my case) become responsive inside grid-items, I used the below code:

itemInitCallback: ((item: GridsterItem, itemComponent: GridsterItemComponentInterface) => {
    window.dispatchEvent(new Event('resize'));  // to reisize respective charts
})

Where itemInitCallback is an inbuilt gridEvent callback method provided by angular-gridster2


问:
Replication and memory leak
Memory leaks in weblogic server.

The memory of our server becomes saturated every day and we are called to make a daily reboot.
    In the code, there is nothing special that saturates the memory. However, a heap dump shows that the classes that occupy more memory are

```<code>weblogic.management.mbeanservers.internal.MBeanCICInterceptor (retained heap 5376058)
 and the weblogic.cluster.replication.ReplicationManager class (retained heap 2690546).
</code>```

weblogic.xml :

<session-descriptor>
      <cookie-name> OURPROJECT_SESSIONID </cookie-name>
      <persistent-store-type> replicated_if_clustered</persistent-store-type>

</session-descriptor>

Is it possible that the fact of putting in configuration in weblogic.xml can cause memory leaks?

答:
There is a know issue at Oracle with MBeanCICInterceptor which causes a memory leak with WebLogic Server 12.2.1.2
If you are running this version you can apply PSU 180717 and the apply path 27469756

If you are running another version open a SR at Oracle support.

Title: Replication and memory leak

Body:
Memory leaks in weblogic server.

The memory of our server becomes saturated every day and we are called to make a daily reboot.
    In the code, there is nothing special that saturates the memory. However, a heap dump shows that the classes that occupy more memory are

weblogic.management.mbeanservers.internal.MBeanCICInterceptor (retained heap 5376058)
 and the weblogic.cluster.replication.ReplicationManager class (retained heap 2690546).

weblogic.xml :

<session-descriptor>
      <cookie-name> OURPROJECT_SESSIONID </cookie-name>
      <persistent-store-type> replicated_if_clustered</persistent-store-type>

</session-descriptor>

Is it possible that the fact of putting in configuration in weblogic.xml can cause memory leaks?


问:
Conventional Routing doesn't deserialize json body requests (ASP.NET Core API)
Problem

Using ApiControllerAttribute and RouteAttribute on controllers and actions, everythings work fine.

When I change the code to work with Convetional Routing, the Identity property in request is always set to null.

Code with ApiControllerAttribute (Identity loaded in request)

```<code>[ApiController]
[Route("api/[controller]")]
Public Class Main : ControllerBase
{
    [HttpPost(nameof(GetExternalRemoteExternal))]
    public async Task<GetByIdentityResponse<RemoteExternal>> GetExternalRemoteExternal(GetByIdentityRequest<RemoteExternalIdentity> request)
    {
        return await GetExternal<RemoteExternal, RemoteExternalIdentity>(request);
    }
}
</code>```

startup.cs

```<code>app.UseEndpoints(endpoints => endpoints.MapControllers());
</code>```

Code with Convetional Routing (request has null Identity)

```<code>Public Class Main : ControllerBase
{
    [HttpPost]
    public async Task<GetByIdentityResponse<RemoteExternal>> GetExternalRemoteExternal(GetByIdentityRequest<RemoteExternalIdentity> request)
    {
        return await GetExternal<RemoteExternal, RemoteExternalIdentity>(request);
    }
}
</code>```

startup.cs

```<code>app.UseEndpoints(endpoints => endpoints.MapControllerRoute(
                                               name: "default",
                                               pattern: "api/{controller}/{action}")) //Not work even with "api/{controller}/{action}/{?id}"
</code>```

Common code

```<code>public class GetByIdentityRequest<TIDentity> : ServiceRequest
    where TIDentity : BaseIdentity
{
    public TIDentity Identity { get; set; }
}

public class RemoteExternalIdentity : BaseIdentity
{
    public int IdX { get; set; }
}
</code>```

JSON

{"$id":"1","Identity":{"$id":"2","IdX":10000}}

API LINK

.../api/Main/GetExternalRemoteExternal

答:
The [ApiController] attribute adds a few conventions to controllers that enables some opinionated behaviors, including binding source parameter inference that will make complex parameters bind from the body by default.

Since you cannot use the [ApiController] attribute with convention-based routing (since one of the convention is to prevent exactly that), you can use an explicit [FromBody] with your parameters to force them to be parsed from the JSON body:

```<code>public class Main : ControllerBase
{
    [HttpPost]
    public async Task<GetByIdentityResponse<RemoteExternal>> GetExternalRemoteExternal(
        [FromBody] GetByIdentityRequest<RemoteExternalIdentity> request)
    {
        return await GetExternal<RemoteExternal, RemoteExternalIdentity>(request);
    }
}
</code>```

Body:
Problem

Using ApiControllerAttribute and RouteAttribute on controllers and actions, everythings work fine.

When I change the code to work with Convetional Routing, the Identity property in request is always set to null.

Code with ApiControllerAttribute (Identity loaded in request)

[ApiController]
[Route("api/[controller]")]
Public Class Main : ControllerBase
{
    [HttpPost(nameof(GetExternalRemoteExternal))]
    public async Task<GetByIdentityResponse<RemoteExternal>> GetExternalRemoteExternal(GetByIdentityRequest<RemoteExternalIdentity> request)
    {
        return await GetExternal<RemoteExternal, RemoteExternalIdentity>(request);
    }
}

startup.cs

app.UseEndpoints(endpoints => endpoints.MapControllers());

Code with Convetional Routing (request has null Identity)

Public Class Main : ControllerBase
{
    [HttpPost]
    public async Task<GetByIdentityResponse<RemoteExternal>> GetExternalRemoteExternal(GetByIdentityRequest<RemoteExternalIdentity> request)
    {
        return await GetExternal<RemoteExternal, RemoteExternalIdentity>(request);
    }
}

startup.cs

app.UseEndpoints(endpoints => endpoints.MapControllerRoute(
                                               name: "default",
                                               pattern: "api/{controller}/{action}")) //Not work even with "api/{controller}/{action}/{?id}"

Common code

public class GetByIdentityRequest<TIDentity> : ServiceRequest
    where TIDentity : BaseIdentity
{
    public TIDentity Identity { get; set; }
}

public class RemoteExternalIdentity : BaseIdentity
{
    public int IdX { get; set; }
}

JSON

{"$id":"1","Identity":{"$id":"2","IdX":10000}}

API LINK

.../api/Main/GetExternalRemoteExternal

Body:
The [ApiController] attribute adds a few conventions to controllers that enables some opinionated behaviors, including binding source parameter inference that will make complex parameters bind from the body by default.

Since you cannot use the [ApiController] attribute with convention-based routing (since one of the convention is to prevent exactly that), you can use an explicit [FromBody] with your parameters to force them to be parsed from the JSON body:

public class Main : ControllerBase
{
    [HttpPost]
    public async Task<GetByIdentityResponse<RemoteExternal>> GetExternalRemoteExternal(
        [FromBody] GetByIdentityRequest<RemoteExternalIdentity> request)
    {
        return await GetExternal<RemoteExternal, RemoteExternalIdentity>(request);
    }
}


问:
how to overwrite initWithRootViewController
How can I overwrite the initWithRootViewController  method in a UINavigationController?

The only methods generated by xcode for me where methods suchs as loadFromNibName and loadView. These methods don't get called and I need to add an NSNotification to the navigationcontroller at startup.

I know it looks a little like the following but I don't know what put in the body of the method

```<code>- (id)initWithRootViewController:(UIViewController *)rootViewController

{
 // what goes here?
}
</code>```

EDIT
I guess the question really is "how do you customize a UIViewCOntroller during initialization"

Edit 2

My Navigation Controller header

```<code>@interface AccountViewNavigationController : UINavigationController {

}
@end
</code>```

Instantiating my UINavigationController Like so will result in no startup methods hitting break point

```<code>accountViewNavController = [[UINavigationController alloc] initWithRootViewController:accountView];
</code>```

Where as if I instantiate like so loadView does get called.... but it gets called numerous times

```<code>accountViewNavController = [[UINavigationController alloc] init];

[accountViewNavController initWithRootViewController:accountView NO];
</code>```

I'm highly confused by this stage.

答:
Use the same basic structure you use for overriding any other init method:

```<code>- (id)initWithRootViewController:(UIViewController *)rootViewController
{
    if ((self = [super initWithRootViewController:rootViewController])) {
        // Your modifications go here
    }
    return self;
}
</code>```

Do note that Apple claims UINavigationController is "not intended for subclassing", but they don't absolutely forbid it. I guess that means "don't try to change how the class works by messing with the internal message flow".

Body:
How can I overwrite the initWithRootViewController  method in a UINavigationController?

The only methods generated by xcode for me where methods suchs as loadFromNibName and loadView. These methods don't get called and I need to add an NSNotification to the navigationcontroller at startup.

I know it looks a little like the following but I don't know what put in the body of the method

- (id)initWithRootViewController:(UIViewController *)rootViewController

{
 // what goes here?
}

EDIT
I guess the question really is "how do you customize a UIViewCOntroller during initialization"

Edit 2

My Navigation Controller header

@interface AccountViewNavigationController : UINavigationController {

}
@end

Instantiating my UINavigationController Like so will result in no startup methods hitting break point

accountViewNavController = [[UINavigationController alloc] initWithRootViewController:accountView];

Where as if I instantiate like so loadView does get called.... but it gets called numerous times

accountViewNavController = [[UINavigationController alloc] init];

[accountViewNavController initWithRootViewController:accountView NO];

I'm highly confused by this stage.

Body:
Use the same basic structure you use for overriding any other init method:

- (id)initWithRootViewController:(UIViewController *)rootViewController
{
    if ((self = [super initWithRootViewController:rootViewController])) {
        // Your modifications go here
    }
    return self;
}

Do note that Apple claims UINavigationController is "not intended for subclassing", but they don't absolutely forbid it. I guess that means "don't try to change how the class works by messing with the internal message flow".


问:
Does Angular memoize inline *ngIf condition statements?
Does Angular memoize inline *ngIf condition statements? If I have for example:

```<code><form [formGroup]="form" *ngIf="inputModels.length < 200">
</code>```

is "inputModels.length < 200" recalculated every time change detection runs, or it's stored until inputModel changes?

答:
Yes, Angular take care of this for you!

This mechanism works because Angular generate a factory for every component.

A component factory mostly consists of the view nodes generated by the compiler as a result of template parsing.

Since a factory component is a large topic, I'll just stop at this function: updateRenderer

The updateRenderer take care about updating the component's DOM when needed.

Every component, by default, is added to a TreeRenderList, an array of objects. Angular use that array for a lot of things. The most important two feature, in my personal opinion, about that, are these two:

Update the component's DOM.

Update the component's binding when they change

Update the component's binding when they change, what does it mean?

Let's take an easy example to exaplain this.

```<code>    export class AppComponent {
      @Input() myInput: string;
    }

<p>{{myInput}}
</code>```

We know that eveytime myInput change we see the changes in the relative html (by default). And this works becasuse of the TreeRenderList and the updateRenderer function.

Can I prevent Angular to update the component's DOM?

Yep! and it's very easy. If we generate a component using the cli (ng g c component-name) it's decorator will be something like that:

```<code>@Component({
    selector: 'my-component',
    templateUrl: 'xxx.component.html',
    styleUrls: ['xxx.component.css'],
})
</code>```

But there a lot of properties we can specify. One of it is changeDetection.

By default Angular use the Default strategy, meaning that the framework will decide on how and when update the component's DOM.

We can change it to be OnPush. By doing that we are telling Angular that it doesn't need  to update the component's DOM on its logic. Adding this property to the decorator, will result like this:

```<code> @Component({
        changeDetection: ChangeDetectionStrategy.OnPush,
        selector: 'my-component',
        templateUrl: 'xxx.component.html',
        styleUrls: ['xxx.component.css'],
    })
</code>```

If we try now to update the @Input, we will not see any changes. That's where ChangeDetectionRef comes in our help. In orded to use it, we need to inject it into the component and we can use this.changeDetectionRef.detectChanges() to programmatically tell Angular to update the component's DOM.

I wrote an in-depth guide on ChangeDetectionRef here, if you want to read it: https://medium.com/@sciampi.jacopo/angular-performances-a-guide-to-change-detection-b8a02c0b7b00

Body:
Does Angular memoize inline *ngIf condition statements? If I have for example:

<form [formGroup]="form" *ngIf="inputModels.length < 200">

is "inputModels.length < 200" recalculated every time change detection runs, or it's stored until inputModel changes?

Body:
Yes, Angular take care of this for you!

This mechanism works because Angular generate a factory for every component.

A component factory mostly consists of the view nodes generated by the compiler as a result of template parsing.

Since a factory component is a large topic, I'll just stop at this function: updateRenderer

The updateRenderer take care about updating the component's DOM when needed.

Every component, by default, is added to a TreeRenderList, an array of objects. Angular use that array for a lot of things. The most important two feature, in my personal opinion, about that, are these two:

Update the component's DOM.

Update the component's binding when they change

Update the component's binding when they change, what does it mean?

Let's take an easy example to exaplain this.

    export class AppComponent {
      @Input() myInput: string;
    }

<p>{{myInput}}

We know that eveytime myInput change we see the changes in the relative html (by default). And this works becasuse of the TreeRenderList and the updateRenderer function.

Can I prevent Angular to update the component's DOM?

Yep! and it's very easy. If we generate a component using the cli (ng g c component-name) it's decorator will be something like that:

@Component({
    selector: 'my-component',
    templateUrl: 'xxx.component.html',
    styleUrls: ['xxx.component.css'],
})

But there a lot of properties we can specify. One of it is changeDetection.

By default Angular use the Default strategy, meaning that the framework will decide on how and when update the component's DOM.

We can change it to be OnPush. By doing that we are telling Angular that it doesn't need  to update the component's DOM on its logic. Adding this property to the decorator, will result like this:

 @Component({
        changeDetection: ChangeDetectionStrategy.OnPush,
        selector: 'my-component',
        templateUrl: 'xxx.component.html',
        styleUrls: ['xxx.component.css'],
    })

If we try now to update the @Input, we will not see any changes. That's where ChangeDetectionRef comes in our help. In orded to use it, we need to inject it into the component and we can use this.changeDetectionRef.detectChanges() to programmatically tell Angular to update the component's DOM.

I wrote an in-depth guide on ChangeDetectionRef here, if you want to read it: https://medium.com/@sciampi.jacopo/angular-performances-a-guide-to-change-detection-b8a02c0b7b00


问:
Error when installing chaincode - failed to calculate dependencies: incomplete package
I am try to installing Chaincode, follow the tutorial of hyperledger. But when I try to run the command

peer chaincode install -p chaincodedev/chaincode/sacc -n mycc -v 0

The terminal gives error message

Error: error getting chaincode deployment spec for mycc: error getting chaincode package bytes: failed to calculate dependencies: incomplete package: github.com/hyperledger/fabric-chaincode-go/shim

I see some other people got similar issue, but there is no answer yet. I am new to these stuffs, so any suggestions can be helpful.

答:
You don't say what version of Fabric and samples you are using, but this looks like a change that was made for Fabric 2.0 and described in the release notes "The shim package and dependencies for go chaincode are no longer included in
the chaincode build environment."

There is more detail in the associated Jira entry.


问:
Is mysql/mongodb cluster suitable for installation on kubernetes?
I used to test installed mongodb-shard on kubernetes by helm,but I found that those helm charts are not really a qualified mongodb shard.These helm charts can correctly create Pods with names like mongos-1 mongod-server-1 mongod-shard-1,this seems to be a correct shard cluster configuration, but the appropriate mongos, mongod server instance is not created on the corresponding Pod.They just create a normal mongod instance on the corresponding pod, and there is no connection between them.Do I need to add scripts to execute commands similar to rs.addShard(config)?Encountered the same problem when installing mysql cluster using helm.

What I want to know is, is it not appropriate to install mysql/mongodb cluster on kubernetes in general scenarios?Is the database installed independently or deployed on Kubernetes?

答:
Yes, you can deploy MongoDB instances on Kubernetes clusters.

Use standalone instance if you want to test and develop and replica set for production like deployments.

Also to make things easier you can use MongoDB Enterprise Kubernetes Operator:

The Operator enables easy deploys of MongoDB into Kubernetes clusters,
  using our management, monitoring and backup platforms, Ops Manager and
  Cloud Manager. By installing this integration, you will be able to
  deploy MongoDB instances with a single simple command.

This guide has references to the official MongoDB documentation with more necessary details regarding:

Install Kubernetes Operator

Deploy Standalone

Deploy Replica Set

Deploy Sharded Cluster

Edit Deployment

Kubernetes Resource Specification

Troubleshooting Kubernetes Operator

Known Issues for Kubernetes Operator

So basically all you need to know in this topic.

Please let me know if that helped.


问:
Change project name on Android Studio
I want to change the name of my project and module. But if I try to rename them Android Studio notify me some errors...

e.g. I want to change the name from "MyApplication" to "AndroidApp" as shown in the image below.

In the first rectangle I want to change it in:

AndroidApp ("G:...\Android\AndroidApp).

In the second rectangle I want to change it in:

AndroidApp [AndroidApp-AndroidApp]

edit: This is the log:

Gradle: Project 'AndroidApp' not found in root project 'MyApplicationProject'.

build.gradle:

```<code>buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.5.+'
    }
}
apply plugin: 'android'

repositories {
    mavenCentral()
}

android {
    compileSdkVersion 18
    buildToolsVersion "18.0.1"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 16
    }
}

dependencies {
    compile 'com.android.support:support-v4:18.0.0'
}
</code>```

settings.gradle:

```<code>include ':MyApplication'
</code>```

答:
Video tutorial: https://youtu.be/7aQjiae2doU

Refactor the name to com.example.[NewFileName] in path:

app>java>com.example.[OldFileName]

Go to strings.xml and change code to <string name="app_name”>[NewFileName]</string> in path:

app>res>values>strings.xml

Go to build.gradle (Module: app) and change code to applicationId "com.example.[NewFileName]” in path:

Gradle Scripts>build.gradle (Module: app)

Go to settings.gradle (Project Settings) and change code to rootProject.name='[NewFileName]' in path:

Gradle Scripts>build.gradle (Project Settings)

Press Sync now prompt

Rename your folder to [NewFileName] outside Android Studio

Reopen your project and rebuild project in path:

Build>Rebuild Project

Title: Change project name on Android Studio

Body:
I want to change the name of my project and module. But if I try to rename them Android Studio notify me some errors...

e.g. I want to change the name from "MyApplication" to "AndroidApp" as shown in the image below.

In the first rectangle I want to change it in:

AndroidApp ("G:...\Android\AndroidApp).

In the second rectangle I want to change it in:

AndroidApp [AndroidApp-AndroidApp]

edit: This is the log:

Gradle: Project 'AndroidApp' not found in root project 'MyApplicationProject'.

build.gradle:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.5.+'
    }
}
apply plugin: 'android'

repositories {
    mavenCentral()
}

android {
    compileSdkVersion 18
    buildToolsVersion "18.0.1"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 16
    }
}

dependencies {
    compile 'com.android.support:support-v4:18.0.0'
}

settings.gradle:

include ':MyApplication'