问:
Java 8 Stream: Defining collectors based on other collectors
I'm new to using Java 8 Stream APIs but I'm looking to use it for the following problem.  Say I have a POJO called InputRecord containing name, fieldA, and fieldB properties that can represent each row record of the following:

```<code>name | fieldA | fieldB
----------------------
A    | 100    | 1.1
A    | 150    | 2.0
B    | 200    | 1.5
A    | 120    | 1.3
</code>```

InputRecord would look like:

```<code>public class InputRecord {
    private String name;
    private Integer fieldA;
    private BigDecimal fieldB;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getFieldA() {
        return fieldA;
    }

    public void setFieldA(Integer fieldA) {
        this.fieldA = fieldA;
    }

    public BigDecimal getFieldB() {
        return fieldB;
    }

    public void setFieldB(BigDecimal fieldB) {
        this.fieldB = fieldB;
    }
}
</code>```

Those four records above need to be combined into two records grouped by name, where:

Property fieldA is summed

Property fieldB is summed

The combined records includes a fieldC property which is the result of multiplying the accumulating sums of both fieldA and fieldB.

Therefore the results for above would be:

```<code>name | sumOfFieldA | sumOfFieldB | fieldC (sumOfFieldA*sumOfFieldB)
-------------------------------------------------------------------
A    | 370         | 4.4         | 1628
B    | 200         | 1.5         | 300
</code>```

A different POJO called OutputRecord would represent each row record of the combined records:

```<code>public class OutputRecord {
    private String name;
    private Integer sumOfFieldA;
    private BigDecimal sumOfFieldB;
    private BigDecimal fieldC;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getSumOfFieldA() {
        return sumOfFieldA;
    }

    public void setSumOfFieldA(Integer sumOfFieldA) {
        this.sumOfFieldA = sumOfFieldA;
    }

    public BigDecimal getSumOfFieldB() {
        return sumOfFieldB;
    }

    public void setSumOfFieldB(BigDecimal sumOfFieldB) {
        this.sumOfFieldB = sumOfFieldB;
    }

    public BigDecimal getFieldC() {
        return fieldC;
    }

    public void setFieldC(BigDecimal fieldC) {
        this.fieldC = fieldC;
    }
}
</code>```

What are some good approaches/solutions for transforming a list of InputRecords into a list of OutputRecords?

I was seeing if the following link would help but I got stuck trying to put collectors for fieldA and fieldB together in order to form a new collector for fieldC:
Java 8 Stream: groupingBy with multiple Collectors

```<code>Collector<InputRecord, ?, Integer> fieldACollector = Collectors.summingInt(InputRecord::getFieldA);
Collector<InputRecord, ?, BigDecimal> fieldBCollector = Collectors.reducing(BigDecimal.ZERO, InputRecord::getFieldB, BigDecimal::add);

List<Collector<InputRecord, ?, ?>> collectors = Arrays.asList(fieldACollector, fieldBCollector); // need a fieldCCollector object in the list
</code>```

The collectors object would then be used to create a complexCollector object (as per the accepted answer by Tagir Valeev in the above link).

答:
To me the cleanest way is to build a custom collector for that. There are multiple lines of code here, but you can hide it under a method, so your ultimate operation would look like this:

```<code>Collection<OutputRecord> output = List.of(first, second, thrid, fourth)
            .stream()
            .parallel()
            .collect(toOutputRecords());
</code>```

While the actual toOutputRecords would be:

```<code> private static Collector<InputRecord, ?, Collection<OutputRecord>> toOutputRecords() {
    class Acc {

        Map<String, OutputRecord> map = new HashMap<>();

        void add(InputRecord elem) {
            String value = elem.getName();
            // constructor without fieldC since you compute it at the end
            OutputRecord record = new OutputRecord(value, elem.getFieldA(), elem.getFieldB());
            mergeIntoMap(map, value, record);
        }

        Acc merge(Acc right) {
            Map<String, OutputRecord> leftMap = map;
            Map<String, OutputRecord> rightMap = right.map;

            for (Entry<String, OutputRecord> entry : rightMap.entrySet()) {
                mergeIntoMap(leftMap, entry.getKey(), entry.getValue());
            }
            return this;
        }

        private void mergeIntoMap(Map<String, OutputRecord> map, String value, OutputRecord record) {

            map.merge(value, record, (left, right) -> {
                left.setSumOfFieldA(left.getSumOfFieldA() + right.getSumOfFieldA());
                left.setSumOfFieldB(left.getSumOfFieldB().add(right.getSumOfFieldB()));

                return left;
            });
        }

        public Collection<OutputRecord> finisher() {
            for (Entry<String, OutputRecord> e : map.entrySet()) {
                OutputRecord output = e.getValue();
                output.setFieldC(output.getSumOfFieldB().multiply(BigDecimal.valueOf(output.getSumOfFieldA())));
            }
            return map.values();
        }

    }
    return Collector.of(Acc::new, Acc::add, Acc::merge, Acc::finisher);
}
</code>```

Body:
I'm new to using Java 8 Stream APIs but I'm looking to use it for the following problem.  Say I have a POJO called InputRecord containing name, fieldA, and fieldB properties that can represent each row record of the following:

name | fieldA | fieldB
----------------------
A    | 100    | 1.1
A    | 150    | 2.0
B    | 200    | 1.5
A    | 120    | 1.3

InputRecord would look like:

public class InputRecord {
    private String name;
    private Integer fieldA;
    private BigDecimal fieldB;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getFieldA() {
        return fieldA;
    }

    public void setFieldA(Integer fieldA) {
        this.fieldA = fieldA;
    }

    public BigDecimal getFieldB() {
        return fieldB;
    }

    public void setFieldB(BigDecimal fieldB) {
        this.fieldB = fieldB;
    }
}

Those four records above need to be combined into two records grouped by name, where:

Property fieldA is summed

Property fieldB is summed

The combined records includes a fieldC property which is the result of multiplying the accumulating sums of both fieldA and fieldB.

Therefore the results for above would be:

name | sumOfFieldA | sumOfFieldB | fieldC (sumOfFieldA*sumOfFieldB)
-------------------------------------------------------------------
A    | 370         | 4.4         | 1628
B    | 200         | 1.5         | 300

A different POJO called OutputRecord would represent each row record of the combined records:

public class OutputRecord {
    private String name;
    private Integer sumOfFieldA;
    private BigDecimal sumOfFieldB;
    private BigDecimal fieldC;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getSumOfFieldA() {
        return sumOfFieldA;
    }

    public void setSumOfFieldA(Integer sumOfFieldA) {
        this.sumOfFieldA = sumOfFieldA;
    }

    public BigDecimal getSumOfFieldB() {
        return sumOfFieldB;
    }

    public void setSumOfFieldB(BigDecimal sumOfFieldB) {
        this.sumOfFieldB = sumOfFieldB;
    }

    public BigDecimal getFieldC() {
        return fieldC;
    }

    public void setFieldC(BigDecimal fieldC) {
        this.fieldC = fieldC;
    }
}

What are some good approaches/solutions for transforming a list of InputRecords into a list of OutputRecords?

I was seeing if the following link would help but I got stuck trying to put collectors for fieldA and fieldB together in order to form a new collector for fieldC:
Java 8 Stream: groupingBy with multiple Collectors

Collector<InputRecord, ?, Integer> fieldACollector = Collectors.summingInt(InputRecord::getFieldA);
Collector<InputRecord, ?, BigDecimal> fieldBCollector = Collectors.reducing(BigDecimal.ZERO, InputRecord::getFieldB, BigDecimal::add);

List<Collector<InputRecord, ?, ?>> collectors = Arrays.asList(fieldACollector, fieldBCollector); // need a fieldCCollector object in the list

The collectors object would then be used to create a complexCollector object (as per the accepted answer by Tagir Valeev in the above link).

Body:
To me the cleanest way is to build a custom collector for that. There are multiple lines of code here, but you can hide it under a method, so your ultimate operation would look like this:

Collection<OutputRecord> output = List.of(first, second, thrid, fourth)
            .stream()
            .parallel()
            .collect(toOutputRecords());

While the actual toOutputRecords would be:

 private static Collector<InputRecord, ?, Collection<OutputRecord>> toOutputRecords() {
    class Acc {

        Map<String, OutputRecord> map = new HashMap<>();

        void add(InputRecord elem) {
            String value = elem.getName();
            // constructor without fieldC since you compute it at the end
            OutputRecord record = new OutputRecord(value, elem.getFieldA(), elem.getFieldB());
            mergeIntoMap(map, value, record);
        }

        Acc merge(Acc right) {
            Map<String, OutputRecord> leftMap = map;
            Map<String, OutputRecord> rightMap = right.map;

            for (Entry<String, OutputRecord> entry : rightMap.entrySet()) {
                mergeIntoMap(leftMap, entry.getKey(), entry.getValue());
            }
            return this;
        }

        private void mergeIntoMap(Map<String, OutputRecord> map, String value, OutputRecord record) {

            map.merge(value, record, (left, right) -> {
                left.setSumOfFieldA(left.getSumOfFieldA() + right.getSumOfFieldA());
                left.setSumOfFieldB(left.getSumOfFieldB().add(right.getSumOfFieldB()));

                return left;
            });
        }

        public Collection<OutputRecord> finisher() {
            for (Entry<String, OutputRecord> e : map.entrySet()) {
                OutputRecord output = e.getValue();
                output.setFieldC(output.getSumOfFieldB().multiply(BigDecimal.valueOf(output.getSumOfFieldA())));
            }
            return map.values();
        }

    }
    return Collector.of(Acc::new, Acc::add, Acc::merge, Acc::finisher);
}


来源: stackexchange

问:
How to make readonly structs XML serializable?
I have an immutable struct with only one field:

```<code>struct MyStruct
{
    private readonly double number;

    public MyStruct(double number)
        => this.number = number;
}
</code>```

And I want this to be able to get serialized/deserialized by:

Data contract serializer

Binary formatter

XML serializer (edit: forgotten in the original question)

Json.NET (without adding Json.NET as a dependency)

So the struct becomes this:

```<code>[Serializable]
struct MyStruct : ISerializable, IXmlSerializable
{
    private readonly double number;

    public MyStruct(double number)
        => this.number = number;

    private MyStruct(SerializationInfo info, StreamingContext context)
        => this.number = info.GetDouble(nameof(this.number));

    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
        => info.AddValue(nameof(this.number), this.number);

    XmlSchema IXmlSerializable.GetSchema() => null;

    void IXmlSerializable.ReadXml(XmlReader reader)
    {
        // Necessary evil
        reader.Read();
        this = new MyStruct(double.Parse(reader.Value, CultureInfo.InvariantCulture));
    }

    void IXmlSerializable.WriteXml(XmlWriter writer)
        => writer.WriteString(this.number.ToString(CultureInfo.InvariantCulture));
}
</code>```

Because:

[Serializable] is required by the binary formatter.

Json.NET honors both [DataContract] and ISerializable.

[DataContract] and ISerializable can't be used together.

Luckily, IXmlSerializer is supported by the data contract serializer.

C# 7.2 introduces the readonly modifier for structs and MyStruct, being an immutable struct seems like an ideal candidate for this.

The problem is that IXmlSerializable interface requires the ability to mutate MyStruct. That's what we did above, assigning to this in IXmlSerializable.ReadXml implementation.

