问:
Linking problem when using jsoncpp library
I have a problem related to the parsing of a JSON file. It is composed of an array of JSON objects and the program I've developed parses this by just iterate over the various { ... } elements found in the file.

The elements (in the JSON file, these are the rows of the file) are structured in such a way that inside each row there can be other inner elements, but this goes beyond the problem I have to handle now.

In short, I have a Block; inside it, I have, in addition to other fields, a vector Operations whose type is Operation, and in this vector, each element can be a subtype of Operation, so e.g., Vote, Comment, Follow, Repost, ...

To handle this, I've created a BlockStructure.hpp file header that includes both the definition of the class Operation together with the (only) virtual method print() and the definition of the classes listed before. In addition to these definitions, there is also the definition of the TransactionBlock, Transaction and BlockStructure

```<code>// BlockStructure.hpp

#include <string>
#include <list>
#include <utility>
#include <iostream>
#include <cstring>
#include <vector>

using namespace std;

using ui = unsigned int;

class Operation{
public:
    string kind = "";
    virtual string print();
};

class Vote : public Operation {
private:
    string voter, author;
public:
    Vote(string voter, string author);
    virtual string print();
    string get_voter();
    string get_author();
};

class Comment : Operation{
private:
    string parent_author, author, title, body;
public:
    Comment(string parent_author, string author, string title, string body);
    string get_author();
    virtual string print();
};

class Follow : Operation{
private:
    string follower, following;
    vector<string> common_follows{};
public:
    CustomJsonFollow(string follower, string following, vector<string> common_follows);
    static void strip(vector<string> *w); // implements the common strip function
    static void stripLeadingAndtrailingSpaces(string *stng); // implements the strip by removing the whitespaces
    string get_follower();
    string get_following();
    vector<string> get_common_follows();
    virtual string print();
};

class Reblog : Operation{
private:
    string account, author;
public:
    CustomJsonReblog(string account, string author);
    string get_account();
    string get_author();
    virtual string print();
};

class TransactionBlock{
private:
    vector<Operation*> operations{};
    string transaction_id;
    int transaction_num = -1;

public:
    TransactionBlock(vector<Operation*> ops);
    TransactionBlock();
    vector<Operation*> get_operations();
    void set_operations(vector<Operation*> ops);
    string get_transaction_id();
    void set_transaction_id(string tid);
    int get_transaction_num();
    void set_transaction_num(int trn);
    string print();
};

class Transaction{
private:
    string transaction_id;
    TransactionBlock transactionBlock;
public:
    Transaction(string tr_id, TransactionBlock  transactionBlock);
    string get_transaction_id();
    void set_transaction_id(string tid);
    TransactionBlock get_transaction_block();
    void set_transaction_block(TransactionBlock tbl);
    void print();
};

class BlockStructure{
private:
    list<Transaction> transactions{};
    string timestamp;
    list<int> transaction_ids;
    TransactionBlock transactionBlock;
public:
    BlockStructure();
    void set_transactions(list<Transaction> transact);
    void set_transaction_block(TransactionBlock transactBlock);
    void set_timestamp(string ts);
    void set_transaction_ids(list<int> tr_ids);
    void set_transaction_block(const TransactionBlock& tb);
    TransactionBlock get_transaction_block();
    void print_block();

};
</code>```

Afterwards, in another file, called BlockStructure.cpp I have the implementation of all the methods defined in the header, so:

```<code>// BlockStructure.cpp

#include "BlockStructure.hpp"

using namespace std;

using ui = unsigned int;

// Operation

string Operation::print(){
    return "";
}

// Vote

Vote::Vote(string voter, string author) : voter(move(voter)), author(move(author)) { this->kind = "VOTE"; }

string Vote::print(){
    string toret = "V\n";
    toret += "voter: " + this->voter + "\n";
    toret += "auth: " + this->author + "\n";
    return toret;
}

string Vote::get_voter(){
    return this->voter;
}

string Vote::get_author(){
    return this->author;
}

// Comment

Comment::Comment(string parent_author, string author, string title, string body){
    this->parent_author = move(parent_author);
    this->author = move(author);
    this->title = move(title);
    this->body = move(body);
    this->kind = "COMMENT";
}

string Comment::get_author(){
    return this->author;
}

string Comment::print(){
    string toret = "C\n";
    toret += "par_auth: " + this->parent_author + "\n";
    toret += "auth: " + this->author + "\n";
    toret += "title: " + this->title + "\n";
    toret += "body: " + this->body + "\n";
    return toret;
}

// Follow

void Follow::strip(vector<string> *w) {
    auto it = w->begin();
    for (ui i = 0; i < w->size(); i++) {
        stripLeadingAndtrailingSpaces(&(*it));
        advance(it, 1);
    }
}

void Follow::stripLeadingAndtrailingSpaces(string *stng) {
    char *cur = const_cast<char *>(stng->c_str());
    /* First remove leading spaces */
    const char *firstNonSpace = cur;
    while (*firstNonSpace != '\0' && isspace(*firstNonSpace))
        ++firstNonSpace;
    size_t len = strlen(firstNonSpace) + 1;
    memmove(cur, firstNonSpace, len);
    /* Now remove trailing spaces */
    char *endOfString = cur + len;
    while (cur < endOfString && isspace(*endOfString))
        --endOfString;
    *endOfString = '\0';
}

Follow::Follow(string follower, string following, vector<string> common_follows, vector<string> required_posting_auths) {
    this->follower = move(follower);
    stripLeadingAndtrailingSpaces(&this->follower);
    this->following = move(following);
    stripLeadingAndtrailingSpaces(&this->following);
    this->common_follows = move(common_follows);
    strip(&this->common_follows);
    this->kind = "FOLLOW";
}

string Follow::get_follower() {
    return this->follower;
}

string Follow::get_following(){
    return this->following;
}

vector<string> Follow::get_common_follows(){
    return this->common_follows;
}

string Follow::print(){
    string toret = "F\n";
    toret += "follower: " + this->follower + "\n";
    toret += "following: " + this->following + "\n";
    if (!this->common_follows.empty()){
        toret += "common_follows: \n";
        for (const string& w : this->common_follows)
            toret += w + "\n";
    } else
        toret += "common_follows: []\n";
    return toret;
}

// Reblog

Reblog::Reblog(string account, string author){
    this->account = move(account);
    this->author = move(author);
    this->kind = "REBLOG";
}

string Reblog::get_account(){
    return this->account;
}

string Reblog::get_author(){
    return this->author;
}

string Reblog::print(){
    string toret = "RB\n";
    toret += "account: " + this->account + "\n";
    toret += "author: " + this->author + "\n";
    return toret;
}

</code>```

(and similarly for the TransactionBlock, Transaction and BlockStructure)

Then, I include BlockStructure.hpp inside the file ParsingBlocks.cpp defined in the following. The

```<code>"jsoncpp/dist/json/json.h"
"jsoncpp/dist/jsoncpp.cpp"
</code>```

files that I include in the beginning are the result of the python amalgamate.py script (this script generates also the jsoncpp/dist/json/json-forward.h, but I have read that it is not commonly used for the projects). I read that it is an approach to integrating JsonCpp in the project.

```<code>#include <fstream>
#include "jsoncpp/dist/json/json.h"
#include "jsoncpp/dist/jsoncpp.cpp"

#include "BlockStructure.hpp"

class ParsingBlocks {
private:
    string path;

public:
    ParsingBlocks(string path) : path(move(path)) {}

    vector<Operation*> fill_ops(const Value& trans_operations){
        vector<Operation*> op_array = {};
        for(Value op : trans_operations) {
            if (op[(UInt) 0].asString() == "vote") {
                string voter = op[1]["voter"].asString();
                Vote vt = Vote(op[1]["voter"].asString(), op[1]["author"].asString());
                op_array.push_back((Operation*)&vt);
            } else if (op[(UInt) 0].asString() == "comment") {
                Comment cmt = Comment(op[1]["parent_author"].asString(),
                                      op[1]["author"].asString(),
                                      op[1]["title"].asString(),
                                      op[1]["body"].asString());
                op_array.push_back((Operation*)&cmt);
            } else if (op[(UInt) 0].asString() == "custom_json") {
                auto custom = op[(UInt) 1];
                if (custom["id"].asString() == "follow") {
                    Value injs = custom["id"];
                    if (injs[(UInt) 0].asString() == "follow") {
                        vector<string> common_follows = {};
                        for (const auto &itr : injs[(UInt) 1]["common_follows"])
                            common_follows.push_back(itr.asString());
                        CustomJsonFollow follow = CustomJsonFollow(
                                injs[1]["follower"].asCString(),
                                injs[1]["following"].asCString(),
                                common_follows);
                        op_array.push_back((Operation*)&follow);
                    } else {
                        if (injs[(UInt) 0].asString() == "reblog") {
                            CustomJsonReblog reblog = CustomJsonReblog(
                                    injs[(UInt) 1]["account"].asCString(),
                                    injs[(UInt) 1]["author"].asCString());
                            op_array.push_back((Operation*)&reblog);
                        }
                    }
                }
            }
        }
    return op_array;

    BlockStructure evaluate_block(const string& line){
        ifstream ifs(line);
        CharReaderBuilder reader;
        Value data;
        string errs;

        Json::parseFromStream(reader, ifs, &data, &errs);
        BlockStructure bs = BlockStructure();

        for(Value::ArrayIndex i = 0; i != data.size(); i++){
            bs.set_timestamp(data[i]["timestamp"].asString());
            list<Transaction> transss{};
            for(const Value& transaction : data[i]["transactions"]){
                vector<Operation*> operations = fill_ops(transaction["operations"]);
                auto t_block = new TransactionBlock();
                t_block->set_transaction_num(transaction["transaction_num"].asInt());
                if (!operations.empty()){
                    t_block->set_operations(operations);
                }
                Transaction t = Transaction(transaction["transaction_id"].asString(), *t_block);
                transss.push_back(t);
            }
            bs.set_transactions(transss);
            bs.set_witness_name(data[i]["witness"].asString());
        }
        return bs;
    }

    list<BlockStructure> parsing_blocks(){
        string line;
        ifstream file;
        file.open(this->path);
        list<BlockStructure> blocks{};

        if(!file.is_open()){
            perror("Error open");
            exit(EXIT_FAILURE);
        }
        while (getline(file, line)){
            BlockStructure b = evaluate_block(line);
            blocks.push_back(b);
        }
        return blocks;
    }

}

</code>```

