问:
"not a Parquet file (too small)" from Presto during Spark structured streaming run
I have a pipeline set up that reads data from Kafka, processes it using Spark structured streaming and then writes parquet files to HDFS. Downstream clients of the data query is using Presto configured to read the data as Hive tables.

Kafka --> Spark --> Parquet on HDFS --> Presto

In general this works. The problem arises when a query happens while the Spark job is running a batch. The Spark job creates a zero-length Parquet file on HDFS. If Presto attempts to open this file in the course of processing a query, then it throws an error:

Query 20171116_170937_07282_489cc failed: Error opening Hive split hdfs://namenode:50071/hive/warehouse/table/part-00000-5a7c242a-3e53-46d0-9ee4-5d004ef4b1e4-c000.snappy.parquet (offset=0, length=0): hdfs://namenode:50071/hive/warehouse/table/part-00000-5a7c242a-3e53-46d0-9ee4-5d004ef4b1e4-c000.snappy.parquet is not a Parquet file (too small)

The file is indeed zero bytes at this time, so the error is strictly correct, but this is not the behavior I want for the pipeline. I would like to be able to continuously write in to the appropriate HDFS folders, without disturbing the Presto queries.

The Spark scala code for the job looks like this:

```<code>val FilesOnDisk = 1
Spark
  .initKafkaStream("fleet_profile_test")
  .filter(_.name.contains(job.kafkaTag))
  .flatMap(job.parser)
  .coalesce(FilesOnDisk)
  .writeStream
  .trigger(ProcessingTime("1 hours"))
  .outputMode("append")
  .queryName(job.queryName)
  .format("parquet")
  .option("path", job.outputFilesPath)
  .start()
</code>```

The job starts at the top of the hour, :00. The file is first visible on HDFS as a zero-length file at :05. It is not updated until it is written completely at :21, just before the job finishes. This makes the table effectively unusable from Presto 25% of the time.

Each file is only a little over 500kB, so I wouldn't expect the physical writing of the file to take very long. From my understanding, Parquet files have their metadata at the end of the file so someone writing bigger files would have even more trouble.

What strategies have people used to integrate Spark structured streaming and Presto while working around this Presto error?

答:
You could try to persuade Presto (or Presto team) to ignore empty files, but that wouldn't help, as the program writing the file (here: Spark) will eventually flush partial data and the file would appear partial, non-empty and not well formed, thus leading to an error as well.

The approach preventing Presto (or other programs reading the table data for that matter) from seeing partial file would be to assembler the file in different location and then atomically move the file into the correct location.

Body:
I have a pipeline set up that reads data from Kafka, processes it using Spark structured streaming and then writes parquet files to HDFS. Downstream clients of the data query is using Presto configured to read the data as Hive tables.

Kafka --> Spark --> Parquet on HDFS --> Presto

In general this works. The problem arises when a query happens while the Spark job is running a batch. The Spark job creates a zero-length Parquet file on HDFS. If Presto attempts to open this file in the course of processing a query, then it throws an error:

Query 20171116_170937_07282_489cc failed: Error opening Hive split hdfs://namenode:50071/hive/warehouse/table/part-00000-5a7c242a-3e53-46d0-9ee4-5d004ef4b1e4-c000.snappy.parquet (offset=0, length=0): hdfs://namenode:50071/hive/warehouse/table/part-00000-5a7c242a-3e53-46d0-9ee4-5d004ef4b1e4-c000.snappy.parquet is not a Parquet file (too small)

The file is indeed zero bytes at this time, so the error is strictly correct, but this is not the behavior I want for the pipeline. I would like to be able to continuously write in to the appropriate HDFS folders, without disturbing the Presto queries.

The Spark scala code for the job looks like this:

val FilesOnDisk = 1
Spark
  .initKafkaStream("fleet_profile_test")
  .filter(_.name.contains(job.kafkaTag))
  .flatMap(job.parser)
  .coalesce(FilesOnDisk)
  .writeStream
  .trigger(ProcessingTime("1 hours"))
  .outputMode("append")
  .queryName(job.queryName)
  .format("parquet")
  .option("path", job.outputFilesPath)
  .start()

The job starts at the top of the hour, :00. The file is first visible on HDFS as a zero-length file at :05. It is not updated until it is written completely at :21, just before the job finishes. This makes the table effectively unusable from Presto 25% of the time.

Each file is only a little over 500kB, so I wouldn't expect the physical writing of the file to take very long. From my understanding, Parquet files have their metadata at the end of the file so someone writing bigger files would have even more trouble.

What strategies have people used to integrate Spark structured streaming and Presto while working around this Presto error?


来源: stackexchange

问:
UIScrollView contentLayoutGuide and zooming centered
The problem to be solved here is how to zoom in a UIScrollView while staying centered. If you don't take some sort of precautions, the default is that as we zoom out, the zoomed view slides up to the top left corner of the scroll view, like this:

So how to prevent this, and keep the zoomed view in the center as we zoom? As you probably know, there are traditional ways of handling this by messing with the scroll view's layout, as described by Josh and Eliza in the brilliant classic WWDC video 104 from 2010. This can be done by using a delegate or by subclassing UIScrollView, and gives the desired result:

