问:
maven - Spring Boot/Angular 2/4 project war build
I have a Spring Boot and Angular 2/4 project that I want to package into a single WAR and serve on Tomcat. I have a parent project with 2 modules (1 for Angular and 1 for Spring Boot), with the following pom.xml configurations:

parent/pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>mk.edu.ukim.feit.bolt</groupId>
<artifactId>parent</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.3.RELEASE</version>
    <relativePath/>
</parent>

<modules>
    <module>api</module>
    <module>frontend</module>
</modules>
</code>```

frontend/pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<artifactId>frontend</artifactId>

<name>Bolt Client</name>
<description>Bolt messaging app frontend client</description>

<parent>
    <groupId>mk.edu.ukim.feit.bolt</groupId>
    <artifactId>parent</artifactId>
    <version>1.0-SNAPSHOT</version>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>com.github.eirslett</groupId>
            <artifactId>frontend-maven-plugin</artifactId>
            <version>1.4</version>

            <configuration>
                <nodeVersion>v7.9.0</nodeVersion>
                <npmVersion>4.6.1</npmVersion>
                <workingDirectory>src/main/frontend</workingDirectory>
            </configuration>

            <executions>
                <execution>
                    <id>install node and npm</id>
                    <goals>
                        <goal>install-node-and-npm</goal>
                    </goals>
                </execution>

                <execution>
                    <id>npm install</id>
                    <goals>
                        <goal>npm</goal>
                    </goals>
                </execution>

                <execution>
                    <id>npm run prod</id>

                    <goals>
                        <goal>npm</goal>
                    </goals>

                    <configuration>
                        <arguments>run prod</arguments>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>

    <resources>
        <resource>
            <directory>target/frontend</directory>
            <targetPath>static</targetPath>
        </resource>
    </resources>
</build>
</code>```

api/pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<artifactId>api</artifactId>
<version>1.0-SNAPSHOT</version>

<name>Bolt API</name>
<description>Bolt messaging app REST API</description>
<packaging>war</packaging>

<parent>
    <groupId>mk.edu.ukim.feit.bolt</groupId>
    <artifactId>parent</artifactId>
    <version>1.0-SNAPSHOT</version>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <!--<dependency>-->
        <!--<groupId>org.springframework.boot</groupId>-->
        <!--<artifactId>spring-boot-starter-jdbc</artifactId>-->
    <!--</dependency>-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web-services</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-mail -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
        <version>1.5.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-logging</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.restdocs</groupId>
        <artifactId>spring-restdocs-mockmvc</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>${h2.version}</version>
        <scope>compile</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt -->
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.6.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/joda-time/joda-time -->
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>2.9.9</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-validator/commons-validator -->
    <dependency>
        <groupId>commons-validator</groupId>
        <artifactId>commons-validator</artifactId>
        <version>1.6</version>
    </dependency>
    <dependency>
        <groupId>mk.edu.ukim.feit.bolt</groupId>
        <artifactId>frontend</artifactId>
        <version>${project.version}</version>
        <scope>runtime</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

I was following this tutorial and I ended up successfully building the project running mvn clean install from the parent directory, then going into the api directory and running mvn spring-boot:run, the application is served on localhost:8080, however while building the war file Maven somehow doesn't pick up the static files compiled from Angular and gives me a 404 on http://localhost:8080. Could anyone give tips on what might be wrong here?

I also tried setting the "prod" NPM script to "ng build --prod --base-href=\"./\"" thinking it might have to do something with it but it didn't help. Any ideas?

答:
The solution I found:

Copy a single "index.html" file to "src/main/resources/templates"
folder under server project. Please note that HTML file structure must be very strict (all opened tags must be closed etc).

Add maven dependency "spring-boot-starter-thymeleaf"

Create HomeController for request mapping "/" to "index" template

Sample:

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

See GitHub commit with HomeController

Would be great if someone know more cleaner/nicer solution and could share.

Body:
I have a Spring Boot and Angular 2/4 project that I want to package into a single WAR and serve on Tomcat. I have a parent project with 2 modules (1 for Angular and 1 for Spring Boot), with the following pom.xml configurations:

parent/pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>mk.edu.ukim.feit.bolt</groupId>
<artifactId>parent</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.3.RELEASE</version>
    <relativePath/>
</parent>

<modules>
    <module>api</module>
    <module>frontend</module>
</modules>

frontend/pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<artifactId>frontend</artifactId>

<name>Bolt Client</name>
<description>Bolt messaging app frontend client</description>

<parent>
    <groupId>mk.edu.ukim.feit.bolt</groupId>
    <artifactId>parent</artifactId>
    <version>1.0-SNAPSHOT</version>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>com.github.eirslett</groupId>
            <artifactId>frontend-maven-plugin</artifactId>
            <version>1.4</version>

            <configuration>
                <nodeVersion>v7.9.0</nodeVersion>
                <npmVersion>4.6.1</npmVersion>
                <workingDirectory>src/main/frontend</workingDirectory>
            </configuration>

            <executions>
                <execution>
                    <id>install node and npm</id>
                    <goals>
                        <goal>install-node-and-npm</goal>
                    </goals>
                </execution>

                <execution>
                    <id>npm install</id>
                    <goals>
                        <goal>npm</goal>
                    </goals>
                </execution>

                <execution>
                    <id>npm run prod</id>

                    <goals>
                        <goal>npm</goal>
                    </goals>

                    <configuration>
                        <arguments>run prod</arguments>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>

    <resources>
        <resource>
            <directory>target/frontend</directory>
            <targetPath>static</targetPath>
        </resource>
    </resources>
</build>

api/pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<artifactId>api</artifactId>
<version>1.0-SNAPSHOT</version>

<name>Bolt API</name>
<description>Bolt messaging app REST API</description>
<packaging>war</packaging>

<parent>
    <groupId>mk.edu.ukim.feit.bolt</groupId>
    <artifactId>parent</artifactId>
    <version>1.0-SNAPSHOT</version>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web-services</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
        <version>1.5.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-logging</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.restdocs</groupId>
        <artifactId>spring-restdocs-mockmvc</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>${h2.version}</version>
        <scope>compile</scope>
    </dependency>

    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.6.0</version>
    </dependency>

    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>2.9.9</version>
    </dependency>

    <dependency>
        <groupId>commons-validator</groupId>
        <artifactId>commons-validator</artifactId>
        <version>1.6</version>
    </dependency>
    <dependency>
        <groupId>mk.edu.ukim.feit.bolt</groupId>
        <artifactId>frontend</artifactId>
        <version>${project.version}</version>
        <scope>runtime</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

I was following this tutorial and I ended up successfully building the project running mvn clean install from the parent directory, then going into the api directory and running mvn spring-boot:run, the application is served on localhost:8080, however while building the war file Maven somehow doesn't pick up the static files compiled from Angular and gives me a 404 on http://localhost:8080. Could anyone give tips on what might be wrong here?

I also tried setting the "prod" NPM script to "ng build --prod --base-href=\"./\"" thinking it might have to do something with it but it didn't help. Any ideas?

Body:
The solution I found:

Copy a single "index.html" file to "src/main/resources/templates"
folder under server project. Please note that HTML file structure must be very strict (all opened tags must be closed etc).

Add maven dependency "spring-boot-starter-thymeleaf"

Create HomeController for request mapping "/" to "index" template

Sample:

@Controller
public class HomeContoller {
    @RequestMapping("/")
    public String index() {
        return "index";
    }
}

See GitHub commit with HomeController

Would be great if someone know more cleaner/nicer solution and could share.


来源: stackexchange

问:
Change particle system material Unity 3D script
I am trying to create particles emission for my objects which are actually pawns in a chess game. I changed particles material using Inspector for particle system and it works fine, however, when I try to change it with a script, nothing happens (particles stay pink for the black pawn).

I am not sure what is wrong with the script, whether it's a change of material problem or maybe I need to set the path for material. I would be glad if someone suggested a solution!

Here is the script:

```<code>public class BlackPawnParticleSystem : MonoBehaviour
{
    private Material m_Material;
    private ParticleSystemRenderer psr;

    private void Start()
    {
        var ps     = GetComponent<ParticleSystem>();
        m_Material = GetComponent<Renderer>).material;
        psr        = GetComponent<ParticleSystemRenderer>);

        psr.material = Resources.GetBuiltinResource<Material>("BlackBishop.mat");
    }
</code>```

This is how it looks like:

EDIT:

Changes in code:

```<code>public class BlackPawnParticleSystem : MonoBehaviour
{
    private Material m_Material;
    private ParticleSystemRenderer psr;

    private void Start()
    {
        var ps       = GetComponent<ParticleSystem>();
        m_Material   = GetComponent<Renderer>().material;
        psr          = GetComponent<ParticleSystemRenderer>();
        psr.material = Resources.Load<Material>("BlackBishop");
    }
</code>```

Location of my materials:

Inspector for the material:

Script attached to the object:

答:
The problem is this line: Resources.GetBuiltinResource<Material>("BlackBishop.mat")

It is returning null. The Resources.GetBuiltinResource function is used to load resources that are built-in into Unity not ones created by you. For example, "Sprites-Default.mat". There is no build-in material named "BlackBishop.mat" so it returns null.

To load material you created, use rhe Resources.Load function.

First, create a folder called "Resources" then put your "BlackBishop.mat" material there. You can now load it as below:

```<code>Resources.Load<Material>("BlackBishop");
</code>```

Notice how I did not include ".mat" in the name. You don't include the extension name when using the Resources.Load function. If you do, it will not find it.

EDIT:

But still nothing happens on my game scene

Please carefully:

1.Like I said in my original answer, you must create a folder named "Resources" and must put the "Black Bishop" material inside that folder. You have not done this and it should not work. The spellings of thisfolder must be correct so copy it directly from this answer. Again, it should be named "Resources".

2.Your material is named "Black Bishop" not "BlackBishop" . See the space. Please fix this in the code. That should be Resources.Load<Material>("Black Bishop"); not Resources.Load<Material>("BlackBishop");.