Leaving aside possible copy-and-paste errors (which I don't think I've done), now, I use the ParsingBlocks.cpp into the main.cpp defined as follows:

```<code>#include "ParsingBlocks.cpp"

using namespace std;

int main() {
    ParsingBlocks *pb = new ParsingBlocks("jsonfile.json");
    list<BlockStructure> blocks = pb->parsing_blocks();
    for(BlockStructure bl : blocks){
        bl.print_block();
    }
    return 0;
}
</code>```

I don't show another class (UserStructure.cpp) used in the compilation because it is useless for the purposes of the question.

My problem now is to understand how to compile the main.cpp file.

I'm relying on the jsoncpp external library so, at compile time I execute from command line the following:

c++ -std=c++17 -Wall -pedantic -I.  .\UserStructure.cpp .\BlockStructure.hpp .\BlockStructure.cpp .\ParsingBlocks.cpp .\main.cpp -o parsing.out

where the -I. flag is used to link in the current directory, the jsoncpp.cpp and json/json.h defined in the #includes at the beginning of the ParsingBlock.cpp file, as shown before.

The compilation gives me the following errors:

```<code>C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x2b6): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x2e0): multiple definition of `Json::Features::all()'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x2e0): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x2fe): multiple definition of `Json::Features::strictMode()'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x2fe): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x32c): multiple definition of `Json::Reader::containsNewLine(char const*, char const*)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x32c): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x36e): multiple definition of `Json::Reader::Reader()'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x36e): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x36e): multiple definition of `Json::Reader::Reader()'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x36e): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x44a): multiple definition of `Json::Reader::Reader(Json::Features const&)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x44a): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x44a): multiple definition of `Json::Reader::Reader(Json::Features const&)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x44a): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x52a): multiple definition of `Json::Reader::parse(std::__cxx11::basic_string<char,
std::char_traits<char>, std::allocator<char> > const&, Json::Value&, bool)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x52a): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x5de): multiple definition of `Json::Reader::parse(std::istream&, Json::Value&, bool)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x5de): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x698): multiple definition of `Json::Reader::parse(char const*, char const*, Json::Value&, bool)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x698): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x934): multiple definition of `Json::Reader::readValue()'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x934): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x1032): multiple definition of `Json::Reader::skipCommentTokens(Json::Reader::Token&)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x1032): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x1086): multiple definition of `Json::Reader::readToken(Json::Reader::Token&)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x1086): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x1246): multiple definition of `Json::Reader::skipSpaces()'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x1246): first defined here
</code>```

So, it should be evident that the problem is in the linking phase, but I cannot solve it!

I have tried by reading both the documentation and other questions on stackoverflow.com, but I get nowhere.

Thanks in advance for the help, and I'm sorry if this question is a little bit huge.

EDIT: The stderr output does not stop there: there are at least 1000 lines of error, but each one of these regards the same multiple definition of ..., C:...: first defined here.

答:
Include the header file in your main file instead of your source file:

```<code>#include "ParsingBlocks.hpp"
</code>```

#include in C and C++ is not a module-based include like in many other languages, but just directly inserts the text of the file. That means that everything from ParsingBlocks.cpp was read twice by the compiler: Once when it compiled your main file and once when it compiled ParsingBlocks.cpp itself, hence the duplicates.

Also you don't need to specify the header files in your compiler command line.

Body:
I have a problem related to the parsing of a JSON file. It is composed of an array of JSON objects and the program I've developed parses this by just iterate over the various { ... } elements found in the file.

The elements (in the JSON file, these are the rows of the file) are structured in such a way that inside each row there can be other inner elements, but this goes beyond the problem I have to handle now.

In short, I have a Block; inside it, I have, in addition to other fields, a vector Operations whose type is Operation, and in this vector, each element can be a subtype of Operation, so e.g., Vote, Comment, Follow, Repost, ...

To handle this, I've created a BlockStructure.hpp file header that includes both the definition of the class Operation together with the (only) virtual method print() and the definition of the classes listed before. In addition to these definitions, there is also the definition of the TransactionBlock, Transaction and BlockStructure

// BlockStructure.hpp

#include <string>
#include <list>
#include <utility>
#include <iostream>
#include <cstring>
#include <vector>

using namespace std;

using ui = unsigned int;

class Operation{
public:
    string kind = "";
    virtual string print();
};

class Vote : public Operation {
private:
    string voter, author;
public:
    Vote(string voter, string author);
    virtual string print();
    string get_voter();
    string get_author();
};

class Comment : Operation{
private:
    string parent_author, author, title, body;
public:
    Comment(string parent_author, string author, string title, string body);
    string get_author();
    virtual string print();
};

class Follow : Operation{
private:
    string follower, following;
    vector<string> common_follows{};
public:
    CustomJsonFollow(string follower, string following, vector<string> common_follows);
    static void strip(vector<string> *w); // implements the common strip function
    static void stripLeadingAndtrailingSpaces(string *stng); // implements the strip by removing the whitespaces
    string get_follower();
    string get_following();
    vector<string> get_common_follows();
    virtual string print();
};

class Reblog : Operation{
private:
    string account, author;
public:
    CustomJsonReblog(string account, string author);
    string get_account();
    string get_author();
    virtual string print();
};

class TransactionBlock{
private:
    vector<Operation*> operations{};
    string transaction_id;
    int transaction_num = -1;

public:
    TransactionBlock(vector<Operation*> ops);
    TransactionBlock();
    vector<Operation*> get_operations();
    void set_operations(vector<Operation*> ops);
    string get_transaction_id();
    void set_transaction_id(string tid);
    int get_transaction_num();
    void set_transaction_num(int trn);
    string print();
};

class Transaction{
private:
    string transaction_id;
    TransactionBlock transactionBlock;
public:
    Transaction(string tr_id, TransactionBlock  transactionBlock);
    string get_transaction_id();
    void set_transaction_id(string tid);
    TransactionBlock get_transaction_block();
    void set_transaction_block(TransactionBlock tbl);
    void print();
};

class BlockStructure{
private:
    list<Transaction> transactions{};
    string timestamp;
    list<int> transaction_ids;
    TransactionBlock transactionBlock;
public:
    BlockStructure();
    void set_transactions(list<Transaction> transact);
    void set_transaction_block(TransactionBlock transactBlock);
    void set_timestamp(string ts);
    void set_transaction_ids(list<int> tr_ids);
    void set_transaction_block(const TransactionBlock& tb);
    TransactionBlock get_transaction_block();
    void print_block();

};

Afterwards, in another file, called BlockStructure.cpp I have the implementation of all the methods defined in the header, so:

// BlockStructure.cpp

#include "BlockStructure.hpp"

using namespace std;

using ui = unsigned int;

// Operation

string Operation::print(){
    return "";
}

// Vote

Vote::Vote(string voter, string author) : voter(move(voter)), author(move(author)) { this->kind = "VOTE"; }

string Vote::print(){
    string toret = "V\n";
    toret += "voter: " + this->voter + "\n";
    toret += "auth: " + this->author + "\n";
    return toret;
}

string Vote::get_voter(){
    return this->voter;
}

string Vote::get_author(){
    return this->author;
}

// Comment

Comment::Comment(string parent_author, string author, string title, string body){
    this->parent_author = move(parent_author);
    this->author = move(author);
    this->title = move(title);
    this->body = move(body);
    this->kind = "COMMENT";
}

string Comment::get_author(){
    return this->author;
}

string Comment::print(){
    string toret = "C\n";
    toret += "par_auth: " + this->parent_author + "\n";
    toret += "auth: " + this->author + "\n";
    toret += "title: " + this->title + "\n";
    toret += "body: " + this->body + "\n";
    return toret;
}

// Follow

void Follow::strip(vector<string> *w) {
    auto it = w->begin();
    for (ui i = 0; i < w->size(); i++) {
        stripLeadingAndtrailingSpaces(&(*it));
        advance(it, 1);
    }
}

void Follow::stripLeadingAndtrailingSpaces(string *stng) {
    char *cur = const_cast<char *>(stng->c_str());
    /* First remove leading spaces */
    const char *firstNonSpace = cur;
    while (*firstNonSpace != '\0' && isspace(*firstNonSpace))
        ++firstNonSpace;
    size_t len = strlen(firstNonSpace) + 1;
    memmove(cur, firstNonSpace, len);
    /* Now remove trailing spaces */
    char *endOfString = cur + len;
    while (cur < endOfString && isspace(*endOfString))
        --endOfString;
    *endOfString = '\0';
}

Follow::Follow(string follower, string following, vector<string> common_follows, vector<string> required_posting_auths) {
    this->follower = move(follower);
    stripLeadingAndtrailingSpaces(&this->follower);
    this->following = move(following);
    stripLeadingAndtrailingSpaces(&this->following);
    this->common_follows = move(common_follows);
    strip(&this->common_follows);
    this->kind = "FOLLOW";
}

string Follow::get_follower() {
    return this->follower;
}

string Follow::get_following(){
    return this->following;
}

vector<string> Follow::get_common_follows(){
    return this->common_follows;
}

string Follow::print(){
    string toret = "F\n";
    toret += "follower: " + this->follower + "\n";
    toret += "following: " + this->following + "\n";
    if (!this->common_follows.empty()){
        toret += "common_follows: \n";
        for (const string& w : this->common_follows)
            toret += w + "\n";
    } else
        toret += "common_follows: []\n";
    return toret;
}

// Reblog

Reblog::Reblog(string account, string author){
    this->account = move(account);
    this->author = move(author);
    this->kind = "REBLOG";
}

string Reblog::get_account(){
    return this->account;
}

string Reblog::get_author(){
    return this->author;
}

string Reblog::print(){
    string toret = "RB\n";
    toret += "account: " + this->account + "\n";
    toret += "author: " + this->author + "\n";
    return toret;
}

(and similarly for the TransactionBlock, Transaction and BlockStructure)

Then, I include BlockStructure.hpp inside the file ParsingBlocks.cpp defined in the following. The

"jsoncpp/dist/json/json.h"
"jsoncpp/dist/jsoncpp.cpp"

files that I include in the beginning are the result of the python amalgamate.py script (this script generates also the jsoncpp/dist/json/json-forward.h, but I have read that it is not commonly used for the projects). I read that it is an approach to integrating JsonCpp in the project.

#include <fstream>
#include "jsoncpp/dist/json/json.h"
#include "jsoncpp/dist/jsoncpp.cpp"

#include "BlockStructure.hpp"

class ParsingBlocks {
private:
    string path;

public:
    ParsingBlocks(string path) : path(move(path)) {}

    vector<Operation*> fill_ops(const Value& trans_operations){
        vector<Operation*> op_array = {};
        for(Value op : trans_operations) {
            if (op[(UInt) 0].asString() == "vote") {
                string voter = op[1]["voter"].asString();
                Vote vt = Vote(op[1]["voter"].asString(), op[1]["author"].asString());
                op_array.push_back((Operation*)&vt);
            } else if (op[(UInt) 0].asString() == "comment") {
                Comment cmt = Comment(op[1]["parent_author"].asString(),
                                      op[1]["author"].asString(),
                                      op[1]["title"].asString(),
                                      op[1]["body"].asString());
                op_array.push_back((Operation*)&cmt);
            } else if (op[(UInt) 0].asString() == "custom_json") {
                auto custom = op[(UInt) 1];
                if (custom["id"].asString() == "follow") {
                    Value injs = custom["id"];
                    if (injs[(UInt) 0].asString() == "follow") {
                        vector<string> common_follows = {};
                        for (const auto &itr : injs[(UInt) 1]["common_follows"])
                            common_follows.push_back(itr.asString());
                        CustomJsonFollow follow = CustomJsonFollow(
                                injs[1]["follower"].asCString(),
                                injs[1]["following"].asCString(),
                                common_follows);
                        op_array.push_back((Operation*)&follow);
                    } else {
                        if (injs[(UInt) 0].asString() == "reblog") {
                            CustomJsonReblog reblog = CustomJsonReblog(
                                    injs[(UInt) 1]["account"].asCString(),
                                    injs[(UInt) 1]["author"].asCString());
                            op_array.push_back((Operation*)&reblog);
                        }
                    }
                }
            }
        }
    return op_array;

    BlockStructure evaluate_block(const string& line){
        ifstream ifs(line);
        CharReaderBuilder reader;
        Value data;
        string errs;

        Json::parseFromStream(reader, ifs, &data, &errs);
        BlockStructure bs = BlockStructure();

        for(Value::ArrayIndex i = 0; i != data.size(); i++){
            bs.set_timestamp(data[i]["timestamp"].asString());
            list<Transaction> transss{};
            for(const Value& transaction : data[i]["transactions"]){
                vector<Operation*> operations = fill_ops(transaction["operations"]);
                auto t_block = new TransactionBlock();
                t_block->set_transaction_num(transaction["transaction_num"].asInt());
                if (!operations.empty()){
                    t_block->set_operations(operations);
                }
                Transaction t = Transaction(transaction["transaction_id"].asString(), *t_block);
                transss.push_back(t);
            }
            bs.set_transactions(transss);
            bs.set_witness_name(data[i]["witness"].asString());
        }
        return bs;
    }

    list<BlockStructure> parsing_blocks(){
        string line;
        ifstream file;
        file.open(this->path);
        list<BlockStructure> blocks{};

        if(!file.is_open()){
            perror("Error open");
            exit(EXIT_FAILURE);
        }
        while (getline(file, line)){
            BlockStructure b = evaluate_block(line);
            blocks.push_back(b);
        }
        return blocks;
    }

}

Leaving aside possible copy-and-paste errors (which I don't think I've done), now, I use the ParsingBlocks.cpp into the main.cpp defined as follows:

#include "ParsingBlocks.cpp"

using namespace std;

int main() {
    ParsingBlocks *pb = new ParsingBlocks("jsonfile.json");
    list<BlockStructure> blocks = pb->parsing_blocks();
    for(BlockStructure bl : blocks){
        bl.print_block();
    }
    return 0;
}

I don't show another class (UserStructure.cpp) used in the compilation because it is useless for the purposes of the question.

My problem now is to understand how to compile the main.cpp file.

I'm relying on the jsoncpp external library so, at compile time I execute from command line the following:

c++ -std=c++17 -Wall -pedantic -I.  .\UserStructure.cpp .\BlockStructure.hpp .\BlockStructure.cpp .\ParsingBlocks.cpp .\main.cpp -o parsing.out

where the -I. flag is used to link in the current directory, the jsoncpp.cpp and json/json.h defined in the #includes at the beginning of the ParsingBlock.cpp file, as shown before.

The compilation gives me the following errors:

C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x2b6): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x2e0): multiple definition of `Json::Features::all()'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x2e0): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x2fe): multiple definition of `Json::Features::strictMode()'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x2fe): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x32c): multiple definition of `Json::Reader::containsNewLine(char const*, char const*)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x32c): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x36e): multiple definition of `Json::Reader::Reader()'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x36e): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x36e): multiple definition of `Json::Reader::Reader()'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x36e): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x44a): multiple definition of `Json::Reader::Reader(Json::Features const&)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x44a): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x44a): multiple definition of `Json::Reader::Reader(Json::Features const&)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x44a): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x52a): multiple definition of `Json::Reader::parse(std::__cxx11::basic_string<char,
std::char_traits<char>, std::allocator<char> > const&, Json::Value&, bool)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x52a): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x5de): multiple definition of `Json::Reader::parse(std::istream&, Json::Value&, bool)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x5de): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x698): multiple definition of `Json::Reader::parse(char const*, char const*, Json::Value&, bool)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x698): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x934): multiple definition of `Json::Reader::readValue()'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x934): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x1032): multiple definition of `Json::Reader::skipCommentTokens(Json::Reader::Token&)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x1032): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x1086): multiple definition of `Json::Reader::readToken(Json::Reader::Token&)'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x1086): first defined here
C:\Users\Utente\AppData\Local\Temp\cc8uGWcY.o:main.cpp:(.text+0x1246): multiple definition of `Json::Reader::skipSpaces()'
C:\Users\Utente\AppData\Local\Temp\ccDGeveZ.o:ParsingBlocks.cpp:(.text+0x1246): first defined here

So, it should be evident that the problem is in the linking phase, but I cannot solve it!

I have tried by reading both the documentation and other questions on stackoverflow.com, but I get nowhere.

Thanks in advance for the help, and I'm sorry if this question is a little bit huge.

EDIT: The stderr output does not stop there: there are at least 1000 lines of error, but each one of these regards the same multiple definition of ..., C:...: first defined here.

Body:
Include the header file in your main file instead of your source file:

#include "ParsingBlocks.hpp"

#include in C and C++ is not a module-based include like in many other languages, but just directly inserts the text of the file. That means that everything from ParsingBlocks.cpp was read twice by the compiler: Once when it compiled your main file and once when it compiled ParsingBlocks.cpp itself, hence the duplicates.

Also you don't need to specify the header files in your compiler command line.


来源: stackexchange

问:
java force an extending class
In Java, can I somehow force a class that extends an abstract class to implement its constructor with a Object as a parameter?

Something like

```<code>public abstract class Points {

    //add some abstract method to force constructor to have object.
}