Now comes WWDC 2017 video 201 (https://developer.apple.com/videos/play/wwdc2017/201/?time=1496), and there's Eliza making a claim that the new (iOS 11) contentLayoutGuide solves the problem of zooming while staying centered in a new way: she says to center the content view at the center of the content layout guide.

But she doesn't demonstrate. And when I try it for myself, I find it isn't solving the problem. I'm zooming in just fine, but when zooming out, so that the zoom scale is smaller than 1, the content view moves up to the top left, just as it always has.

Has anyone figured out what this claim in the video actually means? How does iOS 11 make it easier to zoom centered than in the past?

EDIT I actually received a sample project from Apple in response to my bug report, which they claimed illustrated how to solve this, and it didn't! So I conclude that even Apple doesn't know what they're talking about here.

答:
The view goes to the top left because the contentSize of the scroll view is not defined. When using the new Auto Layout guides in iOS 11, it's still necessary to define the contentSize.

Add the following constraints:

```<code>scrollView.contentLayoutGuide.widthAnchor.constraint(equalTo: scrollView.frameLayoutGuide.widthAnchor),
scrollView.contentLayoutGuide.heightAnchor.constraint(equalTo: scrollView.frameLayoutGuide.heightAnchor)
</code>```

This worked for me, when I had a contentView with a fixed width/height and the following additional constraints:

```<code>//  give the centerView explicit height and width constraints
centerView.widthAnchor.constraint(equalToConstant: 500),
centerView.heightAnchor.constraint(equalToConstant: 500),

//  pin the center of the centerView to the center of the scrollView's contentLayoutGuide
centerView.centerXAnchor.constraint(equalTo: scrollView.contentLayoutGuide.centerXAnchor),
centerView.centerYAnchor.constraint(equalTo: scrollView.contentLayoutGuide.centerYAnchor)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The view goes to the top left because the contentSize of the scroll view is not defined. When using the new Auto Layout guides in iOS 11, it's still necessary to define the contentSize.

Add the following constraints:

scrollView.contentLayoutGuide.widthAnchor.constraint(equalTo: scrollView.frameLayoutGuide.widthAnchor),
scrollView.contentLayoutGuide.heightAnchor.constraint(equalTo: scrollView.frameLayoutGuide.heightAnchor)

This worked for me, when I had a contentView with a fixed width/height and the following additional constraints:

//  give the centerView explicit height and width constraints
centerView.widthAnchor.constraint(equalToConstant: 500),
centerView.heightAnchor.constraint(equalToConstant: 500),

//  pin the center of the centerView to the center of the scrollView's contentLayoutGuide
centerView.centerXAnchor.constraint(equalTo: scrollView.contentLayoutGuide.centerXAnchor),
centerView.centerYAnchor.constraint(equalTo: scrollView.contentLayoutGuide.centerYAnchor)

ContentLicense: CC BY-SA 3.0


问:
Regular expression for valid boolean expression
I want to search for valid boolean formulae e.g A'+BC(D+E) among a list of formulae. Any help on a regular expression to do that?</p>

答:
I implemented it using python using some independant rules, for example:

checking that the expression does not have 'and' followed by 'or', nor 'or' followed by 'and'

open parenthesis '(' must be followed by something other than 'and', 'or' ; and it must follows 'and' or 'or' (except when figuring at the beginning)

closing parenthesis ')' must be followed by 'and' or 'or' or string-end character '$' and it must follow something other than 'or','and'

.....

This is an example using python (but assuming that we use PCRE regexp to support variable width look-behind):

```<code>    tmp= query
    tmp= re.sub("[(]", " (", query)
    tmp= re.sub(" +", " ", query)
    if re.search(r"\(( *and| *or| *\))", tmp) or re.search(r"(?<!\band|\bor) \(", tmp):
        return False

    if re.search(r"\)(?!( *or\b| *and\b|$))", tmp) or re.search(r"(\band *|\bor *)\)", tmp):
        return False

    if re.search(r"(\band|\bor)( and\b| or\b)", tmp) or re.search(r"(?<!\band|\bor) (?!and\b|or\b)", tmp):
        return False

    return True
</code>```

Body:
I implemented it using python using some independant rules, for example:

checking that the expression does not have 'and' followed by 'or', nor 'or' followed by 'and'

open parenthesis '(' must be followed by something other than 'and', 'or' ; and it must follows 'and' or 'or' (except when figuring at the beginning)

closing parenthesis ')' must be followed by 'and' or 'or' or string-end character '$' and it must follow something other than 'or','and'

.....

This is an example using python (but assuming that we use PCRE regexp to support variable width look-behind):

    tmp= query
    tmp= re.sub("[(]", " (", query)
    tmp= re.sub(" +", " ", query)
    if re.search(r"\(( *and| *or| *\))", tmp) or re.search(r"(?<!\band|\bor) \(", tmp):
        return False

    if re.search(r"\)(?!( *or\b| *and\b|$))", tmp) or re.search(r"(\band *|\bor *)\)", tmp):
        return False

    if re.search(r"(\band|\bor)( and\b| or\b)", tmp) or re.search(r"(?<!\band|\bor) (?!and\b|or\b)", tmp):
        return False

    return True


问:
Google dataflow: AvroIO read from file in google storage passed as runtime parameter
I want to read Avro files in my dataflow using java SDK 2

I have schedule my dataflow using cloud function which are triggered based on the files uploaded to the bucket.

Following is the code for options:

```<code>ValueProvider <String> getInputFile();
void setInputFile(ValueProvider<String> value);
</code>```

I am trying to read this input file using following code:

```<code>PCollection<user> records = p.apply(
    AvroIO.read(user.class)
    .from(String.valueOf(options.getInputFile())));
</code>```

I get following error while running the pipeline:

```<code>java.lang.IllegalArgumentException: Unable to find any files matching RuntimeValueProvider{propertyName=inputFile, default=gs://test_bucket/user.avro, value=null}
</code>```

Same code works fine in case of TextIO.

How can we read Avro file which is uploaded for triggering cloud function which triggers the dataflow pipeline?

答:
Please try ...from(options.getInputFile())) without converting it to a string.

For simplicity, you could even define your option as simple string:

```<code>   String getInputFile();
   void setInputFile(String value);
</code>```

Body:
I want to read Avro files in my dataflow using java SDK 2

I have schedule my dataflow using cloud function which are triggered based on the files uploaded to the bucket.

Following is the code for options:

ValueProvider <String> getInputFile();
void setInputFile(ValueProvider<String> value);

I am trying to read this input file using following code:

PCollection<user> records = p.apply(
    AvroIO.read(user.class)
    .from(String.valueOf(options.getInputFile())));

I get following error while running the pipeline:

java.lang.IllegalArgumentException: Unable to find any files matching RuntimeValueProvider{propertyName=inputFile, default=gs://test_bucket/user.avro, value=null}

Same code works fine in case of TextIO.

How can we read Avro file which is uploaded for triggering cloud function which triggers the dataflow pipeline?

Body:
Please try ...from(options.getInputFile())) without converting it to a string.

For simplicity, you could even define your option as simple string:

   String getInputFile();
   void setInputFile(String value);


问:
asp.net mvc - how to write ajax request in javascript
i would like to update follow div with ajax request written in javascript method.

asp.mvc view:

```<code><div id="feed" onload="GetFeeds()">
            <span id="feeds" runat="server">
                    <%= Model.Feeds %>
            </span>
        </div>
</code>```

what schould i do in javasript?:

```<code><script type="text/javascript">

   // some AJAX Request with 'feed' Update, but HOW??
   document.getElementById('feed');

    function GetFeeds() {
    // need to call method from HomeModel.cs GetAllFeeds()??
    // or i should to write hole methode here?
    }

</script>
</code>```

it schould work without any controller action.
method for FeedUpdating is written in HomeModel.cs / GetAllFeeds() and it works. I need just call it from javascript

答: if you don't mind then use jquery $.get function.</p>

ContentLicense: CC BY-SA 2.5

Body:
i would like to update follow div with ajax request written in javascript method.

asp.mvc view:

                    <%= Model.Feeds %>

what schould i do in javasript?:

it schould work without any controller action.
method for FeedUpdating is written in HomeModel.cs / GetAllFeeds() and it works. I need just call it from javascript


问:
Git - fatal: Could not get current working directory?
When I git clone from a repo, I get,

fatal: Could not get current working directory: No such file or directory

What do I do? I have checked the server and found that .git file exists. The server is running a Gitlab instance. I have configured ssh properly with the keys, and I've been committing & cloning for a while now without any error, and this happens all of a sudden.

FWIW, I'm doing the git clone in a bash script.

Update

This is my bash script,

```<code>for repo in $repos
do
   git clone $repo /tmp/tmpdir/
   # do stuff with /tmp/tmpdir/
   rm -rf /tmp/tmpdir/
done
</code>```

for the first repo it's fine, but when the for gets into the second repo it fails and gives the above fatal error.

答: In my case, this was caused by issuing a "git clone" from a subdirectory of a local git repo.  I had to cd to another directory before I could clone the new repo.</p>

Body:
When I git clone from a repo, I get,

fatal: Could not get current working directory: No such file or directory

What do I do? I have checked the server and found that .git file exists. The server is running a Gitlab instance. I have configured ssh properly with the keys, and I've been committing & cloning for a while now without any error, and this happens all of a sudden.

FWIW, I'm doing the git clone in a bash script.

Update

This is my bash script,

for repo in $repos
do
   git clone $repo /tmp/tmpdir/
   # do stuff with /tmp/tmpdir/
   rm -rf /tmp/tmpdir/
done

for the first repo it's fine, but when the for gets into the second repo it fails and gives the above fatal error.


问:
Merge multiple scss files into one css file
I'd like to merge all of my scss files into one compressed css file:

Structure:

stylesheets/

test.scss

test2.scss

gulpfile.js

I tried this two tasks, which I found in several answers and tutorials, but I always got the scss file into a duplicated css file:

```<code>gulp.task('sass', function() {
    return gulp.src('stylesheets/**/*.scss')
      .pipe(sass())
      .pipe(gulp.dest('css/'))
});
</code>```

and

```<code>gulp.task('sass', function() {
    return gulp.src('stylesheets/**/*.scss')
      .pipe(sass())
      .pipe(gulp.dest('css/styles.css'))
});
</code>```

!!! EFFECTIV RESULT !!!

stylesheets/

test.scss

test2.scss

css/

test.css

test2.css

gulpfile.js

or with second tried task:

stylesheets/

test.scss

test2.scss

css/styles.css/

test.css

test2.css

gulpfile.js

??? EXPECTED RESULT ???

stylesheets/

test.scss

test2.scss

css/

styles.css

gulpfile.js

Any ideas?

答:
Hope this hepls.</p>

```<code>gulp.task('styles', () => {
  gulp.src([path.src.sass])
    .pipe(sassGlob())
    .on('error', util.log)
    .pipe(sass({
       includePaths: ['src/scss'],
    }))
    .on('error', util.log)
    .pipe(gulp.dest(path.dist.css))
});
</code>```

Body:
I'd like to merge all of my scss files into one compressed css file:

Structure:

stylesheets/

test.scss

test2.scss

gulpfile.js

I tried this two tasks, which I found in several answers and tutorials, but I always got the scss file into a duplicated css file:

gulp.task('sass', function() {
    return gulp.src('stylesheets/**/*.scss')
      .pipe(sass())
      .pipe(gulp.dest('css/'))
});

and

gulp.task('sass', function() {
    return gulp.src('stylesheets/**/*.scss')
      .pipe(sass())
      .pipe(gulp.dest('css/styles.css'))
});

!!! EFFECTIV RESULT !!!

stylesheets/

test.scss

test2.scss

css/

test.css

test2.css

gulpfile.js

or with second tried task:

stylesheets/

test.scss

test2.scss

css/styles.css/

test.css

test2.css

gulpfile.js

??? EXPECTED RESULT ???

stylesheets/

test.scss

test2.scss

css/

styles.css

gulpfile.js

Any ideas?

Body:
Hope this hepls.

gulp.task('styles', () => {
  gulp.src([path.src.sass])
    .pipe(sassGlob())
    .on('error', util.log)
    .pipe(sass({
       includePaths: ['src/scss'],
    }))
    .on('error', util.log)
    .pipe(gulp.dest(path.dist.css))
});


问:
Wildfly Plugin - Datasource - Required services that are not installed
I'm trying to configure a datasource in Wildfly Maven plugin...

I have searched for solutions but I didn't find!

My project is too basic and I'm following the documentation examples (https://docs.jboss.org/wildfly/plugins/maven/latest)

I did the following steps:

1)I added MySql Connector dependency in my Pom.xml

```<code><dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>6.0.6</version>
</dependency>
</code>```

2)Wildfly plugin configuration

```<code><plugin>
    <groupId>org.wildfly.plugins</groupId>
    <artifactId>wildfly-maven-plugin</artifactId>
    <version>1.2.1.Final</version>
        <configuration>
            <jboss-home>/opt/wildfly</jboss-home>
            <filename>${project.build.finalName}.war</filename>

            <executions>
                <execution>
                    <id>MySQL-Driver</id>
                    <phase>install</phase>
                        <goals>
                            <goal>deploy-artifact</goal>
                        </goals>
                        <configuration>
                            <groupId>mysql</groupId>
                            <artifactId>mysql-connector-java</artifactId>
                            <version>6.0.6</version>
                            <name>mysql-connector-java-6.0.6</name>
                            <driver-name>mysql-connector-java-6.0.6</driver-name>
                        </configuration>
                </execution>
                <execution>
                    <id>DataSource</id>
                        <phase>install</phase>
                        <configuration>
                            <force>false</force>
                            <address>subsystem=datasources,data-source=java:/CondominioDS</address>
                            <resources>
                                <resource>
                                    <enableResource>true</enableResource>
                                            <properties>
                                        <jndi-name>java:/CondominioDS</jndi-name>
                                        <enable>true</enable>
                                        <connection-url>jdbc:mysql://localhost:3306/Condominio?useSSL=false</connection-url>
                                        <driver-class>com.mysql.cj.jdbc.Driver</driver-class>
                                        <driver-name>mysql-connector-java-6.0.6</driver-name>
                                        <user-name>root</user-name>
                                        <password>123</password>
                                    </properties>
                                </resource>
                            </resources>
                        <retryFailedDeploymentCount>1</retryFailedDeploymentCount>
                    </configuration>
                        <goals>
                            <goal>add-resource</goal>
                        </goals>
                </execution>
                <execution>
                    <id>deploy</id>
                        <phase>install</phase>
                        <goals>
                            <goal>deploy</goal>
                        </goals>
                </execution>
            </executions>
    </configuration>
</plugin>
</code>```

3)Part of Persistence.xml

```<code><persistence-unit name="Condominio" transaction-type="JTA">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <jta-data-source>java:/CondominioDS</jta-data-source>
</code>```

4) mvn clean install

5) mvn wildfly:start

6) mvn wildfly:deploy

And I get the error below ....

```<code>09:47:49,668 INFO  [org.jboss.as.repository] (management-handler-thread - 1) WFLYDR0001: Content added at location /opt/wildfly/standalone/data/content/06/1a91a0f2082869d2b08334631636973944d062/content

09:47:49,692 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-1) WFLYSRV0027: Starting deployment of "teste.war" (runtime-name: "teste.war")

09:47:50,941 INFO  [org.jboss.as.jpa] (MSC service thread 1-6) WFLYJPA0002: Read persistence.xml for Condominio

09:47:51,120 INFO  [org.jboss.weld.deployer] (MSC service thread 1-3) WFLYWELD0003: Processing weld deployment teste.war

09:47:51,171 INFO  [org.hibernate.validator.internal.util.Version] (MSC service thread 1-3) HV000001: Hibernate Validator 5.2.4.Final

09:47:51,340 INFO  [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-3) WFLYJCA0005: Deploying non-JDBC-compliant driver class com.mysql.cj.jdbc.Driver (version 6.0)

09:47:51,375 INFO  [org.jboss.weld.Version] (MSC service thread 1-3) WELD-000900: 2.3.5 (Final)

09:47:51,414 INFO  [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-3) WFLYJCA0018: Started Driver service with driver-name = teste.war_com.mysql.cj.jdbc.Driver_6_0

09:47:51,546 ERROR [org.jboss.as.controller.management-operation] (management-handler-thread - 1) WFLYCTL0013: Operation ("add") failed - address: ([("deployment" => "teste.war")]) - failure description:

{
    "WFLYCTL0412: Required services that are not installed:" => ["jboss.naming.context.java.CondominioDS"],
    "WFLYCTL0180: Services with missing/unavailable dependencies" => [
        "jboss.persistenceunit.\"teste.war#Condominio\" is missing [jboss.naming.context.java.CondominioDS]",
        "jboss.persistenceunit.\"teste.war#Condominio\".__FIRST_PHASE__ is missing [jboss.naming.context.java.CondominioDS]"
    ]
}

09:47:51,547 ERROR [org.jboss.as.server] (management-handler-thread - 1) WFLYSRV0021: Deploy of deployment "teste.war" was rolled back with the following failure message:
{
    "WFLYCTL0412: Required services that are not installed:" => ["jboss.naming.context.java.CondominioDS"],
    "WFLYCTL0180: Services with missing/unavailable dependencies" => [
        "jboss.persistenceunit.\"teste.war#Condominio\" is missing [jboss.naming.context.java.CondominioDS]",
        "jboss.persistenceunit.\"teste.war#Condominio\".__FIRST_PHASE__ is missing [jboss.naming.context.java.CondominioDS]"
    ]
}
</code>```

答:
OMG!!!!

I found my error!

```<code><configuration> </configuration>
</code>```

tag was closed in wrong location ..... after executions and so did not perfom the phases and goals.

Now with "mvn install" the artifact was deployed, DS was created and the application deployed..... how said @JamesR.Perkins

Body:
I'm trying to configure a datasource in Wildfly Maven plugin...

I have searched for solutions but I didn't find!

My project is too basic and I'm following the documentation examples (https://docs.jboss.org/wildfly/plugins/maven/latest)

I did the following steps:

1)I added MySql Connector dependency in my Pom.xml

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>6.0.6</version>
</dependency>

2)Wildfly plugin configuration

<plugin>
    <groupId>org.wildfly.plugins</groupId>
    <artifactId>wildfly-maven-plugin</artifactId>
    <version>1.2.1.Final</version>
        <configuration>
            <jboss-home>/opt/wildfly</jboss-home>
            <filename>${project.build.finalName}.war</filename>

            <executions>
                <execution>
                    <id>MySQL-Driver</id>
                    <phase>install</phase>
                        <goals>
                            <goal>deploy-artifact</goal>
                        </goals>
                        <configuration>
                            <groupId>mysql</groupId>
                            <artifactId>mysql-connector-java</artifactId>
                            <version>6.0.6</version>
                            <name>mysql-connector-java-6.0.6</name>
                            <driver-name>mysql-connector-java-6.0.6</driver-name>
                        </configuration>
                </execution>
                <execution>
                    <id>DataSource</id>
                        <phase>install</phase>
                        <configuration>
                            <force>false</force>
                            <address>subsystem=datasources,data-source=java:/CondominioDS</address>
                            <resources>
                                <resource>
                                    <enableResource>true</enableResource>
                                            <properties>
                                        <jndi-name>java:/CondominioDS</jndi-name>
                                        <enable>true</enable>
                                        <connection-url>jdbc:mysql://localhost:3306/Condominio?useSSL=false</connection-url>
                                        <driver-class>com.mysql.cj.jdbc.Driver</driver-class>
                                        <driver-name>mysql-connector-java-6.0.6</driver-name>
                                        <user-name>root</user-name>
                                        <password>123</password>
                                    </properties>
                                </resource>
                            </resources>
                        <retryFailedDeploymentCount>1</retryFailedDeploymentCount>
                    </configuration>
                        <goals>
                            <goal>add-resource</goal>
                        </goals>
                </execution>
                <execution>
                    <id>deploy</id>
                        <phase>install</phase>
                        <goals>
                            <goal>deploy</goal>
                        </goals>
                </execution>
            </executions>
    </configuration>
</plugin>

3)Part of Persistence.xml

<persistence-unit name="Condominio" transaction-type="JTA">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <jta-data-source>java:/CondominioDS</jta-data-source>

4) mvn clean install

5) mvn wildfly:start

6) mvn wildfly:deploy

And I get the error below ....

09:47:49,668 INFO  [org.jboss.as.repository] (management-handler-thread - 1) WFLYDR0001: Content added at location /opt/wildfly/standalone/data/content/06/1a91a0f2082869d2b08334631636973944d062/content

09:47:49,692 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-1) WFLYSRV0027: Starting deployment of "teste.war" (runtime-name: "teste.war")

09:47:50,941 INFO  [org.jboss.as.jpa] (MSC service thread 1-6) WFLYJPA0002: Read persistence.xml for Condominio

09:47:51,120 INFO  [org.jboss.weld.deployer] (MSC service thread 1-3) WFLYWELD0003: Processing weld deployment teste.war

09:47:51,171 INFO  [org.hibernate.validator.internal.util.Version] (MSC service thread 1-3) HV000001: Hibernate Validator 5.2.4.Final

09:47:51,340 INFO  [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-3) WFLYJCA0005: Deploying non-JDBC-compliant driver class com.mysql.cj.jdbc.Driver (version 6.0)

09:47:51,375 INFO  [org.jboss.weld.Version] (MSC service thread 1-3) WELD-000900: 2.3.5 (Final)

09:47:51,414 INFO  [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-3) WFLYJCA0018: Started Driver service with driver-name = teste.war_com.mysql.cj.jdbc.Driver_6_0

09:47:51,546 ERROR [org.jboss.as.controller.management-operation] (management-handler-thread - 1) WFLYCTL0013: Operation ("add") failed - address: ([("deployment" => "teste.war")]) - failure description:

{
    "WFLYCTL0412: Required services that are not installed:" => ["jboss.naming.context.java.CondominioDS"],
    "WFLYCTL0180: Services with missing/unavailable dependencies" => [
        "jboss.persistenceunit.\"teste.war#Condominio\" is missing [jboss.naming.context.java.CondominioDS]",
        "jboss.persistenceunit.\"teste.war#Condominio\".__FIRST_PHASE__ is missing [jboss.naming.context.java.CondominioDS]"
    ]
}

09:47:51,547 ERROR [org.jboss.as.server] (management-handler-thread - 1) WFLYSRV0021: Deploy of deployment "teste.war" was rolled back with the following failure message:
{
    "WFLYCTL0412: Required services that are not installed:" => ["jboss.naming.context.java.CondominioDS"],
    "WFLYCTL0180: Services with missing/unavailable dependencies" => [
        "jboss.persistenceunit.\"teste.war#Condominio\" is missing [jboss.naming.context.java.CondominioDS]",
        "jboss.persistenceunit.\"teste.war#Condominio\".__FIRST_PHASE__ is missing [jboss.naming.context.java.CondominioDS]"
    ]
}

Body:
OMG!!!!

I found my error!

<configuration> </configuration>

tag was closed in wrong location ..... after executions and so did not perfom the phases and goals.

Now with "mvn install" the artifact was deployed, DS was created and the application deployed..... how said @JamesR.Perkins


问:
Remove rows where at least x percent of the values are zero in both groups
Given the following dataframe i would like to remove all rows with at least x percent (e.g 50%) of values = 0 in at least one group.

For example if a row has less than 50% of values in both groups (control and treatment) it will be removed.

If the row has 50% of non zero value in group control(or treatment) and no values in the other group it will be kept since there is still one group with at least 50% values.

Hope it´s clear.

```<code>    treatment   control control treatment control treatment
row1    0 21   21   21    45 34
row2    0 21   78   321   93 0
row3 34 32  98   87    34 0
row4    75 21  12   54    45 34
row5    46 21  13   45     0   0
row6    85 21  87   45     0 23
row7    24 84   0    0    45 5
row8    87 21   0    98   87 76
row9   43  2   0    45   12 9
row10    12 12   0    0    23  0
</code>```

Here below the dataframe

```<code> df <-  structure(list(structure(c(1L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
    2L), .Label = c("row1", "row10", "row2", "row3", "row4", "row5",
    "row6", "row7", "row8", "row9"), class = "factor"), treatment = c(0L,
    0L, 34L, 75L, 46L, 85L, 24L, 87L, 43L, 12L), control = c(21L,
    21L, 32L, 21L, 21L, 21L, 84L, 21L, 2L, 12L), control = c(21L,
    78L, 98L, 12L, 13L, 87L, 0L, 0L, 0L, 0L), treatment = c(21L,
    321L, 87L, 54L, 45L, 45L, 0L, 98L, 45L, 0L), control = c(45L,
    93L, 34L, 45L, 0L, 0L, 45L, 87L, 12L, 23L), treatment = c(34L,
    0L, 0L, 34L, 0L, 23L, 5L, 76L, 9L, 0L)), .Names = c("", "treatment",
    "control", "control", "treatment", "control", "treatment"), class = "data.frame", row.names = c(NA,
    -10L))
</code>```

答:
Based on what you want, if a row has more than 3 "0", you want to remove the row.

```<code>rownames(df) <- df[,1]
df <- df[,-1]
df <- df[apply(df, 1, FUN = function(x){sum(x == 0)}) < 3,]
</code>```

Row 10 is removed.

Body:
Given the following dataframe i would like to remove all rows with at least x percent (e.g 50%) of values = 0 in at least one group.

For example if a row has less than 50% of values in both groups (control and treatment) it will be removed.

If the row has 50% of non zero value in group control(or treatment) and no values in the other group it will be kept since there is still one group with at least 50% values.

Hope it´s clear.

    treatment   control control treatment control treatment
row1    0 21   21   21    45 34
row2    0 21   78   321   93 0
row3 34 32  98   87    34 0
row4    75 21  12   54    45 34
row5    46 21  13   45     0   0
row6    85 21  87   45     0 23
row7    24 84   0    0    45 5
row8    87 21   0    98   87 76
row9   43  2   0    45   12 9
row10    12 12   0    0    23  0

Here below the dataframe

 df <-  structure(list(structure(c(1L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
    2L), .Label = c("row1", "row10", "row2", "row3", "row4", "row5",
    "row6", "row7", "row8", "row9"), class = "factor"), treatment = c(0L,
    0L, 34L, 75L, 46L, 85L, 24L, 87L, 43L, 12L), control = c(21L,
    21L, 32L, 21L, 21L, 21L, 84L, 21L, 2L, 12L), control = c(21L,
    78L, 98L, 12L, 13L, 87L, 0L, 0L, 0L, 0L), treatment = c(21L,
    321L, 87L, 54L, 45L, 45L, 0L, 98L, 45L, 0L), control = c(45L,
    93L, 34L, 45L, 0L, 0L, 45L, 87L, 12L, 23L), treatment = c(34L,
    0L, 0L, 34L, 0L, 23L, 5L, 76L, 9L, 0L)), .Names = c("", "treatment",
    "control", "control", "treatment", "control", "treatment"), class = "data.frame", row.names = c(NA,
    -10L))

Body:
Based on what you want, if a row has more than 3 "0", you want to remove the row.

rownames(df) <- df[,1]
df <- df[,-1]
df <- df[apply(df, 1, FUN = function(x){sum(x == 0)}) < 3,]

Row 10 is removed.


问:
Get email message from Exchange using EWS Tracking Log Message ID or the InternalMessageID
I'm developing an application that tracks exchange email messages in our company.
We where able to get info out from the tracking log, but in the log -by design- there is no subject or body message.
So the next step for us was using EWS to get the message detail when needed.
The question is that in the tracking log we find to IDs :

MessageId in format "F533E7F015A2E24F8D8ABFE2587117C601EDF245@blstex02.subdomain.domain.com"

and

InternalMessageId in format "5840818"

If in EWS we use this id to find the message by id we always get an "Id is malformed." exception.
Here is the code we use:

```<code>public static EmailMessage GetEmailById(string uNameToImpersonate, string StringItemId)
        {
            return EmailMessage.Bind(GetService(uNameToImpersonate), new ItemId(StringItemId));
        }
</code>```

I'm a newbie to EWS so maybe I'm missing something really easy...
Thanks for your help

答:
You can only bind to a Message using the EWSId see https://msdn.microsoft.com/en-us/library/office/dn605828(v=exchg.150).aspx for a more detailed discussion.For the InternetId you will need to search for messages with that particular Id using the findItem operation eg something like</p>

```<code>  ItemView ivew = new ItemView(1);
  service.TraceEnabled = true;
  ExtendedPropertyDefinition PidTagInternetMessageId = new ExtendedPropertyDefinition(4149, MapiPropertyType.String);
  SearchFilter sf = new SearchFilter.IsEqualTo(PidTagInternetMessageId, "F533E7F015A2E24F8D8ABFE2587117C601EDF245@blstex02.subdomain.domain.com");
  FindItemsResults<Item> iCol = service.FindItems(WellKnownFolderName.Inbox, sf, ivew);

  foreach (Item item in iCol.Items)
  {
    Console.WriteLine(item.Subject);
  }
</code>```

Body:
I'm developing an application that tracks exchange email messages in our company.
We where able to get info out from the tracking log, but in the log -by design- there is no subject or body message.
So the next step for us was using EWS to get the message detail when needed.
The question is that in the tracking log we find to IDs :

MessageId in format "F533E7F015A2E24F8D8ABFE2587117C601EDF245@blstex02.subdomain.domain.com"

and

InternalMessageId in format "5840818"

If in EWS we use this id to find the message by id we always get an "Id is malformed." exception.
Here is the code we use:

public static EmailMessage GetEmailById(string uNameToImpersonate, string StringItemId)
        {
            return EmailMessage.Bind(GetService(uNameToImpersonate), new ItemId(StringItemId));
        }

I'm a newbie to EWS so maybe I'm missing something really easy...
Thanks for your help

Body:
You can only bind to a Message using the EWSId see https://msdn.microsoft.com/en-us/library/office/dn605828(v=exchg.150).aspx for a more detailed discussion.For the InternetId you will need to search for messages with that particular Id using the findItem operation eg something like

  ItemView ivew = new ItemView(1);
  service.TraceEnabled = true;
  ExtendedPropertyDefinition PidTagInternetMessageId = new ExtendedPropertyDefinition(4149, MapiPropertyType.String);
  SearchFilter sf = new SearchFilter.IsEqualTo(PidTagInternetMessageId, "F533E7F015A2E24F8D8ABFE2587117C601EDF245@blstex02.subdomain.domain.com");
  FindItemsResults<Item> iCol = service.FindItems(WellKnownFolderName.Inbox, sf, ivew);

  foreach (Item item in iCol.Items)
  {
    Console.WriteLine(item.Subject);
  }


问:
Extract motion vectors from x265 (HEVC) encoded video with ffmpeg/libavcodec?
I know that one can extract the motion vectors from an h264 encoded via by first setting the flag

```<code>av_dict_set(&opts, "flags2", "+export_mvs", 0);
</code>```

then you can query the side-data for the motion vectors by doing this

```<code>sd = av_frame_get_side_data(frame, AV_FRAME_DATA_MOTION_VECTORS);
</code>```

When I looked online to see if you can do something similar with HEVC encoded videos, I wasn't able to find any information. All I found was this by the definition of "AV_FRAME_DATA_MOTION_VECTORS"

Motion vectors exported by some codecs (on demand through the
  export_mvs flag set in the libavcodec AVCodecContext flags2 option).

The data is the AVMotionVector struct defined in
  libavutil/motion_vector.h.

but there was no information on exactly which codecs export this motion vector information. How would I go about finding this out?

答:
If I'm not mistaken h264 is the only codec to print Motion Estimation Vectors.

I would suggest trying out the video filter mestimate.

Also, if you want to have a better ideia what's going on in ffmpeg, check the function ff_print_debug_info2 in libavcodec/mpegvideo.c

Body:
I know that one can extract the motion vectors from an h264 encoded via by first setting the flag

av_dict_set(&opts, "flags2", "+export_mvs", 0);

then you can query the side-data for the motion vectors by doing this

sd = av_frame_get_side_data(frame, AV_FRAME_DATA_MOTION_VECTORS);

When I looked online to see if you can do something similar with HEVC encoded videos, I wasn't able to find any information. All I found was this by the definition of "AV_FRAME_DATA_MOTION_VECTORS"

Motion vectors exported by some codecs (on demand through the
  export_mvs flag set in the libavcodec AVCodecContext flags2 option).

The data is the AVMotionVector struct defined in
  libavutil/motion_vector.h.

but there was no information on exactly which codecs export this motion vector information. How would I go about finding this out?


问:
Using promises with PDFMake on Firebase Cloud Functions
I am using PDFMake (a variant of PDFKit) to generate PDFs on Firebase Cloud Functions using a realtime database trigger. The function gets all relevant data from the database and then passes it to the function that is supposed to generate the PDF.

All this is done using Promises. Everything works fine until the point where the PDF is actually generated.

Here's the code in my main event listener:

```<code>exports.handler = (admin, event, storage) => {
  const quotationData = event.data.val();
  // We must return a Promise when performing async tasks inside Functions
  // Eg: Writing to realtime db
  const companyId = event.params.companyId;
  settings.getCompanyProfile(admin, companyId)
  .then((profile) => {
    return quotPdfHelper.generatePDF(fonts, profile, quotationData, storage);
  })
  .then(() => {
    console.log('Generation Successful. Pass for email');
  })
  .catch((err) => {
    console.log(`Error: ${err}`);
  });
};
</code>```

To generate the PDF, here's my code:

```<code>exports.generatePDF = (fonts, companyInfo, quotationData, storage) => {
  const printer = new PdfPrinter(fonts);
  const docDefinition = {
    content: [
      {
        text: [
          {
            text: `${companyInfo.title}\n`,
            style: 'companyHeader',
          },
          `${companyInfo.addr_line1}, ${companyInfo.addr_line2}\n`,
          `${companyInfo.city} (${companyInfo.state}) - INDIA\n`,
          `Email: ${companyInfo.email} • Web: ${companyInfo.website}\n`,
          `Phone: ${companyInfo.phone}\n`,
          `GSTIN: ${companyInfo.gst_registration_number}  • PAN: AARFK6552G\n`,
        ],
        style: 'body',
         //absolutePosition: {x: 20, y: 45}
      },
    ],
    styles: {
      companyHeader: {
        fontSize: 18,
        bold: true,
      },
      body: {
        fontSize: 10,
      },
    },
    pageMargins: 20,
  };
  return new Promise((resolve, reject) => {
    // const bucket = storage.bucket(`${PROJECT_ID}.appspot.com`);
    // const filename = `${Date.now()}-quotation.pdf`;
    // const file = bucket.file(filename);
    // const stream = file.createWriteStream({ resumable: false });
    const pdfDoc = printer.createPdfKitDocument(docDefinition);
    // pdfDoc.pipe(stream);

    const chunks = [];
    let result = null;

    pdfDoc.on('data', (chunk) => {
      chunks.push(chunk);
    });
    pdfDoc.on('error', (err) => {
      reject(err);
    });
    pdfDoc.on('end', () => {
      result = Buffer.concat(chunks);
      resolve(result);
    });
    pdfDoc.end();
  });
};
</code>```

What could be wrong here that is preventing the promise and thereby the quotation code to be executed as intended?

On firebase log, all I see is Function execution took 3288 ms, finished with status: 'ok'

答:
Based on the execution time and lack of errors, it looks like you're successfully creating the buffer for the PDF but you're not actually returning it from the function.

```<code>.then((profile) => {
  return quotPdfHelper.generatePDF(fonts, profile, quotationData, storage);
})
.then(() => {
  console.log('Generation Successful. Pass for email');
})
</code>```

In the code above, you're passing the result to the next then block, but then returning undefined from that block. The end result of this Promise chain will be undefined. To pass the result through, you'd want to return it at the end of the Promise chain:

```<code>.then((profile) => {
  return quotPdfHelper.generatePDF(fonts, profile, quotationData, storage);
})
.then(buffer => {
  console.log('Generation Successful. Pass for email');
  return buffer;
})
</code>```

Body:
I am using PDFMake (a variant of PDFKit) to generate PDFs on Firebase Cloud Functions using a realtime database trigger. The function gets all relevant data from the database and then passes it to the function that is supposed to generate the PDF.

All this is done using Promises. Everything works fine until the point where the PDF is actually generated.

Here's the code in my main event listener:

exports.handler = (admin, event, storage) => {
  const quotationData = event.data.val();
  // We must return a Promise when performing async tasks inside Functions
  // Eg: Writing to realtime db
  const companyId = event.params.companyId;
  settings.getCompanyProfile(admin, companyId)
  .then((profile) => {
    return quotPdfHelper.generatePDF(fonts, profile, quotationData, storage);
  })
  .then(() => {
    console.log('Generation Successful. Pass for email');
  })
  .catch((err) => {
    console.log(`Error: ${err}`);
  });
};

To generate the PDF, here's my code:

exports.generatePDF = (fonts, companyInfo, quotationData, storage) => {
  const printer = new PdfPrinter(fonts);
  const docDefinition = {
    content: [
      {
        text: [
          {
            text: `${companyInfo.title}\n`,
            style: 'companyHeader',
          },
          `${companyInfo.addr_line1}, ${companyInfo.addr_line2}\n`,
          `${companyInfo.city} (${companyInfo.state}) - INDIA\n`,
          `Email: ${companyInfo.email} • Web: ${companyInfo.website}\n`,
          `Phone: ${companyInfo.phone}\n`,
          `GSTIN: ${companyInfo.gst_registration_number}  • PAN: AARFK6552G\n`,
        ],
        style: 'body',
         //absolutePosition: {x: 20, y: 45}
      },
    ],
    styles: {
      companyHeader: {
        fontSize: 18,
        bold: true,
      },
      body: {
        fontSize: 10,
      },
    },
    pageMargins: 20,
  };
  return new Promise((resolve, reject) => {
    // const bucket = storage.bucket(`${PROJECT_ID}.appspot.com`);
    // const filename = `${Date.now()}-quotation.pdf`;
    // const file = bucket.file(filename);
    // const stream = file.createWriteStream({ resumable: false });
    const pdfDoc = printer.createPdfKitDocument(docDefinition);
    // pdfDoc.pipe(stream);

    const chunks = [];
    let result = null;

    pdfDoc.on('data', (chunk) => {
      chunks.push(chunk);
    });
    pdfDoc.on('error', (err) => {
      reject(err);
    });
    pdfDoc.on('end', () => {
      result = Buffer.concat(chunks);
      resolve(result);
    });
    pdfDoc.end();
  });
};

What could be wrong here that is preventing the promise and thereby the quotation code to be executed as intended?

On firebase log, all I see is Function execution took 3288 ms, finished with status: 'ok'

Body:
Based on the execution time and lack of errors, it looks like you're successfully creating the buffer for the PDF but you're not actually returning it from the function.

.then((profile) => {
  return quotPdfHelper.generatePDF(fonts, profile, quotationData, storage);
})
.then(() => {
  console.log('Generation Successful. Pass for email');
})

In the code above, you're passing the result to the next then block, but then returning undefined from that block. The end result of this Promise chain will be undefined. To pass the result through, you'd want to return it at the end of the Promise chain:

.then((profile) => {
  return quotPdfHelper.generatePDF(fonts, profile, quotationData, storage);
})
.then(buffer => {
  console.log('Generation Successful. Pass for email');
  return buffer;
})


问:
How is the schedule produced in NS2?
Reposting this from EE since folk there don't seem to know the answer.

I am interested in seeing how the NS2 schedule of events is created based on the TCL script. Is there an intermediate file I could look at? Or perhaps there is a book or chapter in a book that talks about it?

I have the NS2 code, but I'm not sure where to look.

Edit: Here is a link to NS2: http://www.isi.edu/nsnam/ns/ . It is a discrete event wireless simulator. To run a simulation, one supplies a script (written in TCL), which describes the network topology, node-to-node connections and so on. When the simulation is run, a schedule of events (because this is discrete time events sim) is created.

I want to know how this schedule is created and what it looks like. For example, if I have a network of 1000 nodes, all communicating in response to an already received packet, how does it schedule the responses? Are those done at runtime?

Thanks (PS. Sorry if this is in the wrong place)

答:
there are many types of ns2 schedulers( real-time, heap,calendar..)
the default scheduled is the "calendar scheduler"
it is automatically called when you create new simulator instance in tcl file.

in this tcl file you specify some event and the time of its occurance

the events may be a sending or receiving packet or  creating a node or ...
these events may also call many other event,  and the mission of scheduler is to arrange these events in the time series

please take a look at ns-allin_one-2.35/common/scheduler.cc
https://www.isi.edu/nsnam/ns/doc/node32.html

very nice explination here

https://www.slideshare.net/TBear76/ns2event-scheduler

regards

Title: How is the schedule produced in NS2?


答:
You need to use simply from(options.getInputFile()): AvroIO explicitly supports reading from a ValueProvider.

Currently the code is taking options.getInputFile() which is a ValueProvider, calling the JavatoString() function on it which gives a human-readable debug string "RuntimeValueProvider{propertyName=inputFile, default=gs://test_bucket/user.avro, value=null}" and passing that as a filename for AvroIO to read, and of course this string is not a valid filename, that's why the code currently doesn't work.

Also note that the whole point of ValueProvider is that it is placeholder for a value that is not known while constructing the pipeline and will be supplied later (potentially the pipeline will be executed several times, supplying different values) - so extracting the value of a ValueProvider at pipeline construction time is impossible by design, because there is no value. At runtime though (e.g. in a DoFn) you can extract the value by calling .get() on it.

Title: Google dataflow: AvroIO read from file in google storage passed as runtime parameter


问:
Django rest Framework sending json to api endpoint within another class-based view
I want to post to an endpoint from within a CBV and retrieve the response (in order to access the id of the created resource). I've had a look at How to programmatically call a Django Rest Framework view within another view? but cannot find how to send field values through with the request object. request.data is immutable, and passing kwargs through doesn't seem to be doing anything:

```<code>from app.views import OtherViewSet

class NewViews(APIView):
   def post(self, request, *args, **kwargs):
       # kwargs value here is {'field1':1, 'field2':2...}
       view_func = OtherViewSet({'post':'create'})
       response = view_func(self.request, *args, **kwargs).data
</code>```

Although the kwargs contains the field values (set through several url named groups), the response always looks like:

```<code>{'field1': ['This field is required'], 'field2':['This field is required...
</code>```

What am I doing wrong? Thanks all :)

Edit:
Once I've got the ID of the created resource, I want to retrieve the resource as rendered by a particular (custom) format (I don't want to return the response object above).

答:
views.py

```<code>from app.views import OtherViewSet

class NewViews(APIView):
    def post(self, request, *args, **kwargs):
        view = OtherViewSet.as_view({'post':'create'})
        response = view(request, *args, **kwargs)
        return response
</code>```

Body:
I want to post to an endpoint from within a CBV and retrieve the response (in order to access the id of the created resource). I've had a look at How to programmatically call a Django Rest Framework view within another view? but cannot find how to send field values through with the request object. request.data is immutable, and passing kwargs through doesn't seem to be doing anything:

from app.views import OtherViewSet

class NewViews(APIView):
   def post(self, request, *args, **kwargs):
       # kwargs value here is {'field1':1, 'field2':2...}
       view_func = OtherViewSet({'post':'create'})
       response = view_func(self.request, *args, **kwargs).data

Although the kwargs contains the field values (set through several url named groups), the response always looks like:

{'field1': ['This field is required'], 'field2':['This field is required...

What am I doing wrong? Thanks all :)

Edit:
Once I've got the ID of the created resource, I want to retrieve the resource as rendered by a particular (custom) format (I don't want to return the response object above).

Body:
views.py

from app.views import OtherViewSet

class NewViews(APIView):
    def post(self, request, *args, **kwargs):
        view = OtherViewSet.as_view({'post':'create'})
        response = view(request, *args, **kwargs)
        return response


问:
How to show PDF file in MigraDoc.Rendering.Forms.DocumentPreview (in WinForms)?
I have a simple questions. How can you show a PDf file by using PagePreview?

I have a full pathname document.FileName = "c:\scans\Insurance_34345.pdf";

pagePreview.Preview(document.FileName); or something...

If there another way for showing a pdf. It's okay. I want to show it on a WinForms Form.

I tried this. I don't know what I have to do...

in the Designer

```<code>private MigraDoc.Rendering.Forms.DocumentPreview dpvScannedDoc;
</code>```

Part of the code

```<code>                string fullPadnaam = Path.Combine(defaultPath, document.FileName);
                //PdfDocument pdfDocument = new PdfDocument(fullPadnaam);
                //PdfPage page = new PdfPage(pdfDocument);
                //XGraphics gfx = XGraphics.FromPdfPage(page);
                MigraDoc.DocumentObjectModel.Document pdfDocument = new MigraDoc.DocumentObjectModel.Document();
                pdfDocument.ImagePath = fullPadnaam;

                 var docRenderer = new DocumentRenderer(pdfDocument);
                 docRenderer.PrepareDocument();

                 var inPdfDoc = PdfReader.Open(fullPadnaam, PdfDocumentOpenMode.ReadOnly);
                 for (var i = 0; i < inPdfDoc.PageCount; i++)
                 {
                     pdfDocument.AddSection();
                     docRenderer.PrepareDocument();

                     var page = inPdfDoc.Pages[i];

                     var gfx = XGraphics.FromPdfPage(page);

                     docRenderer.RenderPage(gfx, i + 1);
                 }

                 var renderer = new PdfDocumentRenderer();

                 renderer.Document = pdfDocument;

                 renderer.RenderDocument();

                // MigraDoc.DocumentObjectModel.IO.DdlWriter dw = new MigraDoc.DocumentObjectModel.IO.DdlWriter("HelloWorld.mdddl");
                // dw.WriteDocument(pdfDocument);
                // dw.Close();

                //renderer.PdfDocument.rea(outFilePath);
                //string ddl = MigraDoc.DocumentObjectModel.IO.DdlWriter.WriteToString(document1);
                dpvScannedDoc.Show( pdfDocument);
</code>```

答:
The MigraDoc DocumentPreview can display MDDDL files (your sample code creates a file "HelloWorld.mdddl"), but it cannot display PDF files.

If the MDDDL uses PDF files as images, they will not show up in the preview. They will show when creating a PDF from the MDDDL.

Body:
I have a simple questions. How can you show a PDf file by using PagePreview?

I have a full pathname document.FileName = "c:\scans\Insurance_34345.pdf";

pagePreview.Preview(document.FileName); or something...

If there another way for showing a pdf. It's okay. I want to show it on a WinForms Form.

I tried this. I don't know what I have to do...

in the Designer

private MigraDoc.Rendering.Forms.DocumentPreview dpvScannedDoc;

Part of the code

                string fullPadnaam = Path.Combine(defaultPath, document.FileName);
                //PdfDocument pdfDocument = new PdfDocument(fullPadnaam);
                //PdfPage page = new PdfPage(pdfDocument);
                //XGraphics gfx = XGraphics.FromPdfPage(page);
                MigraDoc.DocumentObjectModel.Document pdfDocument = new MigraDoc.DocumentObjectModel.Document();
                pdfDocument.ImagePath = fullPadnaam;

                 var docRenderer = new DocumentRenderer(pdfDocument);
                 docRenderer.PrepareDocument();

                 var inPdfDoc = PdfReader.Open(fullPadnaam, PdfDocumentOpenMode.ReadOnly);
                 for (var i = 0; i < inPdfDoc.PageCount; i++)
                 {
                     pdfDocument.AddSection();
                     docRenderer.PrepareDocument();

                     var page = inPdfDoc.Pages[i];

                     var gfx = XGraphics.FromPdfPage(page);

                     docRenderer.RenderPage(gfx, i + 1);
                 }

                 var renderer = new PdfDocumentRenderer();

                 renderer.Document = pdfDocument;

                 renderer.RenderDocument();

                // MigraDoc.DocumentObjectModel.IO.DdlWriter dw = new MigraDoc.DocumentObjectModel.IO.DdlWriter("HelloWorld.mdddl");
                // dw.WriteDocument(pdfDocument);
                // dw.Close();

                //renderer.PdfDocument.rea(outFilePath);
                //string ddl = MigraDoc.DocumentObjectModel.IO.DdlWriter.WriteToString(document1);
                dpvScannedDoc.Show( pdfDocument);


问:
When is StringIO used, as opposed to joining a list of strings?
Using StringIO as string buffer is slower than using list as buffer.

When is StringIO used?

```<code>from io import StringIO

def meth1(string):
    a = []
    for i in range(100):
        a.append(string)
    return ''.join(a)

def meth2(string):
    a = StringIO()
    for i in range(100):
        a.write(string)
    return a.getvalue()

if __name__ == '__main__':
    from timeit import Timer
    string = "This is test string"
    print(Timer("meth1(string)", "from __main__ import meth1, string").timeit())
    print(Timer("meth2(string)", "from __main__ import meth2, string").timeit())
</code>```

Results:

```<code>16.7872819901
18.7160351276
</code>```

答:
Well, I don't know if I would like to call that using it as a "buffer", you are just multiplying a string a 100 times, in two complicated ways. Here is an uncomplicated way:

```<code>def meth3(string):
    return string * 100
</code>```

If we add that to your test:

```<code>if __name__ == '__main__':

    from timeit import Timer
    string = "This is test string"
    # Make sure it all does the same:
    assert(meth1(string) == meth3(string))
    assert(meth2(string) == meth3(string))
    print(Timer("meth1(string)", "from __main__ import meth1, string").timeit())
    print(Timer("meth2(string)", "from __main__ import meth2, string").timeit())
    print(Timer("meth3(string)", "from __main__ import meth3, string").timeit())
</code>```

It turns out to be way faster as a bonus:

```<code>21.0300650597
22.4869811535
0.811429977417
</code>```

If you want to create a bunch of strings, and then join them, meth1() is the correct way. There is no point in writing it to StringIO, which is something completely different, namely a string with a file-like stream interface.

Body:
Using StringIO as string buffer is slower than using list as buffer.

When is StringIO used?

from io import StringIO

def meth1(string):
    a = []
    for i in range(100):
        a.append(string)
    return ''.join(a)

def meth2(string):
    a = StringIO()
    for i in range(100):
        a.write(string)
    return a.getvalue()

if __name__ == '__main__':
    from timeit import Timer
    string = "This is test string"
    print(Timer("meth1(string)", "from __main__ import meth1, string").timeit())
    print(Timer("meth2(string)", "from __main__ import meth2, string").timeit())

Results:

16.7872819901
18.7160351276

Body:
Well, I don't know if I would like to call that using it as a "buffer", you are just multiplying a string a 100 times, in two complicated ways. Here is an uncomplicated way:

def meth3(string):
    return string * 100

If we add that to your test:

if __name__ == '__main__':

    from timeit import Timer
    string = "This is test string"
    # Make sure it all does the same:
    assert(meth1(string) == meth3(string))
    assert(meth2(string) == meth3(string))
    print(Timer("meth1(string)", "from __main__ import meth1, string").timeit())
    print(Timer("meth2(string)", "from __main__ import meth2, string").timeit())
    print(Timer("meth3(string)", "from __main__ import meth3, string").timeit())

It turns out to be way faster as a bonus:

21.0300650597
22.4869811535
0.811429977417

If you want to create a bunch of strings, and then join them, meth1() is the correct way. There is no point in writing it to StringIO, which is something completely different, namely a string with a file-like stream interface.


问:
Reading inputs doesn't fill double array completely
I am trying to write a program that reads doubles that are stored in 2 different arrays, add them and print out the 2 arrays added together. I am trying to test my code but as I fill the arrays the prints show me that it doesnt fill the array after the first index is passed.

```<code>#include <stdio.h>

int main() {
    double arrayA[5];
    double arrayB[5];
    double arrayC[5];

    printf("Enter 5 doubles for array A\n");
    for (int i = 0; i < 5; i ++) {
        scanf("%lf", arrayA);
        printf("%lf\n", arrayA[i]);
    }
    printf("Enter 5 doubles for array B\n");
    for (int i = 0; i < 5; i ++) {
        scanf("%lf", arrayB);
        printf("%lf\n", arrayB[i]);
    }

    printf("Here are the two arrays added together\n");
    for (int i = 0; i < 5; i ++) {
        arrayC[i] = arrayA[i] + arrayB[i];
    }

    for (int i = 0; i < 5; i ++) {
        //printf("%lf\n", arrayA[i]);
        //printf("%lf\n", arrayB[i]);
        printf("%lf\n", arrayC[i]);
    }

}
</code>```

this is the output that i get in console for the first array

```<code>Enter 5 doubles for array A
1
1
1.000000
2
2
0.000000
3
3
0.000000
4
4
0.000000
5
5
0.000000
</code>```

答:
scanf("%lf", arrayA) always reads in into the first element of arrayA, whereas
printf("%lf\n", arrayA[i]) prints the i'th element. So you are accessing an uninitialized part of an array, which yields undefined behaviour. Use scanf("%lf", &arrayA[i]) (and equivalent for arrayB).

Body:
I am trying to write a program that reads doubles that are stored in 2 different arrays, add them and print out the 2 arrays added together. I am trying to test my code but as I fill the arrays the prints show me that it doesnt fill the array after the first index is passed.

#include <stdio.h>

int main() {
    double arrayA[5];
    double arrayB[5];
    double arrayC[5];

    printf("Enter 5 doubles for array A\n");
    for (int i = 0; i < 5; i ++) {
        scanf("%lf", arrayA);
        printf("%lf\n", arrayA[i]);
    }
    printf("Enter 5 doubles for array B\n");
    for (int i = 0; i < 5; i ++) {
        scanf("%lf", arrayB);
        printf("%lf\n", arrayB[i]);
    }

    printf("Here are the two arrays added together\n");
    for (int i = 0; i < 5; i ++) {
        arrayC[i] = arrayA[i] + arrayB[i];
    }

    for (int i = 0; i < 5; i ++) {
        //printf("%lf\n", arrayA[i]);
        //printf("%lf\n", arrayB[i]);
        printf("%lf\n", arrayC[i]);
    }

}

this is the output that i get in console for the first array

Enter 5 doubles for array A
1
1
1.000000
2
2
0.000000
3
3
0.000000
4
4
0.000000
5
5
0.000000


问:
Python 3 - Randomly printing items from list of dictionaries without repeat
I have a modified version of some code I am using in a quiz, my problem is my code is using random.choice to select a quiz question, how do I have it still randomly select a question but also not repeat a question already asked to the user?

Appologies for the odd questions and answers in "quiz_data"

Code:

```<code>def InformationToDictionaries():
quiz_data = [
    {
        "question": "What day is it today?",
        "choices": {"a": "Monday", "b": "Friday", "c": "Wednesday", "d": "Sunday"},
        "answer": "Wednesday")
    },
    {
        "question": "What food am I thinking of?",
        "choices": "Pizza", "b": "Curry", "c": "Pie", "d": "Pasta"},
        "answer": "Curry"
    }
]
return quiz_data

def Quiz():
    score = 0
    for i in range(1,6):
        q = random.choice(quiz_data)
        print("Q." + str(i) + ": ", q.get("question"))
        print('\n'.join("{}: {}".format(x, y) for x, y in q.get("choices").items()))
        userans = str(input("\n>"))

    if userans == q.get("answer"):
        print("Correct")
        score = score + 1
    else: print("Incorrect")

quiz_data = InformationToDictionaries()
Quiz()
</code>```

Many thanks for any responses in advance, if you have any suggestions for me please let me know, this is my first question.

--------EDIT 1----------

Modified code after first suggestions:

```<code>def Quiz():
score = 0
random.shuffle(quiz_data)
for question in quiz_data:
    q = random.choice(quiz_data)
    print("Q." + str("1") + ": ", q.get("question"))
    print('\n'.join("{}: {}".format(x, y) for x, y in q.get("choices").items()))
</code>```

答:
There are several ways. Like removing the question from the list after you use it or shuffle the array and iterate through it.

To get all questions by removing them from the array each time they are picked:

```<code>while(len(quiz_data) != 0):
  q = random.choice(quiz_data)
  quiz_data.remove(q)
  #do stuff with q
</code>```

If you want to iterate through a shuffled array:

```<code>from random import shuffle
shuffle(quiz_data)
for question in quiz_data:
  pass #this is only here for the code to run
  #do stuff with question
</code>```

Both these ways are going to give you all the questions in a random order

Body:
I have a modified version of some code I am using in a quiz, my problem is my code is using random.choice to select a quiz question, how do I have it still randomly select a question but also not repeat a question already asked to the user?

Appologies for the odd questions and answers in "quiz_data"

Code:

def InformationToDictionaries():
quiz_data = [
    {
        "question": "What day is it today?",
        "choices": {"a": "Monday", "b": "Friday", "c": "Wednesday", "d": "Sunday"},
        "answer": "Wednesday")
    },
    {
        "question": "What food am I thinking of?",
        "choices": "Pizza", "b": "Curry", "c": "Pie", "d": "Pasta"},
        "answer": "Curry"
    }
]
return quiz_data

def Quiz():
    score = 0
    for i in range(1,6):
        q = random.choice(quiz_data)
        print("Q." + str(i) + ": ", q.get("question"))
        print('\n'.join("{}: {}".format(x, y) for x, y in q.get("choices").items()))
        userans = str(input("\n>"))

    if userans == q.get("answer"):
        print("Correct")
        score = score + 1
    else: print("Incorrect")

quiz_data = InformationToDictionaries()
Quiz()

Many thanks for any responses in advance, if you have any suggestions for me please let me know, this is my first question.

--------EDIT 1----------

Modified code after first suggestions:

def Quiz():
score = 0
random.shuffle(quiz_data)
for question in quiz_data:
    q = random.choice(quiz_data)
    print("Q." + str("1") + ": ", q.get("question"))
    print('\n'.join("{}: {}".format(x, y) for x, y in q.get("choices").items()))

Body:
There are several ways. Like removing the question from the list after you use it or shuffle the array and iterate through it.

To get all questions by removing them from the array each time they are picked:

while(len(quiz_data) != 0):
  q = random.choice(quiz_data)
  quiz_data.remove(q)
  #do stuff with q

If you want to iterate through a shuffled array:

from random import shuffle
shuffle(quiz_data)
for question in quiz_data:
  pass #this is only here for the code to run
  #do stuff with question

Both these ways are going to give you all the questions in a random order


问:
c++: using a pointer to access a buffer vs using an incremental variable
I am writing a delay based on a circular buffer. This is my implementation.

```<code>#include <iostream>

using namespace std;

int main() {
    cout << "Fixed delay with circular buffer" << endl;
    int dtime = 5;
    int buffersize = 10;
    auto *in = new int[buffersize];
    auto *del = new int[dtime];
    auto *out = new int[buffersize];
    int p = 0;
    // zero-initialise the delay line
    for (int i = 0; i < dtime; i++) {
        del[i] = 0;
    }
    // fill the in buffer
    for (int i = 0; i < buffersize; i++) {
        in[i] = i;
    }

    // apply delay
    for (int i = 0; i < buffersize; i++) {
        // read
        out[i] = del[p];
        // write
        del[p] = in[i];
        // update pointer
        p = (p != dtime-1? p+1 : 0);
    }

    for (int i = 0; i < buffersize; i++) {
        cout << out[i] << ' ';
    }

    delete[] in;
    delete[] out;
    delete[] del;

    return 0;
}
</code>```

And this is the result: 0 0 0 0 0 0 1 2 3 4.

Reading from this book, the Author implements a pointer to the delay line for the writing/reading operations. That means, I have to make the p point to the head of the delay line, i.e. int *p = del and dereference the pointer when accessing the delay line, i.e. out[i] = del[*p] for the reading and del[p] = in[i] for the writing operation. Finally, I update the value as done before.

However,  I get this result: 8 9 0 0 0 0 0 0 0 0. Moreover, if I inspect the value inside the pointer, I get this progression 0 1 2 3 4 0 6 7 8 9, which is quite strange.
I'm trying to understand why such a behaviour, since I expect the two version be the same.

I attach also the version with the pointer for completeness.

```<code>#include <iostream>

using namespace std;

int main() {
    cout << "Fixed delay with circular buffer" << endl;
    int dtime = 5;
    int buffersize = 10;
    auto *in = new int[buffersize];
    auto *del = new int[dtime];
    auto *out = new int[buffersize];
    int *p = del;
    // zero-initialise the delay line
    for (int i = 0; i < dtime; i++) {
        del[i] = 0;
    }
    // fill the in buffer
    for (int i = 0; i < buffersize; i++) {
        in[i] = i;
    }

    // apply delay
    for (int i = 0; i < buffersize; i++) {
        cout << *p << ' ';
        // read
        out[i] = del[*p];
        // write
        del[*p] = in[i];
        // update pointer
        *p = (*p != dtime-1? *p+1 : 0);
    }

    for (int i = 0; i < buffersize; i++) {
        cout << endl << out[i] << ' ';
    }

    delete[] in;
    delete[] out;
    delete[] del;

    return 0;
}
</code>```

答:
You're not handling the pointer correctly.  *p replaces the del[p] operation from the original code.

```<code>out[i] = *p;
*p = in[i];
</code>```

The "update pointer" code then needs to update the pointer, not the value that it points to.

```<code>p = p != &del[dtime - 1] ? p + 1 : del;
</code>```

or

```<code>if (++p == &del[dtime])
    p = del;
</code>```

Body:
I am writing a delay based on a circular buffer. This is my implementation.

#include <iostream>

using namespace std;

int main() {
    cout << "Fixed delay with circular buffer" << endl;
    int dtime = 5;
    int buffersize = 10;
    auto *in = new int[buffersize];
    auto *del = new int[dtime];
    auto *out = new int[buffersize];
    int p = 0;
    // zero-initialise the delay line
    for (int i = 0; i < dtime; i++) {
        del[i] = 0;
    }
    // fill the in buffer
    for (int i = 0; i < buffersize; i++) {
        in[i] = i;
    }

    // apply delay
    for (int i = 0; i < buffersize; i++) {
        // read
        out[i] = del[p];
        // write
        del[p] = in[i];
        // update pointer
        p = (p != dtime-1? p+1 : 0);
    }

    for (int i = 0; i < buffersize; i++) {
        cout << out[i] << ' ';
    }

    delete[] in;
    delete[] out;
    delete[] del;

    return 0;
}

And this is the result: 0 0 0 0 0 0 1 2 3 4.

Reading from this book, the Author implements a pointer to the delay line for the writing/reading operations. That means, I have to make the p point to the head of the delay line, i.e. int *p = del and dereference the pointer when accessing the delay line, i.e. out[i] = del[*p] for the reading and del[p] = in[i] for the writing operation. Finally, I update the value as done before.

However,  I get this result: 8 9 0 0 0 0 0 0 0 0. Moreover, if I inspect the value inside the pointer, I get this progression 0 1 2 3 4 0 6 7 8 9, which is quite strange.
I'm trying to understand why such a behaviour, since I expect the two version be the same.

I attach also the version with the pointer for completeness.

#include <iostream>

using namespace std;

int main() {
    cout << "Fixed delay with circular buffer" << endl;
    int dtime = 5;
    int buffersize = 10;
    auto *in = new int[buffersize];
    auto *del = new int[dtime];
    auto *out = new int[buffersize];
    int *p = del;
    // zero-initialise the delay line
    for (int i = 0; i < dtime; i++) {
        del[i] = 0;
    }
    // fill the in buffer
    for (int i = 0; i < buffersize; i++) {
        in[i] = i;
    }

    // apply delay
    for (int i = 0; i < buffersize; i++) {
        cout << *p << ' ';
        // read
        out[i] = del[*p];
        // write
        del[*p] = in[i];
        // update pointer
        *p = (*p != dtime-1? *p+1 : 0);
    }

    for (int i = 0; i < buffersize; i++) {
        cout << endl << out[i] << ' ';
    }

    delete[] in;
    delete[] out;
    delete[] del;

    return 0;
}

Body:
You're not handling the pointer correctly.  *p replaces the del[p] operation from the original code.

out[i] = *p;
*p = in[i];

The "update pointer" code then needs to update the pointer, not the value that it points to.

p = p != &del[dtime - 1] ? p + 1 : del;

or

if (++p == &del[dtime])
    p = del;


问:
Mongo Connection Error in Azure Linux App Service using docker image
I've deployed a docker image to an Azure Linux App Service which contains a node app. The app is failing to start properly because it can't connect to a Mongo version of Cosmo DB.

error:  MongoError: failed to connect to server [***.documents.azure.com:10255] on first connect [MongoError: getaddrinfo EAI_AGAIN ***.documents.azure.com:10255]

I'm using mongoose and the following to connect:

```<code>mongoose.connect(process.env.MONGODB_URL, { useMongoClient: true });
</code>```

Running the app in a container locally on my machine works. Is there something I'm missing? Some DNS/Firewall setting?

Dockerfile:

```<code>FROM mhart/alpine-node:latest

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
COPY package.json package-lock.json ./

RUN npm install --production

# Bundle app source
COPY . .

EXPOSE 4000

CMD [ "node", "main.js" ]
</code>```

答:
The problem is to do with the image I was using:

```<code>FROM mhart/alpine-node:latest
</code>```

There seems to be a problem with DNS when using this image when deploying it to Azure.

Switched to use

```<code>FROM node:latest
</code>```

and everything is now working.

Body:
I've deployed a docker image to an Azure Linux App Service which contains a node app. The app is failing to start properly because it can't connect to a Mongo version of Cosmo DB.

error:  MongoError: failed to connect to server [***.documents.azure.com:10255] on first connect [MongoError: getaddrinfo EAI_AGAIN ***.documents.azure.com:10255]

I'm using mongoose and the following to connect:

mongoose.connect(process.env.MONGODB_URL, { useMongoClient: true });

Running the app in a container locally on my machine works. Is there something I'm missing? Some DNS/Firewall setting?

Dockerfile:

FROM mhart/alpine-node:latest

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
COPY package.json package-lock.json ./

RUN npm install --production

# Bundle app source
COPY . .

EXPOSE 4000

CMD [ "node", "main.js" ]

Body:
The problem is to do with the image I was using:

FROM mhart/alpine-node:latest

There seems to be a problem with DNS when using this image when deploying it to Azure.

Switched to use

FROM node:latest

and everything is now working.


问:
log4j doesn't write in log file on tomcat7 (ubuntu server)
This is my log4j.properties file:

```<code># LOG4J configuration
log4j.rootLogger=INFO, Appender1,Appender2
log4j.logger.org.hibernate=info
log4j.logger.org.quartz=info

log4j.appender.Appender1=org.apache.log4j.ConsoleAppender
log4j.appender.Appender1.layout=org.apache.log4j.PatternLayout
log4j.appender.Appender1.layout.ConversionPattern=%-7p %d [%t] %c %x - %m%n

log4j.appender.Appender2=org.apache.log4j.FileAppender
log4j.appender.Appender2.File=/home/diego/proyect/log/general.log
log4j.appender.Appender2.layout=org.apache.log4j.PatternLayout
log4j.appender.Appender2.layout.ConversionPattern=%-7p %d [%t] %c %x - %m%n
</code>```

Locally works on my windows machine, but on the server (ubuntu 16.04) side the web application cannot write on the .log file, already modified permissions for the file:

```<code>chmod 777 /home/diego/proyect/log/general.log
</code>```

this is the resuls of ls -lhs on the log directory:

```<code>-rwxrwxrwx 1 diego diego 0 Nov 16 14:23 general.log
</code>```

Also not sure which is the tomcat user on the server.

答:
I solved, it seems I need to add the log4j.properties files into the classpath, my project has the following structure:

main

src/main/java

src/main/resources/log4j.properties

webapp

WEB-INF/log4j.properties

So I put the file under src/main/resources directory and it works.

Body:
This is my log4j.properties file:

# LOG4J configuration
log4j.rootLogger=INFO, Appender1,Appender2
log4j.logger.org.hibernate=info
log4j.logger.org.quartz=info

log4j.appender.Appender1=org.apache.log4j.ConsoleAppender
log4j.appender.Appender1.layout=org.apache.log4j.PatternLayout
log4j.appender.Appender1.layout.ConversionPattern=%-7p %d [%t] %c %x - %m%n

log4j.appender.Appender2=org.apache.log4j.FileAppender
log4j.appender.Appender2.File=/home/diego/proyect/log/general.log
log4j.appender.Appender2.layout=org.apache.log4j.PatternLayout
log4j.appender.Appender2.layout.ConversionPattern=%-7p %d [%t] %c %x - %m%n

Locally works on my windows machine, but on the server (ubuntu 16.04) side the web application cannot write on the .log file, already modified permissions for the file:

chmod 777 /home/diego/proyect/log/general.log

this is the resuls of ls -lhs on the log directory:

-rwxrwxrwx 1 diego diego 0 Nov 16 14:23 general.log

Also not sure which is the tomcat user on the server.


问:
How to set the Log_Level in Ada library alog
I am using the library alog for the first time in a project. I have a problem understanding how to set the log level for all subsequent log commands.

See my test program:

```<code>with Alog;                         use Alog;
with Alog.Logger;
with Alog.Policy_DB;               use Alog.Policy_DB;

procedure Test_Loglevel
is
   L : Logger.Instance (Init => True);

   procedure Act_And_Log
   is begin
      null;
      L.Log_Message (Alog.Debug, "very detailed, only for debugging");
      null;
      L.Log_Message (Alog.Info,  "some more detailed infos");
      null;
      L.Log_Message (Alog.Notice, "general messages for interactive use");
      null;
      L.Log_Message (Alog.Warning, "something serious happened");
      null;
      L.Log_Message (Alog.Error, "error messages should always be displayed");
   end Act_And_Log;

begin
   --
   -- all logs should be displayed
   --
   Set_Loglevel ("*", Debug);
   Set_Default_Loglevel (Debug);
   Act_And_Log;
   --
   -- only error
   --
   Set_Loglevel ("*", Error);
   Set_Default_Loglevel (Error);
   Act_And_Log;

end Test_Loglevel;
</code>```

I would expect that all 5 messages are displayed the first time and only the error message is displayed the second time. The actual output, however, shows the 5 messages twice!

What do I have to do to filter the output based on severity?

答: I directly asked the authors of alog. They responded with a patch. I still find the doc a bit misleading.</p>

Body:
I am using the library alog for the first time in a project. I have a problem understanding how to set the log level for all subsequent log commands.

See my test program:

with Alog;                         use Alog;
with Alog.Logger;
with Alog.Policy_DB;               use Alog.Policy_DB;

procedure Test_Loglevel
is
   L : Logger.Instance (Init => True);

   procedure Act_And_Log
   is begin
      null;
      L.Log_Message (Alog.Debug, "very detailed, only for debugging");
      null;
      L.Log_Message (Alog.Info,  "some more detailed infos");
      null;
      L.Log_Message (Alog.Notice, "general messages for interactive use");
      null;
      L.Log_Message (Alog.Warning, "something serious happened");
      null;
      L.Log_Message (Alog.Error, "error messages should always be displayed");
   end Act_And_Log;

begin
   --
   -- all logs should be displayed
   --
   Set_Loglevel ("*", Debug);
   Set_Default_Loglevel (Debug);
   Act_And_Log;
   --
   -- only error
   --
   Set_Loglevel ("*", Error);
   Set_Default_Loglevel (Error);
   Act_And_Log;

end Test_Loglevel;

I would expect that all 5 messages are displayed the first time and only the error message is displayed the second time. The actual output, however, shows the 5 messages twice!

What do I have to do to filter the output based on severity?


问:
What's wrong with the prime number generator?
I wrote a code. The goal was to find the prime numbers up to 1000. It compiles and runs, but it seems that the table is blank at the end. What is the reason for this? How do I fix it? Thanks.</p>

```<code>#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;

int primes[20];
bool prime;
int main()
{
    int i;
for(i=2;i<=1000;i++){
prime=true;
int ii;
   for (ii=1;ii<=sizeof(primes);ii++){
       if (i/ii==floor(i/ii)){
                             prime=false;
                             }
       }
       if (prime==true){
       primes[sizeof(primes+1)]=i;
   }
}
for (i=1;i<=20;i++){
cout << primes[i] << endl;
system("pause");
}
}
</code>```

答:
This comparison:

```<code>i/ii==floor(i/ii)
</code>```

is always true, because you are doing integer division. Both i and ii are integers, so C++ does an integer division when calculating i/ii.

Body:
I wrote a code. The goal was to find the prime numbers up to 1000. It compiles and runs, but it seems that the table is blank at the end. What is the reason for this? How do I fix it? Thanks.

#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;

int primes[20];
bool prime;
int main()
{
    int i;
for(i=2;i<=1000;i++){
prime=true;
int ii;
   for (ii=1;ii<=sizeof(primes);ii++){
       if (i/ii==floor(i/ii)){
                             prime=false;
                             }
       }
       if (prime==true){
       primes[sizeof(primes+1)]=i;
   }
}
for (i=1;i<=20;i++){
cout << primes[i] << endl;
system("pause");
}
}

Body:
This comparison:

i/ii==floor(i/ii)

is always true, because you are doing integer division. Both i and ii are integers, so C++ does an integer division when calculating i/ii.


问:
MVC Razor view DisplayFor text contents <sup
How do we display superscript inside an @HTML.DisplayFor textbox?

I have the object like this:

```<code><DisplayName("Equation")>
<AllowHtml>
Public Property EquationHTML As String
</code>```

The view says this:

```<code>@Html.DisplayFor(Function(modelItem) item.EquationHTML)
</code>```

The string contents are:

Q=0.3*(CDA[sup]0.6]/sup])*(MAP[sup]2.138[/sup])

(pretend that the square brackets are angle brackets, it turns out that this bulletin board understand the sup tag.

Any Ideas?

答:
I didn't read DavidG's answer close enough.
I tried:

```<code>@Html.Raw(Function(modelItem) item.EquationHTML)
</code>```

David was trying to tell me to drop the lambda like this:

```<code>@Html.Raw(item.EquationHTML)
</code>```

So when you use the Raw helper, strike the lambda function.

Title: MVC Razor view DisplayFor text contents <sup</sup>

Body:
How do we display superscript inside an @HTML.DisplayFor textbox?

I have the object like this:

<DisplayName("Equation")>
<AllowHtml>
Public Property EquationHTML As String

The view says this:

@Html.DisplayFor(Function(modelItem) item.EquationHTML)

The string contents are:

Q=0.3*(CDA[sup]0.6]/sup])*(MAP[sup]2.138[/sup])

(pretend that the square brackets are angle brackets, it turns out that this bulletin board understand the sup tag.

Any Ideas?

Body:
I didn't read DavidG's answer close enough.
I tried:

@Html.Raw(Function(modelItem) item.EquationHTML)

David was trying to tell me to drop the lambda like this:

@Html.Raw(item.EquationHTML)

So when you use the Raw helper, strike the lambda function.


问:
check for the last space in a string?
I have a string that goes "Quisque pretium magna ac aliquet interdum. Mauris posuere, risus non mollis placerat, diam ligula commodo justo, ac aliquet velit ante a ipsum." stored in a variable T and I have a variable L which is set to 30.

I am trying to write a loop that will print the string out, but in such a way that only L amount of characters (30 in this case) can fit on the line. If there is a word which goes over the limit (As in, it starts on character 28 and ends on 32), then I am trying to store the index at which point the last space was (The index of the most recent " ") in a variable called s. This is what I have, but I'm not sure where to go from here:

```<code>finalstr = ""
reg = re.compile('[a-z]')
for i in range(0, L):
    if T[i] >= L and reg.search(T[i]):
        finalstr += "\n"
    else:
        finalstr += T[i]

return finalstr
</code>```

What I want to get is:

```<code>Quisque pretium magna ac
aliquet interdum. Mauris
prosuere, risus non
mollis placerat, diam
ligula commodo justo, ac
aliquet velit ante a
ipsum.
</code>```

However, this is the traceback I get, what am I doing wrong?

```<code>Traceback (most recent call last):
File "problem.py", line 146, in <module>
print wrap(T, L)
File "problem.py", line 122, in wrap
if T[i] >= L and reg.search(T[i]):
IndexError: list index out of range
</code>```

答:
My example will probably need to be hardened in case of exceptions or weird input values, but I think you can accomplish this with something like the following steps:

Cut the string off at 30 characters

If needed, split the string on the last whitespace.

Maybe something like this:

```<code>input = "Quisque pretium magna ac aliquet interdum. Mauris posuere, risus non mollis placerat, diam ligula commodo justo, ac aliquet velit ante a ipsum."
final_string = ''
cut_length = 30
while input:
    temp = input[:cut_length]
    if input[cut_length] != ' ':
        temp = temp.split(" ", 1)[0]
    final_str += temp + "\n"
    input = input.replace(temp, '', 1)
print(final_str)
</code>```

Title: check for the last space in a string?

Body:
I have a string that goes "Quisque pretium magna ac aliquet interdum. Mauris posuere, risus non mollis placerat, diam ligula commodo justo, ac aliquet velit ante a ipsum." stored in a variable T and I have a variable L which is set to 30.

I am trying to write a loop that will print the string out, but in such a way that only L amount of characters (30 in this case) can fit on the line. If there is a word which goes over the limit (As in, it starts on character 28 and ends on 32), then I am trying to store the index at which point the last space was (The index of the most recent " ") in a variable called s. This is what I have, but I'm not sure where to go from here:

finalstr = ""
reg = re.compile('[a-z]')
for i in range(0, L):
    if T[i] >= L and reg.search(T[i]):
        finalstr += "\n"
    else:
        finalstr += T[i]

return finalstr

What I want to get is:

Quisque pretium magna ac
aliquet interdum. Mauris
prosuere, risus non
mollis placerat, diam
ligula commodo justo, ac
aliquet velit ante a
ipsum.

However, this is the traceback I get, what am I doing wrong?

Traceback (most recent call last):
File "problem.py", line 146, in <module>
print wrap(T, L)
File "problem.py", line 122, in wrap
if T[i] >= L and reg.search(T[i]):
IndexError: list index out of range

Body:
My example will probably need to be hardened in case of exceptions or weird input values, but I think you can accomplish this with something like the following steps:

Cut the string off at 30 characters

If needed, split the string on the last whitespace.

Maybe something like this:

input = "Quisque pretium magna ac aliquet interdum. Mauris posuere, risus non mollis placerat, diam ligula commodo justo, ac aliquet velit ante a ipsum."
final_string = ''
cut_length = 30
while input:
    temp = input[:cut_length]
    if input[cut_length] != ' ':
        temp = temp.split(" ", 1)[0]
    final_str += temp + "\n"
    input = input.replace(temp, '', 1)
print(final_str)


问:
Extracting JSON generic string from text file
I have a file the contents of which are formatted as follows:

```<code>{
  "title": "This is a test }",
  "date": "2017-11-16T20:47:16+00:00"
}

This is a test }
</code>```

I'd like to extract just the JSON heading via regex (which I think is the most sensible approach here). However, in the future the JSON might change, (e.g. it might have extra fields added, or the current fields could change), so I'd like to keep the regex flexible. I have tried with the solution suggested here, however, that seems a bit too simplistic for my use case: in fact, the above "tricks" the regex, as shown in this regex101.com example.

Since my knowledge of regex is not that advanced, I'd like to know whether there's a regex approach that is able to cover my use case.

Thank you!

答:
If the JSON always starts with { at the left margin and ends with } at the right margin, with everything else indented as you show, you can use the regular expression

```<code>/^{.*?^}$/ms
</code>```

The m modifier makes ^ and $ match the beginning and end of lines, not the whole string. The s modifier allows . to match newlines.

var str = `{
  "title": "This is a test }",
  "date": "2017-11-16T20:47:16+00:00"
}

