问:
Converting a CSV File Into a 2D Array
How can i convert the data inside an CSV file to a 2d array?

```<code>array[row][column]
</code>```

I already have an upload script that will display all the data inside a CSV file.

Little snippet of my code, here's the full code: http://jsfiddle.net/Meesz/wj6q7c30/

```<code>reader.onload = function (e) {
  var table = document.createElement("table");
  var rows = e.target.result.split("\n");
  for (var i = 0; i < rows.length; i++) {
    var row = table.insertRow(-1);
    var cells = rows[i].split(",");
    for (var j = 0; j < cells.length; j++) {
        var cell = row.insertCell(-1);
        cell.innerHTML = cells[j];
    }
  }
  var dvCSV = document.getElementById("dvCSV");
  dvCSV.innerHTML = "";
  dvCSV.appendChild(table);
}
</code>```

答:
I needed something like this today so I found snippet originally done by by Bennadel and cleaned it up a bit also adding in edge cases.</p>

```<code>/*
 *  shortened version of:
 *   http://www.bennadel.com/blog/1504-ask-ben-parsing-csv-strings-with-javascript-exec-regular-expression-command.htm
 *
 *  Supports columns that are quoted/non-quoted. Takes care of quoted columns that may also have \n's inside
 *  them instead of using a naive approach of split('\n')
 *
 *  @param csvString {string} CSV file of rows separated by new lines.
 *  @param delimiter {string} delimiter used to split columns
 *
 *  return {rows} Array of rows with columns containing parsed CSV data
 */

function CSVParse(csvString, delimiter = ",") {

  if (!csvString || !csvString.length)
    return [];

  const pattern = new RegExp(
   ( "(\\" + delimiter + "|\\r?\\n|\\r|^)" +
     "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
     "([^\"\\" + delimiter + "\\r\\n]*))"
   ), "gi"
  );

  let rows = [[]];
  let matches = false;

  while (matches = pattern.exec(csvString)) {

    const matched_delimiter = matches[1];
    const matched_cellQuote = matches[2];
    const matched_cellNoQuote = matches[3];

    /*
     * Edge case: Data that starts with a delimiter
     */
    if (matches.index == 0 && matched_delimiter)
      rows[rows.length - 1].push("");

    /*
     * Fix empty lines
     */
    if(!matches[2] && !matches[3])
      continue;

    if (matched_delimiter.length && matched_delimiter !== delimiter)
      rows.push([]);

    const matched_value = (matched_cellQuote)
      ? matched_cellQuote.replace(
          new RegExp("\"\"", "g"), "\""
        )
      : matched_cellNoQuote;

    rows[rows.length - 1].push(matched_value);

   }

   return rows;
}
</code>```

Title: Converting a CSV File Into a 2D Array

Body:
How can i convert the data inside an CSV file to a 2d array?

array[row][column]

I already have an upload script that will display all the data inside a CSV file.

Little snippet of my code, here's the full code: http://jsfiddle.net/Meesz/wj6q7c30/

reader.onload = function (e) {
  var table = document.createElement("table");
  var rows = e.target.result.split("\n");
  for (var i = 0; i < rows.length; i++) {
    var row = table.insertRow(-1);
    var cells = rows[i].split(",");
    for (var j = 0; j < cells.length; j++) {
        var cell = row.insertCell(-1);
        cell.innerHTML = cells[j];
    }
  }
  var dvCSV = document.getElementById("dvCSV");
  dvCSV.innerHTML = "";
  dvCSV.appendChild(table);
}

Body:
I needed something like this today so I found snippet originally done by by Bennadel and cleaned it up a bit also adding in edge cases.

/*
 *  shortened version of:
 *   http://www.bennadel.com/blog/1504-ask-ben-parsing-csv-strings-with-javascript-exec-regular-expression-command.htm
 *
 *  Supports columns that are quoted/non-quoted. Takes care of quoted columns that may also have \n's inside
 *  them instead of using a naive approach of split('\n')
 *
 *  @param csvString {string} CSV file of rows separated by new lines.
 *  @param delimiter {string} delimiter used to split columns
 *
 *  return {rows} Array of rows with columns containing parsed CSV data
 */

function CSVParse(csvString, delimiter = ",") {

  if (!csvString || !csvString.length)
    return [];

  const pattern = new RegExp(
   ( "(\\" + delimiter + "|\\r?\\n|\\r|^)" +
     "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
     "([^\"\\" + delimiter + "\\r\\n]*))"
   ), "gi"
  );

  let rows = [[]];
  let matches = false;

  while (matches = pattern.exec(csvString)) {

    const matched_delimiter = matches[1];
    const matched_cellQuote = matches[2];
    const matched_cellNoQuote = matches[3];

    /*
     * Edge case: Data that starts with a delimiter
     */
    if (matches.index == 0 && matched_delimiter)
      rows[rows.length - 1].push("");

    /*
     * Fix empty lines
     */
    if(!matches[2] && !matches[3])
      continue;

    if (matched_delimiter.length && matched_delimiter !== delimiter)
      rows.push([]);

    const matched_value = (matched_cellQuote)
      ? matched_cellQuote.replace(
          new RegExp("\"\"", "g"), "\""
        )
      : matched_cellNoQuote;

    rows[rows.length - 1].push(matched_value);

   }

   return rows;
}


来源: stackexchange

问:
Open modal on ngOnDestroy() and not redirect to previews page
I want to open a popup modal when the user clicks on the browser back button. It should not redirect the user to the previous page but it should open a popup and wait for user action.

```<code>ngOnDestroy(){
    this.finishModal.show();
}
</code>```

Currently, it's redirecting to the previous page and try to open the popup simultaneously which results in redirecting to the previous page and then a backdrop of the modal shows up on the page. I tried preventDefault() as well.

How to just open the modal and stop the execution of ngOnDestroy()?

答:
ngOnDestory can't be used for that purpose, only to clean up (like unsubscribing event listeners or observables)

Without the router Is there any lifecycle hook like window.onbeforeunload in Angular2? might do what you want,

with the router https://angular.io/api/router/CanDeactivate (see also https://angular.io/guide/router#candeactivate-handling-unsaved-changes) might work.

ContentLicense: CC BY-SA 3.0

Body:
I want to open a popup modal when the user clicks on the browser back button. It should not redirect the user to the previous page but it should open a popup and wait for user action.

ngOnDestroy(){
    this.finishModal.show();
}

Currently, it's redirecting to the previous page and try to open the popup simultaneously which results in redirecting to the previous page and then a backdrop of the modal shows up on the page. I tried preventDefault() as well.

How to just open the modal and stop the execution of ngOnDestroy()?


问:
how to add postgresql database from file
Basically when creating new database, PostgreSQL make directory in "data/base" with OID.
Now I have a directory like this from my previous database, can i import this directory as a real database in pgAdmin?

I have a folder from my old database called 16384.I past it in my data/base folder but pgAdmin does not recognize it as a database.
I want to import it in my Pgadmin.
Is there any way to do this?

Thanks a lot.

答:
no. you can't do it with pgadmin.
try starting postgres with your data_directory pg_ctl -D DIR_WITH_BASE_CATALOG. If you lucky to star it, you can try taking a full backup - if success, the directory is usable, if not, you would recommend asking experts to help you extract as much as possible. If you decide to use zero_damaged_pages or other advanced features you can irreversibly destroy data (if there still is what to destroy)

anyway, before you start, I'd recommend copying the whole data_directory to somewhere else, and trying to start cluster from copy, not original...


问:
In Grails, how do I declare a SQL Server Schema name for a Domain Class?
I have recently started reading up on Grails and would like to use SQL Server security schemas to group tables generated by GORM. However, I cannot seem to find a reference explaining how to perform this task. I am new to Hibernate as well and would like to know if this is possible. Thank you.</p>