public class ExtendPoints extends Points {

    /**
     * I want the abstract class to force this implementation to have
     *  a constructor with an object in it?
     * @param o
     */
    public ExtendPoints(Object o){

    }
}
</code>```

答: If you add a public Points(Object o) {} constructor to Points, you force any subclass constructors to call that super constructor.  However I don't think there's no way of ensuring that subclasses use that exact constructor signature.

ContentLicense: CC BY-SA 3.0

Title: java force an extending class

Body:
In Java, can I somehow force a class that extends an abstract class to implement its constructor with a Object as a parameter?

Something like

public abstract class Points {

    //add some abstract method to force constructor to have object.
}

public class ExtendPoints extends Points {

    /**
     * I want the abstract class to force this implementation to have
     *  a constructor with an object in it?
     * @param o
     */
    public ExtendPoints(Object o){

    }
}


答:
you just have included a cpp file. only header files should be included.
by including cpp files, the compiler is trying to define methods multiple times.
this is basically the reason why header files exist.</p>

ContentLicense: CC BY-SA 4.0

Title: Linking problem when using jsoncpp library


问:
Inserting values in table using procedure SQL SERVER
I am trying to insert values in Schedule table which looks like that :

```<code>ID          int         Unchecked
TeacherID   int         Unchecked
SubjectID   int         Unchecked
DayID       int         Unchecked
Time        varchar(5)  Unchecked
StatusID    int         Unchecked
</code>```

Also have Teacher ,Subject and Days table where I store information about teachers like name, surname... it looks like :

```<code>ID          int             Unchecked
FirstName   nvarchar(50)    Unchecked
LastName    nvarchar(50)    Unchecked
Mobile      int             Unchecked
IDNumber    varchar(11)     Unchecked
StatusID    int             Unchecked
</code>```

here is Subject table

```<code>ID          int             Unchecked
Name        nvarchar(50)    Unchecked
StatusID    int             Unchecked
</code>```

here is Days table

```<code>ID      int             Unchecked
Name    nvarchar(15)    Unchecked
</code>```

Want to make a procedure with parameters :

```<code>@FirstName NVARCHAR(50),
@LastName NVARCHAR(50),
@Subject NVARCHAR(50),
@Day NVARCHAR(15),
@Time VARCHAR(5),
@StatusID INT
</code>```

So the procedure shall take Teacher ID from Teacher's table, Subject table, Days table and insert them alongside other parameters.

I dont know if it is possible or not to do with procedure. Suggest other ways too please.

ID Columns are increment types.

答:
```<code>create index iSubj on Subjects (Name) include (ID);
create index iDays on Days (Name) include (ID)
create index iSched on Schedules (TeacherID, SubjectID, DayID, Time, StatusID) include (ID)

create proc InsertSchedule @FirstName varchar(50), @LastName varchar(50), @Subject varchar(50), @Day varchar(15), @Time varchar(5), @StatusID int as begin

insert Schedule (TeacherID, SubjectID, DayID, Time, StatusID)
select distinct t.ID, s.ID, d.ID, @Time, @StatusID
from Teachers t
    inner join Subjects s on s.Name = @Subject
    inner join Days d on d.Name = @Day
    left join Schedule sch (nolock) on sch.TeacherID = t.ID
        and sch.SubjectID = s.ID
        and sch.DayID = d.ID
        and sch.Time = @Time
        and sch.StatusID = @StatusID
where t.FirstName = @FirstName
    and t.LastName = @LastName
    and sch.ID is null

if @@rowcount > 1 print 'Warning: Duplicate Teachers, Subjects, or Days detected'

