问:
How to get Apache Tika (as Maven Dependency) runnning in Java for a first Test using Eclipse?
I am new to Java, Maven, Tika, Eclipse. I want to try Tika. As far as I can see I have made it to set up Tika as a Maven dependency. I added this to my projects pom.xml:

```<code><dependency>
  <groupId>org.apache.tika</groupId>
  <artifactId>tika-parsers</artifactId>
  <version>1.16</version>
</dependency>
</code>```

Then I used the following code from [https://tika.apache.org/1.16/examples.html]

```<code>public String parseToStringExample() throws IOException, SAXException, TikaException {
    Tika tika = new Tika();
    try (InputStream stream = ParsingExample.class.getResourceAsStream("test.txt")) {
        return tika.parseToString(stream);
    }
}
</code>```

I think I imported all needed libraries. Eclipse still shows me 2 Errors in the line:

```<code>ParsingExample.class.getResourceAsStream("test.txt"))
</code>```

The Errors:

Parsing Example cannot be resolved to a type

Resource Specification not allowed here for source level below 1.7

Where does "ParsingExample" come from or by what should it be replaced?

In the context of Java syntax - what does the ".class" mean, behind "ParsingExample"? Is it something like a implicit defined class? Where does ".class" come from?

Is it really necessary to change the source level to 1.7 - why?

The file test.txt has to be in the same directory as the java file where this code lives, right?!

What else do I have to consider to make these lines of code running?

Sorry, that there are so many questions. Thanks in advance.

答:
Promoting a comment to an answer. All of the code examples on the Apache Tika website are pulled from here in the Tika source tree

Specifically, the parsing example comes from this complete example file

The reference to ParsingExample.class is a reference to the example class itself that the method you're copying is taken from. You should either replace that with the name of your own class, or replace the whole line with your own preferred way of getting your input file into Tika

Body:
I am new to Java, Maven, Tika, Eclipse. I want to try Tika. As far as I can see I have made it to set up Tika as a Maven dependency. I added this to my projects pom.xml:

<dependency>
  <groupId>org.apache.tika</groupId>
  <artifactId>tika-parsers</artifactId>
  <version>1.16</version>
</dependency>

Then I used the following code from [https://tika.apache.org/1.16/examples.html]

public String parseToStringExample() throws IOException, SAXException, TikaException {
    Tika tika = new Tika();
    try (InputStream stream = ParsingExample.class.getResourceAsStream("test.txt")) {
        return tika.parseToString(stream);
    }
}

I think I imported all needed libraries. Eclipse still shows me 2 Errors in the line:

ParsingExample.class.getResourceAsStream("test.txt"))

The Errors:

Parsing Example cannot be resolved to a type

Resource Specification not allowed here for source level below 1.7

Where does "ParsingExample" come from or by what should it be replaced?

In the context of Java syntax - what does the ".class" mean, behind "ParsingExample"? Is it something like a implicit defined class? Where does ".class" come from?

Is it really necessary to change the source level to 1.7 - why?

The file test.txt has to be in the same directory as the java file where this code lives, right?!

What else do I have to consider to make these lines of code running?

Sorry, that there are so many questions. Thanks in advance.


来源: stackexchange

问:
Babel error: Class constructor Foo cannot be invoked without 'new'
I am using babel to transpile.

I have class BaseComponent which is extended by class Logger.

When I run new Logger() in the browser, I am getting this error

Class constructor BaseComponent cannot be invoked without 'new'

the code that throws this is:

```<code>var Logger = function (_BaseComponent) {
  _inherits(Logger, _BaseComponent);

  function Logger() {
    _classCallCheck(this, Logger);

    return _possibleConstructorReturn(this, Object.getPrototypeOf(Logger).call(this, "n")); //throws here
  }
</code>```

答:
Another solution is to include { exclude: ["transform-es2015-classes"] } in .babelrc

```<code>presets: [
   ["env", { exclude: ["transform-es2015-classes"] }]
]
</code>```

UPDATE: In the latest version of "env" preset plugin names have changed (e.g. it's now "transform-classes").  Use the "debug" option to inspect which plugins are included.

ContentLicense: CC BY-SA 3.0

Body:
I am using babel to transpile.

I have class BaseComponent which is extended by class Logger.

When I run new Logger() in the browser, I am getting this error

Class constructor BaseComponent cannot be invoked without 'new'

the code that throws this is:

var Logger = function (_BaseComponent) {
  _inherits(Logger, _BaseComponent);

  function Logger() {
    _classCallCheck(this, Logger);

    return _possibleConstructorReturn(this, Object.getPrototypeOf(Logger).call(this, "n")); //throws here
  }

Body:
Another solution is to include { exclude: ["transform-es2015-classes"] } in .babelrc

presets: [
   ["env", { exclude: ["transform-es2015-classes"] }]
]

UPDATE: In the latest version of "env" preset plugin names have changed (e.g. it's now "transform-classes").  Use the "debug" option to inspect which plugins are included.

ContentLicense: CC BY-SA 4.0


问:
Error: EXDEV: cross-device link not permitted, rename '/tmp/ on Ubuntu 16.04 LTS
I have problem upload file nodejs. i have read
stack1
and
stack2. but i think this different case
on terminal output like this :

```<code>> Unhandled rejection Error: EXDEV: cross-device link not permitted,
> rename '/tmp/31941-53enly.png' ->
> 'public/files/complaint/Screenshot_2016-05-01_01-16-55.png'
>     at Error (native)
>     at Object.fs.renameSync (fs.js:681:18)
>     at null.<anonymous> (/home/faris/myprojects/orchestrale-server/routes/complaintimage.js:163:20)
>     at tryCatcher (/home/faris/myprojects/orchestrale-server/node_modules/sequelize/node_modules/bluebird/js/release/util.js:16:23)
>     at Promise._settlePromiseFromHandler (/home/faris/myprojects/orchestrale-server/node_modules/sequelize/node_modules/bluebird/js/release/promise.js:502:31)
>     at Promise._settlePromise (/home/faris/myprojects/orchestrale-server/node_modules/sequelize/node_modules/bluebird/js/release/promise.js:559:18)
>     at Promise._settlePromise0 (/home/faris/myprojects/orchestrale-server/node_modules/sequelize/node_modules/bluebird/js/release/promise.js:604:10)
>     at Promise._settlePromises (/home/faris/myprojects/orchestrale-server/node_modules/sequelize/node_modules/bluebird/js/release/promise.js:683:18)
>     at Async._drainQueue (/home/faris/myprojects/orchestrale-server/node_modules/sequelize/node_modules/bluebird/js/release/async.js:138:16)
>     at Async._drainQueues (/home/faris/myprojects/orchestrale-server/node_modules/sequelize/node_modules/bluebird/js/release/async.js:148:10)
>     at Immediate.Async.drainQueues [as _onImmediate] (/home/faris/myprojects/orchestrale-server/node_modules/sequelize/node_modules/bluebird/js/release/async.js:17:14)
>     at processImmediate [as _immediateCallback] (timers.js:383:17)
</code>```

my code :

```<code>  if (_.isEmpty(req.files) == false) {
      var tp = avatar_folder+req.files.file.name;
      fs.renameSync(req.files.file.path, tp, function(err){});
      var avatar = req.files.file.name;
      }
</code>```

code work on another distro like elementary os, but when i run project on debian jessie or ubuntu 16 LTS that error result on terminal.

any body can't help ? that code just run perfectly on elementary os and arch.

答: it assisted me when working with nodejs , the concept should be the same https://stackoverflow.com/a/43206506/7878987</p>

Body:
I have problem upload file nodejs. i have read
stack1
and
stack2. but i think this different case
on terminal output like this :

> Unhandled rejection Error: EXDEV: cross-device link not permitted,
> rename '/tmp/31941-53enly.png' ->
> 'public/files/complaint/Screenshot_2016-05-01_01-16-55.png'
>     at Error (native)
>     at Object.fs.renameSync (fs.js:681:18)
>     at null.<anonymous> (/home/faris/myprojects/orchestrale-server/routes/complaintimage.js:163:20)
>     at tryCatcher (/home/faris/myprojects/orchestrale-server/node_modules/sequelize/node_modules/bluebird/js/release/util.js:16:23)
>     at Promise._settlePromiseFromHandler (/home/faris/myprojects/orchestrale-server/node_modules/sequelize/node_modules/bluebird/js/release/promise.js:502:31)
>     at Promise._settlePromise (/home/faris/myprojects/orchestrale-server/node_modules/sequelize/node_modules/bluebird/js/release/promise.js:559:18)
>     at Promise._settlePromise0 (/home/faris/myprojects/orchestrale-server/node_modules/sequelize/node_modules/bluebird/js/release/promise.js:604:10)
>     at Promise._settlePromises (/home/faris/myprojects/orchestrale-server/node_modules/sequelize/node_modules/bluebird/js/release/promise.js:683:18)
>     at Async._drainQueue (/home/faris/myprojects/orchestrale-server/node_modules/sequelize/node_modules/bluebird/js/release/async.js:138:16)
>     at Async._drainQueues (/home/faris/myprojects/orchestrale-server/node_modules/sequelize/node_modules/bluebird/js/release/async.js:148:10)
>     at Immediate.Async.drainQueues [as _onImmediate] (/home/faris/myprojects/orchestrale-server/node_modules/sequelize/node_modules/bluebird/js/release/async.js:17:14)
>     at processImmediate [as _immediateCallback] (timers.js:383:17)

my code :

  if (_.isEmpty(req.files) == false) {
      var tp = avatar_folder+req.files.file.name;
      fs.renameSync(req.files.file.path, tp, function(err){});
      var avatar = req.files.file.name;
      }

code work on another distro like elementary os, but when i run project on debian jessie or ubuntu 16 LTS that error result on terminal.

any body can't help ? that code just run perfectly on elementary os and arch.


问:
RecyclerView with start offset
I want that my first element in recycler view have offset by start list.

I try use

```<code>void onCreate(Bundle savedInstanceState){
...
    linearLayoutManager.scrollToPositionWithOffset
...
}
</code>```

But it not work. I undestand that i can use empty view how zero element in list, but it not perfect solution.

答:
I found a solution and it works great. First you need to get your recyclerviews last offset value by;

```<code>int offset = recyclerView.computeVerticalScrollOffset();
</code>```

Or you can assign your offset value. Then after you set your adapter, you can set your offset like below.

```<code>recyclerView.setAdapter(Adapter.this);
LinearLayoutManager llm = (LinearLayoutManager)
recyclerView.getLayoutManager();
llm.scrollToPositionWithOffset(0,-1*offset);
</code>```

Its mean; llm scrolling position to 0(start) and then goes down to offset.
I hope it helps!

Title: RecyclerView with start offset

Body:
I want that my first element in recycler view have offset by start list.

I try use

void onCreate(Bundle savedInstanceState){
...
    linearLayoutManager.scrollToPositionWithOffset
...
}

But it not work. I undestand that i can use empty view how zero element in list, but it not perfect solution.

Body:
I found a solution and it works great. First you need to get your recyclerviews last offset value by;

int offset = recyclerView.computeVerticalScrollOffset();

Or you can assign your offset value. Then after you set your adapter, you can set your offset like below.

recyclerView.setAdapter(Adapter.this);
LinearLayoutManager llm = (LinearLayoutManager)
recyclerView.getLayoutManager();
llm.scrollToPositionWithOffset(0,-1*offset);

Its mean; llm scrolling position to 0(start) and then goes down to offset.
I hope it helps!


问:
Saxon parsed XSL stylesheet cannot access remote resources
Trying to parse an XSLT 2.0 stylesheet with Saxon HE, getting the following error:

```<code>Error on line 44 column 168
  XTSE0165: I/O error reported by XML parser processing
  http://www.loc.gov/standards/mods/inc/mimeType.xsl: Server returned HTTP response code:
  403 for URL: http://www.loc.gov/standards/mods/inc/mimeType.xsl
</code>```

This stylesheet contains a handful of remote resources it attempts to retrieve:

```<code><xsl:include href="http://www.loc.gov/standards/mods/inc/dcmiType.xsl"/>
<xsl:include href="http://www.loc.gov/standards/mods/inc/mimeType.xsl"/>
<xsl:include href="http://www.loc.gov/standards/mods/inc/csdgm.xsl"/>
<xsl:include href="http://www.loc.gov/standards/mods/inc/forms.xsl"/>
<xsl:include href="http://www.loc.gov/standards/mods/inc/iso3166-1.xsl"/>
<xsl:include href="http://www.loc.gov/standards/mods/inc/iso639-2.xsl"/>
</code>```

However, I have confirmed that all the links are valid and be retrieved via a browser or curl.  Additionally, when I serve those files on localhost, and change the <xsl:include> accordingly, I do not get the 403 error.

My question, is there some kind Saxon or Java setting that is preventing Saxon HE from accessing resources not on localhost?

Many thanks in advance for any suggestions.

Update: I'm using pyjxslt as a server to perform the Saxon transformations, running at localhost:6767.

答:
I tried this using the doc() function from the XQuery command line, using "Charles" to monitor the HTTP traffic.

The detailed HTTP response says that the site is using Cloudflare to restrict access, and that it has refused access "based on your browser's signature".

So unless you can insert some kind of proxy to change the browser signature in the request, or persuade the owners of the site that their security policy makes no sense, you may be out of luck.

One thing I notice is that Safari includes "accept application/xml" in the HTTP request header, and Java does not. It's possible that the site has somehow been configured not to serve XML unless the request header says it will accept XML. I haven't seen this happen before, but it's something to investigate.

Incidentally, by default Saxon doesn't call the Java APIs directly to get a document; if you use the standard (default) URIResolver then this creates an InputSource object wrapping the requested URL, and the InputSource is passed to the XML parser which then calls Java to fetch the resource. I don't know which Java APIs the XML parser is actually using. But if you can find a way that works, you could bypass this by writing a URIResolver that configures an HTTP request and gets an InputStream directly.

Body:
Trying to parse an XSLT 2.0 stylesheet with Saxon HE, getting the following error:

Error on line 44 column 168
  XTSE0165: I/O error reported by XML parser processing
  http://www.loc.gov/standards/mods/inc/mimeType.xsl: Server returned HTTP response code:
  403 for URL: http://www.loc.gov/standards/mods/inc/mimeType.xsl

This stylesheet contains a handful of remote resources it attempts to retrieve:

<xsl:include href="http://www.loc.gov/standards/mods/inc/dcmiType.xsl"/>
<xsl:include href="http://www.loc.gov/standards/mods/inc/mimeType.xsl"/>
<xsl:include href="http://www.loc.gov/standards/mods/inc/csdgm.xsl"/>
<xsl:include href="http://www.loc.gov/standards/mods/inc/forms.xsl"/>
<xsl:include href="http://www.loc.gov/standards/mods/inc/iso3166-1.xsl"/>
<xsl:include href="http://www.loc.gov/standards/mods/inc/iso639-2.xsl"/>

However, I have confirmed that all the links are valid and be retrieved via a browser or curl.  Additionally, when I serve those files on localhost, and change the <xsl:include> accordingly, I do not get the 403 error.

My question, is there some kind Saxon or Java setting that is preventing Saxon HE from accessing resources not on localhost?

Many thanks in advance for any suggestions.

Update: I'm using pyjxslt as a server to perform the Saxon transformations, running at localhost:6767.


问:
FirebaseMessagingService onTaskRemoved() not called?
This is what the service in my manifest looks like at the moment,

```<code><service
        android:stopWithTask="false"
        android:name=".FcmMessagingService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>
</code>```

Yet, onTaskRemoved is still never called. I have a simple debug log which is supposed to print. I wish to have onTaskRemoved called to be able to remove notifications still being active when the app is swiped away from the active list.

答:
My experience has been that FirebaseMessagingService is very short-lived.  In the case of processing a received message, the service stops itself immediately after onMessageReceived() returns.  You can observe this by adding log output to onDestroy().

So I think it's very unlikely that the service will ever be active when you swipe the app out of the task list. And if the service is not active, onTaskRemoved() is not called.

Body:
This is what the service in my manifest looks like at the moment,

<service
        android:stopWithTask="false"
        android:name=".FcmMessagingService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>

Yet, onTaskRemoved is still never called. I have a simple debug log which is supposed to print. I wish to have onTaskRemoved called to be able to remove notifications still being active when the app is swiped away from the active list.


问:
Ebean Model class in subproject not enhanced
I'm trying to connect a simple application to two databases, the application has a subproject.
the model for the default database is in the main project while the model for the second database is in the subproject, like so;

```<code>root/app/models/MainModel
root/sub/app/mods/SubModel
</code>```

now i configure the application.conf like so;

```<code>db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play"
#db.default.user=sa
#db.default.password=""

db.sub.driver=org.postgresql.Driver
db.sub.url="jdbc:postgresql://localhost:5432/test"
db.sub.username= postgres
db.sub.password="password@1"

ebean.default = ["models.*"]
ebean.sub = ["mods.*"]
</code>```

(yes i use postgre as the second db)
and the build.sbt like so

```<code>lazy val sub = project.in(file("sub")).enablePlugins(PlayEbean, PlayEnhancer)

lazy val root = (project in file(".")).enablePlugins(PlayJava, PlayEbean)
.aggregate(sub)
.dependsOn(sub)
playEbeanModels in Compile := Seq("models.*", "mods.*")
</code>```

root/app/models/MainModel:

```<code>package models;

import java.io.Serializable;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class MainModel implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    public Integer id;

    public String name;

}
</code>```

and root/sub/app/mods/SubModel:

```<code>package mods;

import javax.persistence.Entity;
import javax.persistence.Id;

import com.avaje.ebean.Model;

@Entity
public class SubModel extends Model {

    @Id
    public Long id;

    public String name;
}
</code>```

but when i run the application i get this exception;

```<code>CreationException: Unable to create injector, see the following errors: 1)
Error injecting constructor, java.lang.IllegalStateException:
Bean class mods.SubModel is not enhanced?
</code>```

apparently the model in the root project is enhanced but the model in the sub-project is not. What am i missing? how do i get this to work?

答:
I had this problem. Half of my models were in my sub module. I put their ebean config in the application.conf of the sub module.

You should put the line below in the sub/conf/application.conf :

```<code>ebean.sub = ["mods.*"]
</code>```

and then add the line below in your sub/build.sbt :

```<code>playEbeanModels in Compile := Seq("mods.*")
</code>```

Body:
I'm trying to connect a simple application to two databases, the application has a subproject.
the model for the default database is in the main project while the model for the second database is in the subproject, like so;

root/app/models/MainModel
root/sub/app/mods/SubModel

now i configure the application.conf like so;

db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play"
#db.default.user=sa
#db.default.password=""

db.sub.driver=org.postgresql.Driver
db.sub.url="jdbc:postgresql://localhost:5432/test"
db.sub.username= postgres
db.sub.password="password@1"

ebean.default = ["models.*"]
ebean.sub = ["mods.*"]

(yes i use postgre as the second db)
and the build.sbt like so

lazy val sub = project.in(file("sub")).enablePlugins(PlayEbean, PlayEnhancer)

lazy val root = (project in file(".")).enablePlugins(PlayJava, PlayEbean)
.aggregate(sub)
.dependsOn(sub)
playEbeanModels in Compile := Seq("models.*", "mods.*")

root/app/models/MainModel:

package models;

import java.io.Serializable;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class MainModel implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    public Integer id;

    public String name;

}

and root/sub/app/mods/SubModel:

package mods;

import javax.persistence.Entity;
import javax.persistence.Id;

import com.avaje.ebean.Model;

@Entity
public class SubModel extends Model {

    @Id
    public Long id;

    public String name;
}

but when i run the application i get this exception;

CreationException: Unable to create injector, see the following errors: 1)
Error injecting constructor, java.lang.IllegalStateException:
Bean class mods.SubModel is not enhanced?

apparently the model in the root project is enhanced but the model in the sub-project is not. What am i missing? how do i get this to work?

Body:
I had this problem. Half of my models were in my sub module. I put their ebean config in the application.conf of the sub module.

You should put the line below in the sub/conf/application.conf :

ebean.sub = ["mods.*"]

and then add the line below in your sub/build.sbt :

playEbeanModels in Compile := Seq("mods.*")


问:
How to Speed up Android Studio 3.0
I just want to ask "How can I speed up my Android Studio?". Though I do own:

```<code>Dell Inspiron 15R
12GB of RAM Core i7 (N5537),
</code>```

these specs may look cool but still I am unable to working on Android Studio in Peace. As my Android Studio takes a lot of time when I reboot my machine and start the Android studio, its indexing process is way too long, the gradle build process is also way too laggy!

Even whenever I try to run my app on any device say on Virtual Device or any other real device it takes a lot of time, to switch between .java to .xml files is also way too long! For the most of times the Android Studio also stuck and hangs on different events especially on Gradle Build or refreshing the project and indexing the project files!

答:
Config + SSD made a huge difference!

Tweaking Paging Size, Clearing Temp Files and Cache do help but you wouldn't not have taken time to post here for saving a few seconds.

For marginal performance boost, We upgraded the machine and it's worth it.

Machine Specs: Alienware-i7 7820HK|16GB RAM|256GB PCie SSD|1TB HDD
Software Config: Android Studio in SSD|SDK in HDD|Project Folder in HDD

Clock Time to load Android Studio: 9s
Clock Time to create a new empty project: 20s till Gradle Build Finished
Clock Time to open an empty project: Less than 5s till Gradle Build Finished
Clock Time to open Android Studio; create a new empty project: 40s till Gradle Build Finished

If you could keep track and manage Android SDK properly, and predominantly use AS alone, we recommend an All-in-SSD approach.

Regards.

Title: How to Speed up Android Studio 3.0

Body:
I just want to ask "How can I speed up my Android Studio?". Though I do own:

Dell Inspiron 15R
12GB of RAM Core i7 (N5537),

these specs may look cool but still I am unable to working on Android Studio in Peace. As my Android Studio takes a lot of time when I reboot my machine and start the Android studio, its indexing process is way too long, the gradle build process is also way too laggy!

Even whenever I try to run my app on any device say on Virtual Device or any other real device it takes a lot of time, to switch between .java to .xml files is also way too long! For the most of times the Android Studio also stuck and hangs on different events especially on Gradle Build or refreshing the project and indexing the project files!


问:
Combine two data frames by one variable and combining columns under one main header
I want to combine two dataframes T2 and T4 by variable "Industry" and the columns of each data set with one main heading.    So in the final output table I want columns Industry, three columns of T2 under one column heading "Executive" and three other columns of T4 as sub-columns of one heading "management".

```<code>T2
                         Industry percentage_Yes percentage_No Total_responses
    1                         ALL           94 %           6 %             117
    2  Banking/Financial Services           83 %          17 %               6
    3                   Chemicals          100 %           0 %               5
    4              Consumer Goods           75 %          25 %               8
    5                      Energy           89 %          11 %               9
    6                   High Tech          100 %           0 %               8
    7       Insurance/Reinsurance          100 %           0 %              14
    8               Life Sciences          100 %           0 %              11
    9                   Logistics             --            --               3
    10            Mining & Metals             --            --               1
    11        Other Manufacturing          100 %           0 %              11
    12    Other Non-Manufacturing             --            --               3
    13         Retail & Wholesale          100 %           0 %              12
    14   Services (Non-Financial)           88 %          12 %              24
    15   Transportation Equipment             --            --               2
    16                       <NA>             --            --               0

T4
                     Industry percentage_Yes percentage_No Total_responses
1                         ALL           96 %           4 %             121
2  Banking/Financial Services           86 %          14 %               7
3                   Chemicals          100 %           0 %               5
4              Consumer Goods          100 %           0 %               8
5                      Energy          100 %           0 %               9
6                   High Tech          100 %           0 %               9
7       Insurance/Reinsurance           93 %           7 %              15
8               Life Sciences           91 %           9 %              11
9                   Logistics             --            --               3
10            Mining & Metals             --            --               1
11        Other Manufacturing          100 %           0 %              12
12    Other Non-Manufacturing             --            --               3
13         Retail & Wholesale          100 %           0 %              12
14   Services (Non-Financial)           92 %           8 %              24
15   Transportation Equipment             --            --               2
16                       <NA>             --            --               0

> dput(T2)
structure(list(Industry = c("ALL", "Banking/Financial Services",
"Chemicals", "Consumer Goods", "Energy", "High Tech", "Insurance/Reinsurance",
"Life Sciences", "Logistics", "Mining & Metals", "Other Manufacturing",
"Other Non-Manufacturing", "Retail & Wholesale", "Services (Non-Financial)",
"Transportation Equipment", NA), percentage_Yes = c("94 %", "83 %",
"100 %", "75 %", "89 %", "100 %", "100 %", "100 %", "--", "--",
"100 %", "--", "100 %", "88 %", "--", "--"), percentage_No = c("6 %",
"17 %", "0 %", "25 %", "11 %", "0 %", "0 %", "0 %", "--", "--",
"0 %", "--", "0 %", "12 %", "--", "--"), Total_responses = c(117,
6, 5, 8, 9, 8, 14, 11, 3, 1, 11, 3, 12, 24, 2, 0)), class = "data.frame", row.names = c(NA,
-16L), .Names = c("Industry", "percentage_Yes", "percentage_No",
"Total_responses"))
> dput(T4)
structure(list(Industry = c("ALL", "Banking/Financial Services",
"Chemicals", "Consumer Goods", "Energy", "High Tech", "Insurance/Reinsurance",
"Life Sciences", "Logistics", "Mining & Metals", "Other Manufacturing",
"Other Non-Manufacturing", "Retail & Wholesale", "Services (Non-Financial)",
"Transportation Equipment", NA), percentage_Yes = c("96 %", "86 %",
"100 %", "100 %", "100 %", "100 %", "93 %", "91 %", "--", "--",
"100 %", "--", "100 %", "92 %", "--", "--"), percentage_No = c("4 %",
"14 %", "0 %", "0 %", "0 %", "0 %", "7 %", "9 %", "--", "--",
"0 %", "--", "0 %", "8 %", "--", "--"), Total_responses = c(121,
7, 5, 8, 9, 9, 15, 11, 3, 1, 12, 3, 12, 24, 2, 0)), class = "data.frame", row.names = c(NA,
-16L), .Names = c("Industry", "percentage_Yes", "percentage_No",
"Total_responses"))
</code>```

I have tried tabular but then m getting Industry column 2 times:

```<code>library("tables")
st<-rbind(data.frame(T2, Employee_Level = 'Exe', what = factor(rownames(T2), levels = rownames(T2)),
             row.names= NULL, check.names = FALSE),
  data.frame(T4,Employee_Level = 'Mgmt',what = factor(rownames(T4), levels = rownames(T4)),
             row.names = NULL,check.names = FALSE))

mytable <- tabular(Heading()*what ~ Employee_Level*(`Industry`+`percentage_Yes`+`percentage_No`+`Total_responses`)*Heading()*(identity),data=st)
latex(mytable)
</code>```

答:
Here's one way using (my) huxtable package:</p>

```<code>library(huxtable)
my_data      <- cbind(T2, T4)[, c(1:4, 6:8)]
my_hux       <- as_hux(my_data, add_colnames = TRUE)
my_hux       <- insert_row(my_hux, rep("", 7))
my_hux[1, 2] <- "Executive"
my_hux[1, 5] <- "Management"
colspan(my_hux)[1, 2] <- 3
colspan(my_hux)[1, 5] <- 3
my_hux[2, 2:7] <- rep(c("% yes", "% no", "Total responses"), 2)
number_format(my_hux) <- 0

# This should look like what you want:
my_hux
</code>```

Body:
I want to combine two dataframes T2 and T4 by variable "Industry" and the columns of each data set with one main heading.    So in the final output table I want columns Industry, three columns of T2 under one column heading "Executive" and three other columns of T4 as sub-columns of one heading "management".

T2
                         Industry percentage_Yes percentage_No Total_responses
    1                         ALL           94 %           6 %             117
    2  Banking/Financial Services           83 %          17 %               6
    3                   Chemicals          100 %           0 %               5
    4              Consumer Goods           75 %          25 %               8
    5                      Energy           89 %          11 %               9
    6                   High Tech          100 %           0 %               8
    7       Insurance/Reinsurance          100 %           0 %              14
    8               Life Sciences          100 %           0 %              11
    9                   Logistics             --            --               3
    10            Mining & Metals             --            --               1
    11        Other Manufacturing          100 %           0 %              11
    12    Other Non-Manufacturing             --            --               3
    13         Retail & Wholesale          100 %           0 %              12
    14   Services (Non-Financial)           88 %          12 %              24
    15   Transportation Equipment             --            --               2
    16                       <NA>             --            --               0

T4
                     Industry percentage_Yes percentage_No Total_responses
1                         ALL           96 %           4 %             121
2  Banking/Financial Services           86 %          14 %               7
3                   Chemicals          100 %           0 %               5
4              Consumer Goods          100 %           0 %               8
5                      Energy          100 %           0 %               9
6                   High Tech          100 %           0 %               9
7       Insurance/Reinsurance           93 %           7 %              15
8               Life Sciences           91 %           9 %              11
9                   Logistics             --            --               3
10            Mining & Metals             --            --               1
11        Other Manufacturing          100 %           0 %              12
12    Other Non-Manufacturing             --            --               3
13         Retail & Wholesale          100 %           0 %              12
14   Services (Non-Financial)           92 %           8 %              24
15   Transportation Equipment             --            --               2
16                       <NA>             --            --               0

> dput(T2)
structure(list(Industry = c("ALL", "Banking/Financial Services",
"Chemicals", "Consumer Goods", "Energy", "High Tech", "Insurance/Reinsurance",
"Life Sciences", "Logistics", "Mining & Metals", "Other Manufacturing",
"Other Non-Manufacturing", "Retail & Wholesale", "Services (Non-Financial)",
"Transportation Equipment", NA), percentage_Yes = c("94 %", "83 %",
"100 %", "75 %", "89 %", "100 %", "100 %", "100 %", "--", "--",
"100 %", "--", "100 %", "88 %", "--", "--"), percentage_No = c("6 %",
"17 %", "0 %", "25 %", "11 %", "0 %", "0 %", "0 %", "--", "--",
"0 %", "--", "0 %", "12 %", "--", "--"), Total_responses = c(117,
6, 5, 8, 9, 8, 14, 11, 3, 1, 11, 3, 12, 24, 2, 0)), class = "data.frame", row.names = c(NA,
-16L), .Names = c("Industry", "percentage_Yes", "percentage_No",
"Total_responses"))
> dput(T4)
structure(list(Industry = c("ALL", "Banking/Financial Services",
"Chemicals", "Consumer Goods", "Energy", "High Tech", "Insurance/Reinsurance",
"Life Sciences", "Logistics", "Mining & Metals", "Other Manufacturing",
"Other Non-Manufacturing", "Retail & Wholesale", "Services (Non-Financial)",
"Transportation Equipment", NA), percentage_Yes = c("96 %", "86 %",
"100 %", "100 %", "100 %", "100 %", "93 %", "91 %", "--", "--",
"100 %", "--", "100 %", "92 %", "--", "--"), percentage_No = c("4 %",
"14 %", "0 %", "0 %", "0 %", "0 %", "7 %", "9 %", "--", "--",
"0 %", "--", "0 %", "8 %", "--", "--"), Total_responses = c(121,
7, 5, 8, 9, 9, 15, 11, 3, 1, 12, 3, 12, 24, 2, 0)), class = "data.frame", row.names = c(NA,
-16L), .Names = c("Industry", "percentage_Yes", "percentage_No",
"Total_responses"))

I have tried tabular but then m getting Industry column 2 times:

library("tables")
st<-rbind(data.frame(T2, Employee_Level = 'Exe', what = factor(rownames(T2), levels = rownames(T2)),
             row.names= NULL, check.names = FALSE),
  data.frame(T4,Employee_Level = 'Mgmt',what = factor(rownames(T4), levels = rownames(T4)),
             row.names = NULL,check.names = FALSE))

mytable <- tabular(Heading()*what ~ Employee_Level*(`Industry`+`percentage_Yes`+`percentage_No`+`Total_responses`)*Heading()*(identity),data=st)
latex(mytable)

Body:
Here's one way using (my) huxtable package:

library(huxtable)
my_data      <- cbind(T2, T4)[, c(1:4, 6:8)]
my_hux       <- as_hux(my_data, add_colnames = TRUE)
my_hux       <- insert_row(my_hux, rep("", 7))
my_hux[1, 2] <- "Executive"
my_hux[1, 5] <- "Management"
colspan(my_hux)[1, 2] <- 3
colspan(my_hux)[1, 5] <- 3
my_hux[2, 2:7] <- rep(c("% yes", "% no", "Total responses"), 2)
number_format(my_hux) <- 0

# This should look like what you want:
my_hux


问:
Getting TypeError: While Creating TFRecords for Image input
Creating TFrecords for Image input: as below

```<code>        char_ids_padded, char_ids_unpadded = encode_utf8_string(text)
        print("char_ids_padded:"+str(char_ids_padded))
        print("char_ids_unpadded:"+str(char_ids_unpadded))
        tf_example = tf.train.Example(features=tf.train.Features(feature={
            'image/format': _bytes_feature(b'png'),
            'image/encoded': _bytes_feature(image.tostring()),
            'image/class': _int64_feature(char_ids_padded),
            'image/unpadded_class': _int64_feature(char_ids_unpadded),
            'height': _int64_feature(image.shape[0]),
            'width': _int64_feature(image.shape[1]),
            'orig_width': _int64_feature(image.shape[1]/num_of_views),
            'image/text': _bytes_feature(text)
            }))

def _int64_feature(value):
  return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

def _bytes_feature(value):
  return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
</code>```

Output for char_ids_padded, char_ids_unpadded as below:

char_ids_padded:[47, 13, 16, 13, 16, 16, 16, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

char_ids_unpadded:[47, 13, 16, 13, 16, 16, 16, 52]

Note: char_ids_padded is in list format with type int, Still while mapping with tf.train.Features, getting error as TypeError: [47, 13, 16, 13, 16, 16, 16, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] has type "class 'list'", but expected one of: ("class 'int'",)

答:
You're already passing a list to tf.train.Int64List, so you don't need to create a new list containing the argument of _int64_feature. That is, you should try changing

```<code>tf.train.Int64List(value=[value])
</code>```

to

```<code>tf.train.Int64List(value=value)
</code>```

in the _int64_feature function.

When I run the following code, it works:

```<code>def _int64_feature(value):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=value))

char_ids_padded = [47, 13, 16, 13, 16, 16, 16, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
tf_example = tf.train.Example(features=tf.train.Features(feature={
     'image/class': _int64_feature(char_ids_padded),
}))
</code>```

Body:
Creating TFrecords for Image input: as below

        char_ids_padded, char_ids_unpadded = encode_utf8_string(text)
        print("char_ids_padded:"+str(char_ids_padded))
        print("char_ids_unpadded:"+str(char_ids_unpadded))
        tf_example = tf.train.Example(features=tf.train.Features(feature={
            'image/format': _bytes_feature(b'png'),
            'image/encoded': _bytes_feature(image.tostring()),
            'image/class': _int64_feature(char_ids_padded),
            'image/unpadded_class': _int64_feature(char_ids_unpadded),
            'height': _int64_feature(image.shape[0]),
            'width': _int64_feature(image.shape[1]),
            'orig_width': _int64_feature(image.shape[1]/num_of_views),
            'image/text': _bytes_feature(text)
            }))

def _int64_feature(value):
  return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

def _bytes_feature(value):
  return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

Output for char_ids_padded, char_ids_unpadded as below:

char_ids_padded:[47, 13, 16, 13, 16, 16, 16, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

char_ids_unpadded:[47, 13, 16, 13, 16, 16, 16, 52]

Note: char_ids_padded is in list format with type int, Still while mapping with tf.train.Features, getting error as TypeError: [47, 13, 16, 13, 16, 16, 16, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] has type "class 'list'", but expected one of: ("class 'int'",)

Body:
You're already passing a list to tf.train.Int64List, so you don't need to create a new list containing the argument of _int64_feature. That is, you should try changing

tf.train.Int64List(value=[value])

to

tf.train.Int64List(value=value)

in the _int64_feature function.

When I run the following code, it works:

def _int64_feature(value):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=value))

char_ids_padded = [47, 13, 16, 13, 16, 16, 16, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
tf_example = tf.train.Example(features=tf.train.Features(feature={
     'image/class': _int64_feature(char_ids_padded),
}))


问:
Line breaking a logical symbol
I'm relatively new to python and don't quite understand what's going on here. I have the following code:

```<code>if cell.location != (always_empty_location
                     and random.random() < self.settings['OBSTACLE_RATIO']):
</code>```

And it's broken, but if I remove the parenthesis and do a simple

```<code>and \
</code>```

on the first line, it works. I can't seem to find a solid explanation of how python treats scenario's like this. Everything online suggests this should work.

答:
This has nothing to do with line breaks, it's just that

```<code>if a != b and c < d:
</code>```

is very different from

```<code>if a != (b and c < d):
</code>```

The first condition parses as (a != b) and (c < d) whereas the second condition parses as a != (b and (c < d)).

Title: Line breaking a logical symbol

Body:
I'm relatively new to python and don't quite understand what's going on here. I have the following code:

if cell.location != (always_empty_location
                     and random.random() < self.settings['OBSTACLE_RATIO']):

And it's broken, but if I remove the parenthesis and do a simple

and \

on the first line, it works. I can't seem to find a solid explanation of how python treats scenario's like this. Everything online suggests this should work.

Body:
This has nothing to do with line breaks, it's just that

if a != b and c < d:

is very different from

if a != (b and c < d):

The first condition parses as (a != b) and (c < d) whereas the second condition parses as a != (b and (c < d)).


问:
How to update the changes in two different eclipse views programmatically
I have created two different views in RCP. Now I want to the changes done in one eclipse view to be automatically reflected in the other view.

I am completely new to RCP plugin development. Can anyone help me with the code to implement the above requirement?

答:
I suppose you use Eclipse 3 platform and, as far as I know, there are three ways of connecting workbench parts (my ref. is "Eclipse Rich Client Platform" second edition p255) :

1) To expose structural changes to other parts use the Selection service :

To register part changes use ISelectionProvider, for instance in your first view :

```<code>public void createPartControl(Composite parent) {
  int style = SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL;
  viewer = new TableViewer(parent, style);
  getSite().setSelectionProvider(viewer);
  ...
}
</code>```

To listen to changes (don't forget to unregister listener when no longer needed) use ISelectionListener, for instance in your second view :

```<code>public class ChaptersView extends ViewPart {
  private TableViewer viewer;
  ISelectionListener listener = new ISelectionListener() {
     public void selectionChanged(IWorkbenchPart part, ISelection sel) {
        if (!(sel instanceof IStructuredSelection))
           return;
        IStructuredSelection ss = (IStructuredSelection) sel;
        Object o = ss.getFirstElement();
        if (o instanceof Book)
           viewer.setInput(ss.size()==1 ? o : null);
     }
  };
  public void createPartControl(Composite parent) {
     getSite().getPage().addSelectionListener(listener);
  }
  public void dispose() {
     getSite().getPage().removeSelectionListener(listener);
  }
}
</code>```

These examples come from here.

2) To listen to part events like close, open or hide, use part listeners :

You must somewhere implement IPartListener2 and then add this listener to the parts listeners using the active page of the active workbench window :

```<code>workbenchWindow().getActivePage().addPartListener(IPartListener2);
</code>```

Don't forget to unregister listener when no longer needed :

```<code>workbenchWindow().getActivePage().removePartListener(IPartListener2);
</code>```

3) You can implement your own communication mechanism but it will probably introduce a too strong coupling between parts.

Body:
I suppose you use Eclipse 3 platform and, as far as I know, there are three ways of connecting workbench parts (my ref. is "Eclipse Rich Client Platform" second edition p255) :

1) To expose structural changes to other parts use the Selection service :