```<code>readonly struct MyStruct : IXmlSerializable
{
    // ...
    void IXmlSerializable.ReadXml(XmlReader reader)
    {
        // No longer works since "this" is now readonly.
        reader.Read();
        this = new MyStruct(double.Parse(reader.Value, CultureInfo.InvariantCulture));
    }
    // ...
}
</code>```

I tried cheating via reflection but FieldInfo.SetValue boxes the value, and FieldInfo.SetValueDirect requires a TypedReference, which I can't obtain since __makeref is also forbidden when this is read-only.

So what are ways that would allow MyStruct to get serialized by the XML serializer?

I should also mention that I do not care what the output XML looks like, I don't really need the fine grained control provided by the IXmlSerializable interface. I only need to make MyClass consistently serializable using the serializers I listed.

答:
To satisfy your requirements all you need is:

```<code>[Serializable]
[DataContract]
public readonly struct MyStruct {
    [DataMember]
    private readonly double number;

    public MyStruct(double number)
        => this.number = number;
}
</code>```

Test code:

```<code>var target = new MyStruct(2);
// with Data Contract serializer
using (var ms = new MemoryStream()) {
    var s = new DataContractSerializer(typeof(MyStruct));
    s.WriteObject(ms, target);
    ms.Position = 0;
    var back = (MyStruct) s.ReadObject(ms);
    Debug.Assert(target.Equals(back));
}

// with Json.NET
var json = JsonConvert.SerializeObject(target);
var jsonBack = JsonConvert.DeserializeObject<MyStruct>(json);
Debug.Assert(target.Equals(jsonBack));

// with binary formatter
using (var ms = new MemoryStream()) {
    var formatter = new BinaryFormatter();
    formatter.Serialize(ms, target);
    ms.Position = 0;
    var back = (MyStruct) formatter.Deserialize(ms);
    Debug.Assert(target.Equals(back));
}
</code>```

Update. Since you also need to support XmlSerializer, you can use some unsafe code to achieve your requirements:

```<code>[Serializable]
public readonly struct MyStruct : ISerializable, IXmlSerializable
{
    private readonly double number;
    public MyStruct(double number)
        => this.number = number;

    private MyStruct(SerializationInfo info, StreamingContext context)
        => this.number = info.GetDouble(nameof(this.number));

    XmlSchema IXmlSerializable.GetSchema() {
        return null;
    }

    unsafe void IXmlSerializable.ReadXml(XmlReader reader) {
        if (reader.Read()) {
            var value = double.Parse(reader.Value, CultureInfo.InvariantCulture);
            fixed (MyStruct* t = &this) {
                *t = new MyStruct(value);
            }
        }
    }

    void IXmlSerializable.WriteXml(XmlWriter writer) {
        writer.WriteString(this.number.ToString(CultureInfo.InvariantCulture));
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context) {
        info.AddValue(nameof(number), this.number);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an immutable struct with only one field:

struct MyStruct
{
    private readonly double number;

    public MyStruct(double number)
        => this.number = number;
}

And I want this to be able to get serialized/deserialized by:

Data contract serializer

Binary formatter

XML serializer (edit: forgotten in the original question)

Json.NET (without adding Json.NET as a dependency)

So the struct becomes this:

[Serializable]
struct MyStruct : ISerializable, IXmlSerializable
{
    private readonly double number;

    public MyStruct(double number)
        => this.number = number;

    private MyStruct(SerializationInfo info, StreamingContext context)
        => this.number = info.GetDouble(nameof(this.number));

    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
        => info.AddValue(nameof(this.number), this.number);

    XmlSchema IXmlSerializable.GetSchema() => null;

    void IXmlSerializable.ReadXml(XmlReader reader)
    {
        // Necessary evil
        reader.Read();
        this = new MyStruct(double.Parse(reader.Value, CultureInfo.InvariantCulture));
    }

    void IXmlSerializable.WriteXml(XmlWriter writer)
        => writer.WriteString(this.number.ToString(CultureInfo.InvariantCulture));
}

Because:

[Serializable] is required by the binary formatter.

Json.NET honors both [DataContract] and ISerializable.

[DataContract] and ISerializable can't be used together.

Luckily, IXmlSerializer is supported by the data contract serializer.

C# 7.2 introduces the readonly modifier for structs and MyStruct, being an immutable struct seems like an ideal candidate for this.

The problem is that IXmlSerializable interface requires the ability to mutate MyStruct. That's what we did above, assigning to this in IXmlSerializable.ReadXml implementation.

readonly struct MyStruct : IXmlSerializable
{
    // ...
    void IXmlSerializable.ReadXml(XmlReader reader)
    {
        // No longer works since "this" is now readonly.
        reader.Read();
        this = new MyStruct(double.Parse(reader.Value, CultureInfo.InvariantCulture));
    }
    // ...
}

I tried cheating via reflection but FieldInfo.SetValue boxes the value, and FieldInfo.SetValueDirect requires a TypedReference, which I can't obtain since __makeref is also forbidden when this is read-only.

So what are ways that would allow MyStruct to get serialized by the XML serializer?

I should also mention that I do not care what the output XML looks like, I don't really need the fine grained control provided by the IXmlSerializable interface. I only need to make MyClass consistently serializable using the serializers I listed.

Body:
To satisfy your requirements all you need is:

[Serializable]
[DataContract]
public readonly struct MyStruct {
    [DataMember]
    private readonly double number;

    public MyStruct(double number)
        => this.number = number;
}

Test code:

var target = new MyStruct(2);
// with Data Contract serializer
using (var ms = new MemoryStream()) {
    var s = new DataContractSerializer(typeof(MyStruct));
    s.WriteObject(ms, target);
    ms.Position = 0;
    var back = (MyStruct) s.ReadObject(ms);
    Debug.Assert(target.Equals(back));
}

// with Json.NET
var json = JsonConvert.SerializeObject(target);
var jsonBack = JsonConvert.DeserializeObject<MyStruct>(json);
Debug.Assert(target.Equals(jsonBack));

// with binary formatter
using (var ms = new MemoryStream()) {
    var formatter = new BinaryFormatter();
    formatter.Serialize(ms, target);
    ms.Position = 0;
    var back = (MyStruct) formatter.Deserialize(ms);
    Debug.Assert(target.Equals(back));
}

Update. Since you also need to support XmlSerializer, you can use some unsafe code to achieve your requirements:

[Serializable]
public readonly struct MyStruct : ISerializable, IXmlSerializable
{
    private readonly double number;
    public MyStruct(double number)
        => this.number = number;

    private MyStruct(SerializationInfo info, StreamingContext context)
        => this.number = info.GetDouble(nameof(this.number));

    XmlSchema IXmlSerializable.GetSchema() {
        return null;
    }

    unsafe void IXmlSerializable.ReadXml(XmlReader reader) {
        if (reader.Read()) {
            var value = double.Parse(reader.Value, CultureInfo.InvariantCulture);
            fixed (MyStruct* t = &this) {
                *t = new MyStruct(value);
            }
        }
    }

    void IXmlSerializable.WriteXml(XmlWriter writer) {
        writer.WriteString(this.number.ToString(CultureInfo.InvariantCulture));
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context) {
        info.AddValue(nameof(number), this.number);
    }
}


问:
Postgres Streaming Replication Error: requested WAL segment has already been removed
I have setup streaming replication between a primary and secondary server. I have enabled archiving. In the Postgres log file I am seeing the below error.

```<code>< 2017-12-05 03:08:45.374 UTC > WARNING:  archive_mode enabled, yet archive_command is not set
< 2017-12-05 03:08:46.668 UTC > ERROR:  requested WAL segment 0000000100000000000000E3 has already been removed
< 2017-12-05 03:08:51.675 UTC > ERROR:  requested WAL segment 0000000100000000000000E3 has already been removed
< 2017-12-05 03:08:56.682 UTC > ERROR:  requested WAL segment 0000000100000000000000E3 has already been removed
</code>```

Do we need to enable archive_mode = on for streaming replication? How can I avoid above error?

```<code>max_wal_senders = 3
wal_keep_segements = 32
</code>```

答:
https://www.postgresql.org/docs/current/static/warm-standby.html

If you use streaming replication without file-based continuous
  archiving, the server might recycle old WAL segments before the
  standby has received them. If this occurs, the standby will need to be
  reinitialized from a new base backup. You can avoid this by setting
  wal_keep_segments to a value large enough to ensure that WAL segments
  are not recycled too early, or by configuring a replication slot for
  the standby. If you set up a WAL archive that's accessible from the
  standby, these solutions are not required, since the standby can
  always use the archive to catch up provided it retains enough
  segments.

emphasis mine.

so either increase wal_keep_segments to big enough (enough for your amount of block changes), or configure archive_command and set up some storage to keep removed wals from master to be available for slave. Or configuring a replication slot for the standby...

ContentLicense: CC BY-SA 4.0

Body:
I have setup streaming replication between a primary and secondary server. I have enabled archiving. In the Postgres log file I am seeing the below error.

< 2017-12-05 03:08:45.374 UTC > WARNING:  archive_mode enabled, yet archive_command is not set
< 2017-12-05 03:08:46.668 UTC > ERROR:  requested WAL segment 0000000100000000000000E3 has already been removed
< 2017-12-05 03:08:51.675 UTC > ERROR:  requested WAL segment 0000000100000000000000E3 has already been removed
< 2017-12-05 03:08:56.682 UTC > ERROR:  requested WAL segment 0000000100000000000000E3 has already been removed

Do we need to enable archive_mode = on for streaming replication? How can I avoid above error?

max_wal_senders = 3
wal_keep_segements = 32


问:
CMAKE_PREFIX_PATH doesn't help CMake in finding Qt5
From here: https://stackoverflow.com/a/28327499/462608

I tried this:

```<code>cmake_minimum_required(VERSION 2.8.12)

project(qtquick_hello_cmake)

set(CMAKE_PREFIX_PATH "/opt/Qt5.9.1/5.9.1/")

set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)

find_package(Qt5 COMPONENTS Quick Core REQUIRED)

qt5_add_resources(RESOURCES qml.qrc)

add_executable(${PROJECT_NAME} "main.cpp" "qml.qrc")

qt5_use_modules(${PROJECT_NAME} Quick Core)

target_link_libraries(${PROJECT_NAME} Qt5::Core Qt5::Quick)
</code>```

Here is the output of cmake .

```<code>:~/junk/qtquick_hello_cmake$ cmake .
CMake Error at CMakeLists.txt:11 (find_package):
  By not providing "FindQt5.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "Qt5", but
  CMake did not find one.

  Could not find a package configuration file provided by "Qt5" with any of
  the following names:

    Qt5Config.cmake
    qt5-config.cmake

  Add the installation prefix of "Qt5" to CMAKE_PREFIX_PATH or set "Qt5_DIR"
  to a directory containing one of the above files.  If "Qt5" provides a
  separate development package or SDK, be sure it has been installed.