end
</code>```

I don't know what your data looks like, but I'd also suggest researching:

Date, Time, and DateTime types

DateName and DatePart functions

Renaming @FirstName and @LastName to reflect that it's the teacher's name

Dropping the Days table, unless you have a super-good reason for not just putting a Date  and/or DateTime column in Schedule.

Selecting a Teacher from a dropdown in your UI and passing the TeacherID in instead.  Ditto for Subjects; and Days, if you can't make Days a "proper" type.

Body:
I am trying to insert values in Schedule table which looks like that :

ID          int         Unchecked
TeacherID   int         Unchecked
SubjectID   int         Unchecked
DayID       int         Unchecked
Time        varchar(5)  Unchecked
StatusID    int         Unchecked

Also have Teacher ,Subject and Days table where I store information about teachers like name, surname... it looks like :

ID          int             Unchecked
FirstName   nvarchar(50)    Unchecked
LastName    nvarchar(50)    Unchecked
Mobile      int             Unchecked
IDNumber    varchar(11)     Unchecked
StatusID    int             Unchecked

here is Subject table

ID          int             Unchecked
Name        nvarchar(50)    Unchecked
StatusID    int             Unchecked

here is Days table

ID      int             Unchecked
Name    nvarchar(15)    Unchecked

Want to make a procedure with parameters :

@FirstName NVARCHAR(50),
@LastName NVARCHAR(50),
@Subject NVARCHAR(50),
@Day NVARCHAR(15),
@Time VARCHAR(5),
@StatusID INT

So the procedure shall take Teacher ID from Teacher's table, Subject table, Days table and insert them alongside other parameters.

I dont know if it is possible or not to do with procedure. Suggest other ways too please.

ID Columns are increment types.

Body:
create index iSubj on Subjects (Name) include (ID);
create index iDays on Days (Name) include (ID)
create index iSched on Schedules (TeacherID, SubjectID, DayID, Time, StatusID) include (ID)

create proc InsertSchedule @FirstName varchar(50), @LastName varchar(50), @Subject varchar(50), @Day varchar(15), @Time varchar(5), @StatusID int as begin

insert Schedule (TeacherID, SubjectID, DayID, Time, StatusID)
select distinct t.ID, s.ID, d.ID, @Time, @StatusID
from Teachers t
    inner join Subjects s on s.Name = @Subject
    inner join Days d on d.Name = @Day
    left join Schedule sch (nolock) on sch.TeacherID = t.ID
        and sch.SubjectID = s.ID
        and sch.DayID = d.ID
        and sch.Time = @Time
        and sch.StatusID = @StatusID
where t.FirstName = @FirstName
    and t.LastName = @LastName
    and sch.ID is null

if @@rowcount > 1 print 'Warning: Duplicate Teachers, Subjects, or Days detected'

end

I don't know what your data looks like, but I'd also suggest researching:

Date, Time, and DateTime types

DateName and DatePart functions

Renaming @FirstName and @LastName to reflect that it's the teacher's name

Dropping the Days table, unless you have a super-good reason for not just putting a Date  and/or DateTime column in Schedule.

Selecting a Teacher from a dropdown in your UI and passing the TeacherID in instead.  Ditto for Subjects; and Days, if you can't make Days a "proper" type.


问:
label the X axis in a System.Windows.Forms.DataVisualization.Charting chart with weekdays
The x dimension of my graph is composed of double values which contain the number of minutes. They cover a range of 1 week. While I have no problem with correctly displaying those values on the graph, I would like the X-axis labels to be week-days (the hour:minute precision is not important on the labels, but is present on the graph, because monday at 15:00 is a point between monday and tuesday, but placed before the points monday at 16:00, for example). Any idea how I can achieve this?

PS: the mentioned values in minutes are obtained from: #(day of week)*24*60 + hours*60 + minutes, where #(day of week) = 0 for monday, 1 for tuesday, ...

答:
You can set the corresponding Axis IntervalType of the ChartArea to Days - assuming it is ok for you to have to transform minutes to days. You state the core idea here is to have a "time" based graph, no matter whether its minutes or days simply divide minutes by /(60[minutes]*24[hours])

Your desire for bigger time spans can be accomplished by calculating minutes related to a fixed start time/date.

```<code>var chartArea = new System.Windows.Forms.DataVisualization.Charting.ChartArea
            {
                Name = "ChartArea1",
                AxisX = new System.Windows.Forms.DataVisualization.Charting.Axis
                {
                    IntervalType = System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType.Days
                }
            };

            //...//
            chart.ChartAreas.Add(chartArea);
</code>```

Body:
You can set the corresponding Axis IntervalType of the ChartArea to Days - assuming it is ok for you to have to transform minutes to days. You state the core idea here is to have a "time" based graph, no matter whether its minutes or days simply divide minutes by /(60[minutes]*24[hours])

Your desire for bigger time spans can be accomplished by calculating minutes related to a fixed start time/date.

var chartArea = new System.Windows.Forms.DataVisualization.Charting.ChartArea
            {
                Name = "ChartArea1",
                AxisX = new System.Windows.Forms.DataVisualization.Charting.Axis
                {
                    IntervalType = System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType.Days
                }
            };

            //...//
            chart.ChartAreas.Add(chartArea);


问:
FirebaseInstanceId.Instance is returning null
I want to get fcm token in my xamarin.android project.
Nugets I am using

  <package id="Xamarin.Firebase.Common" version="71.1610.0" targetFramework="monoandroid90" />
  <package id="Xamarin.Firebase.Core" version="71.1601.0" targetFramework="monoandroid90" />
  <package id="Xamarin.Firebase.Iid" version="71.1710.0" targetFramework="monoandroid90" />
  <package id="Xamarin.Firebase.Iid.Interop" version="71.1601.0" targetFramework="monoandroid90" />
```

<p>Code For retrieving the token</p>

```FirebaseInstanceId instance = FirebaseInstanceId.Instance;
Android.Gms.Tasks.Task instanceId = instance.GetInstanceId();
instanceId.AddOnSuccessListener(this, this);
```

But FirebaseInstanceId.Instance is always null

答:
You lucky, because just recently I have came across the same issue. I assume you also use Xamarin.Firebase.Auth and all related packages to it. There is an issue with the newest version, for some reason Xamarin.Firebase.Auth and Xamarin.Firebase.Messaging don't like each other. Downgrade both version to 60.1142.1 (you will have to downgrade GoogleService.Base to the lower version, I would personally remove both packages first and re-add them using version 60.1142.1).
This fixed my issue with it, which weirdly on my Xamarin on Mac resulted in push notification not working, but on windows version the Instance was null.</p>

Body:
I want to get fcm token in my xamarin.android project.
Nugets I am using

  <package id="Xamarin.Firebase.Common" version="71.1610.0" targetFramework="monoandroid90" />
  <package id="Xamarin.Firebase.Core" version="71.1601.0" targetFramework="monoandroid90" />
  <package id="Xamarin.Firebase.Iid" version="71.1710.0" targetFramework="monoandroid90" />
  <package id="Xamarin.Firebase.Iid.Interop" version="71.1601.0" targetFramework="monoandroid90" />

Code For retrieving the token

FirebaseInstanceId instance = FirebaseInstanceId.Instance;
Android.Gms.Tasks.Task instanceId = instance.GetInstanceId();
instanceId.AddOnSuccessListener(this, this);

But FirebaseInstanceId.Instance is always null


答: As said by others before, the signatue of Constructors cvannot be enforced, but you could enforce a particular set of arguments by using the AbstractFactory pattern instead. Then you can define the create methods of your factory interface to have a particular signature.</p>

Title: java force an extending class


问:
Starting a web request when an nfc sticker is detected
Is there an app which calls a definable URL when a NFC sticker is detected? I want to put different stickers on my desk and when I place my phone on one of the stickers a specific URL should be call:

If StickerA is detectd call https://www.myserver.com/?val=a

If StickerB is detectd call https://www.myserver.com/?val=b

If StickerC is detectd call https://www.myserver.com/?val=c

etc.

Is this possible with android without activating the phone and is there a an existing app for that task?

答:
Detecting a sticker, and taking an action are two different things.  When you detect a sticker, I think you can get the ID of the sticker, then, based on the ID, you would create an Action View Intent passing the URL and that would cause an external browser window to open with the URL you passed.</p>

```<code>//pass any url to this function to open a new browser session
protected void handleExternalDeviceActivity(String url) {
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    startActivity(intent);
}
</code>```

Body:
Detecting a sticker, and taking an action are two different things.  When you detect a sticker, I think you can get the ID of the sticker, then, based on the ID, you would create an Action View Intent passing the URL and that would cause an external browser window to open with the URL you passed.

//pass any url to this function to open a new browser session
protected void handleExternalDeviceActivity(String url) {
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    startActivity(intent);
}


问:
docker-compose healthcheck retry frequency != interval
I recently set up healthchecks in my docker-compose config.

It is doing great and I like it. Here's a typical example:

```<code>services:
  app:
    healthcheck:
      test: curl -sS http://127.0.0.1:4000 || exit 1
      interval: 5s
      timeout: 3s
      retries: 3
      start_period: 30s
</code>```

My container is quite slow to boot, hence I set up a 30 seconds start_period.

But it doesn't really fit my expectation: I don't need check every 5 seconds, but I need to know when the container is ready for the first time as soon as possible for my orchestration, and since my start_period is approximative, if it is not ready yet at first check, I have to wait for interval before retry.

What I'd like to have is:

While container is not healthy, retry every 5 seconds

Once it is healthy, check every 1 minute

Ain't there a way to achieve this out-of-the-box with docker-compose?

I could write a custom script to achieve this, but I'd rather have a native solution if it is possible.

答:
I wrote a script that does this, though I'd rather find a native solution:

```<code>#!/bin/sh

HEALTHCHECK_FILE="/root/.healthchecked"

COMMAND=${*?"Usage: healthcheck_retry <COMMAND>"}

if [ -r "$HEALTHCHECK_FILE" ]; then
  LAST_HEALTHCHECK=$(date -r "$HEALTHCHECK_FILE" +%s)
  # FIVE_MINUTES_AGO=$(date -d 'now - 5 minutes' +%s)
  FIVE_MINUTES_AGO=$(echo "$(( $(date +%s)-5*60 ))")
  echo "Healthcheck file present";
  # if (( $LAST_HEALTHCHECK > $FIVE_MINUTES_AGO )); then
  if [ $LAST_HEALTHCHECK -gt $FIVE_MINUTES_AGO ]; then
    echo "Healthcheck too recent";
    exit 0;
  fi
fi

if $COMMAND ; then
  echo "\"$COMMAND\" succeed: updating file";
  touch $HEALTHCHECK_FILE;
  exit 0;
else
  echo "\"$COMMAND\" failed: exiting";
  exit 1;
fi
</code>```

