问:
I'm trying to make a function "InOrder", which does inorder traversing in Binary Search
I'm trying to make InOrder in void-type, which executes in-order traversal in a binary search tree.

```<code>//Code Provided by Professor
//Program 5.1:Inorder traversal of a binary tree
//===============================================
  template <class T>
  void Tree<T>::Inorder()
  {// Driver.
     Inorder(root);
  }

 template <class T>
 void Tree<T>::Inorder(TreeNode<T> *currentNode)
  {// Workhorse.
 if (currentNode) {
     Inorder(currentNode->leftChild);
     Visit(currentNode);
     Inorder(currentNode->rightChild);
     }
   }
</code>```

The above code is provided by Professor, as a reference making my own InOrder function.

This Code is how I declared the elements(requisites) for my binary search tree.

```<code>#include <iostream>
using namespace std;
template<class K, class E>
class BinarySearchTree
{
public:
    virtual void Insert(const pair<K, E>&) = 0;
    virtual void Delete(const K&) = 0;
    virtual pair<K, E>*Get(const K&) const = 0;
    virtual void InOrder()const;
};
template<class T>
struct TreeNode {
    T data;
    TreeNode<T> *leftChild;
    TreeNode<T> *rightChild;
    TreeNode(T node) : data(node), leftChild(0), rightChild(0) {}
};

template<class K, class E>
class BST : BinarySearchTree<K, E> {
public:
    BST() : root(0) {}
    void Insert(const pair<K, E>&);
    void Delete(const K&);
    pair<K, E>*Get(const K&)const;
    void InOrder()const;

private:
    TreeNode<pair<K, E>> *root;
};
</code>```

Other functions work well, and I would appreciate any help with making InOrder function, using C++.

答:
The concept of in order is just the concept of order. You must also say what should be done in that order. The code provided by your professor calls a visit function.

That means that in your implementation, you also need such a visit function. It can either be hardcoded (display a node on cout) or better passed as a parameter. In that case, you should declare InOrder as:

```<code>void InOrder(void (*visit)(const pair<K, E>&))const;
</code>```

And later call it (for example with a lambda function) as:

```<code>BST<int, string> bst;
...
bst.InOrder([](const pair<int, string>&ke) {
    cout << "K: " << ke.first << " -E: " << ke.second << "\n";
});
</code>```

A possible implementation mimicing your professor's code could be:

```<code>template<class K, class E>
void BST<K,E>::doInOrder(const TN* root, void (*visit)(const pair<K, E>&)) {
    if (root) {
        doInOrder(root->leftChild, visit);
        visit(root->data);
        doInOrder(root->rightChild, visit);
    }
}

template<class K, class E>
void BST<K,E>::InOrder(void (*visit)(const pair<K, E>&))const {
    doInOrder(root, visit);
}
</code>```

Body:
I'm trying to make InOrder in void-type, which executes in-order traversal in a binary search tree.

//Code Provided by Professor
//Program 5.1:Inorder traversal of a binary tree
//===============================================
  template <class T>
  void Tree<T>::Inorder()
  {// Driver.
     Inorder(root);
  }

 template <class T>
 void Tree<T>::Inorder(TreeNode<T> *currentNode)
  {// Workhorse.
 if (currentNode) {
     Inorder(currentNode->leftChild);
     Visit(currentNode);
     Inorder(currentNode->rightChild);
     }
   }

The above code is provided by Professor, as a reference making my own InOrder function.

This Code is how I declared the elements(requisites) for my binary search tree.

#include <iostream>
using namespace std;
template<class K, class E>
class BinarySearchTree
{
public:
    virtual void Insert(const pair<K, E>&) = 0;
    virtual void Delete(const K&) = 0;
    virtual pair<K, E>*Get(const K&) const = 0;
    virtual void InOrder()const;
};
template<class T>
struct TreeNode {
    T data;
    TreeNode<T> *leftChild;
    TreeNode<T> *rightChild;
    TreeNode(T node) : data(node), leftChild(0), rightChild(0) {}
};

template<class K, class E>
class BST : BinarySearchTree<K, E> {
public:
    BST() : root(0) {}
    void Insert(const pair<K, E>&);
    void Delete(const K&);
    pair<K, E>*Get(const K&)const;
    void InOrder()const;

private:
    TreeNode<pair<K, E>> *root;
};

Other functions work well, and I would appreciate any help with making InOrder function, using C++.

Body:
The concept of in order is just the concept of order. You must also say what should be done in that order. The code provided by your professor calls a visit function.

That means that in your implementation, you also need such a visit function. It can either be hardcoded (display a node on cout) or better passed as a parameter. In that case, you should declare InOrder as:

void InOrder(void (*visit)(const pair<K, E>&))const;

And later call it (for example with a lambda function) as:

BST<int, string> bst;
...
bst.InOrder([](const pair<int, string>&ke) {
    cout << "K: " << ke.first << " -E: " << ke.second << "\n";
});

A possible implementation mimicing your professor's code could be:

template<class K, class E>
void BST<K,E>::doInOrder(const TN* root, void (*visit)(const pair<K, E>&)) {
    if (root) {
        doInOrder(root->leftChild, visit);
        visit(root->data);
        doInOrder(root->rightChild, visit);
    }
}

template<class K, class E>
void BST<K,E>::InOrder(void (*visit)(const pair<K, E>&))const {
    doInOrder(root, visit);
}


来源: stackexchange

问:
How to use macro function for multiple
 in xml with xPath?
```<code>I need to extract address, telephone no using xPath from my html page. My
address is sometimes within one `<p>`, else within two `<p>`. I have 11
stores.
This is the html tag <p> in my xml. (Just an example)

<div class="info-block-value"> ==$0
   <p>36 rue de la Verrerie 75004 PARIS</p>
   <p>Tél : 0111 222 222</p>
  </div>
<div class="info-block-value"> ==$0
   <p>11 rue des archives</p>
   <p>75004 PARIS</p>
   <p>Tél : 01 11 11 11 11</p>
  </div>

1st shop: P1 =address P2= tel
2nd shop P1= address P2 = tel P3 = fax
3rd shop P1=address line 1 P2 = address line 2 P3= tel
4th : P1 = address P2 = tel
5th : P1= add P2 = tel
Shops 6,7,8,9,11 : P1 = add line 1 P2 = add line 2 ( they have no
telephone)
10th shop : P1= add line 1 P2= addline 2, P3= tel, P4= space P5 = email

I tried with,
</code>```