答:
The answer given by Michael Borgwardt is technically correct, but be aware that as of Grails 1.3.4, there is still a bug where using table-per-class inheritance all child classes will ignore the schema definition.

A possible work-around is to name the entire table and include the schema thus: "dbo.books", however this can cause problems with referential integrity; GORM will try to construct a name which contains too many "." characters, and PostgreSQL (for one) thinks you're trying to create cross-database server referential integrity, which isn't supported.

ContentLicense: CC BY-SA 2.5


问:
import org.springframework.web.bind.annotation.RestController cannot be resolved
I'm using Eclipse Kepler..I tried to use
import org.springframework.web.bind.annotation.RestController
But this import statement is not getting resolved
I've added all the dependencies required for that..but restcontroller is not getting resolved..

```<code>package s;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RestController {

@Autowired Bean bean;
@RequestMapping(value="/springAngularJS", method=RequestMethod.GET)

public @ResponseBody Bean getBean() {
Bean bean=new Bean();
    bean.setUserName("savitha");

    bean.setAge("22");

    bean.setCompany("Infosys");

    bean.setDesignation("ApplicationDeveloper");

    return bean;
  }
  }
</code>```

And my pom.xml is

```<code><project xmlns="http://maven.apache.org/POM/4.0.0"        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
</code>```

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
    http://maven.apache.org/maven-v4_0_0.xsd">

```<code><modelVersion>4.0.0</modelVersion>
<groupId>AngularRest</groupId>
<artifactId>AngularRest</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>AngularRest</name>
<url>http://maven.apache.org</url>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<repositories>
    <repository>
        <id>objectdb</id>
        <name>ObjectDB Repository</name>
        <url>http://m2.objectdb.com</url>
    </repository>
</repositories>

<dependencies>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.5</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.6.4</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.5</version>
    </dependency>
    <dependency>
        <groupId>com.objectdb</groupId>
        <artifactId>objectdb</artifactId>
        <version>2.0.4</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>3.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>3.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>3.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>aopalliance</groupId>
        <artifactId>aopalliance</artifactId>
        <version>1.0</version>
    </dependency>
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>2.2</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.6.10</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>1.5</source>
                <target>1.5</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.mortbay.jetty</groupId>
            <artifactId>maven-jetty-plugin</artifactId>
            <version>6.1.10</version>
            <configuration>
                <scanIntervalSeconds>10</scanIntervalSeconds>
                <stopKey>foo</stopKey>
                <stopPort>9999</stopPort>
            </configuration>
            <executions>
                <execution>
                    <id>start-jetty</id>
                    <phase>pre-integration-test</phase>
                    <goals>
                        <goal>run</goal>
                    </goals>
                    <configuration>
                        <scanIntervalSeconds>0</scanIntervalSeconds>
                        <daemon>true</daemon>
                    </configuration>
                </execution>
                <execution>
                    <id>stop-jetty</id>
                    <phase>post-integration-test</phase>
                    <goals>
                        <goal>stop</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
    <finalName>AngularRest</finalName>
</build>
</code>```

Thanks in advance..

答:
for a simple boot application,just check these dependencies in your pom.xml:</p>

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

    <groupId>com.example</groupId>
    <artifactId>bootbtb</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>bootbtb</name>
    <description>bus project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

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

    <dependencies>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.1.6.RELEASE</version>
</dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
         <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.1.6.RELEASE</version>
    </dependency>

</dependencies>

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

</project>
</code>```

Body:
I'm using Eclipse Kepler..I tried to use
import org.springframework.web.bind.annotation.RestController
But this import statement is not getting resolved
I've added all the dependencies required for that..but restcontroller is not getting resolved..

package s;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RestController {

@Autowired Bean bean;
@RequestMapping(value="/springAngularJS", method=RequestMethod.GET)

public @ResponseBody Bean getBean() {
Bean bean=new Bean();
    bean.setUserName("savitha");

    bean.setAge("22");

    bean.setCompany("Infosys");

    bean.setDesignation("ApplicationDeveloper");

    return bean;
  }
  }

And my pom.xml is

<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>AngularRest</groupId>
<artifactId>AngularRest</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>AngularRest</name>
<url>http://maven.apache.org</url>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<repositories>
    <repository>
        <id>objectdb</id>
        <name>ObjectDB Repository</name>
        <url>http://m2.objectdb.com</url>
    </repository>
</repositories>

<dependencies>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.5</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.6.4</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.5</version>
    </dependency>
    <dependency>
        <groupId>com.objectdb</groupId>
        <artifactId>objectdb</artifactId>
        <version>2.0.4</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>3.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>3.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>3.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>aopalliance</groupId>
        <artifactId>aopalliance</artifactId>
        <version>1.0</version>
    </dependency>
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>2.2</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.6.10</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>1.5</source>
                <target>1.5</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.mortbay.jetty</groupId>
            <artifactId>maven-jetty-plugin</artifactId>
            <version>6.1.10</version>
            <configuration>
                <scanIntervalSeconds>10</scanIntervalSeconds>
                <stopKey>foo</stopKey>
                <stopPort>9999</stopPort>
            </configuration>
            <executions>
                <execution>
                    <id>start-jetty</id>
                    <phase>pre-integration-test</phase>
                    <goals>
                        <goal>run</goal>
                    </goals>
                    <configuration>
                        <scanIntervalSeconds>0</scanIntervalSeconds>
                        <daemon>true</daemon>
                    </configuration>
                </execution>
                <execution>
                    <id>stop-jetty</id>
                    <phase>post-integration-test</phase>
                    <goals>
                        <goal>stop</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
    <finalName>AngularRest</finalName>
</build>

Thanks in advance..

Body:
for a simple boot application,just check these dependencies in your pom.xml:

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

    <groupId>com.example</groupId>
    <artifactId>bootbtb</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>bootbtb</name>
    <description>bus project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

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

    <dependencies>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.1.6.RELEASE</version>
</dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
         <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.1.6.RELEASE</version>
    </dependency>

</dependencies>

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

</project>


问:
CSS for placeholder box (design-time WYSIWYG)
This is a "silly" but hopefully legitimate if not particularly needful challenge, one that can be reused everywhere by designers, I'm sure, if an answer can be had.

I'm using a WYSIWYG-ish editor (MS Expression Web 4) and am trying to produce HTML-based wireframes which I intend to be the base for actual production. With raw/clean HTML being the #1 objective, I'd like to have a pattern for placeholders whereby I might specify the following HTML (and nothing else, except height, width, and text will vary), which should appear as a rectangular box with an 'X' through it and the text (in this case "logo") appearing at the bottom, or in the middle with white background behind the text:

```<code><div class="placeholder" style="width: 200px; height: 50px;">Logo</div>
</code>```

My question is what is the CSS and the minimum amount of HTML mucking (e.g. img tag) that is required to achieve what I want? For example, if the following HTML is used instead:

```<code><div class="placeholder">
    <img src="placeholder-xbox.png" width="200" height="200"/>
    Logo
</div>
</code>```

or

```<code><div class="placeholder">
    Logo
    <img src="placeholder-xbox.png" width="200" height="200"/>