-- Configuring incomplete, errors occurred!
See also "/home/.../junk/qtquick_hello_cmake/CMakeFiles/CMakeOutput.log".
</code>```

This is to show that /opt/Qt5.9.1/ does exist.

```<code>:~/junk/qtquick_hello_cmake$ cd /opt/Qt5.9.1/5.9.1/
:/opt/Qt5.9.1/5.9.1$ ls
android_armv7  android_x86  gcc_64  Src
</code>```

Here I run the cmake with -DCMAKE option, but the output is still same:

```<code>:~/junk/qtquick_hello_cmake$ cmake -DCMAKE_PREFIX_PATH=/opt/Qt5.9.1/5.9.1/ -DWITH_QT5=1 .
CMake Error at CMakeLists.txt:11 (find_package):
  By not providing "FindQt5.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "Qt5", but
  CMake did not find one.

  Could not find a package configuration file provided by "Qt5" with any of
  the following names:

    Qt5Config.cmake
    qt5-config.cmake

  Add the installation prefix of "Qt5" to CMAKE_PREFIX_PATH or set "Qt5_DIR"
  to a directory containing one of the above files.  If "Qt5" provides a
  separate development package or SDK, be sure it has been installed.

-- Configuring incomplete, errors occurred!
See also "/home/.../junk/qtquick_hello_cmake/CMakeFiles/CMakeOutput.log".
</code>```

Contents of the directory:

```<code>:~/junk/qtquick_hello_cmake$ ls
CMakeCache.txt  CMakeFiles  CMakeLists.txt  main.cpp  main.qml  qml.qrc
</code>```

答:
CMake error message about failed find_package and setting CMAKE_PREFIX_PATH variable

Add the installation prefix of "Qt5" to CMAKE_PREFIX_PATH

is somehow misleading. It talks only about "installation prefix", but this installation still require to contain Qt5Config.cmake or qt5-config.cmake files inside for being discoverable by find_package.

But the message

If "Qt5" provides a
    separate development package or SDK, be sure it has been installed.

is clear:

One need to install a development package which contains required config files.

Everything above is applicable only to CONFIG mode of find_package, when "Find" script is provided neither by CMake nor by CMake project which uses this command.

Body:
From here: https://stackoverflow.com/a/28327499/462608

I tried this:

cmake_minimum_required(VERSION 2.8.12)

project(qtquick_hello_cmake)

set(CMAKE_PREFIX_PATH "/opt/Qt5.9.1/5.9.1/")

set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)

find_package(Qt5 COMPONENTS Quick Core REQUIRED)

qt5_add_resources(RESOURCES qml.qrc)

add_executable(${PROJECT_NAME} "main.cpp" "qml.qrc")

qt5_use_modules(${PROJECT_NAME} Quick Core)

target_link_libraries(${PROJECT_NAME} Qt5::Core Qt5::Quick)

Here is the output of cmake .

:~/junk/qtquick_hello_cmake$ cmake .
CMake Error at CMakeLists.txt:11 (find_package):
  By not providing "FindQt5.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "Qt5", but
  CMake did not find one.

  Could not find a package configuration file provided by "Qt5" with any of
  the following names:

    Qt5Config.cmake
    qt5-config.cmake

  Add the installation prefix of "Qt5" to CMAKE_PREFIX_PATH or set "Qt5_DIR"
  to a directory containing one of the above files.  If "Qt5" provides a
  separate development package or SDK, be sure it has been installed.

-- Configuring incomplete, errors occurred!
See also "/home/.../junk/qtquick_hello_cmake/CMakeFiles/CMakeOutput.log".

This is to show that /opt/Qt5.9.1/ does exist.

:~/junk/qtquick_hello_cmake$ cd /opt/Qt5.9.1/5.9.1/
:/opt/Qt5.9.1/5.9.1$ ls
android_armv7  android_x86  gcc_64  Src

Here I run the cmake with -DCMAKE option, but the output is still same:

:~/junk/qtquick_hello_cmake$ cmake -DCMAKE_PREFIX_PATH=/opt/Qt5.9.1/5.9.1/ -DWITH_QT5=1 .
CMake Error at CMakeLists.txt:11 (find_package):
  By not providing "FindQt5.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "Qt5", but
  CMake did not find one.

  Could not find a package configuration file provided by "Qt5" with any of
  the following names:

    Qt5Config.cmake
    qt5-config.cmake

  Add the installation prefix of "Qt5" to CMAKE_PREFIX_PATH or set "Qt5_DIR"
  to a directory containing one of the above files.  If "Qt5" provides a
  separate development package or SDK, be sure it has been installed.

-- Configuring incomplete, errors occurred!
See also "/home/.../junk/qtquick_hello_cmake/CMakeFiles/CMakeOutput.log".

Contents of the directory:

:~/junk/qtquick_hello_cmake$ ls
CMakeCache.txt  CMakeFiles  CMakeLists.txt  main.cpp  main.qml  qml.qrc


问:
How to compare time ranges?
Hi i am trying to compare time ranges,My requirement is when i select time from time-picker dialog it should be under given time ranges for this i wrote below code this is working when i not select 12 or 00 from time picker dialog

start time:06:00
end time:23:00
selected time from time picker dialog:12:23

above timing not suitable for below code can some one help me please

```<code>     String pattern = "hh:mm";
     SimpleDateFormat sdf = new SimpleDateFormat(pattern);
     Date date1 = sdf.parse(startTime);
     Date date2 = sdf.parse(endTime);
     Date date3 = sdf.parse(selectedTime);
     if (((date3.after(date1) || date3.equals(date1)) && (date3.before(date2) || date3.equals(date2)))) {

     }
     else {
           Toast.makeText(context, "Pickup time should be open and close timings", Toast.LENGTH_SHORT).show();
      }
