问:
Maven build with jenkins for scala spark program : "No primary artifact to install, installing attached artifacts instead
I have a project with multiple scala spark programs, while I run mvn install through eclipse I am able to get the correct jar generated which is used with spark-submit command to run.

After pushing the code to GIT we are trying to build it using jenkins, as we want to automatically push the jar file to our hadoop cluster using ansible.
We have jenkinsfile with build goals as "compile package install -X".

The logs show that-

```<code>[DEBUG](f)artifact = com.esi.rxhome:PROJECT1:jar:0.0.1-SNAPSHOT

[DEBUG](f) attachedArtifacts = [com.esi.rxhome:PROJECT1:jar:jar-   with-dependencies:0.0.1-SNAPSHOT, com.esi.rxhome:PROJECT1:jar:jar-with-dependencies:0.0.1-SNAPSHOT]

[DEBUG]   (f) createChecksum = false

[DEBUG]   (f) localRepository =       id: local
  url: file:///home/jenkins/.m2/repository/
layout: default
snapshots: [enabled => true, update => always]
releases: [enabled => true, update => always]

[DEBUG]   (f) packaging = jar

[DEBUG]   (f) pomFile = /opt/jenkins-data/workspace/ng_datahub-pipeline_develop-JYTJLDEXV65VZWDCZAXG5Y7SHBG2534GFEF3OF2WC4543G6ANZYA/pom.xml

[DEBUG]   (s) skip = false

[DEBUG]   (f) updateReleaseInfo = false

[DEBUG] -- end configuration --

[INFO] **No primary artifact to install, installing attached artifacts instead**
</code>```

I saw the error in the similar post -

Maven: No primary artifact to install, installing attached artifacts instead

But here the answer says - Remove auto clean, I am not sure how to stop that while jenkins is building the jar file.

Below is the pom.xml-

```<code>            <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/maven-v4_0_0.xsd">
                <modelVersion>4.0.0</modelVersion>
                <groupId>com.esi.rxhome</groupId>
                <artifactId>PROJECT1</artifactId>
                <version>0.0.1-SNAPSHOT</version>
                <packaging>jar</packaging>
                <name>${project.artifactId}</name>
                <description>RxHomePreprocessing</description>
                <inceptionYear>2015</inceptionYear>
                <licenses>
                    <license>
                        <name>My License</name>
                        <url>http://....</url>
                        <distribution>repo</distribution>
                    </license>
                </licenses>

                <properties>
                    <maven.compiler.source>1.8</maven.compiler.source>
                    <maven.compiler.target>1.8</maven.compiler.target>
                    <encoding>UTF-8</encoding>
                    <scala.version>2.10.6</scala.version>
                    <scala.compat.version>2.10</scala.compat.version>
                </properties>

                <dependencies>
                    <dependency>
                        <groupId>org.scala-lang</groupId>
                        <artifactId>scala-library</artifactId>
                        <version>${scala.version}</version>
                    </dependency>

                    <!-- Test -->
                    <dependency>
                        <groupId>junit</groupId>
                        <artifactId>junit</artifactId>
                        <version>4.11</version>
                        <scope>test</scope>
                    </dependency>
                    <dependency>
                        <groupId>org.specs2</groupId>
                        <artifactId>specs2-core_${scala.compat.version}</artifactId>
                        <version>2.4.16</version>
                        <scope>test</scope>
                    </dependency>
                    <dependency>
                        <groupId>org.scalatest</groupId>
                        <artifactId>scalatest_${scala.compat.version}</artifactId>
                        <version>2.2.4</version>
                        <scope>test</scope>
                    </dependency>
                    <dependency>
                        <groupId>org.apache.hive</groupId>
                        <artifactId>hive-jdbc</artifactId>
                        <version>1.2.1000.2.6.0.3-8</version>
                    </dependency>

                    <!-- <dependency>
                <groupId>org.apache.spark</groupId>
                <artifactId>spark-core_2.10</artifactId>
                <version>2.1.0</version>
            </dependency>

                    <dependency>
                <groupId>org.apache.spark</groupId>
                <artifactId>spark-sql_2.10</artifactId>
                <version>2.1.0</version>
            </dependency> -->

                    <dependency>
                        <groupId>org.apache.spark</groupId>
                        <artifactId>spark-core_2.10</artifactId>
                        <version>1.6.3</version>
                    </dependency>
                    <dependency>
                        <groupId>org.apache.spark</groupId>
                        <artifactId>spark-sql_2.10</artifactId>
                        <version>1.6.3</version>
                    </dependency>
                    <dependency>
                        <groupId>org.apache.spark</groupId>
                        <artifactId>spark-hive_2.10</artifactId>
                        <version>1.6.3</version>
                    </dependency>

                    <dependency>
                        <groupId>com.databricks</groupId>
                        <artifactId>spark-csv_2.10</artifactId>
                        <version>1.5.0</version>
                    </dependency>

                </dependencies>

                <build>
                    <sourceDirectory>src/main/scala</sourceDirectory>
                    <testSourceDirectory>src/test/scala</testSourceDirectory>
                    <plugins>
                        <plugin>
                            <!-- see http://davidb.github.com/scala-maven-plugin -->
                            <groupId>net.alchim31.maven</groupId>
                            <artifactId>scala-maven-plugin</artifactId>
                            <version>3.2.0</version>
                            <executions>
                                <execution>
                                    <goals>
                                        <goal>compile</goal>
                                        <goal>testCompile</goal>
                                    </goals>
                                    <configuration>
                                        <args>
                                            <arg>-make:transitive</arg>
                                            <arg>-dependencyfile</arg>
                                            <arg>${project.build.directory}/.scala_dependencies</arg>
                                        </args>
                                    </configuration>
                                </execution>
                            </executions>
                        </plugin>
                        <plugin>
                            <groupId>org.apache.maven.plugins</groupId>
                            <artifactId>maven-surefire-plugin</artifactId>
                            <version>2.18.1</version>
                            <configuration>
                                <useFile>false</useFile>
                                <disableXmlReport>true</disableXmlReport>
                                <!-- If you have classpath issue like NoDefClassError,... -->
                                <!-- useManifestOnlyJar>false</useManifestOnlyJar -->
                                <includes>
                                    <include>**/*Test.*</include>
                                    <include>**/*Suite.*</include>
                                </includes>
                            </configuration>
                        </plugin>
                        <plugin>
                                            <groupId>org.apache.maven.plugins</groupId>
                                            <artifactId>maven-jar-plugin</artifactId>
                                            <version>2.4</version>
                                          <configuration>
                                                <skipIfEmpty>true</skipIfEmpty>
                                                </configuration>
                                     <executions>
                                     <execution>
                              <goals>
                              <goal>jar</goal>
                        </goals>
                        </execution>
                        </executions>
                        </plugin>

                        <plugin>
                            <groupId>org.apache.maven.plugins</groupId>
                            <artifactId>maven-assembly-plugin</artifactId>
                            <version>3.0.0</version>
                            <configuration>
                                <descriptorRefs>
                                    <descriptorRef>jar-with-dependencies</descriptorRef>
                                </descriptorRefs>
                                <archive>
                                  <manifest>
                                    <mainClass>com.esi.spark.storedprocedure.Test_jdbc_nospark</mainClass>
                                  </manifest>
                                </archive>
                            </configuration>
                            <executions>
                              <execution>
                                <id>make-assembly</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>single</goal>
                                </goals>
                              </execution>
                            </executions>
                        </plugin>

                        <plugin>
                          <artifactId>maven-clean-plugin</artifactId>
                          <version>3.0.0</version>
                          <configuration>
                            <skip>true</skip>
                          </configuration>
                        </plugin>

                    </plugins>
                </build>
            </project>
</code>```

I tried specifying

1 -" jar " for packaging in pom.xml.

2 -changing the maven goals to -

"install"

"clean install"

"compile package install"

But above tries did not help get rid of the message and jar created was of no use.

When I try to execute the spark submit command-

```<code>            spark-submit  --driver-java-options -Djava.io.tmpdir=/home/EH2524/tmp --conf spark.local.dir=/home/EH2524/tmp --driver-memory 2G --executor-memory 2G --total-executor-cores 1 --num-executors 10 --executor-cores 10 --class com.esi.spark.storedprocedure.Test_jdbc_nospark  --master yarn  /home/EH2524/PROJECT1-0.0.1-20171124.213717-1-jar-with-dependencies.jar
            Multiple versions of Spark are installed but SPARK_MAJOR_VERSION is not set
            Spark1 will be picked by default
            java.lang.ClassNotFoundException: com.esi.spark.storedprocedure.Test_jdbc_nospark
                    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
                    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
                    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
                    at java.lang.Class.forName0(Native Method)
                    at java.lang.Class.forName(Class.java:348)
                    at org.apache.spark.util.Utils$.classForName(Utils.scala:175)
                    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:703)
                    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:181)
                    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:206)
                    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:121)
                    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
</code>```

Here, Test_jdbc_nospark is a scala object.

答:
This message was because of the maven-jar-plugin having the  as true. Once i removed this, the build is not giving the message "No primary artifact to install, installing attached artifacts instead"

The empty jar was getting created because of incorrect  path in pom.xml

Intitally-

```<code>    <build>
      <sourceDirectory>src/main/scala</sourceDirectory>
</code>```

As jenkins was building through code in git and the pom was inside the project folder.

```<code><build>
    <sourceDirectory>folder_name_in_git/src/main/scala</sourceDirectory>
</code>```

Body:
I have a project with multiple scala spark programs, while I run mvn install through eclipse I am able to get the correct jar generated which is used with spark-submit command to run.

After pushing the code to GIT we are trying to build it using jenkins, as we want to automatically push the jar file to our hadoop cluster using ansible.
We have jenkinsfile with build goals as "compile package install -X".

The logs show that-

[DEBUG](f)artifact = com.esi.rxhome:PROJECT1:jar:0.0.1-SNAPSHOT

[DEBUG](f) attachedArtifacts = [com.esi.rxhome:PROJECT1:jar:jar-   with-dependencies:0.0.1-SNAPSHOT, com.esi.rxhome:PROJECT1:jar:jar-with-dependencies:0.0.1-SNAPSHOT]

[DEBUG]   (f) createChecksum = false

[DEBUG]   (f) localRepository =       id: local
  url: file:///home/jenkins/.m2/repository/
layout: default
snapshots: [enabled => true, update => always]
releases: [enabled => true, update => always]

[DEBUG]   (f) packaging = jar