</div>
</code>```

This would be an acceptable compromise on the HTML side, but then what would be the CSS to make this work?

I know I can use jQuery to hijack clean HTML to generate mucky HTML to achieve what I'm trying to do, but I need this  at design-time.

This fake screenshot below is what I'm looking for. I want to drop a tiny snippet of clean HTML and possibly use the anchor points in the WYSIWYG interface to scale the placeholder, while the label stays in the center-bottom or center-middle.

I have an image that is white with a black X through it.

I'm highly doubtful that CSS will support what I want without mucking up the HTML. However, I'd like to see if anyone knows if it's doable. Here's what I started with, which of course didn't work because the background image won't scale, the text won't vertically align, etc., etc.

```<code>.placeholder {
 display: inline;
 background-image: url('placeholder-xbox.png');
 border: 2px solid black;
    vertical-align: bottom;
}
</code>```

So now I have to figure out what compromises to make. I hate mucking up the HTML and don't mind mucked up CSS because a CSS class is reusable.

答:
When I want placeholders like that, I tend to just do something like:

logo
 and #logo{ background:#ccc; border:1px solid red }.

So, it would look like this for you:

```<code><div class="placeholder" style="width: 200px; height: 50px">
    Logo
</div>

.placeholder {
    background: #ccc;
    border: 1px solid red;
    text-align: center
}
</code>```

It takes extra markup to get the text at the bottom:

```<code><div class="placeholder" style="width: 200px; height: 50px">
    <span>Logo</span>
</div>

.placeholder {
    background: #ccc;
    border: 1px solid red;
    text-align: center;
    position: relative
}
.placeholder span {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%
}
</code>```

Live Demo

Having just wrote all that, I realised how easy it is to modify it into the creation you described; try this:

Live Demo

```<code><div class="placeholder" style="width: 200px; height: 50px">
    <img src="http://i.stack.imgur.com/yZlqh.png" />
    <span>Logo</span>
</div>

.placeholder {
    background: #ccc;
    border: 1px solid #000;
    text-align: center;
    position: relative;
    font-weight: bold
}
.placeholder span {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%
}
.placeholder img {
    width: 100%;
    height: 100%
}
</code>```

Body:
This is a "silly" but hopefully legitimate if not particularly needful challenge, one that can be reused everywhere by designers, I'm sure, if an answer can be had.

I'm using a WYSIWYG-ish editor (MS Expression Web 4) and am trying to produce HTML-based wireframes which I intend to be the base for actual production. With raw/clean HTML being the #1 objective, I'd like to have a pattern for placeholders whereby I might specify the following HTML (and nothing else, except height, width, and text will vary), which should appear as a rectangular box with an 'X' through it and the text (in this case "logo") appearing at the bottom, or in the middle with white background behind the text:

Logo

My question is what is the CSS and the minimum amount of HTML mucking (e.g. img tag) that is required to achieve what I want? For example, if the following HTML is used instead:

    Logo

or

    Logo

This would be an acceptable compromise on the HTML side, but then what would be the CSS to make this work?

I know I can use jQuery to hijack clean HTML to generate mucky HTML to achieve what I'm trying to do, but I need this  at design-time.

This fake screenshot below is what I'm looking for. I want to drop a tiny snippet of clean HTML and possibly use the anchor points in the WYSIWYG interface to scale the placeholder, while the label stays in the center-bottom or center-middle.

I have an image that is white with a black X through it.

I'm highly doubtful that CSS will support what I want without mucking up the HTML. However, I'd like to see if anyone knows if it's doable. Here's what I started with, which of course didn't work because the background image won't scale, the text won't vertically align, etc., etc.

.placeholder {
 display: inline;
 background-image: url('placeholder-xbox.png');
 border: 2px solid black;
    vertical-align: bottom;
}

So now I have to figure out what compromises to make. I hate mucking up the HTML and don't mind mucked up CSS because a CSS class is reusable.

Body:
When I want placeholders like that, I tend to just do something like:

<div id="logo">logo</div> and #logo{ background:#ccc; border:1px solid red }.

So, it would look like this for you:

<div class="placeholder" style="width: 200px; height: 50px">
    Logo
</div>

.placeholder {
    background: #ccc;
    border: 1px solid red;
    text-align: center
}

It takes extra markup to get the text at the bottom:

<div class="placeholder" style="width: 200px; height: 50px">
    <span>Logo</span>
</div>

.placeholder {
    background: #ccc;
    border: 1px solid red;
    text-align: center;
    position: relative
}
.placeholder span {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%
}

Live Demo

Having just wrote all that, I realised how easy it is to modify it into the creation you described; try this:

Live Demo

<div class="placeholder" style="width: 200px; height: 50px">
    <img src="http://i.stack.imgur.com/yZlqh.png" />
    <span>Logo</span>
</div>

.placeholder {
    background: #ccc;
    border: 1px solid #000;
    text-align: center;
    position: relative;
    font-weight: bold
}
.placeholder span {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%
}
.placeholder img {
    width: 100%;
    height: 100%
}


问:
BottomNavigationView Does not work
I am working with BottomNavigationView, but the application does directly stopped and give me an error at line

```<code>setContentView(R.layout.activity_main);
</code>```

this is my code ( I did not do anything yet )

Main.java

```<code>public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
</code>```

xml file :

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:Design="http://schemas.android.com/apk/res-auto"
tools:context="com.example.ahmad.testbottomnavigationbar.MainActivity"
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
   />
<android.support.design.widget.BottomNavigationView
    android:id="@+id/NavBar"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_gravity="bottom"
    Design:menu="@menu/menu_nav">
</code>```

And Menu :

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:icon="@drawable/news"
    android:title="news" />
<item
    android:icon="@drawable/sug"
    android:title="sugg" />
<item
    android:icon="@drawable/fav"
    android:title="fav" />
<item
    android:icon="@drawable/myhome"
    android:title="home" />

<item
    android:icon="@drawable/comp"
    android:title="complain" />

<item

    android:icon="@drawable/myaccount"
    android:title="account" />
</code>```

and finally dependacies :

```<code> implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.support:design:26.1.0'
</code>```

and the application stopped after running ,
this is the exception :

java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.example.ahmad.testbottomnavigationbar/com.example.ahmad.testbottomnavigationbar.MainActivity}:
  android.view.InflateException: Binary XML file line #16: Error
  inflating class android.support.design.widget.BottomNavigationView

答:
please try this one

```<code><android.support.design.widget.BottomNavigationView
android:id="@+id/NavBar"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="bottom"
Design:menu="@menu/menu_nav">
</code>```

Replace

```<code><android.support.design.widget.BottomNavigationView
     android:id="@+id/NavBar"
     android:layout_width="match_parent"
     android:layout_height="50dp"
     android:layout_gravity="bottom"
     app:menu="@menu/menu_nav"/>