This is a test }
`;

var match = str.match(/^{.*?^}$/ms);
if (match) {
  var data = JSON.parse(match[0]);
}
console.log(data);```

Body:
I have a file the contents of which are formatted as follows:

{
  "title": "This is a test }",
  "date": "2017-11-16T20:47:16+00:00"
}

This is a test }

I'd like to extract just the JSON heading via regex (which I think is the most sensible approach here). However, in the future the JSON might change, (e.g. it might have extra fields added, or the current fields could change), so I'd like to keep the regex flexible. I have tried with the solution suggested here, however, that seems a bit too simplistic for my use case: in fact, the above "tricks" the regex, as shown in this regex101.com example.

Since my knowledge of regex is not that advanced, I'd like to know whether there's a regex approach that is able to cover my use case.

Thank you!

Body:
If the JSON always starts with { at the left margin and ends with } at the right margin, with everything else indented as you show, you can use the regular expression

/^{.*?^}$/ms

The m modifier makes ^ and $ match the beginning and end of lines, not the whole string. The s modifier allows . to match newlines.

var str = `{
  "title": "This is a test }",
  "date": "2017-11-16T20:47:16+00:00"
}

This is a test }
`;

var match = str.match(/^{.*?^}$/ms);
if (match) {
  var data = JSON.parse(match[0]);
}
console.log(data);