[DEBUG]   (f) pomFile = /opt/jenkins-data/workspace/ng_datahub-pipeline_develop-JYTJLDEXV65VZWDCZAXG5Y7SHBG2534GFEF3OF2WC4543G6ANZYA/pom.xml

[DEBUG]   (s) skip = false

[DEBUG]   (f) updateReleaseInfo = false

[DEBUG] -- end configuration --

[INFO] **No primary artifact to install, installing attached artifacts instead**

I saw the error in the similar post -

Maven: No primary artifact to install, installing attached artifacts instead

But here the answer says - Remove auto clean, I am not sure how to stop that while jenkins is building the jar file.

Below is the pom.xml-

            <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/maven-v4_0_0.xsd">
                <modelVersion>4.0.0</modelVersion>
                <groupId>com.esi.rxhome</groupId>
                <artifactId>PROJECT1</artifactId>
                <version>0.0.1-SNAPSHOT</version>
                <packaging>jar</packaging>
                <name>${project.artifactId}</name>
                <description>RxHomePreprocessing</description>
                <inceptionYear>2015</inceptionYear>
                <licenses>
                    <license>
                        <name>My License</name>
                        <url>http://....</url>
                        <distribution>repo</distribution>
                    </license>
                </licenses>

                <properties>
                    <maven.compiler.source>1.8</maven.compiler.source>
                    <maven.compiler.target>1.8</maven.compiler.target>
                    <encoding>UTF-8</encoding>
                    <scala.version>2.10.6</scala.version>
                    <scala.compat.version>2.10</scala.compat.version>
                </properties>

                <dependencies>
                    <dependency>
                        <groupId>org.scala-lang</groupId>
                        <artifactId>scala-library</artifactId>
                        <version>${scala.version}</version>
                    </dependency>

                    <dependency>
                        <groupId>junit</groupId>
                        <artifactId>junit</artifactId>
                        <version>4.11</version>
                        <scope>test</scope>
                    </dependency>
                    <dependency>
                        <groupId>org.specs2</groupId>
                        <artifactId>specs2-core_${scala.compat.version}</artifactId>
                        <version>2.4.16</version>
                        <scope>test</scope>
                    </dependency>
                    <dependency>
                        <groupId>org.scalatest</groupId>
                        <artifactId>scalatest_${scala.compat.version}</artifactId>
                        <version>2.2.4</version>
                        <scope>test</scope>
                    </dependency>
                    <dependency>
                        <groupId>org.apache.hive</groupId>
                        <artifactId>hive-jdbc</artifactId>
                        <version>1.2.1000.2.6.0.3-8</version>
                    </dependency>

                    <dependency>
                        <groupId>org.apache.spark</groupId>
                        <artifactId>spark-core_2.10</artifactId>
                        <version>1.6.3</version>
                    </dependency>
                    <dependency>
                        <groupId>org.apache.spark</groupId>
                        <artifactId>spark-sql_2.10</artifactId>
                        <version>1.6.3</version>
                    </dependency>
                    <dependency>
                        <groupId>org.apache.spark</groupId>
                        <artifactId>spark-hive_2.10</artifactId>
                        <version>1.6.3</version>
                    </dependency>

                    <dependency>
                        <groupId>com.databricks</groupId>
                        <artifactId>spark-csv_2.10</artifactId>
                        <version>1.5.0</version>
                    </dependency>

                </dependencies>

                <build>
                    <sourceDirectory>src/main/scala</sourceDirectory>
                    <testSourceDirectory>src/test/scala</testSourceDirectory>
                    <plugins>
                        <plugin>

                            <groupId>net.alchim31.maven</groupId>
                            <artifactId>scala-maven-plugin</artifactId>
                            <version>3.2.0</version>
                            <executions>
                                <execution>
                                    <goals>
                                        <goal>compile</goal>
                                        <goal>testCompile</goal>
                                    </goals>
                                    <configuration>
                                        <args>
                                            <arg>-make:transitive</arg>
                                            <arg>-dependencyfile</arg>
                                            <arg>${project.build.directory}/.scala_dependencies</arg>
                                        </args>
                                    </configuration>
                                </execution>
                            </executions>
                        </plugin>
                        <plugin>
                            <groupId>org.apache.maven.plugins</groupId>
                            <artifactId>maven-surefire-plugin</artifactId>
                            <version>2.18.1</version>
                            <configuration>
                                <useFile>false</useFile>
                                <disableXmlReport>true</disableXmlReport>

                                <includes>
                                    <include>**/*Test.*</include>
                                    <include>**/*Suite.*</include>
                                </includes>
                            </configuration>
                        </plugin>
                        <plugin>
                                            <groupId>org.apache.maven.plugins</groupId>
                                            <artifactId>maven-jar-plugin</artifactId>
                                            <version>2.4</version>
                                          <configuration>
                                                <skipIfEmpty>true</skipIfEmpty>
                                                </configuration>
                                     <executions>
                                     <execution>
                              <goals>
                              <goal>jar</goal>
                        </goals>
                        </execution>
                        </executions>
                        </plugin>

                        <plugin>
                            <groupId>org.apache.maven.plugins</groupId>
                            <artifactId>maven-assembly-plugin</artifactId>
                            <version>3.0.0</version>
                            <configuration>
                                <descriptorRefs>
                                    <descriptorRef>jar-with-dependencies</descriptorRef>
                                </descriptorRefs>
                                <archive>
                                  <manifest>
                                    <mainClass>com.esi.spark.storedprocedure.Test_jdbc_nospark</mainClass>
                                  </manifest>
                                </archive>
                            </configuration>
                            <executions>
                              <execution>
                                <id>make-assembly</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>single</goal>
                                </goals>
                              </execution>
                            </executions>
                        </plugin>

                        <plugin>
                          <artifactId>maven-clean-plugin</artifactId>
                          <version>3.0.0</version>
                          <configuration>
                            <skip>true</skip>
                          </configuration>
                        </plugin>

                    </plugins>
                </build>
            </project>

I tried specifying

1 -" jar " for packaging in pom.xml.

2 -changing the maven goals to -

"install"

"clean install"

"compile package install"

But above tries did not help get rid of the message and jar created was of no use.

When I try to execute the spark submit command-

            spark-submit  --driver-java-options -Djava.io.tmpdir=/home/EH2524/tmp --conf spark.local.dir=/home/EH2524/tmp --driver-memory 2G --executor-memory 2G --total-executor-cores 1 --num-executors 10 --executor-cores 10 --class com.esi.spark.storedprocedure.Test_jdbc_nospark  --master yarn  /home/EH2524/PROJECT1-0.0.1-20171124.213717-1-jar-with-dependencies.jar
            Multiple versions of Spark are installed but SPARK_MAJOR_VERSION is not set
            Spark1 will be picked by default
            java.lang.ClassNotFoundException: com.esi.spark.storedprocedure.Test_jdbc_nospark
                    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
                    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
                    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
                    at java.lang.Class.forName0(Native Method)
                    at java.lang.Class.forName(Class.java:348)
                    at org.apache.spark.util.Utils$.classForName(Utils.scala:175)
                    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:703)
                    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:181)
                    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:206)
                    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:121)
                    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

Here, Test_jdbc_nospark is a scala object.

Body:
This message was because of the maven-jar-plugin having the  as true. Once i removed this, the build is not giving the message "No primary artifact to install, installing attached artifacts instead"

The empty jar was getting created because of incorrect  path in pom.xml

Intitally-

    <build>
      <sourceDirectory>src/main/scala</sourceDirectory>

As jenkins was building through code in git and the pom was inside the project folder.

<build>
    <sourceDirectory>folder_name_in_git/src/main/scala</sourceDirectory>


来源: stackexchange