Which I use: test: /healthcheck_retry.sh curl -fsS localhost:4000/healthcheck

The pain is that I need to make sure the script is available in every container, so I have to create an extra volume for this:

```<code>    image: postgres:11.6-alpine
    volumes:
      - ./scripts/utils/healthcheck_retry.sh:/healthcheck_retry.sh
</code>```

Body:
I recently set up healthchecks in my docker-compose config.

It is doing great and I like it. Here's a typical example:

services:
  app:
    healthcheck:
      test: curl -sS http://127.0.0.1:4000 || exit 1
      interval: 5s
      timeout: 3s
      retries: 3
      start_period: 30s

My container is quite slow to boot, hence I set up a 30 seconds start_period.

But it doesn't really fit my expectation: I don't need check every 5 seconds, but I need to know when the container is ready for the first time as soon as possible for my orchestration, and since my start_period is approximative, if it is not ready yet at first check, I have to wait for interval before retry.

What I'd like to have is:

While container is not healthy, retry every 5 seconds

Once it is healthy, check every 1 minute

Ain't there a way to achieve this out-of-the-box with docker-compose?

I could write a custom script to achieve this, but I'd rather have a native solution if it is possible.

Body:
I wrote a script that does this, though I'd rather find a native solution:

#!/bin/sh

HEALTHCHECK_FILE="/root/.healthchecked"

COMMAND=${*?"Usage: healthcheck_retry <COMMAND>"}

if [ -r "$HEALTHCHECK_FILE" ]; then
  LAST_HEALTHCHECK=$(date -r "$HEALTHCHECK_FILE" +%s)
  # FIVE_MINUTES_AGO=$(date -d 'now - 5 minutes' +%s)
  FIVE_MINUTES_AGO=$(echo "$(( $(date +%s)-5*60 ))")
  echo "Healthcheck file present";
  # if (( $LAST_HEALTHCHECK > $FIVE_MINUTES_AGO )); then
  if [ $LAST_HEALTHCHECK -gt $FIVE_MINUTES_AGO ]; then
    echo "Healthcheck too recent";
    exit 0;
  fi
fi

if $COMMAND ; then
  echo "\"$COMMAND\" succeed: updating file";
  touch $HEALTHCHECK_FILE;
  exit 0;
else
  echo "\"$COMMAND\" failed: exiting";
  exit 1;
fi

Which I use: test: /healthcheck_retry.sh curl -fsS localhost:4000/healthcheck

The pain is that I need to make sure the script is available in every container, so I have to create an extra volume for this:

    image: postgres:11.6-alpine
    volumes:
      - ./scripts/utils/healthcheck_retry.sh:/healthcheck_retry.sh


问:
White flash/flicker on Safari when setting background-image src with intersection observer?
I've researched quite a bit and can't solve this issue. Only appears on Safari (Mac & iOS). Works on Chrome, FF, Edge, etc.

UPDATE: The flickering occurs in FireFox as well...

I'm using the IntersectionObserver API along with the required polyfil to lazy load images. When they come into view, the intersection observer replaces the low resolution image set as the background-image and replaces it with the high resolution image stored in a data attribute on the div.

The behaviour is 'working' as the blurry initial image is set, then replaced by the high quality one but there is a white flicker or flash happening inbetween... (The background of the page is white so maybe that's what is showing through?)

After some reading: (How to prevent a background image flickering on change) I did fix the jumping issue by preloading the images using the new Image() consructor.

```<code>const setBackgroundImage = (e) => {
  let image = new Image();
  image.onload = () => e.style.backgroundImage = `url(${e.dataset.bgImage})`;
  image.src = e.dataset.bgImage;
};
</code>```

An example HTML element (PHP):

```<code><div class="my-div"
     style="background-image: url('<?= $imagePreload ?? $image; ?>');"
     data-bg-image="<?= $image; ?>"
</div>
</code>```

I've tried playing around with backface-visibility: hidden but no luck there. I'm not animating anything, just replacing the src on the div with the preloaded, full size image.

答: You can solve this by loading the higher resolution image before it scrolls into view. Set the rootMargin option to something like 200px when creating your IntersectionObserver to have the browser start loading the image 200px before it enters the viewport.

Body:
I've researched quite a bit and can't solve this issue. Only appears on Safari (Mac & iOS). Works on Chrome, FF, Edge, etc.

UPDATE: The flickering occurs in FireFox as well...

I'm using the IntersectionObserver API along with the required polyfil to lazy load images. When they come into view, the intersection observer replaces the low resolution image set as the background-image and replaces it with the high resolution image stored in a data attribute on the div.

The behaviour is 'working' as the blurry initial image is set, then replaced by the high quality one but there is a white flicker or flash happening inbetween... (The background of the page is white so maybe that's what is showing through?)

After some reading: (How to prevent a background image flickering on change) I did fix the jumping issue by preloading the images using the new Image() consructor.

const setBackgroundImage = (e) => {
  let image = new Image();
  image.onload = () => e.style.backgroundImage = `url(${e.dataset.bgImage})`;
  image.src = e.dataset.bgImage;
};

An example HTML element (PHP):

<div class="my-div"
     style="background-image: url('<?= $imagePreload ?? $image; ?>');"
     data-bg-image="<?= $image; ?>"

I've tried playing around with backface-visibility: hidden but no luck there. I'm not animating anything, just replacing the src on the div with the preloaded, full size image.


问:
How to make a local string variable in Lisp?
I am trying to make a local string variable and build the string with variables.

```<code>(setq string-label (make-array 0 :element-type `character
                                 :fill-pointer 0
                                 :adjustable t))