问:
Python Column Generation with AVERAGEIF for LARGER DATASET
I've poured over StackOverflow got part of the way there with groupby in my last question, but groupby can't seem to accomplish what I'm looking for. I have data tables with the unique letter and time combinations, and I'm trying to get the "averageif" of those values into the second table, BUT NOT ALL OF THE VALUES.

```<code>Letter  Time   Value          Time      A2       B3
A1      1:00    7.97          1:00     3.16     4.32
A1      2:00    3.56          2:00     5.06     6.76
A2      1:00    3.16
A2      2:00    9.09
A2      2:00    0.64
A2      2:00    5.44
A3      1:00    1.53
B1      2:00    4.55
B1      3:00    7.36
B2      1:00    3.81
B2      2:00    7.30
B3      1:00    4.34
B3      1:00    4.30
B3      2:00    4.61
B3      2:00    8.91
</code>```

I can't figure out how to write something that can intelligently calculate only the averages, I'm, looking based on the two-column analysis. I have all the code to pull this data in from a CSV, generate the unique values, etc. but it doesn't seem relevant. Thanks for any advice, I just can't get past this step.

答:
Select your desired rows with isin and just call groupby + mean. Make a final unstack call to reshape your output.

```<code>df[df.Letter.isin(['A2', 'B3'])]\
     .groupby(['Letter', 'Time']).Value.mean().unstack().T

Letter        A2    B3
Time
1:00    3.160000  4.32
2:00    5.056667  6.76
</code>```