{
            "name": "store Addr",
            "key": "Address",
            "xPath": "(//div[@class='info-block-value']/p)[1] |
                     (//div[@class='info-block-value']/p)[2]",
            "level": 0,
            "enabled": true,
            "values": []
          },
          {
            "name": "Tel No",
            "key": "TelephoneNumber",
            "xPath": "(//div[@class='info-block-value']/p)[2]|
                     (//div[@class='info-
                     block-value']/p)[3]",
            "regex": "Tél : ((\d+\s*)+)+",
            "level": 0,
            "enabled": true,
            "values": []
          }

```<code>But I'm not getting the correct results. Can someone help me this?

Results:

id name address                               phone
1  a    36 rue de la Verrerie 75004 PARIS     0111 222 222
2  b    11 rue des archives                   01 11 11 11 11

Expecting results
id name address                               phone
1  a    36 rue de la Verrerie 75004 PARIS     0111 222 222
2  b    11 rue des archives  75004 PARIS      01 11 11 11 11
</code>```

答:
You basically need all the
 but the last one for the address, and the last one for the telephone number.

So, get the address with

```<code>//div[@class="info-block-value"]/p[position() < last()]
</code>```

and similarly, the telephone number is under

```<code>//div[@class="info-block-value"]/p[last()]
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to use macro function for multiple <p> in xml with xPath?

Body:
I need to extract address, telephone no using xPath from my html page. My
address is sometimes within one `<p>`, else within two `<p>`. I have 11
stores.
This is the html tag
 in my xml. (Just an example)

 ==$0

36 rue de la Verrerie 75004 PARIS

Tél : 0111 222 222

 ==$0

11 rue des archives

75004 PARIS

Tél : 01 11 11 11 11

1st shop: P1 =address P2= tel
2nd shop P1= address P2 = tel P3 = fax
3rd shop P1=address line 1 P2 = address line 2 P3= tel
4th : P1 = address P2 = tel
5th : P1= add P2 = tel
Shops 6,7,8,9,11 : P1 = add line 1 P2 = add line 2 ( they have no
telephone)
10th shop : P1= add line 1 P2= addline 2, P3= tel, P4= space P5 = email

I tried with,

{
            "name": "store Addr",
            "key": "Address",
            "xPath": "(//div[@class='info-block-value']/p)[1] |
                     (//div[@class='info-block-value']/p)[2]",
            "level": 0,
            "enabled": true,
            "values": []
          },
          {
            "name": "Tel No",
            "key": "TelephoneNumber",
            "xPath": "(//div[@class='info-block-value']/p)[2]|
                     (//div[@class='info-
                     block-value']/p)[3]",
            "regex": "Tél : ((\d+\s*)+)+",
            "level": 0,
            "enabled": true,
            "values": []
          }

But I'm not getting the correct results. Can someone help me this?

Results:

id name address                               phone
1  a    36 rue de la Verrerie 75004 PARIS     0111 222 222
2  b    11 rue des archives                   01 11 11 11 11

Expecting results
id name address                               phone
1  a    36 rue de la Verrerie 75004 PARIS     0111 222 222
2  b    11 rue des archives  75004 PARIS      01 11 11 11 11

Body:
You basically need all the <p> but the last one for the address, and the last one for the telephone number.

So, get the address with

//div[@class="info-block-value"]/p[position() < last()]

and similarly, the telephone number is under

//div[@class="info-block-value"]/p[last()]


问:
DialogFlow - Returning a long response from the webhook via paged results
I have a custom DialogFlow that on fulfilment, processes the user input and extracts a search keyword. DialogFlow then sends the search keyword to my Webhook.

My Webhook looks up the search keyword in a database that I have, and returns the result back.

Now, this mostly works great as long as the results are short. The user searches, and the results are returned back and is read by Google Assistant.

But when the results are long and exceed a certain character count, the search results get cut and are followed by ellipses. This is very shortly followed by a "Google Assistant Not Responding" error message. It might be worth noting that Google Assistant doesn't even manage to begin to read the text. It just crashes.

Now, what I want to happen is for the long results to be displayed. Something similar to when you ask Google Assistant to look up movies:

Or maybe even a paged result that a user can scroll through.

答:
Each Dialogflow integration (Facebook, Slack, Actions on Google, etc) has different features, capabilities, and limits. There is no one solution that will work for all of them.

If you are giving a long answer, however, keep in mind that some of the formats aren't well suited for long answers and this can create a poor UX. Spoken answers on the Assistant, for example, should be kept short.

If you are looking for a reply along the lines of what you illustrate, you can use something like multiple cards to represent the various replies. Some platforms, such as Facebook, will support this. If you're developing for the Assistant, Actions on Google supports a Carousel/List visual selector.


问:
Many to Many Relationship - how to query all children
I am using flask-sqlalchemy to implement many to many relationship. Tried many options but unable to query all children for a parent.

```<code>class Participant(db.Model):
    __tablename__='participant'
    __table_args__ = {'extend_existing': True}

    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(120), unique=True)
    name = db.Column(db.String(120), unique=False)

    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    user = db.relationship("User")

    @staticmethod
    def get_by_user(user):
        return Participant.query.filter_by(user=user).first()

    def __repr__(self):
        return "(Participant '{}')".format(self.email)

    competitions = db.relationship("CompetitionParticipant", back_populates="participant")

class Competition(db.Model):
    __tablename__='competition'
    __table_args__={'extend_existing':True}

    id=db.Column(db.Integer,primary_key=True)

    name=db.Column(db.String(100),unique=True)
    description=db.Column(db.String(255),unique=True)
    # type=db.Column(db.String(50))#Team,Individual,Practice,etc.
    start_date=db.Column(db.DateTime)
    end_date=db.Column(db.DateTime)
    result_date=db.Column(db.DateTime)

    participants = db.relationship('CompetitionParticipant', back_populates='competition')

    def __repr__(self):
        return "(Competition '{}')".format(self.name)

class CompetitionParticipant(db.Model):
    __tablename__='competition_participant'
    __table_args__={'extend_existing':True}

    id=db.Column(db.Integer,primary_key=True)
    participant_id=db.Column(db.Integer, db.ForeignKey('participant.id'))
    competition_id=db.Column(db.Integer, db.ForeignKey('competition.id'))

    competition=db.relationship("Competition",back_populates="participants")
    participant=db.relationship("Participant",back_populates="competitions")

    def __repr__(self):
        return "(competition_id, participant_id '{},{}')".format(self.competition_id,self.participant_id)
</code>```

In this many to many relationship example how will I query all the competitions a participant is enrolled in?

I have tried following:

```<code>participant.competitions # returns relationship object
</code>```

everything else I tried was syntax error. What is right ORM way to extract all competitions a participant is enrolled in?

答:
If you, for example, want to get competitions data for a specific user:

```<code>participants = Participant.query.filter_by(id=1).all()
</code>```

you can iterate through participants and get data :

```<code>for participant in participants:
    for competition in participant.competitions:
        print(competition.competition.name)
</code>```

Body:
I am using flask-sqlalchemy to implement many to many relationship. Tried many options but unable to query all children for a parent.

class Participant(db.Model):
    __tablename__='participant'
    __table_args__ = {'extend_existing': True}

    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(120), unique=True)
    name = db.Column(db.String(120), unique=False)

    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    user = db.relationship("User")

    @staticmethod
    def get_by_user(user):
        return Participant.query.filter_by(user=user).first()

    def __repr__(self):
        return "(Participant '{}')".format(self.email)

    competitions = db.relationship("CompetitionParticipant", back_populates="participant")

class Competition(db.Model):
    __tablename__='competition'
    __table_args__={'extend_existing':True}

    id=db.Column(db.Integer,primary_key=True)

    name=db.Column(db.String(100),unique=True)
    description=db.Column(db.String(255),unique=True)
    # type=db.Column(db.String(50))#Team,Individual,Practice,etc.
    start_date=db.Column(db.DateTime)
    end_date=db.Column(db.DateTime)
    result_date=db.Column(db.DateTime)

    participants = db.relationship('CompetitionParticipant', back_populates='competition')

    def __repr__(self):
        return "(Competition '{}')".format(self.name)

class CompetitionParticipant(db.Model):
    __tablename__='competition_participant'
    __table_args__={'extend_existing':True}

    id=db.Column(db.Integer,primary_key=True)
    participant_id=db.Column(db.Integer, db.ForeignKey('participant.id'))
    competition_id=db.Column(db.Integer, db.ForeignKey('competition.id'))

    competition=db.relationship("Competition",back_populates="participants")
    participant=db.relationship("Participant",back_populates="competitions")

    def __repr__(self):
        return "(competition_id, participant_id '{},{}')".format(self.competition_id,self.participant_id)

In this many to many relationship example how will I query all the competitions a participant is enrolled in?

I have tried following:

participant.competitions # returns relationship object

everything else I tried was syntax error. What is right ORM way to extract all competitions a participant is enrolled in?

Body:
If you, for example, want to get competitions data for a specific user:

participants = Participant.query.filter_by(id=1).all()

you can iterate through participants and get data :

for participant in participants:
    for competition in participant.competitions:
        print(competition.competition.name)


问:
Hibernate Delete, child violation
I am yet again stuck with trying to delete data with Hibernate..

I am at point where I am starting to just stack annotation, hoping something would work... so far nothing has.

I need to delete old calculation when starting new for same time period.

I have the following query

```<code>@Modifying
@QueryHints(value = @QueryHint(name = HINT_FETCH_SIZE, value = "10"))
@Query(value = "DELETE FROM Group a WHERE a.c_date BETWEEN :dateA AND :dateB")
void deleteOld(@Param("dateA") LocalDate dateA, @Param("dateB") LocalDate dateB);
</code>```

which uses entity Group, which has (on top of normal String, LocalDate and long types) attribute

```<code>    @OneToMany(cascade=CascadeType.ALL, mappedBy = "owner", orphanRemoval = true)
    @JsonManagedReference
    @OnDelete(action = OnDeleteAction.CASCADE)
    private List<Instrument> instruments = new ArrayList<>();
</code>```

But I still get  violated - child record found every time I try to run delete method.

I keep finding more and more annotations like this, from threads where people have the same kind of problems, but I would love to understand why is this a problem. From what I read Cascade and orphanRemoval should be all I need, but it sure does not seem to be.

Hibernate: 5.2.17.Final

Please help me to understand, why is this happening ?

答:
The @OnDelete will delete records using a ON DELETE rule on the database, when using Hibernate to generate the schema. If you manage your own schema this will have no effect.

The @QueryHints you have specified doesn't really make sense here, for an DELETE query that is. Nothing will be fetched.

The fact that you are using an @Query basically bypasses the configuration in the @OneToMany, simply due to the fact that you write a query and apparently know what you are doing. So the mapping isn't taken into account.

If you want to delete the childs as then you have 3 options:

Add an additional query and first remove the childs, then the parents

Add an ON DELETE rule to your database, to automatically remove the childs

Retrieve the Group and remove using EntityManager.remove which will take the @OneToMany mappings into account as now Hibernate needs to manage the dependencies between the entities.

Title: Hibernate Delete, child violation

Body:
I am yet again stuck with trying to delete data with Hibernate..

I am at point where I am starting to just stack annotation, hoping something would work... so far nothing has.

I need to delete old calculation when starting new for same time period.

I have the following query

@Modifying
@QueryHints(value = @QueryHint(name = HINT_FETCH_SIZE, value = "10"))
@Query(value = "DELETE FROM Group a WHERE a.c_date BETWEEN :dateA AND :dateB")
void deleteOld(@Param("dateA") LocalDate dateA, @Param("dateB") LocalDate dateB);

which uses entity Group, which has (on top of normal String, LocalDate and long types) attribute

    @OneToMany(cascade=CascadeType.ALL, mappedBy = "owner", orphanRemoval = true)
    @JsonManagedReference
    @OnDelete(action = OnDeleteAction.CASCADE)
    private List<Instrument> instruments = new ArrayList<>();

But I still get  violated - child record found every time I try to run delete method.

I keep finding more and more annotations like this, from threads where people have the same kind of problems, but I would love to understand why is this a problem. From what I read Cascade and orphanRemoval should be all I need, but it sure does not seem to be.

Hibernate: 5.2.17.Final

Please help me to understand, why is this happening ?


问:
Azure Blob - Read using Python
Can someone tell me if it is possible to read a csv file directly from Azure blob storage as a stream and process it using Python? I know it can be done using C#.Net (shown below) but wanted to know the equivalent library in Python to do this. </p>

```<code>CloudBlobClient client = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = client.GetContainerReference("outfiles");
CloudBlob blob = container.GetBlobReference("Test.csv");*
</code>```

答:
One can stream from blob with python like this:</p>

```<code>from tempfile import NamedTemporaryFile
from azure.storage.blob.blockblobservice import BlockBlobService

entry_path = conf['entry_path']
container_name = conf['container_name']
blob_service = BlockBlobService(
            account_name=conf['account_name'],
            account_key=conf['account_key'])

def get_file(filename):
    local_file = NamedTemporaryFile()
    blob_service.get_blob_to_stream(container_name, filename, stream=local_file,
    max_connections=2)

    local_file.seek(0)
    return local_file
</code>```

ContentLicense: CC BY-SA 3.0

Title: Azure Blob - Read using Python

Body:
Can someone tell me if it is possible to read a csv file directly from Azure blob storage as a stream and process it using Python? I know it can be done using C#.Net (shown below) but wanted to know the equivalent library in Python to do this.

CloudBlobClient client = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = client.GetContainerReference("outfiles");
CloudBlob blob = container.GetBlobReference("Test.csv");*

Body:
One can stream from blob with python like this:

from tempfile import NamedTemporaryFile
from azure.storage.blob.blockblobservice import BlockBlobService

entry_path = conf['entry_path']
container_name = conf['container_name']
blob_service = BlockBlobService(
            account_name=conf['account_name'],
            account_key=conf['account_key'])

def get_file(filename):
    local_file = NamedTemporaryFile()
    blob_service.get_blob_to_stream(container_name, filename, stream=local_file,
    max_connections=2)

    local_file.seek(0)
    return local_file


问:
Mongo DB with C# - document added regardless of transaction
I'm trying to test the newly supported transactions in Mongo DB with a simple example I wrote.
I'm using Mongo DB version 4.0.5 with driver version 2.8.1.
It's only a primary instance with no shards/replicas.

I must be missing something basic in the following code.
I create a Mongo client, session & database, then start a transaction, add a document and abort the transaction. After this code, I expect nothing to change in the database, but the document is added. When debugging I can also see the document right after the InsertOne() by using Robo 3T (Mongo client GUI).

Any idea what am I missing?

```<code>        var client =  new MongoClient("mongodb://localhost:27017");
        var session = client.StartSession();
        var database = session.Client.GetDatabase("myDatabase", new MongoDatabaseSettings
        {
            GuidRepresentation = GuidRepresentation.Standard,
            ReadPreference = ReadPreference.Primary,
            WriteConcern = new WriteConcern(1,
                new MongoDB.Driver.Optional<TimeSpan?>(TimeSpan.FromSeconds(30))),

        });

        var entities = database.GetCollection<MyEntity>("test");

        session.StartTransaction();

        // After this line I can already see the document in the db collection using Mongo client GUI (Robo 3T), although I expect not to see it until committing
        entities.InsertOne(new MyEntity { Name =  "Entity" });

        // This does not have any effect
        session.AbortTransaction();
</code>```

Edit:

It's possible to run MongoDB as a 1-node replica set, although I'm not sure what's the difference between a standalone and a 1-node replica set.
See my post below.

In any case, to use the started transaction the insertion code must receive the session as a parameter:

```<code>entities.InsertOne(session, new MyEntity { Name = "Entity" });
</code>```

With these 2 change now the transaction works.

答:
This is inherently a property of MongoDB itself. (More here and here)

Transactions are only available in a replica set setup

Why isnt it available for standalone instances?

With subdocuments and arrays, document databases (MongoDB) allow related data to be unified hierarchically inside a single data structure. The document can be updated with an atomic operation, giving it the same data integrity guarantees as a multi-table transaction in a relational database.

Body:
I'm trying to test the newly supported transactions in Mongo DB with a simple example I wrote.
I'm using Mongo DB version 4.0.5 with driver version 2.8.1.
It's only a primary instance with no shards/replicas.

I must be missing something basic in the following code.
I create a Mongo client, session & database, then start a transaction, add a document and abort the transaction. After this code, I expect nothing to change in the database, but the document is added. When debugging I can also see the document right after the InsertOne() by using Robo 3T (Mongo client GUI).

Any idea what am I missing?

        var client =  new MongoClient("mongodb://localhost:27017");
        var session = client.StartSession();
        var database = session.Client.GetDatabase("myDatabase", new MongoDatabaseSettings
        {
            GuidRepresentation = GuidRepresentation.Standard,
            ReadPreference = ReadPreference.Primary,
            WriteConcern = new WriteConcern(1,
                new MongoDB.Driver.Optional<TimeSpan?>(TimeSpan.FromSeconds(30))),

        });

        var entities = database.GetCollection<MyEntity>("test");

        session.StartTransaction();

        // After this line I can already see the document in the db collection using Mongo client GUI (Robo 3T), although I expect not to see it until committing
        entities.InsertOne(new MyEntity { Name =  "Entity" });

        // This does not have any effect
        session.AbortTransaction();

Edit:

It's possible to run MongoDB as a 1-node replica set, although I'm not sure what's the difference between a standalone and a 1-node replica set.
See my post below.

In any case, to use the started transaction the insertion code must receive the session as a parameter:

entities.InsertOne(session, new MyEntity { Name = "Entity" });

With these 2 change now the transaction works.


问:
Checking if a div is visible within viewport using jquery
I am trying to use jquery to check if Div RED is within the viewport, and if not, then check if  Div ORANGE is in the viewport. The function I am using works great if there is only one IF statement, but when I add another IF ELSE statement, it wont work.

here is the function:

```<code>$.fn.isOnScreen = function(){

    var win = $(window);

    var viewport = {
        top : win.scrollTop(),
        left : win.scrollLeft()
    };
    viewport.right = viewport.left + win.width();
    viewport.bottom = viewport.top + win.height();

    var bounds = this.offset();
    bounds.right = bounds.left + this.outerWidth();
    bounds.bottom = bounds.top + this.outerHeight();

    return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));

};
</code>```

here is the code I added to check and see if div red or div orange is within the viewport

```<code>$(window).scroll(function() {
    if ($('.red').isOnScreen() === true) {
       $('.red').remove();
    } else if ($('.orange').isOnScreen() === true) {
       $('.orange').remove();

    }
});
</code>```

here is a jfiddle http://jsfiddle.net/wN7ah/453/

答:
We can do it with pure javascript function like below

function elementInViewport2(el) {
  var top = el.offsetTop;
  var left = el.offsetLeft;
  var width = el.offsetWidth;
  var height = el.offsetHeight;

  while(el.offsetParent) {
    el = el.offsetParent;
    top += el.offsetTop;
    left += el.offsetLeft;
  }

  return (
    top < (window.pageYOffset + window.innerHeight) &&
    left < (window.pageXOffset + window.innerWidth) &&
    (top + height) > window.pageYOffset &&
    (left + width) > window.pageXOffset
  );
}
ele = document.getElementById('visb_true');
console.log("visible: ", elementInViewport2(ele))
ele = document.getElementById('visb_false');
console.log("visible: ", elementInViewport2(ele))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#visb_true{
    color: green;
    font-weight: 800;
}

#visb_false{
    color: red;
    font-weight: 800;
}</code>```

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

 hello