(loop while (and (char/= char #\Space)
                 (char/= char #\()
                 (char/= char #\Newline))
      do
         (vector-push-extend char string-label)
         (setq char (read-char fstream nil)))
</code>```

I am getting an error:

```<code>*** - SETQ: variable STRING_LABEL has no value
</code>```

答:
The primary constructs for defining local variables are let and let*. Other operators derived from let also bind local variables, such as with-open-file and destructuring-bind. Of course lambda and function definition forms derived from it like defun have parameters, and those are local variables. (Historically, lambda existed before let).

In the loop construct, local variables may be defined using the with clause, as in:

```<code>;; Like a hidden (let ((x 42) ...) in the code generated by loop:

(loop with x = 42 ...)
</code>```

This allows many instances of loop to avoid being surrounded by an extra let, and thus appearing more "tidy".

Local variables may also be automatically stepped across the iterations of a loop, which in many cases can avoid the incorporation of clunky setq assignment forms, if the logic is worked right:

```<code>;; x is initially 1, then 2, 3, ...

(loop with x = 1 then (+ 1 x) ...)
</code>```

Global variables in Common Lisp are defined using defvar and defparameter, not by simply assigning with setf or setq.

The effect of simply issuing a setf or setq on a variable that has previously not been defined is subject to an unfortunate "gray area" of ANSI Lisp, and behaves differently on different implementations due to different interpretations of that gray area.

In some implementations, setq on an undefined variable produces a diagnostic. On others, it creates a special variable, similarly to defparameter, and on others still, it creates something resembling a "global lexical" variable: the symbol receives a binding, but isn't marked as a special variable, remaining available for lexical binding.

Body:
I am trying to make a local string variable and build the string with variables.

(setq string-label (make-array 0 :element-type `character
                                 :fill-pointer 0
                                 :adjustable t))
(loop while (and (char/= char #\Space)
                 (char/= char #\()
                 (char/= char #\Newline))
      do
         (vector-push-extend char string-label)
         (setq char (read-char fstream nil)))

I am getting an error:

*** - SETQ: variable STRING_LABEL has no value

Body:
The primary constructs for defining local variables are let and let*. Other operators derived from let also bind local variables, such as with-open-file and destructuring-bind. Of course lambda and function definition forms derived from it like defun have parameters, and those are local variables. (Historically, lambda existed before let).

In the loop construct, local variables may be defined using the with clause, as in:

;; Like a hidden (let ((x 42) ...) in the code generated by loop:

(loop with x = 42 ...)

This allows many instances of loop to avoid being surrounded by an extra let, and thus appearing more "tidy".

Local variables may also be automatically stepped across the iterations of a loop, which in many cases can avoid the incorporation of clunky setq assignment forms, if the logic is worked right:

;; x is initially 1, then 2, 3, ...

(loop with x = 1 then (+ 1 x) ...)

Global variables in Common Lisp are defined using defvar and defparameter, not by simply assigning with setf or setq.

The effect of simply issuing a setf or setq on a variable that has previously not been defined is subject to an unfortunate "gray area" of ANSI Lisp, and behaves differently on different implementations due to different interpretations of that gray area.

In some implementations, setq on an undefined variable produces a diagnostic. On others, it creates a special variable, similarly to defparameter, and on others still, it creates something resembling a "global lexical" variable: the symbol receives a binding, but isn't marked as a special variable, remaining available for lexical binding.


问:
grep for exact word in a file containing "."
I have a file named "TestGrep" that contains content as shown below

```<code>#!/bin/bash

/ParentFolder/a @email1.com
/ParentFolder/b @email2.com
/ParentFolder/.a @email1.com
/ParentFolder/.b @email2.com
/ParentFolder/ @email3.com

</code>```

I am using the below grep command

```<code>grep -Fw "/ParentFolder/" TestGrep
</code>```

The output is

```<code>/ParentFolder/.a @email1.com
/ParentFolder/.b @email2.com
/ParentFolder/ @email3.com
</code>```

It is somehow ignoring the dots in the TestGrep file.
I want the output to be shown as below

```<code>/ParentFolder/ @email3.com
</code>```

How can I query using grep command that would just check if the exact string match is done and return output as expected.

答:
Could you please try following. Using -E option of grep here.

```<code>grep -E '/ParentFolder/\s+' Input_file
</code>```

From man grep about -E option of grep:

-E, --extended-regexp

Interpret PATTERN as an extended regular expression

\s+ means looks for spaces one or more occurrences.

Body:
I have a file named "TestGrep" that contains content as shown below

#!/bin/bash

/ParentFolder/a @email1.com
/ParentFolder/b @email2.com
/ParentFolder/.a @email1.com
/ParentFolder/.b @email2.com
/ParentFolder/ @email3.com

I am using the below grep command

grep -Fw "/ParentFolder/" TestGrep

The output is

/ParentFolder/.a @email1.com
/ParentFolder/.b @email2.com
/ParentFolder/ @email3.com

It is somehow ignoring the dots in the TestGrep file.
I want the output to be shown as below

/ParentFolder/ @email3.com

How can I query using grep command that would just check if the exact string match is done and return output as expected.

Body:
Could you please try following. Using -E option of grep here.

grep -E '/ParentFolder/\s+' Input_file

From man grep about -E option of grep:

-E, --extended-regexp

Interpret PATTERN as an extended regular expression

\s+ means looks for spaces one or more occurrences.


问:
Swagger codegen generate too long string literals
I need to generate classes based on provided swagger file. Unfortunately I have no influence on content of this file.

My config in gladle looks like:

```<code>task generateApi {
doLast {
    def config = new CodegenConfigurator()
    config.setInputSpec("file:///$projectDir/$swaggerSourceFile")
    config.setOutputDir("$projectDir/$swaggerTargetFolder")
    config.setLang('spring')
    config.setAdditionalProperties([
            'interfaceOnly'       : true,
            'apiPackage'          : 'somepackage',
            'modelPackage'        : 'somepackage.domain',
            'sourceFolder'        : '',
            'java8'               : true,
            'dateLibrary'         : 'java8',
            'skipDefaultInterface': true
    ])
    new DefaultGenerator().opts(config.toClientOptInput()).generate()
}
}
</code>```

Exception which I`m getting is : "error: constant string too long"

Problem is that even I set 'skipDefaultInterface', swagger will generates it. In default interface it generates default response entity body which is json file which is 70k char long string.

Please help!

答:
Looks like this is a known issue with the spring generator in Swagger Codegen:

https://github.com/swagger-api/swagger-codegen/issues/9055

A PR for this issue is available but not yet merged (as of February 2020):

https://github.com/swagger-api/swagger-codegen/pull/8691

Try using openapi-generator v. 4.2.2 or later which is supposed to include a similar fix.

Body:
I need to generate classes based on provided swagger file. Unfortunately I have no influence on content of this file.

My config in gladle looks like:

task generateApi {
doLast {
    def config = new CodegenConfigurator()
    config.setInputSpec("file:///$projectDir/$swaggerSourceFile")
    config.setOutputDir("$projectDir/$swaggerTargetFolder")
    config.setLang('spring')
    config.setAdditionalProperties([
            'interfaceOnly'       : true,
            'apiPackage'          : 'somepackage',
            'modelPackage'        : 'somepackage.domain',
            'sourceFolder'        : '',
            'java8'               : true,
            'dateLibrary'         : 'java8',
            'skipDefaultInterface': true
    ])
    new DefaultGenerator().opts(config.toClientOptInput()).generate()
}
}

Exception which I`m getting is : "error: constant string too long"

Problem is that even I set 'skipDefaultInterface', swagger will generates it. In default interface it generates default response entity body which is json file which is 70k char long string.

Please help!


问:
InvalidCastExeption in LINQ to XML
I am using LINQ to XML to take some data from resources , and here I have a function, where I take some values and then I create a new object (Type Translation), so when I call the function I get a Translation object. By now I have this code:

```<code>     Public Shared Function RetrieveTranslation(ByVal file As String) As List(Of clsTranslation)
    Dim valuetrans = From vl In XElement.Load(file).Elements("data") Select (New clsTranslation With {.Filename = file, .Value = vl.Element("value").Value, .TranslationId = vl.Attribute("name").Value})
    Return valuetrans
End Function
</code>```

The problem is that with this code I got this error:
Unable to cast object of type 'WhereSelectEnumerableIterator2[System.Xml.Linq.XElement,clsTranslation]' to type 'System.Collections.Generic.List1[clsTranslation]'.

Do you know the way to cast it?
Thanks in advance,

Alfonso.

答:
If you were compiling with Option Strict on, you'd have found this out at compile time.

You don't cast it - you call ToList() on the result, to create a List<clsTranslation> from the IEnumerable<clsTranslation>.

(I'd also advise you to ditch the cls prefix; it goes against the .NET naming conventions.)

That would leave:

```<code>Public Shared Function RetrieveTranslation(ByVal file As String) _
        As List(Of Translation)
    Return (From vl In XElement.Load(file).Elements("data") _
            Select (New Translation With { _
                               .Filename = file, _
                               .Value = vl.Element("value").Value, _
                               .TranslationId = vl.Attribute("name").Value}) _
           ).ToList()
End Function
</code>```

Title: InvalidCastExeption in LINQ to XML

Body:
I am using LINQ to XML to take some data from resources , and here I have a function, where I take some values and then I create a new object (Type Translation), so when I call the function I get a Translation object. By now I have this code:

     Public Shared Function RetrieveTranslation(ByVal file As String) As List(Of clsTranslation)
    Dim valuetrans = From vl In XElement.Load(file).Elements("data") Select (New clsTranslation With {.Filename = file, .Value = vl.Element("value").Value, .TranslationId = vl.Attribute("name").Value})
    Return valuetrans
End Function

The problem is that with this code I got this error:
Unable to cast object of type 'WhereSelectEnumerableIterator2[System.Xml.Linq.XElement,clsTranslation]' to type 'System.Collections.Generic.List1[clsTranslation]'.

Do you know the way to cast it?
Thanks in advance,

Alfonso.

Body:
If you were compiling with Option Strict on, you'd have found this out at compile time.

You don't cast it - you call ToList() on the result, to create a List<clsTranslation> from the IEnumerable<clsTranslation>.

(I'd also advise you to ditch the cls prefix; it goes against the .NET naming conventions.)

That would leave:

Public Shared Function RetrieveTranslation(ByVal file As String) _
        As List(Of Translation)
    Return (From vl In XElement.Load(file).Elements("data") _
            Select (New Translation With { _
                               .Filename = file, _
                               .Value = vl.Element("value").Value, _
                               .TranslationId = vl.Attribute("name").Value}) _
           ).ToList()
End Function


问:
issues with the in statement using a subquery
Issues with this statement

```<code>    select * from table
        where ID in (case when table1.changes = 40 THEN
        select top 1 STUFF((SELECT  ',' + CAST(ID as varchar) FROM Tabl1
                WHERE UserID = 121   FOR XML PATH('')), 1, 1, '')
                    FROM Tabl1 where UserID = 121
else
id
end
        )
</code>```

Using above, getting an error

Msg 245, Level 16, State 1, Line 3

Conversion failed when converting the nvarchar value '167,196,107,108,169,111,115,16,162' to data type int.

答:
In takes either a subquery or a list of expressions. You were trying to build a list of expression on-the-fly and that would require using in with dynamic SQL. The correct syntax for using a subquery is:

```<code>select * from table
    where ID in ( select ID FROM Tabl1 WHERE UserID = 121 )
</code>```

Body:
Issues with this statement

    select * from table
        where ID in (case when table1.changes = 40 THEN
        select top 1 STUFF((SELECT  ',' + CAST(ID as varchar) FROM Tabl1
                WHERE UserID = 121   FOR XML PATH('')), 1, 1, '')
                    FROM Tabl1 where UserID = 121
else
id
end
        )

Using above, getting an error

Msg 245, Level 16, State 1, Line 3

Conversion failed when converting the nvarchar value '167,196,107,108,169,111,115,16,162' to data type int.

Body:
In takes either a subquery or a list of expressions. You were trying to build a list of expression on-the-fly and that would require using in with dynamic SQL. The correct syntax for using a subquery is:

select * from table
    where ID in ( select ID FROM Tabl1 WHERE UserID = 121 )


问:
Is it possible to do doctests in repl.it?
I am using the website repl.it to code with python and I was wondering how I would use my doctests when using repl.it. Or any other alternative besides the classic print statement checks.</p>

答:
It can be done in the following way. If you execute the following code on repl.it it will give you the output shown below.

```<code>'''
Credit to the autho-> @pcorkh1

using doctests
for automatic marking
'''

import doctest

def testing():
    doctest.run_docstring_examples(square,globals(),name="square")

def square(n):
    '''
    returns a square of n
    >>> square(3)
    9
    >>> square(1)
    1
    >>> square(6)
    36
    '''
    return n+n

testing()
name = 'Pete'
age = 35
num = 1

print(f'name is: {name} Age is: {age: ^10} num is: {num}')
</code>```

Output:

```<code>**********************************************************************
File "main.py", line 14, in square
Failed example:
    square(3)
Expected:
    9
Got:
    6
**********************************************************************
File "main.py", line 16, in square
Failed example:
    square(1)
Expected:
    1
Got:
    2
**********************************************************************
File "main.py", line 18, in square
Failed example:
    square(6)
Expected:
    36
Got:
    12
name is: Pete Age is:     35     num is: 1
</code>```

The code is very trivial and once you understand it you can incorporate into your program. You may need to change the structure of your code to achieve this.

Body:
It can be done in the following way. If you execute the following code on repl.it it will give you the output shown below.

'''
Credit to the autho-> @pcorkh1

using doctests
for automatic marking
'''

import doctest

def testing():
    doctest.run_docstring_examples(square,globals(),name="square")

def square(n):
    '''
    returns a square of n
    >>> square(3)
    9
    >>> square(1)
    1
    >>> square(6)
    36
    '''
    return n+n

testing()
name = 'Pete'
age = 35
num = 1

print(f'name is: {name} Age is: {age: ^10} num is: {num}')

Output:

**********************************************************************
File "main.py", line 14, in square
Failed example:
    square(3)
Expected:
    9
Got:
    6
**********************************************************************
File "main.py", line 16, in square
Failed example:
    square(1)
Expected:
    1
Got:
    2
**********************************************************************
File "main.py", line 18, in square
Failed example:
    square(6)
Expected:
    36
Got:
    12
name is: Pete Age is:     35     num is: 1

The code is very trivial and once you understand it you can incorporate into your program. You may need to change the structure of your code to achieve this.


问:
Efficiently comparing two lists
so, i have this block of code on my app that scans a directory for files, makes a list with them and compares that list with a list of files from a database (if the path to that directory exists on the db) and adds the difference between them to one of two other lists.Here it is :

```<code> if (id > 0)
                {

                    var dbDrawingList = mdl_drawing.GetDrawingsByBaseId(id);
                    var counter = 0;

                    if (dbDrawingList.Count() < serverDrawingList.Count())
                    {
                        counter = serverDrawingList.Count();
                    }
                    else
                    {
                        counter = dbDrawingList.Count();
                    }

                    for (int i = 0; i <= counter; i++)
                    {

                        if (i < serverDrawingList.Count())
                        {
                            if (dbDrawingList.Select(f => f.partNumber).Contains(serverDrawingList[i].partNumber) == false)
                            {
                                onServerAndNotDb.Add(serverDrawingList[i]);
                            }
                        }

                        if (i < dbDrawingList.Count())
                        {
                            if (serverDrawingList.Select(f => f.partNumber).Contains(dbDrawingList[i].partNumber) == false)
                            {
                                onDbAndNotServer.Add(dbDrawingList[i]);
                            }
                        }
                    }
                    serverDrawingList = null;
                    dbDrawingList = null;
                }
</code>```

Does anyone have a better way of doing this?(there can be more than one file with the same name, so the Except method doesn't work)

答:
I have one method that does exactly that, this is the way I implemented it and it's working so far: </p>

```<code>private void deleteRegistersFromFilesThatWasRemoved(string path)
{
    // add local files to list
    List<string> allFiles = new List<string>();
    string[] dirs = Directory.GetDirectories(path, "*",
    SearchOption.TopDirectoryOnly);
    foreach (var dir in dirs)
    {
        string[] files = Directory.GetFiles(dir, "*", SearchOption.TopDirectoryOnly);
        foreach (var file in files)
        {
                if(file != path)
                {
                    allFiles.Add(file);
                }
            }
        }

        // list for file records in the database
        List<string> record = new List<string>();
        string queryfiles = //your query
        SqlCommand cmd = new SqlCommand(queryfiles, connection);
        cmd.Connection.Open();
        cmd.ExecuteNonQuery();
        SqlDataReader read = cmd.ExecuteReader();
        while (read.Read())
        {
         // I have path and file name separated that's why here's a string sum
            string r = read[2].ToString() + read[1].ToString();
            record.Add(r);

        }
        cmd.Connection.Close();

        for (int i = 0; i < record.Count; i++)
        {
            if (!allFiles.Contains(record[i]))
            {
                // do something if the record on the database is not in the local
                //files list
            }
        }

    }
}
</code>```

Title: Efficiently comparing two lists

Body:
so, i have this block of code on my app that scans a directory for files, makes a list with them and compares that list with a list of files from a database (if the path to that directory exists on the db) and adds the difference between them to one of two other lists.Here it is :

 if (id > 0)
                {

                    var dbDrawingList = mdl_drawing.GetDrawingsByBaseId(id);
                    var counter = 0;

                    if (dbDrawingList.Count() < serverDrawingList.Count())
                    {
                        counter = serverDrawingList.Count();
                    }
                    else
                    {
                        counter = dbDrawingList.Count();
                    }

                    for (int i = 0; i <= counter; i++)
                    {

                        if (i < serverDrawingList.Count())
                        {
                            if (dbDrawingList.Select(f => f.partNumber).Contains(serverDrawingList[i].partNumber) == false)
                            {
                                onServerAndNotDb.Add(serverDrawingList[i]);
                            }
                        }

                        if (i < dbDrawingList.Count())
                        {
                            if (serverDrawingList.Select(f => f.partNumber).Contains(dbDrawingList[i].partNumber) == false)
                            {
                                onDbAndNotServer.Add(dbDrawingList[i]);
                            }
                        }
                    }
                    serverDrawingList = null;
                    dbDrawingList = null;
                }

Does anyone have a better way of doing this?(there can be more than one file with the same name, so the Except method doesn't work)

Body:
I have one method that does exactly that, this is the way I implemented it and it's working so far:

private void deleteRegistersFromFilesThatWasRemoved(string path)
{
    // add local files to list
    List<string> allFiles = new List<string>();
    string[] dirs = Directory.GetDirectories(path, "*",
    SearchOption.TopDirectoryOnly);
    foreach (var dir in dirs)
    {
        string[] files = Directory.GetFiles(dir, "*", SearchOption.TopDirectoryOnly);
        foreach (var file in files)
        {
                if(file != path)
                {
                    allFiles.Add(file);
                }
            }
        }

        // list for file records in the database
        List<string> record = new List<string>();
        string queryfiles = //your query
        SqlCommand cmd = new SqlCommand(queryfiles, connection);
        cmd.Connection.Open();
        cmd.ExecuteNonQuery();
        SqlDataReader read = cmd.ExecuteReader();
        while (read.Read())
        {
         // I have path and file name separated that's why here's a string sum
            string r = read[2].ToString() + read[1].ToString();
            record.Add(r);

        }
        cmd.Connection.Close();

        for (int i = 0; i < record.Count; i++)
        {
            if (!allFiles.Contains(record[i]))
            {
                // do something if the record on the database is not in the local
                //files list
            }
        }

    }
}


问:
Spring: Using @Qualifier & @Profile
I have a component class (let's class in MyService) which is marked by @Qualifier(US).

As this component needed some values present in an application.yml file, I also marked the class with @Profile({"default", "qual"}) to get the correct values for some inner properties of the class.

Problem, when I execute cucumber tests for this specific qualifier (US), the program throws the following error An unexpected internal server error occurred: No bean named 'US' available: No matching MyService bean found for qualifier 'US' - neither qualifier match nor bean name match!

So, what I understand with this, it's the annotations @Qualifier & @Profile don't work together. Is that right? Or do I miss something to use both of them in the same class?

答:
@Qualifer

This annotation may be used on a field or parameter as a qualifier for
  candidate beans when autowiring.

@Profile

Indicates that a component is eligible for registration when one or
  more specified profiles are active.

The class with following set of annotations

```<code>@Service
@Qualifier("US")
@Profile({"default", "qual"})
public class MyService {
...}
</code>```

will only register the MyService bean when "default" or "qual" profiles are active and then on the bean can be autowired with the qualifier "US"

```<code>@Autowired
@Qualifer("US")
private MyService myService;
</code>```

@Value can be used to inject the properties

```<code>@Value(${some.name})
private String name;
</code>```

Title: Spring: Using @Qualifier & @Profile

Body:
@Qualifer

This annotation may be used on a field or parameter as a qualifier for
  candidate beans when autowiring.

@Profile

Indicates that a component is eligible for registration when one or
  more specified profiles are active.

The class with following set of annotations

@Service
@Qualifier("US")
@Profile({"default", "qual"})
public class MyService {
...}

will only register the MyService bean when "default" or "qual" profiles are active and then on the bean can be autowired with the qualifier "US"

@Autowired
@Qualifer("US")
private MyService myService;

@Value can be used to inject the properties

@Value(${some.name})
private String name;


答:
You can do with one query using union:

```<code>SELECT user_id, amount_1, amount_2, amount_3
    FROM table
    WHERE user_id = YOUR_USER_ID
UNION
SELECT -1, SUM(amount_1) AS amount_1, SUM(amount_2) AS amount_2, SUM(amount_3) AS amount_3
    FROM table
    WHERE user_id != YOUR_USER_ID
</code>```

Title: SQL query to return combined data of all rows that don't belong to current user

Body:
Imagine this is my table:

----------------------------------------------------
| id | user_id    | amount_1 | amount_2 | amount_3 |
----------------------------------------------------
| 1  | 1          | 2        | 3        | 4        |
----------------------------------------------------
| 2  | 2          | 2        | 1        | 1        |
----------------------------------------------------
| 3  | 2          | 1        | 2        | 2        |
----------------------------------------------------
| 4  | 3          | 2        | 1        | 4        |
----------------------------------------------------

I need a query that gives me one result set for every entry that belongs to my current user, and then returns everything else as a single combined row with the amounts summed.

So in this case if I am user 1, I should get the following rows back:

---------------------------------------
| id | amount_1 | amount_2 | amount_3 |
---------------------------------------
| 1  | 2        | 3        | 4        |   my own amounts
---------------------------------------
| 2  | 5        | 4        | 7        |   everyone else's amounts
---------------------------------------

Any tips?

I've considered it might be a better idea to just filter the data in the code (php). Please help i'm starting to hate myself

Body:
You can do with one query using union:

SELECT user_id, amount_1, amount_2, amount_3
    FROM table
    WHERE user_id = YOUR_USER_ID
UNION
SELECT -1, SUM(amount_1) AS amount_1, SUM(amount_2) AS amount_2, SUM(amount_3) AS amount_3
    FROM table
    WHERE user_id != YOUR_USER_ID


问:
WSL - GEDIT Unable to init server: Could not connect: Connection refused
I'm using Ubuntu 18.04 as Windows Subsystem for Linux on my Windows 10 machine.

I've installed gedit without any errors or warnings.

But whenever I try to use the command gedit something (here something is a filename)

I get this error:

```<code>Unable to init server: Could not connect: Connection refused

(gedit:48): Gtk-WARNING **: 21:03:26.729: cannot open display:
</code>```

答:
You need an X server to run graphical applications like gedit.
I use VcXsrv or Xming on my Windows desktops, both are very small and easy to install,
but there exist other servers like Cygwin/X.

Short instructions for VcXsrv/Xming:

download and install the Windows package

start XLaunch or Xming

export the DISPLAY variable in your WSL terminal and start gedit

```<code>export DISPLAY=0:0
gedit
</code>```

I have the problem that some checkboxes in gedit's preferences are not working (dconf error, I don't care), but other than that the editor is usable.

Related:

What's the easiest way to run GUI apps on Windows Subsystem for Linux as of 2018? (askubuntu.com)

Body:
I'm using Ubuntu 18.04 as Windows Subsystem for Linux on my Windows 10 machine.

I've installed gedit without any errors or warnings.

But whenever I try to use the command gedit something (here something is a filename)

I get this error:

Unable to init server: Could not connect: Connection refused

(gedit:48): Gtk-WARNING **: 21:03:26.729: cannot open display:

Body:
You need an X server to run graphical applications like gedit.
I use VcXsrv or Xming on my Windows desktops, both are very small and easy to install,
but there exist other servers like Cygwin/X.

Short instructions for VcXsrv/Xming:

download and install the Windows package

start XLaunch or Xming

export the DISPLAY variable in your WSL terminal and start gedit

export DISPLAY=0:0
gedit

I have the problem that some checkboxes in gedit's preferences are not working (dconf error, I don't care), but other than that the editor is usable.

Related:

What's the easiest way to run GUI apps on Windows Subsystem for Linux as of 2018? (askubuntu.com)


问:
Navigation Bar Heading Text Positioning
I have a navigation bar that will expand when the mouse is over it. I wish to display heading text once it is expanded (currently shows icons), I have used display: none on the heading tag, which then toggles to display: inline-block when the :hover event is active on the navbar. However, upon expansion of the navbar the text renders in on two lines before positioning itself into one which I want. I want to get rid of this and have the text render in as one line only while the navbar expands. My code:

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Navigation Bar</title>
    <link href="css/styles.css" rel="stylesheet" type="text/css" />
    <script
      src="https://kit.fontawesome.com/6cc49d804e.js"
      crossorigin="anonymous"
    ></script>
  </head>

  <body>
    <div id="sidenav">
      <div id="sidenav-brand">
        <div id="sidenav-heading">
          <h2>Expanded Test</h2>
        </div>
        <div id="sidenav-expand">
          <i id="expand-icon" class="fas fa-angle-double-right fa-2x"></i>
        </div>
      </div>

      <div id="sidenav-links">
        <ul id="links">
          <li>
            <i class="fas fa-fw fa-id-card fa-2x"></i>
          </li>
          <li>
            <i class="fas fa-fw fa-graduation-cap fa-2x"></i>
          </li>
          <li>
            <i class="fas fa-fw fa-briefcase fa-2x"></i>
          </li>
          <li>
            <i class="fas fa-fw fa-smile-beam fa-2x"></i>
          </li>
        </ul>
      </div>
    </div>
  </body>
</html>

</code>```

```<code>body {
}

/* Make the width full-size then use javascript to minimise so content fits */
#sidenav {
  height: 100%;
  width: 75px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #1e1e2d;
  overflow-x: hidden;
  color: grey;
  transition: width 0.5s;
}

#sidenav-brand {
  padding: 25px 20px;
  background-color: #1a1a27;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

#sidenav-heading {
  display: none;
}

#sidenav-heading h2 {
  margin: 0;
  color: white;
}

#sidenav-expand {
  text-align: center;
  margin-left: 3px;
}

#expand-icon {
  transition: transform 0.5s;
}

#sidenav:hover {
  width: 280px;
}

#sidenav:hover #expand-icon {
  transform: rotate(180deg);
}

#sidenav:hover #sidenav-heading {
  display: inline-block;
}

#sidenav-links {
  margin: 15px 0;
}

#links {
  list-style-type: none;
  padding: 0;
  text-align: left;
}