To register part changes use ISelectionProvider, for instance in your first view :

public void createPartControl(Composite parent) {
  int style = SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL;
  viewer = new TableViewer(parent, style);
  getSite().setSelectionProvider(viewer);
  ...
}

To listen to changes (don't forget to unregister listener when no longer needed) use ISelectionListener, for instance in your second view :

public class ChaptersView extends ViewPart {
  private TableViewer viewer;
  ISelectionListener listener = new ISelectionListener() {
     public void selectionChanged(IWorkbenchPart part, ISelection sel) {
        if (!(sel instanceof IStructuredSelection))
           return;
        IStructuredSelection ss = (IStructuredSelection) sel;
        Object o = ss.getFirstElement();
        if (o instanceof Book)
           viewer.setInput(ss.size()==1 ? o : null);
     }
  };
  public void createPartControl(Composite parent) {
     getSite().getPage().addSelectionListener(listener);
  }
  public void dispose() {
     getSite().getPage().removeSelectionListener(listener);
  }
}

These examples come from here.

2) To listen to part events like close, open or hide, use part listeners :

You must somewhere implement IPartListener2 and then add this listener to the parts listeners using the active page of the active workbench window :

workbenchWindow().getActivePage().addPartListener(IPartListener2);

Don't forget to unregister listener when no longer needed :

