问:
TypeScript compiler complains about nulls when using isNull
When I have strictNullChecks: true in tsconfig.json and use isNull for null checks, the compiler throws the error TS2531: Object is possibly 'null'. isNull gets rid of the error in VsCode, but the compiler still complains when I'm trying to build and run my Angular app. If I use === null for null checks, no error.

Is there a way to tell the compiler to respect isNull as a valid null check?

```<code>import { isNull } from "util"; // from @types/node
    ...

    public run() {
        this.printS("hello");
        this.printS(null);
    }

    public printS(s: string | null) {
        if (isNull(s)) {
            console.log("s is null");
            return;
        }
        console.log("s is not null: ", s.toString()); // error on this line
    }
</code>```

```<code>"typescript": "~3.2.2"
"@types/node": "~8.9.4",
</code>```

答:
Yes, isNull() function is deprecated but if you already have used isNull() function many times in your code and if you don't want to change them everywhere, you can just make your own function named isNull() and use that function.</p>

```<code>function isNull(object:any){
           if(object === null){
               return true
               }
           else {
               return false
               }
           }
</code>```

Body:
When I have strictNullChecks: true in tsconfig.json and use isNull for null checks, the compiler throws the error TS2531: Object is possibly 'null'. isNull gets rid of the error in VsCode, but the compiler still complains when I'm trying to build and run my Angular app. If I use === null for null checks, no error.

Is there a way to tell the compiler to respect isNull as a valid null check?

import { isNull } from "util"; // from @types/node
    ...

    public run() {
        this.printS("hello");
        this.printS(null);
    }

    public printS(s: string | null) {
        if (isNull(s)) {
            console.log("s is null");
            return;
        }
        console.log("s is not null: ", s.toString()); // error on this line
    }

"typescript": "~3.2.2"
"@types/node": "~8.9.4",

Body:
Yes, isNull() function is deprecated but if you already have used isNull() function many times in your code and if you don't want to change them everywhere, you can just make your own function named isNull() and use that function.

function isNull(object:any){
           if(object === null){
               return true
               }
           else {
               return false
               }
           }


来源: stackexchange

问:
ORA-00926: missing VALUES keyword in create table
Hi I have following script to create table with partition and sub partition with Range and list:

```<code>CREATE TABLE C##API_USER.METERENERGY
(
  METERID NUMBER NOT NULL
, ENERGY_ACTIVE_EXPORT FLOAT(63)
, ENERGY_ACTIVE_IMPORT FLOAT(63)
, ENERGY_REACTIVE_EXPORT FLOAT(63)
, ENERGY_REACTIVE_IMPORT FLOAT(63)
, COL_G_DATE NUMBER(10)
)
LOGGING
TABLESPACE HEDC_TABLE_SPACE
PARTITION BY RANGE (COL_G_DATE)
SUBPARTITION BY LIST (METERID)
(
  PARTITION C##API_USER.COL_G_DATE_1483228800 VALUES LESS THAN (1483228800)        TABLESPACE HEDC_TABLE_SPACE
, PARTITION C##API_USER.COL_G_DATE_1485820800 VALUES LESS THAN (1485820800)     TABLESPACE HEDC_TABLE_SPACE
, PARTITION C##API_USER.COL_G_DATE_1488412800 VALUES LESS THAN (1488412800)     TABLESPACE HEDC_TABLE_SPACE
);

CREATE INDEX C##API_USER.METERENERGY_INDEX1 ON C##API_USER.METERENERGY (COL_G_DATE DESC, METERID ASC);

</code>```

but oracle databse show error Report :

```<code>
Error starting at line : 1 in command -

Error report -
ORA-00926: missing VALUES keyword
00926. 00000 -  "missing VALUES keyword"
*Cause:
*Action:

</code>```