Body:
I've poured over StackOverflow got part of the way there with groupby in my last question, but groupby can't seem to accomplish what I'm looking for. I have data tables with the unique letter and time combinations, and I'm trying to get the "averageif" of those values into the second table, BUT NOT ALL OF THE VALUES.

Letter  Time   Value          Time      A2       B3
A1      1:00    7.97          1:00     3.16     4.32
A1      2:00    3.56          2:00     5.06     6.76
A2      1:00    3.16
A2      2:00    9.09
A2      2:00    0.64
A2      2:00    5.44
A3      1:00    1.53
B1      2:00    4.55
B1      3:00    7.36
B2      1:00    3.81
B2      2:00    7.30
B3      1:00    4.34
B3      1:00    4.30
B3      2:00    4.61
B3      2:00    8.91

I can't figure out how to write something that can intelligently calculate only the averages, I'm, looking based on the two-column analysis. I have all the code to pull this data in from a CSV, generate the unique values, etc. but it doesn't seem relevant. Thanks for any advice, I just can't get past this step.

Body:
Select your desired rows with isin and just call groupby + mean. Make a final unstack call to reshape your output.

df[df.Letter.isin(['A2', 'B3'])]\
     .groupby(['Letter', 'Time']).Value.mean().unstack().T

Letter        A2    B3
Time
1:00    3.160000  4.32
2:00    5.056667  6.76