问:
Understanding Windows Phone 7 Development. (.net, c#, silverlight, xna) how do they interact together?
I come from a web development background and am looking into writing applications for the Windows Phone 7 device and am trying to get a better understanding of how things work.

From my online research (and please correct me if i'm wrong in the questions i ask below), this is what I understand so far:

.NET Framework - is a controlled environment that allows you to write in many different types of programming languages like C#

C# is best for wp7 development?

Visual Studio 2010 is best for writing code for the .NET framework?

Are there other programs like Visual Studio 2010 that allow you to write for .NET framework?

C# is the pre-written code in Visual Studio 2010?

Silverlight and XNA - are "libraries" that are made to help you with the development of applications and games.

C# is used to manipulate these libraries into doing what you want them to?

IS Silverlight & XNA libraries embedded in C# similar to how jQuery is embedded in HTML? Do I have the right idea on this or am I completely wrong?

Silverlight is a library that needs to be included into your application in order to run  (a file named silverlight.js perhaps?)

What is the programming language behind silverlight, java? I read somwhere that java is also used in wp7 development? how does java come into play with wp7?

Silverlight is best used for applications and XNA is best used for games.

And the best software write all of these apps in is Visual Studio 2010???  I downloaded the Windows Phone 7 Tools and it installed about 12 things on my computer... I've been watching a few beginner tutorial videos on developing for the wp7, but as you can see I still have some "core" things i need to understand before i proceed.

Any help you guys provide will be gladly appreciated!

答:
C# is the first language available for WP7 development. Being the first, the documentation and msot samples on the net are done with C#, so that can help. There is also VB now. This will likely be a matter of preference for people. There are a couple of limitations to VB's support at the moment (lacking Blend and XNA support).

You will be using VS2010 for WP7 development. It's the only tool supporting Windows Phone 7 development at present and the Express version comes free with the WP7 tools.

I'm not sure what you mean about pre-written code.

The Silverlight and XNA frameworks are effectively libraries that you can utilise with your chosen language. C# for example.

Java doesn't really come into play.

Here is a good post that covers Silverlight and XNA considerations including some discussion on when to use which. It is somewhat like you say, but it's not a firm rule.

XNA for Silverlight developers: Part 0 - Why should I care?

There are also some questions here where people have given their thoughts on this question.

I recommend also watching some of the introductory videos online from Mix 2010 or Tech Ed 2010 NA for getting some more of the fundamentals cleary understood.

ContentLicense: CC BY-SA 2.5


问:
Toggle link HREF
I have a menu panel that is displayed via pure css - using #nav - its controlled by a simple button

```<code><a id="nav-burger" href="#nav">
     <span></span>
     <span></span>
     <span></span>
     <span></span>
</a>
</code>```

I'd like to toggle the href on click to display #home - can anyone advise how to do this?

I am using this format but my syntax is a bit messed up and there must be an easier way!

```<code>$(document).ready(function(){
  $('#nav-burger').click(function(){
    $(this).toggleClass('open');
     $(this).attr('href',$(this).attr('href') == '#nav' ? '#nav' : '#home');
  });
});
</code>```

Thanks

UPDATE
As a demo - In the code snippet below - whenever the link gos red the href should have the value of #home and visa versa fro blue (#nav)

$(document).ready(function(){
  $('#nav-burger').click(function() {
  $(this).toggleClass('open').attr('href', function(_, currHref) {
    return currHref === '#nav' ? '#home' : '#nav';
  });
});
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a{color:blue}
a.open{color:red}</code>```

          hello

      ```

答:
You can use attr(attributeName, function) and chain the methods

```<code>$('#nav-burger').click(function() {
  $(this).toggleClass('open').attr('href', function(_, currHref) {
    return currHref === '#nav' ? '#home' : '#nav';
  });
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Toggle link HREF

Body:
I have a menu panel that is displayed via pure css - using #nav - its controlled by a simple button

I'd like to toggle the href on click to display #home - can anyone advise how to do this?

I am using this format but my syntax is a bit messed up and there must be an easier way!

$(document).ready(function(){
  $('#nav-burger').click(function(){
    $(this).toggleClass('open');
     $(this).attr('href',$(this).attr('href') == '#nav' ? '#nav' : '#home');
  });
});

Thanks

UPDATE
As a demo - In the code snippet below - whenever the link gos red the href should have the value of #home and visa versa fro blue (#nav)

$(document).ready(function(){
  $('#nav-burger').click(function() {
  $(this).toggleClass('open').attr('href', function(_, currHref) {
    return currHref === '#nav' ? '#home' : '#nav';
  });
});
});

a{color:blue}
a.open{color:red}

          hello

Body:
You can use attr(attributeName, function) and chain the methods

$('#nav-burger').click(function() {
  $(this).toggleClass('open').attr('href', function(_, currHref) {
    return currHref === '#nav' ? '#home' : '#nav';
  });
});


问:
Dynamic height for UITableViewCell not working correctly
I'm having some height problems with my dynamic UITableViewCell (sew picture below). Some cells have the correct height and some not, and when I drag the tableView some of the cells become correct and some don't.

I'm using this code to get the cell's height to be dynamic and reloading it in viewDidAppear and viewDidLoad.

```<code>tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = tableView.rowHeight
</code>```

As mentioned the cells are sometimes correct and sometimes not. Is there another way to do it or am I doing something wrong? I have tried many different solutions, all mentioned here as well as other suggestions both here at StackOverflow and other sites.

I appreciate all help!

Edit!

TableView

```<code>extension ChatVC: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return groupMessages.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "groupFeedCell", for: indexPath) as? GroupFeedCell else { return UITableViewCell() }

        let message = groupMessages[indexPath.row]

            DataService.instance.getUsername(forUID: message.senderId, handler: { (name) in
                cell.configureCell(name: name, content: message.content)
            })

        cell.layoutSubviews()
        cell.layoutIfNeeded()

        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        return UITableViewAutomaticDimension
    }

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 66
    }
}
</code>```

Cell

```<code>@IBOutlet weak var nameLbl: UILabel!
@IBOutlet weak var contentLbl: UILabel!

func configureCell(name: String, content: String) {
    self.nameLbl.text = name //email
    self.contentLbl.text = content
}
</code>```

答:
For dynamic tableViewCell

1- Setup this 2 lines with an inital value for the row height to help autolayout drawing it (take it from current cell height in the nib file)

```<code>tableView.rowHeight = UITableViewAutomaticDimension;
tableView.estimatedRowHeight = number;
</code>```

2- don't implement this function heightForRowAtIndexPath . or implement it and return this

```<code>return UITableViewDynamicHeight;
</code>```

3- make sure all constraints in the cell nib file or in storyboard are hooked correctly from top to bottom.

4- in cellForRowAtIndexPath before the line retrun cell insert that

```<code>[cell layoutSubviews];
[cell layoutIfneeded];
</code>```

5- Test in simulator some versions like ios 8 it's a bug also in the viewController call

```<code>[tableView LayouSubviews];
</code>```

in viewdidLayoutSubViews function to re relayout again correctly

6- Make lines property of any UILabel that you want to wrap = 0 and hook it's leading and trailing constarints to superView

Body:
I'm having some height problems with my dynamic UITableViewCell (sew picture below). Some cells have the correct height and some not, and when I drag the tableView some of the cells become correct and some don't.

I'm using this code to get the cell's height to be dynamic and reloading it in viewDidAppear and viewDidLoad.

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = tableView.rowHeight

As mentioned the cells are sometimes correct and sometimes not. Is there another way to do it or am I doing something wrong? I have tried many different solutions, all mentioned here as well as other suggestions both here at StackOverflow and other sites.

I appreciate all help!

Edit!

TableView

extension ChatVC: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return groupMessages.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "groupFeedCell", for: indexPath) as? GroupFeedCell else { return UITableViewCell() }

        let message = groupMessages[indexPath.row]

            DataService.instance.getUsername(forUID: message.senderId, handler: { (name) in
                cell.configureCell(name: name, content: message.content)
            })

        cell.layoutSubviews()
        cell.layoutIfNeeded()

        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        return UITableViewAutomaticDimension
    }

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 66
    }
}

Cell

@IBOutlet weak var nameLbl: UILabel!
@IBOutlet weak var contentLbl: UILabel!

func configureCell(name: String, content: String) {
    self.nameLbl.text = name //email
    self.contentLbl.text = content
}

Body:
For dynamic tableViewCell

1- Setup this 2 lines with an inital value for the row height to help autolayout drawing it (take it from current cell height in the nib file)

tableView.rowHeight = UITableViewAutomaticDimension;
tableView.estimatedRowHeight = number;

2- don't implement this function heightForRowAtIndexPath . or implement it and return this

return UITableViewDynamicHeight;

3- make sure all constraints in the cell nib file or in storyboard are hooked correctly from top to bottom.

4- in cellForRowAtIndexPath before the line retrun cell insert that

[cell layoutSubviews];
[cell layoutIfneeded];

5- Test in simulator some versions like ios 8 it's a bug also in the viewController call

[tableView LayouSubviews];

in viewdidLayoutSubViews function to re relayout again correctly

6- Make lines property of any UILabel that you want to wrap = 0 and hook it's leading and trailing constarints to superView


问:
Spring boot - How to log 500 response body to console
I've created a filter for spring (using spring boot v1.5) which is triggered on every request using OncePerRequestFilter as follows:

```<code>@Component
class LogRequestFilter extends OncePerRequestFilter {

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

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(request);
        ContentCachingResponseWrapper wrappedResponse = new ContentCachingResponseWrapper(response);

        int responseStatus = wrappedResponse.getStatusCode();

        if (responseStatus == 500) {
            String requestUri = wrappedRequest.getRequestURI();
            byte[] responseBodyBytes = wrappedResponse.getContentAsByteArray();
            logger.error("{}, {}, {}", responseStatus, requestUri, new String(responseBodyBytes));
        }

        filterChain.doFilter(wrappedRequest, response);
    }
}
</code>```

My problem it that I need to log the response body when an error occurs. However I get no data from getContentAsByteArray() even though the user receives the following response from spring:

```<code>{
    "timestamp": 1512745726835,
    "status": 500,
    "error": "Internal Server Error",
    "exception": "java.lang.NullPointerException",
    "message": "No message available",
    "path": "/documents/2017-02-17"
}
</code>```

While debugging I can see that the request URI is correct, but response body is missing. How can I fix this problem?

答:
Move your doFilter method call before you read the content of wrappedResponse.
At the very end call wrappedResponse.copyBodyToResponse().

Body:
I've created a filter for spring (using spring boot v1.5) which is triggered on every request using OncePerRequestFilter as follows:

@Component
class LogRequestFilter extends OncePerRequestFilter {

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

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(request);
        ContentCachingResponseWrapper wrappedResponse = new ContentCachingResponseWrapper(response);

        int responseStatus = wrappedResponse.getStatusCode();

        if (responseStatus == 500) {
            String requestUri = wrappedRequest.getRequestURI();
            byte[] responseBodyBytes = wrappedResponse.getContentAsByteArray();
            logger.error("{}, {}, {}", responseStatus, requestUri, new String(responseBodyBytes));
        }

        filterChain.doFilter(wrappedRequest, response);
    }
}

My problem it that I need to log the response body when an error occurs. However I get no data from getContentAsByteArray() even though the user receives the following response from spring:

{
    "timestamp": 1512745726835,
    "status": 500,
    "error": "Internal Server Error",
    "exception": "java.lang.NullPointerException",
    "message": "No message available",
    "path": "/documents/2017-02-17"
}

While debugging I can see that the request URI is correct, but response body is missing. How can I fix this problem?


问:
Use custom font to the Canvas text
In my code I can introduce text to the canvas and I can also change the color and the location. I tried to put a custom font for the text input but it's not working(it remains the standard one which I think is Arial). Can you please help me with this one? This is my JsFiddle code: https://jsfiddle.net/x6dqox1t/  .Thank you for your time.

Here is my CSS code:

```<code>#canvas3 {
 border: 2px dotted black;
 border-radius: 5px;
 position: absolute;
}

#canvas4 {
 border: 2px dotted black;
 border-radius: 5px;
 position: absolute;
}

.green {
 border: 0.1px solid #CCC;
 margin: 1px;
 zoom: 3;
 vertical-align: middle;
 display: inline-block;
 cursor: pointer;
 overflow: hidden;
 width: 22.5px;
 height: 20px;
 background-color: #009933;
}

.green:hover,
.green:active,
.green:focus {
  border: 1px solid black;
  box-shadow: 1px 1px 2px rgba(255, 255, 255, 0.2);
  opacity: 0.7;
  text-decoration: none;
  text-shadow: -1px -1px 0 #136a65;
  -webkit-transition: all 250ms linear;
  transition: all 250ms linear;
 }

 .red {
   border: 0.1px solid #CCC;
   margin: 1px;
   zoom: 3;
   vertical-align: middle;
   display: inline-block;
   cursor: pointer;
   overflow: hidden;
   width: 22.5px;
   height: 20px;
   background-color: #ff0000;
  }

  .red:hover,
  .red:active,
  .red:focus {
   border: 1px solid black;
   box-shadow: 1px 1px 2px rgba(255, 255, 255, 0.2);
   opacity: 0.7;
   text-decoration: none;
   text-shadow: -1px -1px 0 #136a65;
   -webkit-transition: all 250ms linear;
   transition: all 250ms linear;
  }

 .orange {
  border: 0.1px solid #CCC;
  margin: 1px;
  zoom: 3;
  vertical-align: middle;
  display: inline-block;
  cursor: pointer;
  overflow: hidden;
  width: 22.5px;
  height: 20px;
  background-color: orange;
 }

 .orange:hover,
 .orange:active,
 .orange:focus {
   border: 1px solid black;
   box-shadow: 1px 1px 2px rgba(255, 255, 255, 0.2);
   opacity: 0.7;
   text-decoration: none;
   text-shadow: -1px -1px 0 #136a65;
   -webkit-transition: all 250ms linear;
   transition: all 250ms linear;
   }

  @font-face {
   font-family: 'KulminoituvaRegular';
   src: url('http://www.miketaylr.com/f/kulminoituva.ttf');
  }