```

Body:
I am trying to use jquery to check if Div RED is within the viewport, and if not, then check if  Div ORANGE is in the viewport. The function I am using works great if there is only one IF statement, but when I add another IF ELSE statement, it wont work.

here is the function:

$.fn.isOnScreen = function(){

    var win = $(window);

    var viewport = {
        top : win.scrollTop(),
        left : win.scrollLeft()
    };
    viewport.right = viewport.left + win.width();
    viewport.bottom = viewport.top + win.height();

    var bounds = this.offset();
    bounds.right = bounds.left + this.outerWidth();
    bounds.bottom = bounds.top + this.outerHeight();

    return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));

};

here is the code I added to check and see if div red or div orange is within the viewport

$(window).scroll(function() {
    if ($('.red').isOnScreen() === true) {
       $('.red').remove();
    } else if ($('.orange').isOnScreen() === true) {
       $('.orange').remove();

    }
});

here is a jfiddle http://jsfiddle.net/wN7ah/453/

Body:
We can do it with pure javascript function like below

function elementInViewport2(el) {
  var top = el.offsetTop;
  var left = el.offsetLeft;
  var width = el.offsetWidth;
  var height = el.offsetHeight;

  while(el.offsetParent) {
    el = el.offsetParent;
    top += el.offsetTop;
    left += el.offsetLeft;
  }

  return (
    top < (window.pageYOffset + window.innerHeight) &&
    left < (window.pageXOffset + window.innerWidth) &&
    (top + height) > window.pageYOffset &&
    (left + width) > window.pageXOffset
  );
}
ele = document.getElementById('visb_true');
console.log("visible: ", elementInViewport2(ele))
ele = document.getElementById('visb_false');
console.log("visible: ", elementInViewport2(ele))

#visb_true{
    color: green;
    font-weight: 800;
}

#visb_false{
    color: red;
    font-weight: 800;
}

<html>
<body>
<p> hello </p>
<p> hello </p>
<p id="visb_true"> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p>
<p> hello </p><p> hello </p>
<p id="visb_false"> hello </p>
<p> hello </p>
</body>
</html>


问:
jQuery - exclude inputs with certain value from selector
I would like to select all inputs in my div and set them new value but also I want to exclude inputs with certain value
something like this:

```<code>$('#mydiv input:not(val("100")').val(myvariable);
</code>```

how to do that, is it possible in simple selector?
thanks

答:
```<code>$('#mydiv input:not([value="100"])').val(myvariable);
</code>```

or

```<code>$('#mydiv input').filter(function() {
    return $(this).val() != 100;
}).val(myvar);
</code>```

Body:
I would like to select all inputs in my div and set them new value but also I want to exclude inputs with certain value
something like this:

$('#mydiv input:not(val("100")').val(myvariable);

how to do that, is it possible in simple selector?
thanks

Body:
$('#mydiv input:not([value="100"])').val(myvariable);

or

$('#mydiv input').filter(function() {
    return $(this).val() != 100;
}).val(myvar);


问:
Run dotnet core application on Raspberry Pi3 with CentOS UserLand
I am trying to run my AspNetCore 2 application on a Raspberry Pi3 Model B that runs CentOS arm edition (CentOS-Userland-7-armv7hl-Minimal-1708-RaspberryPi3). I installed both libunwind and libicu-devel with yum install, but when trying to run my application, I always get the following error:

```<code>[root@centos-rpi3 ~]# /opt/dotnet/dotnet my.dll