</code>```

Title: BottomNavigationView Does not work

Body:
I am working with BottomNavigationView, but the application does directly stopped and give me an error at line

setContentView(R.layout.activity_main);

this is my code ( I did not do anything yet )

Main.java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

xml file :

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:Design="http://schemas.android.com/apk/res-auto"
tools:context="com.example.ahmad.testbottomnavigationbar.MainActivity"
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
   />
<android.support.design.widget.BottomNavigationView
    android:id="@+id/NavBar"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_gravity="bottom"
    Design:menu="@menu/menu_nav">

And Menu :

<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:icon="@drawable/news"
    android:title="news" />
<item
    android:icon="@drawable/sug"
    android:title="sugg" />
<item
    android:icon="@drawable/fav"
    android:title="fav" />
<item
    android:icon="@drawable/myhome"
    android:title="home" />

<item
    android:icon="@drawable/comp"
    android:title="complain" />

<item

    android:icon="@drawable/myaccount"
    android:title="account" />

and finally dependacies :

 implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.support:design:26.1.0'

and the application stopped after running ,
this is the exception :

java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.example.ahmad.testbottomnavigationbar/com.example.ahmad.testbottomnavigationbar.MainActivity}:
  android.view.InflateException: Binary XML file line #16: Error
  inflating class android.support.design.widget.BottomNavigationView

Body:
please try this one

<android.support.design.widget.BottomNavigationView
android:id="@+id/NavBar"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="bottom"
Design:menu="@menu/menu_nav">

Replace

<android.support.design.widget.BottomNavigationView
     android:id="@+id/NavBar"
     android:layout_width="match_parent"
     android:layout_height="50dp"
     android:layout_gravity="bottom"
     app:menu="@menu/menu_nav"/>


问:
Is there a way to change an input with a certain code
Is their a way to make a value of a form input change based on a certain code in another input without PHP?
EX: User puts in HFS73H into one input, and another changes to John - while another user puts JSJ39Q into the first mentioned input, and the other input changes to Paul</p>

答:
Its possible to do.

We can encode and decode the data with Javascript.

Follow this Link
http://www.minelinks.com/supercode/2cryptoolE.html


问:
Process user input to "phrase/3" method in Prolog
I have build a DCG with Prolog. The code works, when I do the following call:

```<code>phrase(programm(R), [1,+,2], []).
</code>```

I want the user to write the input, so I did this:

```<code>main :- read(Input), atom_chars(Input, R), write(R), phrase(programm(E), R).
</code>```

Calling main and input e.g. '1+2' doesn't work. How can I process the user input to the phrase method for calling my DCG?

答:
SWI-Prolog offers an handy way, by means of tokenize_atom. </p>

```<code>program(sum(L,R)) --> [L, +, R].

?- tokenize_atom('1 + 2', L), phrase(program(P), L).
L = [1, +, 2],
P = sum(1, 2).
</code>```

Body:
I have build a DCG with Prolog. The code works, when I do the following call:

phrase(programm(R), [1,+,2], []).

I want the user to write the input, so I did this:

main :- read(Input), atom_chars(Input, R), write(R), phrase(programm(E), R).

Calling main and input e.g. '1+2' doesn't work. How can I process the user input to the phrase method for calling my DCG?

Body:
SWI-Prolog offers an handy way, by means of tokenize_atom.

program(sum(L,R)) --> [L, +, R].

?- tokenize_atom('1 + 2', L), phrase(program(P), L).
L = [1, +, 2],
P = sum(1, 2).


问:
Parsing file and sort lines by property
So basically someone gave me a text file for me to read through Java and I have to print out certain parts of it.

So what I did was I put all of the text file into a String and between every word there's a ":". So i split all of the text with ":" using split function. At first every line looks like this

```<code>firstName:Surname:Age:Country
firstName:Surname:Age:Country
firstName:Surname:Age:Country
firstName:Surname:Age:Country
firstName:Surname:Age:Country
firstName:Surname:Age:Country
firstName:Surname:Age:Country
firstName:Surname:Age:Country
</code>```

After it would be the same thing without the colons.

So now if I say all[0], I would get all the firstNames only.

What I'm trying to get is get the top 3 highest ages but I do not know how to do that.

答:
Explanation

Suppose you have a file with lines like

```<code>John:Doe:20:USA
Jane:Doe:35:Germany
Robert:Moe:14:Japan
Larry:Loe:25:China
Richard:Roe:27:India
</code>```

and you want the 3 lines with the highest age, that would be

```<code>Jane:Doe:35:Germany
Richard:Roe:27:India
Larry:Loe:25:China
</code>```

The procedure is straightforward. First read all lines, split by : and parse the data into a wrapper class like Person. Collect them into some collection like List<Person> and sort them using a Comparator that compares the age. Alternatively you could let Person implement Comparable and then use their natural order.

If efficiency matters you can also do partial sort since you are only interested in the top 3 hits. For this you could use a PriorityQueue, insert all elements and call poll three times.

Solution

First the Person wrapper class

```<code>public class Person {
    private String mFirstName;
    private String mSurname;
    private int mAge;
    private String mCountry;

    public Person(String firstName, String surname, int age, String country) {
        this.mFirstName = firstName;
        this.mSurname = surname;
        this.mAge = age;
        this.mCountry = country;
    }

    // TODO Some getters

    public String toString() {
        return this.mFirstName + ":" + this.mSurname
            + ":" + this.mAge + ":" + this.mCountry;
    }

    public static Person parse(String[] data) {
        String firstName = data[0];
        String surname = data[1];
        int age = Integer.parseInt(data[2]);
        String country = data[3];

        return new Person(firstName, surname, age, country);
    }
}
</code>```

Next we read all lines, split the data and parse them into Person. After that we sort and limit the result to 3. Finally we collect to a List and print the results.

```<code>Path file = Paths.get(...);
Pattern separator = Pattern.compile(":");

List<Person> persons = Files.lines(file) // Stream<String>
    .map(separator::splitAsStream)       // Stream<String[]>
    .map(Person::parse)                  // Stream<Person>
    .sorted(Comparator.comparingInt(Person::getAge).reversed())
    .limit(3)
    .collect(Collectors.toList());

persons.forEach(System.out::println);
</code>```

Or if you want to use the PriorityQueue as suggested, which will improve runtime:

```<code>Path file = Paths.get(...);
Pattern separator = Pattern.compile(":");

PriorityQueue<Person> personQueue = Files.lines(file)
    .map(separator::splitAsStream)
    .map(Person::parse)
    .collect(Collectors.toCollection(() -> {
        return new PriorityQueue<>(
            Comparator.comparingInt(Person::getAge).reversed());
    }));

List<Person> persons = new ArrayList<>(3);
persons.add(personQueue.poll());
persons.add(personQueue.poll());
persons.add(personQueue.poll());

persons.forEach(System.out::println);
</code>```

Title: Parsing file and sort lines by property

Body:
So basically someone gave me a text file for me to read through Java and I have to print out certain parts of it.

So what I did was I put all of the text file into a String and between every word there's a ":". So i split all of the text with ":" using split function. At first every line looks like this

firstName:Surname:Age:Country
firstName:Surname:Age:Country
firstName:Surname:Age:Country
firstName:Surname:Age:Country
firstName:Surname:Age:Country
firstName:Surname:Age:Country
firstName:Surname:Age:Country
firstName:Surname:Age:Country

After it would be the same thing without the colons.

So now if I say all[0], I would get all the firstNames only.

What I'm trying to get is get the top 3 highest ages but I do not know how to do that.

Body:
Explanation

Suppose you have a file with lines like

John:Doe:20:USA
Jane:Doe:35:Germany
Robert:Moe:14:Japan
Larry:Loe:25:China
Richard:Roe:27:India

and you want the 3 lines with the highest age, that would be

Jane:Doe:35:Germany
Richard:Roe:27:India
Larry:Loe:25:China

The procedure is straightforward. First read all lines, split by : and parse the data into a wrapper class like Person. Collect them into some collection like List<Person> and sort them using a Comparator that compares the age. Alternatively you could let Person implement Comparable and then use their natural order.

If efficiency matters you can also do partial sort since you are only interested in the top 3 hits. For this you could use a PriorityQueue, insert all elements and call poll three times.

Solution

First the Person wrapper class

public class Person {
    private String mFirstName;
    private String mSurname;
    private int mAge;
    private String mCountry;

    public Person(String firstName, String surname, int age, String country) {
        this.mFirstName = firstName;
        this.mSurname = surname;
        this.mAge = age;
        this.mCountry = country;
    }

    // TODO Some getters

    public String toString() {
        return this.mFirstName + ":" + this.mSurname
            + ":" + this.mAge + ":" + this.mCountry;
    }

    public static Person parse(String[] data) {
        String firstName = data[0];
        String surname = data[1];
        int age = Integer.parseInt(data[2]);
        String country = data[3];

        return new Person(firstName, surname, age, country);
    }
}

Next we read all lines, split the data and parse them into Person. After that we sort and limit the result to 3. Finally we collect to a List and print the results.

Path file = Paths.get(...);
Pattern separator = Pattern.compile(":");

List<Person> persons = Files.lines(file) // Stream<String>
    .map(separator::splitAsStream)       // Stream<String[]>
    .map(Person::parse)                  // Stream<Person>
    .sorted(Comparator.comparingInt(Person::getAge).reversed())
    .limit(3)
    .collect(Collectors.toList());

persons.forEach(System.out::println);

Or if you want to use the PriorityQueue as suggested, which will improve runtime:

Path file = Paths.get(...);
Pattern separator = Pattern.compile(":");

PriorityQueue<Person> personQueue = Files.lines(file)
    .map(separator::splitAsStream)
    .map(Person::parse)
    .collect(Collectors.toCollection(() -> {
        return new PriorityQueue<>(
            Comparator.comparingInt(Person::getAge).reversed());
    }));

List<Person> persons = new ArrayList<>(3);
persons.add(personQueue.poll());
persons.add(personQueue.poll());
persons.add(personQueue.poll());

persons.forEach(System.out::println);


问:
In laravel 5.5 use carbon to compare 2 dates
In laravel 5.5 I use carbon to compare 2 dates, but the thing is that createFromFormat returns timestamp and I do not know

how to set time to “00:00:00” . I make :

```<code>echo 'passes ```$value::'.print_r($value, true).'```';
// output 2018-08-01