#links li {
  padding: 18px;
  display: block;
}

#links li:hover {
  color: white;
  background-color: hotpink;
}

.fas {
  vertical-align: middle;
}

</code>```

Please check this fiddle for what I mean when the navbar expands:
https://jsfiddle.net/4pk25oLh/

P.S. The effect I want is the same as when you get rid of the space in the heading text (however, I will need the space). Any help would be greatly appreciated.

答:
Instead of using display property, you can create a cool fade animation for that.

First, add white-space: nowrap to the
, so the text will not wrap.

Then, you use properties such as visiblity, opacity, max-width and transition to create the effect.

```<code>body {
}

/* Make the width full-size then use javascript to minimise so content fits */
#sidenav {
  height: 100%;
  width: 75px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #1e1e2d;
  overflow-x: hidden;
  color: grey;
  transition: width 0.5s;
}

#sidenav-brand {
  padding: 25px 20px;
  background-color: #1a1a27;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

#sidenav-heading {
  display: inline-block;
}

#sidenav-heading h2 {
  margin: 0;
  color: white;
  white-space: nowrap;
  opacity: 0;
  max-width: 0;
  transition: 0.16s;
  visibility: hidden;
}

#sidenav-expand {
  text-align: center;
  margin-left: 3px;
}

#expand-icon {
  transition: transform 0.5s;
}

