问:
Fail to compile due to package not found
Problem: Failed to build using "Run As > Ant Build" on build.xml

When I try to compile a demo java, it failed to compile. Attached with build.xml and corresponding eclipse setting. Required package in place but still failed to compile.

Here is the demo source code You can download this financial tools to have fun too. Warning: involve very high risk investment

```<code><?xml version="1.0"?>
<project default="build" basedir=".">
    <property file="build.properties" />
    <property name="name" value="Login" />
    <property name="src.dir" location="${basedir}/src" />
    <property name="build" location="${basedir}/build" />
    <property name="build.classes" location="${build}/classes" />

    <target name="checkos">
        <condition property="bin.dir" value="${basedir}/../../../../bin">
          <os family="windows" />
        </condition>
        <condition property="bin.dir" value="${basedir}/../../../../lib">
          <os family="unix" />
        </condition>
    </target>

    <!-- App build -->
    <target name="build" depends="checkos" description="Builds the ${name} application">
        <!-- Creating directory -->
        <mkdir dir="${build.classes}" />

        <!-- Compiling sources -->
        <javac srcdir="${src.dir}"
               destdir="${build.classes}"
               includeAntRuntime="false"
               debug="${build.debug}"
               deprecation="true"
               verbose="false"
               optimize="true"
               classpath="${bin.dir}/java/fxcore2.jar" >
        </javac>

        <!-- Creating JAR-file -->
        <jar jarfile="${build}/${name}.jar">
            <fileset dir="${build.classes}" />
            <manifest>
                <attribute name="Main-Class" value="login.Main" />
                <attribute name="Class-Path" value="fxcore2.jar" />
            </manifest>
        </jar>
    </target>

    <target name="rebuild" depends="clean, build" description="Rebuilds project" />

    <!-- Clean -->
    <target name="clean" description="Removes all temporary files">
        <!-- Deleting files -->
        <delete dir="${build}" />
    </target>

    <target name="run" depends="checkos" description="Rebuilds and run ${name}">
        <copy file="${bin.dir}/java/fxcore2.jar" tofile="${build}/fxcore2.jar" overwrite="true" />
        <java jar="${build}/${name}.jar" fork="true" failonerror='true' dir="${bin.dir}">
            <jvmarg value="-Djava.library.path=${java.library.path}${path.separator}${bin.dir}${path.separator}${bin.dir}/java" />
            <arg line="--login {LOGIN}" />
            <arg line="--password {PASSWORD}" />
            <arg line="--url http://www.fxcorporate.com/Hosts.jsp" />
            <arg line="--connection Demo" />
            <arg line="--sessionid {SESSIONID}" />
            <arg line="--pin {PIN}" />
        </java>
    </target>

</project>
</code>```

Error output as follow:

Buildfile: C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\build.xml
checkos:
build:
    [javac] Compiling 3 source files to C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\build\classes
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\Main.java:3: error: package fxcm.fxcore2 does not exist
    [javac] import fxcm.fxcore2.*;
    [javac] ^
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\Main.java:45: error: cannot find symbol
    [javac]     private static void printAccounts(O2GSession session) throws Exception {
    [javac]                                       ^
    [javac]   symbol:   class O2GSession
    [javac]   location: class Main
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\SessionStatusListener.java:6: error: package com.fxcore2 does not exist
    [javac] import com.fxcore2.*;
    [javac] ^
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\SessionStatusListener.java:8: error: cannot find symbol
    [javac] public class SessionStatusListener implements IO2GSessionStatus {
    [javac]                                               ^
    [javac]   symbol: class IO2GSessionStatus
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\SessionStatusListener.java:9: error: cannot find symbol
    [javac]     private O2GSession mSession;
    [javac]             ^
    [javac]   symbol:   class O2GSession
    [javac]   location: class SessionStatusListener
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\SessionStatusListener.java:18: error: cannot find symbol
    [javac]     public SessionStatusListener(O2GSession session, String sSessionID, String sPin) {
    [javac]                                  ^
    [javac]   symbol:   class O2GSession
    [javac]   location: class SessionStatusListener
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\SessionStatusListener.java:48: error: cannot find symbol
    [javac]     public void onSessionStatusChanged(O2GSessionStatusCode status) {
    [javac]                                        ^
    [javac]   symbol:   class O2GSessionStatusCode
    [javac]   location: class SessionStatusListener
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\Main.java:9: error: cannot find symbol
    [javac]         O2GSession session = null;
    [javac]         ^
    [javac]   symbol:   class O2GSession
    [javac]   location: class Main
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\Main.java:22: error: cannot find symbol
    [javac]             session = O2GTransport.createSession();
    [javac]                       ^
    [javac]   symbol:   variable O2GTransport
    [javac]   location: class Main
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\Main.java:46: error: cannot find symbol
    [javac]         O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory();
    [javac]         ^
    [javac]   symbol:   class O2GResponseReaderFactory
    [javac]   location: class Main
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\Main.java:50: error: cannot find symbol
    [javac]         O2GLoginRules loginRules = session.getLoginRules();
    [javac]         ^
    [javac]   symbol:   class O2GLoginRules
    [javac]   location: class Main
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\Main.java:51: error: cannot find symbol
    [javac]         O2GResponse response = loginRules.getTableRefreshResponse(O2GTableType.ACCOUNTS);
    [javac]         ^
    [javac]   symbol:   class O2GResponse
    [javac]   location: class Main
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\Main.java:51: error: cannot find symbol
    [javac]         O2GResponse response = loginRules.getTableRefreshResponse(O2GTableType.ACCOUNTS);
    [javac]                                                                   ^
    [javac]   symbol:   variable O2GTableType
    [javac]   location: class Main
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\Main.java:52: error: cannot find symbol
    [javac]         O2GAccountsTableResponseReader accountsResponseReader = readerFactory.createAccountsTableReader(response);
    [javac]         ^
    [javac]   symbol:   class O2GAccountsTableResponseReader
    [javac]   location: class Main
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\Main.java:54: error: cannot find symbol
    [javac]             O2GAccountRow accountRow = accountsResponseReader.getRow(i);
    [javac]             ^
    [javac]   symbol:   class O2GAccountRow
    [javac]   location: class Main
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\SessionStatusListener.java:51: error: cannot find symbol
    [javac]         case TRADING_SESSION_REQUESTED:
    [javac]              ^
    [javac]   symbol:   variable TRADING_SESSION_REQUESTED
    [javac]   location: class SessionStatusListener
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\SessionStatusListener.java:58: error: cannot find symbol
    [javac]         case CONNECTED:
    [javac]              ^
    [javac]   symbol:   variable CONNECTED
    [javac]   location: class SessionStatusListener
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\SessionStatusListener.java:63: error: cannot find symbol
    [javac]         case DISCONNECTED:
    [javac]              ^
    [javac]   symbol:   variable DISCONNECTED
    [javac]   location: class SessionStatusListener
    [javac] 18 errors

BUILD FAILED
C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\build.xml:31: Compile failed; see the compiler error output for details.

Total time: 1 second```

答:
Using the command line, the following commands might work:

```<code>ant rebuild
ant run
</code>```

from the path C:\Program Files\CandleWorks\ForexConnectAPI\samples\java\NonTableManagerSamples\Login> or equivalent.

As a side-note, IntelliJ may be a good alternative to Eclipse, I prefer IntelliJ myself personally.

Body:
Problem: Failed to build using "Run As > Ant Build" on build.xml

When I try to compile a demo java, it failed to compile. Attached with build.xml and corresponding eclipse setting. Required package in place but still failed to compile.

Here is the demo source code You can download this financial tools to have fun too. Warning: involve very high risk investment

<?xml version="1.0"?>
<project default="build" basedir=".">
    <property file="build.properties" />
    <property name="name" value="Login" />
    <property name="src.dir" location="${basedir}/src" />
    <property name="build" location="${basedir}/build" />
    <property name="build.classes" location="${build}/classes" />

    <target name="checkos">
        <condition property="bin.dir" value="${basedir}/../../../../bin">
          <os family="windows" />
        </condition>
        <condition property="bin.dir" value="${basedir}/../../../../lib">
          <os family="unix" />
        </condition>
    </target>

    <target name="build" depends="checkos" description="Builds the ${name} application">

        <mkdir dir="${build.classes}" />

        <javac srcdir="${src.dir}"
               destdir="${build.classes}"
               includeAntRuntime="false"
               debug="${build.debug}"
               deprecation="true"
               verbose="false"
               optimize="true"
               classpath="${bin.dir}/java/fxcore2.jar" >
        </javac>

        <jar jarfile="${build}/${name}.jar">
            <fileset dir="${build.classes}" />
            <manifest>
                <attribute name="Main-Class" value="login.Main" />
                <attribute name="Class-Path" value="fxcore2.jar" />
            </manifest>
        </jar>
    </target>

    <target name="rebuild" depends="clean, build" description="Rebuilds project" />

    <target name="clean" description="Removes all temporary files">

        <delete dir="${build}" />
    </target>

    <target name="run" depends="checkos" description="Rebuilds and run ${name}">
        <copy file="${bin.dir}/java/fxcore2.jar" tofile="${build}/fxcore2.jar" overwrite="true" />
        <java jar="${build}/${name}.jar" fork="true" failonerror='true' dir="${bin.dir}">
            <jvmarg value="-Djava.library.path=${java.library.path}${path.separator}${bin.dir}${path.separator}${bin.dir}/java" />
            <arg line="--login {LOGIN}" />
            <arg line="--password {PASSWORD}" />
            <arg line="--url http://www.fxcorporate.com/Hosts.jsp" />
            <arg line="--connection Demo" />
            <arg line="--sessionid {SESSIONID}" />
            <arg line="--pin {PIN}" />
        </java>
    </target>

</project>

Error output as follow:

Buildfile: C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\build.xml
checkos:
build:
    [javac] Compiling 3 source files to C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\build\classes
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\Main.java:3: error: package fxcm.fxcore2 does not exist
    [javac] import fxcm.fxcore2.*;
    [javac] ^
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\Main.java:45: error: cannot find symbol
    [javac]     private static void printAccounts(O2GSession session) throws Exception {
    [javac]                                       ^
    [javac]   symbol:   class O2GSession
    [javac]   location: class Main
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\SessionStatusListener.java:6: error: package com.fxcore2 does not exist
    [javac] import com.fxcore2.*;
    [javac] ^
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\SessionStatusListener.java:8: error: cannot find symbol
    [javac] public class SessionStatusListener implements IO2GSessionStatus {
    [javac]                                               ^
    [javac]   symbol: class IO2GSessionStatus
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\SessionStatusListener.java:9: error: cannot find symbol
    [javac]     private O2GSession mSession;
    [javac]             ^
    [javac]   symbol:   class O2GSession
    [javac]   location: class SessionStatusListener
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\SessionStatusListener.java:18: error: cannot find symbol
    [javac]     public SessionStatusListener(O2GSession session, String sSessionID, String sPin) {
    [javac]                                  ^
    [javac]   symbol:   class O2GSession
    [javac]   location: class SessionStatusListener
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\SessionStatusListener.java:48: error: cannot find symbol
    [javac]     public void onSessionStatusChanged(O2GSessionStatusCode status) {
    [javac]                                        ^
    [javac]   symbol:   class O2GSessionStatusCode
    [javac]   location: class SessionStatusListener
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\Main.java:9: error: cannot find symbol
    [javac]         O2GSession session = null;
    [javac]         ^
    [javac]   symbol:   class O2GSession
    [javac]   location: class Main
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\Main.java:22: error: cannot find symbol
    [javac]             session = O2GTransport.createSession();
    [javac]                       ^
    [javac]   symbol:   variable O2GTransport
    [javac]   location: class Main
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\Main.java:46: error: cannot find symbol
    [javac]         O2GResponseReaderFactory readerFactory = session.getResponseReaderFactory();
    [javac]         ^
    [javac]   symbol:   class O2GResponseReaderFactory
    [javac]   location: class Main
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\Main.java:50: error: cannot find symbol
    [javac]         O2GLoginRules loginRules = session.getLoginRules();
    [javac]         ^
    [javac]   symbol:   class O2GLoginRules
    [javac]   location: class Main
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\Main.java:51: error: cannot find symbol
    [javac]         O2GResponse response = loginRules.getTableRefreshResponse(O2GTableType.ACCOUNTS);
    [javac]         ^
    [javac]   symbol:   class O2GResponse
    [javac]   location: class Main
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\Main.java:51: error: cannot find symbol
    [javac]         O2GResponse response = loginRules.getTableRefreshResponse(O2GTableType.ACCOUNTS);
    [javac]                                                                   ^
    [javac]   symbol:   variable O2GTableType
    [javac]   location: class Main
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\Main.java:52: error: cannot find symbol
    [javac]         O2GAccountsTableResponseReader accountsResponseReader = readerFactory.createAccountsTableReader(response);
    [javac]         ^
    [javac]   symbol:   class O2GAccountsTableResponseReader
    [javac]   location: class Main
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\Main.java:54: error: cannot find symbol
    [javac]             O2GAccountRow accountRow = accountsResponseReader.getRow(i);
    [javac]             ^
    [javac]   symbol:   class O2GAccountRow
    [javac]   location: class Main
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\SessionStatusListener.java:51: error: cannot find symbol
    [javac]         case TRADING_SESSION_REQUESTED:
    [javac]              ^
    [javac]   symbol:   variable TRADING_SESSION_REQUESTED
    [javac]   location: class SessionStatusListener
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\SessionStatusListener.java:58: error: cannot find symbol
    [javac]         case CONNECTED:
    [javac]              ^
    [javac]   symbol:   variable CONNECTED
    [javac]   location: class SessionStatusListener
    [javac] C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\src\SessionStatusListener.java:63: error: cannot find symbol
    [javac]         case DISCONNECTED:
    [javac]              ^
    [javac]   symbol:   variable DISCONNECTED
    [javac]   location: class SessionStatusListener
    [javac] 18 errors

BUILD FAILED
C:\Users\clint\Documents\programming\Projects\fxcm\java_sample\NonTableManagerSamples\Login\build.xml:31: Compile failed; see the compiler error output for details.

Total time: 1 second

Body:
Using the command line, the following commands might work:

ant rebuild
ant run

from the path C:\Program Files\CandleWorks\ForexConnectAPI\samples\java\NonTableManagerSamples\Login> or equivalent.

As a side-note, IntelliJ may be a good alternative to Eclipse, I prefer IntelliJ myself personally.


来源: stackexchange

问:
CXF JAXB JAXBEncoderDecoder unmarshalling error : unexpected element when having qualified elements
I have the following problem and cannot find a solution:

The WSDL has elementFormDefault="qualified", in the response that I receive in my CXF client all the elements are prefixed with namespace but JAXB throws an exception

```
org.apache.cxf.interceptor.Fault: Unmarshalling Error: unexpected element (uri:"unm:ENTSCWS", local:"searchReturn"). Expected elements are
    at org.apache.cxf.jaxb.JAXBEncoderDecoder.unmarshall(JAXBEncoderDecoder.java:661)
    at org.apache.cxf.jaxb.JAXBEncoderDecoder.unmarshall(JAXBEncoderDecoder.java:533)
    at org.apache.cxf.jaxb.io.DataReaderImpl.read(DataReaderImpl.java:128) ...
```

If i change in the WSDL elementFormDefault="unqualified" it is working, but I am not allowed to change the WSDL, it should have the elements prefixed with the namespace.

The package-info.java contains the annotaction:

@javax.xml.bind.annotation.XmlSchema(namespace = "unm:ENTSCWS", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package entscws;
```

<p>The response class contains the annotation:</p>

<pre class="lang-java prettyprint-override"><code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "searchReturn"
})
@XmlRootElement(name = "searchResponse")
public class SearchResponse {
</code>```

Do you have any idea why I get this error?

答:
Are you running in OSGi?   I've seen some similar issues with package-info's not being picked up properly there.

Another option could be to add the -xjc-npa flag to the wsdl2java command to have it not use the package-info at all and stick the namespaces in all the other places.

ContentLicense: CC BY-SA 3.0

Body:
I have the following problem and cannot find a solution:

The WSDL has elementFormDefault="qualified", in the response that I receive in my CXF client all the elements are prefixed with namespace but JAXB throws an exception

org.apache.cxf.interceptor.Fault: Unmarshalling Error: unexpected element (uri:"unm:ENTSCWS", local:"searchReturn"). Expected elements are
    at org.apache.cxf.jaxb.JAXBEncoderDecoder.unmarshall(JAXBEncoderDecoder.java:661)
    at org.apache.cxf.jaxb.JAXBEncoderDecoder.unmarshall(JAXBEncoderDecoder.java:533)
    at org.apache.cxf.jaxb.io.DataReaderImpl.read(DataReaderImpl.java:128) ...

If i change in the WSDL elementFormDefault="unqualified" it is working, but I am not allowed to change the WSDL, it should have the elements prefixed with the namespace.

The package-info.java contains the annotaction:

@javax.xml.bind.annotation.XmlSchema(namespace = "unm:ENTSCWS", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package entscws;

The response class contains the annotation:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "searchReturn"
})
@XmlRootElement(name = "searchResponse")
public class SearchResponse {

Do you have any idea why I get this error?

ContentLicense: CC BY-SA 4.0


问:
How to check the object type on runtime in TypeScript?
I'm trying to find a way to pass an object to function in and check it type in a runtime. This is a pseudo code:

function func (obj:any) {
    if(typeof obj === "A") {
        // do something
    } else if(typeof obj === "B") {
        //do something else
    }
}

let a:A;
let b:B;
func(a);
```

But typeof always returns "object" and I could not find a way to get the real type of a or b. instanceof did not work either and returned the same.

Any idea how to do it in TypeScript?

答:
Alternative approach without the need of checking the type

What if you want to introduce more types? Would you then extend your if-statement? How many such if-statements do you have in your codebase?

Using types in conditions makes your code difficult to maintain. There's lots of theory behind that, but I'll save you the hazzle. Here's what you could do instead:

Use polymorphism

Like this:

```<code>abstract class BaseClass {
    abstract theLogic();
}

class A extends BaseClass {
    theLogic() {
       // do something if class is A
    }
}

class B extends BaseClass {
    theLogic() {
       // do something if class is B
    }
}
</code>```

Then you just have to invoke theLogic() from whichever class you want:

```<code>let a: A = new A();
a.theLogic();

let b: B = new B();
b.theLogic();
</code>```

Body:
I'm trying to find a way to pass an object to function in and check it type in a runtime. This is a pseudo code:

function func (obj:any) {
    if(typeof obj === "A") {
        // do something
    } else if(typeof obj === "B") {
        //do something else
    }
}

let a:A;
let b:B;
func(a);

But typeof always returns "object" and I could not find a way to get the real type of a or b. instanceof did not work either and returned the same.

Any idea how to do it in TypeScript?

Body:
Alternative approach without the need of checking the type

What if you want to introduce more types? Would you then extend your if-statement? How many such if-statements do you have in your codebase?

Using types in conditions makes your code difficult to maintain. There's lots of theory behind that, but I'll save you the hazzle. Here's what you could do instead:

Use polymorphism

Like this:

abstract class BaseClass {
    abstract theLogic();
}

class A extends BaseClass {
    theLogic() {
       // do something if class is A
    }
}

class B extends BaseClass {
    theLogic() {
       // do something if class is B
    }
}

Then you just have to invoke theLogic() from whichever class you want:

let a: A = new A();
a.theLogic();

let b: B = new B();
b.theLogic();


问:
Violation of PRIMARY KEY constraint PK_Casting
I'm trying to add a new data base through a script, but getting some errors, already tried to let out the double fields, but that didn't work for me.

```<code>USE master
GO

IF EXISTS (SELECT * FROM sysdatabases WHERE NAME = 'MijnFilms')
BEGIN
    ALTER DATABASE MijnFilms SET SINGLE_USER WITH ROLLBACK IMMEDIATE
    DROP DATABASE MijnFilms
END
GO

-- Creatie databank Bibliotheek
CREATE DATABASE MijnFilms
GO

USE MijnFilms
GO

--Creatie tabel AUTEUR
CREATE TABLE ACTEUR
(
    Acteur_id int NOT NULL,
    ActeurNaam nvarchar(40),
    CONSTRAINT PK_Acteur PRIMARY KEY(acteur_id)
)
GO

--Creatie tabel CATEGORIE
CREATE TABLE CASTING
(
    Film_id int NOT NULL,
    Acteur_id int NOT NULL,
    CONSTRAINT PK_Casting PRIMARY KEY(Film_id),
    CONSTRAINT FK1_Casting FOREIGN KEY(Acteur_id) REFERENCES Acteur(acteur_id)
)
GO

--Creatie tabel BOEKEN
CREATE TABLE FILM
(
    Film_id int NOT NULL,
    Titel nvarchar(40),
    Jaar smallint,
    Score int,
    Stemmen int,
    CONSTRAINT FK1_Film FOREIGN KEY(Film_id) REFERENCES Casting(film_id),
)
GO

--Opvullen van de tabellen met testdata
INSERT INTO ACTEUR(Acteur_id, ActeurNaam) VALUES (1, 'Tom Hanks')
INSERT INTO ACTEUR(Acteur_id, ActeurNaam) VALUES (2, 'Helen Hunt')
INSERT INTO ACTEUR(Acteur_id, ActeurNaam) VALUES (3, 'Catherine Zeta Jones')
GO

INSERT INTO CASTING (Film_id, Acteur_id) VALUES (1, 1)
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (1, 2)
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (2, 1)
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (2, 3)
GO

INSERT INTO FILM(Film_id, Titel, jaar, Score, Stemmen) VALUES (1, 'Cast Away', 2000, 75,1)
INSERT INTO FILM(Film_id, Titel, jaar, Score, Stemmen) VALUES (2, 'The Terminal', 2004, 62,1)
GO
</code>```

Right now, I get an error:

Msg 2627, Level 14, State 1, Line 60

  Violation of PRIMARY KEY constraint 'PK_Casting'. Cannot insert duplicate key in object 'dbo.CASTING'. The duplicate key value is (2).

答:
Well, you're trying to insert a film_id of 1 (and 2) into casting twice but primary keys need to be unique.

You could use a composite primary key here, consisting of the film's and the actor's ID.

Also the film's ID should be the primary key in film and a foreign key in casting not the other way round. That requires film to be created before casting though. That also applies for the INSERTs -- film has to come before casting.

```<code>...
CREATE TABLE film
             (film_id integer
                      NOT NULL,
              titel nvarchar(40),
              jaar smallint,
              score integer,
              stemmen integer,
              CONSTRAINT pk_film
                         PRIMARY KEY (film_id));

CREATE TABLE acteur
             (acteur_id integer
                        NOT NULL,
              acteurnaam nvarchar(40),
              CONSTRAINT pk_acteur
                         PRIMARY KEY (acteur_id));

CREATE TABLE casting
             (film_id integer
                      NOT NULL,
              acteur_id integer
                        NOT NULL,
              CONSTRAINT pk_casting
                         PRIMARY KEY (film_id,
                                      acteur_id),
              CONSTRAINT fk1_casting
                         FOREIGN KEY (film_id)
                                     REFERENCES film
                                                (film_id),
              CONSTRAINT fk2_casting
                         FOREIGN KEY (acteur_id)
                                     REFERENCES acteur
                                                (acteur_id));
...

INSERT INTO film ...

INSERT INTO acteur ...

INSERT INTO casting ...
</code>```

Body:
I'm trying to add a new data base through a script, but getting some errors, already tried to let out the double fields, but that didn't work for me.

USE master
GO

IF EXISTS (SELECT * FROM sysdatabases WHERE NAME = 'MijnFilms')
BEGIN
    ALTER DATABASE MijnFilms SET SINGLE_USER WITH ROLLBACK IMMEDIATE
    DROP DATABASE MijnFilms
END
GO

-- Creatie databank Bibliotheek
CREATE DATABASE MijnFilms
GO

USE MijnFilms
GO

--Creatie tabel AUTEUR
CREATE TABLE ACTEUR
(
    Acteur_id int NOT NULL,
    ActeurNaam nvarchar(40),
    CONSTRAINT PK_Acteur PRIMARY KEY(acteur_id)
)
GO

--Creatie tabel CATEGORIE
CREATE TABLE CASTING
(
    Film_id int NOT NULL,
    Acteur_id int NOT NULL,
    CONSTRAINT PK_Casting PRIMARY KEY(Film_id),
    CONSTRAINT FK1_Casting FOREIGN KEY(Acteur_id) REFERENCES Acteur(acteur_id)
)
GO

--Creatie tabel BOEKEN
CREATE TABLE FILM
(
    Film_id int NOT NULL,
    Titel nvarchar(40),
    Jaar smallint,
    Score int,
    Stemmen int,
    CONSTRAINT FK1_Film FOREIGN KEY(Film_id) REFERENCES Casting(film_id),
)
GO

--Opvullen van de tabellen met testdata
INSERT INTO ACTEUR(Acteur_id, ActeurNaam) VALUES (1, 'Tom Hanks')
INSERT INTO ACTEUR(Acteur_id, ActeurNaam) VALUES (2, 'Helen Hunt')
INSERT INTO ACTEUR(Acteur_id, ActeurNaam) VALUES (3, 'Catherine Zeta Jones')
GO

INSERT INTO CASTING (Film_id, Acteur_id) VALUES (1, 1)
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (1, 2)
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (2, 1)
INSERT INTO CASTING (Film_id, Acteur_id) VALUES (2, 3)
GO

INSERT INTO FILM(Film_id, Titel, jaar, Score, Stemmen) VALUES (1, 'Cast Away', 2000, 75,1)
INSERT INTO FILM(Film_id, Titel, jaar, Score, Stemmen) VALUES (2, 'The Terminal', 2004, 62,1)
GO

Right now, I get an error:

Msg 2627, Level 14, State 1, Line 60

  Violation of PRIMARY KEY constraint 'PK_Casting'. Cannot insert duplicate key in object 'dbo.CASTING'. The duplicate key value is (2).

Body:
Well, you're trying to insert a film_id of 1 (and 2) into casting twice but primary keys need to be unique.

You could use a composite primary key here, consisting of the film's and the actor's ID.

Also the film's ID should be the primary key in film and a foreign key in casting not the other way round. That requires film to be created before casting though. That also applies for the INSERTs -- film has to come before casting.

...
CREATE TABLE film
             (film_id integer
                      NOT NULL,
              titel nvarchar(40),
              jaar smallint,
              score integer,
              stemmen integer,
              CONSTRAINT pk_film
                         PRIMARY KEY (film_id));

CREATE TABLE acteur
             (acteur_id integer
                        NOT NULL,
              acteurnaam nvarchar(40),
              CONSTRAINT pk_acteur
                         PRIMARY KEY (acteur_id));

CREATE TABLE casting
             (film_id integer
                      NOT NULL,
              acteur_id integer
                        NOT NULL,
              CONSTRAINT pk_casting
                         PRIMARY KEY (film_id,
                                      acteur_id),
              CONSTRAINT fk1_casting
                         FOREIGN KEY (film_id)
                                     REFERENCES film
                                                (film_id),
              CONSTRAINT fk2_casting
                         FOREIGN KEY (acteur_id)
                                     REFERENCES acteur
                                                (acteur_id));
...

INSERT INTO film ...

INSERT INTO acteur ...

INSERT INTO casting ...


问:
MySQL query design for booking database with limited amount of goods and heavy traffic
We're running a site for booking salmon fishing licenses. The site has no problem handling the traffic 364 days a year. The 365th day is when the license sale opens, and that's where the problem occurs. The servers are struggling more and more each year due to increased traffic, and we have to further optimize our booking query.

The licenses are divided into many different types (tbl_license_types), and each license type are connected to one or more fishing zones (tbl_zones).

Each license type can have a seasonal quota, which is a single value set as an integer field in tbl_license_types.

Each zone can have a daily quota, a weekly quota and a seasonal quota. The daily quota is the same for all days, and the seasonal quota of course is a single value. Daily and seasonal are therefore integer fields in tbl_zones. The weekly quota however differs by week, therefore those are specified in the separate tbl_weekly_quotas.

Bookings can be for one or more consecutive dates, but are only stated as From_date and To_date in tbl_shopping_cart (and tbl_bookings). For each booking attempt made by a user, the quotas have to be checked against already allowed bookings in both tbl_shopping_cart and tbl_bookings.

To be able to count/group by date, we use a view called view_season_calendar with a single column containing all the dates of the current season.

In the beginning we used a transaction where we first made a query to check the quotas, and if quotas allowed we would use a second query to insert the booking to tbl_bookings.

However that gave a lot of deadlocks under relatively moderate traffic, so we redesigned it to a single query (pseudo-code):

```<code>INSERT INTO tbl_bookings (_booking_)
WHERE _lowest_found_quota_ >= _requested_number_of_licenses_
</code>```

where _lowest_found_quota_ is a ~330 lines long SELECT with multiple subqueries and the related tables being joined multiple times in order to check all quotas.

Example: User wants to book License type A, for zones 5 and 6, from 2020-05-19 to 2020-05-25.
The system needs to

count previous bookings of license type A against the license type A seasonal quota.

count previous bookings in zone 5 for each of the 6 dates against zone 5 daily quota.

same count for zone 6.

count previous bookings in zone 5 for each of the two weeks the dates are part of, against zone 5 weekly quota.

same count for zone 6.

count all previous bookings in zone 5 for the current season against zone 5 seasonal quota.

same count for zone 6.

If all are within quotas, insert the booking.

As I said this was working well earlier, but due to higher traffic load we need to optimize this query further now. I have some thoughts on how to do this;

Using isolation level READ UNCOMMITTED on each booking until quotas for the requested zones/license type are nearly full, then fallback to the default REPEATABLE READ. As long as there's a lot left of the quota, the count doesn't need to be 100% correct. This will greatly reduce lock waits and deadlocks, right?

Creating one or more views which keeps count of all bookings for each date, week, zone and license type, then using those views in the WHERE clauses of the insert.

If doing nr 2, use READ UNCOMMITTED in the views. If views report relevant quota near full, cancel the INSERT and start a new one with the design we're using today. (Hopefully traffic levels are coming down before quotas are becoming full)

I would greatly appreciate thoughts on how the query can be done as efficient as possible.

答:
Rate Per Second = RPS

Suggestions to consider for your AWS Parameters group

```<code>innodb_lru_scan_depth=100  # from 1024 to conserve 90% of CPU cycles used for function every second
innodb_flush_neighbors=2  # from 1 to reduce time required to lower innodb_buffer_pool_pages_dirty count when busy
read_rnd_buffer_size=128K  # from 512K to reduce handler_read_rnd_next RPS of 3,227
innodb_io_capacity=1900  # from 200 to use more of SSD IOPS
log_slow_verbosity=query_plan,explain  # to make slow query log more useful
have_symlink=NO  # from YES for some protection from ransomware
</code>```

You will find these changes will cause transactions to complete processing quicker.  For additional assistance, view profile, Network profile for contact info and free downloadable Utility Scripts to assist with performance tuning. On our FAQ page you will find "Q. How can I find JOINS or QUERIES not using indexes?" to assist in reducing select_scan RPhr of 1,173. Com_rollback averages 1 every ~ 2,700 seconds, usually correctable with consistent read order in maintenance queries.

Body:
We're running a site for booking salmon fishing licenses. The site has no problem handling the traffic 364 days a year. The 365th day is when the license sale opens, and that's where the problem occurs. The servers are struggling more and more each year due to increased traffic, and we have to further optimize our booking query.

The licenses are divided into many different types (tbl_license_types), and each license type are connected to one or more fishing zones (tbl_zones).

Each license type can have a seasonal quota, which is a single value set as an integer field in tbl_license_types.

Each zone can have a daily quota, a weekly quota and a seasonal quota. The daily quota is the same for all days, and the seasonal quota of course is a single value. Daily and seasonal are therefore integer fields in tbl_zones. The weekly quota however differs by week, therefore those are specified in the separate tbl_weekly_quotas.

Bookings can be for one or more consecutive dates, but are only stated as From_date and To_date in tbl_shopping_cart (and tbl_bookings). For each booking attempt made by a user, the quotas have to be checked against already allowed bookings in both tbl_shopping_cart and tbl_bookings.

To be able to count/group by date, we use a view called view_season_calendar with a single column containing all the dates of the current season.

In the beginning we used a transaction where we first made a query to check the quotas, and if quotas allowed we would use a second query to insert the booking to tbl_bookings.

However that gave a lot of deadlocks under relatively moderate traffic, so we redesigned it to a single query (pseudo-code):

INSERT INTO tbl_bookings (_booking_)
WHERE _lowest_found_quota_ >= _requested_number_of_licenses_

where _lowest_found_quota_ is a ~330 lines long SELECT with multiple subqueries and the related tables being joined multiple times in order to check all quotas.

Example: User wants to book License type A, for zones 5 and 6, from 2020-05-19 to 2020-05-25.
The system needs to

count previous bookings of license type A against the license type A seasonal quota.

count previous bookings in zone 5 for each of the 6 dates against zone 5 daily quota.

same count for zone 6.

count previous bookings in zone 5 for each of the two weeks the dates are part of, against zone 5 weekly quota.

same count for zone 6.

count all previous bookings in zone 5 for the current season against zone 5 seasonal quota.

same count for zone 6.

If all are within quotas, insert the booking.

As I said this was working well earlier, but due to higher traffic load we need to optimize this query further now. I have some thoughts on how to do this;

Using isolation level READ UNCOMMITTED on each booking until quotas for the requested zones/license type are nearly full, then fallback to the default REPEATABLE READ. As long as there's a lot left of the quota, the count doesn't need to be 100% correct. This will greatly reduce lock waits and deadlocks, right?

Creating one or more views which keeps count of all bookings for each date, week, zone and license type, then using those views in the WHERE clauses of the insert.

If doing nr 2, use READ UNCOMMITTED in the views. If views report relevant quota near full, cancel the INSERT and start a new one with the design we're using today. (Hopefully traffic levels are coming down before quotas are becoming full)

I would greatly appreciate thoughts on how the query can be done as efficient as possible.

Body:
Rate Per Second = RPS

Suggestions to consider for your AWS Parameters group

innodb_lru_scan_depth=100  # from 1024 to conserve 90% of CPU cycles used for function every second
innodb_flush_neighbors=2  # from 1 to reduce time required to lower innodb_buffer_pool_pages_dirty count when busy
read_rnd_buffer_size=128K  # from 512K to reduce handler_read_rnd_next RPS of 3,227
innodb_io_capacity=1900  # from 200 to use more of SSD IOPS
log_slow_verbosity=query_plan,explain  # to make slow query log more useful
have_symlink=NO  # from YES for some protection from ransomware

You will find these changes will cause transactions to complete processing quicker.  For additional assistance, view profile, Network profile for contact info and free downloadable Utility Scripts to assist with performance tuning. On our FAQ page you will find "Q. How can I find JOINS or QUERIES not using indexes?" to assist in reducing select_scan RPhr of 1,173. Com_rollback averages 1 every ~ 2,700 seconds, usually correctable with consistent read order in maintenance queries.


问:
How can I avoid using *ngIf in an Angular template?
I tried using async/await to avoid *ngIf in the component template.

I'm getting an error in the Chrome console when I remove *ngIf in component template.

Can anyone help to get a solution. I do not want to use *ngIf in the component template as a requirement

I'm calling the GET REST API and used subscribe. Also, I'm getting results without the error if I'm using *ngIf, but I want the same results without using *ngIf

CODE:
component.ts

```<code>export class DisplayComponent implements OnInit {
users : user[];
user: user;
userResult: any;

  constructor(private http: HttpClient) { }

  ngOnInit() {
  }

  async readUser(id){
     this.userResult = await this.http.get<user>("http://localhost:8090/user/" +id).subscribe(
       data => {
         this.user = data;
       },
       error =>{
         return console.error();
         ;
       }
     )
    console.log("Fuuhhh! Client will wait till promise is resolved.");
  }
}
</code>```

CODE: DisplayComponent.html

```<code><div style="text-align: center;">
    <button (click)="loadUsers()">load Users</button>
    <table style="margin: 0 auto;" border="1">
        <tr>
            <th>Identity</th>
        </tr>
        <tr *ngFor="let user of users">
           <td>
            <button style="background: transparent;border: transparent;cursor: pointer;" (click)="readUser(user.id)">{{user?.id}}</button>
            </td>
        </tr>
    </table>

</div>
<div style="text-align: center;">
    <span style="color: darkgray;">Identity:</span> <span style="color: gray;">{{user.id}}</span> <br>
    <span>Name:</span> {{user.name}} <br>
    <span>School:</span> {{user.school}} <br>
</div>
</code>```

答:
Angular have a lifecycle system, so Angular is trying to load the component before getting the data from your API. So yes, you need to handle the case before the API responds.

You have 2 ways to do that :

use *ngIf but you don't have to use *ngIf everywhere if you make many calls if this is your fear, you can use ngrx properly and use one *ngIf only in your HTML

initialize your data with default value. Angular will load your "default" user and replace it by the user received by the API, if there is no error of course. If you really want to use that, try a

user: user = new user();```

and of course, initiliaze all the attribute you are using by empty string, ... in the user constructor.

But I think the first way is better because you can handle the error and the waiting case more properly with a loading spinner, loading and error message, ... BUT you need to learn basics of rxjs :)

Body:
I tried using async/await to avoid *ngIf in the component template.

I'm getting an error in the Chrome console when I remove *ngIf in component template.

Can anyone help to get a solution. I do not want to use *ngIf in the component template as a requirement

I'm calling the GET REST API and used subscribe. Also, I'm getting results without the error if I'm using *ngIf, but I want the same results without using *ngIf

CODE:
component.ts

export class DisplayComponent implements OnInit {
users : user[];
user: user;
userResult: any;

  constructor(private http: HttpClient) { }

  ngOnInit() {
  }

  async readUser(id){
     this.userResult = await this.http.get<user>("http://localhost:8090/user/" +id).subscribe(
       data => {
         this.user = data;
       },
       error =>{
         return console.error();
         ;
       }
     )
    console.log("Fuuhhh! Client will wait till promise is resolved.");
  }
}

CODE: DisplayComponent.html

    <button (click)="loadUsers()">load Users</button>

            Identity

            <button style="background: transparent;border: transparent;cursor: pointer;" (click)="readUser(user.id)">{{user?.id}}</button>

    Identity: {{user.id}}

    Name: {{user.name}}

    School: {{user.school}}

Body:
Angular have a lifecycle system, so Angular is trying to load the component before getting the data from your API. So yes, you need to handle the case before the API responds.

You have 2 ways to do that :

use *ngIf but you don't have to use *ngIf everywhere if you make many calls if this is your fear, you can use ngrx properly and use one *ngIf only in your HTML

initialize your data with default value. Angular will load your "default" user and replace it by the user received by the API, if there is no error of course. If you really want to use that, try a

user: user = new user();

and of course, initiliaze all the attribute you are using by empty string, ... in the user constructor.

But I think the first way is better because you can handle the error and the waiting case more properly with a loading spinner, loading and error message, ... BUT you need to learn basics of rxjs :)


问:
Export Azure Resource Groups with Tags to csv
I'm kinda new to Powershell, and I'm trying to make a script that gets all the data from Azure Resource Group (including tags) and exporting the output to CSV.

As far as I know, there are a few ways to do it, AzureCLI, AzureRM(Powershell), and Az(Powershell).

Example 1:
This "script one-liner" gets the work done, but it requires to input the actual tags, instead of retrieving it automatically from Azure

```<code>$resourceGroupList = Get-AzResourceGroup | select-Object -Property ResourceGroupName,Location,ResourceId,ProvisioningState,@{N='Enviroment (Tag)'; E={$_.Tags.Enviroment}} ,@{N='Ownership (Tag)'; E={$_.Tags.Ownership}}
$resourceGroupList | export-csv test.csv -NoTypeInformation
</code>```

The other way I found is to use AzureCLI

```<code>$resourceGroupList = az group list --query "[].{ResourceGroupName:name,Location:location,ResourceType:type,provisioningState:properties,Tags:tags,ResourceGroupID:id}" -o json | convertfrom-json
$resourceGroupList | Export-Csv test.csv -NoTypeInformation
</code>```

I really struggle with arrays and how to format them to be exported to CSV like in the format of Example 1.

Any help/ideas would be extremely appreciated!

Thanks!

答:
The main thing to understand here is how to work with hashtables as that is what the Tags property contains. The other thing we need to account for is that tags are not consistent, no matter how hard we try as administrators, this will lead to inconsistent properties in our array of PSObjects if we just add properties for the tags from each individual Resource Group. So in advance of starting any sorting of the data for the CSV file, we need a unique list of tags across all groups. Resource Groups that don't have that tag, will need the property just so we have a complete set of data for the resulting CSV file. Anyway, less talking, more code.

```<code># Initialise output array
$Output = @()

# Collect all the groups from the current subscription
$ResourceGroups = Get-AzResourceGroup

# Obtain a unique list of tags for these groups collectively
# Use Sort-Object as per - https://github.com/PowerShell/PowerShell/issues/12059
$UniqueTags = $ResourceGroups.Tags.GetEnumerator().Keys | Sort-Object -Unique

# Loop through the resource groups
foreach ($ResourceGroup in $ResourceGroups) {
    # Create a new ordered hashtable and add the normal properties first.
    $RGHashtable = [ordered] @{}
    $RGHashtable.Add("Name",$ResourceGroup.ResourceGroupName)
    $RGHashtable.Add("Location",$ResourceGroup.Location)
    $RGHashtable.Add("Id",$ResourceGroup.ResourceId)
    $RGHashtable.Add("ProvisioningState",$ResourceGroup.ProvisioningState)

    # Loop through possible tags adding the property if there is one, adding it with a hyphen as it's value if it doesn't.
    if ($ResourceGroup.Tags.Count -ne 0) {
        $UniqueTags | Foreach-Object {
            if ($ResourceGroup.Tags[$_]) {
                $RGHashtable.Add("$_ (Tag)",$ResourceGroup.Tags[$_])
            }
            else {
                $RGHashtable.Add("$_ (Tag)","-")
            }
        }
    }
    else {
        $UniqueTags | Foreach-Object { $RGHashtable.Add("$_ (Tag)","-") }
    }

    # Update the output array, adding the ordered hashtable we have created for the ResourceGroup details.
    $Output += New-Object psobject -Property $RGHashtable
}

# Sent the final output to CSV
$Output | Export-Csv -Path test.csv -NoClobber -NoTypeInformation -Encoding UTF8 -Force
</code>```

I ran a test with just some basic data in a similar structure, because I'm not on my work machine currently.

```<code>$eur = "" | select ResourceGroupName,Location,Tags,ResourceId,ProvisioningState
$asia = "" | select ResourceGroupName,Location,Tags,ResourceId,ProvisioningState
$na = "" | select ResourceGroupName,Location,Tags,ResourceId,ProvisioningState
$sa = "" | select ResourceGroupName,Location,Tags,ResourceId,ProvisioningState

$eur.ResourceGroupName = "ParisDC"
$eur.Location = "westeurope"
$eur.ResourceId = 1
$eur.ProvisioningState = "Succeeded"
$tags = @{
    Computer = "FRDC01"
    IP = "10.11.10.10"
    Datacenter = "West Europe"
    CostCode = 54321
}
$eur.Tags = $tags

$asia.ResourceGroupName = "TokyoDC"
$asia.Location = "eastasia"
$asia.ResourceId = 2
$asia.ProvisioningState = "Succeeded"
$tags = @{
    Server = "TODC01"
    IP = "10.12.10.10"
    CostCode = 98765
}
$asia.Tags = $tags

$na.ResourceGroupName = "NewYorkDC"
$na.Location = "eastus"
$na.ResourceId = 3
$na.ProvisioningState = "Failed"
$tags = @{
    Computer = "USDC01"
    IP = "10.10.10.10"
    Owner = "John Smith"
    CostCode = 12345
}
$na.Tags = $tags

$sa.ResourceGroupName = "RioDC"
$sa.Location = "brazilsouth"
$sa.ResourceId = 4
$sa.ProvisioningState = "Succeeded"
$tags = @{}
$sa.Tags = $tags

$ResourceGroups += $sa,$na,$eur,$asia
</code>```

If you want to see the sample, just copy and paste the data, and then omit the line $ResourceGroups = Get-AzResourceGroup in the code I provided.

Resulting output:

```<code>Name      Location    Id ProvisioningState IP (Tag)    Computer (Tag) Owner (Tag) CostCode (Tag) Datacenter (Tag) Server (Tag)
----      --------    -- ----------------- --------    -------------- ----------- -------------- ---------------- ------------
RioDC     brazilsouth  4 Succeeded         -           -              -           -              -                -
NewYorkDC eastus       3 Failed            10.10.10.10 USDC01         John Smith  12345          -                -
ParisDC   westeurope   1 Succeeded         10.11.10.10 FRDC01         -           54321          West Europe      -
TokyoDC   eastasia     2 Succeeded         10.12.10.10 -              -           98765          -                TODC01
</code>```

Body:
I'm kinda new to Powershell, and I'm trying to make a script that gets all the data from Azure Resource Group (including tags) and exporting the output to CSV.

As far as I know, there are a few ways to do it, AzureCLI, AzureRM(Powershell), and Az(Powershell).

Example 1:
This "script one-liner" gets the work done, but it requires to input the actual tags, instead of retrieving it automatically from Azure

$resourceGroupList = Get-AzResourceGroup | select-Object -Property ResourceGroupName,Location,ResourceId,ProvisioningState,@{N='Enviroment (Tag)'; E={$_.Tags.Enviroment}} ,@{N='Ownership (Tag)'; E={$_.Tags.Ownership}}
$resourceGroupList | export-csv test.csv -NoTypeInformation

The other way I found is to use AzureCLI

$resourceGroupList = az group list --query "[].{ResourceGroupName:name,Location:location,ResourceType:type,provisioningState:properties,Tags:tags,ResourceGroupID:id}" -o json | convertfrom-json
$resourceGroupList | Export-Csv test.csv -NoTypeInformation

I really struggle with arrays and how to format them to be exported to CSV like in the format of Example 1.

Any help/ideas would be extremely appreciated!

Thanks!

Body:
The main thing to understand here is how to work with hashtables as that is what the Tags property contains. The other thing we need to account for is that tags are not consistent, no matter how hard we try as administrators, this will lead to inconsistent properties in our array of PSObjects if we just add properties for the tags from each individual Resource Group. So in advance of starting any sorting of the data for the CSV file, we need a unique list of tags across all groups. Resource Groups that don't have that tag, will need the property just so we have a complete set of data for the resulting CSV file. Anyway, less talking, more code.

# Initialise output array
$Output = @()

# Collect all the groups from the current subscription
$ResourceGroups = Get-AzResourceGroup

# Obtain a unique list of tags for these groups collectively
# Use Sort-Object as per - https://github.com/PowerShell/PowerShell/issues/12059
$UniqueTags = $ResourceGroups.Tags.GetEnumerator().Keys | Sort-Object -Unique

# Loop through the resource groups
foreach ($ResourceGroup in $ResourceGroups) {
    # Create a new ordered hashtable and add the normal properties first.
    $RGHashtable = [ordered] @{}
    $RGHashtable.Add("Name",$ResourceGroup.ResourceGroupName)
    $RGHashtable.Add("Location",$ResourceGroup.Location)
    $RGHashtable.Add("Id",$ResourceGroup.ResourceId)
    $RGHashtable.Add("ProvisioningState",$ResourceGroup.ProvisioningState)

    # Loop through possible tags adding the property if there is one, adding it with a hyphen as it's value if it doesn't.
    if ($ResourceGroup.Tags.Count -ne 0) {
        $UniqueTags | Foreach-Object {
            if ($ResourceGroup.Tags[$_]) {
                $RGHashtable.Add("$_ (Tag)",$ResourceGroup.Tags[$_])
            }
            else {
                $RGHashtable.Add("$_ (Tag)","-")
            }
        }
    }
    else {
        $UniqueTags | Foreach-Object { $RGHashtable.Add("$_ (Tag)","-") }
    }

    # Update the output array, adding the ordered hashtable we have created for the ResourceGroup details.
    $Output += New-Object psobject -Property $RGHashtable
}

# Sent the final output to CSV
$Output | Export-Csv -Path test.csv -NoClobber -NoTypeInformation -Encoding UTF8 -Force

I ran a test with just some basic data in a similar structure, because I'm not on my work machine currently.

$eur = "" | select ResourceGroupName,Location,Tags,ResourceId,ProvisioningState
$asia = "" | select ResourceGroupName,Location,Tags,ResourceId,ProvisioningState
$na = "" | select ResourceGroupName,Location,Tags,ResourceId,ProvisioningState
$sa = "" | select ResourceGroupName,Location,Tags,ResourceId,ProvisioningState

$eur.ResourceGroupName = "ParisDC"
$eur.Location = "westeurope"
$eur.ResourceId = 1
$eur.ProvisioningState = "Succeeded"
$tags = @{
    Computer = "FRDC01"
    IP = "10.11.10.10"
    Datacenter = "West Europe"
    CostCode = 54321
}
$eur.Tags = $tags

$asia.ResourceGroupName = "TokyoDC"
$asia.Location = "eastasia"
$asia.ResourceId = 2
$asia.ProvisioningState = "Succeeded"
$tags = @{
    Server = "TODC01"
    IP = "10.12.10.10"
    CostCode = 98765
}
$asia.Tags = $tags

$na.ResourceGroupName = "NewYorkDC"
$na.Location = "eastus"
$na.ResourceId = 3
$na.ProvisioningState = "Failed"
$tags = @{
    Computer = "USDC01"
    IP = "10.10.10.10"
    Owner = "John Smith"
    CostCode = 12345
}
$na.Tags = $tags

$sa.ResourceGroupName = "RioDC"
$sa.Location = "brazilsouth"
$sa.ResourceId = 4
$sa.ProvisioningState = "Succeeded"
$tags = @{}
$sa.Tags = $tags

$ResourceGroups += $sa,$na,$eur,$asia

If you want to see the sample, just copy and paste the data, and then omit the line $ResourceGroups = Get-AzResourceGroup in the code I provided.

Resulting output:

Name      Location    Id ProvisioningState IP (Tag)    Computer (Tag) Owner (Tag) CostCode (Tag) Datacenter (Tag) Server (Tag)
----      --------    -- ----------------- --------    -------------- ----------- -------------- ---------------- ------------
RioDC     brazilsouth  4 Succeeded         -           -              -           -              -                -
NewYorkDC eastus       3 Failed            10.10.10.10 USDC01         John Smith  12345          -                -
ParisDC   westeurope   1 Succeeded         10.11.10.10 FRDC01         -           54321          West Europe      -
TokyoDC   eastasia     2 Succeeded         10.12.10.10 -              -           98765          -                TODC01


问:
Read starts before the insert completes
```<code>@Transactional
    public void save(String myIds)
    {
            synchronized (this)
            {
                List<mydata> data = getDataToSaveOrUpdate(myIds);//Returns the new dataList and updates old data
                repository.saveAll(data);
                logger.info("request processed");
            }
        logger.debug("exiting the method");
    }
</code>```

In this method if i sent the two same request with the difference between 0.5 sec what happens getDataToSaveOrUpdate method start reading data from repository before the previous request saveAll finishes the job.

Note One thing i noticed that it will work properly once i removed @Transactional

答: Maybe what you need is LockModeType(PESSIMISTIC_WRITE).

Title: Read starts before the insert completes

Body:
@Transactional
    public void save(String myIds)
    {
            synchronized (this)
            {
                List<mydata> data = getDataToSaveOrUpdate(myIds);//Returns the new dataList and updates old data
                repository.saveAll(data);
                logger.info("request processed");
            }
        logger.debug("exiting the method");
    }

In this method if i sent the two same request with the difference between 0.5 sec what happens getDataToSaveOrUpdate method start reading data from repository before the previous request saveAll finishes the job.

Note One thing i noticed that it will work properly once i removed @Transactional


问:
Does C++ support compile-time counters?
For the purpose of introspection, sometimes I've wanted to automatically assign serial numbers to types, or something similar.

Unfortunately, template metaprogramming is essentially a functional language, and as such lacks global variables or modifiable state which would implement such a counter.

Or does it?

Example code by request:

```<code>#include <iostream>

int const a = counter_read;
counter_inc;
counter_inc;
counter_inc;
counter_inc;
counter_inc;

int const b = counter_read;

int main() {
    std::cout << a << ' ' << b << '\n'; // print "0 5"

    counter_inc_t();
    counter_inc_t();
    counter_inc_t();

    std::cout << counter_read << '\n'; // print "8"

    struct {
        counter_inc_t d1;
        char x[ counter_read ];
        counter_inc_t d2;
        char y[ counter_read ];
    } ls;

    std::cout << sizeof ls.x << ' ' << sizeof ls.y << '\n'; // print "9 10"
}
</code>```

答:
I was thinking to solve this problem for quite sometime, and have come up with a very short-clean solution. At least I deserve one upvote to try this out. :))

Following library code achieves namespace level functionality. i.e. I am successful to implement counter_read and counter_inc; but not the counter_inc_t (which is incremented inside function because template classes are not allowed inside function)

```<code>template<unsigned int NUM> struct Counter { enum { value = Counter<NUM-1>::value }; };
template<> struct Counter<0> { enum { value = 0 }; };

#define counter_read Counter<__LINE__>::value
#define counter_inc template<> struct Counter<__LINE__> { enum { value = Counter<__LINE__-1>::value + 1}; }
</code>```

This technique uses template meta-programming and leverages the __LINE__ macro.
See the result for the code from your answer.

Title: Does C++ support compile-time counters?

Body:
For the purpose of introspection, sometimes I've wanted to automatically assign serial numbers to types, or something similar.

Unfortunately, template metaprogramming is essentially a functional language, and as such lacks global variables or modifiable state which would implement such a counter.

Or does it?

Example code by request:

#include <iostream>

int const a = counter_read;
counter_inc;
counter_inc;
counter_inc;
counter_inc;
counter_inc;

int const b = counter_read;

int main() {
    std::cout << a << ' ' << b << '\n'; // print "0 5"

    counter_inc_t();
    counter_inc_t();
    counter_inc_t();

    std::cout << counter_read << '\n'; // print "8"

    struct {
        counter_inc_t d1;
        char x[ counter_read ];
        counter_inc_t d2;
        char y[ counter_read ];
    } ls;

    std::cout << sizeof ls.x << ' ' << sizeof ls.y << '\n'; // print "9 10"
}

Body:
I was thinking to solve this problem for quite sometime, and have come up with a very short-clean solution. At least I deserve one upvote to try this out. :))

Following library code achieves namespace level functionality. i.e. I am successful to implement counter_read and counter_inc; but not the counter_inc_t (which is incremented inside function because template classes are not allowed inside function)

template<unsigned int NUM> struct Counter { enum { value = Counter<NUM-1>::value }; };
template<> struct Counter<0> { enum { value = 0 }; };

#define counter_read Counter<__LINE__>::value
#define counter_inc template<> struct Counter<__LINE__> { enum { value = Counter<__LINE__-1>::value + 1}; }

This technique uses template meta-programming and leverages the __LINE__ macro.
See the result for the code from your answer.


问:
Import only tagged blocks from Ansible role
I want to import into playbook (and execute) only part of Ansible role defined in tagged block.

E.g. I have role some_role containing 3 blocks of tasks tagged as tag1, tag2 and tag3. I could create playbook that imports whole role:

```<code>---
- hosts: some_host
  roles:
    - role: roles/some_role
</code>```

And then execute it from command line specifying single tag:

```<code>$ ansible-playbook -i hosts.yml playbook.yml --tags tag1
</code>```

But I want to move --tags tag1 part into playbook itself to be able to run that single block without providing tags to ansible-playbook.

答:
Never mind.  THIS DOES NOT WORK. --Jack

Useful discussion in comments, so I'm leaving this up.

Never tried it, but give apply a shot with include_role:

```<code>---
- hosts: some_host
  tasks:
  - include_role:
      name: roles/some_role
    apply:
      tags:
      - tag1
</code>```

https://docs.ansible.com/ansible/latest/modules/include_role_module.html

Body:
I want to import into playbook (and execute) only part of Ansible role defined in tagged block.

E.g. I have role some_role containing 3 blocks of tasks tagged as tag1, tag2 and tag3. I could create playbook that imports whole role:

---
- hosts: some_host
  roles:
    - role: roles/some_role

And then execute it from command line specifying single tag:

$ ansible-playbook -i hosts.yml playbook.yml --tags tag1

But I want to move --tags tag1 part into playbook itself to be able to run that single block without providing tags to ansible-playbook.

Body:
Never mind.  THIS DOES NOT WORK. --Jack

Useful discussion in comments, so I'm leaving this up.

Never tried it, but give apply a shot with include_role:

---
- hosts: some_host
  tasks:
  - include_role:
      name: roles/some_role
    apply:
      tags:
      - tag1

https://docs.ansible.com/ansible/latest/modules/include_role_module.html


问:
How to call CMD without opening a window
I've an C++ method (using Visual Studio, if it helps) that calls to cmd like this:

```<code>start \B example.exe arg1 arg2 arg3
</code>```

The problem is that this call opens a (cmd) window. If i have another cmd opened, \B works, but if not, it opens a new window.

I also tried without start \B but it's the same....

I want to avoid this new window, but I don't know how. Any idea?

答:
From win cmd:

```<code>start /b cmd /c "example.exe arg1 arg2 arg3"
</code>```

Runs another instance of CMD without a window to run your program, and doesn't block parent window so it won't freeze.

The /q switch isn't needed (won't work anyway) and will give error:

```<code>'/q' is not recognized as an internal or external command,
operable program or batch file.
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I've an C++ method (using Visual Studio, if it helps) that calls to cmd like this:

start \B example.exe arg1 arg2 arg3

The problem is that this call opens a (cmd) window. If i have another cmd opened, \B works, but if not, it opens a new window.

I also tried without start \B but it's the same....

I want to avoid this new window, but I don't know how. Any idea?

Body:
From win cmd:

start /b cmd /c "example.exe arg1 arg2 arg3"

Runs another instance of CMD without a window to run your program, and doesn't block parent window so it won't freeze.

The /q switch isn't needed (won't work anyway) and will give error:

'/q' is not recognized as an internal or external command,
operable program or batch file.


问:
Symfony forms Length constraint overrides NotBlank constraint
So in my form I have a field to insert password. On the field in the formbuilder I added 2 constraints; one for if the field is empty and one for if the password is too short.

```<code>new NotBlank([
    'message' => 'reset.password.error.enterpassword',
]),
new Length([
    'min' => 6,
    'minMessage' => 'reset.password.error.passwordtooshort',
    // max length allowed by Symfony for security reasons
    'max' => 4096,
]),
</code>```

However, when I leave the password field empty, it will use the Length constraint (I kind of understand, as the password with length 0 is lower than 6), but shouldn't it use the NotBlank constraint since it's defined?

I also tried putting it after the Length constraint but it still didn't work.

答:
The behaviour of the Length validator has changed in recent symfony versions.

Formerly it did not match empty inputs.

The option allowEmptyString controls wether empty strings are allowed.

It defaults to false while older symfony versions defaulted to true.

See the documentation Length#allowemptystring.

Set allowEmptyString to true to solve your issue:

new Length([
    'allowEmptyString' => true,
    'min' => 6,
    'minMessage' => 'reset.password.error.passwordtooshort',
    // max length allowed by Symfony for security reasons
    'max' => 4096,
]),
new NotBlank([
    'message' => 'reset.password.error.enterpassword',
]),
```

Body:
So in my form I have a field to insert password. On the field in the formbuilder I added 2 constraints; one for if the field is empty and one for if the password is too short.

new NotBlank([
    'message' => 'reset.password.error.enterpassword',
]),
new Length([
    'min' => 6,
    'minMessage' => 'reset.password.error.passwordtooshort',
    // max length allowed by Symfony for security reasons
    'max' => 4096,
]),

However, when I leave the password field empty, it will use the Length constraint (I kind of understand, as the password with length 0 is lower than 6), but shouldn't it use the NotBlank constraint since it's defined?

I also tried putting it after the Length constraint but it still didn't work.


问:
Check if value is false, true or null
I want to check if variable is false, true or null. If null or undefined assign array to the variable by default. In other languages this syntax would be just fine to use. In js however when value is false then it assign array to myBool

const boolFromBody = false;
const myBool = boolFromBody || [true, false];
console.log(myBool)```
</div>
</div>
</p>

<p>I managed to do it with this syntax where I only check for null value</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const boolFromBody = null;
let otherBool = boolFromBody;
if (boolFromBody === null) {
  otherBool = [true, false]
}
console.log(otherBool);</code>```

Is there any better way to do it in js?

答:
Nullish coalescing.

Checks if a variable is either null or undefined and assign it to a default value if it's the case. 0 or false are not considered as nullish and will be assigned to the value.

The nullish coalescing operator ?? acts very similar to the || operator, except that we don’t use “truthy” when evaluating the operator. Instead we use the definition of nullish, meaning “is the value strictly equal to null or undefined?”

let a = null;

let b = a ?? "test";

console.log(b);```
</div>
</div>
</p>

<p>Example with <code>false</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let a = false;

let b = a ?? "test";

console.log(b);</code>```

Title: Check if value is false, true or null

Body:
I want to check if variable is false, true or null. If null or undefined assign array to the variable by default. In other languages this syntax would be just fine to use. In js however when value is false then it assign array to myBool

const boolFromBody = false;
const myBool = boolFromBody || [true, false];
console.log(myBool)

I managed to do it with this syntax where I only check for null value

const boolFromBody = null;
let otherBool = boolFromBody;
if (boolFromBody === null) {
  otherBool = [true, false]
}
console.log(otherBool);

Is there any better way to do it in js?

Body:
Nullish coalescing.

Checks if a variable is either null or undefined and assign it to a default value if it's the case. 0 or false are not considered as nullish and will be assigned to the value.

The nullish coalescing operator ?? acts very similar to the || operator, except that we don’t use “truthy” when evaluating the operator. Instead we use the definition of nullish, meaning “is the value strictly equal to null or undefined?”

let a = null;

let b = a ?? "test";

console.log(b);

Example with false

let a = false;

let b = a ?? "test";

console.log(b);


问:
Audio streaming through MediaLive server
I want to have live audio streaming and broadcasting setup. I would stream audio from laptop or mobile through Altacast/rtpmic or any cast to inputs of AWS Elemental MediaLive Input.

I setup AWS Elemental MediaLive Input (RTMP) and then had a AWS MediaPackage configured ahead of it. I created endpoints from MediaPackage.

I tried streaming audio from rtpmic to a IPv4 address and port number provided that I got from Elemental MediaLive and tried to hit the endpoints (output) that I got from MediaPackage. But I keep getting "error 404" at the endpoints. I have also setup channels which takes up input from MediaLive output. And the channels have endpoint which I am trying to check for output.

Where do you think I might be going wrong? How can I investigate if Inputs of Elemental MediaLive is getting Audio? Cant I use AWS Elemental MediaLive for audio streaming?

I am new to this, so please excuse me if I am stating anything incorrectly or not providing any information correctly.

答:
I spoke with chat support of AWS Media Live, and I understand that they havent created Elemental MediaLive for audio only streaming. Hence it cannot be done, what I was thinking to do. Users have tried sending black screen as video input and audio, but thats not the ideal way of doing it.

I am trying wowza now.


问:
Why is Git Windows committing on merge, even with merge.commit=no?
I am using Git Bash in Windows 10, version: git version 2.25.1.windows.1. Let me know if I need to be more specific. I am also using GitExtensions but my question is around merging from Git Bash.

When I merge from there, i.e.:

git merge feature-branch-name

it commits even though, as far as I can tell, all three of my Git config files are set otherwise. I know I can specify --no-commit in the command but I would like not to have to do that.

From the source code directory, git config --list produces the output below, where it shows three times that merge.commit=no.

```<code>diff.astextplain.textconv=astextplain
filter.lfs.clean=git-lfs clean -- %f
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.process=git-lfs filter-process
filter.lfs.required=true
http.sslbackend=openssl
http.sslcainfo=C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt
core.autocrlf=false
core.fscache=true
core.symlinks=false
core.editor="C:\\Program Files\\Notepad++\\notepad++.exe" -multiInst -notabbar -nosession -noPlugin
credential.helper=manager
merge.ff=no
merge.commit=no
core.editor="C:/Program Files (x86)/GitExtensions/GitExtensions.exe" fileeditor
user.email=craig@wereallconnected.ca
user.name=Craig Silver
merge.tool=winmerge
merge.ff=no
merge.commit=no
mergetool.winmerge.path=C:/Program Files (x86)/WinMerge/winmergeu.exe
mergetool.winmerge.cmd="C:/Program Files (x86)/WinMerge/winmergeu.exe" -e -u  -wl -wr -fm -dl "Mine: $LOCAL" -dm "Merged: $BASE" -dr "Theirs: $REMOTE" "$LOCAL" "$BASE" "$REMOTE" -o "$MERGED"
pull.rebase=false
fetch.prune=false
rebase.autostash=false
diff.guitool=winmerge
difftool.winmerge.path=C:/Program Files (x86)/WinMerge/winmergeu.exe
difftool.winmerge.cmd="C:/Program Files (x86)/WinMerge/winmergeu.exe" -e -u "$LOCAL" "$REMOTE"
core.repositoryformatversion=0
core.filemode=false
core.bare=false
core.logallrefupdates=true
core.ignorecase=true
core.sshcommand=ssh
merge.ff=no
merge.commit=no
submodule.active=.
remote.origin.url=REMOVED
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
remote.origin.puttykeyfile=REMOVED
branch.master.remote=origin
branch.master.merge=refs/heads/master
branch.FMS-1203_data-structures-algorithms-string-matching.remote=origin
branch.FMS-1203_data-structures-algorithms-string-matching.merge=refs/heads/FMS-1203_data-structures-algorithms-string-matching
branch.FMS-1205_recency-trumps-frequency-for-small-fr-diff.remote=origin
branch.FMS-1205_recency-trumps-frequency-for-small-fr-diff.merge=refs/heads/FMS-1205_recency-trumps-frequency-for-small-fr-diff
branch.FMS-1204_debug-window.remote=origin
branch.FMS-1204_debug-window.merge=refs/heads/FMS-1204_debug-window
</code>```

Also, git config --get merge.commit outputs no.

FYI, GitExtensions behaves correctly: merging there does not commit.

What am I missing?

答:
As far as I can see - there is no merge.commit option that you can set, only merge.ff. See https://git-scm.com/docs/git-merge#_configuration.

What you can do is declare an alias that runs merge with the wanted option

```<code>git config alias.mr 'merge --no-commit'
</code>```

Body:
I am using Git Bash in Windows 10, version: git version 2.25.1.windows.1. Let me know if I need to be more specific. I am also using GitExtensions but my question is around merging from Git Bash.

When I merge from there, i.e.:

git merge feature-branch-name

it commits even though, as far as I can tell, all three of my Git config files are set otherwise. I know I can specify --no-commit in the command but I would like not to have to do that.

From the source code directory, git config --list produces the output below, where it shows three times that merge.commit=no.

diff.astextplain.textconv=astextplain
filter.lfs.clean=git-lfs clean -- %f
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.process=git-lfs filter-process
filter.lfs.required=true
http.sslbackend=openssl
http.sslcainfo=C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt
core.autocrlf=false
core.fscache=true
core.symlinks=false
core.editor="C:\\Program Files\\Notepad++\\notepad++.exe" -multiInst -notabbar -nosession -noPlugin
credential.helper=manager
merge.ff=no
merge.commit=no
core.editor="C:/Program Files (x86)/GitExtensions/GitExtensions.exe" fileeditor
user.email=craig@wereallconnected.ca
user.name=Craig Silver
merge.tool=winmerge
merge.ff=no
merge.commit=no
mergetool.winmerge.path=C:/Program Files (x86)/WinMerge/winmergeu.exe
mergetool.winmerge.cmd="C:/Program Files (x86)/WinMerge/winmergeu.exe" -e -u  -wl -wr -fm -dl "Mine: $LOCAL" -dm "Merged: $BASE" -dr "Theirs: $REMOTE" "$LOCAL" "$BASE" "$REMOTE" -o "$MERGED"
pull.rebase=false
fetch.prune=false
rebase.autostash=false
diff.guitool=winmerge
difftool.winmerge.path=C:/Program Files (x86)/WinMerge/winmergeu.exe
difftool.winmerge.cmd="C:/Program Files (x86)/WinMerge/winmergeu.exe" -e -u "$LOCAL" "$REMOTE"
core.repositoryformatversion=0
core.filemode=false
core.bare=false
core.logallrefupdates=true
core.ignorecase=true
core.sshcommand=ssh
merge.ff=no
merge.commit=no
submodule.active=.
remote.origin.url=REMOVED
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
remote.origin.puttykeyfile=REMOVED
branch.master.remote=origin
branch.master.merge=refs/heads/master
branch.FMS-1203_data-structures-algorithms-string-matching.remote=origin
branch.FMS-1203_data-structures-algorithms-string-matching.merge=refs/heads/FMS-1203_data-structures-algorithms-string-matching
branch.FMS-1205_recency-trumps-frequency-for-small-fr-diff.remote=origin
branch.FMS-1205_recency-trumps-frequency-for-small-fr-diff.merge=refs/heads/FMS-1205_recency-trumps-frequency-for-small-fr-diff
branch.FMS-1204_debug-window.remote=origin
branch.FMS-1204_debug-window.merge=refs/heads/FMS-1204_debug-window

Also, git config --get merge.commit outputs no.

FYI, GitExtensions behaves correctly: merging there does not commit.

What am I missing?

Body:
As far as I can see - there is no merge.commit option that you can set, only merge.ff. See https://git-scm.com/docs/git-merge#_configuration.

What you can do is declare an alias that runs merge with the wanted option

git config alias.mr 'merge --no-commit'


问:
One liner to remove all occurrences of sub-strings in array with filter?
The title pretty much explains the question. I'd like to filter through an array and remove all occurrences of substrings. Similiar to how can be done by matching entire strings to remove like this

```<code>const x = ["don't delete", "delete", "delete", "don't delete", "delete", "don't delete"]
x= x.filter(i => i !== 'delete me');

> console.log(x)
["don't delete", "don't delete", "don't delete"]
</code>```

So let's say I want to just remove all the occurances of ' so every don't becomes dont, or maybe I just want to remove the every don't all together. I know you can match substrings with includes() but not sure how to implement it with a filter.

How could I go about this in a one liner? Thanks

答:
You can try the following way using includes():

const x = ["don't delete", "delete", "delete", "don't delete", "delete", "don't delete"]
var y = x.filter(i => i.includes("don't"));

console.log(y);```

Please Note: The value of a constant can't be changed through reassignment, and it can't be redeclared.

Body:
The title pretty much explains the question. I'd like to filter through an array and remove all occurrences of substrings. Similiar to how can be done by matching entire strings to remove like this

const x = ["don't delete", "delete", "delete", "don't delete", "delete", "don't delete"]
x= x.filter(i => i !== 'delete me');

> console.log(x)
["don't delete", "don't delete", "don't delete"]

So let's say I want to just remove all the occurances of ' so every don't becomes dont, or maybe I just want to remove the every don't all together. I know you can match substrings with includes() but not sure how to implement it with a filter.

How could I go about this in a one liner? Thanks

Body:
You can try the following way using includes():

const x = ["don't delete", "delete", "delete", "don't delete", "delete", "don't delete"]
var y = x.filter(i => i.includes("don't"));

console.log(y);

Please Note: The value of a constant can't be changed through reassignment, and it can't be redeclared.


问:
How to get rid of double quotes wrapping serverless-offline html response body?
I'm trying to get a HTML response from my serverless-offline project, but it returns html body wrapped with double quotes, which ruins the page. How can I get rid of the quotes?

Content-type looks valid

I have this versions of serverless plugins installed

```<code>"serverless-base-path-plugin": "0.0.1",
    "serverless-cors-plugin": "^0.2.1",
    "serverless": "1.71.3",
    "serverless-offline": "6.1.7",
    "serverless-optimizer-plugin": "^1.0.0",
    "serverless-resources-validation-plugin": "^0.2.0",
    "serverless-helpers-js": "0.2.0",
    "serverless-webpack": "5.3.2",
</code>```

serverless.yml

```<code>provider:
  name: aws
  runtime: nodejs8.10
  region: eu-west-1
  profile: default
  memorySize: 256 # optional, in MB, default is 1024
  stage: local

plugins:
  - serverless-offline

custom:
  serverless-offline:
    host: 0.0.0.0
    httpPort: 1465
    useDocker: false
    noPrependStageInUrl: true

functions:
  xdomainProxy:
    handler: dist/xdomain-proxy/handler.handler
    events:
      - http:
         path: /api/xdomain-proxy
         method: get
         integration: lambda
         response:
            headers:
                Content-Type: "'text/html'"
</code>```

handler.js

```<code>'use strict';

var ServerlessHelpers = require('serverless-helpers-js').loadEnv(); // all content must be assembled into a single variable

function render() {
  return ['<!DOCTYPE HTML>', '<link rel="shortcut icon" href="about:blank">', '<script src="https://cdn.rawgit.com/jpillora/xdomain/0.7.4/dist/xdomain.min.js"></script>'].join(' ');
} // Lambda Handler

module.exports.handler = function (event, context) {
  try {
      var html = render();
      context.succeed(html);
  } catch (err) {
    console.log(err);
    context.fail(err);
  }
};
</code>```

答: Ok, looks like it's serverless-offline version 6 issue. I could find out that it runs json.stringify if you try to return a string. Downgrading to version 5 solved the issue for me.</p>

Body:
I'm trying to get a HTML response from my serverless-offline project, but it returns html body wrapped with double quotes, which ruins the page. How can I get rid of the quotes?

Content-type looks valid

I have this versions of serverless plugins installed

"serverless-base-path-plugin": "0.0.1",
    "serverless-cors-plugin": "^0.2.1",
    "serverless": "1.71.3",
    "serverless-offline": "6.1.7",
    "serverless-optimizer-plugin": "^1.0.0",
    "serverless-resources-validation-plugin": "^0.2.0",
    "serverless-helpers-js": "0.2.0",
    "serverless-webpack": "5.3.2",

serverless.yml

provider:
  name: aws
  runtime: nodejs8.10
  region: eu-west-1
  profile: default
  memorySize: 256 # optional, in MB, default is 1024
  stage: local

plugins:
  - serverless-offline

custom:
  serverless-offline:
    host: 0.0.0.0
    httpPort: 1465
    useDocker: false
    noPrependStageInUrl: true

functions:
  xdomainProxy:
    handler: dist/xdomain-proxy/handler.handler
    events:
      - http:
         path: /api/xdomain-proxy
         method: get
         integration: lambda
         response:
            headers:
                Content-Type: "'text/html'"

handler.js

'use strict';

var ServerlessHelpers = require('serverless-helpers-js').loadEnv(); // all content must be assembled into a single variable

function render() {
  return ['<!DOCTYPE HTML>', '<link rel="shortcut icon" href="about:blank">', ''].join(' ');
} // Lambda Handler

module.exports.handler = function (event, context) {
  try {
      var html = render();
      context.succeed(html);
  } catch (err) {
    console.log(err);
    context.fail(err);
  }
};


答:
The code that you have for storing the userResult is not a promise, is a subscription:

async readUser(id){
     // this block is wrong, userResult is a subscription
     this.userResult = await this.http.get<user>("http://localhost:8090/user/" +id).subscribe(
       data => {
         this.user = data;
       },
       error =>{
         return console.error();
         ;
       }
     )
    console.log("Fuuhhh! Client will wait till promise is resolved.");
  }
```

<p>If you want to use promises (but you should you observables in Angular) you can do it using <code>toPromise()</code> method like this:</p>

<pre class="lang-js prettyprint-override"><code>async readUser(id){
     try {
       this.userResult = await this.http.get<user>("http://localhost:8090/user/" +id).toPromise();
       this.user = this.userResult // if you really want an extra step here
    } catch(error) {
      console.log(error);
    }
  }
</code>```

Regarding your question, you should use *ngIf for this case.

For blocks of code use it with ng-container like so:

<ng-container *ngIf="user">
   .....
</ng-container>
```

Title: How can I avoid using *ngIf in an Angular template?

Body:
I tried using async/await to avoid *ngIf in the component template.

I'm getting an error in the Chrome console when I remove *ngIf in component template.

Can anyone help to get a solution. I do not want to use *ngIf in the component template as a requirement

I'm calling the GET REST API and used subscribe. Also, I'm getting results without the error if I'm using *ngIf, but I want the same results without using *ngIf

CODE:
component.ts

export class DisplayComponent implements OnInit {
users : user[];
user: user;
userResult: any;

  constructor(private http: HttpClient) { }

  ngOnInit() {
  }

  async readUser(id){
     this.userResult = await this.http.get<user>("http://localhost:8090/user/" +id).subscribe(
       data => {
         this.user = data;
       },
       error =>{
         return console.error();
         ;
       }
     )
    console.log("Fuuhhh! Client will wait till promise is resolved.");
  }
}

CODE: DisplayComponent.html

    <button (click)="loadUsers()">load Users</button>

            Identity

            <button style="background: transparent;border: transparent;cursor: pointer;" (click)="readUser(user.id)">{{user?.id}}</button>

    Identity: {{user.id}}

    Name: {{user.name}}

    School: {{user.school}}

Body:
The code that you have for storing the userResult is not a promise, is a subscription:

async readUser(id){
     // this block is wrong, userResult is a subscription
     this.userResult = await this.http.get<user>("http://localhost:8090/user/" +id).subscribe(
       data => {
         this.user = data;
       },
       error =>{
         return console.error();
         ;
       }
     )
    console.log("Fuuhhh! Client will wait till promise is resolved.");
  }

If you want to use promises (but you should you observables in Angular) you can do it using toPromise() method like this:

async readUser(id){
     try {
       this.userResult = await this.http.get<user>("http://localhost:8090/user/" +id).toPromise();
       this.user = this.userResult // if you really want an extra step here
    } catch(error) {
      console.log(error);
    }
  }

Regarding your question, you should use *ngIf for this case.

For blocks of code use it with ng-container like so:

<ng-container *ngIf="user">
   .....
</ng-container>


问:
Mysql query WHERE column is in json array
I have setup an query where it selects multiple things.

```<code>$stm = $db->query('SELECT startUser, forUser, percentage, time, taskTitle, taskDesc, color FROM admin_task WHERE forUser = "'.$queryanswer.'")');
</code>```

But for user is like this in the DB:

```<code>["demo","   user"]
</code>```

How can I check if forUser (the json array above) has demo? can i even check this?

答:
```<code>SELECT startUser,
forUser,
percentage,
time,
taskTitle,
taskDesc,
color
FROM admin_task WHERE JSON_SEARCH(forUser -> '$[*]', 'one', 'demo');
</code>```

Body:
I have setup an query where it selects multiple things.

$stm = $db->query('SELECT startUser, forUser, percentage, time, taskTitle, taskDesc, color FROM admin_task WHERE forUser = "'.$queryanswer.'")');

But for user is like this in the DB:

["demo","   user"]

How can I check if forUser (the json array above) has demo? can i even check this?


问:
float not working in mysql database
i am using $_GET['var'] to get a variable then compare it with a variable in my database. the variable is 1.1 the var is set to "float" on the database so i know it can handle decimals but when i compare them with the code below i get nothing.</p>

```<code>include 'connect.php';

$sql=mysql_query("SELECT * FROM table WHERE stuff='$stuff'");

while ($row=mysql_fetch_assoc($sql)) {

$start=$row['start'];

}

echo $start; //nothing happens
</code>```

答:
Change the stuff field to DOUBLE type.
Then,

```<code>SELECT * FROM table WHERE stuff=$stuff
</code>```

this should be the sql query

Title: float not working in mysql database

Body:
i am using $_GET['var'] to get a variable then compare it with a variable in my database. the variable is 1.1 the var is set to "float" on the database so i know it can handle decimals but when i compare them with the code below i get nothing.

include 'connect.php';

$sql=mysql_query("SELECT * FROM table WHERE stuff='$stuff'");

while ($row=mysql_fetch_assoc($sql)) {

$start=$row['start'];

}

echo $start; //nothing happens

Body:
Change the stuff field to DOUBLE type.
Then,

SELECT * FROM table WHERE stuff=$stuff

this should be the sql query


问:
call different function during page refresh and close javascript
I am creating a web app using web socket, which on user closes the tab I will make an API call to the server to clean the user related info in the server, I used onBeforeUnload listener in javascript, but this method also gets triggered during the page refresh.

I need to trigger a method only during the tab or browser close, but not during the page refresh.

I know this question has been asked several times, some solution suggested using cookies will not be helpful in my case

答:
As far as I know, you can not listen to actions of browser's tab close or exits. For your application it is an "unload", whatever caused it...

The only thing I could think about is maybe add a listener for keyboard key press (F5), however it doesn't help in case someone refreshed by clicking on the browser's refresh button.

I don't know what is the use case, but most of the things should be done when a page unloads (no matter why) and/or when the page is back up again. So most of the solutions are for situations where your page is loaded again - and then you can determine what was the source of the load and make farther actions, but since you have an option were someone can close and never come back, that might not be the case.

Some solutions for page load up:

You can use Navigation type.

You can check referer.

You can use cookies or other types of browser storage.

I would recommend to rethink about your use case. Maybe you can do whatever you want on load up or leave it on onBeforeUnLoad without knowing the future :)


问:
Why are elements of my array being over written?
I have written a simple function in Python which aims to find, if from two elements a and b, one can be obtained from another by swapping at most one pair of elements in one of the arrays.

This is my function:

```<code>def areSimilar(a, b):
    test = 0
    for i in range(len(b)):
        for j in range(len(b)):
            b2 = b
            b2[i] = b[j]
            b2[j] = b[i]
            if a == b2:
                test = 1
    return(test==1)
</code>```

The issue is that upon inspecting b, it has changed even though I don't actually perform any calculations on b - what's going on!!??

答:
(EDITED: to better address the second point)

There are two issues with your code:

When you do b2 = b this just creates another reference to the underlying object. If b is mutable, any change made to b2 will be reflected in b too.

When a single swapping suffices there is no need to test further, but if you keep on looping the test will be successful again with i and j swapped, so test condition is hit either never or (at least -- depending on the amount of duplicates) twice. While this would not lead to incorrect results, it would normally be regarded as an error in the logic.

To fix your code, you could just create a copy of b. Assuming that by Python arrays you actually mean Python lists one way of doing it would be to create a new list every time by replacing b2 = b with b2 = list(b). A more efficient approach is to perform the swapping on b itself (and swap back):

```<code>def are_similar(a, b):
    for i in range(len(b)):
        for j in range(len(b)):
            b[i], b[j] = b[j], b[i]
            if a == b:
                b[i], b[j] = b[j], b[i]  # swap back
                return True
            else:
                b[i], b[j] = b[j], b[i]  # swap back
    return False

print(are_similar([1, 1, 2, 3], [1, 2, 1, 3]))
# True
print(are_similar([1, 1, 2, 3], [3, 2, 1, 1]))
# False
</code>```

By contrast, you can see how inefficient (while correct) the copying-based approach is:

```<code>def are_similar2(a, b):
    for i in range(len(b)):
        for j in range(len(b)):
            b2 = list(b)
            b2[i] = b[j]
            b2[j] = b[i]
            if a == b2:
                return True
    return False

print(are_similar2([1, 1, 2, 3], [1, 2, 1, 3]))
# True
print(are_similar2([1, 1, 2, 3], [3, 2, 1, 1]))
# False
</code>```

with much worse timings, even on relatively small inputs:

```<code>a = [1, 1, 2, 3] + list(range(100))
b = [1, 2, 1, 3] + list(range(100))
%timeit are_similar(a, b)
# 10000 loops, best of 3: 22.9 µs per loop
%timeit are_similar2(a, b)
# 10000 loops, best of 3: 73.9 µs per loop
</code>```

Body:
I have written a simple function in Python which aims to find, if from two elements a and b, one can be obtained from another by swapping at most one pair of elements in one of the arrays.

This is my function:

def areSimilar(a, b):
    test = 0
    for i in range(len(b)):
        for j in range(len(b)):
            b2 = b
            b2[i] = b[j]
            b2[j] = b[i]
            if a == b2:
                test = 1
    return(test==1)

The issue is that upon inspecting b, it has changed even though I don't actually perform any calculations on b - what's going on!!??

Body:
(EDITED: to better address the second point)

There are two issues with your code:

When you do b2 = b this just creates another reference to the underlying object. If b is mutable, any change made to b2 will be reflected in b too.

When a single swapping suffices there is no need to test further, but if you keep on looping the test will be successful again with i and j swapped, so test condition is hit either never or (at least -- depending on the amount of duplicates) twice. While this would not lead to incorrect results, it would normally be regarded as an error in the logic.

To fix your code, you could just create a copy of b. Assuming that by Python arrays you actually mean Python lists one way of doing it would be to create a new list every time by replacing b2 = b with b2 = list(b). A more efficient approach is to perform the swapping on b itself (and swap back):

def are_similar(a, b):
    for i in range(len(b)):
        for j in range(len(b)):
            b[i], b[j] = b[j], b[i]
            if a == b:
                b[i], b[j] = b[j], b[i]  # swap back
                return True
            else:
                b[i], b[j] = b[j], b[i]  # swap back
    return False

print(are_similar([1, 1, 2, 3], [1, 2, 1, 3]))
# True
print(are_similar([1, 1, 2, 3], [3, 2, 1, 1]))
# False

By contrast, you can see how inefficient (while correct) the copying-based approach is:

def are_similar2(a, b):
    for i in range(len(b)):
        for j in range(len(b)):
            b2 = list(b)
            b2[i] = b[j]
            b2[j] = b[i]
            if a == b2:
                return True
    return False

print(are_similar2([1, 1, 2, 3], [1, 2, 1, 3]))
# True
print(are_similar2([1, 1, 2, 3], [3, 2, 1, 1]))
# False

with much worse timings, even on relatively small inputs:

a = [1, 1, 2, 3] + list(range(100))
b = [1, 2, 1, 3] + list(range(100))
%timeit are_similar(a, b)
# 10000 loops, best of 3: 22.9 µs per loop
%timeit are_similar2(a, b)
# 10000 loops, best of 3: 73.9 µs per loop


问:
How to return closure from function in Rust language?
I am pretty new to Rust language and trying to make with Actix web framework. Now I want to return following closure from one function

```<code>let list = || {
    App::new()
        // enable logger
        .wrap(middleware::Logger::default())
        .service(web::resource("/index.html").to(|| async { "Hello world!" }))
        .service(web::resource("/").to(index::home))
        .service(web::resource("/h2").to(index::home2))
};
</code>```

So, I can consume that with

```<code>HttpServer::new(routes::list())
.bind("127.0.0.1:8080")?
.run()
.await
</code>```

So, what will be the signature of Rust function will be?

答:
This is what impl trait is for: the closure type itself doesn't have a name, but it allows you to say "function returns some type satisfying these trait bounds" without naming the type. So it should be

```<code>fn list() -> impl Fn() -> ???
</code>```

Where ??? should be replaced by the return type. See "impl Trait and closures" section in the link for another example.

But note that there still must be a single return type, so you can't e.g. return one of several closures depending on some condition, their types are different!

Body:
I am pretty new to Rust language and trying to make with Actix web framework. Now I want to return following closure from one function

let list = || {
    App::new()
        // enable logger
        .wrap(middleware::Logger::default())
        .service(web::resource("/index.html").to(|| async { "Hello world!" }))
        .service(web::resource("/").to(index::home))
        .service(web::resource("/h2").to(index::home2))
};

So, I can consume that with

HttpServer::new(routes::list())
.bind("127.0.0.1:8080")?
.run()
.await

So, what will be the signature of Rust function will be?

Body:
This is what impl trait is for: the closure type itself doesn't have a name, but it allows you to say "function returns some type satisfying these trait bounds" without naming the type. So it should be

fn list() -> impl Fn() -> ???

Where ??? should be replaced by the return type. See "impl Trait and closures" section in the link for another example.

But note that there still must be a single return type, so you can't e.g. return one of several closures depending on some condition, their types are different!