so What I missing?(I'm using Oracle 19c with oracle sql Developer)
and if could you help me to find another answer Thanks:

(Oracle Database create automatic partition by range (long))

答:
Subpartitions are missing.

This is just an example; you'd use smart values.

```<code>SQL> CREATE TABLE meterenergy
  2  (
  3     meterid                 NUMBER NOT NULL,
  4     energy_active_export    FLOAT (63),
  5     energy_active_import    FLOAT (63),
  6     energy_reactive_export  FLOAT (63),
  7     energy_reactive_import  FLOAT (63),
  8     col_g_date              NUMBER (10)
  9  )
 10  PARTITION BY RANGE (col_g_date)
 11     SUBPARTITION BY LIST (meterid)
 12     (PARTITION col_g_date_1483228800 VALUES LESS THAN (1483228800)
 13         (SUBPARTITION sub1 VALUES (1),
 14          SUBPARTITION sub2 VALUES (2)
 15         ),
 16      PARTITION col_g_date_1485820800 VALUES LESS THAN (1485820800)
 17         (SUBPARTITION sub3 VALUES (3),
 18          SUBPARTITION sub4 VALUES (4)
 19         )
 20     );

Table created.

SQL>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Hi I have following script to create table with partition and sub partition with Range and list:

CREATE TABLE C##API_USER.METERENERGY
(
  METERID NUMBER NOT NULL
, ENERGY_ACTIVE_EXPORT FLOAT(63)
, ENERGY_ACTIVE_IMPORT FLOAT(63)
, ENERGY_REACTIVE_EXPORT FLOAT(63)
, ENERGY_REACTIVE_IMPORT FLOAT(63)
, COL_G_DATE NUMBER(10)
)
LOGGING
TABLESPACE HEDC_TABLE_SPACE
PARTITION BY RANGE (COL_G_DATE)
SUBPARTITION BY LIST (METERID)
(
  PARTITION C##API_USER.COL_G_DATE_1483228800 VALUES LESS THAN (1483228800)        TABLESPACE HEDC_TABLE_SPACE
, PARTITION C##API_USER.COL_G_DATE_1485820800 VALUES LESS THAN (1485820800)     TABLESPACE HEDC_TABLE_SPACE
, PARTITION C##API_USER.COL_G_DATE_1488412800 VALUES LESS THAN (1488412800)     TABLESPACE HEDC_TABLE_SPACE
);

CREATE INDEX C##API_USER.METERENERGY_INDEX1 ON C##API_USER.METERENERGY (COL_G_DATE DESC, METERID ASC);

but oracle databse show error Report :

Error starting at line : 1 in command -

Error report -
ORA-00926: missing VALUES keyword
00926. 00000 -  "missing VALUES keyword"
*Cause:
*Action:

so What I missing?(I'm using Oracle 19c with oracle sql Developer)
and if could you help me to find another answer Thanks:

(Oracle Database create automatic partition by range (long))

Body:
Subpartitions are missing.

This is just an example; you'd use smart values.

SQL> CREATE TABLE meterenergy
  2  (
  3     meterid                 NUMBER NOT NULL,
  4     energy_active_export    FLOAT (63),
  5     energy_active_import    FLOAT (63),
  6     energy_reactive_export  FLOAT (63),
  7     energy_reactive_import  FLOAT (63),
  8     col_g_date              NUMBER (10)
  9  )
 10  PARTITION BY RANGE (col_g_date)
 11     SUBPARTITION BY LIST (meterid)
 12     (PARTITION col_g_date_1483228800 VALUES LESS THAN (1483228800)
 13         (SUBPARTITION sub1 VALUES (1),
 14          SUBPARTITION sub2 VALUES (2)
 15         ),
 16      PARTITION col_g_date_1485820800 VALUES LESS THAN (1485820800)
 17         (SUBPARTITION sub3 VALUES (3),
 18          SUBPARTITION sub4 VALUES (4)
 19         )
 20     );

Table created.

SQL>


问:
Can a SOAP client in Java handle WCF message credential
Need to communicate from a Java platform with a SOAP server implemented in .NET with transport security and message credentials.

A working .net client has the following setups to talk to the server successfully:

```<code>X509Store store = new X509Store(StoreLocation.localMachine);
store.Open(...to load the cert..);
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential;
binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.Certificate;
binding.UseDefaultWebProxy = false;
...setting the proxy here ...
EndpointAddress endpoint = new Address(the end point);
ClientGenertedFromWSDL client = new ClientGenertedFromWSDL(binding, endpoint);

... setting other stuffs...

client.ClientCredentials.ClientCertificate.SetCertificate(cert suject name, store.Location, StoreName.My);

...client does something...
</code>```

I have tried using axis1 that comes with eclipse to generate client code, but I don't see there are obvious methods (within xxxLocator where xxx is the service specified in the WSDL, or anywhere related) to handle things similar to WCF message security.

I seem to have successfully set transport level security by doing like

```<code>System.setProperty("javax.net.ssl.keyStore", certFilePath);
...

</code>```

and I can see client/server ssl hand shaking in the debug log, yet it gets 400 Bad Request back. BTW, I can capture SOAP request and response from the binding (from xxxLocator), and the request sent is exactly the same as the one the .net client sent.

I know there are many ways to generate Java stub/code from a WSDL, for instance axis1, axis2, JAX_WS, ...

My question is: does Java, with some Java tool, have the capability of handling WCF message security with certificate? If yes, which one and how?

答:
There is always a solution. Although this type of communication may not be as easily used in Java as in .Net there is a way to achieve this with CXF and WS-Security.

There at least 2 approaches to do this. With policy element embedded in wsdl file  or with manually defined interceptors. I will show here first approach but is shouldn't be hard to find the second one in mentioned docs.

Add appropriate tag (Policy) in your wsdl file you need secured with https with message credentials. The one presented below will add a timestamp to your request and signed it.

```<code><?xml version="1.0" encoding="utf-8"?>
<wsdl:definitions xmlns:tns="uri://someservice.com/" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl"
                  xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
                  xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
                  xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
                  xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="SomeService"
                  targetNamespace="uri://someservice.com/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
    <wsp:Policy wsu:Id="BasicHttpBinding_SomeService_policy">
        <wsp:ExactlyOne>
            <wsp:All>
                <sp:TransportBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                    <wsp:Policy>
                        <sp:TransportToken>
                            <wsp:Policy>
                                <sp:HttpsToken RequireClientCertificate="false"/>
                            </wsp:Policy>
                        </sp:TransportToken>
                        <sp:AlgorithmSuite>
                            <wsp:Policy>
                                <sp:Basic256/>
                            </wsp:Policy>
                        </sp:AlgorithmSuite>
                        <sp:Layout>
                            <wsp:Policy>
                                <sp:Lax/>
                            </wsp:Policy>
                        </sp:Layout>
                        <sp:IncludeTimestamp/>
                    </wsp:Policy>
                </sp:TransportBinding>
                <sp:EndorsingSupportingTokens xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                    <wsp:Policy>
                        <sp:X509Token
                                sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient">
                            <wsp:Policy>
                                <sp:WssX509V3Token10/>
                            </wsp:Policy>
                        </sp:X509Token>
                    </wsp:Policy>
                </sp:EndorsingSupportingTokens>
                <sp:Wss10 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                    <wsp:Policy>
                        <sp:MustSupportRefKeyIdentifier/>
                        <sp:MustSupportRefIssuerSerial/>
                    </wsp:Policy>
                </sp:Wss10>
                <sp:SignedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                    <sp:Header
                            Namespace="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
                            Name="Timestamp"/>
                </sp:SignedParts>
            </wsp:All>
        </wsp:ExactlyOne>
    </wsp:Policy>
    ...
</wsdl:definitions>
</code>```

Added dependencies to ws-security modules

```<code><dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-ws-security</artifactId>
    <version>${cxf.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-ws-security</artifactId>
    <version>${cxf.version}</version>
</dependency>
</code>```

Generate stubs using maven cxf-codegen-plugin

```<code><plugin>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-codegen-plugin</artifactId>
    <version>${cxf.version}</version>
    <executions>
        <execution>
            <id>generate-sources</id>
            <phase>generate-sources</phase>
            <configuration>
                <sourceRoot>${project.build.directory}/generated-sources/cxf</sourceRoot>
                <wsdlOptions>
                    <wsdlOption>
                        <wsdl>src/main/resources/wsdl/SomeService.wsdl</wsdl>
                        <wsdlLocation>classpath:wsdl/SomeService.wsdl</wsdlLocation>
                    </wsdlOption>
                </wsdlOptions>
            </configuration>
            <goals>
                <goal>wsdl2java</goal>
            </goals>
        </execution>
    </executions>
</plugin>
</code>```

Create properties file with configuration of key you want to use. You have to specify there keystore used. In example this file is named tls.propreties and is placed under /someservice/config/ directory.

```<code>org.apache.ws.security.crypto.provider=org.apache.ws.security.components.crypto.Merlin
org.apache.ws.security.crypto.merlin.keystore.file=/someservice/config/someservice.jks
org.apache.ws.security.crypto.merlin.keystore.password=qwe123
org.apache.ws.security.crypto.merlin.keystore.type=jks
org.apache.ws.security.crypto.merlin.keystore.alias=someservice
</code>```

Create callback which will provide password to keys in your jks. Below I present the simplest possible implementation providing the same password for all key names.

```<code>private class KeystorePasswordCallback implements CallbackHandler {
    public void handle(Callback[] callbacks) {
        for (Callback callback : callbacks) {
            WSPasswordCallback pc = (WSPasswordCallback) callback;
            pc.setPassword("password");
        }
    }
}
</code>```

Enchance your port with properties telling it how to secure message. When using with spring I tend to wrap this enhanced port as a bean and later just inject it, so I don't have to configure it every time it is used.

```<code>
@Bean
SomeService vehiclePricingGatewayService() {
    // this 2 below are classes genarated from our wsdl file
    SomeService_Service vpgService = new SomeService();
    SomeService port = vpgService.getBasicHttpBindingSomeService();

   Map<String, Object> requestContext = ((BindingProvider) port).getRequestContext();

    // add wssecurity keystore configuration properties
    try {
        requestContext.put("ws-security.signature.properties",
                Paths.get("/someservice/config/tls.properties").toUri().toURL());
        requestContext.put("ws-security.encryption.properties",
                Paths.get("/someservice/config/tls.properties").toUri().toURL());
    } catch (MalformedURLException e) {
        log.error("Error while reading tls properties", e);
    }

    // add alias of key from keystore which should be used
    requestContext.put("ws-security.signature.username", "someservice");
    requestContext.put("ws-security.encryption.username", "someservice");

    // we add callback whioch will provide password for used key
    requestContext.put("ws-security.callback-handler", new KeystorePasswordCallback());

    // additional properties
    requestContext.put("schema-validation-enabled", false);
    requestContext.put("set-jaxb-validation-event-handler", false);

    return port;
}
</code>```

[OPTIONAL] If not using default Trustore you may want to set it with those jvm args

```<code>-Djavax.ssl.net.trustStore=/someservice/config/cacerts -Djavax.ssl.net.trustStorePassword=changeit
</code>```

I suppose there may be more ways to configure such communication but It was the one I found, used and succeeded with.

Mind that this is only client configuration. If you would like to act like a server in this form of communication (you need to verify incoming signature) it is also easily configurable with wss4j interceptors which can be appliad to cxf soap enpoint as well as spring-ws endpoint.

Body:
Need to communicate from a Java platform with a SOAP server implemented in .NET with transport security and message credentials.

A working .net client has the following setups to talk to the server successfully:

X509Store store = new X509Store(StoreLocation.localMachine);
store.Open(...to load the cert..);
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential;
binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.Certificate;
binding.UseDefaultWebProxy = false;
...setting the proxy here ...
EndpointAddress endpoint = new Address(the end point);
ClientGenertedFromWSDL client = new ClientGenertedFromWSDL(binding, endpoint);

... setting other stuffs...

client.ClientCredentials.ClientCertificate.SetCertificate(cert suject name, store.Location, StoreName.My);

...client does something...

I have tried using axis1 that comes with eclipse to generate client code, but I don't see there are obvious methods (within xxxLocator where xxx is the service specified in the WSDL, or anywhere related) to handle things similar to WCF message security.

I seem to have successfully set transport level security by doing like

System.setProperty("javax.net.ssl.keyStore", certFilePath);
...

and I can see client/server ssl hand shaking in the debug log, yet it gets 400 Bad Request back. BTW, I can capture SOAP request and response from the binding (from xxxLocator), and the request sent is exactly the same as the one the .net client sent.

I know there are many ways to generate Java stub/code from a WSDL, for instance axis1, axis2, JAX_WS, ...

My question is: does Java, with some Java tool, have the capability of handling WCF message security with certificate? If yes, which one and how?

Body:
There is always a solution. Although this type of communication may not be as easily used in Java as in .Net there is a way to achieve this with CXF and WS-Security.

There at least 2 approaches to do this. With policy element embedded in wsdl file  or with manually defined interceptors. I will show here first approach but is shouldn't be hard to find the second one in mentioned docs.

Add appropriate tag (Policy) in your wsdl file you need secured with https with message credentials. The one presented below will add a timestamp to your request and signed it.

<?xml version="1.0" encoding="utf-8"?>
<wsdl:definitions xmlns:tns="uri://someservice.com/" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl"
                  xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
                  xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
                  xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
                  xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="SomeService"
                  targetNamespace="uri://someservice.com/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
    <wsp:Policy wsu:Id="BasicHttpBinding_SomeService_policy">
        <wsp:ExactlyOne>
            <wsp:All>
                <sp:TransportBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                    <wsp:Policy>
                        <sp:TransportToken>
                            <wsp:Policy>
                                <sp:HttpsToken RequireClientCertificate="false"/>
                            </wsp:Policy>
                        </sp:TransportToken>
                        <sp:AlgorithmSuite>
                            <wsp:Policy>
                                <sp:Basic256/>
                            </wsp:Policy>
                        </sp:AlgorithmSuite>
                        <sp:Layout>
                            <wsp:Policy>
                                <sp:Lax/>
                            </wsp:Policy>
                        </sp:Layout>
                        <sp:IncludeTimestamp/>
                    </wsp:Policy>
                </sp:TransportBinding>
                <sp:EndorsingSupportingTokens xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                    <wsp:Policy>
                        <sp:X509Token
                                sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient">
                            <wsp:Policy>
                                <sp:WssX509V3Token10/>
                            </wsp:Policy>
                        </sp:X509Token>
                    </wsp:Policy>
                </sp:EndorsingSupportingTokens>
                <sp:Wss10 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                    <wsp:Policy>
                        <sp:MustSupportRefKeyIdentifier/>
                        <sp:MustSupportRefIssuerSerial/>
                    </wsp:Policy>
                </sp:Wss10>
                <sp:SignedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                    <sp:Header
                            Namespace="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
                            Name="Timestamp"/>
                </sp:SignedParts>
            </wsp:All>
        </wsp:ExactlyOne>
    </wsp:Policy>
    ...
</wsdl:definitions>

Added dependencies to ws-security modules

<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-ws-security</artifactId>
    <version>${cxf.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-ws-security</artifactId>
    <version>${cxf.version}</version>
</dependency>

Generate stubs using maven cxf-codegen-plugin

<plugin>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-codegen-plugin</artifactId>
    <version>${cxf.version}</version>
    <executions>
        <execution>
            <id>generate-sources</id>
            <phase>generate-sources</phase>
            <configuration>
                <sourceRoot>${project.build.directory}/generated-sources/cxf</sourceRoot>
                <wsdlOptions>
                    <wsdlOption>
                        <wsdl>src/main/resources/wsdl/SomeService.wsdl</wsdl>
                        <wsdlLocation>classpath:wsdl/SomeService.wsdl</wsdlLocation>
                    </wsdlOption>
                </wsdlOptions>
            </configuration>
            <goals>
                <goal>wsdl2java</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Create properties file with configuration of key you want to use. You have to specify there keystore used. In example this file is named tls.propreties and is placed under /someservice/config/ directory.

org.apache.ws.security.crypto.provider=org.apache.ws.security.components.crypto.Merlin
org.apache.ws.security.crypto.merlin.keystore.file=/someservice/config/someservice.jks
org.apache.ws.security.crypto.merlin.keystore.password=qwe123
org.apache.ws.security.crypto.merlin.keystore.type=jks
org.apache.ws.security.crypto.merlin.keystore.alias=someservice

Create callback which will provide password to keys in your jks. Below I present the simplest possible implementation providing the same password for all key names.

private class KeystorePasswordCallback implements CallbackHandler {
    public void handle(Callback[] callbacks) {
        for (Callback callback : callbacks) {
            WSPasswordCallback pc = (WSPasswordCallback) callback;
            pc.setPassword("password");
        }
    }
}

Enchance your port with properties telling it how to secure message. When using with spring I tend to wrap this enhanced port as a bean and later just inject it, so I don't have to configure it every time it is used.

@Bean
SomeService vehiclePricingGatewayService() {
    // this 2 below are classes genarated from our wsdl file
    SomeService_Service vpgService = new SomeService();
    SomeService port = vpgService.getBasicHttpBindingSomeService();

   Map<String, Object> requestContext = ((BindingProvider) port).getRequestContext();

    // add wssecurity keystore configuration properties
    try {
        requestContext.put("ws-security.signature.properties",
                Paths.get("/someservice/config/tls.properties").toUri().toURL());
        requestContext.put("ws-security.encryption.properties",
                Paths.get("/someservice/config/tls.properties").toUri().toURL());
    } catch (MalformedURLException e) {
        log.error("Error while reading tls properties", e);
    }

    // add alias of key from keystore which should be used
    requestContext.put("ws-security.signature.username", "someservice");
    requestContext.put("ws-security.encryption.username", "someservice");

    // we add callback whioch will provide password for used key
    requestContext.put("ws-security.callback-handler", new KeystorePasswordCallback());

    // additional properties
    requestContext.put("schema-validation-enabled", false);
    requestContext.put("set-jaxb-validation-event-handler", false);

    return port;
}

[OPTIONAL] If not using default Trustore you may want to set it with those jvm args

-Djavax.ssl.net.trustStore=/someservice/config/cacerts -Djavax.ssl.net.trustStorePassword=changeit

I suppose there may be more ways to configure such communication but It was the one I found, used and succeeded with.

Mind that this is only client configuration. If you would like to act like a server in this form of communication (you need to verify incoming signature) it is also easily configurable with wss4j interceptors which can be appliad to cxf soap enpoint as well as spring-ws endpoint.


问:
Using moment.js to determine if current time (in hour) is between certain hours
I am working on a function that'd greet its users with a time-aware greeting (Good Morning, Afternoon, Evening, Night). Here's the script that I've made

```<code>import moment from "moment";

function generateGreetings(){
    if (moment().isBetween(3, 12, 'HH')){
        return "Good Morning";
    } else if (moment().isBetween(12, 15, 'HH')){
        return "Good Afternoon";
    }   else if (moment().isBetween(15, 20, 'HH')){
        return "Good Evening";
    } else if (moment().isBetween(20, 3, 'HH')){
        return "Good Night";
    } else {
        return "Hello"
    }
}

$("greet")
.css({
    display: "block",
    fontSize: "4vw",
    textAlign: "center",
    })
.text(generateGreetings() +", name")
</code>```

But it simply wont work and just returns "Hello". I've also tried using

```<code>var currentTime = moment();
var currentHour = currentTime.hour();
</code>```

and use currentHour to replace moment() inside the function but when I do so the site just dissapears.
Hoping anyone here has any insight on what I should do to fix this issue.

答:
You are using moment().isBetween() in a wrong way. You can see the correct method usage from here. For your requirement, no need to use this isBetween method. You can simply get the hour and then check it against the if condition.

You can re-arrange your method like below.

```<code>function generateGreetings(){

  var currentHour = moment().format("HH");

  if (currentHour >= 3 && currentHour < 12){
      return "Good Morning";
  } else if (currentHour >= 12 && currentHour < 15){
      return "Good Afternoon";
  }   else if (currentHour >= 15 && currentHour < 20){
      return "Good Evening";
  } else if (currentHour >= 20 || currentHour < 3){
      return "Good Night";
  } else {
      return "Hello"
  }

}
</code>```

Body:
I am working on a function that'd greet its users with a time-aware greeting (Good Morning, Afternoon, Evening, Night). Here's the script that I've made

import moment from "moment";

function generateGreetings(){
    if (moment().isBetween(3, 12, 'HH')){
        return "Good Morning";
    } else if (moment().isBetween(12, 15, 'HH')){
        return "Good Afternoon";
    }   else if (moment().isBetween(15, 20, 'HH')){
        return "Good Evening";
    } else if (moment().isBetween(20, 3, 'HH')){
        return "Good Night";
    } else {
        return "Hello"
    }
}

$("greet")
.css({
    display: "block",
    fontSize: "4vw",
    textAlign: "center",
    })
.text(generateGreetings() +", name")

But it simply wont work and just returns "Hello". I've also tried using

var currentTime = moment();
var currentHour = currentTime.hour();

and use currentHour to replace moment() inside the function but when I do so the site just dissapears.
Hoping anyone here has any insight on what I should do to fix this issue.

Body:
You are using moment().isBetween() in a wrong way. You can see the correct method usage from here. For your requirement, no need to use this isBetween method. You can simply get the hour and then check it against the if condition.

You can re-arrange your method like below.

function generateGreetings(){

  var currentHour = moment().format("HH");

  if (currentHour >= 3 && currentHour < 12){
      return "Good Morning";
  } else if (currentHour >= 12 && currentHour < 15){
      return "Good Afternoon";
  }   else if (currentHour >= 15 && currentHour < 20){
      return "Good Evening";
  } else if (currentHour >= 20 || currentHour < 3){
      return "Good Night";
  } else {
      return "Hello"
  }

}


问:
Select the First value Greater than a specific value
I have two tables first table is Stock Receiving

```<code>  Store   Item_No        Receiving_Time

   2       1         2020-05-27 13:44:27.829 UTC
   2       1         2020-05-27 17:44:28.829 UTC
   2       1         2020-05-28 14:44:28.829 UTC
   2       1         2020-05-29 14:44:28.829 UTC
</code>```

Second one is item going Out of Stock

```<code>   Store   Item_No        Out_OF_Stock_Time

       2       1         2020-05-26 13:44:27.829 UTC
       2       1         2020-05-27 18:44:28.829 UTC
       2       1         2020-05-27 20:44:28.829 UTC
</code>```

So i want to find the value when the last out of stock was filled in my case last out of stock happens on 2020-05-27 20:44:28.829 UTC so output value should be 2020-05-28 14:44:28.829 UTC
from Stock Receiving Table

SO output:

```<code>Store Item_No.    Last_OutOfStock.              Received Time                   Difference Time
2.      1        2020-05-27 20:44:28.829 UTC    2020-05-28 14:44:28.829 UTC
</code>```

My Query:

```<code>Select  o.store, o.item_No, Max(o.Out_OF_Stock_Time) as S, Min(r.Receiving_Time) as R
from Out_of_Stock o
join Stock_Receiving r on o.store = r.store and o.item_no = r.item_no
and S < R
group By o.store, o.item_No;
</code>```

So it's not getting me the right result.

答:
If Oracle you can do it like this:

```<code>with cte as(select o.store
                   , o.item_No
                   , Max(o.Out_OF_Stock_Time) as S
            from Out_of_Stock o
            group By o.store, o.item_No)
select distinct cte.store
       , cte.item_No
       , cte.S "Last_OutOfStock"
       , first_value(r.Receiving_Time) over (order by r.Receiving_Time asc) "Received Time"
from cte
join Stock_Receiving r on cte.store = r.store and cte.item_no = r.item_no
where r.Receiving_Time > cte.S;
</code>```

here is a demo

Body:
I have two tables first table is Stock Receiving

  Store   Item_No        Receiving_Time

   2       1         2020-05-27 13:44:27.829 UTC
   2       1         2020-05-27 17:44:28.829 UTC
   2       1         2020-05-28 14:44:28.829 UTC
   2       1         2020-05-29 14:44:28.829 UTC

Second one is item going Out of Stock

   Store   Item_No        Out_OF_Stock_Time

       2       1         2020-05-26 13:44:27.829 UTC
       2       1         2020-05-27 18:44:28.829 UTC
       2       1         2020-05-27 20:44:28.829 UTC

So i want to find the value when the last out of stock was filled in my case last out of stock happens on 2020-05-27 20:44:28.829 UTC so output value should be 2020-05-28 14:44:28.829 UTC
from Stock Receiving Table

SO output:

Store Item_No.    Last_OutOfStock.              Received Time                   Difference Time
2.      1        2020-05-27 20:44:28.829 UTC    2020-05-28 14:44:28.829 UTC

My Query:

Select  o.store, o.item_No, Max(o.Out_OF_Stock_Time) as S, Min(r.Receiving_Time) as R
from Out_of_Stock o
join Stock_Receiving r on o.store = r.store and o.item_no = r.item_no
and S < R
group By o.store, o.item_No;

So it's not getting me the right result.

Body:
If Oracle you can do it like this:

with cte as(select o.store
                   , o.item_No
                   , Max(o.Out_OF_Stock_Time) as S
            from Out_of_Stock o
            group By o.store, o.item_No)
select distinct cte.store
       , cte.item_No
       , cte.S "Last_OutOfStock"
       , first_value(r.Receiving_Time) over (order by r.Receiving_Time asc) "Received Time"
from cte
join Stock_Receiving r on cte.store = r.store and cte.item_no = r.item_no
where r.Receiving_Time > cte.S;

here is a demo


问:
Is it possible to pass through a backend url endpoint that is relative to that url through an Azure Function Proxy or perhaps api management
As of now, from what I see, the only way to use Azure Function Proxy is to re-route an existing api is to call upon that api directly. For example:

Backend URL

https://gateway-api.com/api/getSomething

Route Template

/api

Proxy URL

https://gateway.azurewebsites.net/api

What I want is to have the Backend URL pass through any endpoint relative to the main endpoint.

Effectively this:

Backend URL

https://gateway-api.com/* or i even tried this https://gateway-api.com/{*restOfPath}

This way, any api's that follow the core domain URL will still work as expected.

Here is a re-write of the example above:

Backend URL 2

https://gateway-api.com/*

Route Template 2

/*

Proxy URL 2

https://gateway.azurewebsites.net/api/getSomething

When I do this I can't get it to work or even reach the debuger to log anything.

Is this possible and if not would this be something Azure API Management would be able to accomplish?

答:
Can you provide your configuration file? this is mine:

Proxies.json:

```<code>{
  "$schema": "http://json.schemastore.org/proxies",
  "proxies": {
    "proxy1": {
      "matchCondition": {
        "methods": [ "GET" ],
        "route": "/{test}"
      },
      "backendUri": "http://localhost:7071/abc/Function1"
    }
  }
}
</code>```

host.json:

```<code>{
  "version": "2.0",
  "extensions": {
    "http": {
      "routePrefix": "abc"
    }
  },
  "logging": {
    "applicationInsights": {
      "samplingExcludedTypes": "Request",
      "samplingSettings": {
        "isEnabled": true
      }
    }
  }
}
</code>```

This is the backend url and proxy of my function:

Both of them works fine.

If you change route template, I think the backend url will not have /api unless you give the /api to routePrefix.

Any way, please show the file about how to configure proxy and route template.

Body:
Can you provide your configuration file? this is mine:

Proxies.json:

{
  "$schema": "http://json.schemastore.org/proxies",
  "proxies": {
    "proxy1": {
      "matchCondition": {
        "methods": [ "GET" ],
        "route": "/{test}"
      },
      "backendUri": "http://localhost:7071/abc/Function1"
    }
  }
}

host.json:

{
  "version": "2.0",
  "extensions": {
    "http": {
      "routePrefix": "abc"
    }
  },
  "logging": {
    "applicationInsights": {
      "samplingExcludedTypes": "Request",
      "samplingSettings": {
        "isEnabled": true
      }
    }
  }
}

This is the backend url and proxy of my function:

Both of them works fine.

If you change route template, I think the backend url will not have /api unless you give the /api to routePrefix.

Any way, please show the file about how to configure proxy and route template.


问:
Xamarin forms TabbedPage icons are tiny
Using a TabbedPage with five tabs, though the issue is the same with only two, I see the rendered icons being very small, as shown in this image, using some placeholder graphics.

I have tried images at all pixel resolutions from 32x32 to 512x512 and they all render the same size. You would expect an option to set this, but when looking for solutions, it seems to always boil down to making custom renderes. I have not seen anyone complaining about tiny icons, though, but generally more complex issues, so I am still hoping for a generalized forms solution.

In the screenshot (android on device) I use a master detail page to give a toolbar and left menu, but the issue is the same when I have a clean TabbedPage on its own.

The definition of the TabbedPage is trivial, so I doubt there is any issue there

```<code><?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            xmlns:d="http://xamarin.com/schemas/2014/forms/design"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            mc:Ignorable="d"
            xmlns:views="clr-namespace:CloudDash.Views"
            x:Class="CloudDash.Views.TabPage">

    <TabbedPage.Children>
        <views:ThermalingPage IconImageSource="fly.png"/>
        <views:DataPage IconImageSource="fly.png"/>
        <views:FlightPage IconImageSource="fly.png"/>
        <views:RoutePage IconImageSource="fly.png"/>
        <views:AwarenessPage IconImageSource="fly.png"/>
    </TabbedPage.Children>

</TabbedPage>
</code>```

答:
In this particular case would recommend to use Sharpnado.Presentation.Forms nuget, you can customize your tabs at will:

https://github.com/roubachof/Sharpnado.Presentation.Forms

Title: Xamarin forms TabbedPage icons are tiny

Body:
Using a TabbedPage with five tabs, though the issue is the same with only two, I see the rendered icons being very small, as shown in this image, using some placeholder graphics.

I have tried images at all pixel resolutions from 32x32 to 512x512 and they all render the same size. You would expect an option to set this, but when looking for solutions, it seems to always boil down to making custom renderes. I have not seen anyone complaining about tiny icons, though, but generally more complex issues, so I am still hoping for a generalized forms solution.

In the screenshot (android on device) I use a master detail page to give a toolbar and left menu, but the issue is the same when I have a clean TabbedPage on its own.

The definition of the TabbedPage is trivial, so I doubt there is any issue there

<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            xmlns:d="http://xamarin.com/schemas/2014/forms/design"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            mc:Ignorable="d"
            xmlns:views="clr-namespace:CloudDash.Views"
            x:Class="CloudDash.Views.TabPage">

    <TabbedPage.Children>
        <views:ThermalingPage IconImageSource="fly.png"/>
        <views:DataPage IconImageSource="fly.png"/>
        <views:FlightPage IconImageSource="fly.png"/>
        <views:RoutePage IconImageSource="fly.png"/>
        <views:AwarenessPage IconImageSource="fly.png"/>
    </TabbedPage.Children>

</TabbedPage>


问:
In CI, I want to login 3 different usr Role's acount present in 3 different db table's of my db namd as m_admin,, m_faculty ,m_supervisior
In code igniter I want to login 3 different user's of different roles from one login page whose username and passwords are presented in different database table using "if elseif & else" in my controller i think that if form validation is true than it will go to if and when if is not correct it will go to elseif and if it doesn't work then it will go to third one i.e m_faculty and if it also don work then it will show alert that u have inserted wrong id and password by this if else I'm able to redirect to go to "faculty/m_dashboard" only that is my faculty dashboard other redirections are not working any when know why its not working or any better way to do this ..........?????</p>
```<code>public function Auth()
{
    $rules = array(
        array('field' => 'username', 'label' => 'Username', 'rules' => 'required'),
        array('field' => 'password', 'label' => 'Password', 'rules' => 'required'),
    );

    $this->form_validation->set_rules($rules);
    if ($this->form_validation->run() == false) {
        $Msg = array('Msg' => validation_errors(), 'Type' => 'danger');
        $this->session->set_flashdata($Msg);
        redirect(base_url() . 'Admin/');
    }

    # faculty dashboard dashboard

    elseif ($this->form_validation->run() == true)
    {
        $username = $this->lib->validate($this->input->post('username'));
        $password = $this->lib->validate($this->input->post('password'));

        $username = $this->security->xss_clean($username);
        $password = $this->security->xss_clean($password);
        $count = $this->lib_model->Counter('m_faculty', array('username' => $username, 'password' => $password, 'status' => 0));

        if ($count == 1) {
            $Sessions = array(
                'EmpCode' => $username,
                'EmpName' => 'Administration',
                'ELogin' => true);
            $this->session->set_userdata($Sessions);

            $Msg = array('Msg' => ' Have a Nice Day ', 'Type' => 'success');
            $this->session->set_flashdata($Msg);
            redirect(base_url() . 'Faculty/f_dashboard');

        }
    }

    #supervisior dashboard

    elseif ($this->form_validation->run() == true)
    {

        $username = $this->lib->validate($this->input->post('username'));
        $password = $this->lib->validate($this->input->post('password'));

        $username = $this->security->xss_clean($username);
        $password = $this->security->xss_clean($password);
        $count = $this->lib_model->Counter('m_supervisior', array('username' => $username, 'password' => $password, 'status' => 0));

        if ($count == 1) {
            $Sessions = array(
                'EmpCode' => $username,
                'EmpName' => 'Administration',
                'ELogin' => true);
            $this->session->set_userdata($Sessions);

            $Msg = array('Msg' => ' Have a Nice Day ', 'Type' => 'success');
            $this->session->set_flashdata($Msg);
            redirect(base_url() . 'Supervisior/supervisior_dashboard');
        }
   }

    #admin dashboard

    elseif ($this->form_validation->run() == true)
    {
        $username = $this->lib->validate($this->input->post('username'));
        $password = $this->lib->validate($this->input->post('password'));

        $username = $this->security->xss_clean($username);
        $password = $this->security->xss_clean($password);
        $count = $this->lib_model->Counter('m_admin', array('username' => $username, 'password' => $password, 'status' => 0));

        if ($count == 1) {
            $Sessions = array(
                'EmpCode' => $username,
                'EmpName' => 'Administration',
                'ELogin' => true);
            $this->session->set_userdata($Sessions);

            $Msg = array('Msg' => ' Have a Nice Day ', 'Type' => 'success');
            $this->session->set_flashdata($Msg);
            redirect(base_url() . 'Admin/dashboard');
        }
    }

#error msg

    else {
        $Msg = array('Msg' => 'Username and Password Invalid', 'Type' => 'danger');
        $this->session->set_flashdata($Msg);
        redirect(base_url() . 'Admin/');
    }

}
</code>```

答:
your code won't work because after the first validation check it will always get stuck in your first else clause.

I'm not sure what exactly you are doing here - but a possible approach would be

```<code>public function Auth()
{

    try
    {
        $rules = array(
            array('field' => 'username', 'label' => 'Username', 'rules' => 'required'),
            array('field' => 'password', 'label' => 'Password', 'rules' => 'required'),
        );
        $this->form_validation->set_rules($rules);
        if (!$this->form_validation->run()) throw new Exception(validation_errors());

        $username = $this->lib->validate($this->input->post('username'));
        $password = $this->lib->validate($this->input->post('password'));

        $arrAuthenticationTypes = [
            [
                'table' => 'm_faculty',
                'view' => 'Faculty/f_dashboard'
            ],
            [
                'table' => 'm_supervisior',
                'view' => 'Supervisior/supervisior_dashboard'
            ],
            [
                'table' => 'm_admin',
                'view' => 'Admin/dashboard'
            ],
        ];

        foreach($arrAuthenticationTypes AS $arrAuthenticationType)
        {
            $count = $this->lib_model->Counter($arrAuthenticationType['table'], array('username' => $username, 'password' => $password, 'status' => 0));
            if ($count == 1)
            {
                $Sessions = array(
                    'EmpCode' => $username,
                    'EmpName' => 'Administration',
                    'ELogin' => true
                );
                $this->session->set_userdata($Sessions);
                $Msg = array('Msg' => ' Have a Nice Day ', 'Type' => 'success');
                $this->session->set_flashdata($Msg);
                redirect(base_url() . $arrAuthenticationType['view']);
            }
        }

        throw new Exception('Username and Password Invalid');
    }
    catch(\Exception $e)
    {
        $arrMessage = [
            'Msg' => $e->getMessage(),
            'Type' => 'danger'
        ];
        $this->session->set_flashdata($Msg);
        redirect(base_url() . 'Admin/');
    }
}
</code>```

Body:
In code igniter I want to login 3 different user's of different roles from one login page whose username and passwords are presented in different database table using "if elseif & else" in my controller i think that if form validation is true than it will go to if and when if is not correct it will go to elseif and if it doesn't work then it will go to third one i.e m_faculty and if it also don work then it will show alert that u have inserted wrong id and password by this if else I'm able to redirect to go to "faculty/m_dashboard" only that is my faculty dashboard other redirections are not working any when know why its not working or any better way to do this ..........?????

public function Auth()
{
    $rules = array(
        array('field' => 'username', 'label' => 'Username', 'rules' => 'required'),
        array('field' => 'password', 'label' => 'Password', 'rules' => 'required'),
    );

    $this->form_validation->set_rules($rules);
    if ($this->form_validation->run() == false) {
        $Msg = array('Msg' => validation_errors(), 'Type' => 'danger');
        $this->session->set_flashdata($Msg);
        redirect(base_url() . 'Admin/');
    }

    # faculty dashboard dashboard

    elseif ($this->form_validation->run() == true)
    {
        $username = $this->lib->validate($this->input->post('username'));
        $password = $this->lib->validate($this->input->post('password'));

        $username = $this->security->xss_clean($username);
        $password = $this->security->xss_clean($password);
        $count = $this->lib_model->Counter('m_faculty', array('username' => $username, 'password' => $password, 'status' => 0));

        if ($count == 1) {
            $Sessions = array(
                'EmpCode' => $username,
                'EmpName' => 'Administration',
                'ELogin' => true);
            $this->session->set_userdata($Sessions);

            $Msg = array('Msg' => ' Have a Nice Day ', 'Type' => 'success');
            $this->session->set_flashdata($Msg);
            redirect(base_url() . 'Faculty/f_dashboard');

        }
    }

    #supervisior dashboard

    elseif ($this->form_validation->run() == true)
    {

        $username = $this->lib->validate($this->input->post('username'));
        $password = $this->lib->validate($this->input->post('password'));

        $username = $this->security->xss_clean($username);
        $password = $this->security->xss_clean($password);
        $count = $this->lib_model->Counter('m_supervisior', array('username' => $username, 'password' => $password, 'status' => 0));

        if ($count == 1) {
            $Sessions = array(
                'EmpCode' => $username,
                'EmpName' => 'Administration',
                'ELogin' => true);
            $this->session->set_userdata($Sessions);

            $Msg = array('Msg' => ' Have a Nice Day ', 'Type' => 'success');
            $this->session->set_flashdata($Msg);
            redirect(base_url() . 'Supervisior/supervisior_dashboard');
        }
   }

    #admin dashboard

    elseif ($this->form_validation->run() == true)
    {
        $username = $this->lib->validate($this->input->post('username'));
        $password = $this->lib->validate($this->input->post('password'));

        $username = $this->security->xss_clean($username);
        $password = $this->security->xss_clean($password);
        $count = $this->lib_model->Counter('m_admin', array('username' => $username, 'password' => $password, 'status' => 0));

        if ($count == 1) {
            $Sessions = array(
                'EmpCode' => $username,
                'EmpName' => 'Administration',
                'ELogin' => true);
            $this->session->set_userdata($Sessions);

            $Msg = array('Msg' => ' Have a Nice Day ', 'Type' => 'success');
            $this->session->set_flashdata($Msg);
            redirect(base_url() . 'Admin/dashboard');
        }
    }

#error msg

    else {
        $Msg = array('Msg' => 'Username and Password Invalid', 'Type' => 'danger');
        $this->session->set_flashdata($Msg);
        redirect(base_url() . 'Admin/');
    }

}

Body:
your code won't work because after the first validation check it will always get stuck in your first else clause.

I'm not sure what exactly you are doing here - but a possible approach would be

public function Auth()
{

    try
    {
        $rules = array(
            array('field' => 'username', 'label' => 'Username', 'rules' => 'required'),
            array('field' => 'password', 'label' => 'Password', 'rules' => 'required'),
        );
        $this->form_validation->set_rules($rules);
        if (!$this->form_validation->run()) throw new Exception(validation_errors());

        $username = $this->lib->validate($this->input->post('username'));
        $password = $this->lib->validate($this->input->post('password'));

        $arrAuthenticationTypes = [
            [
                'table' => 'm_faculty',
                'view' => 'Faculty/f_dashboard'
            ],
            [
                'table' => 'm_supervisior',
                'view' => 'Supervisior/supervisior_dashboard'
            ],
            [
                'table' => 'm_admin',
                'view' => 'Admin/dashboard'
            ],
        ];

        foreach($arrAuthenticationTypes AS $arrAuthenticationType)
        {
            $count = $this->lib_model->Counter($arrAuthenticationType['table'], array('username' => $username, 'password' => $password, 'status' => 0));
            if ($count == 1)
            {
                $Sessions = array(
                    'EmpCode' => $username,
                    'EmpName' => 'Administration',
                    'ELogin' => true
                );
                $this->session->set_userdata($Sessions);
                $Msg = array('Msg' => ' Have a Nice Day ', 'Type' => 'success');
                $this->session->set_flashdata($Msg);
                redirect(base_url() . $arrAuthenticationType['view']);
            }
        }

        throw new Exception('Username and Password Invalid');
    }
    catch(\Exception $e)
    {
        $arrMessage = [
            'Msg' => $e->getMessage(),
            'Type' => 'danger'
        ];
        $this->session->set_flashdata($Msg);
        redirect(base_url() . 'Admin/');
    }
}


问:
How to get currently active item`s index number (and not active item`s id) on a card layout on Extjs?
How do I get the currently active item's index number (and not active item's id) on a card layout?
The following code will return active item's id:

```<code>     Ext.getCmp('my-wizard').getLayout().activeItem.id];
</code>```

What if I don't want to define an id for my component items and I just want to access active item's index number?

答:
I couldn't find a built-in quick and easy way, but the following would work:

```<code>var wiz = Ext.getCmp('my-wizard');
var activeItem = wiz.getLayout().activeItem;
var activeIndex = wiz.items.indexOf(activeItem);
</code>```

If this was something that you wanted to do often, you could add it to the CardLayout prototype:

```<code>Ext.override(Ext.layout.CardLayout, {
    getActiveIndex: function() {
        return this.container.items.indexOf(this.activeItem);
    }
});
</code>```

Then you could use it with:

```<code>var activeIndex = Ext.getCmp('my-wizard').getLayout().getActiveIndex();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How do I get the currently active item's index number (and not active item's id) on a card layout?
The following code will return active item's id:

     Ext.getCmp('my-wizard').getLayout().activeItem.id];