$postgresql_format = config('app.postgresql_date_format', 'Y-m-d');

echo '```$postgresql_format::'.print_r($postgresql_format,true).'```';
// output $postgresql_format::Y-m-d

$A = preg_split("/ /", $value);
if (count($A) == 2) {
    $value= $A[0];
}

$a= Carbon::createFromFormat($postgresql_format, $value);

echo '```$a->isPast()::'.print_r($a->isPast(),true).'```';
//output $a->isPast():: - seems it is does not work

$today= Carbon::today();
echo '```$today::'.print_r($today,true).'```';
/* Output:
$today::Carbon\Carbon Object
(
    [date] => 2017-12-04 00:00:00.000000
    [timezone_type] => 3
    [timezone] => UTC
)
 */

var_dump($today->lt($a)); // bool(false)
echo '```$a::'.print_r($a,true).'```';

/*
$a::Carbon\Carbon Object
(
    [date] => 2018-08-01 08:41:56.000000
    [timezone_type] => 3
    [timezone] => UTC
)
 */
</code>```

How to set time of $a to “00:00:00” to exclude time from comparison ?

PS: $a->isPast() does not seems to work

Thanks!

答:
If I understand correctly, you want to compare two dates based on the dates only, excluding the time.

Carbon has a method to compare it with another Carbon object, based on the date, excluding the time.

From the Carbon source code:

```<code>public function isSameDay(Carbon $dt)
    {
        return $this->toDateString() === $dt->toDateString();
    }
</code>```

Where toDateString formats the date to "Y-m-d".

So you can do:

```<code>$date = Carbon::parse('2016-09-17 11:00:00');
$now = Carbon::now();