</code>```

Here is my JAVASCRIPT code:

```<code> var canvas3 = document.getElementById("canvas3");
    var ctx3 = canvas3.getContext("2d");

    ctx3.font = " bold 90px KulminoituvaRegular";
    ctx3.fillStyle = "black";
    ctx3.textAlign = "center";

    var $text3 = document.getElementById("sourceText3");

    $text3.onkeyup = function(e) {
      redrawTextsCan3();
    }

    function redrawTextsCan3() {
      ctx3.clearRect(0, 0, canvas3.width, canvas3.height);
      wrapText(ctx3, $text3.value, 66.5, 82, "KulminoituvaRegular");
    }

    function wrapText(context, text, x, y, maxWidth, fontSize, fontFace) {
      var words = text.split(' ');
      var line = '';
      var lineHeight = fontSize;

      context.font = fontSize + " " + fontFace;

      for (var n = 0; n < words.length; n++) {
        var testLine = line + words[n] + ' ';
        var metrics = context.measureText(testLine);
        var testWidth = metrics.width;
        if (testWidth > maxWidth) {
          context.fillText(line, x, y);
          line = words[n] + ' ';
          y += lineHeight;
        } else {
          line = testLine;
        }
      }
      context.fillText(line, x, y);
      return (y);
    }

    var loc = document.getElementById("canvas3");
    var ctxx = loc.getContext("2d");

    function path3(v2) {
      switch (v2) {
        // top: 103px; left: 210px
        case "rightabove":
          loc.style.top = "93px";
          loc.style.left = "130px";
          loc.style.position = "absolute";
          break;

        case "rightbelow":
          loc.style.top = "133px";
          loc.style.left = "130px";
          loc.style.position = "absolute";
          break;

        case "left":
          loc.style.top = "113px";
          loc.style.left = "400px";
          loc.style.position = "absolute";
          break;

        case "center":
          loc.style.top = "113px";
          loc.style.left = "173px";
          loc.style.position = "absolute";
          break;
      }
      redrawTextsCan3();
    }

    function color3(v4) {
      v4 = v4.dataset.id;
      switch (v4) {
        // top: 103px; left: 210px

        case "black":
          ctx3.fillStyle = '#000000';
          break;

        case "red":
          ctx3.fillStyle = "#ff0000";
          break;

        case "green":
          ctx3.fillStyle = "#009933";
          break;

        case "orange":
          ctx3.fillStyle = "#ff9900";
          break;
      }
      redrawTextsCan3();
    }
</code>```

Here is HTML code:

```<code><div>
 <select name="change1" onchange="path3(this.value)">
   <option value="left">Left</option>
   <option value="center" selected>Center</option>
   <option value="rightabove">Right Above</option>
   <option value="rightbelow">Right Below</option>
 </select>

 <h3 style="font-size: 15px;padding-top: 0px">Choose Colour</h3>

 <button type="button" class="black" data-id="black" onclick="color3(this)">
 </button>
 <button type="button" class="red" data-id="red" onclick="color3(this)">
 </button>
 <button type="button" class="green" data-id="green" onclick="color3(this)">
 </button>
 <button type="button" class="orange" data-id="orange" onclick="color3(this)"></button>

 <h3 style="font-size: 15px;padding-top: 0px">Number</h3>

 <input id="sourceText3" maxlength="1" type="text" style="height: 32px;width: 223px;">

 <canvas id="canvas3" width="150" height="150" style="position: absolute; top: 113px; left: 400px; z-index: 10;"></canvas>

 </div>
</code>```

答:
The reason your font isn't working is because the font source (http://www.miketaylr.com/f/kulminoituva.ttf) is loaded over http, while the jsfiddle is loaded over https. So you get a Mixed Content Error.

I've uploaded that font to GitHub, then used RawGit to generate a source link.

 var canvas3 = document.getElementById("canvas3");
        var ctx3 = canvas3.getContext("2d");

        ctx3.font = "90px MyFont";
        ctx3.fillStyle = "black";
        ctx3.textAlign = "center";

        var $text3 = document.getElementById("sourceText3");

        $text3.onkeyup = function(e) {
          redrawTextsCan3();
        }

        function redrawTextsCan3() {
          ctx3.clearRect(0, 0, canvas3.width, canvas3.height);
          wrapText(ctx3, $text3.value, 66.5, 82, "MyFont");
        }

        function wrapText(context, text, x, y, maxWidth, fontSize, fontFace) {
          var words = text.split(' ');
          var line = '';
          var lineHeight = fontSize;

          context.font = fontSize + " " + fontFace;

          for (var n = 0; n < words.length; n++) {
            var testLine = line + words[n] + ' ';
            var metrics = context.measureText(testLine);
            var testWidth = metrics.width;
            if (testWidth > maxWidth) {
              context.fillText(line, x, y);
              line = words[n] + ' ';
              y += lineHeight;
            } else {
              line = testLine;
            }
          }
          context.fillText(line, x, y);
          return (y);
        }

        var loc = document.getElementById("canvas3");
        var ctxx = loc.getContext("2d");

        function path3(v2) {
          switch (v2) {
            // top: 103px; left: 210px
            case "rightabove":
              loc.style.top = "93px";
              loc.style.left = "130px";
              loc.style.position = "absolute";
              break;

            case "rightbelow":
              loc.style.top = "133px";
              loc.style.left = "130px";
              loc.style.position = "absolute";
              break;

            case "left":
              loc.style.top = "113px";
              loc.style.left = "400px";
              loc.style.position = "absolute";
              break;

            case "center":
              loc.style.top = "113px";
              loc.style.left = "173px";
              loc.style.position = "absolute";
              break;
          }
          redrawTextsCan3();
        }

        function color3(v4) {
          v4 = v4.dataset.id;
          switch (v4) {
            // top: 103px; left: 210px

            case "black":
              ctx3.fillStyle = '#000000';
              break;

            case "red":
              ctx3.fillStyle = "#ff0000";
              break;

            case "green":
              ctx3.fillStyle = "#009933";
              break;

            case "orange":
              ctx3.fillStyle = "#ff9900";
              break;
          }
          redrawTextsCan3();
        }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>   #canvas3 {
   border: 2px dotted black;
   border-radius: 5px;
   position: absolute;
 }

 #canvas4 {
   border: 2px dotted black;
   border-radius: 5px;
   position: absolute;
 }

 .green {
   border: 0.1px solid #CCC;
   margin: 1px;
   zoom: 3;
   vertical-align: middle;
   display: inline-block;
   cursor: pointer;
   overflow: hidden;
   width: 22.5px;
   height: 20px;
   background-color: #009933;
 }

 .green:hover,
 .green:active,
 .green:focus {
   border: 1px solid black;
   box-shadow: 1px 1px 2px rgba(255, 255, 255, 0.2);
   opacity: 0.7;
   text-decoration: none;
   text-shadow: -1px -1px 0 #136a65;
   -webkit-transition: all 250ms linear;
   transition: all 250ms linear;
 }

 .red {
   border: 0.1px solid #CCC;
   margin: 1px;
   zoom: 3;
   vertical-align: middle;
   display: inline-block;
   cursor: pointer;
   overflow: hidden;
   width: 22.5px;
   height: 20px;
   background-color: #ff0000;
 }

 .red:hover,
 .red:active,
 .red:focus {
   border: 1px solid black;
   box-shadow: 1px 1px 2px rgba(255, 255, 255, 0.2);
   opacity: 0.7;
   text-decoration: none;
   text-shadow: -1px -1px 0 #136a65;
   -webkit-transition: all 250ms linear;
   transition: all 250ms linear;
 }

 .black {
   border: 0.1px solid #CCC;
   margin: 1px;
   zoom: 3;
   vertical-align: middle;
   display: inline-block;
   cursor: pointer;
   overflow: hidden;
   width: 22.5px;
   height: 20px;
   background-color: black;
 }

 .black:hover,
 .black:active,
 .black:focus {
   border: 1px solid black;
   box-shadow: 1px 1px 2px rgba(255, 255, 255, 0.2);
   opacity: 0.7;
   text-decoration: none;
   text-shadow: -1px -1px 0 #136a65;
   -webkit-transition: all 250ms linear;
   transition: all 250ms linear;
 }

 .orange {
   border: 0.1px solid #CCC;
   margin: 1px;
   zoom: 3;
   vertical-align: middle;
   display: inline-block;
   cursor: pointer;
   overflow: hidden;
   width: 22.5px;
   height: 20px;
   background-color: orange;
 }

 .orange:hover,
 .orange:active,
 .orange:focus {
   border: 1px solid black;
   box-shadow: 1px 1px 2px rgba(255, 255, 255, 0.2);
   opacity: 0.7;
   text-decoration: none;
   text-shadow: -1px -1px 0 #136a65;
   -webkit-transition: all 250ms linear;
   transition: all 250ms linear;
 }

 @font-face {
    font-family: 'MyFont';
    src: url('https://cdn.rawgit.com/BlazingFire007/Misc/d656d2e6/kulminoituva.ttf');
}</code>```

  <select name="change1" onchange="path3(this.value)">
    <option value="left">Left</option>
    <option value="center" selected>Center</option>
    <option value="rightabove">Right Above</option>
    <option value="rightbelow">Right Below</option>
  </select>

Choose Colour

  <button type="button" class="black" data-id="black" onclick="color3(this)"></button>
  <button type="button" class="red" data-id="red" onclick="color3(this)"></button>
  <button type="button" class="green" data-id="green" onclick="color3(this)"></button>
  <button type="button" class="orange" data-id="orange" onclick="color3(this)"></button>

Number

  <input id="sourceText3" maxlength="2" type="text" style="height: 32px;width: 223px;">

  <canvas id="canvas3" width="150" height="150" style="position: absolute; top: 113px; left: 400px; z-index: 10;"></canvas>