workbenchWindow().getActivePage().removePartListener(IPartListener2);

3) You can implement your own communication mechanism but it will probably introduce a too strong coupling between parts.


问:
Dynamically load additional Javascript source files with createElement();
I have to load some script source dynamically. Since I can not use jQuery and did not know about the XmlHttpRequest+eval method, I tried to do it this way:

```<code>API.prototype.initCallback = null;
API.prototype.sourceLoadCnt = 0;

API.prototype.sourceReady = function () {
    this.sourceLoadCnt--;
    if(this.sourceLoadCnt===0){
        this.initCallback();    //if all sources loaded
    }
}

API.prototype.init = function (callback) {

    this.initCallback = callback;

    var _this = this;
    var js = "../../js/";

    var script1 = document.createElement('script');
    script1.type = 'text/javascript';
    script1.src = js+'script1.js';
    this.sourceLoadCnt++;
    script1.onload = function(){ _this.sourceReady() };

    var script2 = document.createElement('script');
    script2.type = 'text/javascript';
    script2.src = js+'script2.js';
    this.sourceLoadCnt++;
    script2.onload = function(){ _this.sourceReady() };

    var css1 = document.createElement('link');
    css1.type = 'text/css';
    css1.rel = 'stylesheet';
    css1.href = 'style.css';
    css1.media = 'screen';
    this.sourceLoadCnt++;
    css1.onload = function(){ _this.sourceReady() };

    head.appendChild(script1);
    head.appendChild(script2);
    head.appendChild(css1);
};
</code>```