3.Your material is currently using the "Standard" shader. Change that to Particle shader. You can do that by selecting the Material and changing the shader from "Standard"  to "Particles/Alpha Blended Premultiply". That's it. Your problem should now be solved.

Extra:

I noticed you are using folders to organize your resources. Your "Black Bishop.mat" is inside Arcane Cyber --> Chess --> Materials --> Pieces --> Plastic. I suggest you move the "Materials" folder to the "Resources" folder created in #1 above.

Now, your "Black Bishop.mat" should be inside Assets --> Resources -->  Materials --> Pieces --> Plastic.

You can now load it as:

Resources.Load<Material>("Materials/Pieces/Plastic/Black Bishop");

If you still have problems, please update your code and new Inspector images again. Remember that spellings count.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create particles emission for my objects which are actually pawns in a chess game. I changed particles material using Inspector for particle system and it works fine, however, when I try to change it with a script, nothing happens (particles stay pink for the black pawn).

I am not sure what is wrong with the script, whether it's a change of material problem or maybe I need to set the path for material. I would be glad if someone suggested a solution!

Here is the script:

public class BlackPawnParticleSystem : MonoBehaviour
{
    private Material m_Material;
    private ParticleSystemRenderer psr;

    private void Start()
    {
        var ps     = GetComponent<ParticleSystem>();
        m_Material = GetComponent<Renderer>).material;
        psr        = GetComponent<ParticleSystemRenderer>);

        psr.material = Resources.GetBuiltinResource<Material>("BlackBishop.mat");
    }

This is how it looks like:

EDIT:

Changes in code:

public class BlackPawnParticleSystem : MonoBehaviour
{
    private Material m_Material;
    private ParticleSystemRenderer psr;

    private void Start()
    {
        var ps       = GetComponent<ParticleSystem>();
        m_Material   = GetComponent<Renderer>().material;
        psr          = GetComponent<ParticleSystemRenderer>();
        psr.material = Resources.Load<Material>("BlackBishop");
    }

Location of my materials:

Inspector for the material:

Script attached to the object:

Body:
The problem is this line: Resources.GetBuiltinResource<Material>("BlackBishop.mat")

It is returning null. The Resources.GetBuiltinResource function is used to load resources that are built-in into Unity not ones created by you. For example, "Sprites-Default.mat". There is no build-in material named "BlackBishop.mat" so it returns null.

To load material you created, use rhe Resources.Load function.

First, create a folder called "Resources" then put your "BlackBishop.mat" material there. You can now load it as below:

Resources.Load<Material>("BlackBishop");

Notice how I did not include ".mat" in the name. You don't include the extension name when using the Resources.Load function. If you do, it will not find it.

EDIT:

But still nothing happens on my game scene

Please carefully:

1.Like I said in my original answer, you must create a folder named "Resources" and must put the "Black Bishop" material inside that folder. You have not done this and it should not work. The spellings of thisfolder must be correct so copy it directly from this answer. Again, it should be named "Resources".

2.Your material is named "Black Bishop" not "BlackBishop" . See the space. Please fix this in the code. That should be Resources.Load<Material>("Black Bishop"); not Resources.Load<Material>("BlackBishop");.

3.Your material is currently using the "Standard" shader. Change that to Particle shader. You can do that by selecting the Material and changing the shader from "Standard"  to "Particles/Alpha Blended Premultiply". That's it. Your problem should now be solved.

Extra:

I noticed you are using folders to organize your resources. Your "Black Bishop.mat" is inside Arcane Cyber --> Chess --> Materials --> Pieces --> Plastic. I suggest you move the "Materials" folder to the "Resources" folder created in #1 above.

Now, your "Black Bishop.mat" should be inside Assets --> Resources -->  Materials --> Pieces --> Plastic.

You can now load it as:

Resources.Load<Material>("Materials/Pieces/Plastic/Black Bishop");

If you still have problems, please update your code and new Inspector images again. Remember that spellings count.

ContentLicense: CC BY-SA 3.0


问:
pre-commit hook validating c++ code
Today I've updated our repository and tried to recompile it (it's a c++ application). It doesn't compile. My first reaction was to kill my coworker, but because I can't do it I need to find another solution.

Is it possibile to prevent to commit code that doesn't compile? We have a Makefile and what the pre-commit hook need to do it's simpy to check the output status of the command make. Is it right?