```

Title: Use custom font to the Canvas text

Body:
In my code I can introduce text to the canvas and I can also change the color and the location. I tried to put a custom font for the text input but it's not working(it remains the standard one which I think is Arial). Can you please help me with this one? This is my JsFiddle code: https://jsfiddle.net/x6dqox1t/  .Thank you for your time.

Here is my CSS code:

#canvas3 {
 border: 2px dotted black;
 border-radius: 5px;
 position: absolute;
}

#canvas4 {
 border: 2px dotted black;
 border-radius: 5px;
 position: absolute;
}

.green {
 border: 0.1px solid #CCC;
 margin: 1px;
 zoom: 3;
 vertical-align: middle;
 display: inline-block;
 cursor: pointer;
 overflow: hidden;
 width: 22.5px;
 height: 20px;
 background-color: #009933;
}

.green:hover,
.green:active,
.green:focus {
  border: 1px solid black;
  box-shadow: 1px 1px 2px rgba(255, 255, 255, 0.2);
  opacity: 0.7;
  text-decoration: none;
  text-shadow: -1px -1px 0 #136a65;
  -webkit-transition: all 250ms linear;
  transition: all 250ms linear;
 }

 .red {
   border: 0.1px solid #CCC;
   margin: 1px;
   zoom: 3;
   vertical-align: middle;
   display: inline-block;
   cursor: pointer;
   overflow: hidden;
   width: 22.5px;
   height: 20px;
   background-color: #ff0000;
  }

  .red:hover,
  .red:active,
  .red:focus {
   border: 1px solid black;
   box-shadow: 1px 1px 2px rgba(255, 255, 255, 0.2);
   opacity: 0.7;
   text-decoration: none;
   text-shadow: -1px -1px 0 #136a65;
   -webkit-transition: all 250ms linear;
   transition: all 250ms linear;
  }

 .orange {
  border: 0.1px solid #CCC;
  margin: 1px;
  zoom: 3;
  vertical-align: middle;
  display: inline-block;
  cursor: pointer;
  overflow: hidden;
  width: 22.5px;
  height: 20px;
  background-color: orange;
 }

 .orange:hover,
 .orange:active,
 .orange:focus {
   border: 1px solid black;
   box-shadow: 1px 1px 2px rgba(255, 255, 255, 0.2);
   opacity: 0.7;
   text-decoration: none;
   text-shadow: -1px -1px 0 #136a65;
   -webkit-transition: all 250ms linear;
   transition: all 250ms linear;
   }

  @font-face {
   font-family: 'KulminoituvaRegular';
   src: url('http://www.miketaylr.com/f/kulminoituva.ttf');
  }

Here is my JAVASCRIPT code:

 var canvas3 = document.getElementById("canvas3");
    var ctx3 = canvas3.getContext("2d");

    ctx3.font = " bold 90px KulminoituvaRegular";
    ctx3.fillStyle = "black";
    ctx3.textAlign = "center";

    var $text3 = document.getElementById("sourceText3");

    $text3.onkeyup = function(e) {
      redrawTextsCan3();
    }

    function redrawTextsCan3() {
      ctx3.clearRect(0, 0, canvas3.width, canvas3.height);
      wrapText(ctx3, $text3.value, 66.5, 82, "KulminoituvaRegular");
    }

    function wrapText(context, text, x, y, maxWidth, fontSize, fontFace) {
      var words = text.split(' ');
      var line = '';
      var lineHeight = fontSize;

      context.font = fontSize + " " + fontFace;

      for (var n = 0; n < words.length; n++) {
        var testLine = line + words[n] + ' ';
        var metrics = context.measureText(testLine);
        var testWidth = metrics.width;
        if (testWidth > maxWidth) {
          context.fillText(line, x, y);
          line = words[n] + ' ';
          y += lineHeight;
        } else {
          line = testLine;
        }
      }
      context.fillText(line, x, y);
      return (y);
    }

    var loc = document.getElementById("canvas3");
    var ctxx = loc.getContext("2d");

    function path3(v2) {
      switch (v2) {
        // top: 103px; left: 210px
        case "rightabove":
          loc.style.top = "93px";
          loc.style.left = "130px";
          loc.style.position = "absolute";
          break;

        case "rightbelow":
          loc.style.top = "133px";
          loc.style.left = "130px";
          loc.style.position = "absolute";
          break;

        case "left":
          loc.style.top = "113px";
          loc.style.left = "400px";
          loc.style.position = "absolute";
          break;

        case "center":
          loc.style.top = "113px";
          loc.style.left = "173px";
          loc.style.position = "absolute";
          break;
      }
      redrawTextsCan3();
    }

    function color3(v4) {
      v4 = v4.dataset.id;
      switch (v4) {
        // top: 103px; left: 210px

        case "black":
          ctx3.fillStyle = '#000000';
          break;

        case "red":
          ctx3.fillStyle = "#ff0000";
          break;

        case "green":
          ctx3.fillStyle = "#009933";
          break;

        case "orange":
          ctx3.fillStyle = "#ff9900";
          break;
      }
      redrawTextsCan3();
    }

Here is HTML code:

 <select name="change1" onchange="path3(this.value)">
   <option value="left">Left</option>
   <option value="center" selected>Center</option>
   <option value="rightabove">Right Above</option>
   <option value="rightbelow">Right Below</option>
 </select>

Choose Colour

 <button type="button" class="black" data-id="black" onclick="color3(this)">
 </button>
 <button type="button" class="red" data-id="red" onclick="color3(this)">
 </button>
 <button type="button" class="green" data-id="green" onclick="color3(this)">
 </button>
 <button type="button" class="orange" data-id="orange" onclick="color3(this)"></button>

Number

 <input id="sourceText3" maxlength="1" type="text" style="height: 32px;width: 223px;">

 <canvas id="canvas3" width="150" height="150" style="position: absolute; top: 113px; left: 400px; z-index: 10;"></canvas>

Body:
The reason your font isn't working is because the font source (http://www.miketaylr.com/f/kulminoituva.ttf) is loaded over http, while the jsfiddle is loaded over https. So you get a Mixed Content Error.

I've uploaded that font to GitHub, then used RawGit to generate a source link.

 var canvas3 = document.getElementById("canvas3");
        var ctx3 = canvas3.getContext("2d");

        ctx3.font = "90px MyFont";
        ctx3.fillStyle = "black";
        ctx3.textAlign = "center";

        var $text3 = document.getElementById("sourceText3");

        $text3.onkeyup = function(e) {
          redrawTextsCan3();
        }

        function redrawTextsCan3() {
          ctx3.clearRect(0, 0, canvas3.width, canvas3.height);
          wrapText(ctx3, $text3.value, 66.5, 82, "MyFont");
        }

        function wrapText(context, text, x, y, maxWidth, fontSize, fontFace) {
          var words = text.split(' ');
          var line = '';
          var lineHeight = fontSize;

          context.font = fontSize + " " + fontFace;

          for (var n = 0; n < words.length; n++) {
            var testLine = line + words[n] + ' ';
            var metrics = context.measureText(testLine);
            var testWidth = metrics.width;
            if (testWidth > maxWidth) {
              context.fillText(line, x, y);
              line = words[n] + ' ';
              y += lineHeight;
            } else {
              line = testLine;
            }
          }
          context.fillText(line, x, y);
          return (y);
        }

        var loc = document.getElementById("canvas3");
        var ctxx = loc.getContext("2d");

        function path3(v2) {
          switch (v2) {
            // top: 103px; left: 210px
            case "rightabove":
              loc.style.top = "93px";
              loc.style.left = "130px";
              loc.style.position = "absolute";
              break;

            case "rightbelow":
              loc.style.top = "133px";
              loc.style.left = "130px";
              loc.style.position = "absolute";
              break;

            case "left":
              loc.style.top = "113px";
              loc.style.left = "400px";
              loc.style.position = "absolute";
              break;

            case "center":
              loc.style.top = "113px";
              loc.style.left = "173px";
              loc.style.position = "absolute";
              break;
          }
          redrawTextsCan3();
        }

        function color3(v4) {
          v4 = v4.dataset.id;
          switch (v4) {
            // top: 103px; left: 210px

            case "black":
              ctx3.fillStyle = '#000000';
              break;

            case "red":
              ctx3.fillStyle = "#ff0000";
              break;

            case "green":
              ctx3.fillStyle = "#009933";
              break;

            case "orange":
              ctx3.fillStyle = "#ff9900";
              break;
          }
          redrawTextsCan3();
        }

   #canvas3 {
   border: 2px dotted black;
   border-radius: 5px;
   position: absolute;
 }

 #canvas4 {
   border: 2px dotted black;
   border-radius: 5px;
   position: absolute;
 }

 .green {
   border: 0.1px solid #CCC;
   margin: 1px;
   zoom: 3;
   vertical-align: middle;
   display: inline-block;
   cursor: pointer;
   overflow: hidden;
   width: 22.5px;
   height: 20px;
   background-color: #009933;
 }

 .green:hover,
 .green:active,
 .green:focus {
   border: 1px solid black;
   box-shadow: 1px 1px 2px rgba(255, 255, 255, 0.2);
   opacity: 0.7;
   text-decoration: none;
   text-shadow: -1px -1px 0 #136a65;
   -webkit-transition: all 250ms linear;
   transition: all 250ms linear;
 }

 .red {
   border: 0.1px solid #CCC;
   margin: 1px;
   zoom: 3;
   vertical-align: middle;
   display: inline-block;
   cursor: pointer;
   overflow: hidden;
   width: 22.5px;
   height: 20px;
   background-color: #ff0000;
 }

 .red:hover,
 .red:active,
 .red:focus {
   border: 1px solid black;
   box-shadow: 1px 1px 2px rgba(255, 255, 255, 0.2);
   opacity: 0.7;
   text-decoration: none;
   text-shadow: -1px -1px 0 #136a65;
   -webkit-transition: all 250ms linear;
   transition: all 250ms linear;
 }

 .black {
   border: 0.1px solid #CCC;
   margin: 1px;
   zoom: 3;
   vertical-align: middle;
   display: inline-block;
   cursor: pointer;
   overflow: hidden;
   width: 22.5px;
   height: 20px;
   background-color: black;
 }

 .black:hover,
 .black:active,
 .black:focus {
   border: 1px solid black;
   box-shadow: 1px 1px 2px rgba(255, 255, 255, 0.2);
   opacity: 0.7;
   text-decoration: none;
   text-shadow: -1px -1px 0 #136a65;
   -webkit-transition: all 250ms linear;
   transition: all 250ms linear;
 }

 .orange {
   border: 0.1px solid #CCC;
   margin: 1px;
   zoom: 3;
   vertical-align: middle;
   display: inline-block;
   cursor: pointer;
   overflow: hidden;
   width: 22.5px;
   height: 20px;
   background-color: orange;
 }

 .orange:hover,
 .orange:active,
 .orange:focus {
   border: 1px solid black;
   box-shadow: 1px 1px 2px rgba(255, 255, 255, 0.2);
   opacity: 0.7;
   text-decoration: none;
   text-shadow: -1px -1px 0 #136a65;
   -webkit-transition: all 250ms linear;
   transition: all 250ms linear;
 }

 @font-face {
    font-family: 'MyFont';
    src: url('https://cdn.rawgit.com/BlazingFire007/Misc/d656d2e6/kulminoituva.ttf');
}

<div>
  <select name="change1" onchange="path3(this.value)">
    <option value="left">Left</option>
    <option value="center" selected>Center</option>
    <option value="rightabove">Right Above</option>
    <option value="rightbelow">Right Below</option>
  </select>

  <h3 style="font-size: 15px;padding-top: 0px">Choose Colour</h3>

  <button type="button" class="black" data-id="black" onclick="color3(this)"></button>
  <button type="button" class="red" data-id="red" onclick="color3(this)"></button>
  <button type="button" class="green" data-id="green" onclick="color3(this)"></button>
  <button type="button" class="orange" data-id="orange" onclick="color3(this)"></button>

  <h3 style="font-size: 15px;padding-top: 0px">Number</h3>

  <input id="sourceText3" maxlength="2" type="text" style="height: 32px;width: 223px;">

  <canvas id="canvas3" width="150" height="150" style="position: absolute; top: 113px; left: 400px; z-index: 10;"></canvas>

</div>


问:
how to get values of JSON object only among multiple values to display instead of displaying all stateandref details in api method corda
am trying to display only JSON object values among multiple values in StateandRef using @GET @Produces api method.but can't to retrieve particular value from that. please help me out.</p>

答:
Here's an example with IOUStates. We map each IOUState in the vault to an instance of a simple data class, which we then return as JSON.

The IOUStateData dataclass

```<code>data class IOUStateData(
    val value: Int,
    val lender: Party,
    val borrower: Party
)
</code>```

The endpoint

```<code>@GET
@Path("ious")
@Produces(MediaType.APPLICATION_JSON)
fun getIOUs(): Map<String, List<IOUStateData>> {
    // Extract the IOUState StateAndRefs from the vault.
    val iouStateAndRefs = rpcOps.vaultQueryBy<IOUState>().states

    // Map each StateAndRef to its IOUState.
    val iouStates = iouStateAndRefs.map { it.state.data }

    // Map each IOUState to a data class that will be returned as JSON.
    val iouStateDatas = iouStates.map { iouState ->
        IOUStateData(iouState.value, iouState.lender, iouState.borrower)
    }

    return mapOf("iouStates" to iouStateDatas)
}
</code>```

Body:
Here's an example with IOUStates. We map each IOUState in the vault to an instance of a simple data class, which we then return as JSON.

The IOUStateData dataclass

data class IOUStateData(
    val value: Int,
    val lender: Party,
    val borrower: Party
)

The endpoint

@GET
@Path("ious")
@Produces(MediaType.APPLICATION_JSON)
fun getIOUs(): Map<String, List<IOUStateData>> {
    // Extract the IOUState StateAndRefs from the vault.
    val iouStateAndRefs = rpcOps.vaultQueryBy<IOUState>().states

    // Map each StateAndRef to its IOUState.
    val iouStates = iouStateAndRefs.map { it.state.data }

    // Map each IOUState to a data class that will be returned as JSON.
    val iouStateDatas = iouStates.map { iouState ->
        IOUStateData(iouState.value, iouState.lender, iouState.borrower)
    }

    return mapOf("iouStates" to iouStateDatas)
}


问:
How can I search iframe content (text) using an input field that is on the parent page?
Yes, I know something like this has been asked over here before and I have searched but the one that is closest to what I'm trying to achieve doesn't have an answer ( Search iframe content with jquery and input element on parent page ) and the one that does is making use of nested iframes ( Access the content of a nested Iframe ) and I didn't quite understand the solution (VERY new with javascript so please bear with me). Honestly, it's getting a bit frustrating (it's quite late over here) so I thought I might as well ask.

I have an iframe that displays a page from my site therefore the page is from the same domain. What I would like to do is to search the iframe for some text using javascript (not jquery). The search input box, however, is on the parent page.

I've done something similar to this before by putting the search input box in the page displayed in the iframe instead ( I followed this tutorial: http://help.dottoro.com/ljkjvqqo.php ) but now I need to have the search input box on the parent page because I going to make it "sticky" so that it will follow the user as they scroll down the page. I've resized the parent page height to be the same as the length of the page in the iframe by also using javascript.

So, my question is: How can I use javascript to search text that is in the iframe by using a search input box that is on the parent page?

My HTML so far:

```<code>        <input type="text" name="page_no" size="3"/>
        <input type="submit" name="goto" value="Go"/>