My problem is, that the sourceReady-function is called only once.

I still could change everything to load it via XmlHttpRequest but I am curious why my way isn't working. Does anyone have an idea?

答:
It might be because API.prototype.sourceLoadCnt should not exist, it should be an instance variable that lives on this.

The way you have coded it now will only work if you only have a single instance, and if you only have a single instance, going the oob/prototype way seems like a design failure.

ContentLicense: CC BY-SA 2.5

Body:
I have to load some script source dynamically. Since I can not use jQuery and did not know about the XmlHttpRequest+eval method, I tried to do it this way:

API.prototype.initCallback = null;
API.prototype.sourceLoadCnt = 0;

API.prototype.sourceReady = function () {
    this.sourceLoadCnt--;
    if(this.sourceLoadCnt===0){
        this.initCallback();    //if all sources loaded
    }
}

API.prototype.init = function (callback) {

    this.initCallback = callback;

    var _this = this;
    var js = "../../js/";

    var script1 = document.createElement('script');
    script1.type = 'text/javascript';
    script1.src = js+'script1.js';
    this.sourceLoadCnt++;
    script1.onload = function(){ _this.sourceReady() };

    var script2 = document.createElement('script');
    script2.type = 'text/javascript';
    script2.src = js+'script2.js';
    this.sourceLoadCnt++;
    script2.onload = function(){ _this.sourceReady() };

    var css1 = document.createElement('link');
    css1.type = 'text/css';
    css1.rel = 'stylesheet';
    css1.href = 'style.css';
    css1.media = 'screen';
    this.sourceLoadCnt++;
    css1.onload = function(){ _this.sourceReady() };

    head.appendChild(script1);
    head.appendChild(script2);
    head.appendChild(css1);
};