#sidenav:hover {
  width: 280px;
}

#sidenav:hover #expand-icon {
  transform: rotate(180deg);
}

#sidenav:hover #sidenav-heading h2 {
  opacity: 1;
  max-width: 100vw;
  visibility: visible;
  transition: 0.4s 0.5s;
}

#sidenav-links {
  margin: 15px 0;
}

#links {
  list-style-type: none;
  padding: 0;
  text-align: left;
}

#links li {
  padding: 18px;
  display: block;
}

#links li:hover {
  color: white;
  background-color: hotpink;
}

.fas {
  vertical-align: middle;
}
</code>```

Title: Navigation Bar Heading Text Positioning

Body:
I have a navigation bar that will expand when the mouse is over it. I wish to display heading text once it is expanded (currently shows icons), I have used display: none on the heading tag, which then toggles to display: inline-block when the :hover event is active on the navbar. However, upon expansion of the navbar the text renders in on two lines before positioning itself into one which I want. I want to get rid of this and have the text render in as one line only while the navbar expands. My code:

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Navigation Bar</title>
    <link href="css/styles.css" rel="stylesheet" type="text/css" />

Expanded Test

body {
}

/* Make the width full-size then use javascript to minimise so content fits */
#sidenav {
  height: 100%;
  width: 75px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #1e1e2d;
  overflow-x: hidden;
  color: grey;
  transition: width 0.5s;
}

#sidenav-brand {
  padding: 25px 20px;
  background-color: #1a1a27;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

#sidenav-heading {
  display: none;
}

#sidenav-heading h2 {
  margin: 0;
  color: white;
}

#sidenav-expand {
  text-align: center;
  margin-left: 3px;
}

#expand-icon {
  transition: transform 0.5s;
}

#sidenav:hover {
  width: 280px;
}

#sidenav:hover #expand-icon {
  transform: rotate(180deg);
}

#sidenav:hover #sidenav-heading {
  display: inline-block;
}

#sidenav-links {
  margin: 15px 0;
}

#links {
  list-style-type: none;
  padding: 0;
  text-align: left;
}

#links li {
  padding: 18px;
  display: block;
}

#links li:hover {
  color: white;
  background-color: hotpink;
}

.fas {
  vertical-align: middle;
}

Please check this fiddle for what I mean when the navbar expands:
https://jsfiddle.net/4pk25oLh/

P.S. The effect I want is the same as when you get rid of the space in the heading text (however, I will need the space). Any help would be greatly appreciated.

Body:
Instead of using display property, you can create a cool fade animation for that.

First, add white-space: nowrap to the <h2>, so the text will not wrap.

Then, you use properties such as visiblity, opacity, max-width and transition to create the effect.

body {
}

/* Make the width full-size then use javascript to minimise so content fits */
#sidenav {
  height: 100%;
  width: 75px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #1e1e2d;
  overflow-x: hidden;
  color: grey;
  transition: width 0.5s;
}

#sidenav-brand {
  padding: 25px 20px;
  background-color: #1a1a27;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

#sidenav-heading {
  display: inline-block;
}

#sidenav-heading h2 {
  margin: 0;
  color: white;
  white-space: nowrap;
  opacity: 0;
  max-width: 0;
  transition: 0.16s;
  visibility: hidden;
}

#sidenav-expand {
  text-align: center;
  margin-left: 3px;
}

#expand-icon {
  transition: transform 0.5s;
}

#sidenav:hover {
  width: 280px;
}

#sidenav:hover #expand-icon {
  transform: rotate(180deg);
}

#sidenav:hover #sidenav-heading h2 {
  opacity: 1;
  max-width: 100vw;
  visibility: visible;
  transition: 0.4s 0.5s;
}

#sidenav-links {
  margin: 15px 0;
}

#links {
  list-style-type: none;
  padding: 0;
  text-align: left;
}

#links li {
  padding: 18px;
  display: block;
}

#links li:hover {
  color: white;
  background-color: hotpink;
}

.fas {
  vertical-align: middle;
}


问:
Get nth character of a string in Swift
How can I get the nth character of a string? I tried bracket([]) accessor with no luck.

```<code>var string = "Hello, world!"

var firstChar = string[0] // Throws error
</code>```

ERROR: 'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion

答:
Swift 5.1.3:

Add a String extension:

```<code>extension String {

 func stringAt(_ i: Int) -> String {
   return String(Array(self)[i])
 }

 func charAt(_ i: Int) -> Character {
  return Array(self)[i]
 }
}

let str = "Teja Kumar"
let str1: String = str.stringAt(2)  //"j"
let str2: Character = str.charAt(5)  //"k"
</code>```

Title: Get nth character of a string in Swift

Body:
How can I get the nth character of a string? I tried bracket([]) accessor with no luck.

var string = "Hello, world!"

var firstChar = string[0] // Throws error

ERROR: 'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion

Body:
Swift 5.1.3:

Add a String extension:

extension String {

 func stringAt(_ i: Int) -> String {
   return String(Array(self)[i])
 }

 func charAt(_ i: Int) -> Character {
  return Array(self)[i]
 }
}

let str = "Teja Kumar"
let str1: String = str.stringAt(2)  //"j"
let str2: Character = str.charAt(5)  //"k"


问:
How to give label for null values with previous value
I have a table "person_visits" table have data like as below

The expected output should be like as below, the nulls should be replaced with the previous not null visited_location

Please suggest on this

Thanks

答:
You should be able to get it with not exists clause</p>

```<code>select a.Person_id, a.Calendar_Date, coalesce(a.Visited_Location, b.Visited_Location) as Visited_Location, a.Holiday_Flag
from person_visits a
left join person_visits b on a.Person_id = b.Person_id
and a.Calendar_Date > b.Calendar_Date
and b.Visited_Location is not null
and not exists
(select 1 from
person_visits c where a.Person_id = c.Person_id
and a.Calendar_Date > c.Calendar_Date
and c.Calendar_Date > b.Calendar_Date and c.Visited_Location is not null)
</code>```

Body:
You should be able to get it with not exists clause

select a.Person_id, a.Calendar_Date, coalesce(a.Visited_Location, b.Visited_Location) as Visited_Location, a.Holiday_Flag
from person_visits a
left join person_visits b on a.Person_id = b.Person_id
and a.Calendar_Date > b.Calendar_Date
and b.Visited_Location is not null
and not exists
(select 1 from
person_visits c where a.Person_id = c.Person_id
and a.Calendar_Date > c.Calendar_Date
and c.Calendar_Date > b.Calendar_Date and c.Visited_Location is not null)


问:
Can no longer login to Graph Explorer
I've been using Graph Explorer for a good while, but not just recently (couple of months or so); I came back to it and found I could no longer login; by that I mean I try to login, it seems successful, but leaves me not logged in. Further investigation revealed that some of the logins I can use work, but most of them - the ones I used to use - no longer do. Finally, what's the meaning of the Login in the top right corner, if logged in there, it still treats all web calls as sample account. Help!

答: This turned out to be a browser problem: I was using Edge (recommended by MS for W10), but this regressed a while ago, effectively preventing login. I found that Epic works fine.</p>

Title: Can no longer login to Graph Explorer