<iframe id='iframe2' src="http://example.com/files/<?php echo $filename;?>" frameborder="0" style="text-align:center; margin:0; width:100%; height:150px; border:none; overflow:hidden;" scrolling="yes" onload="AdjustIframeHeightOnLoad()"></iframe>
        <script type="text/javascript">
function AdjustIframeHeightOnLoad() {    document.getElementById("iframe2").style.height = document.getElementById("iframe2").contentWindow.document.body.scrollHeight + "px"; }
function AdjustIframeHeight(i) { document.getElementById("iframe2").style.height = parseInt(i) + "px"; }
</code>```

Not sure how to move on from there. I'd really appreciate some help.

Thanks in advance!

EDIT:
The search works now (saw that I put the javascript above the html so I put it under it to get it working) so this is what I want to do with the search results:

I intend to use the search box to enter a page number such that when the user clicks "Go" the search will look for that page and scroll the user down to where the result (that is, the page number) is.

EDIT 2:  I just thought I'd mention that my page numbers are written like this: -2- for page 2, -3- for page 3, etc.

答:
function myFunction(x) {
  var att = document.querySelector("iframe[id=iframe2]").getAttribute(x);

  alert(att);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" name="page_no" size="3"/>
<input type="submit" name="goto" onclick="myFunction(document.querySelector('input[name=page_no]').value)" value="Go"/>

<hr />

<iframe id='iframe2' src="https://www.example.com" frameborder="0" style="text-align:center; margin:0; width:100%; height:150px; border:none; overflow:hidden;" scrolling="yes" ></iframe></code>```

Body:
Yes, I know something like this has been asked over here before and I have searched but the one that is closest to what I'm trying to achieve doesn't have an answer ( Search iframe content with jquery and input element on parent page ) and the one that does is making use of nested iframes ( Access the content of a nested Iframe ) and I didn't quite understand the solution (VERY new with javascript so please bear with me). Honestly, it's getting a bit frustrating (it's quite late over here) so I thought I might as well ask.

I have an iframe that displays a page from my site therefore the page is from the same domain. What I would like to do is to search the iframe for some text using javascript (not jquery). The search input box, however, is on the parent page.

I've done something similar to this before by putting the search input box in the page displayed in the iframe instead ( I followed this tutorial: http://help.dottoro.com/ljkjvqqo.php ) but now I need to have the search input box on the parent page because I going to make it "sticky" so that it will follow the user as they scroll down the page. I've resized the parent page height to be the same as the length of the page in the iframe by also using javascript.

So, my question is: How can I use javascript to search text that is in the iframe by using a search input box that is on the parent page?

My HTML so far:

        <input type="text" name="page_no" size="3"/>
        <input type="submit" name="goto" value="Go"/>

<iframe id='iframe2' src="http://example.com/files/<?php echo $filename;?>" frameborder="0" style="text-align:center; margin:0; width:100%; height:150px; border:none; overflow:hidden;" scrolling="yes" onload="AdjustIframeHeightOnLoad()">

Body:
function myFunction(x) {
  var att = document.querySelector("iframe[id=iframe2]").getAttribute(x);

  alert(att);
}

<input type="text" name="page_no" size="3"/>
<input type="submit" name="goto" onclick="myFunction(document.querySelector('input[name=page_no]').value)" value="Go"/>

<hr />

<iframe id='iframe2' src="https://www.example.com" frameborder="0" style="text-align:center; margin:0; width:100%; height:150px; border:none; overflow:hidden;" scrolling="yes" ></iframe>


问:
PHP search text file line by line for two strings then output line
I am trying to search a text file for two values on a line. If both values are present I need to output the entire line. The values I am searching for may not be next to each other which is where I am getting stuck. I have the following code which works well but only for one search value:

```<code><?php
$search = $_REQUEST["search"];
// Read from file
$lines = file('archive.txt');
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false)
echo"<html><title>SEARCH RESULTS FOR: $search</title><font face='Arial'> $line <hr>";
}

?>
</code>```

Any assistance much appreciated. Many thanks in advance.

答:
This worked for me. You may define what you like in searchthis aray and it will be displayed with whole line.</p>

```<code><?php
$searchthis = array('1','2','3');
$matches = array();

$handle = fopen("file_path", "r");
if ($handle)
{
while (!feof($handle))
{
    $buffer = fgets($handle);

    foreach ($searchthis as $param) {
    if(strpos($buffer, $param) !== FALSE)
        $matches[] = $buffer;
 }}
 fclose($handle);
 }

 foreach ($matches as $parts) {
echo $parts;
}
?>
</code>```

Body:
I am trying to search a text file for two values on a line. If both values are present I need to output the entire line. The values I am searching for may not be next to each other which is where I am getting stuck. I have the following code which works well but only for one search value:

<?php
$search = $_REQUEST["search"];
// Read from file
$lines = file('archive.txt');
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false)
echo"<title>SEARCH RESULTS FOR: $search</title> $line
";
}

?>

Any assistance much appreciated. Many thanks in advance.

Body:
This worked for me. You may define what you like in searchthis aray and it will be displayed with whole line.

<?php
$searchthis = array('1','2','3');
$matches = array();

$handle = fopen("file_path", "r");
if ($handle)
{
while (!feof($handle))
{
    $buffer = fgets($handle);

    foreach ($searchthis as $param) {
    if(strpos($buffer, $param) !== FALSE)
        $matches[] = $buffer;
 }}
 fclose($handle);
 }

 foreach ($matches as $parts) {
echo $parts;
}
?>