What if I don't want to define an id for my component items and I just want to access active item's index number?

Body:
I couldn't find a built-in quick and easy way, but the following would work:

var wiz = Ext.getCmp('my-wizard');
var activeItem = wiz.getLayout().activeItem;
var activeIndex = wiz.items.indexOf(activeItem);

If this was something that you wanted to do often, you could add it to the CardLayout prototype:

Ext.override(Ext.layout.CardLayout, {
    getActiveIndex: function() {
        return this.container.items.indexOf(this.activeItem);
    }
});

Then you could use it with:

var activeIndex = Ext.getCmp('my-wizard').getLayout().getActiveIndex();


问:
Does Emacs have elm-lang programming language support?
I am getting started with Elm language https://elm-lang.org/ and I am using Emacs but did not find any package/plugin for elm-lang.
In case if you know any then please help.</p>

答:
I suggest you to try using Language Server Protocol for elm. It help to bring the most up-to-date solution for any editor, including Emacs.

Install elm-language-server on your machine.

Install lsp-mode package in your Emacs and configure some settings.

If you are Doom of Spacemacs user, you can use one of the preconfigured solutions.

For Doom use preinstalled elm module

For Spacemacs use elm layer


问:
How to find unique value range between two values and fill in
Let me start off with the caveat that I'm new to the site and newer to coding, so hopefully, the formating of this all displays correctly.