</code>```

答:
You can use code below .

```<code> String pattern = "HH:mm";
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
    try {
        Date date1 = sdf.parse(startTime);
        Date date2 = sdf.parse(endTime);
        Date date3 = sdf.parse(selectedTime);
        if (date3.compareTo(date1) >= 0 && date3.compareTo(date2) <= 0) {
            // Do your stuff
        } else {
            // Wrong time
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
</code>```

h represents Hour in am/pm (1-12)

H represents Hour in day (0-23)

Your date is in 24 hour formate so you should use H instead of h.

Title: How to compare time ranges?

Body:
Hi i am trying to compare time ranges,My requirement is when i select time from time-picker dialog it should be under given time ranges for this i wrote below code this is working when i not select 12 or 00 from time picker dialog

start time:06:00
end time:23:00
selected time from time picker dialog:12:23

above timing not suitable for below code can some one help me please

     String pattern = "hh:mm";
     SimpleDateFormat sdf = new SimpleDateFormat(pattern);
     Date date1 = sdf.parse(startTime);
     Date date2 = sdf.parse(endTime);
     Date date3 = sdf.parse(selectedTime);
     if (((date3.after(date1) || date3.equals(date1)) && (date3.before(date2) || date3.equals(date2)))) {

     }
     else {
           Toast.makeText(context, "Pickup time should be open and close timings", Toast.LENGTH_SHORT).show();
      }

Body:
You can use code below .

 String pattern = "HH:mm";
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
    try {
        Date date1 = sdf.parse(startTime);
        Date date2 = sdf.parse(endTime);
        Date date3 = sdf.parse(selectedTime);
        if (date3.compareTo(date1) >= 0 && date3.compareTo(date2) <= 0) {
            // Do your stuff
        } else {
            // Wrong time
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

h represents Hour in am/pm (1-12)

H represents Hour in day (0-23)

Your date is in 24 hour formate so you should use H instead of h.


问:
How to read from application.properties
I'm trying to read from application.properties and I can't get it working.

this is my code:

```<code>package config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@Configuration
@PropertySource("classpath:application.properties")
public class PropertiesReader {

        @Autowired
        private Environment env;

        public String readProperty(String key) {
            return env.getProperty(key);
        }

}
</code>```

this is where I invoke the readProperty:

```<code>public class JwtSettings {

    public String key;

    public long expiration;

    //The JWT signature algorithm we will be using to sign the token
    public SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

    public JwtSettings() {
        PropertiesReader propertiesReader = new PropertiesReader();
        key = propertiesReader.readProperty(ApplicationProperties.JWT_KEY.key);
    }
</code>```

When I run this code, the env instance is null.
My application.properties file is located in the resource folder.
I'm out of ideas, please help.

答:
Try to use your configuration like this:

```<code>@Service
public class JwtSettings {

   private String key;

   private long expiration;

   //The JWT signature algorithm we will be using to sign the token
   public SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

   @Autowired
   public JwtSettings(PropertiesReader propertiesReader) {
      this.key = propertiesReader.readProperty(ApplicationProperties.JWT_KEY.key);
   }
}
</code>```

You should never instantiate Spring managed components yourself (by invoking the constructor in your code). Instead you should use Spring Dependency-Injection via @Autowired to make sure that all your dependencies are resolved correctly.

To inject properties with Spring (generally):

If you try to get access to a property value from a property resource, try to inject it with Springs @Value annotation.

Your application.properties may look like:

```<code>myproperty.test1=mytestvalue
myproperty.test2=123
</code>```

Now you have a Spring component, where you want to use the property values and you inject them like:

```<code>@Component
private class MyTestComponent {

   @Value("${myproperty.test1:mydefaultvalue}")
   private String test1Value;

   @Value("${myproperty.test2:-1}")
   private int test2Value;

}
</code>```

Of course you can use other datatypes than String for your property.

Title: How to read from application.properties

Body:
I'm trying to read from application.properties and I can't get it working.

this is my code:

package config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@Configuration
@PropertySource("classpath:application.properties")
public class PropertiesReader {

        @Autowired
        private Environment env;

        public String readProperty(String key) {
            return env.getProperty(key);
        }

}

this is where I invoke the readProperty:

public class JwtSettings {

    public String key;

    public long expiration;

    //The JWT signature algorithm we will be using to sign the token
    public SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

    public JwtSettings() {
        PropertiesReader propertiesReader = new PropertiesReader();
        key = propertiesReader.readProperty(ApplicationProperties.JWT_KEY.key);
    }

When I run this code, the env instance is null.
My application.properties file is located in the resource folder.
I'm out of ideas, please help.

Body:
Try to use your configuration like this:

@Service
public class JwtSettings {

   private String key;

   private long expiration;

   //The JWT signature algorithm we will be using to sign the token
   public SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

   @Autowired
   public JwtSettings(PropertiesReader propertiesReader) {
      this.key = propertiesReader.readProperty(ApplicationProperties.JWT_KEY.key);
   }
}

You should never instantiate Spring managed components yourself (by invoking the constructor in your code). Instead you should use Spring Dependency-Injection via @Autowired to make sure that all your dependencies are resolved correctly.

To inject properties with Spring (generally):

If you try to get access to a property value from a property resource, try to inject it with Springs @Value annotation.

Your application.properties may look like:

myproperty.test1=mytestvalue
myproperty.test2=123

Now you have a Spring component, where you want to use the property values and you inject them like:

@Component
private class MyTestComponent {

   @Value("${myproperty.test1:mydefaultvalue}")
   private String test1Value;

   @Value("${myproperty.test2:-1}")
   private int test2Value;

}

Of course you can use other datatypes than String for your property.


问:
errors when making spree to work?
First of all i am following the steps from the official documentation

https://github.com/spree/spree

I have Rails 5.1 installed so i copied the following gems and ran bundle install

```<code>gem 'spree', '~> 3.4.0'
gem 'spree_auth_devise', '~> 3.3'
gem 'spree_gateway', '~> 3.3'
</code>```

Also i ran

```<code>bundle update i18n
</code>```

When i run the first generator

```<code>rails g spree:install --user_class=Spree::User
</code>```

i get the following error

```<code>rails g spree:install --user_class=Spree::User
/usr/local/rvm/gems/ruby-2.3.4/gems/activerecord-5.1.4/lib/active_record/dynamic_matchers.rb:22:in `method_missing': undefined method `raise_in_transactional_callbacks=' for ActiveRecord::Base:Class (NoMethodError)
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activerecord-5.1.4/lib/active_record/railtie.rb:112:in `block (3 levels) in <class:Railtie>'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activerecord-5.1.4/lib/active_record/railtie.rb:111:in `each'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activerecord-5.1.4/lib/active_record/railtie.rb:111:in `block (2 levels) in <class:Railtie>'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activesupport-5.1.4/lib/active_support/lazy_load_hooks.rb:69:in `instance_eval'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activesupport-5.1.4/lib/active_support/lazy_load_hooks.rb:69:in `block in execute_hook'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activesupport-5.1.4/lib/active_support/lazy_load_hooks.rb:60:in `with_execution_control'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activesupport-5.1.4/lib/active_support/lazy_load_hooks.rb:65:in `execute_hook'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activesupport-5.1.4/lib/active_support/lazy_load_hooks.rb:41:in `block in on_load'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activesupport-5.1.4/lib/active_support/lazy_load_hooks.rb:40:in `each'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activesupport-5.1.4/lib/active_support/lazy_load_hooks.rb:40:in `on_load'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activerecord-5.1.4/lib/active_record/railtie.rb:110:in `block in <class:Railtie>'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/railties-5.1.4/lib/rails/initializable.rb:30:in `instance_exec'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/railties-5.1.4/lib/rails/initializable.rb:30:in `run'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/railties-5.1.4/lib/rails/initializable.rb:59:in `block in run_initializers'
        from /usr/local/rvm/rubies/ruby-2.3.4/lib/ruby/2.3.0/tsort.rb:228:in `block in tsort_each'
        from /usr/local/rvm/rubies/ruby-2.3.4/lib/ruby/2.3.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
        from /usr/local/rvm/rubies/ruby-2.3.4/lib/ruby/2.3.0/tsort.rb:431:in `each_strongly_connected_component_from'
        from /usr/local/rvm/rubies/ruby-2.3.4/lib/ruby/2.3.0/tsort.rb:349:in `block in each_strongly_connected_component'
        from /usr/local/rvm/rubies/ruby-2.3.4/lib/ruby/2.3.0/tsort.rb:347:in `each'
        from /usr/local/rvm/rubies/ruby-2.3.4/lib/ruby/2.3.0/tsort.rb:347:in `call'
        from /usr/local/rvm/rubies/ruby-2.3.4/lib/ruby/2.3.0/tsort.rb:347:in `each_strongly_connected_component'
        from /usr/local/rvm/rubies/ruby-2.3.4/lib/ruby/2.3.0/tsort.rb:226:in `tsort_each'
        from /usr/local/rvm/rubies/ruby-2.3.4/lib/ruby/2.3.0/tsort.rb:205:in `tsort_each'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/railties-5.1.4/lib/rails/initializable.rb:58:in `run_initializers'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/railties-5.1.4/lib/rails/application.rb:353:in `initialize!'
        from /home/ubuntu/workspace/config/environment.rb:5:in `<top (required)>'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/polyglot-0.3.5/lib/polyglot.rb:65:in `require'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/polyglot-0.3.5/lib/polyglot.rb:65:in `require'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:292:in `block in require'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:258:in `load_dependency'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:292:in `require'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/spring-2.0.2/lib/spring/application.rb:102:in `preload'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/spring-2.0.2/lib/spring/application.rb:153:in `serve'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/spring-2.0.2/lib/spring/application.rb:141:in `block in run'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/spring-2.0.2/lib/spring/application.rb:135:in `loop'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/spring-2.0.2/lib/spring/application.rb:135:in `run'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/spring-2.0.2/lib/spring/application/boot.rb:19:in `<top (required)>'
        from /usr/local/rvm/rubies/ruby-2.3.4/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
        from /usr/local/rvm/rubies/ruby-2.3.4/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
        from -e:1:in `<main>'
</code>```

答:
given this post, I would try to do bundle update or follow the instruction in that post

Can't create a new Spree app: "undefined method `raise_in_transactional_callbacks='"

Title: errors when making spree to work?

Body:
First of all i am following the steps from the official documentation

https://github.com/spree/spree

I have Rails 5.1 installed so i copied the following gems and ran bundle install

gem 'spree', '~> 3.4.0'
gem 'spree_auth_devise', '~> 3.3'
gem 'spree_gateway', '~> 3.3'

Also i ran

bundle update i18n

When i run the first generator

rails g spree:install --user_class=Spree::User

i get the following error

rails g spree:install --user_class=Spree::User
/usr/local/rvm/gems/ruby-2.3.4/gems/activerecord-5.1.4/lib/active_record/dynamic_matchers.rb:22:in `method_missing': undefined method `raise_in_transactional_callbacks=' for ActiveRecord::Base:Class (NoMethodError)
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activerecord-5.1.4/lib/active_record/railtie.rb:112:in `block (3 levels) in <class:Railtie>'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activerecord-5.1.4/lib/active_record/railtie.rb:111:in `each'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activerecord-5.1.4/lib/active_record/railtie.rb:111:in `block (2 levels) in <class:Railtie>'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activesupport-5.1.4/lib/active_support/lazy_load_hooks.rb:69:in `instance_eval'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activesupport-5.1.4/lib/active_support/lazy_load_hooks.rb:69:in `block in execute_hook'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activesupport-5.1.4/lib/active_support/lazy_load_hooks.rb:60:in `with_execution_control'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activesupport-5.1.4/lib/active_support/lazy_load_hooks.rb:65:in `execute_hook'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activesupport-5.1.4/lib/active_support/lazy_load_hooks.rb:41:in `block in on_load'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activesupport-5.1.4/lib/active_support/lazy_load_hooks.rb:40:in `each'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activesupport-5.1.4/lib/active_support/lazy_load_hooks.rb:40:in `on_load'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activerecord-5.1.4/lib/active_record/railtie.rb:110:in `block in <class:Railtie>'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/railties-5.1.4/lib/rails/initializable.rb:30:in `instance_exec'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/railties-5.1.4/lib/rails/initializable.rb:30:in `run'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/railties-5.1.4/lib/rails/initializable.rb:59:in `block in run_initializers'
        from /usr/local/rvm/rubies/ruby-2.3.4/lib/ruby/2.3.0/tsort.rb:228:in `block in tsort_each'
        from /usr/local/rvm/rubies/ruby-2.3.4/lib/ruby/2.3.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
        from /usr/local/rvm/rubies/ruby-2.3.4/lib/ruby/2.3.0/tsort.rb:431:in `each_strongly_connected_component_from'
        from /usr/local/rvm/rubies/ruby-2.3.4/lib/ruby/2.3.0/tsort.rb:349:in `block in each_strongly_connected_component'
        from /usr/local/rvm/rubies/ruby-2.3.4/lib/ruby/2.3.0/tsort.rb:347:in `each'
        from /usr/local/rvm/rubies/ruby-2.3.4/lib/ruby/2.3.0/tsort.rb:347:in `call'
        from /usr/local/rvm/rubies/ruby-2.3.4/lib/ruby/2.3.0/tsort.rb:347:in `each_strongly_connected_component'
        from /usr/local/rvm/rubies/ruby-2.3.4/lib/ruby/2.3.0/tsort.rb:226:in `tsort_each'
        from /usr/local/rvm/rubies/ruby-2.3.4/lib/ruby/2.3.0/tsort.rb:205:in `tsort_each'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/railties-5.1.4/lib/rails/initializable.rb:58:in `run_initializers'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/railties-5.1.4/lib/rails/application.rb:353:in `initialize!'
        from /home/ubuntu/workspace/config/environment.rb:5:in `<top (required)>'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/polyglot-0.3.5/lib/polyglot.rb:65:in `require'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/polyglot-0.3.5/lib/polyglot.rb:65:in `require'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:292:in `block in require'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:258:in `load_dependency'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:292:in `require'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/spring-2.0.2/lib/spring/application.rb:102:in `preload'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/spring-2.0.2/lib/spring/application.rb:153:in `serve'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/spring-2.0.2/lib/spring/application.rb:141:in `block in run'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/spring-2.0.2/lib/spring/application.rb:135:in `loop'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/spring-2.0.2/lib/spring/application.rb:135:in `run'
        from /usr/local/rvm/gems/ruby-2.3.4/gems/spring-2.0.2/lib/spring/application/boot.rb:19:in `<top (required)>'
        from /usr/local/rvm/rubies/ruby-2.3.4/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
        from /usr/local/rvm/rubies/ruby-2.3.4/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
        from -e:1:in `'


问:
Why in my WebClient DownloadFileAsync method downloading an Empty File?
I have this C# code but the final esi.zip results in 0 length or basically empty. The URL does exist and confirms to download the file manually. I am baffled buy this.

```<code>string zipPath = @"C:\download\esi.zip";

Client.DownloadFileAsync(new Uri("http://ec.europa.eu/economy_finance/db_indicators
 /surveys/documents/series/nace2_ecfin_1409/all_surveys_total_sa_nace2.zip"), zipPath)
</code>```

Thanks

UPDATED: I updated the code where no spaces exist at all but it still downloads 0 bytes.

答:
```<code> objFeedBO = new FeedBO();
 string strfilename = System.IO.Path.GetFileName(url);
 FileStream outputStream = new FileStream(DownloadPath + "\\" + strfilename, FileMode.Create);

 string targetdownloadedFile = @"D:\TestZip.php";

 WebClient myWebClient = new WebClient();
 myWebClient.DownloadFileAsync(new Uri(url), targetdownloadedFile);
 while (myWebClient.IsBusy) { }
</code>```

Body:
I have this C# code but the final esi.zip results in 0 length or basically empty. The URL does exist and confirms to download the file manually. I am baffled buy this.

string zipPath = @"C:\download\esi.zip";

Client.DownloadFileAsync(new Uri("http://ec.europa.eu/economy_finance/db_indicators
 /surveys/documents/series/nace2_ecfin_1409/all_surveys_total_sa_nace2.zip"), zipPath)

Thanks

UPDATED: I updated the code where no spaces exist at all but it still downloads 0 bytes.


问:
foreach not recognized in C++
In my the cs106b book we use the expression "foreach" to go through a list of words in a Map. I implemented the code and banged my head against the wall facing mysterious errors. Here's the code:

```<code>   void DisplayWordCounts(Map<int> & wordsCount) {
     foreach (string word in wordsCount) {
        cout << left << setw(15) << word << right << setw(5)
        << wordsCount[word] << endl;
     }
}
</code>```

on the line starting with "foreach" I get the following errors:
lesson4-macbeth/life.cpp:58: error: expected primary-expression before 'word'
lesson4-macbeth/life.cpp:58: error: 'foreach' was not declared in this scope
lesson4-macbeth/life.cpp:58: error: expected `;' before '{' token

I guess foreach is not recognized. In that case, how can I go through a list of items from the Map class?

答:
foreach is not a standard C++ feature. This was something Eric Roberts and I developed for the Stanford introductory programming sequence and predates the more modern C++11 range-based for loop. Now that C++11 compiler support is more widespread, we've stopped using foreach and just opted to go with the standard C++ enhanced for loop.

I would generally not advice using foreach going forward as it's nonstandard. However, if you're compiling older code that uses it, you'll need to include one of the header files from the Stanford C++ Libraries that defines it.

ContentLicense: CC BY-SA 2.5

Title: foreach not recognized in C++

Body:
In my the cs106b book we use the expression "foreach" to go through a list of words in a Map. I implemented the code and banged my head against the wall facing mysterious errors. Here's the code:

   void DisplayWordCounts(Map<int> & wordsCount) {
     foreach (string word in wordsCount) {
        cout << left << setw(15) << word << right << setw(5)
        << wordsCount[word] << endl;
     }
}

on the line starting with "foreach" I get the following errors:
lesson4-macbeth/life.cpp:58: error: expected primary-expression before 'word'
lesson4-macbeth/life.cpp:58: error: 'foreach' was not declared in this scope
lesson4-macbeth/life.cpp:58: error: expected `;' before '{' token

I guess foreach is not recognized. In that case, how can I go through a list of items from the Map class?


问:
Flex menu on more rows without lonely last element?
Easy row menu with flex. In some viewport width (~600px) is menu splited with one lonely element on own second row. How to split that menu better?

Screenshot:

"Better" means for example 4 elements on first row and 3 elements on second row. Or 5 element on first row and 2 elements on second row. Just not this 6:1.

Here is my code

* {
  box-sizing: border-box;
}

html {
  font: Georgia, serif;
  color: #333;
  background: #a0522d;
  line-height: 1.5;
}

ul {
  display: flex;
  flex-wrap: wrap;
  max-width: 75em;
  margin: 0 auto;
  font-family: helvetica;
  padding: 0
}

ul li {
  list-style: none;
  flex-grow: 1;
  /*max-width:16rem*/
}

ul li a {
  line-height: 1.5;
  padding: 0.2em 0.2em;
  display: block;
  text-align: center;
  border-radius: 0.313em;
  background: PaleGoldenrod;
  margin: 0.063em;
  text-decoration: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="content">
  <li>Site name</li>
  <li>Next link</li>
  <li>Another link</li>
  <li>Something else</li>
  <li>Contact</li>
  <li>Almost last link</li>
  <li>Last link</li>
</ul></code>```

答:
You may use media query and change the flex propery of the elements like this :

* {
  box-sizing: border-box;
}

html {
  font: Georgia, serif;
  color: #333;
  background: #a0522d;
  line-height: 1.5;
}

ul {
  display: flex;
  flex-wrap: wrap;
  max-width: 75em;
  margin: 0 auto;
  font-family: helvetica;
  padding: 0
}

ul li {
  list-style: none;
  flex-grow: 1;
}

ul li a {
  line-height: 1.5;
  padding: 0.2em 0.2em;
  display: block;
  text-align: center;
  border-radius: 0.313em;
  background: PaleGoldenrod;
  margin: 0.063em;
  text-decoration: none;
}

@media all and (max-width:620px) {
  ul li {
    flex: 0 0 25%;
  }
  ul li:nth-child(n+5) {
    flex: 0 0 33%;
  }
}
@media all and (max-width:500px) {
  ul li:nth-child(n) {
    flex: 0 0 50%;
  }
  ul li:last-child{
    flex: 0 0 100%;
  }
}
@media all and (max-width:320px) {
  ul li:nth-child(n) {
    flex: 0 0 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="content">
  <li>Site name</li>
  <li>Next link</li>
  <li>Another link</li>
  <li>Something else</li>
  <li>Contact</li>
  <li>Almost last link</li>
  <li>Last link</li>
</ul></code>```

Another solution if you can change your HTML structure is to divide the menu into two ul like this :

* {
  box-sizing: border-box;
}

html {
  font: Georgia, serif;
  color: #333;
  background: #a0522d;
  line-height: 1.5;
}

.menu {
  display: flex;
  flex-wrap:wrap;
}

.menu .content {
  flex-grow: 1;
}

ul {
  display: flex;
  flex-wrap: wrap;
  max-width: 75em;
  margin: 0 auto;
  font-family: helvetica;
  padding: 0
}

ul li {
  list-style: none;
  flex-grow: 1;
  min-width:120px;
}

ul li a {
  line-height: 1.5;
  padding: 0.2em 0.2em;
  display: block;
  text-align: center;
  border-radius: 0.313em;
  background: PaleGoldenrod;
  margin: 0.063em;
  text-decoration: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu">
  <ul class="content">
    <li>Site name</li>
    <li>Next link</li>
    <li>Another link</li>
    <li>Something else</li>
  </ul>
  <ul class="content">
    <li>Contact</li>
    <li>Almost last link</li>
    <li>Last link</li>
  </ul>
</div></code>```

Body:
Easy row menu with flex. In some viewport width (~600px) is menu splited with one lonely element on own second row. How to split that menu better?

Screenshot:

"Better" means for example 4 elements on first row and 3 elements on second row. Or 5 element on first row and 2 elements on second row. Just not this 6:1.

Here is my code

* {
  box-sizing: border-box;
}

html {
  font: Georgia, serif;
  color: #333;
  background: #a0522d;
  line-height: 1.5;
}

ul {
  display: flex;
  flex-wrap: wrap;
  max-width: 75em;
  margin: 0 auto;
  font-family: helvetica;
  padding: 0
}

ul li {
  list-style: none;
  flex-grow: 1;
  /*max-width:16rem*/
}

ul li a {
  line-height: 1.5;
  padding: 0.2em 0.2em;
  display: block;
  text-align: center;
  border-radius: 0.313em;
  background: PaleGoldenrod;
  margin: 0.063em;
  text-decoration: none;
}

Site name

Next link

Another link

Something else

Contact

Almost last link

Last link

Body:
You may use media query and change the flex propery of the elements like this :

* {
  box-sizing: border-box;
}

html {
  font: Georgia, serif;
  color: #333;
  background: #a0522d;
  line-height: 1.5;
}

ul {
  display: flex;
  flex-wrap: wrap;
  max-width: 75em;
  margin: 0 auto;
  font-family: helvetica;
  padding: 0
}

ul li {
  list-style: none;
  flex-grow: 1;
}

ul li a {
  line-height: 1.5;
  padding: 0.2em 0.2em;
  display: block;
  text-align: center;
  border-radius: 0.313em;
  background: PaleGoldenrod;
  margin: 0.063em;
  text-decoration: none;
}

@media all and (max-width:620px) {
  ul li {
    flex: 0 0 25%;
  }
  ul li:nth-child(n+5) {
    flex: 0 0 33%;
  }
}
@media all and (max-width:500px) {
  ul li:nth-child(n) {
    flex: 0 0 50%;
  }
  ul li:last-child{
    flex: 0 0 100%;
  }
}
@media all and (max-width:320px) {
  ul li:nth-child(n) {
    flex: 0 0 100%;
  }
}

<ul class="content">
  <li><a href="#">Site name</a></li>
  <li><a href="#">Next link</a></li>
  <li><a href="#">Another link</a></li>
  <li><a href="#">Something else</a></li>
  <li><a href="#">Contact</a></li>
  <li><a href="#">Almost last link</a></li>
  <li><a href="#">Last link</a></li>
</ul>

Another solution if you can change your HTML structure is to divide the menu into two ul like this :

* {
  box-sizing: border-box;
}

html {
  font: Georgia, serif;
  color: #333;
  background: #a0522d;
  line-height: 1.5;
}

.menu {
  display: flex;
  flex-wrap:wrap;
}

.menu .content {
  flex-grow: 1;
}

ul {
  display: flex;
  flex-wrap: wrap;
  max-width: 75em;
  margin: 0 auto;
  font-family: helvetica;
  padding: 0
}

ul li {
  list-style: none;
  flex-grow: 1;
  min-width:120px;
}

ul li a {
  line-height: 1.5;
  padding: 0.2em 0.2em;
  display: block;
  text-align: center;
  border-radius: 0.313em;
  background: PaleGoldenrod;
  margin: 0.063em;
  text-decoration: none;
}

<div class="menu">
  <ul class="content">
    <li><a href="#">Site name</a></li>
    <li><a href="#">Next link</a></li>
    <li><a href="#">Another link</a></li>
    <li><a href="#">Something else</a></li>
  </ul>
  <ul class="content">
    <li><a href="#">Contact</a></li>
    <li><a href="#">Almost last link</a></li>
    <li><a href="#">Last link</a></li>
  </ul>
</div>


问:
data conversion in python
I have crawled data online. these data are saved in a mongodb. the day is always before month and year. I just need the month and year.I want to remove the number in front of the month, the data frame are not the same,like:

20-21 May 2008,
19 March 2008,
16-17 September 2010,
5 September 2011,

these data are saved as strings in python, is there any function to remove the numbers of day in python? these are about 3000 data,so I think I need a cycle to deal the problem.

答:
you can use

```<code>pd.Series(['20-21 May 2008', '19 March 2008', '16-17 September 2010', '5 September 2011']).str.extract('(\w{3,}\s\d{4})', expand=False)
</code>```

This will extract the required string and would create a new Series object.

Title: data conversion in python

Body:
you can use

pd.Series(['20-21 May 2008', '19 March 2008', '16-17 September 2010', '5 September 2011']).str.extract('(\w{3,}\s\d{4})', expand=False)

This will extract the required string and would create a new Series object.


问:
Mysql forcibly order by exact value
Need help with mysql request.

I make a request and I want to order result by the field ID.

ID for exemple: 1,2,3,4,5,6,7,8,9

But I need that it would be ordered like this: 6,3,1,2,4,5,7,8,9

Is there any solution in mysql  to forcibly put ID=6 in 1st place, ID=3 in 2nd...?

or I want the impossible)

答:
Use:

```<code>ORDER BY FIELD(id, 6,3,1,2,4,5,7,8,9)
</code>```

The FIELD function returns the position of the first value in the remaining list.

Title: Mysql forcibly order by exact value

Body:
Use:

ORDER BY FIELD(id, 6,3,1,2,4,5,7,8,9)

The FIELD function returns the position of the first value in the remaining list.


问:
Accessing Properties of the code-behind from aspx page in web application project
I have a property x in my code-behind file in a web application project. It gives me compile time error while it does not give any error in website project

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="test.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
<div>
<%= x2 %>
<%# x2 %>
</div>
</form>
</body>
</html>
</code>```

Codebehind file :

```<code>using System;
namespace test
{public partial class WebForm1 : System.Web.UI.Page
{
    public int x2 = 2;
    protected void Page_Load(object sender, EventArgs e)
    {
    }
   }
}
</code>```

It is working fine when I use the same technique in my website project
Kindly help
Thanks

答:
Your original post has changed so here's a new answer.

Try removing the namespace from the code behind and change 'inherits' on the page to Inherits="WebForm1".

page directive:

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
    Inherits="WebForm1" %>
</code>```

code behind:

```<code>using System;

public partial class WebForm1 : System.Web.UI.Page
{
    public int x2 = 2;
    protected void Page_Load(object sender, EventArgs e)
    {
    }
}
</code>```

'Inherits' must match the partial class name.

Body:
I have a property x in my code-behind file in a web application project. It gives me compile time error while it does not give any error in website project

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="test.WebForm1" %>
<!DOCTYPE html>

    <title></title>

    <form id="form1" runat="server">

<%= x2 %>
<%# x2 %>

</form>

Codebehind file :

using System;
namespace test
{public partial class WebForm1 : System.Web.UI.Page
{
    public int x2 = 2;
    protected void Page_Load(object sender, EventArgs e)
    {
    }
   }
}

It is working fine when I use the same technique in my website project
Kindly help
Thanks

Body:
Your original post has changed so here's a new answer.

Try removing the namespace from the code behind and change 'inherits' on the page to Inherits="WebForm1".

page directive:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
    Inherits="WebForm1" %>

code behind:

using System;

public partial class WebForm1 : System.Web.UI.Page
{
    public int x2 = 2;
    protected void Page_Load(object sender, EventArgs e)
    {
    }
}

'Inherits' must match the partial class name.


答:
What book are you using?

foreach is not a C++ keyword, and I think the closest extension that introduces it, with that specific syntax, into the language is in Visual C++, as described in this link: http://blogs.msdn.com/b/arich/archive/2004/09/08/227139.aspx

There is for_each in <algorithm>, but its signature is very different from what you're using (which is a very Java for-each syntax).

Also I notice that you're using Map which is different from std::map?

Title: foreach not recognized in C++


问:
Passing a string with double quotations as parameter from php to javascript
I've been trying to figure this thing out and I don't know what I'm doing wrong or maybe I'm missing something.

I'm trying to pass a string which contains double quotes that I retrieved from my database to be displayed in a textarea.

Situation sample looks like this:

```<code><?php
   $content = '<div align="center"><b>This is a sample content.</b></div>';
   echo '<textarea id="myTextArea"></textarea>';
   echo '<button onclick="myFunction('.$content.')">Click me</button>';
?>

<script>
  function myFunction(content){
    document.getElementById("myTextArea").innerHTML = content;
  }
</script>
</code>```

Expected results should be that myTextArea should contain the text, but the result shows:

Output

Your help is greatly appreciated.

答:
You need to escape your quotes inside the string:

```<code>   $content = "<div align=\"center\"><b>This is a sample content.</b></div>";
</code>```

You could also use apostrophes in this case, like

```<code>   $content = "<div align='center'><b>This is a sample content.</b></div>";
</code>```

or

```<code>   $content = '<div align="center"><b>This is a sample content.</b></div>';
</code>```

EDIT:

Also, make sure you use content as a string:

```<code>echo '<button onclick="myFunction(\''.$content.'\')">Click me</button>';
</code>```

Body:
I've been trying to figure this thing out and I don't know what I'm doing wrong or maybe I'm missing something.

I'm trying to pass a string which contains double quotes that I retrieved from my database to be displayed in a textarea.

Situation sample looks like this:

<?php
   $content = '
This is a sample content.
';
   echo '<textarea id="myTextArea"></textarea>';
   echo '<button onclick="myFunction('.$content.')">Click me</button>';
?>

Expected results should be that myTextArea should contain the text, but the result shows:

Output

Your help is greatly appreciated.

Body:
You need to escape your quotes inside the string:

   $content = "<div align=\"center\"><b>This is a sample content.</b></div>";

You could also use apostrophes in this case, like

   $content = "<div align='center'><b>This is a sample content.</b></div>";

or

   $content = '<div align="center"><b>This is a sample content.</b></div>';

EDIT:

Also, make sure you use content as a string:

echo '<button onclick="myFunction(\''.$content.'\')">Click me</button>';


问:
Get site control feedback widget not loading in react app
I recently changed to use browserHistory from hashHistory in a react app. The get site control feedback widget used to work without any problem with the different urls in the app.But its not working after the change. E.g at www.xxx.com, the widget works but at www.xxx.com/yyy, it does not work.

When I inspect the element, i can see the scripts needed to load the widget. I am wondering if it is something related to browswerHistory thing.
Would highly appreciate, if anyone has any idea about it.

答:
I actually found a solution. Its actually getsitecontrol that is making not to display in other pagers. I had to make a small change in the setting of getsitecontrol dashboard. I added * on the target url after slash (/). www.xyz.com/*
It had nothing to do with browserHistory as I thought before. </p>


答:
You should quote your output using htmlspecialchars(), such that it reads:</p>

```<code><?php
   $content = "<div align=\"center\"><b>This is a sample content.</b></div>";
   echo '<textarea id="myTextArea"></textarea>';
   echo '<button onclick="myFunction(\''.htmlspecialchars($content).'\')">Click me</button>';
?>

<script>
  function myFunction(content){
    document.getElementById("myTextArea").innerHTML = content;
  }
</script>
</code>```

Title: Passing a string with double quotations as parameter from php to javascript

Body:
You should quote your output using htmlspecialchars(), such that it reads:

<?php
   $content = "<div align=\"center\"><b>This is a sample content.</b></div>";
   echo '<textarea id="myTextArea"></textarea>';
   echo '<button onclick="myFunction(\''.htmlspecialchars($content).'\')">Click me</button>';
?>

<script>
  function myFunction(content){
    document.getElementById("myTextArea").innerHTML = content;
  }
</script>


问:
How can we configure database connection from JBOSS?
Can we configure database connection from JBOSS? If it is possible, than is there any configuration file in JBOSS to configure database connection from JBOSS?</p>

答:
Follow the following steps:

Add my sql connector jar in main folder (eg. \modules\system\layers\base\com\mysql\main).

Add a module.xml file to this folder consisting of the following config:

<?xml version="1.0" encoding="UTF-8"?>

<module xmlns="urn:jboss:module:1.0" name="com.mysql">
    <resources>
        <resource-root path="mysql-connector-java-5.1.17-bin.jar"/>
    </resources>

    <dependencies>
        <module name="javax.api"/>
        <module name="javax.transaction.api"/>
        <module name="javax.servlet.api" optional="true"/>
    </dependencies>
</module>
```
<ol start="3">
<li>Now in stanalone.xml file add mysql driver under drivers tag as following:</li>
</ol>
<pre class="lang-xml prettyprint-override"><code><driver name="mysql" module="com.mysql">
    <driver-class>com.mysql.jdbc.Driver</driver-class>
</driver>
</code>```

start the jboss server from command prompt by going to location of the jboss/bin folder and executing standalone.bat

Now in a browser, open localhost:8080,  click on administration console and under create a datasource click datasource. Then click on add.
Add the following details:

Name: MysqlDS5

JNDI Name : java:/mysql

click next and under "detected driver" select mysql.

click next

Connection url : jdbc:mysql://localhost:3306/sampledb

UserName:****

Password:****

click done, select the MysqlDS and click on enable.

click on test connection and it will successfully connect.

Body:
Follow the following steps:

Add my sql connector jar in main folder (eg. \modules\system\layers\base\com\mysql\main).

Add a module.xml file to this folder consisting of the following config:

<?xml version="1.0" encoding="UTF-8"?>

<module xmlns="urn:jboss:module:1.0" name="com.mysql">
    <resources>
        <resource-root path="mysql-connector-java-5.1.17-bin.jar"/>
    </resources>

    <dependencies>
        <module name="javax.api"/>
        <module name="javax.transaction.api"/>
        <module name="javax.servlet.api" optional="true"/>
    </dependencies>
</module>

Now in stanalone.xml file add mysql driver under drivers tag as following:

<driver name="mysql" module="com.mysql">
    <driver-class>com.mysql.jdbc.Driver</driver-class>
</driver>

start the jboss server from command prompt by going to location of the jboss/bin folder and executing standalone.bat

Now in a browser, open localhost:8080,  click on administration console and under create a datasource click datasource. Then click on add.
Add the following details:

Name: MysqlDS5

JNDI Name : java:/mysql

click next and under "detected driver" select mysql.

click next

Connection url : jdbc:mysql://localhost:3306/sampledb

UserName:****

Password:****

click done, select the MysqlDS and click on enable.

click on test connection and it will successfully connect.


问:
What is the type for boolean attributes in Core Data entities?
I am using Core Data programmatically (i.e. not using .xcdatamodel data model files) in much the same manner as depicted in Apple's Core Data Utility Tutorial. So my problem is that when I try to add an attribute to an entity with the type NSBooleanAttributeType, it gets a bit buggy. When I add it to my NSManagedObject subclass header file (in the tutorial, that would be Run.h) as

```<code>@property (retain) BOOL *booleanProperty;
</code>```

compiling fails, saying error: property 'booleanProperty' with 'retain' attribute must be of object type.

It seems like some places in Cocoa use NSNumber objects to represent booleans, so I tried setting it to

```<code>@property (retain) NSNumber *booleanProperty;
</code>```

instead. However, this evokes the following runtime errors:

```<code>*** -[NSAttributeDescription _setManagedObjectModel:]: unrecognized selector sent to instance 0x101b470
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSAttributeDescription _setManagedObjectModel:]: unrecognized selector sent to instance 0x101b470'
</code>```

Using GDB, I am able to trace this back to the line in my source code where I add my entity to the managed object model:

```<code>[DVManagedObjectModel setEntities:[NSArray arrayWithObjects:myEntityWithABooleanAttribute, myOtherEntity]];
</code>```

So my question is this: what type should I set booleanProperty to in my custom class header?

答: Use NSNumber. There's no bool in the CoreData framework.</p>

Body:
I am using Core Data programmatically (i.e. not using .xcdatamodel data model files) in much the same manner as depicted in Apple's Core Data Utility Tutorial. So my problem is that when I try to add an attribute to an entity with the type NSBooleanAttributeType, it gets a bit buggy. When I add it to my NSManagedObject subclass header file (in the tutorial, that would be Run.h) as

@property (retain) BOOL *booleanProperty;

compiling fails, saying error: property 'booleanProperty' with 'retain' attribute must be of object type.

It seems like some places in Cocoa use NSNumber objects to represent booleans, so I tried setting it to

@property (retain) NSNumber *booleanProperty;

instead. However, this evokes the following runtime errors:

*** -[NSAttributeDescription _setManagedObjectModel:]: unrecognized selector sent to instance 0x101b470
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSAttributeDescription _setManagedObjectModel:]: unrecognized selector sent to instance 0x101b470'

Using GDB, I am able to trace this back to the line in my source code where I add my entity to the managed object model:

[DVManagedObjectModel setEntities:[NSArray arrayWithObjects:myEntityWithABooleanAttribute, myOtherEntity]];

So my question is this: what type should I set booleanProperty to in my custom class header?


问:
Read an url HTTPS in a JSON file swift
I try to read an URL request (in dictionary "vehicles")in a json but the array will empty
This is the json and I need to read the dictionary and the url that are in vehicles

```<code>{
"count": 87,
"next": "https://swapi.co/api/people/?page=2",
"previous": null,
"results": [
    {
        "name": "Luke Skywalker",
        "height": "172",
        "mass": "77",
        "hair_color": "blond",
        "skin_color": "fair",
        "eye_color": "blue",
        "birth_year": "19BBY",
        "gender": "male",
        "homeworld": "https://swapi.co/api/planets/1/",
        "films": [
            "https://swapi.co/api/films/2/",
            "https://swapi.co/api/films/6/",
            "https://swapi.co/api/films/3/",
            "https://swapi.co/api/films/1/",
            "https://swapi.co/api/films/7/"
        ],
        "species": [
            "https://swapi.co/api/species/1/"
        ],
        "vehicles": [
            "https://swapi.co/api/vehicles/14/",
            "https://swapi.co/api/vehicles/30/"
        ],
</code>```

This is the code that I try

```<code>if let results = json["results"] as? [[String : AnyObject]] {

                    var finalArray2 : [String] = []
                    for result in results {
                        if let dict = result as? [String: Any], let vehicles = dict["vehicles"] as? String{
                            self.URLveicoli = vehicles
                            //print(self.nomepersonaggio)
                            print(self.URLveicoli)
                            //finalArray.append(name)
                            finalArray2.append(vehicles)

                        }
                    }
                    print(finalArray2)

                }
</code>```

答:
In json vehicles is an array of strings (urls) not a string.

Change this

```<code>let vehicles = dict["vehicles"] as? String
</code>```

To

```<code>let vehicles = dict["vehicles"] as? [String]
</code>```

And to append array of vechicles

```<code>finalArray2.append(contentsOf: vehicles)
</code>```

Title: Read an url HTTPS in a JSON file swift

Body:
I try to read an URL request (in dictionary "vehicles")in a json but the array will empty
This is the json and I need to read the dictionary and the url that are in vehicles

{
"count": 87,
"next": "https://swapi.co/api/people/?page=2",
"previous": null,
"results": [
    {
        "name": "Luke Skywalker",
        "height": "172",
        "mass": "77",
        "hair_color": "blond",
        "skin_color": "fair",
        "eye_color": "blue",
        "birth_year": "19BBY",
        "gender": "male",
        "homeworld": "https://swapi.co/api/planets/1/",
        "films": [
            "https://swapi.co/api/films/2/",
            "https://swapi.co/api/films/6/",
            "https://swapi.co/api/films/3/",
            "https://swapi.co/api/films/1/",
            "https://swapi.co/api/films/7/"
        ],
        "species": [
            "https://swapi.co/api/species/1/"
        ],
        "vehicles": [
            "https://swapi.co/api/vehicles/14/",
            "https://swapi.co/api/vehicles/30/"
        ],

This is the code that I try

if let results = json["results"] as? [[String : AnyObject]] {

                    var finalArray2 : [String] = []
                    for result in results {
                        if let dict = result as? [String: Any], let vehicles = dict["vehicles"] as? String{
                            self.URLveicoli = vehicles
                            //print(self.nomepersonaggio)
                            print(self.URLveicoli)
                            //finalArray.append(name)
                            finalArray2.append(vehicles)

                        }
                    }
                    print(finalArray2)

                }

Body:
In json vehicles is an array of strings (urls) not a string.

Change this

let vehicles = dict["vehicles"] as? String

To

let vehicles = dict["vehicles"] as? [String]

And to append array of vechicles

finalArray2.append(contentsOf: vehicles)


问:
Lags data on Pandas dataframes
I'm using sklearn to make a forecast. Usually i will create lagged data to forecasting, this is easy if the feature only consist 1 column.

for example:

```<code>index  temperature
1      100
2      80
3      50
4      90
5      110
</code>```

Usually i will create another column with shifting the temperature value to create lagged data using function like:

```<code>dataframe.temperature.shift()
</code>```

So my dataframe become:

```<code>index  temperature temperature2 temperature3
1      100         NaN          NaN
2      80          100          NaN
3      50          80           100
4      90          50           80
5      110         90           50
</code>```

Then when i want to forecast, i can fit using code like:

```<code>x = dataframe.loc[:,('temperature3','temperature2')]
y = dataframe.temperature
model.fit([x],y)
</code>```

The problem is when i have a lot of column to create lag data, and need more lagged data for each column, my dataframe will be too big.

Is there any simple approach that i can use? Thanks!

For reference, this is my dataframe:

```<code>import pandas as pd
import talib

df = pd.read_csv('..\\data\\uj5.CSV', names=['date','time','open','high','low','close','volume'])
df.index = pd.to_datetime(df.date + df.time,format='%Y.%m.%d%H:%M')

# assuming this is the 'X', let say i need 100 lags of these column to predict the 'Y'
df['CDLBELTHOLD'] = talib.CDLBELTHOLD(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLCLOSINGMARUBOZU'] = talib.CDLCLOSINGMARUBOZU(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLDOJI'] = talib.CDLDOJI(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLHIKKAKE'] = talib.CDLHIKKAKE(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLLONGLEGGEDDOJI'] = talib.CDLLONGLEGGEDDOJI(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLLONGLINE'] = talib.  CDLLONGLINE(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLSHORTLINE'] = talib.CDLSHORTLINE(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLSPINNINGTOP'] = talib.CDLSPINNINGTOP(df.open.values, df.high.values, df.low.values, df.close.values)
df['atr'] = talib.ATR(df.high.values, df.low.values, df.close.values,timeperiod=14)

#assuming this is the Y
df['target'] = #some int value
</code>```

答:
So don't create multiple columns with lag-n data.

Only dynamically compute the lagged data when you need it. For example, it might even be possible to frame the computation with all the lags it as multiplication by some matrix kernel. We don't know till we see your code.
Show us your specific code or formula you're trying to compute if you want a more specific answer.

EDIT: to the downvoters, this is actually the more correct answer. If you clog up your dataframe with all sorts of intermediate and temporary columns, you will waste memory. On stuff you can dynamically compute as-needed. That's the wrong way to go. Same general principle as lazy-evaluation in Spark.

Title: Lags data on Pandas dataframes

Body:
I'm using sklearn to make a forecast. Usually i will create lagged data to forecasting, this is easy if the feature only consist 1 column.

for example:

index  temperature
1      100
2      80
3      50
4      90
5      110

Usually i will create another column with shifting the temperature value to create lagged data using function like:

dataframe.temperature.shift()

So my dataframe become:

index  temperature temperature2 temperature3
1      100         NaN          NaN
2      80          100          NaN
3      50          80           100
4      90          50           80
5      110         90           50

Then when i want to forecast, i can fit using code like:

x = dataframe.loc[:,('temperature3','temperature2')]
y = dataframe.temperature
model.fit([x],y)

The problem is when i have a lot of column to create lag data, and need more lagged data for each column, my dataframe will be too big.

Is there any simple approach that i can use? Thanks!

For reference, this is my dataframe:

import pandas as pd
import talib

df = pd.read_csv('..\\data\\uj5.CSV', names=['date','time','open','high','low','close','volume'])
df.index = pd.to_datetime(df.date + df.time,format='%Y.%m.%d%H:%M')

# assuming this is the 'X', let say i need 100 lags of these column to predict the 'Y'
df['CDLBELTHOLD'] = talib.CDLBELTHOLD(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLCLOSINGMARUBOZU'] = talib.CDLCLOSINGMARUBOZU(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLDOJI'] = talib.CDLDOJI(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLHIKKAKE'] = talib.CDLHIKKAKE(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLLONGLEGGEDDOJI'] = talib.CDLLONGLEGGEDDOJI(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLLONGLINE'] = talib.  CDLLONGLINE(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLSHORTLINE'] = talib.CDLSHORTLINE(df.open.values, df.high.values, df.low.values, df.close.values)
df['CDLSPINNINGTOP'] = talib.CDLSPINNINGTOP(df.open.values, df.high.values, df.low.values, df.close.values)
df['atr'] = talib.ATR(df.high.values, df.low.values, df.close.values,timeperiod=14)

#assuming this is the Y
df['target'] = #some int value


问:
How to get the interface used to join a multicast group programmatically?
Is there a way to find which interface has been used to join an IPv6 multicast group, if the index used was 0 meaning that we leave to the kernel to choose which interface is suitable.
Can we get that information afterwards?</p>

答: Does the IPV6_MULTICAST_IF socket option change after the join is complete? If not you'll have to look at the interface table and see which is the default, on windows this would be done with GetAdaptersAddresses, no idea for *nix.</p>


问:
Converting Curl Sheel code to PHP
I want to convert Curl Shell code to PHP code, but i am getting a error that illegal charaters found in URL

```<code><?php
    $url = "https://www.unocoin.com/api/v1/general/prices";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_URL, "Content-Type:application/json
    -H");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST
    -H");

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }
    curl_close ($ch);
?>
</code>```

I want the json format to be displayed on the screen

The Output of above code

答:
Looking briefly at the api documentation you need to set the authorization header and set the content-type and make a POST request. I hope the following will give some guidance  - though I'm unable to fully test due to not having a valid  bearer token.

```<code><?php

    $url='https://www.unocoin.com/api/v1/general/prices';
    $token='ef0e897abb0c573fbed4bcf617bfb9c0e8b34bb3';
    $result=unicoinrequest( $url, $token );

    if( $result->info->http_code==200 ){

        echo '```',print_r( $result->response,true ),'```';

    } else {
        echo '```',print_r( $result->info,true ),'```';
        echo '```',print_r( $result->errors,true ),'```';
    }

    function unicoinrequest( $url=false, $token=false ){
        /*
            Download a copy of cacert.pem from
            https://curl.haxx.se/ca/cacert.pem
        */
        $cacert='c:/wwwroot/cacert.pem';#   <----- set to applicable location

        $res=array(
            'response'  =>  null,
            'info'      =>  array( 'http_code' => 0 ),
            'headers'   =>  null,
            'errors'    =>  null,
            'verbose'   =>  null
        );
        if( empty( $url ) ) return (object)$res;

        $vbh = fopen('php://temp', 'w+');

        session_write_close();

        /* Initialise curl request object */
        $curl=curl_init();
        if( parse_url( $url,PHP_URL_SCHEME )=='https' ){
            curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, true );
            curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, 2 );
            curl_setopt( $curl, CURLOPT_CAINFO, $cacert );
        }

        /* Define standard options */
        curl_setopt( $curl, CURLOPT_URL,trim( $url ) );
        curl_setopt( $curl, CURLOPT_AUTOREFERER, true );
        curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );
        curl_setopt( $curl, CURLOPT_FAILONERROR, true );
        curl_setopt( $curl, CURLOPT_HEADER, false );
        curl_setopt( $curl, CURLINFO_HEADER_OUT, false );
        curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $curl, CURLOPT_BINARYTRANSFER, true );
        curl_setopt( $curl, CURLOPT_CONNECTTIMEOUT, 20 );
        curl_setopt( $curl, CURLOPT_TIMEOUT, 60 );
        curl_setopt( $curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' );
        curl_setopt( $curl, CURLOPT_MAXREDIRS, 10 );
        curl_setopt( $curl, CURLOPT_ENCODING, '' );

        curl_setopt( $curl, CURLOPT_CUSTOMREQUEST, 'POST' );
        curl_setopt( $curl, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Authorization: Bearer ' . $token ) );

        curl_setopt( $curl,CURLOPT_VERBOSE,true );
        curl_setopt( $curl,CURLOPT_NOPROGRESS,true );
        curl_setopt( $curl,CURLOPT_STDERR,$vbh );

        /* Execute the request and store responses */
        $res=(object)array(
            'response'  =>  curl_exec( $curl ),
            'info'      =>  (object)curl_getinfo( $curl ),
            'errors'    =>  curl_error( $curl )
        );
        curl_close( $curl );

        rewind( $vbh );
        $res->verbose=stream_get_contents( $vbh );
        fclose( $vbh );

        return $res;
    }

?>
</code>```

The result

```<code>stdClass Object
(
    [url] => https://www.unocoin.com/api/v1/general/prices
    [content_type] =>
    [http_code] => 401
    [header_size] => 0
    [request_size] => 268
    [filetime] => -1
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 1.747
    [namelookup_time] => 0
    [connect_time] => 0.281
    [pretransfer_time] => 0.827
    [size_upload] => 0
    [size_download] => 0
    [speed_download] => 0
    [speed_upload] => 0
    [download_content_length] => -1
    [upload_content_length] => 0
    [starttransfer_time] => 1.747
    [redirect_time] => 0
    [certinfo] => Array
        (
        )

)
The requested URL returned error: 401
</code>```

Title: Converting Curl Sheel code to PHP

Body:
I want to convert Curl Shell code to PHP code, but i am getting a error that illegal charaters found in URL

<?php
    $url = "https://www.unocoin.com/api/v1/general/prices";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_URL, "Content-Type:application/json
    -H");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST
    -H");

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }
    curl_close ($ch);
?>

I want the json format to be displayed on the screen

The Output of above code

Body:
Looking briefly at the api documentation you need to set the authorization header and set the content-type and make a POST request. I hope the following will give some guidance  - though I'm unable to fully test due to not having a valid  bearer token.

<?php

    $url='https://www.unocoin.com/api/v1/general/prices';
    $token='ef0e897abb0c573fbed4bcf617bfb9c0e8b34bb3';
    $result=unicoinrequest( $url, $token );

    if( $result->info->http_code==200 ){

        echo '<pre>',print_r( $result->response,true ),'</pre>';

    } else {
        echo '<pre>',print_r( $result->info,true ),'</pre>';
        echo '<pre>',print_r( $result->errors,true ),'</pre>';
    }

    function unicoinrequest( $url=false, $token=false ){
        /*
            Download a copy of cacert.pem from
            https://curl.haxx.se/ca/cacert.pem
        */
        $cacert='c:/wwwroot/cacert.pem';#   <----- set to applicable location

        $res=array(
            'response'  =>  null,
            'info'      =>  array( 'http_code' => 0 ),
            'headers'   =>  null,
            'errors'    =>  null,
            'verbose'   =>  null
        );
        if( empty( $url ) ) return (object)$res;

        $vbh = fopen('php://temp', 'w+');

        session_write_close();

        /* Initialise curl request object */
        $curl=curl_init();
        if( parse_url( $url,PHP_URL_SCHEME )=='https' ){
            curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, true );
            curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, 2 );
            curl_setopt( $curl, CURLOPT_CAINFO, $cacert );
        }

        /* Define standard options */
        curl_setopt( $curl, CURLOPT_URL,trim( $url ) );
        curl_setopt( $curl, CURLOPT_AUTOREFERER, true );
        curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );
        curl_setopt( $curl, CURLOPT_FAILONERROR, true );
        curl_setopt( $curl, CURLOPT_HEADER, false );
        curl_setopt( $curl, CURLINFO_HEADER_OUT, false );
        curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $curl, CURLOPT_BINARYTRANSFER, true );
        curl_setopt( $curl, CURLOPT_CONNECTTIMEOUT, 20 );
        curl_setopt( $curl, CURLOPT_TIMEOUT, 60 );
        curl_setopt( $curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' );
        curl_setopt( $curl, CURLOPT_MAXREDIRS, 10 );
        curl_setopt( $curl, CURLOPT_ENCODING, '' );

        curl_setopt( $curl, CURLOPT_CUSTOMREQUEST, 'POST' );
        curl_setopt( $curl, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Authorization: Bearer ' . $token ) );

        curl_setopt( $curl,CURLOPT_VERBOSE,true );
        curl_setopt( $curl,CURLOPT_NOPROGRESS,true );
        curl_setopt( $curl,CURLOPT_STDERR,$vbh );

        /* Execute the request and store responses */
        $res=(object)array(
            'response'  =>  curl_exec( $curl ),
            'info'      =>  (object)curl_getinfo( $curl ),
            'errors'    =>  curl_error( $curl )
        );
        curl_close( $curl );

        rewind( $vbh );
        $res->verbose=stream_get_contents( $vbh );
        fclose( $vbh );

        return $res;
    }

?>

The result

stdClass Object
(
    [url] => https://www.unocoin.com/api/v1/general/prices
    [content_type] =>
    [http_code] => 401
    [header_size] => 0
    [request_size] => 268
    [filetime] => -1
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 1.747
    [namelookup_time] => 0
    [connect_time] => 0.281
    [pretransfer_time] => 0.827
    [size_upload] => 0
    [size_download] => 0
    [speed_download] => 0
    [speed_upload] => 0
    [download_content_length] => -1
    [upload_content_length] => 0
    [starttransfer_time] => 1.747
    [redirect_time] => 0
    [certinfo] => Array
        (
        )

)
The requested URL returned error: 401


问:
Saving and running wide_deep.py model
I've been playing around with the Tensorflow Wide and Deep tutorial using the census dataset.

The linear/wide tutorial states:

```<code>We will train a logistic regression model, and given an individual's information our model will output a number between 0 and 1
</code>```

At the moment, I can't work out how to predict the output of an individual input (copied from the unit test):

```<code>TEST_INPUT_VALUES = {
    'age': 18,
    'education_num': 12,
    'capital_gain': 34,
    'capital_loss': 56,
    'hours_per_week': 78,
    'education': 'Bachelors',
    'marital_status': 'Married-civ-spouse',
    'relationship': 'Husband',
    'workclass': 'Self-emp-not-inc',
    'occupation': 'abc',
}
</code>```

How can we predict and output whether this person is likely to earn <50k (0) or >=50k (1)?

答:
Hookay, I can answer this now.. So if you want to evaluate the test set accuracy, you can follow the accepted answer, but if you want to make your own predictions, here are the steps.

First, construct a new input_fn, notice you need to alter the columns and the default column values since the label column wouldn't be there.

```<code>def parse_csv(value):
    print('Parsing', data_file)
    columns = tf.decode_csv(value, record_defaults=_PREDICT_COLUMNS_DEFAULTS)
    features = dict(zip(_PREDICT_COLUMNS, columns))

    return features

def predict_input_fn(data_file):
    assert tf.gfile.Exists(data_file), ('%s not found. Please make sure the path is correct.' % data_file)

    dataset = tf.data.TextLineDataset(data_file)
    dataset = dataset.map(parse_csv, num_parallel_calls=5)
    dataset = dataset.batch(1) # => This is very important to get the rank correct
    iterator = dataset.make_one_shot_iterator()
    features = iterator.get_next()
    return features
</code>```

Then you can just call it simply by

```<code>results = model.predict(
        input_fn=lambda: predict_input_fn(data_file='test.csv')
    )
</code>```

Title: Saving and running wide_deep.py model

Body:
I've been playing around with the Tensorflow Wide and Deep tutorial using the census dataset.

The linear/wide tutorial states:

We will train a logistic regression model, and given an individual's information our model will output a number between 0 and 1

At the moment, I can't work out how to predict the output of an individual input (copied from the unit test):

TEST_INPUT_VALUES = {
    'age': 18,
    'education_num': 12,
    'capital_gain': 34,
    'capital_loss': 56,
    'hours_per_week': 78,
    'education': 'Bachelors',
    'marital_status': 'Married-civ-spouse',
    'relationship': 'Husband',
    'workclass': 'Self-emp-not-inc',
    'occupation': 'abc',
}

How can we predict and output whether this person is likely to earn <50k (0) or >=50k (1)?

Body:
Hookay, I can answer this now.. So if you want to evaluate the test set accuracy, you can follow the accepted answer, but if you want to make your own predictions, here are the steps.

First, construct a new input_fn, notice you need to alter the columns and the default column values since the label column wouldn't be there.

def parse_csv(value):
    print('Parsing', data_file)
    columns = tf.decode_csv(value, record_defaults=_PREDICT_COLUMNS_DEFAULTS)
    features = dict(zip(_PREDICT_COLUMNS, columns))

    return features

def predict_input_fn(data_file):
    assert tf.gfile.Exists(data_file), ('%s not found. Please make sure the path is correct.' % data_file)

    dataset = tf.data.TextLineDataset(data_file)
    dataset = dataset.map(parse_csv, num_parallel_calls=5)
    dataset = dataset.batch(1) # => This is very important to get the rank correct
    iterator = dataset.make_one_shot_iterator()
    features = iterator.get_next()
    return features

Then you can just call it simply by

results = model.predict(
        input_fn=lambda: predict_input_fn(data_file='test.csv')
    )


问:
State in componentDidMount always null, there should be data from the task variable
I have a problem, every i call state "modalData" in componentDidMount, state always null, there should be data from the task variable.</p>

```<code>constructor(props){
    super(props);
    this.tasksRef = firebase.database().ref('/users/'+ this.props.card_id);
    this.state = {
        modalData : null,
    }
}

componentDidMount(tasksRef){
    var task = [];
    tasksRef.on('value', (dataSnapshot) => {
        task.push({
            about : dataSnapshot.val().about,
            card : dataSnapshot.val().card,
            company : dataSnapshot.val().company,
            first_name : dataSnapshot.val().first_name,
            job_title : dataSnapshot.val().job_title,
            last_name : dataSnapshot.val().last_name,
            photo : dataSnapshot.val().photo,
            role : dataSnapshot.val().role,
            thumbnail : dataSnapshot.val().thumbnail,
            title : dataSnapshot.val().title,
            website : dataSnapshot.val().website,
            _key : dataSnapshot.key
        });
        console.log('dataSnapshot.val().first_name : ' + dataSnapshot.val().first_name);
    });
    console.log(task); //there is data
    this.setState({
        modalData : task,
    });
    console.log(this.state.modalData); //there is no data
}
</code>```

答:
Logging it after setting won't work. You can use </p>

```<code> this.state.modalData = task
</code>```

<p>, then logging it . That would work. for your logging.</p>

Body:
I have a problem, every i call state "modalData" in componentDidMount, state always null, there should be data from the task variable.

constructor(props){
    super(props);
    this.tasksRef = firebase.database().ref('/users/'+ this.props.card_id);
    this.state = {
        modalData : null,
    }
}

componentDidMount(tasksRef){
    var task = [];
    tasksRef.on('value', (dataSnapshot) => {
        task.push({
            about : dataSnapshot.val().about,
            card : dataSnapshot.val().card,
            company : dataSnapshot.val().company,
            first_name : dataSnapshot.val().first_name,
            job_title : dataSnapshot.val().job_title,
            last_name : dataSnapshot.val().last_name,
            photo : dataSnapshot.val().photo,
            role : dataSnapshot.val().role,
            thumbnail : dataSnapshot.val().thumbnail,
            title : dataSnapshot.val().title,
            website : dataSnapshot.val().website,
            _key : dataSnapshot.key
        });
        console.log('dataSnapshot.val().first_name : ' + dataSnapshot.val().first_name);
    });
    console.log(task); //there is data
    this.setState({
        modalData : task,
    });
    console.log(this.state.modalData); //there is no data
}

Body:
Logging it after setting won't work. You can use

 this.state.modalData = task

, then logging it . That would work. for your logging.