问:
Maven build no main manifest attribute
I'm building a small app with Maven that has dependencies and is an executable jar file.

Here is my 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>com.company</groupId>
    <artifactId>site-downloader</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.141.59</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>com.company.siteripper</groupId>
            <artifactId>common-interfaces</artifactId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <archive>
                                <manifest>
                                    <mainClass>
                                        com.company.Main
                                    </mainClass>
                                </manifest>
                            </archive>
                            <descriptorRefs>
                                <descriptorRef>jar-with-dependencies</descriptorRef>
                            </descriptorRefs>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

The build completes with no issues but when executing the jar it writes

no main manifest attribute, in local maven repo / my jar.

I sought aid at the docs and Baeldung too to no avail.

I seek assistance to make the jar include its dependencies and is executable at the same time.

Edit:

I updated my pom to use the jar and the dependencies plugins instead of the assembly. Here is the updated pom:

```<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>com.company</groupId>
    <artifactId>site-downloader</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.141.59</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>com.company.siteripper</groupId>
            <artifactId>common-interfaces</artifactId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>
                                com.company.Main
                            </mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>
                                ${project.build.directory}/libs
                            </outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

But I get a NoClassDefFoundError when running it:

C:\Users\myusername\Documents\Commands>call java -jar
  D:.m2\repository\com\company\site-downloader\1.0.0\site-downloader-1.0.0.jar
  -9gag https://9gag.com/gag/arGEvRX?ref C:\Users\myusername\Documents\sites\data\android Error: A JNI error
  has occurred, please check your installation and try again Exception
  in thread "main" java.lang.NoClassDefFoundError:
  org/openqa/selenium/WebDriver
          at java.lang.Class.getDeclaredMethods0(Native Method)
          at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
          at java.lang.Class.privateGetMethodRecursive(Unknown Source)
          at java.lang.Class.getMethod0(Unknown Source)
          at java.lang.Class.getMethod(Unknown Source)
          at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
          at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source) Caused by: java.lang.ClassNotFoundException:
  org.openqa.selenium.WebDriver
          at java.net.URLClassLoader.findClass(Unknown Source)
          at java.lang.ClassLoader.loadClass(Unknown Source)
          at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
          at java.lang.ClassLoader.loadClass(Unknown Source)
          ... 7 more

答:
This is how I solved your issue:

Please ignore business logic,
since I am using MongoDB, added MongoDB driver as a dependency and able to run with java -jar command.

The end goal is same as of yours.

I am using maven-shade plug-in.

Checkout project from Github source code:

unzip, build, test

OR

1. Created a maven project

mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4

Update pom.xml with following, added mongo client code from OP and printing collection names

Execute
mvn clean package

Execute
java -jar test.jar
output I got is:

```<code>INFO: Opened connection [connectionId{localValue:1, serverValue:9}] to localhost:27017
Jun 01, 2019 8:17:22 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 5]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=2249770}
Jun 01, 2019 8:17:22 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:2, serverValue:10}] to localhost:27017
admin
config
local
test
[XenonSuite] Successfully connected to MongoDB
</code>```

pom.xml(ignore package names)

Check shade plugin configuration

<?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>test</groupId>
  <artifactId>test</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>test</name>

  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <mainClass>test.App</mainClass>
  </properties>

  <packaging>jar</packaging>

  <dependencies>

    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>3.10.2</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-assembly-plugin</artifactId>
          <version>3.1.1</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-dependency-plugin</artifactId>
          <version>3.1.1</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.1.1</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-shade-plugin</artifactId>
          <version>3.2.1</version>
          <executions>
            <execution>
              <phase>package</phase>
              <goals>
                <goal>shade</goal>
              </goals>
              <configuration>
                <shadedArtifactAttached>true</shadedArtifactAttached>
                <transformers>
                  <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                    <mainClass>test.App</mainClass>
                  </transformer>
                </transformers>
                <finalName>test</finalName>
              </configuration>
            </execution>
          </executions>
        </plugin>
      </plugins>
  </build>
</project>

```

There are multiple ways to solve this problem
Ref: https://www.baeldung.com/executable-jar-with-maven

Title: Maven build no main manifest attribute

Body:
I'm building a small app with Maven that has dependencies and is an executable jar file.

Here is my 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>com.company</groupId>
    <artifactId>site-downloader</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.141.59</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>com.company.siteripper</groupId>
            <artifactId>common-interfaces</artifactId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <archive>
                                <manifest>
                                    <mainClass>
                                        com.company.Main
                                    </mainClass>
                                </manifest>
                            </archive>
                            <descriptorRefs>
                                <descriptorRef>jar-with-dependencies</descriptorRef>
                            </descriptorRefs>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

The build completes with no issues but when executing the jar it writes

no main manifest attribute, in local maven repo / my jar.

I sought aid at the docs and Baeldung too to no avail.

I seek assistance to make the jar include its dependencies and is executable at the same time.

Edit:

I updated my pom to use the jar and the dependencies plugins instead of the assembly. Here is the updated pom:

<?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>com.company</groupId>
    <artifactId>site-downloader</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.141.59</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>com.company.siteripper</groupId>
            <artifactId>common-interfaces</artifactId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>
                                com.company.Main
                            </mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>
                                ${project.build.directory}/libs
                            </outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

But I get a NoClassDefFoundError when running it:

C:\Users\myusername\Documents\Commands>call java -jar
  D:.m2\repository\com\company\site-downloader\1.0.0\site-downloader-1.0.0.jar
  -9gag https://9gag.com/gag/arGEvRX?ref C:\Users\myusername\Documents\sites\data\android Error: A JNI error
  has occurred, please check your installation and try again Exception
  in thread "main" java.lang.NoClassDefFoundError:
  org/openqa/selenium/WebDriver
          at java.lang.Class.getDeclaredMethods0(Native Method)
          at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
          at java.lang.Class.privateGetMethodRecursive(Unknown Source)
          at java.lang.Class.getMethod0(Unknown Source)
          at java.lang.Class.getMethod(Unknown Source)
          at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
          at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source) Caused by: java.lang.ClassNotFoundException:
  org.openqa.selenium.WebDriver
          at java.net.URLClassLoader.findClass(Unknown Source)
          at java.lang.ClassLoader.loadClass(Unknown Source)
          at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
          at java.lang.ClassLoader.loadClass(Unknown Source)
          ... 7 more

Body:
This is how I solved your issue:

Please ignore business logic,
since I am using MongoDB, added MongoDB driver as a dependency and able to run with java -jar command.

The end goal is same as of yours.

I am using maven-shade plug-in.

Checkout project from Github source code:

unzip, build, test

OR

1. Created a maven project

mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4

Update pom.xml with following, added mongo client code from OP and printing collection names

Execute
mvn clean package

Execute
java -jar test.jar
output I got is:

INFO: Opened connection [connectionId{localValue:1, serverValue:9}] to localhost:27017
Jun 01, 2019 8:17:22 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 5]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=2249770}
Jun 01, 2019 8:17:22 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:2, serverValue:10}] to localhost:27017
admin
config
local
test
[XenonSuite] Successfully connected to MongoDB

pom.xml(ignore package names)

Check shade plugin configuration

<?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>test</groupId>
  <artifactId>test</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>test</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <mainClass>test.App</mainClass>
  </properties>

  <packaging>jar</packaging>

  <dependencies>

  <!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>3.10.2</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-assembly-plugin</artifactId>
          <version>3.1.1</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-dependency-plugin</artifactId>
          <version>3.1.1</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.1.1</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-shade-plugin</artifactId>
          <version>3.2.1</version>
          <executions>
            <execution>
              <phase>package</phase>
              <goals>
                <goal>shade</goal>
              </goals>
              <configuration>
                <shadedArtifactAttached>true</shadedArtifactAttached>
                <transformers>
                  <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                    <mainClass>test.App</mainClass>
                  </transformer>
                </transformers>
                <finalName>test</finalName>
              </configuration>
            </execution>
          </executions>
        </plugin>
      </plugins>
  </build>
</project>

There are multiple ways to solve this problem
Ref: https://www.baeldung.com/executable-jar-with-maven


来源: stackexchange

问:
WPF WebView doesn't show
I'm learning WPF WebView control, I have the below MainWindow.xaml file:

```<code><Window x:Class="MyWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MyWPF"
        xmlns:WPF="clr-namespace:Microsoft.Toolkit.Wpf.UI.Controls;assembly=Microsoft.Toolkit.Wpf.UI.Controls.WebView"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid x:Name="Grid1" Grid.Row="1" Grid.Column="1">
        <WPF:WebView x:Name="webView1"
                      Grid.Row="0"
                      Grid.Column="0"
                      Loaded="WebView_Loaded" />
    </Grid>
</Window>
</code>```

and the below corresponding MainWindow.xaml.cs file:

```<code>namespace MyWPF
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            webView1.Navigate(new Uri("https://www.google.com"));
        }

        private void WebView_Loaded(object sender, RoutedEventArgs e)
        {
        }
    }
}
</code>```

But I don't get any expecting popup window. If I remove

webView1.Navigate(new Uri("https://www.google.com"));