I looking to locate a few given unique records in a data set (in example data "blah4" and "blah44") and update the value below their location up to the location of the other unique record I flagged. I've tried searching on this topic but haven't had much luck yet. Any help/direction that you could provide would be much appreciated. Cheers!

```<code>    import pandas as pd

    info = [("blah1","blah2","blah3"),
           ("blah4","blah5","blah6"),
           ("blah11","blah22","blah33"),
           ("blah44","blah55","blah66"),
           ("blah7","blah8","blah9"),
           ("blah77","blah88","blah99")]

           df = pd.DataFrame(info, columns =["Name","Type","Class"])
           print(df)

       #Highlighting the data values that I'm looking to locate and use to replace values beneth untill reaching the next data value
       print(df[df[:].isin(["blah4","blah44"])])

       #Desired outcome
       info2 = [("blah1","blah2","blah3"),
                ("blah4","blah5","blah6"),
                ("blah4","blah22","blah33"),
                ("blah44","blah55","blah66"),
                ("blah44","blah8","blah9"),
                ("blah44","blah88","blah99")]
       df2 = pd.DataFrame(info2, columns =["Name","Type","Class"])
       print(df2)
</code>```

答:
You can group by cumsum and transform:

```<code>df["Name"] = df.groupby(df["Name"].isin(["blah4","blah44"]).cumsum())["Name"].transform("first")

print (df)

     Name    Type   Class
0   blah1   blah2   blah3
1   blah4   blah5   blah6
2   blah4  blah22  blah33
3  blah44  blah55  blah66
4  blah44   blah8   blah9
5  blah44  blah88  blah99
</code>```