How in pratice can I implement it (I've never work with svn hook)?

答:
It's right in principle. However, it will likely cause major delays in committing (unless your application compiles in under a second). So you should really look for a different approach, where it lets users commit, but than starts a build process right away, and sends out email if it fails to build.

One way of doing that is buidbot.

ContentLicense: CC BY-SA 2.5

Title: pre-commit hook validating c++ code


答:
We can use pivot_table with aggfunc size and then convert notnull() values to int i.e

```<code>df.pivot_table(index = pd.Grouper(key='Index',freq='s'),columns='Receiver',aggfunc='size').notnull().astype(int)

Receiver                R1 R2
Index
1970-01-01 00:00:00      1  0
1970-01-01 00:00:01      0  1
1970-01-01 00:00:02      1  1
1970-01-01 00:00:03      1  1
</code>```

Title: Group b Time and return Boolean value if group contain

Body:
I have df as below.

Index                                Receiver
1970-01-01 00:00:00.000000000         R1
1970-01-01 00:00:00.800000000         R1
1970-01-01 00:00:01.000287000         R2
1970-01-01 00:00:01.600896000         R2
1970-01-01 00:00:02.001388000         R1
1970-01-01 00:00:02.004698000         R1
1970-01-01 00:00:02.006706000         R2
1970-01-01 00:00:02.501351000         R2
1970-01-01 00:00:02.810382000         R2
1970-01-01 00:00:03.001981000         R1
1970-01-01 00:00:03.377116000         R1
1970-01-01 00:00:03.701811000         R2
1970-01-01 00:00:03.910326000         R2
1970-01-01 00:00:03.951355000         R2

How to get the following df from above?

Index                        R1   R2
1970-01-01 00:00:00          1    0
1970-01-01 00:00:01          0    1
1970-01-01 00:00:02          1    1
1970-01-01 00:00:03          1    1

Appreciate one liner code.
Regards,
Asif

Body:
We can use pivot_table with aggfunc size and then convert notnull() values to int i.e

df.pivot_table(index = pd.Grouper(key='Index',freq='s'),columns='Receiver',aggfunc='size').notnull().astype(int)

Receiver                R1 R2
Index
1970-01-01 00:00:00      1  0
1970-01-01 00:00:01      0  1
1970-01-01 00:00:02      1  1
1970-01-01 00:00:03      1  1


问:
How to return or get output value from stored procedure which is executing inside procedure main (get this in c#)
How can I know if a stored procedure that is executed within another procedure returns an error or exception, a void?

In this code I show only one (EXAMPLE) where I have a stored procedure and inside it I get data from another stored procedure, but if for some reason it returns empty or something happens inside the stored procedure storedp_SearchTurn as I can compute the value that returns this procedure before obener the one that returns the main procedure storedp_Process.

```<code>ALTER PROCEDURE [dbo].[storedp_Process] (
    @id numeric,
    @type_time      char(1)
 )
As

declare     @terminal       varchar(30),
    @id_employee    numeric,
    @hour           datetime,
    @date       datetime,
    @inic           numeric

set  @terminal =   host_name()
set  @inic = convert(numeric,replace(left(right(convert(varchar(80),getdate(),9),14),12),':',''))

-- Other stored procedure
exec storedp_SearchTurn    @hour,
                     @turn  output ,
                     @date_valid output

print @turn

Declare @period  numeric(10)
Select  @period = period from setup
            where convert(char(10),date_valid,111)=convert(char(10),@date,111)  and id_turn = @turn

--The code continues, this is just an example
--The code continues, this is just an example
--The code continues, this is just an example
--The code continues, this is just an example
--The code continues, this is just an example
</code>```

Because even if storedp_SearchTurn executes and returns empty or something happens, anyway storedp_Process will return 0 if a problem does not occur in sp_Process. I need to capture some error or exception of the procedure that runs inside the other.

I get the output values well and use them within the main procedure, but I need to obtain those output values that belong to the secondary procedure, get them in C#, in order to inform the user if something happened during the process.

In C # I tried adding these parameters as output, but since they do not belong to the main procedure when executing, the exception jumps that the stored procedure has more arguments than those specified.

NOTE: The stored procedure works perfectly, I just need to obtain those output values of the secondary procedure in C#

But I must not modify the stored procedure, the company has created it that way and it works perfectly, I just need to know if at some point the output values returned empty, or have data, or if an exception occurred and get this in C#

I also found these related topics, but none of them answered my question:

How to return or get output value from stored procedure which is executing inside another proceed

Return Output Param of a Stored Procedure inside another Stored Procedure

Executing a stored procedure inside another stored procedure using Select Query

Get the value of a stored procedure inside another stored procedure with select

How to call stored procedure inside another stored procedure and set the values as in variable in DB2

Stored procedure executing another stored procedure

答:
How can I know if a stored procedure that is executed within another procedure returns an error or exception, a void?

TRY...CATCH (Transact-SQL)

@@ERROR (Transact-SQL)

IS NULL (Transact-SQL)

You could try something like

```<code>ALTER PROCEDURE [dbo].[storedp_Process] (
...
BEGIN TRY
    exec sp_SearchTurn    @hour,
                          @turn  output ,
                          @date_valid output
END TRY
BEGIN CATCH
    RAISERROR (0, 0, 0, 'An error has ocurred during sp_SearchTurn.')
    RETURN
END CATCH;

IF @@ERROR != 0
BEGIN
    RAISERROR (0, 0, 0, 'An error has ocurred during sp_SearchTurn.')
    RETURN
END

IF @turn IS NULL OR @date_valid IS NULL
    RAISERROR (0, 0, 0, 'An error has ocurred during sp_SearchTurn.')
    RETURN
END
</code>```

Body:
How can I know if a stored procedure that is executed within another procedure returns an error or exception, a void?

In this code I show only one (EXAMPLE) where I have a stored procedure and inside it I get data from another stored procedure, but if for some reason it returns empty or something happens inside the stored procedure storedp_SearchTurn as I can compute the value that returns this procedure before obener the one that returns the main procedure storedp_Process.

ALTER PROCEDURE [dbo].[storedp_Process] (
    @id numeric,
    @type_time      char(1)
 )
As

declare     @terminal       varchar(30),
    @id_employee    numeric,
    @hour           datetime,
    @date       datetime,
    @inic           numeric

set  @terminal =   host_name()
set  @inic = convert(numeric,replace(left(right(convert(varchar(80),getdate(),9),14),12),':',''))

-- Other stored procedure
exec storedp_SearchTurn    @hour,
                     @turn  output ,
                     @date_valid output

print @turn

Declare @period  numeric(10)
Select  @period = period from setup
            where convert(char(10),date_valid,111)=convert(char(10),@date,111)  and id_turn = @turn

--The code continues, this is just an example
--The code continues, this is just an example
--The code continues, this is just an example
--The code continues, this is just an example
--The code continues, this is just an example

Because even if storedp_SearchTurn executes and returns empty or something happens, anyway storedp_Process will return 0 if a problem does not occur in sp_Process. I need to capture some error or exception of the procedure that runs inside the other.

I get the output values well and use them within the main procedure, but I need to obtain those output values that belong to the secondary procedure, get them in C#, in order to inform the user if something happened during the process.

In C # I tried adding these parameters as output, but since they do not belong to the main procedure when executing, the exception jumps that the stored procedure has more arguments than those specified.

NOTE: The stored procedure works perfectly, I just need to obtain those output values of the secondary procedure in C#

But I must not modify the stored procedure, the company has created it that way and it works perfectly, I just need to know if at some point the output values returned empty, or have data, or if an exception occurred and get this in C#

I also found these related topics, but none of them answered my question:

How to return or get output value from stored procedure which is executing inside another proceed

Return Output Param of a Stored Procedure inside another Stored Procedure

Executing a stored procedure inside another stored procedure using Select Query

Get the value of a stored procedure inside another stored procedure with select

How to call stored procedure inside another stored procedure and set the values as in variable in DB2

Stored procedure executing another stored procedure

Body:
How can I know if a stored procedure that is executed within another procedure returns an error or exception, a void?

TRY...CATCH (Transact-SQL)

@@ERROR (Transact-SQL)

IS NULL (Transact-SQL)

You could try something like

ALTER PROCEDURE [dbo].[storedp_Process] (
...
BEGIN TRY
    exec sp_SearchTurn    @hour,
                          @turn  output ,
                          @date_valid output
END TRY
BEGIN CATCH
    RAISERROR (0, 0, 0, 'An error has ocurred during sp_SearchTurn.')
    RETURN
END CATCH;

IF @@ERROR != 0
BEGIN
    RAISERROR (0, 0, 0, 'An error has ocurred during sp_SearchTurn.')
    RETURN
END

IF @turn IS NULL OR @date_valid IS NULL
    RAISERROR (0, 0, 0, 'An error has ocurred during sp_SearchTurn.')
    RETURN
END


问:
Define variables in gradle to fill data in persistence.xml
Can I define variables in gradle, which are fill in the placeholders in the persistence.xml?

Example

gradle.properties:

```<code>dev.classes= <class>my.package.class</class>.....<class>my.package.class</class>
</code>```

persistence.xml

```<code><persistence>
   <persistence-unit name "a">
     <!--define a variable that will be overwritten by build.gradle-->
       ...
  </persistence-unit>
</persistence>
</code>```

build.gradle

```<code>task replaceTokens {
  from(//persistence.xml path) {
     filter(ReplaceTokens, tokens: [//variable in xml, //value in gradle.properties])
   }
}
</code>```

I need it, because I have more persistence-units in my persistence.xml, which all needs the same classes. Currently the classes are in all persistence-unit "hardcoded". It would be nicer, if I can define it only once.

答:
If it were me, I'd put the xml template under src/template/resources

src/template/resources/persistence.xml

```<code><persistence>
    <persistence-unit name="a">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <jta-data-source>java:/A</jta-data-source>
@persistence.classes@
    </persistence-unit>

    <persistence-unit name="b">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <jta-data-source>java:/B</jta-data-source>
@persistence.classes@
    </persistence-unit>
</persistence>
</code>```

gradle.properties

```<code>persistence.classes=\
        <class>com.example.Foo</class>\
        <class>com.example.Bar</class>\
        ...
</code>```

build.gradle

```<code>apply plugin: 'java'
processResources {
    from 'src/template/resources', {
        filter(ReplaceTokens, tokens: ['persistence.classes': property('persistence.classes')])
    }
}
</code>```

Body:
Can I define variables in gradle, which are fill in the placeholders in the persistence.xml?

Example

gradle.properties:

dev.classes= <class>my.package.class</class>.....<class>my.package.class</class>

persistence.xml

<persistence>
   <persistence-unit name "a">

       ...
  </persistence-unit>
</persistence>

build.gradle

task replaceTokens {
  from(//persistence.xml path) {
     filter(ReplaceTokens, tokens: [//variable in xml, //value in gradle.properties])
   }
}

I need it, because I have more persistence-units in my persistence.xml, which all needs the same classes. Currently the classes are in all persistence-unit "hardcoded". It would be nicer, if I can define it only once.

Body:
If it were me, I'd put the xml template under src/template/resources

src/template/resources/persistence.xml

<persistence>
    <persistence-unit name="a">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <jta-data-source>java:/A</jta-data-source>
@persistence.classes@
    </persistence-unit>

    <persistence-unit name="b">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <jta-data-source>java:/B</jta-data-source>
@persistence.classes@
    </persistence-unit>
</persistence>

gradle.properties

persistence.classes=\
        <class>com.example.Foo</class>\
        <class>com.example.Bar</class>\
        ...

build.gradle

apply plugin: 'java'
processResources {
    from 'src/template/resources', {
        filter(ReplaceTokens, tokens: ['persistence.classes': property('persistence.classes')])
    }
}


问:
How to filter an array based on the true/false value of the object properties inside the array
I am trying to take an array that contains a list of people, and create a new array out of it. I would like the new array to contain only the people that have "true" for one of their properties. So it would look something like this.

```<code>{% for adult in household.adults %}
    {% unless adult.inactive == true %}
        {% assign active_adults = adult %}
    {% endunless %}
{% endfor %}
</code>```

So I'm basically taking one array, filtering out the objects that have a certain property set to True, and making a new array out of only those objects. I hope that makes sense. Thanks for the help!

答:
I'm no expert but as far as I know you can do something like this in Ruby to filter an array:

household.adults.select {|adult| adult.inactive != true}

and it returns a new array with only matching elements.

I think you can use Ruby in the Liquid template language?

Link to the API doc: https://ruby-doc.org/core-2.2.0/Array.html#method-i-select

Body:
I am trying to take an array that contains a list of people, and create a new array out of it. I would like the new array to contain only the people that have "true" for one of their properties. So it would look something like this.

{% for adult in household.adults %}
    {% unless adult.inactive == true %}
        {% assign active_adults = adult %}
    {% endunless %}
{% endfor %}

So I'm basically taking one array, filtering out the objects that have a certain property set to True, and making a new array out of only those objects. I hope that makes sense. Thanks for the help!


问:
Ubuntu sqldeveloper network adapter could not establish the connection hr database
I have a problem with my sqldeveloper on Ubuntu 14.
 When I try to connect to default database hr (login hr, pass hr, host: localhost, sid: orcl) I get an error: "network adapter could not establish the connection".

What should I do?
Ask me additional questions if necessary.

答:
please , first start your listener if in ubantu environment as

```<code>sudo service oracle-xe start
</code>```

then start your sql developer.

Body:
please , first start your listener if in ubantu environment as

sudo service oracle-xe start

then start your sql developer.


问:
I need to convert audio file from μ-law to PCM
I need to convert wav file from FORMAT 1 to FORMAT 2

Format 1 :
μ-law, 8000Hz, 64 kbps, mono

FORMAT 2 :
Container   WAV
Encoding    PCM
Rate    16K
Sample Format   16 bit
Channels    Mono

Following is the Code snippet :

```<code>File file = new File("audio_before_conversion.wav");
AudioFormat audioFormat = new AudioFormat(16000, 16, 1, true , true);
AudioInputStream audioInputStream1 = new AudioInputStream(
     new FileInputStream(file), audioFormat, numFrames);
AudioSystem.write(audioInputStream1, Type.WAVE,
     new File("audio_after_conversion.wav"));
</code>```

Issue :
But, this is not working. It playing some noise and also reducing my audio file length.

Edit 1: mu-Law to μ-law

答:
Following code worked for me --

```<code>File sourceFile = new File("<Source_Path>.wav");

        File targetFile = new File("<Destination_Path>.wav");

        AudioInputStream sourceAudioInputStream = AudioSystem.getAudioInputStream(sourceFile);

        AudioInputStream targetAudioInputStream=AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED, sourceAudioInputStream);
        System.out.println("Sample Rate1 "+targetAudioInputStream.getFormat().getFrameRate());
    AudioFormat targetFormat = new AudioFormat(new AudioFormat.Encoding("PCM_SIGNED"), 16000, 16, 1, 2, 8000, false);

        AudioInputStream targetAudioInputStream1 = AudioSystem.getAudioInputStream(targetFormat, targetAudioInputStream);
        System.out.println("Sample Rate "+targetAudioInputStream1.getFormat().getFrameRate());

        try {
            AudioSystem.write(targetAudioInputStream1, AudioFileFormat.Type.WAVE, targetFile);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
</code>```

Body:
I need to convert wav file from FORMAT 1 to FORMAT 2

Format 1 :
μ-law, 8000Hz, 64 kbps, mono

FORMAT 2 :
Container   WAV
Encoding    PCM
Rate    16K
Sample Format   16 bit
Channels    Mono

Following is the Code snippet :

File file = new File("audio_before_conversion.wav");
AudioFormat audioFormat = new AudioFormat(16000, 16, 1, true , true);
AudioInputStream audioInputStream1 = new AudioInputStream(
     new FileInputStream(file), audioFormat, numFrames);
AudioSystem.write(audioInputStream1, Type.WAVE,
     new File("audio_after_conversion.wav"));

Issue :
But, this is not working. It playing some noise and also reducing my audio file length.

Edit 1: mu-Law to μ-law

Body:
Following code worked for me --

File sourceFile = new File("<Source_Path>.wav");

        File targetFile = new File("<Destination_Path>.wav");

        AudioInputStream sourceAudioInputStream = AudioSystem.getAudioInputStream(sourceFile);

        AudioInputStream targetAudioInputStream=AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED, sourceAudioInputStream);
        System.out.println("Sample Rate1 "+targetAudioInputStream.getFormat().getFrameRate());
    AudioFormat targetFormat = new AudioFormat(new AudioFormat.Encoding("PCM_SIGNED"), 16000, 16, 1, 2, 8000, false);

        AudioInputStream targetAudioInputStream1 = AudioSystem.getAudioInputStream(targetFormat, targetAudioInputStream);
        System.out.println("Sample Rate "+targetAudioInputStream1.getFormat().getFrameRate());

        try {
            AudioSystem.write(targetAudioInputStream1, AudioFileFormat.Type.WAVE, targetFile);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


问:
Deploy Node JS REST APi Mongo DB on Windows
I'm new to node js. In the last months, i developed a REST API using node js, Express and Mongo DB for my customer.
I would like to deploy the WEB API on Linux, but now my customer asks me to deploy the solution into a Production Environment with Windows Server 2008 / 2012 R2.
Which is the best way to deploy this solution on Windows Server?
There is some best guide to see?

Thanks

答:
PM2 on Windows:

Personally I am using pm2 on my linux machines. Pm2 is a process manager for node apps, which makes deployment and maintainance of your node applications a lot easier. You can also use pm2 on windows, see: https://github.com/Unitech/pm2

You need to make sure pm2 start upon restarts / server crashes and therefore you want to setup a service. You could take a look at: https://github.com/jon-hall/pm2-windows-service which may be a help for that purpose.

Docker:

If you are just struggling because it's windows and you are still looking for your "common deploy methods" you could still setup a docker container with your favourite environment. However if you don't have experience with it, it is probably a bad idea to test it first in a customer project.


问:
Keycloak 1.9.1.Final- failed verification of token: Token is not active
I'm trying to connect a Spring App Keycloak, but I get this error:

After I enter to my app, and I was redirected to Keycloak for authentication, I receive an error in my browser:

```<code>192.168.1.66 redirected you too many times.
</code>```

Full url

```<code>URL: http://192.168.1.66:9092/keycloak-sp-example/sso/login?state=139%2F1ed115fb-4d4f-468c-9a72-845f9cfa9cdb&code=PVGhg5X28G8fjNt36tMGHTJIP7CQdHOhoK4XhPgUh3E.2d885db5-5c4f-43b1-9095-305494718a97
</code>```

And, in the console, I got:

```<code>ERROR org.keycloak.adapters.OAuthRequestAuthenticator - failed verification of token: Token is not active.
</code>```

It's a bug? Or is anything that I should configure in the console?

答: Try to sync the server timing of Keycloak and application server or else increase the access token life span which is not recommended.</p>

Body:
I'm trying to connect a Spring App Keycloak, but I get this error:

After I enter to my app, and I was redirected to Keycloak for authentication, I receive an error in my browser:

192.168.1.66 redirected you too many times.

Full url

URL: http://192.168.1.66:9092/keycloak-sp-example/sso/login?state=139%2F1ed115fb-4d4f-468c-9a72-845f9cfa9cdb&code=PVGhg5X28G8fjNt36tMGHTJIP7CQdHOhoK4XhPgUh3E.2d885db5-5c4f-43b1-9095-305494718a97

And, in the console, I got:

ERROR org.keycloak.adapters.OAuthRequestAuthenticator - failed verification of token: Token is not active.

It's a bug? Or is anything that I should configure in the console?


问:
Does anyone know about Kephas?
I stumbled upon a framework promising a powerful and flexible infrastructure, named Kephas, and I am currently evaluating it for an existing application to get it updated to the latest technologies. I just browsed the documentation and the samples and I can see the potential for new applications, but what about existing ones? Is it possible to implement an incremental strategy and not rewrite it from scratch? Does anyone know about it, what was the experience?</p>

答:
Sure it can be done incrementally, provided the application uses the .NET framework with a version higher than 4.5 (as a matter of fact .NET Core/.NET Standard and Mono are also supported). In fact, there are organizations using it for production which integrated it step by step. There are also architectural issues which need to be considered thoughtfully, like the integration of a DI framework or a data persistence layer, but basically the incremental adoption should not pose any serious problems.

Do not forget that central to Kephas Framework are the application services available through dependency injection. Use the ones provided by default, or override them, just by the means of a mere attribute. You can follow more approaches:

Have the original application's DI container live side by side with the one provided by Kephas (by the way, it is only an abstraction over existing DIs, we didn't want to reinvent the wheel). Not very recommended, but it works if you want to have it that way.

Have the original application's DI container integrate the one from Kephas. I personally used this strategy when working with ServiceStack's Funq DI container and it worked. However, this way the original application has access to Kephas services, but not the way round. I would use this approach if you need to let the original application be in control.

Have Kephas integrate the application's DI container. This way Kephas services have access to the original application's services, but not the way round. I would use this approach if you want to walk the Kephas way completely, now or in the future.

Use the DI containers provided by Kephas entirely. I would go this way if you don't use DI at all or have a compatible DI container (like MEF/System.Composition or Autofac - for Autofac there is no built-in support but it shouldn't be that hard to implement it).

There are a lot of things to discuss, but this would go beyond the scope of this question.

Disclaimer: I am the lead developer behind the Kephas Framework - more information can be obtained from the Wiki page. Check also the samples here.

Title: Does anyone know about Kephas?


问:
A Vampire Data Analysis Program for the FWPD, Clojure for the Brave and True
I am trying to understand the program "A Vampire Data Analysis Program for the FWPD" at the end of the 4th chapter in the book "Clojure for the Brave and True". Here is the code:

```<code>(ns fwpd.core)

(def filename "suspects.csv")

(def vamp-keys [:name :glitter-index])

(defn str->int
  [str]
  (Integer. str))

(def conversions {:name identity
              :glitter-index str->int})

(defn convert
   [vamp-key value]
  ((get conversions vamp-key) value))

(defn parse
  "Convert a CSV into rows of columns"
  [string]
  (map #(clojure.string/split % #",")
   (clojure.string/split string #"\n")))

(defn mapify
  "Return a seq of maps like {:name \"Edward Cullen\" :glitter-index 10}"
  [rows]
 (map (fn [unmapped-row]
     (reduce (fn [row-map [vamp-key value]]
               (assoc row-map vamp-key (convert vamp-key value)))
             {}
             (map vector vamp-keys unmapped-row)))
   rows))

(defn glitter-filter
  [minimum-glitter records]
  (filter #(>= (:glitter-index %) minimum-glitter) records))
</code>```

Can somebody help about conversions and convert function?

答:
conversions is a map, and as such contains key value pairs, called map-entries. get is a function that allows you to get the respective value returned when all you have is a key, and of course the map. So for convert to do its job then vamp-key must be either :name or :glitter-index (as they are the only keys on the map). Lets assume it is :glitter-index and that str->int is returned. Thus:

```<code>((get conversions vamp-key) value))
</code>```

, becomes:

```<code>(str->int value)
</code>```

So vamp-key is needed to obtain the correct function to convert the value. If :glitter-index and "10" are the arguments passed into the function then 10 will be returned.

Body:
I am trying to understand the program "A Vampire Data Analysis Program for the FWPD" at the end of the 4th chapter in the book "Clojure for the Brave and True". Here is the code:

(ns fwpd.core)

(def filename "suspects.csv")

(def vamp-keys [:name :glitter-index])

(defn str->int
  [str]
  (Integer. str))

(def conversions {:name identity
              :glitter-index str->int})

(defn convert
   [vamp-key value]
  ((get conversions vamp-key) value))

(defn parse
  "Convert a CSV into rows of columns"
  [string]
  (map #(clojure.string/split % #",")
   (clojure.string/split string #"\n")))

(defn mapify
  "Return a seq of maps like {:name \"Edward Cullen\" :glitter-index 10}"
  [rows]
 (map (fn [unmapped-row]
     (reduce (fn [row-map [vamp-key value]]
               (assoc row-map vamp-key (convert vamp-key value)))
             {}
             (map vector vamp-keys unmapped-row)))
   rows))

(defn glitter-filter
  [minimum-glitter records]
  (filter #(>= (:glitter-index %) minimum-glitter) records))

Can somebody help about conversions and convert function?

Body:
conversions is a map, and as such contains key value pairs, called map-entries. get is a function that allows you to get the respective value returned when all you have is a key, and of course the map. So for convert to do its job then vamp-key must be either :name or :glitter-index (as they are the only keys on the map). Lets assume it is :glitter-index and that str->int is returned. Thus:

((get conversions vamp-key) value))

, becomes:

(str->int value)

So vamp-key is needed to obtain the correct function to convert the value. If :glitter-index and "10" are the arguments passed into the function then 10 will be returned.


问:
External SDcards with Android API 26
Evironment:

Android Studio 3.0.1. All latest patches applied.
AVD Nexus 6, Sd card external.

Issue:
Having launched the AVD, the external sdcard does not show in ESExplorer, nor in my app New Playlist Manager when browsing local folders.

Using

```<code>adb shell
su
cd /storage
ls -al
</code>```

shows

```<code>emulated
self
</code>```

so no external sdcard.

However, using the new Files app, the external sdcard DOES show.
Also, running the Picker when requesting access to the sdcard (with the Storage Access Framework)

```<code>            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
            startActivityForResult(intent, OPEN_DIRECTORY_REQUEST_CODE);
</code>```

again the External Sdcard shows

I have explored several selinux level options using a class called MemoryStorage (posted on this forum)

/proc/mounts does not return the external sdcard

/system/etc/vold.fstab does not exist

Have Google yet again changed access to the external sdcard?

How can I get the physical external sdcard.?

Additional:
The sdcard is part of the filesystem as proven below where LOST.DIR is located on the external sdcard

```<code>generic_x86:/ # ls -alR |grep LOST.DIR
drwxrwx--- 2 media_rw media_rw 2048 2017-12-04 15:06 LOST.DIR
./mnt/media_rw/14FA-3B13/LOST.DIR:
</code>```

答:
I found this:
The new "SDCardFS" file system wrapper

Google hasn't officially said a word about this, but apparently Android 8.0 comes with support for a new file system wrapper called "SDCardFS." Maybe that statement is too presumptuous—with the 8.0 upgrade, the Google Pixel and a few Nexus devices magically start using SDCardFS, so presumably that means the new file storage scheme is available for anyone in AOSP. The intrepid hardware hackers over at XDA have been tracking the implementation progress, and apparently SDCardFS should significantly reduce the I/O overhead involved in accessing Android's shared data storage.

Reference:

arstechnica.com

https://arstechnica.com/gadgets/2017/09/android-8-0-oreo-thoroughly-reviewed/8/

another interesting article:

xda developers

https://www.xda-developers.com/diving-into-sdcardfs-how-googles-fuse-replacement-will-reduce-io-overhead/

and

http://pocketnow.com/2015/12/18/adoptable-storage

Update:
further investigations show that the external sdcard does exist but the permissions xrw are only set for User (owner) and Group access. The Other Access has no permissions.

Using chmod o+r  has no effect

```<code>generic_x86:/mnt # ls -al
total 0
drwxr-xr-x 10 root   system   220 2017-12-07 11:29 .
drwxrwxrwt 16 root   root     660 2017-12-07 11:29 ..
drwx--x--x  2 root   root      40 2017-12-07 11:29 appfuse
drwxr-xr-x  2 root   system    40 2017-12-07 11:29 asec
drwxrwx--x  2 system system    40 2017-12-07 11:29 expand
drwxr-x---  3 root   media_rw  60 2017-12-07 11:29 media_rw
drwxr-xr-x  2 root   system    40 2017-12-07 11:29 obb
drwx------  5 root   root     100 2017-12-07 11:29 runtime
lrwxrwxrwx  1 root   root      21 2017-12-07 11:29 sdcard -> /storage/self/primary
drwx------  3 root   root      60 2017-12-07 11:29 secure
drwxr-xr-x  3 root   root      60 2017-12-07 11:29 user
generic_x86:/mnt # cd media_rw
generic_x86:/mnt/media_rw # ls -al
total 0
drwxr-x---  3 root     media_rw  60 2017-12-07 11:29 .
drwxr-xr-x 10 root     system   220 2017-12-07 11:29 ..
drwxrwx---  3 media_rw media_rw 512 2017-12-07 11:29 12FE-0C07
</code>```

Further update:

Guess what

```<code>adb shell sm set-force-adoptable true
</code>```

makes the sdcard appear as /storage/xxxx-xxxx.

switches for the selinux sm command:

```<code>   generic_x86:/ # sm /?
    usage: sm list-disks [adoptable]
           sm list-volumes [public|private|emulated|all]
           sm has-adoptable
           sm get-primary-storage-uuid
           sm set-force-adoptable [true|false]
           sm set-virtual-disk [true|false]
           sm partition DISK [public|private|mixed] [ratio]
           sm mount VOLUME
           sm unmount VOLUME
           sm format VOLUME
           sm benchmark VOLUME
           sm fstrim
           sm forget [UUID|all]
           sm set-emulate-fbe [true|false]
</code>```

Title: External SDcards with Android API 26

Body:
Evironment:

Android Studio 3.0.1. All latest patches applied.
AVD Nexus 6, Sd card external.

Issue:
Having launched the AVD, the external sdcard does not show in ESExplorer, nor in my app New Playlist Manager when browsing local folders.

Using

adb shell
su
cd /storage
ls -al

shows

emulated
self

so no external sdcard.

However, using the new Files app, the external sdcard DOES show.
Also, running the Picker when requesting access to the sdcard (with the Storage Access Framework)

            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
            startActivityForResult(intent, OPEN_DIRECTORY_REQUEST_CODE);

again the External Sdcard shows

I have explored several selinux level options using a class called MemoryStorage (posted on this forum)

/proc/mounts does not return the external sdcard

/system/etc/vold.fstab does not exist

Have Google yet again changed access to the external sdcard?

How can I get the physical external sdcard.?

Additional:
The sdcard is part of the filesystem as proven below where LOST.DIR is located on the external sdcard

generic_x86:/ # ls -alR |grep LOST.DIR
drwxrwx--- 2 media_rw media_rw 2048 2017-12-04 15:06 LOST.DIR
./mnt/media_rw/14FA-3B13/LOST.DIR:

Body:
I found this:
The new "SDCardFS" file system wrapper

Google hasn't officially said a word about this, but apparently Android 8.0 comes with support for a new file system wrapper called "SDCardFS." Maybe that statement is too presumptuous—with the 8.0 upgrade, the Google Pixel and a few Nexus devices magically start using SDCardFS, so presumably that means the new file storage scheme is available for anyone in AOSP. The intrepid hardware hackers over at XDA have been tracking the implementation progress, and apparently SDCardFS should significantly reduce the I/O overhead involved in accessing Android's shared data storage.

Reference:

arstechnica.com

https://arstechnica.com/gadgets/2017/09/android-8-0-oreo-thoroughly-reviewed/8/

another interesting article:

xda developers

https://www.xda-developers.com/diving-into-sdcardfs-how-googles-fuse-replacement-will-reduce-io-overhead/

and

http://pocketnow.com/2015/12/18/adoptable-storage

Update:
further investigations show that the external sdcard does exist but the permissions xrw are only set for User (owner) and Group access. The Other Access has no permissions.

Using chmod o+r  has no effect

generic_x86:/mnt # ls -al
total 0
drwxr-xr-x 10 root   system   220 2017-12-07 11:29 .
drwxrwxrwt 16 root   root     660 2017-12-07 11:29 ..
drwx--x--x  2 root   root      40 2017-12-07 11:29 appfuse
drwxr-xr-x  2 root   system    40 2017-12-07 11:29 asec
drwxrwx--x  2 system system    40 2017-12-07 11:29 expand
drwxr-x---  3 root   media_rw  60 2017-12-07 11:29 media_rw
drwxr-xr-x  2 root   system    40 2017-12-07 11:29 obb
drwx------  5 root   root     100 2017-12-07 11:29 runtime
lrwxrwxrwx  1 root   root      21 2017-12-07 11:29 sdcard -> /storage/self/primary
drwx------  3 root   root      60 2017-12-07 11:29 secure
drwxr-xr-x  3 root   root      60 2017-12-07 11:29 user
generic_x86:/mnt # cd media_rw
generic_x86:/mnt/media_rw # ls -al
total 0
drwxr-x---  3 root     media_rw  60 2017-12-07 11:29 .
drwxr-xr-x 10 root     system   220 2017-12-07 11:29 ..
drwxrwx---  3 media_rw media_rw 512 2017-12-07 11:29 12FE-0C07

Further update:

Guess what

adb shell sm set-force-adoptable true

makes the sdcard appear as /storage/xxxx-xxxx.

switches for the selinux sm command:

   generic_x86:/ # sm /?
    usage: sm list-disks [adoptable]
           sm list-volumes [public|private|emulated|all]
           sm has-adoptable
           sm get-primary-storage-uuid
           sm set-force-adoptable [true|false]
           sm set-virtual-disk [true|false]
           sm partition DISK [public|private|mixed] [ratio]
           sm mount VOLUME
           sm unmount VOLUME
           sm format VOLUME
           sm benchmark VOLUME
           sm fstrim
           sm forget [UUID|all]
           sm set-emulate-fbe [true|false]


问:
Prevent access to constructor / only specific class has access
Let's say I have an Apple Class and an AppleFactoryClass.
Nobody should be able to use Apple redApple = new Apple(). Instead new Apples should only be able to be created from  AppleFactory.Create().

This mean the Constructor of Apple must be inaccessible for everyone but the AppleFactory Class.

How can this be done?

EDIT: Apple is more like an AppleModel. So there is only Properties in there.

答:
If you want a different type to act as the factory, then the closest you can get is internal:

```<code>public sealed class Apple() {
    internal Apple() {}
}
public class AppleFactory() {
    public Apple CreateApple() => new Apple();
}
</code>```

However, if you can have the factory as a static method on Apple, then you can keep everything private:

```<code>public sealed class Apple() {
    private Apple() {}
    public static Apple Create() => new Apple();
}
</code>```

Body:
If you want a different type to act as the factory, then the closest you can get is internal:

public sealed class Apple() {
    internal Apple() {}
}
public class AppleFactory() {
    public Apple CreateApple() => new Apple();
}

However, if you can have the factory as a static method on Apple, then you can keep everything private:

public sealed class Apple() {
    private Apple() {}
    public static Apple Create() => new Apple();
}


问:
Enabling and disabling comments on youtube video through api
How do you enable/disable comments on a video using the YouTube api? Basically what's the api way of doing this:

答:
As stated in this thread, disabling comments and ratings on a video is not supported by the v3 API at this time.

There is a known issue where if you disable comments on your videos in your channel preferences and then upload a video through the v3 API, comments are still allowed on the video (note that this bug was reported internally, but it does not appear to have been fixed). YouTube is still working out these features for v3.


问:
How to sum the value of child items from a hierarchical list in a loop
How to sum the value of child items from a hierarchical list in a loop.

I need that during the loop in the list the values of the amount and price property contain the sum of these properties of the children.

Below are the two classes to be used to help me solve my problem.

```<code>namespace SGP.Dto.Custo
{
    public class PlanilhaCusto
    {
        public int id{ get; set; }
        public int parenteId{ get; set; }
        public string name { get; set; }
        public decimal amount{ get; set; }
        public decimal price{ get; set; }

        public PlanilhaCusto(int pId, int pParenteId, pName, decimal pAmount, decimal pPrice)
        {
            id = pId;
            parentId = pParentId;
            name = pName;
            amount = pAmount;
            price = pPrice;
        }
    }
}

namespace SGP.Dto.Custo
{
    public class ShowList
    {
        List<Dto.Custo.PlanilhaCusto> myList = new List<PlanilhaCusto>();

        public void Show()
        {
            myList.Add(new PlanilhaCusto(1, null, "Projetos", 0, 0));
            myList.Add(new PlanilhaCusto(2, 1, "Arquitetura", 5,10));
            myList.Add(new PlanilhaCusto(3, 1, "Estrutura", 0, 0));
            myList.Add(new PlanilhaCusto(4, 3, "Civil", 1, 50));
            myList.Add(new PlanilhaCusto(5, 3, "Infra", 3, 75));
            myList.Add(new PlanilhaCusto(6, null, "Pessoal", 0, 0));
            myList.Add(new PlanilhaCusto(7, 6, "Mão de Obra", 20, 5700));

            /*In this loop the value of the parent items must be updated
              (calculated). The hierarchy of the list can be unlimited,
              like a tree. I tried using a recursive method but I could
              not do it.*/
            foreach (var itemList in myList)
            {

            }
        }
    }
}
</code>```

答:
for creating a hierarchical structure, i modified your PlanilhaCusto to resemble a sort of a Node in tree, having both parent and children members, for ease the traverse

```<code>public class PlanilhaCusto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? ParentId { get; set; }
    public decimal Amount { get; set; }
    public decimal Price { get; set; }
    public IEnumerable<PlanilhaCusto> Children { get; set; }
}
</code>```

Given this structure and an initial input

you can build the entire tree structure regardless of how many levels there are relying on some recursion

```<code>public IEnumerable<PlanilhaCusto> Descendants(PlanilhaCusto parent, IEnumerable<PlanilhaCusto> source)
{
    var query = from node in source
                where node.ParentId == parent.Id
                let children = Descendants(node, source)
                select new PlanilhaCusto
                {
                    Id = node.Id,
                    ParentId = node.ParentId,
                    Name = node.Name,
                    Amount = node.Amount,
                    Price = node.Price,
                    Children = children,
                };

    return query.ToList();
}

var hierarchy = from node in source
                let children = Descendants(node, source)
                where node.ParentId == null
                select new PlanilhaCusto
                {
                    Id = node.Id,
                    ParentId = node.ParentId,
                    Name = node.Name,
                    Price = node.Price,
                    Children = children,
                };
</code>```

that would project the initial data source into something similar

and from here you just need to traverse the hierarchy and compose the total price

```<code>public decimal? Total(PlanilhaCusto node)
{
    decimal? price = node.Price * node.Amount;
    if (node.Children != null)
    {
        foreach (var child in node.Children)
        {
            price += Total(child);
        }
    }

    return price;
}

var totals = from node in hierarchy
             select new
             {
                Id = node.Id,
                Name = node.Name,
                Total = Total(node),
             };
</code>```

Body:
How to sum the value of child items from a hierarchical list in a loop.

I need that during the loop in the list the values of the amount and price property contain the sum of these properties of the children.

Below are the two classes to be used to help me solve my problem.

namespace SGP.Dto.Custo
{
    public class PlanilhaCusto
    {
        public int id{ get; set; }
        public int parenteId{ get; set; }
        public string name { get; set; }
        public decimal amount{ get; set; }
        public decimal price{ get; set; }

        public PlanilhaCusto(int pId, int pParenteId, pName, decimal pAmount, decimal pPrice)
        {
            id = pId;
            parentId = pParentId;
            name = pName;
            amount = pAmount;
            price = pPrice;
        }
    }
}

namespace SGP.Dto.Custo
{
    public class ShowList
    {
        List<Dto.Custo.PlanilhaCusto> myList = new List<PlanilhaCusto>();

        public void Show()
        {
            myList.Add(new PlanilhaCusto(1, null, "Projetos", 0, 0));
            myList.Add(new PlanilhaCusto(2, 1, "Arquitetura", 5,10));
            myList.Add(new PlanilhaCusto(3, 1, "Estrutura", 0, 0));
            myList.Add(new PlanilhaCusto(4, 3, "Civil", 1, 50));
            myList.Add(new PlanilhaCusto(5, 3, "Infra", 3, 75));
            myList.Add(new PlanilhaCusto(6, null, "Pessoal", 0, 0));
            myList.Add(new PlanilhaCusto(7, 6, "Mão de Obra", 20, 5700));

            /*In this loop the value of the parent items must be updated
              (calculated). The hierarchy of the list can be unlimited,
              like a tree. I tried using a recursive method but I could
              not do it.*/
            foreach (var itemList in myList)
            {

            }
        }
    }
}

Body:
for creating a hierarchical structure, i modified your PlanilhaCusto to resemble a sort of a Node in tree, having both parent and children members, for ease the traverse

public class PlanilhaCusto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? ParentId { get; set; }
    public decimal Amount { get; set; }
    public decimal Price { get; set; }
    public IEnumerable<PlanilhaCusto> Children { get; set; }
}

Given this structure and an initial input

you can build the entire tree structure regardless of how many levels there are relying on some recursion

public IEnumerable<PlanilhaCusto> Descendants(PlanilhaCusto parent, IEnumerable<PlanilhaCusto> source)
{
    var query = from node in source
                where node.ParentId == parent.Id
                let children = Descendants(node, source)
                select new PlanilhaCusto
                {
                    Id = node.Id,
                    ParentId = node.ParentId,
                    Name = node.Name,
                    Amount = node.Amount,
                    Price = node.Price,
                    Children = children,
                };

    return query.ToList();
}

var hierarchy = from node in source
                let children = Descendants(node, source)
                where node.ParentId == null
                select new PlanilhaCusto
                {
                    Id = node.Id,
                    ParentId = node.ParentId,
                    Name = node.Name,
                    Price = node.Price,
                    Children = children,
                };

that would project the initial data source into something similar

and from here you just need to traverse the hierarchy and compose the total price

public decimal? Total(PlanilhaCusto node)
{
    decimal? price = node.Price * node.Amount;
    if (node.Children != null)
    {
        foreach (var child in node.Children)
        {
            price += Total(child);
        }
    }

    return price;
}

var totals = from node in hierarchy
             select new
             {
                Id = node.Id,
                Name = node.Name,
                Total = Total(node),
             };


问:
How to loop through a JSON array and put data in variables
I am trying to get the data from an API and save it to a MySQL database. The problem is when I want to echo the data to check if it gets all the values I'm getting this error:

Notice: Trying to get property of non-object

My JSON data looks like this:

```<code>{"AttractionInfo":[{"Id":"sprookjesbos","Type":"Attraction","MapLocation":"1","State":"open","StateColor":"green","WaitingTime":0,"StatePercentage":0},{"Id":"zanggelukkig","Type":"Show","MapLocation":".","State":"gesloten","StateColor":"clear"},
</code>```

I think this is because it is in an array. Because when I use this bit of code it gives no errors but I have to define the index of the array. What is the best way to loop through my data and put it in variables?

```<code><?php

    //Get content
    $url = "https://eftelingapi.herokuapp.com/attractions";
    $data = json_decode(file_get_contents($url));

    //Fetch data
    $attractieId = $data->AttractionInfo[0]->Id;
    $attractieType = $data->AttractionInfo[0]->Type;
    $attractieStatus = $data->AttractionInfo[0]->State;
    $attractieStatusKleur = $data->AttractionInfo[0]->StateColor;
    $attractieWachttijd = $data->AttractionInfo[0]->WaitingTime;
    $attractieStatusPercentage = $data->AttractionInfo[0]->StatePercentage;

?>
</code>```

I tried to find some solutions but all they use is a foreach loop. But i don't think that'll work right. Can anyone help me in the good direction or tell me how I might possibly fix this? I am not very experienced so any advice is welcome. Thanks in advance.

Update code:

```<code>require 'database-connection.php';
//Get content
$url = "https://eftelingapi.herokuapp.com/attractions";
$data = json_decode(file_get_contents($url));

//Fetch data
$attractieId = isset($data->AttractionInfo->Id);
$attractieType = isset($data->AttractionInfo->Type);
$attractieStatus = isset($data->AttractionInfo->State);
$attractieStatusKleur = isset($data->AttractionInfo->StateColor);
$attractieWachttijd = isset($data->AttractionInfo->WaitingTime);
$attractieStatusPercentage = isset($data->AttractionInfo->StatePercentage);

$sql =  "INSERT INTO attracties (attractieId, attractieType, attractieStatus, attractieStatusKleur, attractieWachttijd, attractieStatusPercentage)
VALUES ('$attractieId', '$attractieType', '$attractieStatus', '$attractieStatusKleur', '$attractieWachttijd', '$attractieStatusPercentage')";
if ($db->query($sql) === TRUE) {
    echo "success";
} else {
    echo "Error: " . $sql . "<br>" . $db->error;
}
</code>```

It says 'success' but when I look into my database it inserted only empty data. I need to add all the attractions to my database so not just one row. So I need to loop through my data.

答:
try this...</p>

```<code>$content = json_decode(file_get_contents($url));

foreach($content->AttractionInfo as $data ){
      $id      = $data->Id;
      $type    = $data->Type;
      $map     = $data->MapLocation;
      $state   = $data->State;
      $color   = $data->StateColor;
      if(!empty($data->WaitingTime)) {
      $time = $data->WaitingTime;
      }
     if(!empty($data->StatePercentage)) {
       $percent = $data->StatePercentage;
     }

  //persist your data into DB....
}
</code>```

Body:
I am trying to get the data from an API and save it to a MySQL database. The problem is when I want to echo the data to check if it gets all the values I'm getting this error:

Notice: Trying to get property of non-object

My JSON data looks like this:

{"AttractionInfo":[{"Id":"sprookjesbos","Type":"Attraction","MapLocation":"1","State":"open","StateColor":"green","WaitingTime":0,"StatePercentage":0},{"Id":"zanggelukkig","Type":"Show","MapLocation":".","State":"gesloten","StateColor":"clear"},

I think this is because it is in an array. Because when I use this bit of code it gives no errors but I have to define the index of the array. What is the best way to loop through my data and put it in variables?

<?php

    //Get content
    $url = "https://eftelingapi.herokuapp.com/attractions";
    $data = json_decode(file_get_contents($url));

    //Fetch data
    $attractieId = $data->AttractionInfo[0]->Id;
    $attractieType = $data->AttractionInfo[0]->Type;
    $attractieStatus = $data->AttractionInfo[0]->State;
    $attractieStatusKleur = $data->AttractionInfo[0]->StateColor;
    $attractieWachttijd = $data->AttractionInfo[0]->WaitingTime;
    $attractieStatusPercentage = $data->AttractionInfo[0]->StatePercentage;

?>

I tried to find some solutions but all they use is a foreach loop. But i don't think that'll work right. Can anyone help me in the good direction or tell me how I might possibly fix this? I am not very experienced so any advice is welcome. Thanks in advance.

Update code:

require 'database-connection.php';
//Get content
$url = "https://eftelingapi.herokuapp.com/attractions";
$data = json_decode(file_get_contents($url));

//Fetch data
$attractieId = isset($data->AttractionInfo->Id);
$attractieType = isset($data->AttractionInfo->Type);
$attractieStatus = isset($data->AttractionInfo->State);
$attractieStatusKleur = isset($data->AttractionInfo->StateColor);
$attractieWachttijd = isset($data->AttractionInfo->WaitingTime);
$attractieStatusPercentage = isset($data->AttractionInfo->StatePercentage);

$sql =  "INSERT INTO attracties (attractieId, attractieType, attractieStatus, attractieStatusKleur, attractieWachttijd, attractieStatusPercentage)
VALUES ('$attractieId', '$attractieType', '$attractieStatus', '$attractieStatusKleur', '$attractieWachttijd', '$attractieStatusPercentage')";
if ($db->query($sql) === TRUE) {
    echo "success";
} else {
    echo "Error: " . $sql . "
" . $db->error;
}

It says 'success' but when I look into my database it inserted only empty data. I need to add all the attractions to my database so not just one row. So I need to loop through my data.

Body:
try this...

$content = json_decode(file_get_contents($url));

foreach($content->AttractionInfo as $data ){
      $id      = $data->Id;
      $type    = $data->Type;
      $map     = $data->MapLocation;
      $state   = $data->State;
      $color   = $data->StateColor;
      if(!empty($data->WaitingTime)) {
      $time = $data->WaitingTime;
      }
     if(!empty($data->StatePercentage)) {
       $percent = $data->StatePercentage;
     }

  //persist your data into DB....
}


问:
simplexml_load_file not working for some xml
I have a basic common line to parse xml from file.
The issue is XML 2 is parsing fine,but XML 1 is returning NULL.
I have checked all errors ,look into everything,couldn't figure out yet.

Also tried with file_contents but still not working.

```<code>$xml =(simplexml_load_file($data, 'SimpleXMLElement', LIBXML_NOCDATA));
</code>```

XML 1

```<code><?xml version="1.0" encoding="utf-8"?>
<msg:Message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:msg="urn:xmlns:SSE-HomeServices:Messages:Inbound">
  <msg:MessageHeader>
    <msg:senderOrgId>Actavo</msg:senderOrgId>
    <msg:senderTimeStamp>2017-12-06T09:16:57</msg:senderTimeStamp>
    <msg:contractId>CNR-420781-Z7L8Q8</msg:contractId>
  </msg:MessageHeader>
  <msg:Response>
    <msg:WorkOrders>
      <msg:WorkOrder>
        <msg:woNumber>W00521062</msg:woNumber>
        <msg:woNotes>Leak and aav all sorted .
Boiler now operating correctly and no leaks
Sop7 done No combustion affected Visuals done </msg:woNotes>
        <msg:isProductSwitchRequired>No</msg:isProductSwitchRequired>
        <msg:productSwitchReason xsi:nil="true" />
      </msg:WorkOrder>
    </msg:WorkOrders>
  </msg:Response>
</msg:Message>
</code>```

XML 2

```<code><Message xmlns="urn:xmlns:SSE-HomeServices:Messages:Outbound" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <MessageHeader>
    <senderOrgId>SSE</senderOrgId>
    <senderTimeStamp>2017-10-16T15:50:53.2291513+01:00</senderTimeStamp>
  </MessageHeader>
  <Request>
    <WorkOrders>
      <WorkOrder>
        <woNumber>W00617195</woNumber>
        <woCategory>Maintenance</woCategory>
        <woGroup>Gas Work</woGroup>
        <woType>Same Day Breakdown + Service</woType>
        <woInstruction>Cust has no CH or HW. Can an initial inspection be carried out too please. Please can we phone this customer asap due to previous lack of communication. Promotion :N/A Base Product Name :Boiler Cover Addon Product Name :Gas Service Feature Product
          Name :N/A Staff :False Landlord :False</woInstruction>
        <isCentralHeatingOperational>No</isCentralHeatingOperational>
        <isHotWaterOperational>No</isHotWaterOperational>
        <isCallOutChargeable>Non Chargeable</isCallOutChargeable>
        <isPartsChargeable>Determine on site</isPartsChargeable>
        <isLabourChargeable>Determine on site</isLabourChargeable>
        <dueDate>2017-10-17T14:49:00Z</dueDate>
        <name>Same Day Breakdown + Service workorder for Daniel Ward</name>
        <appointmentNumber>1</appointmentNumber>
      </WorkOrder>
    </WorkOrders>
  </Request>
</Message>
</code>```

答:
I think for xml 1, you should add the namespace to simplexml_load_file for msg like:

```<code>$xml =simplexml_load_file($data, 'SimpleXMLElement', LIBXML_NOCDATA, "urn:xmlns:SSE-HomeServices:Messages:Inbound");
</code>```

You can also remove one set of parenthesis from your code.

Body:
I have a basic common line to parse xml from file.
The issue is XML 2 is parsing fine,but XML 1 is returning NULL.
I have checked all errors ,look into everything,couldn't figure out yet.

Also tried with file_contents but still not working.

$xml =(simplexml_load_file($data, 'SimpleXMLElement', LIBXML_NOCDATA));

XML 1

<?xml version="1.0" encoding="utf-8"?>
<msg:Message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:msg="urn:xmlns:SSE-HomeServices:Messages:Inbound">
  <msg:MessageHeader>
    <msg:senderOrgId>Actavo</msg:senderOrgId>
    <msg:senderTimeStamp>2017-12-06T09:16:57</msg:senderTimeStamp>
    <msg:contractId>CNR-420781-Z7L8Q8</msg:contractId>
  </msg:MessageHeader>
  <msg:Response>
    <msg:WorkOrders>
      <msg:WorkOrder>
        <msg:woNumber>W00521062</msg:woNumber>
        <msg:woNotes>Leak and aav all sorted .
Boiler now operating correctly and no leaks
Sop7 done No combustion affected Visuals done </msg:woNotes>
        <msg:isProductSwitchRequired>No</msg:isProductSwitchRequired>
        <msg:productSwitchReason xsi:nil="true" />
      </msg:WorkOrder>
    </msg:WorkOrders>
  </msg:Response>
</msg:Message>

XML 2

<Message xmlns="urn:xmlns:SSE-HomeServices:Messages:Outbound" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <MessageHeader>
    <senderOrgId>SSE</senderOrgId>
    <senderTimeStamp>2017-10-16T15:50:53.2291513+01:00</senderTimeStamp>
  </MessageHeader>
  <Request>
    <WorkOrders>
      <WorkOrder>
        <woNumber>W00617195</woNumber>
        <woCategory>Maintenance</woCategory>
        <woGroup>Gas Work</woGroup>
        <woType>Same Day Breakdown + Service</woType>
        <woInstruction>Cust has no CH or HW. Can an initial inspection be carried out too please. Please can we phone this customer asap due to previous lack of communication. Promotion :N/A Base Product Name :Boiler Cover Addon Product Name :Gas Service Feature Product
          Name :N/A Staff :False Landlord :False</woInstruction>
        <isCentralHeatingOperational>No</isCentralHeatingOperational>
        <isHotWaterOperational>No</isHotWaterOperational>
        <isCallOutChargeable>Non Chargeable</isCallOutChargeable>
        <isPartsChargeable>Determine on site</isPartsChargeable>
        <isLabourChargeable>Determine on site</isLabourChargeable>
        <dueDate>2017-10-17T14:49:00Z</dueDate>
        <name>Same Day Breakdown + Service workorder for Daniel Ward</name>
        <appointmentNumber>1</appointmentNumber>
      </WorkOrder>
    </WorkOrders>
  </Request>
</Message>

Body:
I think for xml 1, you should add the namespace to simplexml_load_file for msg like:

$xml =simplexml_load_file($data, 'SimpleXMLElement', LIBXML_NOCDATA, "urn:xmlns:SSE-HomeServices:Messages:Inbound");

You can also remove one set of parenthesis from your code.


问:
Can I detect at compile time "function arguments" that are compile-time constants
Can I detect at compile time whether "function arguments"1 are compile-time constants?

For example a function print(int i) that can print "constant 5" if called as print(5) but "non-constant 5" if called as print(i) where i is some non-constant variable. In particular, in the "is constant" branch I should be able to treat i as a constexpr, including using it for template arguments, etc.

Macro tricks, template meta-programming and SFINAE tricks are all OK. Ideally it is portable, but solutions that are compiler-specific are better than nothing.

It's OK if there are "false negatives" - i.e., if constant values are sometimes detected as non-constant (e.g., when certain optimizations are disabled).

Bonus points if the solution can detect when constant values are indirectly passed to the function (e.g., when a constant value is passed to an intermediate function that calls print and which is subsequently inlined exposing the constant to print). This last behavior is evidently optimization dependent.

Double bonus points if it naturally extends to multiple arguments.

If one could have overloaded versions of functions with and without constexpr arguments this would presumably be straightforward, but you can't.

1 I'm putting "function arguments" in quotes here because the solution doesn't strictly require detecting this state within a function (or at the caller/callee boundary with special arguments) - it just has to appear to the caller like a function but macros or other tricks like a static object with operator() etc could be used.

答:
it doesn't have to be a plain function void print(int i) - it could be a function-like macro that does some magic on its arguments and calls a different function depending on whether it is a constant, or it could be some template magic

"function-like macro" you said?

Well... first of all I have to warn you that C-style function-like macro are dangerous. Distilled evil, IMHO.

Said this, if you really accept a macro based solution, I suppose that combining it with constexpr methods, a template struct, static local variables and SFINAE...

If you define the following template PrintStruct struct

```<code>template <typename T>
struct PrintStruct
 {
   template <bool>
   static void func (...)
    { std::cout << "func non-const: " << T::func(true) << std::endl; }

   template <bool b, int I = T::func(b)>
   static void func (int)
    { std::cout << "func const:     " << I << std::endl; }
 };
</code>```

and the following C-style function-like macro, that define a foo local struct and pass it, as template argument, to PrintStruct to activate SFINAE to select the desired func() (and call func(), obviously) [EDIT: macro improved by jxh to make it expand as a statement; thanks!] [EDIT 2: macro modified, following an observation of the OP, to accept expressions]

```<code>#define Print(i)                          \
[&]()                                     \
 {                                        \
   static int const printLocalVar { i };  \
                                          \
   struct local_foo                       \
    {                                     \
      static constexpr int func (bool b)  \
       { return b ? printLocalVar : 0; }  \
    } ;                                   \
                                          \
   PrintStruct<local_foo>::func<true>(0); \
 }                                        \
()
</code>```

Observe that the printed value, in the const version of PrintStruct::func(), is a template integer value; so can be used also for template arguments, C-style array dimensions, static_assert()s tests, etc.

Not sure that is perfectly standard (I'm not a really expert) and that do what you exactly want, but the following is a full working example

```<code>#include <iostream>

template <typename T>
struct PrintStruct
 {
   template <bool>
   static void func (...)
    { std::cout << "func non-const: " << T::func(true) << std::endl; }

   template <bool b, int I = T::func(b)>
   static void func (int)
    { std::cout << "func const:     " << I << std::endl; }
 };

#define Print(i)                          \
[&]()                                     \
 {                                        \
   static int const printLocalVar { i };  \
                                          \
   struct local_foo                       \
    {                                     \
      static constexpr int func (bool b)  \
       { return b ? printLocalVar : 0; }  \
    } ;                                   \
                                          \
   PrintStruct<local_foo>::func<true>(0); \
 }                                        \
()

int main()
 {
   constexpr int  i { 2 };
   int const      j { 3 };
   int            k { 4 };
   int const      l { k+1 };

   Print(1);    // print func const:     1
   Print(i);    // print func const:     2
   Print(j);    // print func const:     3
   Print(k);    // print func non-const: 4
   Print(l);    // print func non-const: 5
   Print(2+2);  // print func const:     4
 }
</code>```

Body:
it doesn't have to be a plain function void print(int i) - it could be a function-like macro that does some magic on its arguments and calls a different function depending on whether it is a constant, or it could be some template magic

"function-like macro" you said?

Well... first of all I have to warn you that C-style function-like macro are dangerous. Distilled evil, IMHO.

Said this, if you really accept a macro based solution, I suppose that combining it with constexpr methods, a template struct, static local variables and SFINAE...

If you define the following template PrintStruct struct

template <typename T>
struct PrintStruct
 {
   template <bool>
   static void func (...)
    { std::cout << "func non-const: " << T::func(true) << std::endl; }

   template <bool b, int I = T::func(b)>
   static void func (int)
    { std::cout << "func const:     " << I << std::endl; }
 };

and the following C-style function-like macro, that define a foo local struct and pass it, as template argument, to PrintStruct to activate SFINAE to select the desired func() (and call func(), obviously) [EDIT: macro improved by jxh to make it expand as a statement; thanks!] [EDIT 2: macro modified, following an observation of the OP, to accept expressions]

#define Print(i)                          \
[&]()                                     \
 {                                        \
   static int const printLocalVar { i };  \
                                          \
   struct local_foo                       \
    {                                     \
      static constexpr int func (bool b)  \
       { return b ? printLocalVar : 0; }  \
    } ;                                   \
                                          \
   PrintStruct<local_foo>::func<true>(0); \
 }                                        \
()

Observe that the printed value, in the const version of PrintStruct::func(), is a template integer value; so can be used also for template arguments, C-style array dimensions, static_assert()s tests, etc.

Not sure that is perfectly standard (I'm not a really expert) and that do what you exactly want, but the following is a full working example

#include <iostream>

template <typename T>
struct PrintStruct
 {
   template <bool>
   static void func (...)
    { std::cout << "func non-const: " << T::func(true) << std::endl; }

   template <bool b, int I = T::func(b)>
   static void func (int)
    { std::cout << "func const:     " << I << std::endl; }
 };

#define Print(i)                          \
[&]()                                     \
 {                                        \
   static int const printLocalVar { i };  \
                                          \
   struct local_foo                       \
    {                                     \
      static constexpr int func (bool b)  \
       { return b ? printLocalVar : 0; }  \
    } ;                                   \
                                          \
   PrintStruct<local_foo>::func<true>(0); \
 }                                        \
()

int main()
 {
   constexpr int  i { 2 };
   int const      j { 3 };
   int            k { 4 };
   int const      l { k+1 };

   Print(1);    // print func const:     1
   Print(i);    // print func const:     2
   Print(j);    // print func const:     3
   Print(k);    // print func non-const: 4
   Print(l);    // print func non-const: 5
   Print(2+2);  // print func const:     4
 }


问:
Android - shadow on text?
I am wondering how to add shadow on text in android?

I have the following code which is applied on a bitmap and I wanted to be shadowed...

```<code>paint.setColor(Color.BLACK);
paint.setTextSize(55);
paint.setFakeBoldText(false);
paint.setShadowLayer(1, 0, 0, Color.BLACK); //This only shadows my whole view...
</code>```

答:
```<code> <style name="WhiteTextWithShadow" parent="@android:style/TextAppearance">
    <item name="android:shadowDx">1</item>
    <item name="android:shadowDy">1</item>
    <item name="android:shadowRadius">1</item>
    <item name="android:shadowColor">@android:color/black</item>
    <item name="android:textColor">@android:color/white</item>
</style>
</code>```

then use as

```<code> <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="15sp"
            tools:text="Today, May 21"
            style="@style/WhiteTextWithShadow"/>
</code>```

Title: Android - shadow on text?

Body:
I am wondering how to add shadow on text in android?

I have the following code which is applied on a bitmap and I wanted to be shadowed...

paint.setColor(Color.BLACK);
paint.setTextSize(55);
paint.setFakeBoldText(false);
paint.setShadowLayer(1, 0, 0, Color.BLACK); //This only shadows my whole view...

Body:
 <style name="WhiteTextWithShadow" parent="@android:style/TextAppearance">
    <item name="android:shadowDx">1</item>
    <item name="android:shadowDy">1</item>
    <item name="android:shadowRadius">1</item>
    <item name="android:shadowColor">@android:color/black</item>
    <item name="android:textColor">@android:color/white</item>
</style>

then use as

 <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="15sp"
            tools:text="Today, May 21"
            style="@style/WhiteTextWithShadow"/>


问:
If User sets Security setting in High mode from internet option. How to get Security mode in C# code?
In my web application I calling webmethods using javascript/Jquery in asp.net c# web application,
If User sets Security setting in High mode then no any javascript runs on client machine
it means Javascript goes disable.
All the web methods going stopped running & no action take place..

If User set in IE8.0 browser

```<code>Goto Tools,
-> internet option
-> security Tab
-> select Internet and set security mode to High
-> then It disabled Javascript.
</code>```

How we get security mode setting by user in C#?
If any alternate way to know that javascript is not enabled or change the mode!!
I want alert to if user set Internet security setting in high mode/Medium High mode..

-Thanks

Abhishek

答:
How we get security mode setting by user in C#?

You can't.

If any alternate way to know that javascript is not enabled or change the mode

You could use the  HTML tag to provide alternate content when a script is not executed.

Body:
In my web application I calling webmethods using javascript/Jquery in asp.net c# web application,
If User sets Security setting in High mode then no any javascript runs on client machine
it means Javascript goes disable.
All the web methods going stopped running & no action take place..

If User set in IE8.0 browser

Goto Tools,
-> internet option
-> security Tab
-> select Internet and set security mode to High
-> then It disabled Javascript.

How we get security mode setting by user in C#?
If any alternate way to know that javascript is not enabled or change the mode!!
I want alert to if user set Internet security setting in high mode/Medium High mode..

-Thanks

Abhishek

Body:
How we get security mode setting by user in C#?

You can't.

If any alternate way to know that javascript is not enabled or change the mode

You could use the <noscript> HTML tag to provide alternate content when a script is not executed.


答:
You can let the Apple class be its own factory.

```<code>public class Apple
{
    private Apple()
    {}

    internal static Apple Create()
    {
        var apple = new Apple();
        // TODO: Initialize
        return apple;
    }
}
</code>```

The real Apple factory can then call this factory method:

```<code>public class AppleFactory() {
    public CreateApple() => Apple.Create();
}
</code>```

By making Apple.Create() internal, you can restrict its usage to the current assembly. The constructor can be called only insde Apple anway, because it is private.

Title: Prevent access to constructor / only specific class has access

Body:
Let's say I have an Apple Class and an AppleFactoryClass.
Nobody should be able to use Apple redApple = new Apple(). Instead new Apples should only be able to be created from  AppleFactory.Create().

This mean the Constructor of Apple must be inaccessible for everyone but the AppleFactory Class.

How can this be done?

EDIT: Apple is more like an AppleModel. So there is only Properties in there.

Body:
You can let the Apple class be its own factory.

public class Apple
{
    private Apple()
    {}

    internal static Apple Create()
    {
        var apple = new Apple();
        // TODO: Initialize
        return apple;
    }
}

The real Apple factory can then call this factory method:

public class AppleFactory() {
    public CreateApple() => Apple.Create();
}

By making Apple.Create() internal, you can restrict its usage to the current assembly. The constructor can be called only insde Apple anway, because it is private.