问:
Different ways to vertically align in CSS
I'm a bit confused about various options to vertically align elements. I've read through several posts which explain each of the options stand-alone, but failing to find anything that explains the different use cases of each.

In particular, what are the differences between the following, when to (not) use them, and why?

align-items: center;

vertical-align: middle;

margin: auto 0;

Also, it seems that in many cases there needs to be a fixed height defined and display set to flex to make the alignment work, which is not good for responsive design. How can this be avoided?

答:
The first one align-items: center is used with display: flex. This aligns all children elements vertically.
Second one vertical-align: middle can be used in two contexts:

to vertically align an inline element's box inside its containing line box. For example, it could be used to vertically align an  in a line of text:

to vertically align the content of a cell in a table

Third one margin: auto 0 works only if you have margins on top and bottom side (does not mean that they need to be specified, what I mean is, you cant center span or any other inline element with margin: auto 0).
Using flex in my opinion is the best option and its definitely not bad for responsive design. And you dont need fixed height.
I hope this answers your question.

Body:
The first one align-items: center is used with display: flex. This aligns all children elements vertically.
Second one vertical-align: middle can be used in two contexts:

to vertically align an inline element's box inside its containing line box. For example, it could be used to vertically align an <img> in a line of text:

to vertically align the content of a cell in a table

Third one margin: auto 0 works only if you have margins on top and bottom side (does not mean that they need to be specified, what I mean is, you cant center span or any other inline element with margin: auto 0).
Using flex in my opinion is the best option and its definitely not bad for responsive design. And you dont need fixed height.
I hope this answers your question.