Body:
Let me start off with the caveat that I'm new to the site and newer to coding, so hopefully, the formating of this all displays correctly.

I looking to locate a few given unique records in a data set (in example data "blah4" and "blah44") and update the value below their location up to the location of the other unique record I flagged. I've tried searching on this topic but haven't had much luck yet. Any help/direction that you could provide would be much appreciated. Cheers!

    import pandas as pd

    info = [("blah1","blah2","blah3"),
           ("blah4","blah5","blah6"),
           ("blah11","blah22","blah33"),
           ("blah44","blah55","blah66"),
           ("blah7","blah8","blah9"),
           ("blah77","blah88","blah99")]

           df = pd.DataFrame(info, columns =["Name","Type","Class"])
           print(df)

       #Highlighting the data values that I'm looking to locate and use to replace values beneth untill reaching the next data value
       print(df[df[:].isin(["blah4","blah44"])])

       #Desired outcome
       info2 = [("blah1","blah2","blah3"),
                ("blah4","blah5","blah6"),
                ("blah4","blah22","blah33"),
                ("blah44","blah55","blah66"),
                ("blah44","blah8","blah9"),
                ("blah44","blah88","blah99")]
       df2 = pd.DataFrame(info2, columns =["Name","Type","Class"])
       print(df2)

Body:
You can group by cumsum and transform:

df["Name"] = df.groupby(df["Name"].isin(["blah4","blah44"]).cumsum())["Name"].transform("first")

print (df)

     Name    Type   Class
0   blah1   blah2   blah3
1   blah4   blah5   blah6
2   blah4  blah22  blah33
3  blah44  blah55  blah66
4  blah44   blah8   blah9
5  blah44  blah88  blah99


问:
After updating composer i am getting Call to undefined function Illuminate\Encryption\openssl_cipher_iv_length()
I ran composer update and also i updated php version, Now i am getting below error msg on my every laravel project

```<code>Call to undefined function Illuminate\Encryption\openssl_cipher_iv_length()
</code>```

I am using xampp.

what i tried

i reinstall my composer by running composer install but i got

```<code>[Composer\Exception\NoSslException]
</code>```

i updated path environment variable to php.ini,But still getting this error
 what should i need to do ?

答:
I think you will need to add a missing php-openssl package to your PHP installation.

Open the php.ini file in your xampp installation and change

```<code>;extension=php_openssl.dll
</code>```

to

```<code>extension=php_openssl.dll
</code>```

remove the semicolon

You might need to restart xampp/apache after this change.

Body:
I ran composer update and also i updated php version, Now i am getting below error msg on my every laravel project

Call to undefined function Illuminate\Encryption\openssl_cipher_iv_length()

I am using xampp.

what i tried

i reinstall my composer by running composer install but i got

[Composer\Exception\NoSslException]

i updated path environment variable to php.ini,But still getting this error
 what should i need to do ?

Body:
I think you will need to add a missing php-openssl package to your PHP installation.

Open the php.ini file in your xampp installation and change

;extension=php_openssl.dll

to

extension=php_openssl.dll

remove the semicolon

You might need to restart xampp/apache after this change.


问:
BigQuery: GitHub repo year over year growth
I've created a table to show Github star count as of 05/2020 using the following query

```<code>SELECT repo.name
, MAX(CAST(JSON_EXTRACT_SCALAR(payload, '$.pull_request.base.repo.stargazers_count')AS INT64)) stars
FROM `githubarchive.month.202005`
GROUP by repo.name
ORDER BY stars DESC
LIMIT 100
</code>```

I'd like to now create another column next to it to show the repo star count one year ago so I can calculate year over year growth. I'm not sure how to do this so any help here would be great.

Thank you,
Danel

答:
Check the comments in code for how-to.

Especially important: I'm scanning days instead of months for 1/30th of the data scanned.

Usually you'll want to extract this data to a new table first, and then you won't need to scan so many GBs every time just to extract the daily number of stars.

Solution:

WITH data AS (
  SELECT ANY_VALUE(repo.name) name, repo.id
    , MAX(CAST(JSON_EXTRACT_SCALAR(payload, '$.pull_request.base.repo.stargazers_count')AS INT64)) stars
    , '20'||_table_suffix AS date
  FROM `githubarchive.day.20*`
  # day instead of month, 1/30th of data scanned
  GROUP by repo.id, date
)

, stars_now AS (
  SELECT ANY_VALUE(name) name, id, MAX(date) date, MAX(stars) stars
  FROM data
  WHERE date BETWEEN '20200526' AND '20200527'
  # a couple days to capture projects without activity
  GROUP BY id # names change, ids don't
  ORDER BY stars DESC
  LIMIT 100 # pick the top 100
)

, stars_before AS (
  SELECT id, stars, date
  FROM data
  WHERE date BETWEEN '20190520' AND '20190527'
  # a couple days to capture projects without activity
)