if ($date->isSameDay($now) ...
</code>```

Or, in case you need to check only against today:

```<code>if ($date->isToday() ...
</code>```

For more see here.

Body:
In laravel 5.5 I use carbon to compare 2 dates, but the thing is that createFromFormat returns timestamp and I do not know

how to set time to “00:00:00” . I make :

echo 'passes
$value::'.print_r($value, true).'
';
// output 2018-08-01

$postgresql_format = config('app.postgresql_date_format', 'Y-m-d');

echo '
$postgresql_format::'.print_r($postgresql_format,true).'
';
// output $postgresql_format::Y-m-d

$A = preg_split("/ /", $value);
if (count($A) == 2) {
    $value= $A[0];
}

$a= Carbon::createFromFormat($postgresql_format, $value);

echo '
$a->isPast()::'.print_r($a->isPast(),true).'
';
//output $a->isPast():: - seems it is does not work

$today= Carbon::today();
echo '
$today::'.print_r($today,true).'
';
/* Output:
$today::Carbon\Carbon Object
(
    [date] => 2017-12-04 00:00:00.000000
    [timezone_type] => 3
    [timezone] => UTC
)
 */

var_dump($today->lt($a)); // bool(false)
echo '
$a::'.print_r($a,true).'
';

/*
$a::Carbon\Carbon Object
(
    [date] => 2018-08-01 08:41:56.000000
    [timezone_type] => 3
    [timezone] => UTC
)
 */

How to set time of $a to “00:00:00” to exclude time from comparison ?

PS: $a->isPast() does not seems to work

Thanks!

Body:
If I understand correctly, you want to compare two dates based on the dates only, excluding the time.

Carbon has a method to compare it with another Carbon object, based on the date, excluding the time.

From the Carbon source code:

public function isSameDay(Carbon $dt)
    {
        return $this->toDateString() === $dt->toDateString();
    }

Where toDateString formats the date to "Y-m-d".

So you can do:

$date = Carbon::parse('2016-09-17 11:00:00');
$now = Carbon::now();

if ($date->isSameDay($now) ...

Or, in case you need to check only against today:

if ($date->isToday() ...

For more see here.


问:
Generate tr on click of Image button jquery
I have a scenario where I want to duplicate the existing
 whenever I click on  + button which is:

Below is my
. how to generate this using jquery or javascript

```<code> <tr>
    <td>
        <div class="row noPadding vendorForm">
            <div class="vendorDaterow">
                <div class="vendorName">
                    <label>SP Vender Name</label><span>Shri Kamalkanth Co.</span>
                </div>
                <div class="vendorFromDate">
                    <label>From Date</label><span class="datepicker"><input type="text" id="spFromDate1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                </div>
                <div class="vendorToDate">
                    <label>To Date</label><span class="datepicker"><input type="text" id="spToDate1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                </div>
            </div>
            <div class="add">
                <i class="fa fa-plus" aria-hidden="true"></i>
            </div>
            <i class="max">(Maximum 5 Vendors)</i>

        </div>
    </td>
</tr>
</code>```

答:
You need the template of the
 somehow. Use some kind of templating engine or the lazy way: copy it on page load. (to not have existing input when copying the
)

```<code>var $template = $('yourTrSelector').clone();
</code>```

And then paste it on button click.

```<code>$('yourButtonSelector').on('click', function(){
  $('yourTableSelector').append($template.copy());
});
</code>```

Body:
I have a scenario where I want to duplicate the existing
 whenever I click on  + button which is:

Below is my
. how to generate this using jquery or javascript

                    SP Vender NameShri Kamalkanth Co.

                    From Date<input type="text" id="spFromDate1" />

                    To Date<input type="text" id="spToDate1" />

            (Maximum 5 Vendors)

Body:
You need the template of the <tr> somehow. Use some kind of templating engine or the lazy way: copy it on page load. (to not have existing input when copying the <tr>)

var $template = $('yourTrSelector').clone();

And then paste it on button click.

$('yourButtonSelector').on('click', function(){
  $('yourTableSelector').append($template.copy());
});


问:
Copying directory doesn't copy source folder Java
I am trying to copy a folder/file from one location to another in Java. I am a beginner in Java and I fould a neat little library, I believe it is called Apache FileUtils, which has a FileUtils.CopyDirectory() method which should copy a folder from one destination to another. However, for me it only copies what is inside the folder itself.

```<code>else if (command.equals("COPY")){
        System.out.println("Enter the path of the file/folder you wish to copy : ");
        Scanner scannerPath = new Scanner(System.in);
        path = scannerPath.nextLine();
        File copiedFolder = new File(path);
        System.out.println("Enter the path where you want to copy the file/folder: ");
        String newpath = scannerPath.nextLine();
        File copyFolder = new File(newpath);
        if (copiedFolder.isDirectory() && copiedFolder.exists())
        {

            FileUtils.copyDirectory(copiedFolder, copyFolder);
            System.out.println("Copy successful !");
        }
        else if (copiedFolder.isFile())
        {

            FileUtils.copyFile(copiedFolder, copyFolder);
            System.out.println("Copy successful !");
        }
        else {
            System.out.println("Copy failed. Check if the file/folder exists !");
        }
</code>```

It should copy the whole directory, but for some reason It does not work for me.

答:
From the documentation of copyDirectory :

The destination is the new location and name of the directory.

and

If the destination directory did exist, then this method merges the
  source with the destination, with the source taking precedence.

So basically the target directory will represent itself the copy of your source directory.

You may consider adding a subdirectory with the desired name in the path, like :

```<code>File copyFolder = new File(newpath + File.separator + copiedFolder.getName());
</code>```

Body:
I am trying to copy a folder/file from one location to another in Java. I am a beginner in Java and I fould a neat little library, I believe it is called Apache FileUtils, which has a FileUtils.CopyDirectory() method which should copy a folder from one destination to another. However, for me it only copies what is inside the folder itself.

else if (command.equals("COPY")){
        System.out.println("Enter the path of the file/folder you wish to copy : ");
        Scanner scannerPath = new Scanner(System.in);
        path = scannerPath.nextLine();
        File copiedFolder = new File(path);
        System.out.println("Enter the path where you want to copy the file/folder: ");
        String newpath = scannerPath.nextLine();
        File copyFolder = new File(newpath);
        if (copiedFolder.isDirectory() && copiedFolder.exists())
        {

            FileUtils.copyDirectory(copiedFolder, copyFolder);
            System.out.println("Copy successful !");
        }
        else if (copiedFolder.isFile())
        {

            FileUtils.copyFile(copiedFolder, copyFolder);
            System.out.println("Copy successful !");
        }
        else {
            System.out.println("Copy failed. Check if the file/folder exists !");
        }

It should copy the whole directory, but for some reason It does not work for me.

Body:
From the documentation of copyDirectory :

The destination is the new location and name of the directory.

and

If the destination directory did exist, then this method merges the
  source with the destination, with the source taking precedence.

So basically the target directory will represent itself the copy of your source directory.

You may consider adding a subdirectory with the desired name in the path, like :

File copyFolder = new File(newpath + File.separator + copiedFolder.getName());


问:
How to add sd card to android emulator in android studio 1.5.1?
I am using android studio 1.5.1 and ubuntu 14.04. I want to add sd card to mobile device emulator.

I created new virtual device using Android Virtual Device Manager from android studio menus Tools --> Android --> AVD Manager. But there is no option to add sd card to virtual device. So tried command line tool mksdcard to create sd card as per instructions given in developer.android.com.

```<code>./mksdcard -l mySdCard 128M mySdCardFile.img
</code>```

And then used following command to start emulator and load sd card.

./emulator -avd Nexus_5_API_23_x86 -sdcard mySdCardFile.img

But it gave me warning emulator: WARNING: Emulated hardware doesn't support SD Cards. -sdcard option ignored.

How can I use sd card in emulator? Please help!

答:
Go to your avd location (typically at ~/.android/avd/your-android-avd-id)

There is a file named config.ini

Open that and look for the line hw.sdCard=no and change it to hw.sdCard=yes.

Should work now.
If you open the settings for this avd in the avd manager, you will have to set this setting in config.ini again.

Body:
I am using android studio 1.5.1 and ubuntu 14.04. I want to add sd card to mobile device emulator.

I created new virtual device using Android Virtual Device Manager from android studio menus Tools --> Android --> AVD Manager. But there is no option to add sd card to virtual device. So tried command line tool mksdcard to create sd card as per instructions given in developer.android.com.

./mksdcard -l mySdCard 128M mySdCardFile.img

And then used following command to start emulator and load sd card.

./emulator -avd Nexus_5_API_23_x86 -sdcard mySdCardFile.img

But it gave me warning emulator: WARNING: Emulated hardware doesn't support SD Cards. -sdcard option ignored.

How can I use sd card in emulator? Please help!


问:
How to elegantly convert multi-col rows into dataframe?
I want to convert RDD to DataFrame using StructType. But item "Broken,Line," would cause error. Is there an elegant way to process record like this? Thanks.

import org.apache.spark.sql.types.{StructType, StructField, StringType}
import org.apache.spark.sql.Row

val mySchema = StructType(Array(
  StructField("colA", StringType, true),
  StructField("colB", StringType, true),
  StructField("colC", StringType, true)))
val x = List("97573,Start,eee", "9713,END,Good", "Broken,Line,")
val inputx = sc.parallelize(x).
| map((x:String) => Row.fromSeq(x.split(",").slice(0,mySchema.size).toSeq))
val df = spark.createDataFrame(inputx, mySchema)
df.show
```

Error would be like this:

Name: org.apache.spark.SparkException  Message: Job aborted due to
  stage failure: Task 0 in stage 14.0 failed 1 times, most recent
  failure: Lost task 0.0 in stage 14.0 (TID 14, localhost, executor
  driver): java.lang.RuntimeException: Error while encoding:
  java.lang.ArrayIndexOutOfBoundsException: 2

I'm using:

Spark: 2.2.0

Scala: 2.11.8

And I ran the code in spark-shell.

答:
Row.fromSeq on which we apply your schema throws the error that you are getting. Your third element in your list contains just 2 elements. You can't transform it into a Row with three elements unless you add a null value instead of the missing value.

And when creating your DataFrame, Spark is expecting 3 elements per Row on which to apply the schema, thus the error.

A quick and dirty solution would be to use scala.util.Try to get fields separately :

```<code>import org.apache.spark.sql.types.{StructType, StructField, StringType}
import org.apache.spark.sql.Row
import scala.util.Try

val mySchema = StructType(Array(StructField("colA", StringType, true), StructField("colB", StringType, true), StructField("colC", StringType, true)))

val l = List("97573,Start,eee", "9713,END,Good", "Broken,Line,")

val rdd = sc.parallelize(l).map {
 x => {
  val fields = x.split(",").slice(0, mySchema.size)
  val f1 = Try(fields(0)).getOrElse("")
  val f2 = Try(fields(1)).getOrElse("")
  val f3 = Try(fields(2)).getOrElse("")
  Row(f1, f2, f3)
 }
}

val df = spark.createDataFrame(rdd, mySchema)

df.show
// +------+-----+----+
// |  colA| colB|colC|
// +------+-----+----+
// | 97573|Start| eee|
// |  9713|  END|Good|
// |Broken| Line|    |
// +------+-----+----+
</code>```

I wouldn't say that it's an elegant solution like you've asked. Parsing strings is never elegant ! You ought using the csv source to read it correctly (or spark-csv for < 2.x).

ContentLicense: CC BY-SA 4.0

Body:
I want to convert RDD to DataFrame using StructType. But item "Broken,Line," would cause error. Is there an elegant way to process record like this? Thanks.

import org.apache.spark.sql.types.{StructType, StructField, StringType}
import org.apache.spark.sql.Row

val mySchema = StructType(Array(
  StructField("colA", StringType, true),
  StructField("colB", StringType, true),
  StructField("colC", StringType, true)))
val x = List("97573,Start,eee", "9713,END,Good", "Broken,Line,")
val inputx = sc.parallelize(x).
| map((x:String) => Row.fromSeq(x.split(",").slice(0,mySchema.size).toSeq))
val df = spark.createDataFrame(inputx, mySchema)
df.show

Error would be like this:

Name: org.apache.spark.SparkException  Message: Job aborted due to
  stage failure: Task 0 in stage 14.0 failed 1 times, most recent
  failure: Lost task 0.0 in stage 14.0 (TID 14, localhost, executor
  driver): java.lang.RuntimeException: Error while encoding:
  java.lang.ArrayIndexOutOfBoundsException: 2

I'm using:

Spark: 2.2.0

Scala: 2.11.8

And I ran the code in spark-shell.

Body:
Row.fromSeq on which we apply your schema throws the error that you are getting. Your third element in your list contains just 2 elements. You can't transform it into a Row with three elements unless you add a null value instead of the missing value.

And when creating your DataFrame, Spark is expecting 3 elements per Row on which to apply the schema, thus the error.

A quick and dirty solution would be to use scala.util.Try to get fields separately :

import org.apache.spark.sql.types.{StructType, StructField, StringType}
import org.apache.spark.sql.Row
import scala.util.Try

val mySchema = StructType(Array(StructField("colA", StringType, true), StructField("colB", StringType, true), StructField("colC", StringType, true)))

val l = List("97573,Start,eee", "9713,END,Good", "Broken,Line,")

val rdd = sc.parallelize(l).map {
 x => {
  val fields = x.split(",").slice(0, mySchema.size)
  val f1 = Try(fields(0)).getOrElse("")
  val f2 = Try(fields(1)).getOrElse("")
  val f3 = Try(fields(2)).getOrElse("")
  Row(f1, f2, f3)
 }
}

val df = spark.createDataFrame(rdd, mySchema)

df.show
// +------+-----+----+
// |  colA| colB|colC|
// +------+-----+----+
// | 97573|Start| eee|
// |  9713|  END|Good|
// |Broken| Line|    |
// +------+-----+----+

I wouldn't say that it's an elegant solution like you've asked. Parsing strings is never elegant ! You ought using the csv source to read it correctly (or spark-csv for < 2.x).


问:
How to setup a rewrite rule on Azure CDN to serve index.html that don't match a path pattern?
I want to use Azure CDN (which is powered by EdgeCast, apparently) to serve static content for my React + GraphQL web app.

The CDN will pull the static files from a Storage account, and Node.js will handle the GraphQL endpoint.

For the client-side routing to work properly, I need to serve /static/index.html for all requests that don't match the static content path (/static/somefile.ext).

I want to avoid using Node.js to serve the index.html in this fashion:

```<code>var express = require('express');
var app = express();

app.all('*', function(req, res){
  res.sendfile("index.html");
});
</code>```

答: You could try to use the "Modify Client Response Header" feature:

Body:
I want to use Azure CDN (which is powered by EdgeCast, apparently) to serve static content for my React + GraphQL web app.

The CDN will pull the static files from a Storage account, and Node.js will handle the GraphQL endpoint.

For the client-side routing to work properly, I need to serve /static/index.html for all requests that don't match the static content path (/static/somefile.ext).

I want to avoid using Node.js to serve the index.html in this fashion:

var express = require('express');
var app = express();

app.all('*', function(req, res){
  res.sendfile("index.html");
});


问:
Advice converting recursive Diff Algorithm to an iterative one?
Greetings!

I wrote a recursive diff algorithm from scratch. It finds the "best match" between two strings such that the differences are minimized, and prints out the two strings with any differences represented in CAPS. It works fine "as is", except that it is pretty inefficient. I've been staring at it for a day and a half now, trying to find ways to make it iterative or at least reduce the stack depth that it reaches, but I'm at my wit's end and was hoping that a keen mind here would see the solution more clearly than me.

Below is the meat of the code. The MergePoint class that is referenced is just a simple "linked list" style node that contains an "index in original" integer, an "index in altered" integer, and a "next" MergePoint. The MergePoint list represents a series of indexes in each array that have been "merged". When the chain is completed, any indexes that are not represented in the chain are insertions/deletions. The NullObject object is an extension of MergePoint that, thinking back on it, wasn't strictly necessary to create and can basically be considered a regular 'null'.

Any advice/suggestions would be very deeply appreciated.

```<code>public class StringCompare
{
    public static int[][]       mergeList       = new int[0][0];
    public static MergePoint    NULL            = NullObject.getNull();
    public static int           maxMerged       = 0;
    public static int           minClusterSize  = -1;

    public static void diff(String orig, String alt)
    {
        String[] original = orig.toUpperCase().split(" ");
        String[] altered  = alt.toUpperCase().split(" ");

        for(int i = 0; i < altered.length; i++)
        {
            merge(original, altered, 0, i, NULL, NULL, 0, 0);
        }

        for(int i = 0; i < mergeList.length; i++)
        {
            or[mergeList[i][0]] = or[mergeList[i][0]].toLowerCase();
            al[mergeList[i][1]] = al[mergeList[i][1]].toLowerCase();
        }

        printStringArray(or);
        printStringArray(al);
    }

    private void printStringArray(String[] arr)
    {
        for(String word : arr)
        {
            System.out.print(word.trim() + " ");
        }

        System.out.println();
    }

    private static void merge(String[] original, String[] altered, int indexInOriginal, int indexInAltered, MergePoint head, MergePoint tail, int listSize, int clusters)
    {
        if (indexInOriginal >= original.length)
        {
            if (listSize > 0)
            {
                if (((listSize == maxMerged) && (clusters < minClusterSize)) ||
                    (listSize > maxMerged))
                {
                    storeMergePoints(head, listSize, clusters);
                }
            }
        }
        else if (indexInAltered >= altered.length)
        {
            if (tail != NULL)
            {
                merge(original, altered, (indexInOriginal + 1), (tail.indexInNew() + 1), head, tail, listSize, clusters);
            }
            else
            {
                merge(original, altered, (indexInOriginal + 1), 0, head, tail, listSize, 0);
            }
        }
        else
        {
            if(original[indexInOriginal].equals(altered[indexInAltered]))
            {
                MergePoint  mergePoint  = new MergePoint(indexInOriginal, indexInAltered);
                MergePoint  bookMark    = NULL;
                int         newClusters = clusters;

                if (indexInOriginal != (tail.indexInOriginal() + 1))
                {
                    newClusters++;
                }

                if (indexInAltered != (tail.indexInNew() + 1))
                {
                    newClusters++;
                }

                if (head == NULL)
                {
                    head = mergePoint;
                    tail = head;
                }
                else
                {
                    tail.setNext(mergePoint);

                    bookMark    = tail;
                    tail        = tail.next();
                }

                merge(original, altered, (indexInOriginal + 1), (indexInAltered + 1), head, tail, (listSize + 1), newClusters);

                if (bookMark == NULL)
                {
                    merge(original, altered, indexInOriginal, (indexInAltered + 1), NULL, NULL, 0, 0);
                }
                else
                {
                    bookMark.setNext(NULL);

                    merge(original, altered, indexInOriginal, (indexInAltered + 1), head, bookMark, listSize, newClusters);
                }
            }
            else
            {
                merge(original, altered, indexInOriginal, (indexInAltered + 1), head, tail, listSize, clusters);
            }
        }
    }

    public static void storeMergePoints(MergePoint current, int size, int clusters)
    {
        mergeList       = new int[size][2];
        maxMerged       = size;
        minClusterSize  = clusters;

        for(int i = 0; i < size; i++)
        {
            mergeList[i][0] = current.indexInOriginal();
            mergeList[i][1] = current.indexInNew();
            current         = current.next();
        }
    }
}
</code>```

答: For replacing recursion with iteration you may consider replacing the JVM stack with a stack object that you control: java.util.Stack would be quite suitable for this. Simply push() and pop() your data on that stack on each iteration instead of having the method call itself.</p>

Body:
Greetings!

I wrote a recursive diff algorithm from scratch. It finds the "best match" between two strings such that the differences are minimized, and prints out the two strings with any differences represented in CAPS. It works fine "as is", except that it is pretty inefficient. I've been staring at it for a day and a half now, trying to find ways to make it iterative or at least reduce the stack depth that it reaches, but I'm at my wit's end and was hoping that a keen mind here would see the solution more clearly than me.

Below is the meat of the code. The MergePoint class that is referenced is just a simple "linked list" style node that contains an "index in original" integer, an "index in altered" integer, and a "next" MergePoint. The MergePoint list represents a series of indexes in each array that have been "merged". When the chain is completed, any indexes that are not represented in the chain are insertions/deletions. The NullObject object is an extension of MergePoint that, thinking back on it, wasn't strictly necessary to create and can basically be considered a regular 'null'.

Any advice/suggestions would be very deeply appreciated.

public class StringCompare
{
    public static int[][]       mergeList       = new int[0][0];
    public static MergePoint    NULL            = NullObject.getNull();
    public static int           maxMerged       = 0;
    public static int           minClusterSize  = -1;

    public static void diff(String orig, String alt)
    {
        String[] original = orig.toUpperCase().split(" ");
        String[] altered  = alt.toUpperCase().split(" ");

        for(int i = 0; i < altered.length; i++)
        {
            merge(original, altered, 0, i, NULL, NULL, 0, 0);
        }

        for(int i = 0; i < mergeList.length; i++)
        {
            or[mergeList[i][0]] = or[mergeList[i][0]].toLowerCase();
            al[mergeList[i][1]] = al[mergeList[i][1]].toLowerCase();
        }

        printStringArray(or);
        printStringArray(al);
    }

    private void printStringArray(String[] arr)
    {
        for(String word : arr)
        {
            System.out.print(word.trim() + " ");
        }

        System.out.println();
    }

    private static void merge(String[] original, String[] altered, int indexInOriginal, int indexInAltered, MergePoint head, MergePoint tail, int listSize, int clusters)
    {
        if (indexInOriginal >= original.length)
        {
            if (listSize > 0)
            {
                if (((listSize == maxMerged) && (clusters < minClusterSize)) ||
                    (listSize > maxMerged))
                {
                    storeMergePoints(head, listSize, clusters);
                }
            }
        }
        else if (indexInAltered >= altered.length)
        {
            if (tail != NULL)
            {
                merge(original, altered, (indexInOriginal + 1), (tail.indexInNew() + 1), head, tail, listSize, clusters);
            }
            else
            {
                merge(original, altered, (indexInOriginal + 1), 0, head, tail, listSize, 0);
            }
        }
        else
        {
            if(original[indexInOriginal].equals(altered[indexInAltered]))
            {
                MergePoint  mergePoint  = new MergePoint(indexInOriginal, indexInAltered);
                MergePoint  bookMark    = NULL;
                int         newClusters = clusters;

                if (indexInOriginal != (tail.indexInOriginal() + 1))
                {
                    newClusters++;
                }

                if (indexInAltered != (tail.indexInNew() + 1))
                {
                    newClusters++;
                }

                if (head == NULL)
                {
                    head = mergePoint;
                    tail = head;
                }
                else
                {
                    tail.setNext(mergePoint);

                    bookMark    = tail;
                    tail        = tail.next();
                }

                merge(original, altered, (indexInOriginal + 1), (indexInAltered + 1), head, tail, (listSize + 1), newClusters);

                if (bookMark == NULL)
                {
                    merge(original, altered, indexInOriginal, (indexInAltered + 1), NULL, NULL, 0, 0);
                }
                else
                {
                    bookMark.setNext(NULL);

                    merge(original, altered, indexInOriginal, (indexInAltered + 1), head, bookMark, listSize, newClusters);
                }
            }
            else
            {
                merge(original, altered, indexInOriginal, (indexInAltered + 1), head, tail, listSize, clusters);
            }
        }
    }

    public static void storeMergePoints(MergePoint current, int size, int clusters)
    {
        mergeList       = new int[size][2];
        maxMerged       = size;
        minClusterSize  = clusters;

        for(int i = 0; i < size; i++)
        {
            mergeList[i][0] = current.indexInOriginal();
            mergeList[i][1] = current.indexInNew();
            current         = current.next();
        }
    }
}


问:
Clear Date Selection using Primefaces Calendar
Is there any way to clear the date selection using prime faces calendar?

```<code><p:calendar pattern="MM/dd/yyyy" navigator="true" id="endDate" for="endDate"
readonlyInput="true" mindate="#{manageMarketingProgramsBean.currentDate}" showOn="button">
<f:convertDateTime pattern="MM/dd/yyyy" timeZone="America/New_York" />
</p:calendar>
</code>```

I have readonlyInput="true" because I dont want user to type the date. I force them to pick the date from the calendar, there needs to be another way to provide user the ability to clear the date selected. Please let me know how can I achieve this?

答:
This worked for me </p>

```<code><p:calendar widgetVar="calendarWidget" pattern="MM/dd/yyyy" />
<p:commandButton value="Reset" onclick="PF('calendarWidget').setDate(null)"
type="button" />
</code>```

Body:
Is there any way to clear the date selection using prime faces calendar?

<f:convertDateTime pattern="MM/dd/yyyy" timeZone="America/New_York" />

I have readonlyInput="true" because I dont want user to type the date. I force them to pick the date from the calendar, there needs to be another way to provide user the ability to clear the date selected. Please let me know how can I achieve this?

Body:
This worked for me

<p:calendar widgetVar="calendarWidget" pattern="MM/dd/yyyy" />
<p:commandButton value="Reset" onclick="PF('calendarWidget').setDate(null)"
type="button" />


问:
Select second submit button in JS
I want to use TestCafe to click on a submit button in a form. Here is what the button looks like:

```<code><button type="submit" class="btn btn-lg btn-cart pull-left">
<span class="hidden-xs hidden-sm">
     <i class="fa fa-shopping-basket"></i>
</span>
     Add To Cart
</button>
</code>```

This button is inside a form:

```<code><form name="product1" action="domain.tld/product" method="post" role="form">
</form>
</code>```

In my test I want to add the product to the cart:

```<code>test('add it', async t =>{
     await t
          .click(Selector('button[type="submit"]'))
});
</code>```

The problem is, that in the nabber is another button with the type submit. How can I use this specific button to add my product to the cart?

答:
You can use a more specific selector to execute an action with this button. For example, if this button has a class that another submit button doesn't have, use it to make a more selective selector.

Let's consider an example. Another submit button doesn't have the pull-left class. Use the following selectors Selector('button[type="submit"].pull-left') or Selector('.btn.pull-left').

If there is no difference between these buttons, you can use the Selector's method nth(index): Selector('button[type="submit"]').nth(1). See more in our documentation.

Title: Select second submit button in JS

Body:
I want to use TestCafe to click on a submit button in a form. Here is what the button looks like:

<button type="submit" class="btn btn-lg btn-cart pull-left">

     Add To Cart
</button>

This button is inside a form:

<form name="product1" action="domain.tld/product" method="post" role="form">
</form>

In my test I want to add the product to the cart:

test('add it', async t =>{
     await t
          .click(Selector('button[type="submit"]'))
});

The problem is, that in the nabber is another button with the type submit. How can I use this specific button to add my product to the cart?