FailFast: Couldn't find a valid ICU package installed on the system. Set the configuration flag System.Globalization.Invariant to true if you want to run with no globalization support.

   at System.Environment.FailFast(System.String)
   at System.Globalization.GlobalizationMode.GetGlobalizationInvariantMode()
   at System.Globalization.GlobalizationMode..cctor()
   at System.Globalization.CultureData.CreateCultureWithInvariantData()
   at System.Globalization.CultureData.get_Invariant()
   at System.Globalization.CultureData.GetCultureData(System.String, Boolean)
   at System.Globalization.CultureInfo.InitializeFromName(System.String, Boolean)
   at System.Globalization.CultureInfo.Init()
   at System.Globalization.CultureInfo..cctor()
   at System.Globalization.CultureInfo.get_InvariantCulture()
   at System.StringComparer..cctor()
   at System.AppDomainSetup.SetCompatibilitySwitches(System.Collections.Generic.IEnumerable`1<System.String>)
   at System.AppDomain.PrepareDataForSetup(System.String, System.AppDomainSetup, System.Security.Policy.Evidence, System.Security.Policy.Evidence, IntPtr, System.String, System.String[], System.String[])
Aborted
</code>```

For dotnet core installation I followed the guide described here (Task: Install the .NET Core Runtime on the Raspberry Pi): https://blogs.msdn.microsoft.com/david/2017/07/20/setting_up_raspian_and_dotnet_core_2_0_on_a_raspberry_pi/

Any ideas why dotnet core throws this error?

答:
On my CentOs 7 system,i install icu library with this:

sudo yum install libicu

Body:
I am trying to run my AspNetCore 2 application on a Raspberry Pi3 Model B that runs CentOS arm edition (CentOS-Userland-7-armv7hl-Minimal-1708-RaspberryPi3). I installed both libunwind and libicu-devel with yum install, but when trying to run my application, I always get the following error:

[root@centos-rpi3 ~]# /opt/dotnet/dotnet my.dll

FailFast: Couldn't find a valid ICU package installed on the system. Set the configuration flag System.Globalization.Invariant to true if you want to run with no globalization support.

   at System.Environment.FailFast(System.String)
   at System.Globalization.GlobalizationMode.GetGlobalizationInvariantMode()
   at System.Globalization.GlobalizationMode..cctor()
   at System.Globalization.CultureData.CreateCultureWithInvariantData()
   at System.Globalization.CultureData.get_Invariant()
   at System.Globalization.CultureData.GetCultureData(System.String, Boolean)
   at System.Globalization.CultureInfo.InitializeFromName(System.String, Boolean)
   at System.Globalization.CultureInfo.Init()
   at System.Globalization.CultureInfo..cctor()
   at System.Globalization.CultureInfo.get_InvariantCulture()
   at System.StringComparer..cctor()
   at System.AppDomainSetup.SetCompatibilitySwitches(System.Collections.Generic.IEnumerable`1<System.String>)
   at System.AppDomain.PrepareDataForSetup(System.String, System.AppDomainSetup, System.Security.Policy.Evidence, System.Security.Policy.Evidence, IntPtr, System.String, System.String[], System.String[])
Aborted

For dotnet core installation I followed the guide described here (Task: Install the .NET Core Runtime on the Raspberry Pi): https://blogs.msdn.microsoft.com/david/2017/07/20/setting_up_raspian_and_dotnet_core_2_0_on_a_raspberry_pi/

Any ideas why dotnet core throws this error?


问:
You can't specify target table 'A' for update in FROM clause
This is my request

```<code>> DELETE FROM A WHERE id in (    Select
> id From A    Left Join B on A.id=B.id
> Where B.id is null )
</code>```

When I execute this I have this error

You can't specify target table 'A' for
  update in FROM clause

答:
Maybe you could do it like this instead?  </p>

```<code>DELETE FROM A WHERE id NOT IN (SELECT DISTINCT B.id FROM B);
</code>```

Body:
This is my request

> DELETE FROM A WHERE id in (    Select
> id From A    Left Join B on A.id=B.id
> Where B.id is null )

When I execute this I have this error

You can't specify target table 'A' for
  update in FROM clause

Body:
Maybe you could do it like this instead?

DELETE FROM A WHERE id NOT IN (SELECT DISTINCT B.id FROM B);


问:
Serving .APK file from CDN with headers to install in Android
I want to serve a .APK file to users to download. I have a CDN and it works fine. When I request file download, It downloads from CDN. But I have a problem. My users request downloads from Android devices, in this case, Downloading pure APK file goes trouble because I want to users install that APK file and with pure APK it's not possible as I know. So I create a .php file like this and add 'Content-Type: application/vnd.android.package-archive':

```<code><?php

$file = 'myfile.apk'; //File that we want to send to user.

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/vnd.android.package-archive');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}
?>
</code>```

When I request download.php, Its work and users can download and install the APK file. And now my question is, In this case, That file downloads from the CDN? I want both download.php and APK file served from CDN because I don't have enough traffic.

Or is this possible to add 'Content-Type: application/vnd.android.package-archive' to downloading file from CDN without php?

PS: When i request pure APK file, Because it's from CDN, It downloads instantly like it's caching, But with download.php, It takes time to download. it means in this case it's not from CDN?

答:
Or is this possible to add 'Content-Type: application/vnd.android.package-archive' to downloading file from CDN without php?

Yes, downloading must work correct in this case.

But with download.php, It takes time to download. it means in this case it's not from CDN?

It takes time, because you use readfile and output buffering. In this case, download started only after php fully load content of target file into memory. This is potential problem, if you plan serve big apk files.

You can serve them, to example in this way:

```<code>// set headers here ...
$output = fopen('php://out', 'a');
$target = fopen($target, 'r');

if (!$target || !$output) {
    //  throw error, if cant read file or
}

// read target file, using buffer size 1024
while (!feof($target)) {
    fwrite($output, fread($target, 1024), 1024);
}

fclose($target);
fclose($output);
</code>```

Body:
I want to serve a .APK file to users to download. I have a CDN and it works fine. When I request file download, It downloads from CDN. But I have a problem. My users request downloads from Android devices, in this case, Downloading pure APK file goes trouble because I want to users install that APK file and with pure APK it's not possible as I know. So I create a .php file like this and add 'Content-Type: application/vnd.android.package-archive':

<?php

$file = 'myfile.apk'; //File that we want to send to user.

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/vnd.android.package-archive');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}
?>

When I request download.php, Its work and users can download and install the APK file. And now my question is, In this case, That file downloads from the CDN? I want both download.php and APK file served from CDN because I don't have enough traffic.

Or is this possible to add 'Content-Type: application/vnd.android.package-archive' to downloading file from CDN without php?

PS: When i request pure APK file, Because it's from CDN, It downloads instantly like it's caching, But with download.php, It takes time to download. it means in this case it's not from CDN?

Body:
Or is this possible to add 'Content-Type: application/vnd.android.package-archive' to downloading file from CDN without php?

Yes, downloading must work correct in this case.

But with download.php, It takes time to download. it means in this case it's not from CDN?

It takes time, because you use readfile and output buffering. In this case, download started only after php fully load content of target file into memory. This is potential problem, if you plan serve big apk files.

You can serve them, to example in this way:

// set headers here ...
$output = fopen('php://out', 'a');
$target = fopen($target, 'r');

if (!$target || !$output) {
    //  throw error, if cant read file or
}

// read target file, using buffer size 1024
while (!feof($target)) {
    fwrite($output, fread($target, 1024), 1024);
}

fclose($target);
fclose($output);


问:
Radio buttons are not switching
I have radio buttons and one of them :checked and they have the same name. When I click another radio button they are both selected.

My code is:

```<code><input name="a" type="radio">
<input name="a "type="radio" checked>
</code>```

JS

```<code>$("input[type='radio']").each(function () {
    if ($(this).is(":checked")) {
    $(this).addClass("some");
   }
 });
</code>```

CSS

```<code>  .some {
      background-color:#06c!important;
  }
</code>```

My approach is to first check if my inputs are :checked and if they are, put some css class with background color.  I achieve that, the next thing I want to is remove that :checked when users click on radio button or any other (better) idea. Right now both radio buttons are selected. Can anybody help me with this?

Fiddle:

```<code>https://jsfiddle.net/0ns58xcq/
</code>```

答:
If you are talking about another approach, then I suggest, there is no need to use javascript at all. You can do it with css too, if you just want to change color of radiobutton and check which one is checked.

Well you can not change the color of native radio button directly. But
  there is an alternate way, mentioned below.

/* The container */
.container {
  display: block;
  position: relative;
  padding-left: 35px;
  margin-bottom: 12px;
  cursor: pointer;
  font-size: 22px;
}

/* Hide the browser's default radio button */
.container input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
}

/* Create a custom radio button */
.checkmark {
  position: absolute;
  top: 0;
  left: 0;
  height: 25px;
  width: 25px;
  background-color: #eee;
  border-radius: 50%;
}

/* On mouse-over, add a grey background color */
.container:hover input ~ .checkmark {
  background-color: #ccc;
}

/* When the radio button is checked, add a blue background */
.container input:checked ~ .checkmark {
  background-color: #06c;
}

/* Create the indicator (the dot/circle - hidden when not checked) */
.checkmark:after {
  content: "";
  position: absolute;
  display: none;
}

/* Show the indicator (dot/circle) when checked */
.container input:checked ~ .checkmark:after {
  display: block;
}

/* Style the indicator (dot/circle) */
.container .checkmark:after {
  top: 9px;
 left: 9px;
 width: 8px;
 height: 8px;
 border-radius: 50%;
 background: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label class="container">One
  <input type="radio" checked="checked" name="a">
  <span class="checkmark"></span>
</label>
<label class="container">Two
  <input type="radio" name="a">
  <span class="checkmark"></span>
</label></code>```

Title: Radio buttons are not switching

Body:
I have radio buttons and one of them :checked and they have the same name. When I click another radio button they are both selected.

My code is:

<input name="a" type="radio">
<input name="a "type="radio" checked>

JS

$("input[type='radio']").each(function () {
    if ($(this).is(":checked")) {
    $(this).addClass("some");
   }
 });

CSS

  .some {
      background-color:#06c!important;
  }

My approach is to first check if my inputs are :checked and if they are, put some css class with background color.  I achieve that, the next thing I want to is remove that :checked when users click on radio button or any other (better) idea. Right now both radio buttons are selected. Can anybody help me with this?

Fiddle:

https://jsfiddle.net/0ns58xcq/

Body:
If you are talking about another approach, then I suggest, there is no need to use javascript at all. You can do it with css too, if you just want to change color of radiobutton and check which one is checked.

Well you can not change the color of native radio button directly. But
  there is an alternate way, mentioned below.

/* The container */
.container {
  display: block;
  position: relative;
  padding-left: 35px;
  margin-bottom: 12px;
  cursor: pointer;
  font-size: 22px;
}

/* Hide the browser's default radio button */
.container input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
}

/* Create a custom radio button */
.checkmark {
  position: absolute;
  top: 0;
  left: 0;
  height: 25px;
  width: 25px;
  background-color: #eee;
  border-radius: 50%;
}

/* On mouse-over, add a grey background color */
.container:hover input ~ .checkmark {
  background-color: #ccc;
}

/* When the radio button is checked, add a blue background */
.container input:checked ~ .checkmark {
  background-color: #06c;
}

/* Create the indicator (the dot/circle - hidden when not checked) */
.checkmark:after {
  content: "";
  position: absolute;
  display: none;
}

/* Show the indicator (dot/circle) when checked */
.container input:checked ~ .checkmark:after {
  display: block;
}

/* Style the indicator (dot/circle) */
.container .checkmark:after {
  top: 9px;
 left: 9px;
 width: 8px;
 height: 8px;
 border-radius: 50%;
 background: white;
}

<label class="container">One
  <input type="radio" checked="checked" name="a">
  <span class="checkmark"></span>
</label>
<label class="container">Two
  <input type="radio" name="a">
  <span class="checkmark"></span>
</label>


问:
The function idr_alloc(...) fails sometimes with the error -EINVAL(-22)
I'm trying out the Kernel API for IDR (Integer ID Management). It's a map where an ID get's associated with a pointer.
The API has changed, so old examples that i found, didn't work.
So i did my own example and it works only partially.
Sometimes the function idr_alloc fails with -22(-EINVAL).

When i looked at the implementation source code(https://elixir.bootlin.com/linux/latest/source), i found out, that the only error's are (-ENOMEM, no memory and -ENOSPC(No more ID's).
I complile my code against : Linux ubuntu 4.15.0-33-generic.

```<code>#include <linux/module.h>
#include <linux/init.h>
#include <linux/idr.h>

struct idr map;

char *cptr1 = "Chennai";
char *cptr2 = "Lockheed Martin";
char *cptr3 = "Libary";

int deleter (int id, void *ptr, void *data ) {
    idr_remove( &map, id );
    return 0;
}

int showKeyValuePair( int id, void *ptr, void *data ) {
    printk("Key : %d | Value : %s\n", id, (char *)ptr );
    return 0;
}

static int __init mod_init(void)
{
    int id[3];
    char *ptr;

    printk("IDR\n");
    idr_init( &map );

    id[0] = idr_alloc( &map, (void *)cptr1, 0, 0, GFP_KERNEL );
    id[1] = idr_alloc( &map, (void *)cptr2, 0, 0, GFP_KERNEL );
    id[2] = idr_alloc( &map, (void *)cptr3, 0, 0, GFP_KERNEL );

    printk("Reserved ID's : {%d, %d, %d}\n", id[0], id[1], id[2] );

    ptr = idr_find( &map, id[0] );
    printk("Find for ID %d = %s\n", id[0], (ptr != NULL) ? ptr : "not found" );

    idr_for_each( &map, showKeyValuePair, NULL );

    return 0;
}

static void __exit mod_exit(void)
{
    idr_for_each( &map, deleter, NULL );
    idr_destroy( &map );        // void idr_destroy (struct idr *)
}

module_init(mod_init);
module_exit(mod_exit);
MODULE_LICENSE("GPL");
</code>```

答:
Ok i found out that the implementation in Linux ubuntu 4.15.0-33-generic was buggy. I compiled my code against the Kernel Source Tree version 4.9.0-8-amd64 and it worked out.
The code -EINVAL get returned when start, the third parameter of idr_alloc is smaller then 0, but that was not the case, but idr_alloc calls idr_alloc_cmn in the old version and this probably returned -EINVAL. I can't find the implementation of idr_alloc_cmn, but the most important thing: It works now.</p>

Body:
I'm trying out the Kernel API for IDR (Integer ID Management). It's a map where an ID get's associated with a pointer.
The API has changed, so old examples that i found, didn't work.
So i did my own example and it works only partially.
Sometimes the function idr_alloc fails with -22(-EINVAL).

When i looked at the implementation source code(https://elixir.bootlin.com/linux/latest/source), i found out, that the only error's are (-ENOMEM, no memory and -ENOSPC(No more ID's).
I complile my code against : Linux ubuntu 4.15.0-33-generic.

#include <linux/module.h>
#include <linux/init.h>
#include <linux/idr.h>

struct idr map;

char *cptr1 = "Chennai";
char *cptr2 = "Lockheed Martin";
char *cptr3 = "Libary";

int deleter (int id, void *ptr, void *data ) {
    idr_remove( &map, id );
    return 0;
}

int showKeyValuePair( int id, void *ptr, void *data ) {
    printk("Key : %d | Value : %s\n", id, (char *)ptr );
    return 0;
}

static int __init mod_init(void)
{
    int id[3];
    char *ptr;

    printk("IDR\n");
    idr_init( &map );

    id[0] = idr_alloc( &map, (void *)cptr1, 0, 0, GFP_KERNEL );
    id[1] = idr_alloc( &map, (void *)cptr2, 0, 0, GFP_KERNEL );
    id[2] = idr_alloc( &map, (void *)cptr3, 0, 0, GFP_KERNEL );

    printk("Reserved ID's : {%d, %d, %d}\n", id[0], id[1], id[2] );

    ptr = idr_find( &map, id[0] );
    printk("Find for ID %d = %s\n", id[0], (ptr != NULL) ? ptr : "not found" );

    idr_for_each( &map, showKeyValuePair, NULL );

    return 0;
}

static void __exit mod_exit(void)
{
    idr_for_each( &map, deleter, NULL );
    idr_destroy( &map );        // void idr_destroy (struct idr *)
}

module_init(mod_init);
module_exit(mod_exit);
MODULE_LICENSE("GPL");


问:
How to download all the dependencies of fabric-sdk-go?
I used command "go get github.com/hyperledger/fabric-sdk-go" to download fabric-sdk-go and its dependencies. No error happened.

In the golang documentation( https://golang.org/cmd/go/#hdr-Download_and_install_packages_and_dependencies ), it said that "Get downloads the packages named by the import paths, along with their dependencies. It then installs the named packages, like 'go install'."

So I originally thought that all the dependencies of fabric-sdk-go would be downloaded recursively. But the fact proved that I was wrong.

When I ran command "go install ./..." under fabric-sdk-go directory, many errors "cannot find package" were displayed:

So my questions are:

Does "go get" download dependencies recursively or not?

How to download all the dependencies of fabric-sdk-go, instead of using "go get [a_dependency_package]" to download every single dependency one by one?

Thanks very much.

答:
Does "go get" download dependencies recursively or not?

Yes it does. No need to worry or doubt the documentation

How to download all the dependencies of fabric-sdk-go, instead of using "go get [a_dependency_package]" to download every single dependency one by one?

Just use go modules: export GO111MODULE=on and build your code.


问:
Errors say that unexpected syntax error is that </script> is unexpected, and multiple HTML onclick events aren't defined
So I'm doing my assignment, due tomorrow (this is the extension aspect).
Two errors come up when I click buttons:

Uncaught ReferenceError: list is not defined
      at HTMLButtonElement.onclick

This happens with all of the functions I have.
2nd error is this:

Uncaught SyntaxError: Unexpected end of input

And apparently this error is this </script> tag.

I've tried changing code, functions and more but nothing seems to change.

```<code>  <body>
        <div id="navbar">
          <nav class="navbar navbar-inverse">
            <a href="/form.html">Tasks</a>
            <a href="/dbform.html">DB Tasks</a>
            <ul class-"nav navbar-nav">
              <li>
                <a href="/">Home Page</a>
              </li>
              <li>
                <a href="/welcome">Welcome!</a>
              </li>
              <li>
                <a href="list">List of tasks!</a>
              </li>
            </ul>
          </nav>
        </div>
        <h1>To Do List</h1>
        <h2>List your tasks</h2>
        <button onclick="list()">List all tasks</button>
        <h2>Add a task</h2>
        <p>
          <input type="text" placeholder="Task ID" id="taskId">
          <input type="text" placeholder="Task Description" id="taskDesc">

          <input type="button" value="Add task" onclick="addTask()">
        </p>
        <h2>Delete a task</h2>
        <p>
          <input type="text" placeholder="Task ID" id="taskId2">
          <input type="button" value="Delete task" onclick="deleteTask()">
        </p>
        <h2>Show your tasks in a table</h2>
        <p>
          <button onclick="makeTable()">Table To Do List</button>
          <table id="makeTable" border="1">
            <thead>
              <tr>
                <th align="left">ID</th>
                <th align="left">Description</th>
              </tr>
            </thead>
            <tbody id="tableBody">

            </tbody>
          </table>

        </p>
        <p id="msg">  </p>
        <script>
        /*
        This links the list from server.js to form.html.The fetch is used to fetch the localhost:3000/list
        link so all tasks can be displayed.
        */
        async function list() {
          let response =  await fetch('/tasks', {
            method: 'GET',
            headers: {
              "Content-Type": "application/json"
            }
          });

          let jsonPayload = await response.json();

          var data = document.getElementById("msg");
          data.innerHTML = JSON.stringify(jsonPayload);
        }
        /*
        This fetch(url) utilises the /add url so the textboxes essentially do the same thing
        as the /add?id=<number>&desc=<string>, so when the add task button is clicked, a task is added.
        */
        function addTask() {

          var url = "/tasks";

          //Puts all values inside the object.
          var data = {
            "id": taskId,
            "desc": taskDesc,
          }

          //This fetch requests take the url /tasks and fetches it using the POST method, which creates the tasks.
          fetch(url, {
            method: "POST",
            //The url tasks which is fetched with POST method uses req.bodyParser to get the data, so the data object - containing the information about the task, has been converted to JSON.
            body: JSON.stringify(data),
            headers: {
              "Content-Type": "application/json"
            }
          })
        /*
        This utilises the /delete url in the localhost website. It is like the add task button, except instead of
        doing the same thing as /add it does /delete. The fetch url "fetches" the /delete url.
        */
        function deleteTask() {
          //the variable "taskId", is the number submitted in the text box to delete the selected task.
          var taskId = document.getElementById("taskId2").value;

          //the url that is fetched with the taskId variable which deletes the function.
          var url = "/tasks/"+taskId;

          //fetches /tasks with the DELETE method
          fetch(url, {
            method: "DELETE",
            headers: {
              "Content-Type": "application/json"
            }
          });

          //display(); calls the display function to list the tasks again without the deleted tasks
          display();
        }

        async function makeTable() {
          let response = await fetch("http://localhost:3000/list");
          let data = await response.json();
          let tableBody = document.getElementById("tableBody");

          for (var i = data.length - 1; i > -1; i--) {
            let row = tableBody.insertRow(0);
            let col1 = row.insertCell(0);
            let col2 = row.insertCell(1);
            col1.innerHTML = data[i].id;
            col2.innerHTML = data[i].desc;
          }
        }
        </script>
      </body>
      </html>
</code>```

And the error is:

Uncaught ReferenceError: list is not defined
      at HTMLButtonElement.onclick

答:
Had a look at the whole thing...
Not very formatted as I did it very quickly but this seemed to remove some of the errors:

```<code><html>
<body>
        <div id="navbar">
          <nav class="navbar navbar-inverse">
            <a href="/form.html">Tasks</a>
            <a href="/dbform.html">DB Tasks</a>
            <ul class-"nav navbar-nav">
              <li>
                <a href="/">Home Page</a>
              </li>
              <li>
                <a href="/welcome">Welcome!</a>
              </li>
              <li>
                <a href="list">List of tasks!</a>
              </li>
            </ul>
          </nav>
        </div>
        <h1>To Do List</h1>
        <h2>List your tasks</h2>
        <button onclick="list()">List all tasks</button>
        <h2>Add a task</h2>
        <p>
          <input type="text" placeholder="Task ID" id="taskId">
          <input type="text" placeholder="Task Description" id="taskDesc">

          <input type="button" value="Add task" onclick="addTask()">
        </p>
        <h2>Delete a task</h2>
        <p>
          <input type="text" placeholder="Task ID" id="taskId2">
          <input type="button" value="Delete task" onclick="deleteTask()">
        </p>
        <h2>Show your tasks in a table</h2>
        <p>
          <button onclick="makeTable()">Table To Do List</button>
          <table id="makeTable" border="1">
            <thead>
              <tr>
                <th align="left">ID</th>
                <th align="left">Description</th>
              </tr>
            </thead>
            <tbody id="tableBody">

            </tbody>
          </table>

        </p>
        <p id="msg">  </p>

        <script>
        /*
        This links the list from server.js to form.html.The fetch is used to fetch the localhost:3000/list
        link so all tasks can be displayed.
        */
        async function list() {
          let response =  await fetch('/tasks', {
            method: 'GET',
            headers: {
              "Content-Type": "application/json"
            }
          });

          let jsonPayload = await response.json();

          var data = document.getElementById("msg");
          data.innerHTML = JSON.stringify(jsonPayload);
        }
        /*
        This fetch(url) utilises the /add url so the textboxes essentially do the same thing
        as the /add?id=<number>&desc=<string>, so when the add task button is clicked, a task is added.
        */
        function addTask() {

          var url = "/tasks";

          //Puts all values inside the object.
          var data = {
            "id": taskId,
            "desc": taskDesc,
          }

          //This fetch requests take the url /tasks and fetches it using the POST method, which creates the tasks.
          fetch(url, {
            method: "POST",
            //The url tasks which is fetched with POST method uses req.bodyParser to get the data, so the data object - containing the information about the task, has been converted to JSON.
            body: JSON.stringify(data),
            headers: {
              "Content-Type": "application/json"
            }
          })
        /*
        This utilises the /delete url in the localhost website. It is like the add task button, except instead of
        doing the same thing as /add it does /delete. The fetch url "fetches" the /delete url.
        */
        function deleteTask() {
          //the variable "taskId", is the number submitted in the text box to delete the selected task.
          var taskId = document.getElementById("taskId2").value;

          //the url that is fetched with the taskId variable which deletes the function.
          var url = "/tasks/"+taskId;

          //fetches /tasks with the DELETE method
          fetch(url, {
            method: "DELETE",
            headers: {
              "Content-Type": "application/json"
            }
          });

          //display(); calls the display function to list the tasks again without the deleted tasks
          display();
        }

        async function makeTable() {
          let response = await fetch("http://localhost:3000/list");
          let data = await response.json();
          let tableBody = document.getElementById("tableBody");

          for (var i = data.length - 1; i > -1; i--) {
            let row = tableBody.insertRow(0);
            let col1 = row.insertCell(0);
            let col2 = row.insertCell(1);
            col1.innerHTML = data[i].id;
            col2.innerHTML = data[i].desc;
          }
        }
        }
      </script>
      </body>
      </html>
</code>```

Sorry for the mess... tell me if this works or not I tried it in a basic HTML viewer so I don't know if it'll work :)

Body:
So I'm doing my assignment, due tomorrow (this is the extension aspect).
Two errors come up when I click buttons:

Uncaught ReferenceError: list is not defined
      at HTMLButtonElement.onclick

This happens with all of the functions I have.
2nd error is this:

Uncaught SyntaxError: Unexpected end of input

And apparently this error is this </script> tag.

I've tried changing code, functions and more but nothing seems to change.

            Tasks
            DB Tasks

                Home Page

                Welcome!

                List of tasks!

To Do List

List your tasks

        <button onclick="list()">List all tasks</button>

Add a task

          <input type="text" placeholder="Task ID" id="taskId">
          <input type="text" placeholder="Task Description" id="taskDesc">

          <input type="button" value="Add task" onclick="addTask()">

Delete a task

          <input type="text" placeholder="Task ID" id="taskId2">
          <input type="button" value="Delete task" onclick="deleteTask()">

Show your tasks in a table

          <button onclick="makeTable()">Table To Do List</button>

                ID
                Description

And the error is:

Uncaught ReferenceError: list is not defined
      at HTMLButtonElement.onclick

Body:
Had a look at the whole thing...
Not very formatted as I did it very quickly but this seemed to remove some of the errors:

<html>
<body>
        <div id="navbar">
          <nav class="navbar navbar-inverse">
            <a href="/form.html">Tasks</a>
            <a href="/dbform.html">DB Tasks</a>
            <ul class-"nav navbar-nav">
              <li>
                <a href="/">Home Page</a>
              </li>
              <li>
                <a href="/welcome">Welcome!</a>
              </li>
              <li>
                <a href="list">List of tasks!</a>
              </li>
            </ul>
          </nav>
        </div>
        <h1>To Do List</h1>
        <h2>List your tasks</h2>
        <button onclick="list()">List all tasks</button>
        <h2>Add a task</h2>
        <p>
          <input type="text" placeholder="Task ID" id="taskId">
          <input type="text" placeholder="Task Description" id="taskDesc">

          <input type="button" value="Add task" onclick="addTask()">
        </p>
        <h2>Delete a task</h2>
        <p>
          <input type="text" placeholder="Task ID" id="taskId2">
          <input type="button" value="Delete task" onclick="deleteTask()">
        </p>
        <h2>Show your tasks in a table</h2>
        <p>
          <button onclick="makeTable()">Table To Do List</button>
          <table id="makeTable" border="1">
            <thead>
              <tr>
                <th align="left">ID</th>
                <th align="left">Description</th>
              </tr>
            </thead>
            <tbody id="tableBody">

            </tbody>
          </table>

        </p>
        <p id="msg">  </p>

        <script>
        /*
        This links the list from server.js to form.html.The fetch is used to fetch the localhost:3000/list
        link so all tasks can be displayed.
        */
        async function list() {
          let response =  await fetch('/tasks', {
            method: 'GET',
            headers: {
              "Content-Type": "application/json"
            }
          });

          let jsonPayload = await response.json();

          var data = document.getElementById("msg");
          data.innerHTML = JSON.stringify(jsonPayload);
        }
        /*
        This fetch(url) utilises the /add url so the textboxes essentially do the same thing
        as the /add?id=<number>&desc=<string>, so when the add task button is clicked, a task is added.
        */
        function addTask() {

          var url = "/tasks";

          //Puts all values inside the object.
          var data = {
            "id": taskId,
            "desc": taskDesc,
          }

          //This fetch requests take the url /tasks and fetches it using the POST method, which creates the tasks.
          fetch(url, {
            method: "POST",
            //The url tasks which is fetched with POST method uses req.bodyParser to get the data, so the data object - containing the information about the task, has been converted to JSON.
            body: JSON.stringify(data),
            headers: {
              "Content-Type": "application/json"
            }
          })
        /*
        This utilises the /delete url in the localhost website. It is like the add task button, except instead of
        doing the same thing as /add it does /delete. The fetch url "fetches" the /delete url.
        */
        function deleteTask() {
          //the variable "taskId", is the number submitted in the text box to delete the selected task.
          var taskId = document.getElementById("taskId2").value;

          //the url that is fetched with the taskId variable which deletes the function.
          var url = "/tasks/"+taskId;

          //fetches /tasks with the DELETE method
          fetch(url, {
            method: "DELETE",
            headers: {
              "Content-Type": "application/json"
            }
          });

          //display(); calls the display function to list the tasks again without the deleted tasks
          display();
        }

        async function makeTable() {
          let response = await fetch("http://localhost:3000/list");
          let data = await response.json();
          let tableBody = document.getElementById("tableBody");

          for (var i = data.length - 1; i > -1; i--) {
            let row = tableBody.insertRow(0);
            let col1 = row.insertCell(0);
            let col2 = row.insertCell(1);
            col1.innerHTML = data[i].id;
            col2.innerHTML = data[i].desc;
          }
        }
        }
      </script>
      </body>
      </html>

Sorry for the mess... tell me if this works or not I tried it in a basic HTML viewer so I don't know if it'll work :)


问:
IOSApp unable to install
I try to deploy an app for my company use. So I do  Product->Archive, select the good distribution cert/profil. I upload the file on the web, make the link to the manifest.plist to .ipa and then I try to install it on my ipad but ... unable to intall:

UPDATE: I don't want to install it directly on a Ipad, but download it from an url with the ipad and I'm using entreprise developper program and it work if I directly build it for the ipad

Here the ios console Log :

I find strange that in the log after

INVALID >> { 642AFE.... this number is not the same there is in my
  ipa filename.

I also find strange to get many plist file (distribution, export ...) .

Here the folder i drop to the server :

Does anyone have some idea ?
thanks by adavance

答:
If you are using the normal developer account then to install the application in device(either directly or from any third party sites) you have to sign the archive file either with development profile of AdHoc distribution profile. Here if you have selected the Appstore distribution certificate and profile then the application will not be able to install in any device.

If the device's UDID is added to the profile(development or AdHoc distribution) then you can install the app directly using Xcode or via an URL.

If you are using the enterprise program and the application is signed with the distribution certificate and profile then the application can be install in any device regardless of the existence of UDID in the profile.

Please check the profile when you are archiving the ipa.

Hope this helps you in some way.

Title: IOSApp unable to install


答:
'a' is not same as 'a ' .The name attribute contains CDATA. It can be more or less anything you like. (You shouldn't include leading or tailing white space because user agents can ignore it, but white space in the middle is fine).what i should use as name attributes

$("input[type='radio']").each(function () {
    if ($(this).is(":checked")) {
    $(this).addClass("some");
   }
 });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  .some {
      background-color:#06c!important;
  }</code>```

<input name="a" type="radio">
<input name="a"type="radio" checked>```

Title: Radio buttons are not switching

Body:
'a' is not same as 'a ' .The name attribute contains CDATA. It can be more or less anything you like. (You shouldn't include leading or tailing white space because user agents can ignore it, but white space in the middle is fine).what i should use as name attributes

$("input[type='radio']").each(function () {
    if ($(this).is(":checked")) {
    $(this).addClass("some");
   }
 });

  .some {
      background-color:#06c!important;
  }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<input name="a" type="radio">
<input name="a"type="radio" checked>


问:
SQL issue - how do I select all tuples which contain all references in a second table?
Heres the deal - I have three tables here:

```<code>Companies:
ID | NAME | DETAILS

TAGS
ID | TAGNAME

TAGS_COMPANIES
COMPANY_ID | TAGID
</code>```

Using a nested query I can retrieve all companies that are tagged by tags in a certain set i.e:

```<code>select c.* from companies c where c.id in (select t.company_id where t.tagid in (12,43,67))
</code>```

The above query returns all companies that have an either tag id 12, 43 or 67 but I need to retrieve all companies who are tagged 12 AND 43 AND 67

How would I redo my query here? I'm using MySQL

答:
With one subquery.

```<code>select c.*
      from companies c
      where (c.id, 3) in
         (select t.company_id, count(distinct t.tagid)
                 from tags t
           where t.tagid in (12,43,67)
             group by t.company_id)
</code>```

magic number 3 means different tags count.

Body:
Heres the deal - I have three tables here:

Companies:
ID | NAME | DETAILS

TAGS
ID | TAGNAME

TAGS_COMPANIES
COMPANY_ID | TAGID

Using a nested query I can retrieve all companies that are tagged by tags in a certain set i.e:

select c.* from companies c where c.id in (select t.company_id where t.tagid in (12,43,67))

The above query returns all companies that have an either tag id 12, 43 or 67 but I need to retrieve all companies who are tagged 12 AND 43 AND 67

How would I redo my query here? I'm using MySQL

Body:
With one subquery.

select c.*
      from companies c
      where (c.id, 3) in
         (select t.company_id, count(distinct t.tagid)
                 from tags t
           where t.tagid in (12,43,67)
             group by t.company_id)

magic number 3 means different tags count.


问:
Combine the result of 2 SELECT in one
I have 2 selects:

```<code>SELECT *
FROM driverdetails
WHERE driverdetails.driverid = '32bbdbe8-eda0-32a5-92c0-f9215e24edcf'

SELECT *
FROM location
WHERE location.utc = (  SELECT MAX(location.utc)
                        FROM location
                        WHERE location.driverid = '32bbdbe8-eda0-32a5-92c0-f9215e24edcf'
                    );
</code>```

And I am trying to have a single result like:
Columns from select1 + columns from select 2

How do I achieve the columns one after another by keeping all conditions from example?

答:
```<code>SELECT *
FROM driverdetails
INNER JOIN location ON location.driverid = driverdetails.driverid
WHERE driverdetails.driverid = '32bbdbe8-eda0-32a5-92c0-f9215e24edcf'
</code>```

On the above, you will get joined one. But as per your condition, it need a MAX(location.utc)

so for that, you need to create a temporary table on the query

```<code>SELECT *
FROM driverdetails
INNER JOIN (
             SELECT *,MAX(location.utc) as maxUTC
             FROM location
             GROUP BY location.driverid
           ) as location_temp ON location_temp.driverid = driverdetails.driverid
WHERE driverdetails.driverid = '32bbdbe8-eda0-32a5-92c0-f9215e24edcf'
</code>```

Hope this works for you.

Title: Combine the result of 2 SELECT in one

Body:
I have 2 selects:

SELECT *
FROM driverdetails
WHERE driverdetails.driverid = '32bbdbe8-eda0-32a5-92c0-f9215e24edcf'

SELECT *
FROM location
WHERE location.utc = (  SELECT MAX(location.utc)
                        FROM location
                        WHERE location.driverid = '32bbdbe8-eda0-32a5-92c0-f9215e24edcf'
                    );

And I am trying to have a single result like:
Columns from select1 + columns from select 2

How do I achieve the columns one after another by keeping all conditions from example?

Body:
SELECT *
FROM driverdetails
INNER JOIN location ON location.driverid = driverdetails.driverid
WHERE driverdetails.driverid = '32bbdbe8-eda0-32a5-92c0-f9215e24edcf'

On the above, you will get joined one. But as per your condition, it need a MAX(location.utc)

so for that, you need to create a temporary table on the query

SELECT *
FROM driverdetails
INNER JOIN (
             SELECT *,MAX(location.utc) as maxUTC
             FROM location
             GROUP BY location.driverid
           ) as location_temp ON location_temp.driverid = driverdetails.driverid
WHERE driverdetails.driverid = '32bbdbe8-eda0-32a5-92c0-f9215e24edcf'

Hope this works for you.


问:
Should the Eigen-unsupported modules be avoided?
The popular linear algebra library Eigen comes with a long list of so-called "unsupported" modules, for example modules for FFT, numerical differentiation or Euler angles.

In the Eigen documentation, it is clearly stated:

These modules are contributions from various users. They are provided "as is", without any support.

Unfortunately, there is no statement in the documentation about potential discontinuation of unsupported modules, requirements to the quality of implementation, level of testing, and so on.

This leaves me with the following question:

Should I be using Eigen unsupported modules at all, if I want my software to be stable for a few years (and at least to be compatible with future major/minor Eigen releases). Example: in particular, I would like to avoid the situation that an unsupported module I am using drops away when upgrading from Eigen 3.7.x to 3.8.x, for instance.

Are there any experiences or opinions out there regarding the stability and availability of the unsupported modules?

(Just for completeness: the particular unsupported module I am considering is the EulerAngles module).

答:
Unfortunately, there is no statement in the documentation about potential discontinuation of unsupported modules, requirements to the quality of implementation, level of testing, and so on.

Since unsupported modules are provided "as is" their testing coverage and maybe even quality can heavily differ. All modules, unsupported or not, are tested. However, there are modules that are very frequently used and others that might be not used that often. This results in a variety of experiences the community has with different unsupported modules. Very popular modules are likely to be well tested just because there is a high chance that someone stepped over some corner case while using it.

Are there any experiences or opinions out there regarding the
  stability and availability of the unsupported modules?

An example for a widely adopted module is the unsupported Tensor module which is used in the core parts of Google's Tensorflow.

However, there are no guarantees about the ABI or API stability of unsupported modules. E.g., an unsupported module could get merged into the supported part which could lead to (at least) API changes.

Should I be using Eigen unsupported modules at all, if I want my
  software to be stable for a few years (and at least to be compatible
  with future major/minor Eigen releases).

It's hard to answer that somewhat broad question. If you really depend on stability for years you maybe should avoid unsupported modules. However this is in no sense a general advice and depends on your specific needs and the module you plan to use.

If you plan to use an unsupported module as a critical part of your application, you should probably keep an eye on updates (e.g. check Eigen's changelog or watch pull requests).


问:
“No 'Access-Control-Allow-Origin' header is present” error for some requests but not others
I have a VueJS app running on S3 that is served by a Flask-powered API running on AWS Elastic Beastalk.

The problem

When making some requests, I get the following:

```<code>Access to XMLHttpRequest at 'https://api.myflaskapi.net/blueprint/get_info?date=2019-01-01' from origin 'https://app.myvuejsapp.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

What I've done so far

In my __init__.py file, initialized by the app factory in Flask I have set CORS(app, support_credentials=True) as the example on this link. With that, I would hope that basically any request would have the CORS heading, so I wouldn't have any policy blocking my frontend requests.

The ideal scenario would be to only allow requests from https://app.myvuejsapp.net, so I tried using CORS(app, support_credentials=True, origins=['https://app.myvuejsapp.net']) but also without success.

I've also tried making one CORS instance for each of my blueprints with CORS(myblueprint) for each .py route file (I have one for each blueprint), also without success.

The strange thing is, I do have one function on Vue that runs when the app is mounted that works just fine. I can't see any difference between this and other functions that won't work.

Example of working function (returns true or false from the backend):

```<code>      checkDB() {
        const path = this.base_url + 'blueprint/check_db'
        axios.get(path, this.token)
          .then(checkupd => {
            this.isupdated = Boolean(checkupd.data);
            if (this.isupdated == true) {
              this.update_msg = "Database up to date."
              this.loading = false
              this.finished = true
            } else {
              this.update_msg = "WARNING: Check DB status."
            }
          })
          .catch(error => {
            console.log(error)
          })
      },
</code>```

Example of non-working function (returns a XLS from the backend):

```<code>      getSalesFrom(file) {
        const fs = require('fs')
        const FileDownload = require('js-file-download');
        const path = this.base_url + `blueprint/get_sales?date=${this.date}`
        axios.get(path, {
            headers:
              {
                "X-Access-Token": "mytoken",
                "Content-Type": "application/json"
              },
            responseType: 'blob'
          })
          .then(response => {
            const content = response.headers['content-type'];
            download(response.data, 'text.xlsx', content)
          })
          .catch(error => {
            console.log(error)
          })
        this.export_dialog = false
      }
</code>```

S3 CORS Configuration XML

```<code><?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>Authorization</AllowedHeader>
    <AllowedHeader>Content-Length</AllowedHeader>
    <AllowedHeader>Access-Control-Allow-Origin</AllowedHeader>
    <AllowedHeader>X-Access-Token</AllowedHeader>
</CORSRule>
</CORSConfiguration>
</code>```

Any ideas on what I might be doing wrong?
I've been reading for a while, but can't seem to find a solution for what it seems a pretty simple problem... Maybe I should mess with the S3 bucket permission configuration?

Thanks.

答:
As I understand correctly you host your Vue.js application from S3.

You need to include CORS headers in your S3 buckets. Without them the browser will block all requests to your Flask application. You are making requests to api.myflaskapi.net from app.myvuejsapp.net so you need configure CORS in app.myvuejsapp.net.

You can read documentation how to set CORS in S3 here and here.

To configure your bucket to allow cross-origin requests, you create a CORS configuration, which is an XML document with rules that identify the origins that you will allow to access your bucket, the operations (HTTP methods) that will support for each origin, and other operation-specific information.

You can add up to 100 rules to the configuration. You add the XML document as the cors subresource to the bucket either programmatically or by using the Amazon S3 console. For more information, see Enabling Cross-Origin Resource Sharing (CORS).

Body:
I have a VueJS app running on S3 that is served by a Flask-powered API running on AWS Elastic Beastalk.

The problem

When making some requests, I get the following:

Access to XMLHttpRequest at 'https://api.myflaskapi.net/blueprint/get_info?date=2019-01-01' from origin 'https://app.myvuejsapp.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

What I've done so far

In my __init__.py file, initialized by the app factory in Flask I have set CORS(app, support_credentials=True) as the example on this link. With that, I would hope that basically any request would have the CORS heading, so I wouldn't have any policy blocking my frontend requests.

The ideal scenario would be to only allow requests from https://app.myvuejsapp.net, so I tried using CORS(app, support_credentials=True, origins=['https://app.myvuejsapp.net']) but also without success.

I've also tried making one CORS instance for each of my blueprints with CORS(myblueprint) for each .py route file (I have one for each blueprint), also without success.

The strange thing is, I do have one function on Vue that runs when the app is mounted that works just fine. I can't see any difference between this and other functions that won't work.

Example of working function (returns true or false from the backend):

      checkDB() {
        const path = this.base_url + 'blueprint/check_db'
        axios.get(path, this.token)
          .then(checkupd => {
            this.isupdated = Boolean(checkupd.data);
            if (this.isupdated == true) {
              this.update_msg = "Database up to date."
              this.loading = false
              this.finished = true
            } else {
              this.update_msg = "WARNING: Check DB status."
            }
          })
          .catch(error => {
            console.log(error)
          })
      },

Example of non-working function (returns a XLS from the backend):

      getSalesFrom(file) {
        const fs = require('fs')
        const FileDownload = require('js-file-download');
        const path = this.base_url + `blueprint/get_sales?date=${this.date}`
        axios.get(path, {
            headers:
              {
                "X-Access-Token": "mytoken",
                "Content-Type": "application/json"
              },
            responseType: 'blob'
          })
          .then(response => {
            const content = response.headers['content-type'];
            download(response.data, 'text.xlsx', content)
          })
          .catch(error => {
            console.log(error)
          })
        this.export_dialog = false
      }

S3 CORS Configuration XML

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>Authorization</AllowedHeader>
    <AllowedHeader>Content-Length</AllowedHeader>
    <AllowedHeader>Access-Control-Allow-Origin</AllowedHeader>
    <AllowedHeader>X-Access-Token</AllowedHeader>
</CORSRule>
</CORSConfiguration>

Any ideas on what I might be doing wrong?
I've been reading for a while, but can't seem to find a solution for what it seems a pretty simple problem... Maybe I should mess with the S3 bucket permission configuration?

Thanks.


问:
Create a class with fields automatic in TypeScript
See my code:

```<code>interface IMyInterface{
  a:string
  b:string
  c:number
  //and more...
}
class MyClass extends IMyInterface{ //err 1
  //the class has all fields from IMyInterface
  constructor(opt:IMyInterface){
    for(let key in opt){
      this[key]=opt[key] //err2
    }
  }
  myOtherMethods(){}
}
</code>```

I want a class has all fields extends from an interface(returned from a HTTP request) and auto construct it with values. Above code has 2 errors:

Classes can not extends an interface, but if I use implements, I need to write all fields and types in the class again.

The type of the key is string, and I can not access the field trough it on this.

答:
Maybe rewrite IMyInterface to be class and then extend eg

```<code>class BaseClass {
  public a: string = 'foo';
}

class MyClass extends BaseClass {
  constructor() {
    super();
    console.log(this.a); // 'foo'
  }

  public someMethod() {
    console.log(this.a); // 'foo'
  }
}
</code>```

Interfaces are type information only. They don't have any semantic meaning (like default value)

Body:
See my code:

interface IMyInterface{
  a:string
  b:string
  c:number
  //and more...
}
class MyClass extends IMyInterface{ //err 1
  //the class has all fields from IMyInterface
  constructor(opt:IMyInterface){
    for(let key in opt){
      this[key]=opt[key] //err2
    }
  }
  myOtherMethods(){}
}

I want a class has all fields extends from an interface(returned from a HTTP request) and auto construct it with values. Above code has 2 errors:

Classes can not extends an interface, but if I use implements, I need to write all fields and types in the class again.

The type of the key is string, and I can not access the field trough it on this.

Body:
Maybe rewrite IMyInterface to be class and then extend eg

class BaseClass {
  public a: string = 'foo';
}

class MyClass extends BaseClass {
  constructor() {
    super();
    console.log(this.a); // 'foo'
  }

  public someMethod() {
    console.log(this.a); // 'foo'
  }
}

Interfaces are type information only. They don't have any semantic meaning (like default value)


问:
difference between 2 different implementations of declaring structures
```<code>gcc 4.4.4
c89
</code>```

I am wondering what is the real difference between the following 2 implementations of defining structures?

```<code>channel.h file

struct channel_tag;

struct channel_tag* init_channel(size_t channel_id);
void dispose_channels(struct channel_tag *channel);

channel.c file

typedef struct channel_tag {
    size_t channel_id;
} channel_t;
</code>```

=================== Second implemenation ===============

```<code>channel.h file

typedef struct channel_tag channel;

channel* init_channel(size_t channel_id);
void dispose_channels(channel *channel);

channel.c file

struct channel_tag {
    size_t channel_id;
};
</code>```

Many thanks for any suggestions,

答: There is nothing different in the implementations. Its just a matter of choice. I prefer the second one in terms of readability. The extra "_tag" is ugly. Linux kernel coding style prefers all structure definitions without typedef. </p>

Body:
gcc 4.4.4
c89

I am wondering what is the real difference between the following 2 implementations of defining structures?

channel.h file

struct channel_tag;

struct channel_tag* init_channel(size_t channel_id);
void dispose_channels(struct channel_tag *channel);

channel.c file

typedef struct channel_tag {
    size_t channel_id;
} channel_t;

=================== Second implemenation ===============

channel.h file

typedef struct channel_tag channel;

channel* init_channel(size_t channel_id);
void dispose_channels(channel *channel);

channel.c file

struct channel_tag {
    size_t channel_id;
};

Many thanks for any suggestions,


问:
How to write to one value in a JSON file with LibGDX
For example, if I have this JSON file:

```<code>{
  "player": {
    "gold":100,
    "diamonds":100,
    "username":"placeholder"
  }
}
</code>```

And the player's gold amount was modified and I wanted to overwrite ONLY the gold value, how would I code that?

Here is what I have so far but it overwrites the whole JSON file, whereas I only want to overwrite one value.

```<code>   public void save(Player player, String path) {
        Json json = new Json();
        String txt = json.toJson(player);
        FileHandle file = Gdx.files.local(path);
        file.writeString(json.prettyPrint(txt), true);
    }
</code>```

答:
You've to overwrite the complete file so it's better to use a separate file for your player.

Like this player.json

```<code>{
    "gold":100,
    "diamonds":100,
    "username":"placeholder"
}
</code>```

And Player.java

```<code>public class Player {

    public int gold;
    public int diamonds;
    public String username;
}
</code>```

Use below code that will modify and save data to a json file.

```<code>Json json = new Json();
FileHandle file = Gdx.files.local("player.json");
Player player = file.exists()? json.fromJson(Player.class,file) : new Player();
player.gold=300;       // modify player data

save(player,file);
</code>```

After then call save method, given below :

```<code>private void save(Player player, FileHandle file) {
    Json json = new Json();
    json.setTypeName(null);
    json.setUsePrototypes(false);
    json.setIgnoreUnknownFields(true);
    json.setOutputType(JsonWriter.OutputType.json);

    String txt = json.toJson(player);
    file.writeString(json.prettyPrint(txt), false);
}
</code>```

Body:
For example, if I have this JSON file:

{
  "player": {
    "gold":100,
    "diamonds":100,
    "username":"placeholder"
  }
}

And the player's gold amount was modified and I wanted to overwrite ONLY the gold value, how would I code that?

Here is what I have so far but it overwrites the whole JSON file, whereas I only want to overwrite one value.

   public void save(Player player, String path) {
        Json json = new Json();
        String txt = json.toJson(player);
        FileHandle file = Gdx.files.local(path);
        file.writeString(json.prettyPrint(txt), true);
    }

Body:
You've to overwrite the complete file so it's better to use a separate file for your player.

Like this player.json

{
    "gold":100,
    "diamonds":100,
    "username":"placeholder"
}

And Player.java

public class Player {

    public int gold;
    public int diamonds;
    public String username;
}

Use below code that will modify and save data to a json file.

Json json = new Json();
FileHandle file = Gdx.files.local("player.json");
Player player = file.exists()? json.fromJson(Player.class,file) : new Player();
player.gold=300;       // modify player data

save(player,file);

After then call save method, given below :

private void save(Player player, FileHandle file) {
    Json json = new Json();
    json.setTypeName(null);
    json.setUsePrototypes(false);
    json.setIgnoreUnknownFields(true);
    json.setOutputType(JsonWriter.OutputType.json);

    String txt = json.toJson(player);
    file.writeString(json.prettyPrint(txt), false);
}


问:
Is there a way to combine multiple powerbi api requests in to a single restapi call? Something like a batch request to get a collective response?
I'm trying to reduce the api calls to fetch data out of powerbi rest api. when i call endpoint like /Groups, The response is straight forward in a single api call, I get all the groups. in order to get datasets,dashboards and reports i'll have to pass every group id to endpoints of reports,datasets.,etc.

eg.
GET https://api.powerbi.com/v1.0/myorg/groups/{groupId}/datasets

Is there a way to combine these requests, such a way that i send multiple group ids in a single api call to get all the datasets from their respective groups?

I have not found a way to combine it all together to make a single batch api call.

However, I tried a different endpoint found from MSDocs to avoid input of group id.

GET https://api.powerbi.com/v1.0/myorg/datasets

But the problem with this is, the response wont have information of which group the dataset belongs to. without group information,the retrieved data wont be useful for me.

https://learn.microsoft.com/en-us/rest/api/power-bi/datasets

答:
You must use the admin part of the API. To get a list of all groups in your organization, call GetGroupsAsAdmin (you can filter what you want to get too). Similarly, call GetDatasetsAsAdmin to get list of datasets. Look at their webUrl property to find their group.

https://api.powerbi.com/v1.0/myorg/datasets wont return all datasets (or datasets from multiple groups) but will give you the datasets located in your own My workspace.


问:
Is it ok to unit-test an abstract class by instantiating it as a mock object?
It has come to my attention that you can unit-test an abstract class by instantiating it as a mock object. Thereby you mock the abstract properties and methods, while being able to test the implemented ones.

However, I am accustomed to distinguish between the class to test and the injected dependencies to mock/stub. So, in this early stage of my new enlightenment I wonder if there are any pitfalls to this way of testing?? Any thoughts on this?

Regards,
Morten

答:
Instead of using inheritance to combine two classes, see if you can use composition.

So instead of this:

```<code>abstract class PaySalary {
    payAmount(decimal money) {
        if (transferAmount(money)) {
            isPaid = true;
        }
    }

    abstract void transferAmount(decimal money);
}
</code>```

Do this:

```<code>class PaySalary {
    public MoneyTransferrer;

    payAmount(decimal money) {
        if (MoneyTransferrer.transferAmount(money)) {
            isPaid = true;
        }
    }
}
</code>```

This way, you don't have to inherit the class in your unit test, but you can simply mock a MoneyTransferrer. You can also test the MoneyTransferrer without depending on the base class.

Body:
Instead of using inheritance to combine two classes, see if you can use composition.

So instead of this:

abstract class PaySalary {
    payAmount(decimal money) {
        if (transferAmount(money)) {
            isPaid = true;
        }
    }

    abstract void transferAmount(decimal money);
}

Do this:

class PaySalary {
    public MoneyTransferrer;

    payAmount(decimal money) {
        if (MoneyTransferrer.transferAmount(money)) {
            isPaid = true;
        }
    }
}

This way, you don't have to inherit the class in your unit test, but you can simply mock a MoneyTransferrer. You can also test the MoneyTransferrer without depending on the base class.