My problem is, that the sourceReady-function is called only once.

I still could change everything to load it via XmlHttpRequest but I am curious why my way isn't working. Does anyone have an idea?


问:
How can I list available operating system signals by name in a cross-platform way in Go?
Let's say I'm implementing the kill program in Go. I can accept numeric signals and PIDs from the commandline and send them to syscall.Kill no problem.

However, I don't know how to implement the "string" form of signal dispatch, e.g. kill -INT 12345.

The real use case is a part of a larger program that prompts the user to send kill signals; not a replacement for kill.

Question:

How can I convert valid signal names to signal numbers on any supported platform, at runtime (or at least without writing per-platform code to be run at compile time)?

What I've tried:

Keep a static map of signal names to numbers. This doesn't work in a cross-platform way (for example, different signal lists are returned by kill -l on Mac OSX versus a modern Linux versus an older Linux, for example). The only way to make this solution work in general would be to make maps for every OS, which would require me to know the behavior of every OS, and keep up to date as they add new signal support.

Shell out to the GNU kill tool and capture the signal lists from it. This is inelegant and kind of a paradox, and also requires a) being able to find kill, b) having the ability/permission to exec subprocesses, and c) being able to predict/parse the output of kill-the-binary.

Use the various Signal types' String method. This just returns strings containing the signal number, e.g. os.Signal(4).String() == "signal 4", which is not useful.

Call the private function runtime.signame, which does exactly what I want. go://linkname hacks will work, but I'm assuming that this sort of thing is frowned-upon for a reason.

Ideas/Things I Haven't Tried:

Use CGo somehow. I'd rather not venture into CGO territory for a project that is otherwise not low-level/needful of native integration at all. If that's the only option, I will, but have no idea where to start.

Use templating and code generation to build lists of signals based on external sources at compile time. This is not preferable for the same reasons as CGo.

Reflect and parse the members of syscall that start with SIG somehow. I am told that this is not possible because names are compiled away; is it possible that, for something as fundamental as signal names, there's someplace they're not compiled away?

答:
Update some time after I posted the below answer, Golang's stdlib acquired this functionality. An answer describing how to use that functionality was posted by @marco.m and accepted; the below is not recommended unless the version of Go you are using pre-dates the availability of the right tool for the job.

Since no answers were posted, I'll post the less-than-ideal solution I was able to use by "breaking into" a private signal-enumeration function inside Go's standard library.

The signame internal function can get a signal name by number on Unix and Windows. To call it, you have to use the linkname/assembler workaround. Basically, make a file in your project called empty.s or similar, with no contents, and then a function declaration like so:

```<code>//go:linkname signame runtime.signame
func signame(sig uint32) string
</code>```

Then, you can get a list of all signals known by the operating system by calling signame on an increasing number until it doesn't return a value, like so:

```<code>signum := uint32(0)
signalmap = make(map[uint32]string)
for len(signame(signum)) > 0 {
    words := strings.Fields(signame(signum))
    if words[0] == "signal"  || ! strings.HasPrefix(words[0], "SIG") {
        signalmap[signum] = ""
    } else {
        // Remove leading SIG and trailing colon.
        signalmap[signum] = strings.TrimRight(words[0][3:], ":")
    }
    signum++
}
</code>```

After that runs, signalmap will have keys for every signal that can be sent on the current operating system. It will have an empty string where Go doesn't think the OS has a name for the signal (the kill(1) may name some signals that Go won't return names for, I've found, but it's usually the higher-numbered/nonstandard ones), or a string name, e.g. "INT" where a name can be found.

This behavior is undocumented, subject to change, and may not hold true on some platforms. It would be nice if this were made public, though.

Body:
Update some time after I posted the below answer, Golang's stdlib acquired this functionality. An answer describing how to use that functionality was posted by @marco.m and accepted; the below is not recommended unless the version of Go you are using pre-dates the availability of the right tool for the job.

Since no answers were posted, I'll post the less-than-ideal solution I was able to use by "breaking into" a private signal-enumeration function inside Go's standard library.

The signame internal function can get a signal name by number on Unix and Windows. To call it, you have to use the linkname/assembler workaround. Basically, make a file in your project called empty.s or similar, with no contents, and then a function declaration like so:

//go:linkname signame runtime.signame
func signame(sig uint32) string

Then, you can get a list of all signals known by the operating system by calling signame on an increasing number until it doesn't return a value, like so:

signum := uint32(0)
signalmap = make(map[uint32]string)
for len(signame(signum)) > 0 {
    words := strings.Fields(signame(signum))
    if words[0] == "signal"  || ! strings.HasPrefix(words[0], "SIG") {
        signalmap[signum] = ""
    } else {
        // Remove leading SIG and trailing colon.
        signalmap[signum] = strings.TrimRight(words[0][3:], ":")
    }
    signum++
}

After that runs, signalmap will have keys for every signal that can be sent on the current operating system. It will have an empty string where Go doesn't think the OS has a name for the signal (the kill(1) may name some signals that Go won't return names for, I've found, but it's usually the higher-numbered/nonstandard ones), or a string name, e.g. "INT" where a name can be found.

This behavior is undocumented, subject to change, and may not hold true on some platforms. It would be nice if this were made public, though.


问:
@ngtools\webpack AOT doesn't work OR freezes at 95% emitting
I've been stuck trying to get AOT working with my Webpack app.
(@ngtools/webpack)

Can anyone help me at all?

It appears to work, however, compiler.js is still included in the bundle.
Also it is still looking for all of my .html files and getting 404 on all of the component templates.

So as far as I can tell it's not really doing the best parts of the AOT?

Can any shine any light here, I'm stuck!!

Thank you!!

答:
(I won't tell you how long it took me to get this working.) First of all, are you using Angular 4.x or 5.x? If 4.x you need to use the AotPlugin, if 5.x then use the AngularCompilerPlugin. Also if you are using 5.0 then the compiler is probably finding some errors in your templates that weren't a problem before. Those need to be corrected before it will work. It was a long time even before I could see the errors, I think because of issues in my tsconfig.json file. So make sure that is correct, and is being pointed to correctly by your AngularCompilerPlugin options. Some examples have it in your source directory, I found it was simpler to keep it in the root directory (same as webpack.config.js) and refer to it like this in the AngularCompilerPlugin options:

```<code>   tsConfigPath: "./tsconfig.ngtools.json",
</code>```

Here is a link to the possible plugin options

https://www.npmjs.com/package/@ngtools/webpack

and here are the tsconfig options that worked for me:

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist.ngtools",
    "baseUrl": ".",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "module": "es2015",
    "listEmittedFiles": true,
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  },
  "files": [
    "./src/app/app.module.ts", /* this includes all dependents */
    "src/polyfills.ts",
    "src/main.ts"
  ]
}
</code>```

Also note that you don't need or want a separate main.aot.ts file when using ngtools, it will automatically  adjust the platform-browser-dynamic version to platform-browser at compile time. Also with ngtools you don't need to reference  the AppModuleNgFactory component, this is also handled automatically.

I found it less than helpful that ngtools doesn't output intermediate files to the file system, so debugging is more difficult, but once things are working it is nice to not have to deal with the intermediate files.

Good luck!

Body:
(I won't tell you how long it took me to get this working.) First of all, are you using Angular 4.x or 5.x? If 4.x you need to use the AotPlugin, if 5.x then use the AngularCompilerPlugin. Also if you are using 5.0 then the compiler is probably finding some errors in your templates that weren't a problem before. Those need to be corrected before it will work. It was a long time even before I could see the errors, I think because of issues in my tsconfig.json file. So make sure that is correct, and is being pointed to correctly by your AngularCompilerPlugin options. Some examples have it in your source directory, I found it was simpler to keep it in the root directory (same as webpack.config.js) and refer to it like this in the AngularCompilerPlugin options:

   tsConfigPath: "./tsconfig.ngtools.json",

Here is a link to the possible plugin options

https://www.npmjs.com/package/@ngtools/webpack

and here are the tsconfig options that worked for me:

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist.ngtools",
    "baseUrl": ".",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "module": "es2015",
    "listEmittedFiles": true,
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  },
  "files": [
    "./src/app/app.module.ts", /* this includes all dependents */
    "src/polyfills.ts",
    "src/main.ts"
  ]
}

Also note that you don't need or want a separate main.aot.ts file when using ngtools, it will automatically  adjust the platform-browser-dynamic version to platform-browser at compile time. Also with ngtools you don't need to reference  the AppModuleNgFactory component, this is also handled automatically.

I found it less than helpful that ngtools doesn't output intermediate files to the file system, so debugging is more difficult, but once things are working it is nice to not have to deal with the intermediate files.

Good luck!


问:
Options for printing R output?
I am running a very time consuming chunk of code that will give an output that exceeds maxprint. I would like to be able to access the output at a later date without re-running the code.

I know there are many ways to do this, but it there a simple (one to two lines) way to do it? I would like to be able to just save the output as a .csv or something similar.

答:
Thanks for your helpful reply @S Rivero.
I think the following will work well for me:</p>

```<code>write.csv(MyData, file = "MyData.csv",row.names=FALSE)
</code>```

Title: Options for printing R output?

Body:
Thanks for your helpful reply @S Rivero.
I think the following will work well for me:

write.csv(MyData, file = "MyData.csv",row.names=FALSE)


问:
Windows API functions
Are they standard code c or c++ code? what are they?</p>

答:
The standard Windows API is a C library. Wrappers exist for other languages (C++, etc).

Just read it on wikipedia.

Title: Windows API functions


问:
How to write back end server code in Firebase
I am learning Firebase. I have learned how to read & write to Firebase Realtime Database and how to make rules for that database. I have also read about Cloud Functions.

But I'm still confused how to write my server-side code that applies some algorithm on Firebase Realtime Database and returns it to my Android app.

答:
Cloud Functions

Using Cloud Functions for Firebase lets you automatically run backend code in response to events triggered by Firebase features and HTTPS requests.

If you need a function to perform work on the database when called, you could configure a HTTP trigger to do this. For example, the below Cloud Function reads the last stored number from the database (stored at /lastNumber), adds 1 (one) to it, saves it back to the database and then returns the current value:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.nextNumber = functions.https.onRequest((req, res) => {
    var ref = admin.database().ref('/lastNumber');
    ref.transaction(function(current) {
      return (current || 0) + 1;
    }, function(error, committed, snapshot) {
      var currentNumber = snapshot.val().toString();
      console.log("Generated number: ", currentNumber);
      res.status(200).send(currentNumber);
    });
});
```