I can get a blank popup window. What is wrong with my code and how to solve it?

UPDATE1

I added Window_Loaded event handler and move the below two in it, now I can see a blank popup window but without any content as well as message box.

```<code>Uri uri = new Uri("https://www.google.com");
WebView1.Navigate(uri);
</code>```

The whole updated code-behind:

```<code>namespace MyWPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Loaded");
            Uri uri = new Uri("https://www.google.com");
            WebView1.Navigate(uri);
        }
    }
}
</code>```

UPDATE2

I added one HyperLink and one Button into xaml file, the below is the updated xaml file:

```<code><Window x:Class="MyWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MyWPF"
        xmlns:WPF="clr-namespace:Microsoft.Toolkit.Wpf.UI.Controls;assembly=Microsoft.Toolkit.Wpf.UI.Controls.WebView"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" AllowsTransparency="False" >
    <Grid x:Name="Grid1" Visibility="Visible" >
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="71*"/>
        </Grid.ColumnDefinitions>
        <WPF:WebView x:Name="WebView1" Visibility="Visible" Grid.Column="1" Margin="50,50,50,50">
        </WPF:WebView>
        <Button Name="BTN1" Click="BTN1_Click" Margin="285,380,285,10" Grid.Column="1" >Click Me</Button>
        <TextBlock Margin="0,0,747,390" Grid.ColumnSpan="2">
            <Hyperlink
                NavigateUri="http://www.google.com">
                Google
            </Hyperlink>
        </TextBlock>
    </Grid>
</Window>
</code>```

and adding Button click event handler into the code-behind with webview initialization inside it:

```<code>namespace MyWPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Loaded");

            //Uri uri = ;
            WebView1.Navigate(new Uri("https://www.google.com"));
        }
        private void BTN1_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Loaded");
            WebView1.Navigate(new Uri("https://www.google.com"));
        }
    }
}
</code>```

Nothing happens after clicking the HyperLink. I see popup Messagebox after clicking button but still google doesn't show up.

UPDATE3

I followed the link:

https://learn.microsoft.com/en-us/windows/communitytoolkit/controls/wpf-winforms/webview#high-dpi

I set Source property Source="http://www.google.com" inside the xaml file, see the below code:

```<code><Window x:Class="MyWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MyWPF"
        xmlns:WPF="clr-namespace:Microsoft.Toolkit.Wpf.UI.Controls;assembly=Microsoft.Toolkit.Wpf.UI.Controls.WebView"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" AllowsTransparency="False" >
    <Grid x:Name="Grid1"  >
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="71*"/>
        </Grid.ColumnDefinitions>
        <WPF:WebView x:Name="WebView1" Visibility="Visible" Grid.Column="1" Margin="50,50,50,50" Source="http://www.google.com" >
        </WPF:WebView>
        <Button Name="BTN1" Click="BTN1_Click" Margin="285,380,285,10" Grid.Column="1" >Click Me</Button>
        <TextBlock Margin="0,0,747,390" Grid.ColumnSpan="2">
            <Hyperlink
                NavigateUri="http://www.google.com">
                Google
            </Hyperlink>
        </TextBlock>
    </Grid>
</Window>
</code>```

But still not working.

UPDATE4

I added((ISupportInitialize)webView).BeginInit() and ((ISupportInitialize)webView).EndInit() into the button click event handler, see the below:

```<code>using Microsoft.Toolkit.Wpf.UI.Controls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MyWPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Loaded");
        }
        private void BTN1_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Loaded");
            ((ISupportInitialize)WebView1).BeginInit();
            ((ISupportInitialize)WebView1).EndInit();
            WebView1.Navigate(new Uri("https://localhost:3000"));
            Console.ReadLine();
        }
    }
}
</code>```

But get the below error message at this line:
            ((ISupportInitialize)WebView1).BeginInit();
:

$exception  {"Could not find any resources appropriate for the specified culture or the neutral culture.  Make sure
  \"Microsoft.Toolkit.Win32.UI.Controls.DesignerUI.resources\" was
  correctly embedded or linked into assembly
  \"Microsoft.Toolkit.Wpf.UI.Controls.WebView\" at compile time, or that
  all the satellite assemblies required are loadable and fully
  signed."} System.Resources.MissingManifestResourceException

Then I went back and added more properties based on this link:

https://github.com/rjmurillo/webview-samples/blob/master/Toolkit/dotnet/Microsoft.Toolkit.Win32.Samples.WPF.WebView/MainWindow.xaml

```<code><WPF:WebView x:Name="WebView1" Visibility="Visible" Grid.Column="1" Margin="50,50,50,50" Source="http://www.google.com" IsIndexedDBEnabled="True"
            IsJavaScriptEnabled="True"
            IsPrivateNetworkClientServerCapabilityEnabled="True"
            IsScriptNotifyAllowed="True" >
</WPF:WebView>
</code>```

But still WebView not working.

答:
I was also having this issue and even using the ```<code>myWebBrowser.Source = new Uri("<a href="https://www.google.com" rel="nofollow noreferrer">https://www.google.com</a>");</code>``` it was not showing the page.

I added the following to the code and now it loads fine.

```<code> myWebBrowser.BringIntoView();</code>```

I am using this with WPF and displaying it in a popup window, I'm not sure if that has anything to do with the issue I was having or not.

ContentLicense: CC BY-SA 4.0

Title: WPF WebView doesn't show

Body:
I'm learning WPF WebView control, I have the below MainWindow.xaml file:

<Window x:Class="MyWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MyWPF"
        xmlns:WPF="clr-namespace:Microsoft.Toolkit.Wpf.UI.Controls;assembly=Microsoft.Toolkit.Wpf.UI.Controls.WebView"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid x:Name="Grid1" Grid.Row="1" Grid.Column="1">
        <WPF:WebView x:Name="webView1"
                      Grid.Row="0"
                      Grid.Column="0"
                      Loaded="WebView_Loaded" />
    </Grid>
</Window>

and the below corresponding MainWindow.xaml.cs file:

namespace MyWPF
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            webView1.Navigate(new Uri("https://www.google.com"));
        }

        private void WebView_Loaded(object sender, RoutedEventArgs e)
        {
        }
    }
}

But I don't get any expecting popup window. If I remove

webView1.Navigate(new Uri("https://www.google.com"));

I can get a blank popup window. What is wrong with my code and how to solve it?

UPDATE1

I added Window_Loaded event handler and move the below two in it, now I can see a blank popup window but without any content as well as message box.

Uri uri = new Uri("https://www.google.com");
WebView1.Navigate(uri);

The whole updated code-behind:

namespace MyWPF
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Loaded");
            Uri uri = new Uri("https://www.google.com");
            WebView1.Navigate(uri);
        }
    }
}

UPDATE2

I added one HyperLink and one Button into xaml file, the below is the updated xaml file:

<Window x:Class="MyWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MyWPF"
        xmlns:WPF="clr-namespace:Microsoft.Toolkit.Wpf.UI.Controls;assembly=Microsoft.Toolkit.Wpf.UI.Controls.WebView"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" AllowsTransparency="False" >
    <Grid x:Name="Grid1" Visibility="Visible" >
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="71*"/>
        </Grid.ColumnDefinitions>
        <WPF:WebView x:Name="WebView1" Visibility="Visible" Grid.Column="1" Margin="50,50,50,50">
        </WPF:WebView>
        <Button Name="BTN1" Click="BTN1_Click" Margin="285,380,285,10" Grid.Column="1" >Click Me</Button>
        <TextBlock Margin="0,0,747,390" Grid.ColumnSpan="2">
            <Hyperlink
                NavigateUri="http://www.google.com">
                Google
            </Hyperlink>
        </TextBlock>
    </Grid>
</Window>

and adding Button click event handler into the code-behind with webview initialization inside it:

namespace MyWPF
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Loaded");

            //Uri uri = ;
            WebView1.Navigate(new Uri("https://www.google.com"));
        }
        private void BTN1_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Loaded");
            WebView1.Navigate(new Uri("https://www.google.com"));
        }
    }
}

Nothing happens after clicking the HyperLink. I see popup Messagebox after clicking button but still google doesn't show up.

UPDATE3

I followed the link:

https://learn.microsoft.com/en-us/windows/communitytoolkit/controls/wpf-winforms/webview#high-dpi

I set Source property Source="http://www.google.com" inside the xaml file, see the below code:

<Window x:Class="MyWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MyWPF"
        xmlns:WPF="clr-namespace:Microsoft.Toolkit.Wpf.UI.Controls;assembly=Microsoft.Toolkit.Wpf.UI.Controls.WebView"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" AllowsTransparency="False" >
    <Grid x:Name="Grid1"  >
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="71*"/>
        </Grid.ColumnDefinitions>
        <WPF:WebView x:Name="WebView1" Visibility="Visible" Grid.Column="1" Margin="50,50,50,50" Source="http://www.google.com" >
        </WPF:WebView>
        <Button Name="BTN1" Click="BTN1_Click" Margin="285,380,285,10" Grid.Column="1" >Click Me</Button>
        <TextBlock Margin="0,0,747,390" Grid.ColumnSpan="2">
            <Hyperlink
                NavigateUri="http://www.google.com">
                Google
            </Hyperlink>
        </TextBlock>
    </Grid>