SELECT * # everything from stars_now
  , (SELECT MAX(stars) FROM stars_before WHERE a.id=id) stars_before  # an implicit JOIN
FROM stars_now a
```

Body:
I've created a table to show Github star count as of 05/2020 using the following query

SELECT repo.name
, MAX(CAST(JSON_EXTRACT_SCALAR(payload, '$.pull_request.base.repo.stargazers_count')AS INT64)) stars
FROM `githubarchive.month.202005`
GROUP by repo.name
ORDER BY stars DESC
LIMIT 100

I'd like to now create another column next to it to show the repo star count one year ago so I can calculate year over year growth. I'm not sure how to do this so any help here would be great.

Thank you,
Danel


问:
Class "Department" is mapped, but is not included in any persistence unit
I am getting this error and I have no idea the reason: Class "Department" is mapped, but is not included in any persistence unit.

I have two project.
One is In my persistence.xml, between  tag, there is only two lines:

```<code><persistence-unit name="UserJPA">
</persistence-unit>
</code>```

My class is:

```<code>package br.com.jm.user;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;;

@Entity
@Table(name = "DEPARTMENT")
public class Department implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    private Long id;
    private String name;

//getters and setters
}
</code>```

I am using EclipseLink2.1.2. Actually I can remove this if it makes the things easier.

Hugs,
Demetrio

答:
The persistence.xml should have:

```<code><persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
       http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0">
     <persistence-unit>..</persistence-unit>
 </persistence>
</code>```

Body:
I am getting this error and I have no idea the reason: Class "Department" is mapped, but is not included in any persistence unit.

I have two project.
One is In my persistence.xml, between  tag, there is only two lines:

<persistence-unit name="UserJPA">
</persistence-unit>

My class is:

package br.com.jm.user;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;;

@Entity
@Table(name = "DEPARTMENT")
public class Department implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    private Long id;
    private String name;

//getters and setters
}

I am using EclipseLink2.1.2. Actually I can remove this if it makes the things easier.

Hugs,
Demetrio

Body:
The persistence.xml should have:

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
       http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0">
     <persistence-unit>..</persistence-unit>
 </persistence>


问:
SQL Query to retrieve values inside tags(child nodes) from a XML data in SnowFlake
I have a XML(edited) File with the following data:

```<code><dept dept_id="1" dept_name="Marketing">
     <progress>1</progress>
    <employee empname="a">
         <end> 1 </end>
        <address addr1="123 abc">
        ...
        </address>
    </employee>
</dept>
<dept dept_id="2" dept_name="Sales">
    <progress>1</progress>
    <employee empname="b">
        <end> 1 </end>
        <address addr1="456 cde">
        ...
        </address>
    </employee>
</dept>
</code>```

I put this file in AWS S3 and then used 'copy into' to transfer this data into a external table in snowflake in a variant column. Like Below:

```<code>  copy into DB.AWS_S3_STAGE_SCHEMA.test_XML_copy
  from @AWS_S3_LANDING/websiteXML/Test_xml.xml
  FILE_FORMAT = ( TYPE =  XML STRIP_OUTER_ELEMENT = TRUE  )  ;
</code>```

Now, I can query the data from this table and retrieve data like 'marketing' and 'sales', which are inside tags using the following query(I got the syntax from snowflake docs and used it. ):

```<code>SELECT
    GET(xmldata, '@dept_id')::integer as dept_id,
    GET(xmldata, '@dept_name')::string as dept_name
FROM test_XML_copy;
</code>```

But, I cannot query the data inside tags which are in child nodes. For example: I need data like 'a' and '123 abc'.
If anybody can help me in this query, that would be appreciated.

答:
Use a combination of XMLGET and GET functions to traverse nested objects in an XML document.

The former helps fetch an entire tag object found below the current tag, while the latter allows querying attributes and regular values within the current tag.

SELECT
    -- <dept> (root)
    GET(xmldata, '@dept_id')::integer as dept_id,
    GET(xmldata, '@dept_name')::string as dept_name,
    -- <dept>.<employee>
    GET(XMLGET(xmldata, 'employee'), '@empname')::string as employee_name,
    -- <dept>.<employee>.<address>
    GET(XMLGET(XMLGET(xmldata, 'employee'), 'address'), '@addr1')::string as address_1
FROM test_XML_copy;
```

<p>Which should yield:</p>

<pre class="lang-sh prettyprint-override"><code>+---------+-----------+---------------+-----------+
| DEPT_ID | DEPT_NAME | EMPLOYEE_NAME | ADDRESS_1 |
|---------+-----------+---------------+-----------|
|       1 | Marketing | a             | 123 abc   |
|       2 | Sales     | b             | 456 def   |
| ...     | ...       | ...           | ...       |
+---------+-----------+---------------+-----------+
</code>```

Your example data shows no repetition of child tags, but if they do repeat (such as multiple employee in each dept) then FLATTEN can first be used to produce one employee per row and the above approach can be reapplied. Alternatively, if it is a fixed form of tag structure and they are always ordered, you can use the instance number in XMLGET to point to each one (implicit default is 0, the first object).

An example that explodes the document into one row per employee and per address inner tags:

SELECT
xmldata:"@dept_id"::integer as dept_id,
xmldata:"@dept_name"::string as dept_name,
emp.value:"@empname"::string as employee_name,
addr.value:"@addr1"::string as address_1
FROM
test_XML_copy,
LATERAL FLATTEN(xmldata:"$") emp,
LATERAL FLATTEN(emp.value:"$") addr
WHERE emp.value:"@" = 'employee' AND addr.value:"@" = 'address';
```