问:
Any papers on bitmask-widening?
I'm in need of a bitmask that can grow beyond the 64 bits that can be atomically manipulated by Java.

The "obvious" candidates (both of which require the introduction of some kind of locking scheme) are:

re-allocation as consecutive area of a fixed size

a fractured bitmask formed by chained words ("thread-safe BitSet")

Are there any papers on this matter? (Don't have to be Java-specific.)

答:
From your clarifications, it seems like what you really need is papers on ways to write "atomic" operations in Java.

For what you want to do I can't think of a way to avoid using locks. After all, even just writing to a long or double is not atomic without synchronization.

Here are some links related to what you want to do:

https://www.ibm.com/developerworks/library/j-jtp11234/index.html

"Atomically" update an entire array

You should determine what locking mechanism to use based on your expected use cases of this data structure.

https://blog.takipi.com/java-8-stampedlocks-vs-readwritelocks-and-synchronized/

Also, some people might complain about premature optimization but I also like to consider the efficiency of code before it's an issue. However using synchronization/locks in this case probably isn't as bad as you might think.

If you want lower level then I would resort to JNI.

However, no matter how low-level you go, I think using locks/synchronization  would still be unavoidable since there's no guarantee the hardware would have instructions that could do what you want atomically. How would a CPU perform an or operation across multiple words atomically?

As a side note, if you are going to be using these bitmasks a lot and want the most performance, then it might possibly maybe be worth writing this code for a GPU. Though I'm not fully sure of the pros and cons, those would be left for further research...

I think you're looking for a level of efficiency that hardware simply cannot provide right now.

Title: Any papers on bitmask-widening?


问:
Media query to detect if device is touchscreen
What is the safest way, using media queries, to make something happen when not on a touchscreen device? If there is no way, do you suggest using a JavaScript solution such as !window.Touch or Modernizr?

答:
adding a class touchscreen to the body using JS or jQuery</p>

```<code>  //allowing mobile only css
    var isMobile = ('ontouchstart' in document.documentElement && navigator.userAgent.match(/Mobi/));
    if(isMobile){
        jQuery("body").attr("class",'touchscreen');
    }
</code>```

Body:
adding a class touchscreen to the body using JS or jQuery

  //allowing mobile only css
    var isMobile = ('ontouchstart' in document.documentElement && navigator.userAgent.match(/Mobi/));
    if(isMobile){
        jQuery("body").attr("class",'touchscreen');
    }


问:
Use php array as parameter for Postgres IN clause
I am trying to bind a PHP array as argument for a SQL stmt. I am using auraSQL extended PDO so it looks like this:

```<code>$php_array = ['first', 'second', 'third']
$db->fetchColumn("SELECT * FROM my_table WHERE column IN (:php_array), ['php_array' => $php_array])"
</code>```

Is there a way to do that? I cannot find out how. I tried to append the $php_array as string separated with commas and wrapped in quotes but that doesn't work.

EDIT: Solution was to use AuraSql function quote like so:

```<code> $db->fetchColumn("SELECT * FROM my_table WHERE column IN (".$db->quote($php_array).")";
</code>```

答:
Take a look at the Aura.Sql documentation for quote(), here:  https://github.com/auraphp/Aura.Sql/blob/3.x/docs/getting-started.md#array-quoting

The SQL IN clause requires a comma-delimited list of values.  The Aura.Sql quote() method appears to generate that for you.

You should consider using perform method.

https://github.com/auraphp/Aura.Sql/blob/3.x/docs/getting-started.md#the-perform-method

Body:
I am trying to bind a PHP array as argument for a SQL stmt. I am using auraSQL extended PDO so it looks like this:

$php_array = ['first', 'second', 'third']
$db->fetchColumn("SELECT * FROM my_table WHERE column IN (:php_array), ['php_array' => $php_array])"

Is there a way to do that? I cannot find out how. I tried to append the $php_array as string separated with commas and wrapped in quotes but that doesn't work.

EDIT: Solution was to use AuraSql function quote like so:

 $db->fetchColumn("SELECT * FROM my_table WHERE column IN (".$db->quote($php_array).")";


问:
quick question about HTML5 article and figure element
I have a section where there is a image of a site and a paragraph thats referencing to that site. I am wondering what would be the correct way, in your opinion how I should wrap these 2 HTML objects.

I have originally thought this would just work(ignore .img-wrap and the h2):

```<code><section class="featured">
    <h1> Featured Project </h1>
    <div class="img-wrap">
        <img src="" height="" width="" alt="Name of Site">
        <h2> Title </h2>
    </div><!-- .img-wrap -->
    <p>
        <a href="#">Lorem ipsum</a> dolor sit amet, consectetur adipisicing
        elit, seddo eiusmod tempor incididunt ut labore et dolore magna aliqua.
        Ut enim ad minim veniam, quis nostrud exercitation ullamco
    </p>
</section><!-- .featured -->
</code>```

But what if my client adds multiple paragraphs? It will be styled with a background color and margin so it wouldn't look right.

Wouldn't figure and figcaption be appropriate? I can't really tell when I read on it on HTML5Doctor.

```<code><section class="featured">
    <h1> Featured Project </h1>
    <figure>
        <div class="img-wrap">
            <img src="" height="" width="" alt="Name of Site">
            <h2> Title </h2>
        </div><!-- .img-wrap -->
        <figcaption>
            <p>
                <a href="#">Lorem ipsum</a> dolor sit amet, consectetur adipisicing
                elit, seddo eiusmod tempor incididunt ut labore et dolore magna aliqua.
                Ut enim ad minim veniam, quis nostrud exercitation ullamco
            </p>
        </figcaption>
    </figure>
</section><!-- .featured -->
</code>```

Or maybe just wrap the paragraph?

答:
It's hard to say what the best practice here would be since you haven't given us enough context. I doubt that what you're showing us here really is a good candidate for a
, since it seems more like the bulk of an article, especially with that
 thrown in there.

As far as using that
 around paragraphs of content, well, that's not really what it's intended for. Think about a newspaper or magazine article with an image or two to spice it up. The image isn't described in the body of the content, but the image content is related to the article. The captions on the image are brief descriptions of what the image is showing, usually to clarify who or what you're looking at.

For your situation, something like the following might be most appropriate:

```<code><article id="featured">
  <h1>Featured Project</h1>
  <figure>
    <img src="image.jpg" alt="A brief caption about the image.">
    <figcaption>A brief caption about the image.</figcaption>
  </figure>

  <p>
    Lorem ipsum, your articlus can goeth here.
  </p>
</article>
</code>```

There's no need for you to wrap the entire article inside of a
 wrapped inside a
, just to show an image. You don't have to use
 at all, and if you do, a
 is quite possibly unnecessary. Don't get caught up with trying to use HTML5 elements just for the sake of using them. If you don't think there's a compelling reason to use them, your time is probably better spent just getting things built and iterating over them later to make semantic improvements to the markup.

Body:
I have a section where there is a image of a site and a paragraph thats referencing to that site. I am wondering what would be the correct way, in your opinion how I should wrap these 2 HTML objects.

I have originally thought this would just work(ignore .img-wrap and the h2):

 Featured Project

 Title

        Lorem ipsum dolor sit amet, consectetur adipisicing
        elit, seddo eiusmod tempor incididunt ut labore et dolore magna aliqua.
        Ut enim ad minim veniam, quis nostrud exercitation ullamco

But what if my client adds multiple paragraphs? It will be styled with a background color and margin so it wouldn't look right.

Wouldn't figure and figcaption be appropriate? I can't really tell when I read on it on HTML5Doctor.

 Featured Project

 Title

                Lorem ipsum dolor sit amet, consectetur adipisicing
                elit, seddo eiusmod tempor incididunt ut labore et dolore magna aliqua.
                Ut enim ad minim veniam, quis nostrud exercitation ullamco

Or maybe just wrap the paragraph?

Body:
It's hard to say what the best practice here would be since you haven't given us enough context. I doubt that what you're showing us here really is a good candidate for a <section>, since it seems more like the bulk of an article, especially with that <h1> thrown in there.

As far as using that <figcaption> around paragraphs of content, well, that's not really what it's intended for. Think about a newspaper or magazine article with an image or two to spice it up. The image isn't described in the body of the content, but the image content is related to the article. The captions on the image are brief descriptions of what the image is showing, usually to clarify who or what you're looking at.

For your situation, something like the following might be most appropriate:

<article id="featured">
  <h1>Featured Project</h1>
  <figure>
    <img src="image.jpg" alt="A brief caption about the image.">
    <figcaption>A brief caption about the image.</figcaption>
  </figure>

  <p>
    Lorem ipsum, your articlus can goeth here.
  </p>
</article>

There's no need for you to wrap the entire article inside of a <figcaption> wrapped inside a <figure>, just to show an image. You don't have to use <figure> at all, and if you do, a <figcaption> is quite possibly unnecessary. Don't get caught up with trying to use HTML5 elements just for the sake of using them. If you don't think there's a compelling reason to use them, your time is probably better spent just getting things built and iterating over them later to make semantic improvements to the markup.


问:
Routing Params URL not working when navigated from component
I've two component MovieListComponent and MovieDetailComponent.

When I click on the View Detail button from MovieListComponent it should take me to MovieDetailComponent with the params printed on the Screen.

The issue here is, this URL http://localhost:4200/movie-detail/1 is working fine if I enter directly.  Same URL if I hit from MovieListComponent is not working.

Not sure what I'm doing wrong here. Please help

MovieListComponent

export class MovieListComponent implements OnInit {
  movies = JSON.parse(localStorage.getItem('movies'));
  constructor(private movieService: MovieService, private router: Router) {
    this.movieService.getMovies();
  }
  onSelect(movie) {
    this.router.navigate(['/movie-detail', movie.id])
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="card" *ngFor="let movie of movies">
  <img alt="Thumbnail [100%x280]" style="height: 280px; width: 100%; display: block;" src="{{movie.image}}">
  <h2 class="card-text">{{movie.title}}</h2>
  View Details
</div></code>```

MovieDetailComponent.html

export class MovieDetailComponent implements OnInit {
  id: number;
  constructor(private router: ActivatedRoute, private movieService: MovieService) {}
  ngOnInit() {
    this.router.params.subscribe((params) => {
      this.id = params['id'];
    })
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>{{ id }}</code>```

AppRouting

const routes: Routes = [{
    path: '',
    component: MovieListComponent,
  },
  {
    path: 'admin',
    component: MovieControlComponent,
  },
  {
    path: 'movie-list',
    component: MovieListComponent,
  }, {
    path: 'movie-detail/:id',
    component: MovieDetailComponent,
  }
];```
</div>
</div>
</p>

<p><strong>MovieService.ts</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>@Injectable()
export class MovieService {

  constructor(private http: Http) {
    //this.http.get('../movies.json').map(response => response.json());
  }
  getMovies() {
    return this.http.get('data/movies.json')
      .map(response => response.json())
      .subscribe(result => localStorage.setItem("movies", JSON.stringify(result)));
  }
}</code>```

答:
problem is this.id = params['id'];   you've set your id to number id: number; but params is string. To convert it to number add + before params like this:

this.id = +params['id'];

(+) converts id string into number

Body:
I've two component MovieListComponent and MovieDetailComponent.

When I click on the View Detail button from MovieListComponent it should take me to MovieDetailComponent with the params printed on the Screen.

The issue here is, this URL http://localhost:4200/movie-detail/1 is working fine if I enter directly.  Same URL if I hit from MovieListComponent is not working.

Not sure what I'm doing wrong here. Please help

MovieListComponent

export class MovieListComponent implements OnInit {
  movies = JSON.parse(localStorage.getItem('movies'));
  constructor(private movieService: MovieService, private router: Router) {
    this.movieService.getMovies();
  }
  onSelect(movie) {
    this.router.navigate(['/movie-detail', movie.id])
  }
}

{{movie.title}}

  View Details

MovieDetailComponent.html

export class MovieDetailComponent implements OnInit {
  id: number;
  constructor(private router: ActivatedRoute, private movieService: MovieService) {}
  ngOnInit() {
    this.router.params.subscribe((params) => {
      this.id = params['id'];
    })
  }
}

{{ id }}

AppRouting

const routes: Routes = [{
    path: '',
    component: MovieListComponent,
  },
  {
    path: 'admin',
    component: MovieControlComponent,
  },
  {
    path: 'movie-list',
    component: MovieListComponent,
  }, {
    path: 'movie-detail/:id',
    component: MovieDetailComponent,
  }
];

MovieService.ts

@Injectable()
export class MovieService {

  constructor(private http: Http) {
    //this.http.get('../movies.json').map(response => response.json());
  }
  getMovies() {
    return this.http.get('data/movies.json')
      .map(response => response.json())
      .subscribe(result => localStorage.setItem("movies", JSON.stringify(result)));
  }
}


问:
Querying two tables with different columns but one and with no relation between
I have two tables, internal_mail and external_mail, they relatively have different columns. I'm trying to select all records from both tables with ordering by a date column, called date_of_arrival in both tables.

For example this is internal_mail:

```<code>colunm 1          colunm 2          colunm 3          date_of_arrival
some_record       some_record       some_record       2017/8/12
.....             .....             .....             .....
.....             .....             .....             .....
.....             .....             .....             .....
.....             .....             .....             .....
</code>```

And this is external_mail:

```<code>colunm A          colunm B          colunm C          date_of_arrival
another_record    another_record    another_record       2017/7/12
.....             .....             .....             .....
.....             .....             .....             .....
.....             .....             .....             .....
.....             .....             .....             .....
</code>```

What I'm trying to achieve here is something like this(in case of a descending order by):

```<code>colunm 1  colunm 2  colunm 3  column A  column B  column C   date_of_arrival
s_r       s_r       s_r       empty     empty     empty      2017/8/12
empty     empty     empty     a_r       a_r       a_r        2017/7/12
s_r       s_r       s_r       empty     empty     empty      2017/8/12
empty     empty     empty     a_r       a_r       a_r        2017/7/12
</code>```

答:
The first part is an easy UNION query, but you said you want to unify the rows if both tables have data for a given date. That would be achieved by FULL OUTER JOIN on the date, but MySQL doesn't support FULL OUTER JOIN.

So here's an example (untested) of a workaround:

```<code>SELECT
  MAX(column1) AS column1,
  MAX(column2) AS column2,
  MAX(column3) AS column3,
  MAX(columnA) AS columnA,
  MAX(columnB) AS columnB,
  MAX(columnC) AS columnC,
  date_of_arrival
FROM (
    (SELECT column1, column2, column3,
       NULL AS columnA, NULL AS columnB, NULL AS columnC,
       date_of_arrival
     FROM internal_mail)
    UNION ALL
    (SELECT NULL, NULL, NULL, columnA, columnB, columnC,
       date_of_arrival
     FROM external_mail)
) AS t
GROUP BY date_of_arrival;
</code>```

The GROUP BY is to combine rows with the same date into one row, even if both unioned tables have a row with the same date.

But we want this combined row to have the non-null values in each column. In a group of two rows for a given date, one row will have a non-null value, and the other row will have a null value. MAX() ignores the null, and takes the single other value. MIN() would have worked just as well, because it's choosing from a set of exactly 1 row, but I arbitrarily chose to use MAX().

Body:
I have two tables, internal_mail and external_mail, they relatively have different columns. I'm trying to select all records from both tables with ordering by a date column, called date_of_arrival in both tables.

For example this is internal_mail:

colunm 1          colunm 2          colunm 3          date_of_arrival
some_record       some_record       some_record       2017/8/12
.....             .....             .....             .....
.....             .....             .....             .....
.....             .....             .....             .....
.....             .....             .....             .....

And this is external_mail:

colunm A          colunm B          colunm C          date_of_arrival
another_record    another_record    another_record       2017/7/12
.....             .....             .....             .....
.....             .....             .....             .....
.....             .....             .....             .....
.....             .....             .....             .....

What I'm trying to achieve here is something like this(in case of a descending order by):

colunm 1  colunm 2  colunm 3  column A  column B  column C   date_of_arrival
s_r       s_r       s_r       empty     empty     empty      2017/8/12
empty     empty     empty     a_r       a_r       a_r        2017/7/12
s_r       s_r       s_r       empty     empty     empty      2017/8/12
empty     empty     empty     a_r       a_r       a_r        2017/7/12

Body:
The first part is an easy UNION query, but you said you want to unify the rows if both tables have data for a given date. That would be achieved by FULL OUTER JOIN on the date, but MySQL doesn't support FULL OUTER JOIN.

So here's an example (untested) of a workaround:

SELECT
  MAX(column1) AS column1,
  MAX(column2) AS column2,
  MAX(column3) AS column3,
  MAX(columnA) AS columnA,
  MAX(columnB) AS columnB,
  MAX(columnC) AS columnC,
  date_of_arrival
FROM (
    (SELECT column1, column2, column3,
       NULL AS columnA, NULL AS columnB, NULL AS columnC,
       date_of_arrival
     FROM internal_mail)
    UNION ALL
    (SELECT NULL, NULL, NULL, columnA, columnB, columnC,
       date_of_arrival
     FROM external_mail)
) AS t
GROUP BY date_of_arrival;

The GROUP BY is to combine rows with the same date into one row, even if both unioned tables have a row with the same date.

But we want this combined row to have the non-null values in each column. In a group of two rows for a given date, one row will have a non-null value, and the other row will have a null value. MAX() ignores the null, and takes the single other value. MIN() would have worked just as well, because it's choosing from a set of exactly 1 row, but I arbitrarily chose to use MAX().


答:
This can be done with full join. As MySQL doesn't support it, union all is your best option. Assuming you have to show the records on one row when the date matches in both the tables, you have to aggregate by date_of_arrival. If that isn't the case, leave out the aggregation and just use the inner query.

```<code>select max(column_1),max(column_2),max(column_3),max(columnA),max(columnB),max(columnC),date_of_arrival
from (select column_1,column_2,column_3,
      null as columnA,null as columnB,null as columnC,date_of_arrival
      from internal_email
      union all
      select null,null,null,columnA,columnB,columnC,date_of_arrival
      from external_email
     ) t
group by date_of_arrival
</code>```

Title: Querying two tables with different columns but one and with no relation between

Body:
This can be done with full join. As MySQL doesn't support it, union all is your best option. Assuming you have to show the records on one row when the date matches in both the tables, you have to aggregate by date_of_arrival. If that isn't the case, leave out the aggregation and just use the inner query.

select max(column_1),max(column_2),max(column_3),max(columnA),max(columnB),max(columnC),date_of_arrival
from (select column_1,column_2,column_3,
      null as columnA,null as columnB,null as columnC,date_of_arrival
      from internal_email
      union all
      select null,null,null,columnA,columnB,columnC,date_of_arrival
      from external_email
     ) t
group by date_of_arrival


问:
English texts lexicon comparison
Let's imagine, we can build a statistics table, how much each word is used in some English text or book. We can gather statistics for each text/book in library.
What is the simplest way to compare these statistics with each other? How can we find group/cluster of texts with very statistically similar lexicon?</p>

答:
First, you'd need to normalize the lexicon (i.e ensure that both lexicons have the same vocabulary).

Then you could use a similarity metric like the Hellenger distance or the cosine similarity to compare the two lexicons.

It may also be a good idea to look into machine learning packages such as Weka.

This book is an excellent source for machine learning and you may find it useful.

Title: English texts lexicon comparison


问:
Laravel Passport basic api auth returns "error":"invalid_client","message":"Client authentication failed"

The Problem

I've been trying to use Laravel Passport and I'm countinously getting the error {"error":"invalid_client","message":"Client authentication failed"}. I have used it in this Android and Laravel project but I just can register the user correctly as I see the proper data in the database. Then when the Android app tries to get the access token it crashes because the server return the previous error message.

I have also been following this YouTube tutorial exactly as it is explained but I got this error at the part it sends the "access token request".

Postman data

oauth_clients table

What I have tried

I have tried to fix this using this Stack Overflow page, this GitHub and many other webpages page but nothing worked

Possible cause

I think that it might be the uncompatibility of my laravel version
and passport (see below). I have manually changed laravel version to 5.4 but I
got a composer error. I don't want to reinstall laravel because i think I
could crash all my laravel projects.

The 'user_id' column has to be populated by laravel (I have manually
changed it to the user_id of the user and after that I restored it to
zero)

How to print data to the console? I use error_log() but I can't print variable names and with dd()I get and error saying that the variable couldn't be converted to string.

答:
you have to wrong pass client_id and client_password

if you have to right pass client_id and client_password then check in the database table oauth_clients client_id and client_password is row inserted or not if not added then run this command in console

php artisan passport:client

this will register client_id and client_password and then check that in this table(oauth_clients) if not added then maunally added client_id and client_passsword