</Window>

But still not working.

UPDATE4

I added((ISupportInitialize)webView).BeginInit() and ((ISupportInitialize)webView).EndInit() into the button click event handler, see the below:

using Microsoft.Toolkit.Wpf.UI.Controls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MyWPF
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Loaded");
        }
        private void BTN1_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Loaded");
            ((ISupportInitialize)WebView1).BeginInit();
            ((ISupportInitialize)WebView1).EndInit();
            WebView1.Navigate(new Uri("https://localhost:3000"));
            Console.ReadLine();
        }
    }
}

But get the below error message at this line:
            ((ISupportInitialize)WebView1).BeginInit();
:

$exception  {"Could not find any resources appropriate for the specified culture or the neutral culture.  Make sure
  \"Microsoft.Toolkit.Win32.UI.Controls.DesignerUI.resources\" was
  correctly embedded or linked into assembly
  \"Microsoft.Toolkit.Wpf.UI.Controls.WebView\" at compile time, or that
  all the satellite assemblies required are loadable and fully
  signed."} System.Resources.MissingManifestResourceException

Then I went back and added more properties based on this link:

https://github.com/rjmurillo/webview-samples/blob/master/Toolkit/dotnet/Microsoft.Toolkit.Win32.Samples.WPF.WebView/MainWindow.xaml

<WPF:WebView x:Name="WebView1" Visibility="Visible" Grid.Column="1" Margin="50,50,50,50" Source="http://www.google.com" IsIndexedDBEnabled="True"
            IsJavaScriptEnabled="True"
            IsPrivateNetworkClientServerCapabilityEnabled="True"
            IsScriptNotifyAllowed="True" >
</WPF:WebView>

But still WebView not working.

Body:
I was also having this issue and even using the
myWebBrowser.Source = new Uri("https://www.google.com");
 it was not showing the page.

I added the following to the code and now it loads fine.

 myWebBrowser.BringIntoView();

I am using this with WPF and displaying it in a popup window, I'm not sure if that has anything to do with the issue I was having or not.


问:
Rails 5.2.3 / Heroku - Why is it not possible to run postgres in production mode with squlite3 in development mode?
I'm using Rails 5.2.3 and I'm getting an application error when I try to view my production app on Heroku pipeline & the following errors when:

I run heroku logs I get: heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/"

I run heroku run rails console I get: Error loading the 'sqlite3' Active Record adapter. Missing a gem it depends on? sqlite3 is not part of the bundle. Add it to your Gemfile. (LoadError)

I run heroku run rails db:migrate I get: LoadError: Error loading the 'sqlite3' Active Record adapter. Missing a gem it depends on? sqlite3 is not part of the bundle. Add it to your Gemfile.

I want to use sqlite3 for development and postgres for production, so why do I need to make the sqlite3 gemfile available in production mode?

Here's my gemfile:

```<code>group :development do
  gem 'sqlite3'
end

group :production do
  gem 'pg'
end
</code>```

Here's my database.yml:

```<code>default: &default
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

test:
  <<: *default
  database: db/test.sqlite3

production:
  <<: *default
  database: db/production.sqlite3
</code>```

答:
I know you wrote

I want to use sqlite3 for development and postgres for production

and I can understand because I've been there myself; feeling that postgres seems like a big step to install and "I just want something small that works".

Perhaps your reason is different, but if it is not - installing postgres will save you a lot of trouble. Postgres is free and the default installation settings will probably work great for you.

In addition to saving you the hassle of adapter and gem incompatibilities, you also sometimes have differences in the SQL-commands available (when you want to do something more advanced) and what things have high performance or not.

https://www.postgresql.org/download/

When you have a development and production environment that differs - you'll spend a lot of time fixing things that does not increase the value of whatever you are building.

Body:
I'm using Rails 5.2.3 and I'm getting an application error when I try to view my production app on Heroku pipeline & the following errors when:

I run heroku logs I get: heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/"

I run heroku run rails console I get: Error loading the 'sqlite3' Active Record adapter. Missing a gem it depends on? sqlite3 is not part of the bundle. Add it to your Gemfile. (LoadError)

I run heroku run rails db:migrate I get: LoadError: Error loading the 'sqlite3' Active Record adapter. Missing a gem it depends on? sqlite3 is not part of the bundle. Add it to your Gemfile.

I want to use sqlite3 for development and postgres for production, so why do I need to make the sqlite3 gemfile available in production mode?

Here's my gemfile:

group :development do
  gem 'sqlite3'
end

group :production do
  gem 'pg'
end

Here's my database.yml:

default: &default
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

test:
  <<: *default
  database: db/test.sqlite3

production:
  <<: *default
  database: db/production.sqlite3


问:
Why do I get this "Context = NullPointerException" error in my homework?
I am doing a tutorial for homework, which is to build an Instagram app. The tutorial is about two years old and I am having some problems with the coding.

I am having the following error and am not sure why.

```<code> java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
</code>```

My UniversalImageLoader class

```<code>public class UniversalImageLoader {

    private static final int defaultImage = R.drawable.ic_android;
    private Context mContext;

    public UniversalImageLoader(Context context) {
        mContext = context;
    }

    public ImageLoaderConfiguration getConfig(){
        //File cacheDir = StorageUtils.getCacheDirectory(mContext);
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(mContext)//<--the error is in this line
                .memoryCacheExtraOptions(480, 800) // default = device screen dimensions
                .diskCacheExtraOptions(480, 800, null)
                .threadPriority(Thread.NORM_PRIORITY - 2) // default
                .tasksProcessingOrder(QueueProcessingType.FIFO) // default
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
                .memoryCacheSize(2 * 1024 * 1024)
                .memoryCacheSizePercentage(13) // default
                .diskCacheSize(50 * 1024 * 1024)
                .diskCacheFileCount(100)
                .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
                .imageDownloader(new BaseImageDownloader(mContext)) // default
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
                .writeDebugLogs()
                .build();

        return config;
    }
</code>```

in HomeActivity:(and OnCreate)[in every Activity I call it like this]

```<code>initImageLoader();
</code>```

```<code>
private void initImageLoader(){
        UniversalImageLoader universalImageLoader = new UniversalImageLoader(mContext);
        ImageLoader.getInstance().init(universalImageLoader.getConfig());
    }
</code>```

答:
When you are creating object of UniversalImageLoader class, pass getApplicationContext() instead of activity context.

Application context is available through out application while activity context is bound to activity life cycle.

Update:

Application Context: It is an instance which is the singleton and can be accessed in an activity via getApplicationContext(). This context is tied to the lifecycle of an application. The application context can be used where you need a context whose lifecycle is separate from the current context or when you are passing a context beyond the scope of an activity

```<code>private void initImageLoader(){
    UniversalImageLoader universalImageLoader = new UniversalImageLoader(getApplicationContext());
    ImageLoader.getInstance().init(universalImageLoader.getConfig());
}
</code>```

Activity Context This context is available in an activity. This context is tied to the lifecycle of an activity.

Here read more about the difference in Activity context and application context.
https://blog.mindorks.com/understanding-context-in-android-application-330913e32514

For Multiple Activities you can initialize in Application class onCreate method.

```<code>public class MyApplication extends Application {

@Override
public void onCreate() {
    super.onCreate();
        // Initialize the Universal Image Loader here

    DisplayImageOptions defaultOptions = new
    DisplayImageOptions.Builder()
            .cacheOnDisk(true).cacheInMemory(true).build();

    ImageLoaderConfiguration config = new
    ImageLoaderConfiguration.Builder(getApplicationContext())
            .defaultDisplayImageOptions(defaultOptions).build();

    ImageLoader.getInstance().init(config);

}
</code>```

Then in your Activity get image Loader instance like this.

```<code>ImageLoader mImageLoader = ImageLoader.getInstance();
</code>```

Also you need to add your Application class in AndroidManifest like this.

```<code><application
    android:name=".MyApplication"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
</code>```

Body:
I am doing a tutorial for homework, which is to build an Instagram app. The tutorial is about two years old and I am having some problems with the coding.

I am having the following error and am not sure why.

 java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference

My UniversalImageLoader class

public class UniversalImageLoader {

    private static final int defaultImage = R.drawable.ic_android;
    private Context mContext;

    public UniversalImageLoader(Context context) {
        mContext = context;
    }

    public ImageLoaderConfiguration getConfig(){
        //File cacheDir = StorageUtils.getCacheDirectory(mContext);
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(mContext)//<--the error is in this line
                .memoryCacheExtraOptions(480, 800) // default = device screen dimensions
                .diskCacheExtraOptions(480, 800, null)
                .threadPriority(Thread.NORM_PRIORITY - 2) // default
                .tasksProcessingOrder(QueueProcessingType.FIFO) // default
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
                .memoryCacheSize(2 * 1024 * 1024)
                .memoryCacheSizePercentage(13) // default
                .diskCacheSize(50 * 1024 * 1024)
                .diskCacheFileCount(100)
                .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
                .imageDownloader(new BaseImageDownloader(mContext)) // default
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
                .writeDebugLogs()
                .build();

        return config;
    }

in HomeActivity:(and OnCreate)[in every Activity I call it like this]

initImageLoader();

private void initImageLoader(){
        UniversalImageLoader universalImageLoader = new UniversalImageLoader(mContext);
        ImageLoader.getInstance().init(universalImageLoader.getConfig());
    }

Body:
When you are creating object of UniversalImageLoader class, pass getApplicationContext() instead of activity context.

Application context is available through out application while activity context is bound to activity life cycle.

Update:

Application Context: It is an instance which is the singleton and can be accessed in an activity via getApplicationContext(). This context is tied to the lifecycle of an application. The application context can be used where you need a context whose lifecycle is separate from the current context or when you are passing a context beyond the scope of an activity

private void initImageLoader(){
    UniversalImageLoader universalImageLoader = new UniversalImageLoader(getApplicationContext());
    ImageLoader.getInstance().init(universalImageLoader.getConfig());
}

Activity Context This context is available in an activity. This context is tied to the lifecycle of an activity.

Here read more about the difference in Activity context and application context.
https://blog.mindorks.com/understanding-context-in-android-application-330913e32514

For Multiple Activities you can initialize in Application class onCreate method.

public class MyApplication extends Application {

@Override
public void onCreate() {
    super.onCreate();
        // Initialize the Universal Image Loader here

    DisplayImageOptions defaultOptions = new
    DisplayImageOptions.Builder()
            .cacheOnDisk(true).cacheInMemory(true).build();

    ImageLoaderConfiguration config = new
    ImageLoaderConfiguration.Builder(getApplicationContext())
            .defaultDisplayImageOptions(defaultOptions).build();

    ImageLoader.getInstance().init(config);

}

Then in your Activity get image Loader instance like this.

ImageLoader mImageLoader = ImageLoader.getInstance();

Also you need to add your Application class in AndroidManifest like this.

<application
    android:name=".MyApplication"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"


问:
Apply HTML and CSS style to Java Swing component
I have to write a multi-line text inside the header cells of a JTable.

For this reason, I'm using HTML this way (this is an example):

```<code>     JTable.getModel().getColumnModel().getColumn(i).setHeaderValue("
    <html>
          <div style='width:100%;height:300px;overflow:hidden'>
               <div style='width:100%;height:150px;overflow:hidden'>
                       text of line 1
               </div>
               <div style='width:100%;height:150px;overflow:hidden'>
                        text of line 2
               </div>
         </div>
   </html>
    ");
</code>```

I want set the inner div a 100% width and 150px height.
But seems that height, width and overflow doesn't work.

What is my error?

答:
I have to write a multi-line text inside the header cells of a JTable.

Keep the HTML simple:

```<code>setHeaderValue("<html>Line1<br>line2<br>&nbsp</html>");
</code>```

The above will allow for 3 lines of text (for all columns of the header).

Note: the height of the header is determined by the height of the renderer in the first column.

Body:
I have to write a multi-line text inside the header cells of a JTable.

For this reason, I'm using HTML this way (this is an example):

     JTable.getModel().getColumnModel().getColumn(i).setHeaderValue("

                       text of line 1

                        text of line 2

    ");

I want set the inner div a 100% width and 150px height.
But seems that height, width and overflow doesn't work.

What is my error?

Body:
I have to write a multi-line text inside the header cells of a JTable.

Keep the HTML simple:

setHeaderValue("<html>Line1<br>line2<br>&nbsp</html>");

The above will allow for 3 lines of text (for all columns of the header).

Note: the height of the header is determined by the height of the renderer in the first column.


问:
How to modify a Debian source package to include an additional executable script?
Goal: I want to create a modified Debian source package, namely the official rrdtool package + "some changes". One of these changes is the addition of an executable script.

I have this recipe for patching packages that I've used for many years:

dget http://bla/bla/bla.dsc
cd bla-1.0
(hack hack hack...)
dpkg-source -b .
```

<p>That works if the patches don't chmod any files, but with a patch that introduces an executable file, following the recipe above produces this message:</p>

<pre class="lang-sh prettyprint-override"><code>dpkg-source: warning: executable mode 0755 of 'foobar' will not be represented in diff
</code>```

And sure enough, when I unpack my new source package foobar exists but is not executable.

As I understand it, quilt handles patches based on GNU diff+patch. GNU diff+patch don't handle file permissions. Hmm...

So how do I introduce an executable script into a source package maintained by quilt?

Googling has not been helpful. It seems others have asked, but without replies.

I'm aware that I could simply make my modifications to the *.orig.tar.gz archive, but I'd like to avoid that if at all possible. I'm just amazed that this has been so difficult...

答:
As with most things involving Debian packaging, I believe there are most likely several methods one could employ to accomplish your goal. As I'm still a novice at the process, the one I'm going to suggest is rather inelegant, but also very easy to implement.

The Debian Maintainers' Guide tells us that the debian/install file...

has one line per file installed, with the name of
  the file (relative to the top build directory) then a space then the
  installation directory (relative to the install directory). One
  example of where this is used is if a binary src/bar is left
  uninstalled; the install file might look like:

```<code>src/bar usr/bin

</code>```

This means when this package is installed, there will
  be an executable command /usr/bin/bar.

Which leads me to think that if you created such a debian/install file for your package's new executable script produced by the quilt patch, listing its path relative to the build dir root and the bindir you wish it to reside in, you'll have the package performing as desired.

Another approach might be to make use of the postinst script as outlined in this section of the DMM.

Body:
Goal: I want to create a modified Debian source package, namely the official rrdtool package + "some changes". One of these changes is the addition of an executable script.

I have this recipe for patching packages that I've used for many years:

dget http://bla/bla/bla.dsc
cd bla-1.0
(hack hack hack...)
dpkg-source -b .

That works if the patches don't chmod any files, but with a patch that introduces an executable file, following the recipe above produces this message:

dpkg-source: warning: executable mode 0755 of 'foobar' will not be represented in diff

And sure enough, when I unpack my new source package foobar exists but is not executable.

As I understand it, quilt handles patches based on GNU diff+patch. GNU diff+patch don't handle file permissions. Hmm...

So how do I introduce an executable script into a source package maintained by quilt?

Googling has not been helpful. It seems others have asked, but without replies.

I'm aware that I could simply make my modifications to the *.orig.tar.gz archive, but I'd like to avoid that if at all possible. I'm just amazed that this has been so difficult...

Body:
As with most things involving Debian packaging, I believe there are most likely several methods one could employ to accomplish your goal. As I'm still a novice at the process, the one I'm going to suggest is rather inelegant, but also very easy to implement.

The Debian Maintainers' Guide tells us that the debian/install file...

has one line per file installed, with the name of
  the file (relative to the top build directory) then a space then the
  installation directory (relative to the install directory). One
  example of where this is used is if a binary src/bar is left
  uninstalled; the install file might look like:

src/bar usr/bin

This means when this package is installed, there will
  be an executable command /usr/bin/bar.

Which leads me to think that if you created such a debian/install file for your package's new executable script produced by the quilt patch, listing its path relative to the build dir root and the bindir you wish it to reside in, you'll have the package performing as desired.

Another approach might be to make use of the postinst script as outlined in this section of the DMM.


问:
Spring Batch Job + Spring Cloud Data Flow UI
Our application is built using Spring boot + Gradle. We have got a new requirement to implement spring batch job and it will be triggered using autosys(job scheduling tool) and it has 3 steps performing 3 different operations (file preparation, ftp & audit operations). I have attached @EnableBatchProcessing configuration file for your reference. Here are my questions related to Spring Cloud Data Flow.

Can Spring cloud data flow project be built using Gradle ?. I see all the sample projects built using Maven and official Spring page says Maven is must for Spring Cloud Data Flow. Gradle is the only approved build project in our company.

We are looking for Spring batch admin UI kind of features or operations in Spring Cloud data flow. May i know how can i configure Jobs in Spring Cloud data flow? any sample project?

Our application is deployed into PCF(Pivotal Cloud Foundry) container. So the question is, Do we need to add any services/plugins/space must be allocated in PCF infrastructure to support Spring Cloud data flow ?...

Is Spring Cloud data flow project production ready ?. can this be used in Production?.

```<code>
     @Configuration
     @EnableBatchProcessing
     public class TaskletsConfig {

     @Autowired
     private JobBuilderFactory jobs;

     @Autowired
     private StepBuilderFactory steps;

     @Bean
     protected Step flatFilePreparation() {
         return steps
                 .get("flatFilePreparation")
                 .tasklet(new FlatFilePreparation())
                 .build();
     }

     @Bean
     protected Step ftpFile() {
         return steps
                 .get("ftpFile")
                 .tasklet(new FtpFile())
                 .build();
     }

     @Bean
     protected Step auditFilePreparation() {
         return steps
                 .get("auditFilePreparation")
                 .tasklet(new AuditFilePreparation())
                 .build();
     }

     @Bean
     protected Step errorStep() {
         return steps
                 .get("errorStep")
                 .tasklet(new ErrorStep())
                 .build();
     }

     @Bean
     public Job job() {
        return jobs.get("psbijob").start(flatFilePreparation()).on(ExitStatus.FAILED.getExitCode()).to(errorStep())
             .from(flatFilePreparation()).on("*").to(ftpFile()).on(ExitStatus.FAILED.getExitCode()).to(errorStep())
             .from(ftpFile()).on("*").to(auditFilePreparation()).end().build();
     }

     @Bean
     public JobRepository jobRepository() throws Exception {
         MapJobRepositoryFactoryBean factory
                 = new MapJobRepositoryFactoryBean();
         factory.setTransactionManager(transactionManager());
         return (JobRepository) factory.getObject();
     }

     @Bean
     public PlatformTransactionManager transactionManager() {
         return new ResourcelessTransactionManager();
     }

     @Bean
     public JobLauncher jobLauncher() throws Exception {
         SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
         jobLauncher.setJobRepository(jobRepository());
         return jobLauncher;
     }
     }

</code>```

答:
I will attempt to unpack the questions.

Can Spring cloud data flow project be built using Gradle?

All that Spring Cloud Data Flow (SCDF) requires to create and launch your batch-job is a Spring Boot App (a uber-jar). It doesn't matter whether or not you build the application with Maven, Gradle or by other custom means. Docker is another popular choice and that's the only choice for Kubernetes. In PCF, we recommend the use of maven artifacts, which you can, of course, produce it with Gradle, too.

We are looking for Spring batch admin UI kind of features or operations in Spring Cloud data flow. May i know how can i configure Jobs in Spring Cloud data flow? any sample project?

I'd suggest that you explore the Dashboard section in the reference guide. Also, we have an end-to-end Task and Batch Developer Guide in the SCDF Microsite. Anything and everything you did in Spring Batch Admin can be entirely covered in SCDF, and a lot more features sit on top of it, too. Please take a moment to at least review what all are included.

Do we need to add any services/plugins/space must be allocated in PCF infrastructure to support Spring Cloud data flow?

No special requirement. SCDF is simply just a Boot app, too. You can push it manually to your Org/Space or use the SCDF Tile for PCF (a fully managed marketplace service) to provision SCDF and the related components (Security / Upgrades / DB / Broker) automatically.

Is Spring Cloud data flow project production ready ?. can this be used in Production?

The 1.0 GA of SCDF was released back in July 2016. We are currently at 2.1 GA version. There have been 50+ production releases since the first GA milestone. The SCDF tile for PCF is in production for >1yr now also. And, in PCF specifically, we have several customers using SCDF in production.

Body:
Our application is built using Spring boot + Gradle. We have got a new requirement to implement spring batch job and it will be triggered using autosys(job scheduling tool) and it has 3 steps performing 3 different operations (file preparation, ftp & audit operations). I have attached @EnableBatchProcessing configuration file for your reference. Here are my questions related to Spring Cloud Data Flow.

Can Spring cloud data flow project be built using Gradle ?. I see all the sample projects built using Maven and official Spring page says Maven is must for Spring Cloud Data Flow. Gradle is the only approved build project in our company.

We are looking for Spring batch admin UI kind of features or operations in Spring Cloud data flow. May i know how can i configure Jobs in Spring Cloud data flow? any sample project?

Our application is deployed into PCF(Pivotal Cloud Foundry) container. So the question is, Do we need to add any services/plugins/space must be allocated in PCF infrastructure to support Spring Cloud data flow ?...

Is Spring Cloud data flow project production ready ?. can this be used in Production?.

     @Configuration
     @EnableBatchProcessing
     public class TaskletsConfig {

     @Autowired
     private JobBuilderFactory jobs;

     @Autowired
     private StepBuilderFactory steps;

     @Bean
     protected Step flatFilePreparation() {
         return steps
                 .get("flatFilePreparation")
                 .tasklet(new FlatFilePreparation())
                 .build();
     }

     @Bean
     protected Step ftpFile() {
         return steps
                 .get("ftpFile")
                 .tasklet(new FtpFile())
                 .build();
     }

     @Bean
     protected Step auditFilePreparation() {
         return steps
                 .get("auditFilePreparation")
                 .tasklet(new AuditFilePreparation())
                 .build();
     }

     @Bean
     protected Step errorStep() {
         return steps
                 .get("errorStep")
                 .tasklet(new ErrorStep())
                 .build();
     }

     @Bean
     public Job job() {
        return jobs.get("psbijob").start(flatFilePreparation()).on(ExitStatus.FAILED.getExitCode()).to(errorStep())
             .from(flatFilePreparation()).on("*").to(ftpFile()).on(ExitStatus.FAILED.getExitCode()).to(errorStep())
             .from(ftpFile()).on("*").to(auditFilePreparation()).end().build();
     }

     @Bean
     public JobRepository jobRepository() throws Exception {
         MapJobRepositoryFactoryBean factory
                 = new MapJobRepositoryFactoryBean();
         factory.setTransactionManager(transactionManager());
         return (JobRepository) factory.getObject();
     }

     @Bean
     public PlatformTransactionManager transactionManager() {
         return new ResourcelessTransactionManager();
     }

     @Bean
     public JobLauncher jobLauncher() throws Exception {
         SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
         jobLauncher.setJobRepository(jobRepository());
         return jobLauncher;
     }
     }


问:
Selecting thousands separator character with RegEx
I need to change the decimal separator in a given string that has numbers in it.

What RegEx code can ONLY select the thousands separator character in the string?

It need to only select, when there is number around it. For example only when 123,456 I need to select and replace ,

I'm converting English numbers into Persian (e.g: Hello 123 becomes Hello ۱۲۳). Now I need to replace the decimal separator with Persian version too. But I don't know how I can select it with regex. e.g. Hello 121,534 most become Hello ۱۲۱/۵۳۴

The character that needs to be replaced is , with /

答:
In PHP you can do that using str_replace

```<code>$a="Hello 123,456";
echo str_replace(",", "X", $a);
</code>```

This will return: Hello 123X456

Body:
In PHP you can do that using str_replace

$a="Hello 123,456";
echo str_replace(",", "X", $a);

This will return: Hello 123X456


问:
Angular build not getting deployed to azure in Visual Studio 2017
I have been working on an Angular project for a while now, I have been running Angular 5 for a while now and I upgraded the project to Angular 6, and hopefully soon to Angular 7. When I try to publish the project to Azure App Service it succesfully builds both .net and angular files. I also deploys the .net build to the server, but for some reason it does not upload the angular build anymore. I haven't changed anything in my csproj, it comes directly from the Angular template from Visual Studio.

With Angular 5 i never had this problem, I then upgraded to 6 and had that issue. Couldn't resolve it, so i created a new project and copied all the files. It worked for a few days, and now it's broken again. I have not made any changed to any file involved with publishing the project.

Here is my csproj:

```<code><Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
    <TypeScriptToolsVersion>Latest</TypeScriptToolsVersion>
    <IsPackable>false</IsPackable>
    <SpaRoot>ClientApp\</SpaRoot>
    <DefaultItemExcludes>$(DefaultItemExcludes);$(SpaRoot)node_modules\**</DefaultItemExcludes>

    <!-- Set this to true if you enable server-side prerendering -->
    <BuildServerSideRenderer>false</BuildServerSideRenderer>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="CsvHelper" Version="12.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
    <PackageReference Include="Sendgrid" Version="9.10.0" />
    <PackageReference Include="WindowsAzure.Storage" Version="9.3.3" />
  </ItemGroup>

  <ItemGroup>
    <!-- Don't publish the SPA source files, but do show them in the project files list -->
    <Content Remove="$(SpaRoot)**" />
    <None Remove="$(SpaRoot)**" />
    <None Include="$(SpaRoot)**" Exclude="$(SpaRoot)node_modules\**" />
  </ItemGroup>

  <Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
    <!-- Ensure Node.js is installed -->
    <Exec Command="node --version" ContinueOnError="true">
      <Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
    </Exec>
    <Error Condition="'$(ErrorCode)' != '0'" Text="Node.js is required to build and run this project. To continue, please install Node.js from https://nodejs.org/, and then restart your command prompt or IDE." />
    <Message Importance="high" Text="Restoring dependencies using 'npm'. This may take several minutes..." />
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
  </Target>

  <Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">
    <!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm run build --prod" />
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm run build:ssr --prod" Condition=" '$(BuildServerSideRenderer)' == 'true' " />

    <!-- Include the newly-built files in the publish output -->
    <ItemGroup>
      <DistFiles Include="$(SpaRoot)dist\**; $(SpaRoot)dist-server\**" />
      <DistFiles Include="$(SpaRoot)node_modules\**" Condition="'$(BuildServerSideRenderer)' == 'true'" />
      <ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
        <RelativePath>%(DistFiles.Identity)</RelativePath>
        <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
      </ResolvedFileToPublish>
    </ItemGroup>
  </Target>

</Project>
</code>```

The path should be correct because it builds the angular files on that same path and i can find the build files within the dist folder.

Grabbing the files from the build in the output folder and uploading it with ftp manually works, but ofcourse this behaviour is unwanted.

答:
I, too, have this problem. Although I do not yet have a solution I do have a work-around that might be faster/easier than ftp transfer. In visual studio, you can [right click] the 'dist' directory and publish it directly.

This worked for me and is a clue.

Body:
I have been working on an Angular project for a while now, I have been running Angular 5 for a while now and I upgraded the project to Angular 6, and hopefully soon to Angular 7. When I try to publish the project to Azure App Service it succesfully builds both .net and angular files. I also deploys the .net build to the server, but for some reason it does not upload the angular build anymore. I haven't changed anything in my csproj, it comes directly from the Angular template from Visual Studio.

With Angular 5 i never had this problem, I then upgraded to 6 and had that issue. Couldn't resolve it, so i created a new project and copied all the files. It worked for a few days, and now it's broken again. I have not made any changed to any file involved with publishing the project.

Here is my csproj:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
    <TypeScriptToolsVersion>Latest</TypeScriptToolsVersion>
    <IsPackable>false</IsPackable>
    <SpaRoot>ClientApp\</SpaRoot>
    <DefaultItemExcludes>$(DefaultItemExcludes);$(SpaRoot)node_modules\**</DefaultItemExcludes>

    <BuildServerSideRenderer>false</BuildServerSideRenderer>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="CsvHelper" Version="12.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
    <PackageReference Include="Sendgrid" Version="9.10.0" />
    <PackageReference Include="WindowsAzure.Storage" Version="9.3.3" />
  </ItemGroup>

  <ItemGroup>

    <Content Remove="$(SpaRoot)**" />
    <None Remove="$(SpaRoot)**" />
    <None Include="$(SpaRoot)**" Exclude="$(SpaRoot)node_modules\**" />
  </ItemGroup>

  <Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">

    <Exec Command="node --version" ContinueOnError="true">
      <Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
    </Exec>
    <Error Condition="'$(ErrorCode)' != '0'" Text="Node.js is required to build and run this project. To continue, please install Node.js from https://nodejs.org/, and then restart your command prompt or IDE." />
    <Message Importance="high" Text="Restoring dependencies using 'npm'. This may take several minutes..." />
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
  </Target>

  <Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">

    <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm run build --prod" />
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm run build:ssr --prod" Condition=" '$(BuildServerSideRenderer)' == 'true' " />

    <ItemGroup>
      <DistFiles Include="$(SpaRoot)dist\**; $(SpaRoot)dist-server\**" />
      <DistFiles Include="$(SpaRoot)node_modules\**" Condition="'$(BuildServerSideRenderer)' == 'true'" />
      <ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
        <RelativePath>%(DistFiles.Identity)</RelativePath>
        <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
      </ResolvedFileToPublish>
    </ItemGroup>
  </Target>

</Project>

The path should be correct because it builds the angular files on that same path and i can find the build files within the dist folder.

Grabbing the files from the build in the output folder and uploading it with ftp manually works, but ofcourse this behaviour is unwanted.


问:
Why IMutableEntityType.BaseType is null for entities that inherit directly from a base class?
I've defined the following classes:

```<code>public class DeletableEntity
{
    public bool IsDeleted { get; set; }
}

public class ClassA : DeletableEntity
{
}

public class ClassB : ClassA
{
}
</code>```

In the OnModelCreating I'm getting only entities that inherit from DeletableEntity like this:

```<code>    foreach (var entityType in builder.Model.GetEntityTypes())
    {
        if (typeof(DeletableEntity).IsAssignableFrom(entityType.ClrType) == true)
        {
            var et = entityType.BaseType;
        }
    }
</code>```

Interestingly ClassA has entityType.BaseType == null but ClrType.BaseType clearly shows ClassA inherits from DeletableEntity:

:

For ClassB entityType.BaseType is ClassA as expected:

Why first successor's parent class is being ignored? Is this by design?

PS: I'm using EF Core 2.2.

答:
It's because there is a difference between base class and base entity.

IEntityType represents class mapped as EF Core entity. The type BaseType property of IEnityType is also IEnityType. But in your example DeletableEntity is just a base class, not a base entity, so the property returns null.

Probably the best explanation is the property declaration:

```<code>//
// Summary:
//     Gets the base type of the entity. Returns null if this is not a derived type
//     in an inheritance hierarchy.
IEntityType BaseType { get; }
</code>```

where "inheritance hierarchy" refers to EF Inheritance:

Inheritance in the EF model is used to control how inheritance in the entity classes is represented in the database.

and also Inheritance (Relational Database).

Body:
I've defined the following classes:

public class DeletableEntity
{
    public bool IsDeleted { get; set; }
}

public class ClassA : DeletableEntity
{
}

public class ClassB : ClassA
{
}

In the OnModelCreating I'm getting only entities that inherit from DeletableEntity like this:

    foreach (var entityType in builder.Model.GetEntityTypes())
    {
        if (typeof(DeletableEntity).IsAssignableFrom(entityType.ClrType) == true)
        {
            var et = entityType.BaseType;
        }
    }

Interestingly ClassA has entityType.BaseType == null but ClrType.BaseType clearly shows ClassA inherits from DeletableEntity:

:

For ClassB entityType.BaseType is ClassA as expected:

Why first successor's parent class is being ignored? Is this by design?

PS: I'm using EF Core 2.2.

Body:
It's because there is a difference between base class and base entity.

IEntityType represents class mapped as EF Core entity. The type BaseType property of IEnityType is also IEnityType. But in your example DeletableEntity is just a base class, not a base entity, so the property returns null.

Probably the best explanation is the property declaration:

//
// Summary:
//     Gets the base type of the entity. Returns null if this is not a derived type
//     in an inheritance hierarchy.
IEntityType BaseType { get; }

where "inheritance hierarchy" refers to EF Inheritance:

Inheritance in the EF model is used to control how inheritance in the entity classes is represented in the database.

and also Inheritance (Relational Database).


问:
How to find a mathematical method to solve this big value recursion problem?
A python code with a recursion function. To calculate this is to slow by PC. So do there have a easy way to find the answer of this python code?

def rec(n):
    if n<1:
      return 1
    return rec(n//4)+rec(n//2)
print(rec(12345678987654321))
```

答:
You could look into expanding the recurrence relation, or you could simply use memoization:

```<code>def memoize(f):
    memo = {}
    def helper(x):
        if x not in memo:
            memo[x] = f(x)
        return memo[x]
    return helper

@memoize
def rec(n):
    if n<1:
      return 1
    return rec(n//4)+rec(n//2)

print(rec(12345678987654321))
</code>```

The above takes ~30ms on my computer, including the time it takes to start the Python interpreter.

The memoization speeds things up by not computing rec() for the same value of n more than once (the original version repeats the same computations over and over again, wasting a lot of CPU cycles).

Body:
You could look into expanding the recurrence relation, or you could simply use memoization:

def memoize(f):
    memo = {}
    def helper(x):
        if x not in memo:
            memo[x] = f(x)
        return memo[x]
    return helper

@memoize
def rec(n):
    if n<1:
      return 1
    return rec(n//4)+rec(n//2)

print(rec(12345678987654321))

The above takes ~30ms on my computer, including the time it takes to start the Python interpreter.

The memoization speeds things up by not computing rec() for the same value of n more than once (the original version repeats the same computations over and over again, wasting a lot of CPU cycles).


问:
Why do Berkeley sockets require byte swapping?
I understand that on the wire, most integers are in big endian format.

But why is it the burden of the application to do the byte swapping in structures like sockaddr_in and not the kernels, where all the low level work actually happens? It would make more sense if the userspace API was more platform agnostic and should not deal with this.

Why was the Berkeley socket API designed like this?

答:
The reason is probably historical.

The socket API was invented (in the 1980s) when Sun-3 (MC68030) and Sun-4 (Sparc) workstations were kings. The endianness of these (slow by today's standards) processors mattered.

I forgot the details, and probably BSD sockets conventions have been invented for some PDP-11 or VAX-780.

But why is it the burden of the application to do the byte swapping in structures like sockaddr_in and not the kernels

Probably because in the 1980s you did not want the computer (a thousand times slower than your mobile phone) to spend too much (uninterruptible) time in kernel-land.

That question should really be asked on https://retrocomputing.stackexchange.com/ (and its answer lies inside the source code of some 1980s era Unix kernel)


问:
Using an empty keystore password used to be possible?
When signing an apk after a long break from Android development I was surprised that I'm no longer able to enter an empty keystore password to unlock it. Is it just me or has this been possible before? If so, when did that change and how can I manage to unlock the keystore anyway?

Some background: maybe I'm just crazy and didn't use an empty password for the keystore before, but the one and only possible password that I could have been using instead doesn't work either (I swear, there's no chance I'd have used another password!).

答:
That works for me:

```<code>keytool -list -keystore keyStoreFileWithotPassword.jks -protected
</code>```

CORRECTION: It turn out the list feature works without entering the actual password! But the import features do require a password

ContentLicense: CC BY-SA 3.0

Body:
That works for me:

keytool -list -keystore keyStoreFileWithotPassword.jks -protected

CORRECTION: It turn out the list feature works without entering the actual password! But the import features do require a password


问:
Transform and remove brackets from json using PHP
What will be the best way to simplify this json? My function returns a json like this:

```<code>   {
    "token": {
        "0": "MJfdZLQRsu42VmUFzc9jozCa6mtJ0KJwziBEv3IXfr9RW_uhws",
        "user_id": 123,
        "username": "name"
    }
}
</code>```

My goal is to achieve this:

```<code>{
   'token': "MJfdZLQRsu42VmUFzc9jozCa6mtJ0KJwziBEv3IXfr9RW_uhws",
   'username: "name",
   'user_id': '168'
}
</code>```

This is the method that returns the json:

```<code>class MyJWTManager extends JWTManager
{
    public function create(UserInterface $user)
    {
        $payload = ['roles' => null];
        $this->addUserIdentityToPayload($user, $payload);

        $jwtCreatedEvent = new JWTCreatedEvent($payload, $user);
        $this->dispatcher->dispatch(Events::JWT_CREATED, $jwtCreatedEvent);

        $jwtString = $this->jwtEncoder->encode($jwtCreatedEvent->getData());

        $jwtEncodedEvent = new JWTEncodedEvent($jwtString);
        $this->dispatcher->dispatch(Events::JWT_ENCODED, $jwtEncodedEvent);

        return [
            $jwtString,
            'user_id' => $user->getId(),
            'username' => $user->getUsername()
        ];
        // return $jwtString // outputs "token": "ssdsmdmasdms;dm;samd;msdm;sdm;sdm"
        //return $userInfo;

    }
}
</code>```

答:
Extract the token value and return it as part of the return array </p>

```<code>class MyJWTManager extends JWTManager
{
    public function create(UserInterface $user)
    {
        $payload = ['roles' => null];
        $this->addUserIdentityToPayload($user, $payload);

        $jwtCreatedEvent = new JWTCreatedEvent($payload, $user);
        $this->dispatcher->dispatch(Events::JWT_CREATED, $jwtCreatedEvent);

        $jwtString = $this->jwtEncoder->encode($jwtCreatedEvent->getData());

        $jwtEncodedEvent = new JWTEncodedEvent($jwtString);
        $this->dispatcher->dispatch(Events::JWT_ENCODED, $jwtEncodedEvent);
        $ra=json_decode($jwtString,1);
        return [
            'token' => $ra['token'],
            'user_id' => $user->getId(),
            'username' => $user->getUsername()
        ];

    }
}
</code>```

Body:
What will be the best way to simplify this json? My function returns a json like this:

   {
    "token": {
        "0": "MJfdZLQRsu42VmUFzc9jozCa6mtJ0KJwziBEv3IXfr9RW_uhws",
        "user_id": 123,
        "username": "name"
    }
}

My goal is to achieve this:

{
   'token': "MJfdZLQRsu42VmUFzc9jozCa6mtJ0KJwziBEv3IXfr9RW_uhws",
   'username: "name",
   'user_id': '168'
}

This is the method that returns the json:

class MyJWTManager extends JWTManager
{
    public function create(UserInterface $user)
    {
        $payload = ['roles' => null];
        $this->addUserIdentityToPayload($user, $payload);

        $jwtCreatedEvent = new JWTCreatedEvent($payload, $user);
        $this->dispatcher->dispatch(Events::JWT_CREATED, $jwtCreatedEvent);

        $jwtString = $this->jwtEncoder->encode($jwtCreatedEvent->getData());

        $jwtEncodedEvent = new JWTEncodedEvent($jwtString);
        $this->dispatcher->dispatch(Events::JWT_ENCODED, $jwtEncodedEvent);

        return [
            $jwtString,
            'user_id' => $user->getId(),
            'username' => $user->getUsername()
        ];
        // return $jwtString // outputs "token": "ssdsmdmasdms;dm;samd;msdm;sdm;sdm"
        //return $userInfo;

    }
}

Body:
Extract the token value and return it as part of the return array

class MyJWTManager extends JWTManager
{
    public function create(UserInterface $user)
    {
        $payload = ['roles' => null];
        $this->addUserIdentityToPayload($user, $payload);

        $jwtCreatedEvent = new JWTCreatedEvent($payload, $user);
        $this->dispatcher->dispatch(Events::JWT_CREATED, $jwtCreatedEvent);

        $jwtString = $this->jwtEncoder->encode($jwtCreatedEvent->getData());

        $jwtEncodedEvent = new JWTEncodedEvent($jwtString);
        $this->dispatcher->dispatch(Events::JWT_ENCODED, $jwtEncodedEvent);
        $ra=json_decode($jwtString,1);
        return [
            'token' => $ra['token'],
            'user_id' => $user->getId(),
            'username' => $user->getUsername()
        ];

    }
}


问:
Using CDN vs Installing library by NPM
I recently started using NPM, but I don't understand how the files in node_modules are added to my index.html.

Case 1: CDN

For example, if I want to use jQuery via CDN, it is so simple! I add the CDN link to a

```

Case 2: NPM

Now I'm trying to use node modules and npm rather than CDNs. I have done the following:

Created package.json by using npm init --yes

Installed the jQuery package with npm install jquery --save

Now, my project folder looks like this:

I have removed the script tag with the link to the jQuery CDN from index.html, but I don't understand how to add jQuery from node_modules?

I am doing this on a browser.

答:
in addition to above, npm install packages to local also:

let your local IDE provide code intellisense and type-checking;

provide source code for (Webpack) bundling, which combines all the JavaScript files to be a (minified) single file, so no dependencies.

Title: Using CDN vs Installing library by NPM

Body:
I recently started using NPM, but I don't understand how the files in node_modules are added to my index.html.

Case 1: CDN

For example, if I want to use jQuery via CDN, it is so simple! I add the CDN link to a

Case 2: NPM

Now I'm trying to use node modules and npm rather than CDNs. I have done the following:

Created package.json by using npm init --yes

Installed the jQuery package with npm install jquery --save

Now, my project folder looks like this:

I have removed the script tag with the link to the jQuery CDN from index.html, but I don't understand how to add jQuery from node_modules?

I am doing this on a browser.


问:
Fit buttons and photos as the Game unity to the screen
I want my buttons and photos to have the same scale as game inspector . I want them to show on the mobile screen at the same size , but when I transfer the game to the phone with Xcode , it has other sizes.
enter image description here
enter image description here</p>

答:
You will see Canvas Scaler component on canvas gameobject , set its UI Scale Mode to Scale With Screen Size. With this scale mode you can specify a resolution to use as reference. And it will make UI to stretch on large screen and shrinks on smaller screens.

For more information visit : https://docs.unity3d.com/Manual/HOWTO-UIMultiResolution.html


问:
How to fix code in Android to resolve "cannot find symbol"?
I don't fix the error. How should I edit code.

Try add:

```<code>package android.graphics;

import android.graphics.AvoidXfermode;
import android.graphics.AvoidXfermode.Mode;

public ColorSwapBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int pColorKeyColorARGBPackedInt, final int pTolerance, final int pColorSwapColorARGBPackedInt, final TextureAtlasSourceDecoratorOptions pTextureAtlasSourceDecoratorOptions) {
        super(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pTextureAtlasSourceDecoratorOptions);

    this.mColorKeyColorARGBPackedInt = pColorKeyColorARGBPackedInt;
    this.mTolerance = pTolerance;
    this.mColorSwapColorARGBPackedInt = pColorSwapColorARGBPackedInt;
    this.mPaint.setXfermode(new AvoidXfermode(pColorKeyColorARGBPackedInt, pTolerance, Mode.TARGET));
    this.mPaint.setColor(pColorSwapColorARGBPackedInt);

    if (SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.JELLY_BEAN)) {
        Debug.w("The class " + ColorSwapBitmapTextureAtlasSourceDecorator.class.getSimpleName() + " is deprecated for Android API Level: '" + Build.VERSION_CODES.JELLY_BEAN + "' and higher, since the class " + AvoidXfermode.class.getSimpleName() + " is deprecated since then.");
    }
}

@Override
public ColorSwapBitmapTextureAtlasSourceDecorator deepCopy() {
    return new ColorSwapBitmapTextureAtlasSourceDecorator(this.mBitmapTextureAtlasSource, this.mBitmapTextureAtlasSourceDecoratorShape, this.mColorKeyColorARGBPackedInt, this.mTolerance, this.mColorSwapColorARGBPackedInt, this.mTextureAtlasSourceDecoratorOptions);
}
</code>```

Error:

Task :andEngine:compileDebugJavaWithJavac
  C:\Users\Admin\Desktop\New\Super\andEngine\src\main\java\org\andengine\opengl\texture\atlas\bitmap\source\decorator\ColorSwapBitmapTextureAtlasSourceDecorator.java:10: error: cannot find symbol
  import android.graphics.AvoidXfermode;
                         ^
    symbol:   class AvoidXfermode
    location: package android.graphics
  C:\Users\Admin\Desktop\New\Super\andEngine\src\main\java\org\andengine\opengl\texture\atlas\bitmap\source\decorator\ColorSwapBitmapTextureAtlasSourceDecorator.java:11: error: package android.graphics.AvoidXfermode does not exist
  import android.graphics.AvoidXfermode.Mode;
                                       ^
  C:\Users\Admin\Desktop\New\Super\andEngine\src\main\java\org\andengine\opengl\texture\atlas\bitmap\source\decorator\ColorSwapBitmapTextureAtlasSourceDecorator.java:79: error: cannot find symbol
          this.mPaint.setXfermode(new AvoidXfermode(pColorKeyColorARGBPackedInt, pTolerance, Mode.TARGET));
                                      ^
    symbol:   class AvoidXfermode
    location: class ColorSwapBitmapTextureAtlasSourceDecorator
  C:\Users\Admin\Desktop\New\Super\andEngine\src\main\java\org\andengine\opengl\texture\atlas\bitmap\source\decorator\ColorSwapBitmapTextureAtlasSourceDecorator.java:79: error: cannot find symbol
          this.mPaint.setXfermode(new AvoidXfermode(pColorKeyColorARGBPackedInt, pTolerance, Mode.TARGET));
                                                                                ^
    symbol:   variable Mode
    location: class ColorSwapBitmapTextureAtlasSourceDecorator
  C:\Users\Admin\Desktop\New\Super Max World\andEngine\src\main\java\org\andengine\opengl\texture\atlas\bitmap\source\decorator\ColorSwapBitmapTextureAtlasSourceDecorator.java:83: error: cannot find symbol
              Debug.w("The class " + ColorSwapBitmapTextureAtlasSourceDecorator.class.getSimpleName() + " is deprecated for Android API Level: '" + Build.VERSION_CODES.JELLY_BEAN + "' and higher, since the class " + AvoidXfermode.class.getSimpleName() + " is deprecated since then.");
                                                                                ^
    symbol:   class AvoidXfermode
    location: class ColorSwapBitmapTextureAtlasSourceDecorator
  Note: Some input files use or override a deprecated API.
  Note: Recompile with -Xlint:deprecation for details.
  Note: Some input files use unchecked or unsafe operations.
  Note: Recompile with -Xlint:unchecked for details.
  5 errors

答:
Modify your code, use Log for debug the code</p>

```<code>   if (SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.JELLY_BEAN)) {
    Log.d("The class " + ColorSwapBitmapTextureAtlasSourceDecorator.class.getSimpleName() + " is deprecated for Android API Level: '" + Build.VERSION_CODES.JELLY_BEAN + "' and higher, since the class " + AvoidXfermode.class.getSimpleName() + " is deprecated since then.");
}
</code>```

Body:
I don't fix the error. How should I edit code.

Try add:

package android.graphics;

import android.graphics.AvoidXfermode;
import android.graphics.AvoidXfermode.Mode;

public ColorSwapBitmapTextureAtlasSourceDecorator(final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final IBitmapTextureAtlasSourceDecoratorShape pBitmapTextureAtlasSourceDecoratorShape, final int pColorKeyColorARGBPackedInt, final int pTolerance, final int pColorSwapColorARGBPackedInt, final TextureAtlasSourceDecoratorOptions pTextureAtlasSourceDecoratorOptions) {
        super(pBitmapTextureAtlasSource, pBitmapTextureAtlasSourceDecoratorShape, pTextureAtlasSourceDecoratorOptions);

    this.mColorKeyColorARGBPackedInt = pColorKeyColorARGBPackedInt;
    this.mTolerance = pTolerance;
    this.mColorSwapColorARGBPackedInt = pColorSwapColorARGBPackedInt;
    this.mPaint.setXfermode(new AvoidXfermode(pColorKeyColorARGBPackedInt, pTolerance, Mode.TARGET));
    this.mPaint.setColor(pColorSwapColorARGBPackedInt);

    if (SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.JELLY_BEAN)) {
        Debug.w("The class " + ColorSwapBitmapTextureAtlasSourceDecorator.class.getSimpleName() + " is deprecated for Android API Level: '" + Build.VERSION_CODES.JELLY_BEAN + "' and higher, since the class " + AvoidXfermode.class.getSimpleName() + " is deprecated since then.");
    }
}

@Override
public ColorSwapBitmapTextureAtlasSourceDecorator deepCopy() {
    return new ColorSwapBitmapTextureAtlasSourceDecorator(this.mBitmapTextureAtlasSource, this.mBitmapTextureAtlasSourceDecoratorShape, this.mColorKeyColorARGBPackedInt, this.mTolerance, this.mColorSwapColorARGBPackedInt, this.mTextureAtlasSourceDecoratorOptions);
}

Error:

Task :andEngine:compileDebugJavaWithJavac
  C:\Users\Admin\Desktop\New\Super\andEngine\src\main\java\org\andengine\opengl\texture\atlas\bitmap\source\decorator\ColorSwapBitmapTextureAtlasSourceDecorator.java:10: error: cannot find symbol
  import android.graphics.AvoidXfermode;
                         ^
    symbol:   class AvoidXfermode
    location: package android.graphics
  C:\Users\Admin\Desktop\New\Super\andEngine\src\main\java\org\andengine\opengl\texture\atlas\bitmap\source\decorator\ColorSwapBitmapTextureAtlasSourceDecorator.java:11: error: package android.graphics.AvoidXfermode does not exist
  import android.graphics.AvoidXfermode.Mode;
                                       ^
  C:\Users\Admin\Desktop\New\Super\andEngine\src\main\java\org\andengine\opengl\texture\atlas\bitmap\source\decorator\ColorSwapBitmapTextureAtlasSourceDecorator.java:79: error: cannot find symbol
          this.mPaint.setXfermode(new AvoidXfermode(pColorKeyColorARGBPackedInt, pTolerance, Mode.TARGET));
                                      ^
    symbol:   class AvoidXfermode
    location: class ColorSwapBitmapTextureAtlasSourceDecorator
  C:\Users\Admin\Desktop\New\Super\andEngine\src\main\java\org\andengine\opengl\texture\atlas\bitmap\source\decorator\ColorSwapBitmapTextureAtlasSourceDecorator.java:79: error: cannot find symbol
          this.mPaint.setXfermode(new AvoidXfermode(pColorKeyColorARGBPackedInt, pTolerance, Mode.TARGET));
                                                                                ^
    symbol:   variable Mode
    location: class ColorSwapBitmapTextureAtlasSourceDecorator
  C:\Users\Admin\Desktop\New\Super Max World\andEngine\src\main\java\org\andengine\opengl\texture\atlas\bitmap\source\decorator\ColorSwapBitmapTextureAtlasSourceDecorator.java:83: error: cannot find symbol
              Debug.w("The class " + ColorSwapBitmapTextureAtlasSourceDecorator.class.getSimpleName() + " is deprecated for Android API Level: '" + Build.VERSION_CODES.JELLY_BEAN + "' and higher, since the class " + AvoidXfermode.class.getSimpleName() + " is deprecated since then.");
                                                                                ^
    symbol:   class AvoidXfermode
    location: class ColorSwapBitmapTextureAtlasSourceDecorator
  Note: Some input files use or override a deprecated API.
  Note: Recompile with -Xlint:deprecation for details.
  Note: Some input files use unchecked or unsafe operations.
  Note: Recompile with -Xlint:unchecked for details.
  5 errors

Body:
Modify your code, use Log for debug the code

   if (SystemUtils.isAndroidVersionOrHigher(Build.VERSION_CODES.JELLY_BEAN)) {
    Log.d("The class " + ColorSwapBitmapTextureAtlasSourceDecorator.class.getSimpleName() + " is deprecated for Android API Level: '" + Build.VERSION_CODES.JELLY_BEAN + "' and higher, since the class " + AvoidXfermode.class.getSimpleName() + " is deprecated since then.");
}


问:
How to add row to table dynamically on button click with Angular2?
I am working on Angular2 project and want to want to add rows to table dynamically, when a button is clicked. I know that *ngFor can be used to add rows dynamically, but I am interested if it is possible to use *ngFor only if button is clicked.

答:
A quick sample:  </p>

```<code>  <button (onClick)="sth=!sth">click</button>
       <div *ngIf="sth">
        <div *ngFor="...">
         ...
        </div>
       </div>
</code>```

Body:
A quick sample:

  <button (onClick)="sth=!sth">click</button>
       <div *ngIf="sth">
        <div *ngFor="...">
         ...
        </div>
       </div>


问:
Hibernate SessionFactory vs. JPA EntityManagerFactory
I am new to Hibernate and I'm not sure whether to use a Hibernate SessionFactory or a JPA EntityManagerFactory to create a Hibernate Session.

What is the difference between these two?  What are the pros & cons of using each of those?

答:
Prefer EntityManagerFactory and EntityManager. They are defined by the JPA standard.

SessionFactory and Session are hibernate-specific. The EntityManager invokes the hibernate session under the hood. And if you need some specific features that are not available in the EntityManager, you can obtain the session by calling:

```<code>Session session = entityManager.unwrap(Session.class);
</code>```

Body:
Prefer EntityManagerFactory and EntityManager. They are defined by the JPA standard.

SessionFactory and Session are hibernate-specific. The EntityManager invokes the hibernate session under the hood. And if you need some specific features that are not available in the EntityManager, you can obtain the session by calling:

Session session = entityManager.unwrap(Session.class);