<p>(This yields results similar to the above, for the example provided in OP's question)</p>

<p><strong>Note</strong>: You can also use the path syntax with <code>$</code> and <code>@</code> characters to navigate the structure instead of nesting functions, but these rely on strict ordering of the input data structure:</p>

<pre class="lang-sql prettyprint-override"><code>-- See outer / inner structures in 'JSON' form
SELECT
    xmldata:"@" dept_tag,
    xmldata:"$" dept_tag_contents
FROM test_XML_copy;

-- Sample equivalent query using path expressions, relying on ordering:
SELECT
    xmldata:"@dept_id",
    xmldata:"@dept_name",
    xmldata:"$"[1]."@empname",
    xmldata:"$"[1]."$"[1]."@addr1"
FROM test_XML_copy;
</code>```

Body:
I have a XML(edited) File with the following data:

<dept dept_id="1" dept_name="Marketing">
     <progress>1</progress>
    <employee empname="a">
         <end> 1 </end>
        <address addr1="123 abc">
        ...
        </address>
    </employee>
</dept>
<dept dept_id="2" dept_name="Sales">
    <progress>1</progress>
    <employee empname="b">
        <end> 1 </end>
        <address addr1="456 cde">
        ...
        </address>
    </employee>
</dept>

I put this file in AWS S3 and then used 'copy into' to transfer this data into a external table in snowflake in a variant column. Like Below:

  copy into DB.AWS_S3_STAGE_SCHEMA.test_XML_copy
  from @AWS_S3_LANDING/websiteXML/Test_xml.xml
  FILE_FORMAT = ( TYPE =  XML STRIP_OUTER_ELEMENT = TRUE  )  ;

Now, I can query the data from this table and retrieve data like 'marketing' and 'sales', which are inside tags using the following query(I got the syntax from snowflake docs and used it. ):

SELECT
    GET(xmldata, '@dept_id')::integer as dept_id,
    GET(xmldata, '@dept_name')::string as dept_name
FROM test_XML_copy;

But, I cannot query the data inside tags which are in child nodes. For example: I need data like 'a' and '123 abc'.
If anybody can help me in this query, that would be appreciated.

Body:
Use a combination of XMLGET and GET functions to traverse nested objects in an XML document.

The former helps fetch an entire tag object found below the current tag, while the latter allows querying attributes and regular values within the current tag.

SELECT
    -- <dept> (root)
    GET(xmldata, '@dept_id')::integer as dept_id,
    GET(xmldata, '@dept_name')::string as dept_name,
    -- <dept>.<employee>
    GET(XMLGET(xmldata, 'employee'), '@empname')::string as employee_name,
    -- <dept>.<employee>.<address>
    GET(XMLGET(XMLGET(xmldata, 'employee'), 'address'), '@addr1')::string as address_1
FROM test_XML_copy;

Which should yield:

+---------+-----------+---------------+-----------+
| DEPT_ID | DEPT_NAME | EMPLOYEE_NAME | ADDRESS_1 |
|---------+-----------+---------------+-----------|
|       1 | Marketing | a             | 123 abc   |
|       2 | Sales     | b             | 456 def   |
| ...     | ...       | ...           | ...       |
+---------+-----------+---------------+-----------+

Your example data shows no repetition of child tags, but if they do repeat (such as multiple employee in each dept) then FLATTEN can first be used to produce one employee per row and the above approach can be reapplied. Alternatively, if it is a fixed form of tag structure and they are always ordered, you can use the instance number in XMLGET to point to each one (implicit default is 0, the first object).

An example that explodes the document into one row per employee and per address inner tags:

SELECT
xmldata:"@dept_id"::integer as dept_id,
xmldata:"@dept_name"::string as dept_name,
emp.value:"@empname"::string as employee_name,
addr.value:"@addr1"::string as address_1
FROM
test_XML_copy,
LATERAL FLATTEN(xmldata:"$") emp,
LATERAL FLATTEN(emp.value:"$") addr
WHERE emp.value:"@" = 'employee' AND addr.value:"@" = 'address';

(This yields results similar to the above, for the example provided in OP's question)

Note: You can also use the path syntax with $ and @ characters to navigate the structure instead of nesting functions, but these rely on strict ordering of the input data structure:

-- See outer / inner structures in 'JSON' form
SELECT
    xmldata:"@" dept_tag,
    xmldata:"$" dept_tag_contents
FROM test_XML_copy;

-- Sample equivalent query using path expressions, relying on ordering:
SELECT
    xmldata:"@dept_id",
    xmldata:"@dept_name",
    xmldata:"$"[1]."@empname",
    xmldata:"$"[1]."$"[1]."@addr1"
FROM test_XML_copy;


问:
Check array with day object
I have an array of object,

```<code>DayEffort:[{
    Description: null
    Effort: 2
    EffortDate: "2019-05-20T00:00:00"
    day:Sunday
    Status: "In Progress"
   },
    {
    Description: null
    Effort: 1.5
    EffortDate: "2019-05-22T00:00:00"
    Day : Tuesday
    Status: "In Progress"
    },
    {

    Description: null
    Effort: 1.5
    EffortDate: "2019-05-23T00:00:00"
    Day : Thursday
    Status: "In Progress"

}]
</code>```

which contain day property, if day is sunday, it needs to push on zero index of new array, Monday is on 1st index, if not matching push null value,

Excepted result:

```<code>NewArray : [
0:{Description: null Effort: 2 EffortDate: "2019-05-20T00:00:00" day:Sunday Status: "In Progress"},
1: null,
2: {Description: null Effort: 2 EffortDate: "2019-05-20T00:00:00" day:Tuesday Status: "In Progress"},
3: null,
4: {Description: null Effort: 2 EffortDate: "2019-05-20T00:00:00" day:Thursday Status: "InProgress"},
5: null,
6: null,
]
</code>```

Tried,

```<code>var DayArray = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday', 'Saterday'];
for(var k = 0 ; k < DayArray.length; k++){
                     for(var m = 0; m < DayEffort.length; m++){

                         if(DayArray[k] == DayEffort[m].day){
                             NewArray.push(DayEffort[m]);

                         }
                         else{
                             NewArray.push(null);
                         }

                     }
                 }
</code>```

Please help me,

答:
Like this (After fixing your invalid object values and missing commas)

const DayEffort = [{ Description: null, Effort: 2, EffortDate: "2019-05-20T00:00:00", Day: "Sunday", Status: "In Progress" }, { Description: null, Effort: 1.5, EffortDate: "2019-05-22T00:00:00", Day: "Tuesday", Status: "In Progress" }, { Description: null, Effort: 1.5, EffortDate: "2019-05-23T00:00:00", Day: "Thursday", Status: "In Progress" } ];

let NewArray= new Array(7).fill(null);
const DayArray = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

DayEffort.forEach(item => NewArray[DayArray.indexOf(item.Day)] = item);
console.log(NewArray);```

Title: Check array with day object

Body:
I have an array of object,

DayEffort:[{
    Description: null
    Effort: 2
    EffortDate: "2019-05-20T00:00:00"
    day:Sunday
    Status: "In Progress"
   },
    {
    Description: null
    Effort: 1.5
    EffortDate: "2019-05-22T00:00:00"
    Day : Tuesday
    Status: "In Progress"
    },
    {

    Description: null
    Effort: 1.5
    EffortDate: "2019-05-23T00:00:00"
    Day : Thursday
    Status: "In Progress"

}]

which contain day property, if day is sunday, it needs to push on zero index of new array, Monday is on 1st index, if not matching push null value,

Excepted result:

NewArray : [
0:{Description: null Effort: 2 EffortDate: "2019-05-20T00:00:00" day:Sunday Status: "In Progress"},
1: null,
2: {Description: null Effort: 2 EffortDate: "2019-05-20T00:00:00" day:Tuesday Status: "In Progress"},
3: null,
4: {Description: null Effort: 2 EffortDate: "2019-05-20T00:00:00" day:Thursday Status: "InProgress"},
5: null,
6: null,
]

Tried,

var DayArray = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday', 'Saterday'];
for(var k = 0 ; k < DayArray.length; k++){
                     for(var m = 0; m < DayEffort.length; m++){

                         if(DayArray[k] == DayEffort[m].day){
                             NewArray.push(DayEffort[m]);

                         }
                         else{
                             NewArray.push(null);
                         }

                     }
                 }

Please help me,


问:
What does & after a return type mean in C++ OOP
so I have a method of a class given below that multiplies two complex numbers using operator overloading :

Complex operator*(Complex &c2) {
    Complex temp;

    temp.realPart = realPart * c2.realPart - (imaginaryPart * c2.imaginaryPart);
    temp.imaginaryPart = (realPart * c2.imaginaryPart) + (imaginaryPart * c2.realPart);

    return temp;
}
```

<p>This seems to work fine. However, my program does not run when I change the member function header to:</p>

<pre class="lang-cpp prettyprint-override"><code>Complex& operator * (Complex &c2) {  // Adding & after the class name.
</code>```

The program does not crash but it can't compute the answer/ ends after the cursor on the program blinks for a while. What does & after the class name mean? And I have seen it being used when returning a this pointer.

答:
Your Are Returning a Refrence To An Object just like next to any variable , Now that is good in some cases, but in others you might be returning a refrence to temporary variables and then by any change these temporary objects get freed from memory then you are referencing a freed block of memory
The Cherno explains it very well in his rvalue and lvalues video you can go and see it here: https://www.youtube.com/watch?v=fbYknr-HPYE</p>

Body:
so I have a method of a class given below that multiplies two complex numbers using operator overloading :

Complex operator*(Complex &c2) {
    Complex temp;

    temp.realPart = realPart * c2.realPart - (imaginaryPart * c2.imaginaryPart);
    temp.imaginaryPart = (realPart * c2.imaginaryPart) + (imaginaryPart * c2.realPart);

    return temp;
}

This seems to work fine. However, my program does not run when I change the member function header to:

Complex& operator * (Complex &c2) {  // Adding & after the class name.

The program does not crash but it can't compute the answer/ ends after the cursor on the program blinks for a while. What does & after the class name mean? And I have seen it being used when returning a this pointer.


问:
Calculate column value when I upload document to SharePoint Online
I am new to SharePoint and trying to explore Content Types, Lists, libraries;
I created my own Content Type called "Salary Report" (Parent - Document) and assigned to my "Salary Report Library".
"Salary Report" content type have only two columns - Date Created and Document (and also hidden Title).

I would like to handle document creation and use Date Created column to store Salary Report Month value by calculating this in code. Are there any options to handle document creation in code (C#/.NET or JavaScript) or how can I handle this?

Thanks!

答:
You could use Microsoft Flow to achieve this.

Step1:

Step2:get current month   utcNow('MM')

You could know more about this here: https://www.o365dude.com/2017/05/01/working-with-dates-times-in-microsoft-flow/

Step3:get current file ID

Step4:call a rest api update column value you want.

‘date’ is the ordinary column, ’DateCreatedByme’ is the column in content type.


问:
Feathers vuex : user is no longer logged in after refresh
I am new to feathers and vue js I don't understand this, when i log in a user the v-if directives works on the navbar, but when i refresh the page i notice that the user is no longer logged in still the JWT is stored in the localStorage.</p>

```<code>App-Navbar.vue

<template>
  <div>
    <q-header bordered class="bg-white">
      <q-toolbar>
        <div class="q-gutter-sm" v-if="!user">

          <q-btn to="/login" />
          <q-btn to="/signup" />

        </div>
        <div class="q-gutter-sm" v-if="user">

          <q-btn @click="logout"/>
        </div>

      </q-toolbar>
    </q-header>
  </div>
</template>

<script>
import { mapActions, mapState } from "vuex";

export default {

methods: {
    ...mapActions("auth", { authLogout: "logout" }),
    logout() {
      this.authLogout().then(() => this.$router.push("/login"));
    }
  },
  computed: {
    ...mapState("auth", { user: "payload" })
  }
};
</script>
</code>```

答:
You just need some logic to fetch your token on refresh.
You will first need to save it somewhere, let's say sessionStorage.

You can use vuex-persistedstate as you mentioned, but a lighter solution would be just setting your user property in the state of the store like this

```<code>user: sessionStorage.getItem(yourkey) ?? null
</code>```

Body:
I am new to feathers and vue js I don't understand this, when i log in a user the v-if directives works on the navbar, but when i refresh the page i notice that the user is no longer logged in still the JWT is stored in the localStorage.

App-Navbar.vue

<template>

    <q-header bordered class="bg-white">
      <q-toolbar>

          <q-btn to="/login" />
          <q-btn to="/signup" />

          <q-btn @click="logout"/>

      </q-toolbar>
    </q-header>

</template>

Body:
You just need some logic to fetch your token on refresh.
You will first need to save it somewhere, let's say sessionStorage.

You can use vuex-persistedstate as you mentioned, but a lighter solution would be just setting your user property in the state of the store like this

user: sessionStorage.getItem(yourkey) ?? null


问:
How do I write text to the username/password input controls of a 3rd party page using ASP.NET?
My title is pretty much the question: "How do I write text to the username/password input controls of a 3rd party web page using ASP.NET?"

Just for examples sake, if I wanted to write an ASP.NET page that would initially authenticate  a user on my end, and then redirect to a 3rd party site and log into it using the fields displayed with credentials my app has within it (encypted obviously), how can I do this?

If you had ever seen the old Microsoft FingerPrint reader USB control, it used to do this. The software would allow you to highlight fields on a web page, and then store the credentials you provide it, and auto write to the fields upon visiting the site and using your fingerprint. I don't want the finger print reader, just the similar functionality.

It will be a static 3rd party site and does not have to account for any site visited. I should be able to look at the source of the site I need to log into to if this helps.

Anyone know how to go about this? Thanks!!

答: Basically you need to use the WebRequest class and simulate a user controlling a web browser and manually execute each GET and POST operation that is required to log into the site.


问:
WPF Combobox should only open on arrow
Is there a chance to change the wpf combobox that it only opens when I click on the arrow on the left side?
Usually you can click anywhere to open it. I dont want that.

Thanks

答:
I managed to get it working with the following code. Note that I am using Materialdesign and you have to change it a little if you are not using that.

Code in App.xaml

```<code>  <Style x:Key="MaterialDesignComboBox2" TargetType="{x:Type ComboBox}">
                <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
                <Setter Property="Background" Value="Transparent"/>
                <Setter Property="BorderBrush" Value="{DynamicResource MaterialDesignTextBoxBorder}"/>
                <Setter Property="Foreground" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type FrameworkElement}}, Path=(TextElement.Foreground)}"/>
                <Setter Property="BorderThickness" Value="0 0 0 1"/>
                <Setter Property="ItemContainerStyle" Value="{StaticResource MaterialDesignComboBoxItemSelectedCollapsedStyle}" />
                <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto" />
                <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto" />
                <Setter Property="Padding" Value="0 6 0 6" />
                <Setter Property="VerticalContentAlignment" Value="Top" />
                <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
                <Setter Property="HorizontalAlignment" Value="Stretch"/>
                <Setter Property="VerticalAlignment" Value="Center"/>
                <Setter Property="ScrollViewer.CanContentScroll" Value="true" />
                <Setter Property="ScrollViewer.PanningMode" Value="Both" />
                <Setter Property="Stylus.IsFlicksEnabled" Value="False" />
                <Setter Property="Validation.ErrorTemplate" Value="{StaticResource MaterialDesignValidationErrorTemplate}"/>
                <Setter Property="wpf:TextFieldAssist.TextBoxViewMargin" Value="1 0 1 0" />
                <Setter Property="Template" Value="{StaticResource MaterialDesignFloatingHintComboBoxTemplate2}" />
                <Style.Triggers>
                    <Trigger Property="IsKeyboardFocused" Value="true">
                        <Setter Property="BorderBrush" Value="{DynamicResource PrimaryHueMidBrush}" />
                    </Trigger>
                    <Trigger Property="IsKeyboardFocusWithin" Value="true">
                        <Setter Property="BorderBrush" Value="{DynamicResource PrimaryHueMidBrush}" />
                    </Trigger>
                    <Trigger Property="IsEditable" Value="true">
                        <Setter Property="IsTabStop" Value="false" />
                        <!-- designer prefers hard bool -->
                        <Setter Property="wpf:ComboBoxAssist.ShowSelectedItem" Value="{StaticResource TrueValue}" />
                    </Trigger>
                    <!-- designer prefers hard bool -->
                    <Trigger Property="wpf:ComboBoxAssist.ShowSelectedItem" Value="{StaticResource TrueValue}" >
                        <Setter Property="ItemContainerStyle" Value="{StaticResource MaterialDesignComboBoxItemStyle}" />
                    </Trigger>
                </Style.Triggers>
            </Style>

        <Style x:Key="MaterialDesignFloatingHintComboBox2"
               BasedOn="{StaticResource MaterialDesignComboBox2}"
               TargetType="{x:Type ComboBox}">
            <Setter Property="wpf:HintAssist.IsFloating" Value="True"/>
        </Style>
</code>```

Helperclass EditableComboBox

```<code>public static class EditableComboBox
{
    public static int GetMaxLength(DependencyObject obj)
    {
        return (int)obj.GetValue(MaxLengthProperty);
    }

    public static void SetMaxLength(DependencyObject obj, int value)
    {
        obj.SetValue(MaxLengthProperty, value);
    }

    public static readonly DependencyProperty MaxLengthProperty = DependencyProperty.RegisterAttached("MaxLength", typeof(int), typeof(EditableComboBox), new UIPropertyMetadata(OnMaxLenghtChanged));

    private static void OnMaxLenghtChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
    {
        if (!(obj is ComboBox comboBox)) return;

        comboBox.Loaded +=
            (s, e) =>
            {
                var textBox = comboBox.FindChild("PART_EditableTextBox", typeof(TextBox));
                if (textBox == null) return;

                textBox.SetValue(TextBox.MaxLengthProperty, args.NewValue);
            };
    }
}
</code>```

And the combobox itself in the View

```<code> <ComboBox materialDesign:HintAssist.Hint="{lex:Loc ordernumber}" Style="{StaticResource MaterialDesignFloatingHintComboBox2}"   Text="{Binding SalesOrderNumber}" Margin="0 0 40 0" FontSize="22" Width="250"
              IsEditable="True" DisplayMemberPath="Identifier" SelectedItem="{Binding SelectedSalesOrder}"
              ItemsSource="{Binding LastSalesOrders}" IsTextSearchEnabled="False" utility:EditableComboBox.MaxLength="10"  x:Name="TbOrder" >
            <ComboBox.InputBindings>
                <KeyBinding Command="{Binding OpenSalesOrderOrCustomerCommand}" Key="Return" />
            </ComboBox.InputBindings>

            <ComboBox.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="{lex:Loc paste}" Command="{Binding PasteOrdernumberCommand}" />
                </ContextMenu>
            </ComboBox.ContextMenu>
  </ComboBox>
</code>```

Title: WPF Combobox should only open on arrow

Body:
I managed to get it working with the following code. Note that I am using Materialdesign and you have to change it a little if you are not using that.

Code in App.xaml

  <Style x:Key="MaterialDesignComboBox2" TargetType="{x:Type ComboBox}">
                <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
                <Setter Property="Background" Value="Transparent"/>
                <Setter Property="BorderBrush" Value="{DynamicResource MaterialDesignTextBoxBorder}"/>
                <Setter Property="Foreground" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type FrameworkElement}}, Path=(TextElement.Foreground)}"/>
                <Setter Property="BorderThickness" Value="0 0 0 1"/>
                <Setter Property="ItemContainerStyle" Value="{StaticResource MaterialDesignComboBoxItemSelectedCollapsedStyle}" />
                <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto" />
                <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto" />
                <Setter Property="Padding" Value="0 6 0 6" />
                <Setter Property="VerticalContentAlignment" Value="Top" />
                <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
                <Setter Property="HorizontalAlignment" Value="Stretch"/>
                <Setter Property="VerticalAlignment" Value="Center"/>
                <Setter Property="ScrollViewer.CanContentScroll" Value="true" />
                <Setter Property="ScrollViewer.PanningMode" Value="Both" />
                <Setter Property="Stylus.IsFlicksEnabled" Value="False" />
                <Setter Property="Validation.ErrorTemplate" Value="{StaticResource MaterialDesignValidationErrorTemplate}"/>
                <Setter Property="wpf:TextFieldAssist.TextBoxViewMargin" Value="1 0 1 0" />
                <Setter Property="Template" Value="{StaticResource MaterialDesignFloatingHintComboBoxTemplate2}" />
                <Style.Triggers>
                    <Trigger Property="IsKeyboardFocused" Value="true">
                        <Setter Property="BorderBrush" Value="{DynamicResource PrimaryHueMidBrush}" />
                    </Trigger>
                    <Trigger Property="IsKeyboardFocusWithin" Value="true">
                        <Setter Property="BorderBrush" Value="{DynamicResource PrimaryHueMidBrush}" />
                    </Trigger>
                    <Trigger Property="IsEditable" Value="true">
                        <Setter Property="IsTabStop" Value="false" />
                        <!-- designer prefers hard bool -->
                        <Setter Property="wpf:ComboBoxAssist.ShowSelectedItem" Value="{StaticResource TrueValue}" />
                    </Trigger>
                    <!-- designer prefers hard bool -->
                    <Trigger Property="wpf:ComboBoxAssist.ShowSelectedItem" Value="{StaticResource TrueValue}" >
                        <Setter Property="ItemContainerStyle" Value="{StaticResource MaterialDesignComboBoxItemStyle}" />
                    </Trigger>
                </Style.Triggers>
            </Style>

        <Style x:Key="MaterialDesignFloatingHintComboBox2"
               BasedOn="{StaticResource MaterialDesignComboBox2}"
               TargetType="{x:Type ComboBox}">
            <Setter Property="wpf:HintAssist.IsFloating" Value="True"/>
        </Style>