<p>Once deployed to Cloud Functions, you can call this function simply by visiting the HTTPS endpoint for it (where <code><region></code> is your region & <code><project-id></code> is your project ID):</p>

```https://<region>-<project-id>.cloudfunctions.net/nextNumber
```

<p>There are a whole host of other examples available on the Firebase Functions Samples repository which you can browse & use.</p>

<hr>

<h2>Realtime Database</h2>

<p>The Firebase Realtime Database is known as NoSQL which means that there are no direct relationships or foreign key constraints and therefore it is suggested that you employ a process of denormalization when storing data.</p>

<p>The documentation goes into detail on the best practices for structuring your data and the most important thing is to avoid nesting data, and instead flatten data structures as much as possible to create data that scales.</p>

<p>The basic premise here is that you want to avoid downloading all data from the database when you only need to obtain a select number of items, but likewise have the ability to link items together, much like you can in a relational database. From the documentation on data fanout:</p>

<blockquote>
  <p>Consider, for example, a two-way relationship between users and groups. Users can belong to a group, and groups comprise a list of users. When it comes time to decide which groups a user belongs to, things get complicated.</p>

  <p>What's needed is an elegant way to list the groups a user belongs to and fetch only data for those groups. An index of groups can help a great deal here:</p>

```// An index to track Ada's memberships
{
  "users": {
    "alovelace": {
      "name": "Ada Lovelace",
      // Index Ada's groups in her profile
      "groups": {
         // the value here doesn't matter, just that the key exists
         "techpioneers": true,
         "womentechmakers": true
      }
    },
    ...
  },
  "groups": {
    "techpioneers": {
      "name": "Historical Tech Pioneers",
      "members": {
        "alovelace": true,
        "ghopper": true,
        "eclarke": true
      }
    },
    ...
  }
}
```
</blockquote>

<p>Duplicating of data and using indexes like this is a suggested pattern for these types of databases. That's why there are functions available that allow you to perform multi-location writes in order to simplify the denormalization process.</p>

<p>For example in Android, with the above database structure, you could easily insert a new user (with username <code>testuser</code>) and add them to the <code>techpioneers</code> group in a single operation:</p>

```DatabaseReference database = FirebaseDatabase.getInstance().getReference();
HashMap<String, Object> data = new HashMap<>();

// Build the new data using location paths
data.put("/users/testuser/name", "Test User");
data.put("/users/testuser/groups/techpioneers", true)
data.put("/groups/techpioneers/members/testuser", true);

// Save this new data all at once
database.updateChildren(data);
```

Firebase have published a number of samples, examples and code labs to help you get started.

Body:
Cloud Functions

Using Cloud Functions for Firebase lets you automatically run backend code in response to events triggered by Firebase features and HTTPS requests.

If you need a function to perform work on the database when called, you could configure a HTTP trigger to do this. For example, the below Cloud Function reads the last stored number from the database (stored at /lastNumber), adds 1 (one) to it, saves it back to the database and then returns the current value:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.nextNumber = functions.https.onRequest((req, res) => {
    var ref = admin.database().ref('/lastNumber');
    ref.transaction(function(current) {
      return (current || 0) + 1;
    }, function(error, committed, snapshot) {
      var currentNumber = snapshot.val().toString();
      console.log("Generated number: ", currentNumber);
      res.status(200).send(currentNumber);
    });
});

Once deployed to Cloud Functions, you can call this function simply by visiting the HTTPS endpoint for it (where <region> is your region & <project-id> is your project ID):

https://<region>-<project-id>.cloudfunctions.net/nextNumber

There are a whole host of other examples available on the Firebase Functions Samples repository which you can browse & use.

Realtime Database

The Firebase Realtime Database is known as NoSQL which means that there are no direct relationships or foreign key constraints and therefore it is suggested that you employ a process of denormalization when storing data.

The documentation goes into detail on the best practices for structuring your data and the most important thing is to avoid nesting data, and instead flatten data structures as much as possible to create data that scales.

The basic premise here is that you want to avoid downloading all data from the database when you only need to obtain a select number of items, but likewise have the ability to link items together, much like you can in a relational database. From the documentation on data fanout:

Consider, for example, a two-way relationship between users and groups. Users can belong to a group, and groups comprise a list of users. When it comes time to decide which groups a user belongs to, things get complicated.

What's needed is an elegant way to list the groups a user belongs to and fetch only data for those groups. An index of groups can help a great deal here:

// An index to track Ada's memberships
{
  "users": {
    "alovelace": {
      "name": "Ada Lovelace",
      // Index Ada's groups in her profile
      "groups": {
         // the value here doesn't matter, just that the key exists
         "techpioneers": true,
         "womentechmakers": true
      }
    },
    ...
  },
  "groups": {
    "techpioneers": {
      "name": "Historical Tech Pioneers",
      "members": {
        "alovelace": true,
        "ghopper": true,
        "eclarke": true
      }
    },
    ...
  }
}

Duplicating of data and using indexes like this is a suggested pattern for these types of databases. That's why there are functions available that allow you to perform multi-location writes in order to simplify the denormalization process.

For example in Android, with the above database structure, you could easily insert a new user (with username testuser) and add them to the techpioneers group in a single operation:

DatabaseReference database = FirebaseDatabase.getInstance().getReference();
HashMap<String, Object> data = new HashMap<>();

// Build the new data using location paths
data.put("/users/testuser/name", "Test User");
data.put("/users/testuser/groups/techpioneers", true)
data.put("/groups/techpioneers/members/testuser", true);

// Save this new data all at once
database.updateChildren(data);

Firebase have published a number of samples, examples and code labs to help you get started.


问:
COPY . . command in Dockerfile for ASP.NET
The Visual Studio tooling for Docker creates a Dockerfile for ASP.NET projects containing a COPY . . command as below:

```<code>WORKDIR /src
COPY *.sln ./
...
COPY . .
</code>```

From what I've read, the <src> parameter is relative to the context, so isn't affected by the WORKDIR /src command. The <dest> however is relative to the WORKDIR so will be pointing at /src.

Is this command just bringing over the remaining files from the root for packaging (docker-compose.yml, .dockerignore, etc.)? If so, then why is this done ahead of the RUN dotnet build... command?

Full Dockerfile below:

```<code>FROM microsoft/aspnetcore:2.0 AS base
WORKDIR /app
EXPOSE 80

FROM microsoft/aspnetcore-build:2.0 AS build
WORKDIR /src
COPY *.sln ./
COPY MyProject/MyProject.csproj MyProject/
RUN dotnet restore
COPY . . # The line mentioned above
WORKDIR /src/MyProject
RUN dotnet build -c Release -o /app

FROM build AS publish
RUN dotnet publish -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "MyProject.dll"]
</code>```

答:
Some more pointers on the above from Scott Hanselman: https://www.hanselman.com/blog/OptimizingASPNETCoreDockerImageSizes.aspx

PRO TIP: Docker is smart about making intermediate images and doing the least work, but it's useful if we (the authors) do the right thing as well to help it out.

For example, see where we COPY the .csproj over and then do a "dotnet restore"? Often you'll see folks do a "COPY . ." and then do a restore. That doesn't allow Docker to detect what's changed and you'll end up paying for the restore on EVERY BUILD.

By making this two steps - copy the project, restore, copy the code, this means your "dotnet restore" intermediate step will be cached by Docker and things will be WAY faster.

Body:
The Visual Studio tooling for Docker creates a Dockerfile for ASP.NET projects containing a COPY . . command as below:

WORKDIR /src
COPY *.sln ./
...
COPY . .

From what I've read, the <src> parameter is relative to the context, so isn't affected by the WORKDIR /src command. The <dest> however is relative to the WORKDIR so will be pointing at /src.

Is this command just bringing over the remaining files from the root for packaging (docker-compose.yml, .dockerignore, etc.)? If so, then why is this done ahead of the RUN dotnet build... command?

Full Dockerfile below:

FROM microsoft/aspnetcore:2.0 AS base
WORKDIR /app
EXPOSE 80

FROM microsoft/aspnetcore-build:2.0 AS build
WORKDIR /src
COPY *.sln ./
COPY MyProject/MyProject.csproj MyProject/
RUN dotnet restore
COPY . . # The line mentioned above
WORKDIR /src/MyProject
RUN dotnet build -c Release -o /app

FROM build AS publish
RUN dotnet publish -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "MyProject.dll"]


问:
Is there a simple CLI command to copy just the speed of a SELECT statement into a text file (without the data) in MySQL?
Let's say I run:

```<code>CREATE TABLE t1 AS
SELECT ssn, title
FROM employees
WHERE title = "Dictator"
</code>```

I want to automatically save into a text file:

```<code>Query OK, 1118933 rows affected (3.84 sec)
Records: 1118933  Duplicates: 0  Warnings: 0
</code>```

Bonus points if you can also save the query above it :)!

```<code>CREATE TABLE t1 AS
SELECT ssn, title
FROM employees
WHERE title = "Dictator"

Query OK, 1118933 rows affected (3.84 sec)
Records: 1118933  Duplicates: 0  Warnings: 0
</code>```

答:
You can use the tee builtin command in the mysql client.

I tested this on MacOS:

```<code>mysql> tee out
Logging to file 'out'

mysql> create table test.mytable as select sleep(2);
Query OK, 1 row affected (2.09 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> exit;
Bye

$ cat out
mysql> create table test.mytable as select sleep(2);
Query OK, 1 row affected (2.09 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql>
</code>```

Body:
Let's say I run:

CREATE TABLE t1 AS
SELECT ssn, title
FROM employees
WHERE title = "Dictator"

I want to automatically save into a text file:

Query OK, 1118933 rows affected (3.84 sec)
Records: 1118933  Duplicates: 0  Warnings: 0

Bonus points if you can also save the query above it :)!

CREATE TABLE t1 AS
SELECT ssn, title
FROM employees
WHERE title = "Dictator"

Query OK, 1118933 rows affected (3.84 sec)
Records: 1118933  Duplicates: 0  Warnings: 0

Body:
You can use the tee builtin command in the mysql client.

I tested this on MacOS:

mysql> tee out
Logging to file 'out'