Helperclass EditableComboBox

public static class EditableComboBox
{
    public static int GetMaxLength(DependencyObject obj)
    {
        return (int)obj.GetValue(MaxLengthProperty);
    }

    public static void SetMaxLength(DependencyObject obj, int value)
    {
        obj.SetValue(MaxLengthProperty, value);
    }

    public static readonly DependencyProperty MaxLengthProperty = DependencyProperty.RegisterAttached("MaxLength", typeof(int), typeof(EditableComboBox), new UIPropertyMetadata(OnMaxLenghtChanged));

    private static void OnMaxLenghtChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
    {
        if (!(obj is ComboBox comboBox)) return;

        comboBox.Loaded +=
            (s, e) =>
            {
                var textBox = comboBox.FindChild("PART_EditableTextBox", typeof(TextBox));
                if (textBox == null) return;

                textBox.SetValue(TextBox.MaxLengthProperty, args.NewValue);
            };
    }
}

And the combobox itself in the View

 <ComboBox materialDesign:HintAssist.Hint="{lex:Loc ordernumber}" Style="{StaticResource MaterialDesignFloatingHintComboBox2}"   Text="{Binding SalesOrderNumber}" Margin="0 0 40 0" FontSize="22" Width="250"
              IsEditable="True" DisplayMemberPath="Identifier" SelectedItem="{Binding SelectedSalesOrder}"
              ItemsSource="{Binding LastSalesOrders}" IsTextSearchEnabled="False" utility:EditableComboBox.MaxLength="10"  x:Name="TbOrder" >
            <ComboBox.InputBindings>
                <KeyBinding Command="{Binding OpenSalesOrderOrCustomerCommand}" Key="Return" />
            </ComboBox.InputBindings>

            <ComboBox.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="{lex:Loc paste}" Command="{Binding PasteOrdernumberCommand}" />
                </ContextMenu>
            </ComboBox.ContextMenu>
  </ComboBox>


问:
Gunicorn sync workers spawning processes
We're using Django + Gunicorn + Nginx in our server. The problem is that after a while we see lot's of gunicorn worker processes that have became orphan, and a lot other ones that have became zombie. Also we can see that some of Gunicorn worker processes spawn some other Gunicorn workers. Our best guess is that these workers become orphans after their parent workers have died.

Why Gunicorn workers spawn child workers? Why do they die?! And how can we prevent this?

I should also mention that we've set Gunicorn log level to debug and still we don't see any thing significant, other than periodical log of workers number, which reports count of workers we wanted from it.

UPDATE
This is the line we used to run gunicorn:

gunicorn --env DJANGO_SETTINGS_MODULE=proj.settings proj.wsgi --name proj --workers 10 --user proj --group proj --bind 127.0.0.1:7003  --log-level=debug --pid gunicorn.pid  --timeout 600 --access-logfile /home/proj/access.log --error-logfile /home/proj/error.log

答:
This sounds like a timeout issue.

You have multiple timeouts going on and they all need to be in a descending order. It seems they may not be.

For example:

Nginx has a default timeout of 60 seconds

Gunicorn has a default timeout of 30 seconds

Django has a default timeout of 300 seconds

Postgres default timeout is complicated but let's pose 60 seconds for this example.

In this example, when 30 seconds has passed and Django is still waiting for Postgres to respond. Gunicorn tells Django to stop, which in turn should tell Postgres to stop. Gunicorn will wait a certain amount of time for this to happen before it kills django, leaving the postgres process as an orphan query. The user will re-initiate their query and this time the query will take longer because the old one is still running.

I see that you have set your Gunicorn tiemeout to 300 seconds.

This would probably mean that Nginx tells Gunicorn to stop after 60 seconds, Gunicorn may wait for Django who waits for Postgres or any other underlying processes, and when Nginx gets tired of waiting, it kills Gunicorn, leaving Django hanging.

This is still just a theory, but it is a very common problem and hopefully leads you and any others experiencing similar problems, to the right place.


问:
Differences of PowerShell window based on launch type
Could someone explain differences of PowerShell window based on how I launch it?

Starting PowerShell from Start Menu default PowerShell shortcut to

%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe

Font size and window color is normal.

Starting PowerShell from Run windows (Win + R)

type powershell or %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe

Font size is bigger (window's size too) and window color is slightly different

Testing on fresh installation of Windows 10 1903 and 1909.

答:
Similar to what Mathias R. Jessen commented, if you look at the start menu version of powershell, you can see via rightclick -> open file location that the Start Menu version simply points to another shortcut which then points to %systemroot%\system32\windowspowershell\v1.0\powershell.exe

Now, if you rightclick that shortcut and go to, for example, Font, you can see it is configured to "14".

If you start powershell via run, rightclick the top bar -> defaults -> fonts, you can see the run-started instance of powershell uses the Font size 16.

Other than that, there is literally no difference, I just checked with a few extra steps whether it launches in elevated rights or if there is a difference in the powershell version, but nope. All the same.

Its just the config thats pushed with the extra shortcut.


问:
How to set default branch policies in azure devops
Is it possible to set branch policies across all repo's? In other words, When creating a branch, a default branch policy is already set for master. </p>

答:
Indeed as @Thomas Harris mentioned in the comment above, you can set it for all repos in a single project via

**Project Settings*

Cross-repo policies under "Repos" heading

Click Add branch protection button

And then you can select whether this applies to the default branch or a specific branch name pattern.