mysql> create table test.mytable as select sleep(2);
Query OK, 1 row affected (2.09 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> exit;
Bye

$ cat out
mysql> create table test.mytable as select sleep(2);
Query OK, 1 row affected (2.09 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql>


问:
Asynchronous DNS look-ups using NodeJS
I'm trying to write a script in NodeJS to asynchronously do many DNS look-ups (to check blacklists on an IP address)

Here is my current attempt:

```<code>const dns = require('dns');

RBLs = [
    'b.barracudacentral.org',
    'cbl.abuseat.org',
    'http.dnsbl.sorbs.net',
    'misc.dnsbl.sorbs.net',
    'socks.dnsbl.sorbs.net',
    'web.dnsbl.sorbs.net',
];

var testIP = "IP.ADDRESS";

console.time("exetime");
var RBLResults = {};

var RBLCallback = function(err, result, RBL){
  if(typeof result !== "undefined" && result.length > 0){
    console.log("LISTED on " + RBL);
  }else{
    console.log(" Not listed on " + RBL);
  }
};

RBLs.forEach(function(RBL){
  dns.lookup(testIP + '.' + RBL, function(err, result){
    RBLCallback(err,result,RBL);
  });
});
</code>```

As far as I understand, this should asynchronously start all the DNS lookups. However, the longer the list gets, the more clear it is that the DNS requests are not happening at the same time. (I'm trying to check 106 blacklists at once.)

Am I hitting some limitation with how many DNS lookups I can do at once? The order that the results comes in almost never changes, so it seems like they are not happening asynchronously. The last one in the list always takes much much longer to come in than the first.

The amount of time it takes to complete is really variable, going from 10 seconds to 100+ seconds.

答:
I found my issue in the nodeJS documentation for dns:

Though the call to dns.lookup() will be asynchronous from JavaScript's
  perspective, it is implemented as a synchronous call to getaddrinfo(3)
  that runs on libuv's threadpool. This can have surprising negative
  performance implications for some applications, see the
  UV_THREADPOOL_SIZE documentation for more information.

https://nodejs.org/docs/latest/api/dns.html#dns_implementation_considerations

So from the Javascript side of things, it did appear to be working asynchronously, but it actually wasn't.

To make the DNS look ups happen asynchronously, I just replaced dns.lookup with dns.resolve().

I instantly started getting results that actually looked asynchronous. (results started actually coming back in different orders than the look ups were starting in)

Title: Asynchronous DNS look-ups using NodeJS

Body:
I'm trying to write a script in NodeJS to asynchronously do many DNS look-ups (to check blacklists on an IP address)

Here is my current attempt:

const dns = require('dns');

RBLs = [
    'b.barracudacentral.org',
    'cbl.abuseat.org',
    'http.dnsbl.sorbs.net',
    'misc.dnsbl.sorbs.net',
    'socks.dnsbl.sorbs.net',
    'web.dnsbl.sorbs.net',
];

var testIP = "IP.ADDRESS";

console.time("exetime");
var RBLResults = {};

var RBLCallback = function(err, result, RBL){
  if(typeof result !== "undefined" && result.length > 0){
    console.log("LISTED on " + RBL);
  }else{
    console.log(" Not listed on " + RBL);
  }
};

RBLs.forEach(function(RBL){
  dns.lookup(testIP + '.' + RBL, function(err, result){
    RBLCallback(err,result,RBL);
  });
});

As far as I understand, this should asynchronously start all the DNS lookups. However, the longer the list gets, the more clear it is that the DNS requests are not happening at the same time. (I'm trying to check 106 blacklists at once.)

Am I hitting some limitation with how many DNS lookups I can do at once? The order that the results comes in almost never changes, so it seems like they are not happening asynchronously. The last one in the list always takes much much longer to come in than the first.

The amount of time it takes to complete is really variable, going from 10 seconds to 100+ seconds.


问:
Code Analysis Check-In Policy Not Enforce To Clean Code Analysis Warning
I have got problem with Code analysis policy.

Must code analysis policy enforce users to fix code analysis warnings before check-in? If they don't, policy failure occurs. Is it wrong?

But when i am trying to check-in TFS my codes with code analysis warnings, i don't get any policy failures about this.

Is it normal?

答: Do you see check-in policy failure for CA errors?  If not, then you would seem to have a problem.  However, if you are seeing failures for errors but not for warnings, you are experiencing the expected behaviour.  If you wish to prevent a check-in when a given rule fails, you must set violations of that rule to be treated as errors instead of as warnings.  For Visual Studio 2010, this can most easily be done by editing your target CA ruleset.</p>


问:
Arules Subset Transactions Matching LHS of Rule
When I attempt to subset transactions with arules it returns the entire transaction database/item matrix.

I've referenced the following post, but it doesn't seem to work correctly: R arules - subset of transactions that match a rule

Any hints as to where I am going wrong?

```<code>require(arules)
data("Adult")
## Mine association rules.
rules <- apriori(Adult,
                 parameter = list(supp = 0.5, conf = 0.9, target = "rules", minlen = 2))
summary(rules)
sub_rules <- rules[1]
inspect(sub_rules)
sub_trans <- subset(Adult, items %in% lhs(sub_rules))
</code>```

答:
I think your code should work and this is a bug in arules. For now you can do the following:

```<code>subset(Adult, items %in% unlist(as(lhs(sub_rules), "list")))
</code>```

It basically translates the item in the LHS into a character string.

It will be fixed in the next release (arules_1.5-5).

Body:
When I attempt to subset transactions with arules it returns the entire transaction database/item matrix.

I've referenced the following post, but it doesn't seem to work correctly: R arules - subset of transactions that match a rule

Any hints as to where I am going wrong?

require(arules)
data("Adult")
## Mine association rules.
rules <- apriori(Adult,
                 parameter = list(supp = 0.5, conf = 0.9, target = "rules", minlen = 2))
summary(rules)
sub_rules <- rules[1]
inspect(sub_rules)
sub_trans <- subset(Adult, items %in% lhs(sub_rules))

Body:
I think your code should work and this is a bug in arules. For now you can do the following:

subset(Adult, items %in% unlist(as(lhs(sub_rules), "list")))

It basically translates the item in the LHS into a character string.

It will be fixed in the next release (arules_1.5-5).


问:
IBM Cloud Private 2.1.0 CE - Hostname should be resolved to a valid IP address
I'm trying to install IBM Cloud Private on a VM. I've created master, proxy, and worker nodes and I'm at the last stage installing the ICP. However, I'm having a problem with the hostnames. The errors are shown below:

The error is below:

```<code>TASK [check : Validating Hostname is resolvable]
*******************************************************************
skipping: [172.16.22.190]
fatal: [172.16.22.82] => Hostname should be resolved to a valid IP address
fatal: [172.16.22.81] => Hostname should be resolved to a valid IP address

NO MORE HOSTS LEFT
********************************************************************************

NO MORE HOSTS LEFT
********************************************************************************

PLAY RECAP
********************************************************************************
172.16.22.190              : ok=4    changed=3    unreachable=0    failed=0
172.16.22.81               : ok=4    changed=3    unreachable=0    failed=1
172.16.22.82               : ok=4    changed=3    unreachable=0    failed=1

Playbook run took 0 days, 0 hours, 0 minutes, 4 seconds
</code>```

My /etc/hosts file:

```<code>172.16.22.190   icp
172.16.22.81    proxy
172.16.22.82    worker

# The following lines are desirable for IPv6 capable hosts
::1     localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
</code>```

My cluster hosts file:

```<code>[master]
172.16.22.190

[worker]
172.16.22.82

[proxy]
172.16.22.81

#[management]
#4.4.4.4
</code>```

All nodes see and ping each other and I'm using Ubuntu.

答:
You haven't defined a master in the icp hosts file.

The host file needs to be updated on each node, not just master.

My working icp hosts  and /etc/hosts and look like this, respectively:

icp hosts file:

```<code>[master]
10.121.9.226

[worker]
10.143.76.132
10.143.76.134

[proxy]
10.121.9.226

#[management]
#4.4.4.4
</code>```

and

```<code>10.121.9.226    icpdemo1.xxx.com    icpdemo1
10.143.76.132   icpdemo2.xxx.com    icpdemo2
10.143.76.134   icpdemo3.xxx.com    icpdemo3
</code>```

Body:
I'm trying to install IBM Cloud Private on a VM. I've created master, proxy, and worker nodes and I'm at the last stage installing the ICP. However, I'm having a problem with the hostnames. The errors are shown below:

The error is below:

TASK [check : Validating Hostname is resolvable]
*******************************************************************
skipping: [172.16.22.190]
fatal: [172.16.22.82] => Hostname should be resolved to a valid IP address
fatal: [172.16.22.81] => Hostname should be resolved to a valid IP address

NO MORE HOSTS LEFT
********************************************************************************

NO MORE HOSTS LEFT
********************************************************************************

PLAY RECAP
********************************************************************************
172.16.22.190              : ok=4    changed=3    unreachable=0    failed=0
172.16.22.81               : ok=4    changed=3    unreachable=0    failed=1
172.16.22.82               : ok=4    changed=3    unreachable=0    failed=1

Playbook run took 0 days, 0 hours, 0 minutes, 4 seconds

My /etc/hosts file:

172.16.22.190   icp
172.16.22.81    proxy
172.16.22.82    worker

# The following lines are desirable for IPv6 capable hosts
::1     localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

My cluster hosts file:

[master]
172.16.22.190

[worker]
172.16.22.82

[proxy]
172.16.22.81

#[management]
#4.4.4.4

All nodes see and ping each other and I'm using Ubuntu.

Body:
You haven't defined a master in the icp hosts file.

The host file needs to be updated on each node, not just master.

My working icp hosts  and /etc/hosts and look like this, respectively:

icp hosts file:

[master]
10.121.9.226

[worker]
10.143.76.132
10.143.76.134

[proxy]
10.121.9.226

#[management]
#4.4.4.4

and

10.121.9.226    icpdemo1.xxx.com    icpdemo1
10.143.76.132   icpdemo2.xxx.com    icpdemo2
10.143.76.134   icpdemo3.xxx.com    icpdemo3


问:
Rails query subclasses and limit one each
I have an artifacts table that holds downloaded files. Each type holds different data.

```<code>class Artifact < ActiveRecord::Base
end

class ForecastArtifact < Artifact
end

class ChargebackArtifact < Artifact
end

class CatalogArtifact < Artifact
end
</code>```

For a single account, I am querying the MOST RECENT of each artifact type:

```<code>  artifact_types = Artifact.subclasses.map(&:to_s)

  artifacts_for_account = artifact_types.map do |type|
    @account.artifacts
            .where(type: type)
            .order("valid_as_of DESC")
            .limit(1).first
            .as_json({only: [:id, :account_id, :type]})
  end
</code>```

unfortunately this does N queries.

Is there a single query you would do for this? a more rails-style of solving this problem?

答:
If you're using PostgreSQL, you can use DISTINCT ON to solve this:

```<code>>> a = Account.last
  Account Load (0.4ms)  SELECT  "accounts".* FROM "accounts" ORDER BY "accounts"."id" DESC LIMIT $1  [["LIMIT", 1]]
=> #<Account id: 1, created_at: "2017-11-17 17:16:03", updated_at: "2017-11-17 17:16:03">

>> a.artifacts.select("distinct on (type) valid_as_of, type, id").group(:type, :valid_as_of, :id).order(:type, valid_as_of: :desc)
  Artifact Load (0.6ms)  SELECT  distinct on (type) valid_as_of, type, id FROM "artifacts" WHERE "artifacts"."account_id" = $1 GROUP BY "artifacts"."type", "artifacts"."valid_as_of", "artifacts"."id" ORDER BY "artifacts"."type" ASC, "artifacts"."valid_as_of" DESC LIMIT $2  [["account_id", 1], ["LIMIT", 11]]
=> #<ActiveRecord::AssociationRelation [#<ChargebackArtifact id: 22, type: "ChargebackArtifact", valid_as_of: "2017-11-17 17:06:03">, #<ForecastArtifact id: 21, type: "ForecastArtifact", valid_as_of: "2017-11-17 17:11:03">]>
</code>```

This requires only one query for each account.

Body:
I have an artifacts table that holds downloaded files. Each type holds different data.

class Artifact < ActiveRecord::Base
end

class ForecastArtifact < Artifact
end

class ChargebackArtifact < Artifact
end

class CatalogArtifact < Artifact
end

For a single account, I am querying the MOST RECENT of each artifact type:

  artifact_types = Artifact.subclasses.map(&:to_s)

  artifacts_for_account = artifact_types.map do |type|
    @account.artifacts
            .where(type: type)
            .order("valid_as_of DESC")
            .limit(1).first
            .as_json({only: [:id, :account_id, :type]})
  end

unfortunately this does N queries.

Is there a single query you would do for this? a more rails-style of solving this problem?

Body:
If you're using PostgreSQL, you can use DISTINCT ON to solve this:

>> a = Account.last
  Account Load (0.4ms)  SELECT  "accounts".* FROM "accounts" ORDER BY "accounts"."id" DESC LIMIT $1  [["LIMIT", 1]]
=> #<Account id: 1, created_at: "2017-11-17 17:16:03", updated_at: "2017-11-17 17:16:03">

>> a.artifacts.select("distinct on (type) valid_as_of, type, id").group(:type, :valid_as_of, :id).order(:type, valid_as_of: :desc)
  Artifact Load (0.6ms)  SELECT  distinct on (type) valid_as_of, type, id FROM "artifacts" WHERE "artifacts"."account_id" = $1 GROUP BY "artifacts"."type", "artifacts"."valid_as_of", "artifacts"."id" ORDER BY "artifacts"."type" ASC, "artifacts"."valid_as_of" DESC LIMIT $2  [["account_id", 1], ["LIMIT", 11]]
=> #<ActiveRecord::AssociationRelation [#<ChargebackArtifact id: 22, type: "ChargebackArtifact", valid_as_of: "2017-11-17 17:06:03">, #<ForecastArtifact id: 21, type: "ForecastArtifact", valid_as_of: "2017-11-17 17:11:03">]>

This requires only one query for each account.


问:
How to turn off hover with Jquery?
I have a keyframe animation that lasts 6 seconds. What I want is : Every time I click on '.box', wait animation end (6 seconds),

```<code>$('.box').click(function() {
        $('.content').addClass("my-animation"); // this animation last 6 seconds
    });
</code>```

then activate this hover fonction :

```<code> $('.content').hover(function() {
// ... specific animation
}, function() {
// ...
});
</code>```

In other words I want to "turn off" the hover function only when #content is animated, because if I hover on my content while "my-animation" is running, it cancels.

EDIT html :

```<code><p class="box">see</p>
<p class="content faconC button-p"> title </p>
</code>```

答:
Just add a variable to prevent the hover.  No need for unbinding/rebinding..

$(document).ready(() => {
      var isAnimating = false;

      $('.box').on('click', function() {
        isAnimating = true;

        $('.content').addClass("my-animation"); // this animation last 6 seconds
        setTimeout(() => { isAnimating = false; }, 6000);
      });

      $('.content').hover(function()  {
        if (isAnimating) return;
        $(this).addClass('border-green');
      }, function() {
        if (isAnimating) return;
        // do something else...
        $(this).removeClass('border-green');
      });
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box, .content{
  display: block;
  width: 100px;
  height: 50px;
  border: 5px solid red;
  transition-duration: 6s;
  transition-property: transform;
}
.content { border-color: blue; }

.my-animation{
  transform:rotate(360deg);
}

.border-green { border-color: green; }</code>```

Box

Title
```

If you have multiple .box on the screen let me know, I'll update the answer to work with multiple .box and .content objects.

Title: How to turn off hover with Jquery?

Body:
I have a keyframe animation that lasts 6 seconds. What I want is : Every time I click on '.box', wait animation end (6 seconds),

$('.box').click(function() {
        $('.content').addClass("my-animation"); // this animation last 6 seconds
    });

then activate this hover fonction :

 $('.content').hover(function() {
// ... specific animation
}, function() {
// ...
});

In other words I want to "turn off" the hover function only when #content is animated, because if I hover on my content while "my-animation" is running, it cancels.

EDIT html :

see

 title

Body:
Just add a variable to prevent the hover.  No need for unbinding/rebinding..

$(document).ready(() => {
      var isAnimating = false;

      $('.box').on('click', function() {
        isAnimating = true;

        $('.content').addClass("my-animation"); // this animation last 6 seconds
        setTimeout(() => { isAnimating = false; }, 6000);
      });

      $('.content').hover(function()  {
        if (isAnimating) return;
        $(this).addClass('border-green');
      }, function() {
        if (isAnimating) return;
        // do something else...
        $(this).removeClass('border-green');
      });
    });

.box, .content{
  display: block;
  width: 100px;
  height: 50px;
  border: 5px solid red;
  transition-duration: 6s;
  transition-property: transform;
}
.content { border-color: blue; }

.my-animation{
  transform:rotate(360deg);
}

.border-green { border-color: green; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p class="box">Box</p>
<p class="content">Title</p>

If you have multiple .box on the screen let me know, I'll update the answer to work with multiple .box and .content objects.


问:
API to read, write and manipulate msword files
I want to write some java code to read, write, edit and do other things with sets of Microsoft Word files (different Word versions). What is the best API for this, and how do I get started?
P.S. I searched StackOverflow and found that this question has been asked before, but several years ago. I would like to know the best available API today. Thanks.</p>

答:
Check out apache POI : https://poi.apache.org/

As quoted on their website.. "Apache POI - the Java API for Microsoft Documents"

Personally I have only used this for EXCEL spreadsheet manipulation, but it does support word documents as well...

The best part is it's open source and completely free!


问:
PHP Composer - Unable to install composer on macOS Sierra
I'm trying to install composer running the command provided on the getcomposer.org/download documentation site:

```<code>php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('SHA384', 'composer-setup.php') === 'e115a8dc7871f15d853148a7fbac7da27d6c0030b848d9b3dc09e2a0388afed865e6a3d6b3c0fad45c48e2b5fc1196ae') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"
</code>```

But I get an error message saying:

```<code>Warning: copy(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed in Command line code on line 1

Warning: copy(): Failed to enable crypto in Command line code on line 1

Warning: copy(https://getcomposer.org/installer): failed to open stream: operation failed in Command line code on line 1
Yoshihiros-MacBook-Pro:~ yoshihiro$ php -r "if (hash_file('SHA384', 'composer-setup.php') === 'e115a8dc7871f15d853148a7fbac7da27d6c0030b848d9b3dc09e2a0388afed865e6a3d6b3c0fad45c48e2b5fc1196ae') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

Warning: hash_file(composer-setup.php): failed to open stream: No such file or directory in Command line code on line 1
Installer corrupt
Warning: unlink(composer-setup.php): No such file or directory in Command line code on line 1

Yoshihiros-MacBook-Pro:~ yoshihiro$ php composer-setup.php
Could not open input file: composer-setup.php
</code>```

I'm also trying to install it globally but I can't get out of this message. Please help D:

答: You can also just put composer.phar (which is what you end up with after you do the install) wherever you want and create a symlink in /usr/local/bin/composer to it using ln -s

Body:
I'm trying to install composer running the command provided on the getcomposer.org/download documentation site:

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('SHA384', 'composer-setup.php') === 'e115a8dc7871f15d853148a7fbac7da27d6c0030b848d9b3dc09e2a0388afed865e6a3d6b3c0fad45c48e2b5fc1196ae') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"

But I get an error message saying:

Warning: copy(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed in Command line code on line 1

Warning: copy(): Failed to enable crypto in Command line code on line 1

Warning: copy(https://getcomposer.org/installer): failed to open stream: operation failed in Command line code on line 1
Yoshihiros-MacBook-Pro:~ yoshihiro$ php -r "if (hash_file('SHA384', 'composer-setup.php') === 'e115a8dc7871f15d853148a7fbac7da27d6c0030b848d9b3dc09e2a0388afed865e6a3d6b3c0fad45c48e2b5fc1196ae') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

Warning: hash_file(composer-setup.php): failed to open stream: No such file or directory in Command line code on line 1
Installer corrupt
Warning: unlink(composer-setup.php): No such file or directory in Command line code on line 1

Yoshihiros-MacBook-Pro:~ yoshihiro$ php composer-setup.php
Could not open input file: composer-setup.php

I'm also trying to install it globally but I can't get out of this message. Please help D:


问:
Jackson wrongly ignoring unknown fields by default
I have a pretty simple REST API project using Spring Boot 1.5.7 and Jackson 2.8.

Problem

I want Jackson to complain and raise an exception if there is an unknown field in the request. Although I have not set up anything telling it to ignore them, it simply ignores it and I do not know why.

Request:

```<code>{
  "appId":1,
  "version":"1.0",
  "status":true,
  "locked":false,
  "field": "it is ignored, but it must not be"
}
</code>```

Requet method

```<code>@PutMapping
public ResponseEntity<?> updateAppToggle(@RequestBody AppToggleUpdateRequest request) {
   AppToggle updatedAppToggle = service.update(request);
   return new ResponseEntity<AppToggleResponse>
       (AppToggleResponse.fillResponse(updatedAppToggle), HttpStatus.OK);
   }
</code>```

Request class

```<code>@Data
public class AppToggleUpdateRequest {

   @NotNull
   @Getter
   private Long appId;

   @NotNull
   @Getter
   private String version;

   private Boolean status;

   private Boolean locked;
}
</code>```

My application.properties does not contain anything special, just datasource and a few stuff for H2 in-memory database.

I really do not know what is going on. Any help would be truly appreciated.

答:
I fixed my application adding the following to the application.properties file:</p>

```<code>spring.jackson.deserialization.FAIL_ON_UNKNOWN_PROPERTIES=true
</code>```

Body:
I have a pretty simple REST API project using Spring Boot 1.5.7 and Jackson 2.8.

Problem

I want Jackson to complain and raise an exception if there is an unknown field in the request. Although I have not set up anything telling it to ignore them, it simply ignores it and I do not know why.

Request:

{
  "appId":1,
  "version":"1.0",
  "status":true,
  "locked":false,
  "field": "it is ignored, but it must not be"
}

Requet method

@PutMapping
public ResponseEntity<?> updateAppToggle(@RequestBody AppToggleUpdateRequest request) {
   AppToggle updatedAppToggle = service.update(request);
   return new ResponseEntity<AppToggleResponse>
       (AppToggleResponse.fillResponse(updatedAppToggle), HttpStatus.OK);
   }

Request class

@Data
public class AppToggleUpdateRequest {

   @NotNull
   @Getter
   private Long appId;

   @NotNull
   @Getter
   private String version;

   private Boolean status;

   private Boolean locked;
}

My application.properties does not contain anything special, just datasource and a few stuff for H2 in-memory database.

I really do not know what is going on. Any help would be truly appreciated.

Body:
I fixed my application adding the following to the application.properties file:

spring.jackson.deserialization.FAIL_ON_UNKNOWN_PROPERTIES=true