问:
Is there any simple way to create a list of formula in R
Here I want to create a list of formula for a simple linear regression, 2nd and 3rd order polynomial models. I just did this. It could be ok for a few variables but my data is a quite lot variables. So how could I avoid overloading work using another way to do the same thing?

```<code>ind1.lm <- lm(dep ~ ind1, data = df)
ind1.qd <- lm(dep ~ poly(ind1, 2, raw = TRUE), data = df)
ind1.cb <- lm(dep ~ poly(ind1, 3, raw = TRUE), data = df)

ind2.lm <- lm(dep ~ ind2, data = datAll)
ind2.qd <- lm(dep ~ poly(ind2, 2, raw = TRUE), data = df)
ind2.cb <- lm(dep ~ poly(ind2, 3, raw = TRUE), data = df)

ind3.lm <- lm(dep ~ ind3, data = df)
ind3.qd <- lm(dep ~ poly(ind3, 2, raw = TRUE), data = df)
ind3.cb <- lm(dep ~ poly(ind3, 3, raw = TRUE), data = df)

formula.list <- list(as.formula(ind1.lm), as.formula(ind1.qd),
    as.formula(ind1.cb), as.formula(ind2.lm), as.formula(ind2.qd),
    as.formula(ind2.cb), as.formula(ind3.lm), as.formula(ind3.qd),
    as.formula(ind3.cb))

 formula.list
</code>```

Thanks in advance!

答:
Define the independent variables and the formats of the formulas and from that we can get the formula strings.  Since lm accepts strings as formulas we can then apply over that giving a list of lm objects whose names are the formulas.

```<code>ind <- c("ind1", "ind2", "ind3")
fmt <- c("dep ~ %s",
         "dep ~ poly(%s, 2, raw=TRUE)",
         "dep ~ poly(%s, 3, raw=TRUE)")

fo.strings <- c(outer(fmt, ind, sprintf))

sapply(fo.strings, lm, data = df, simplify = FALSE)
</code>```

Questions to SO should include reproducible code and df was omitted from the question but we can run it using the builtin anscombe data frame like this:

```<code>fmt <- c("y1~ %s",
         "y1~ poly(%s, 2, raw=TRUE)",
         "y1 ~ poly(%s, 2, raw=TRUE)")
ind <- c("x1", "x2", "x3")
fo.strings <- c(outer(fmt, ind, sprintf))
sapply(fo.strings, lm, data = anscombe, simplify = FALSE)
</code>```

Body:
Here I want to create a list of formula for a simple linear regression, 2nd and 3rd order polynomial models. I just did this. It could be ok for a few variables but my data is a quite lot variables. So how could I avoid overloading work using another way to do the same thing?

ind1.lm <- lm(dep ~ ind1, data = df)
ind1.qd <- lm(dep ~ poly(ind1, 2, raw = TRUE), data = df)
ind1.cb <- lm(dep ~ poly(ind1, 3, raw = TRUE), data = df)

ind2.lm <- lm(dep ~ ind2, data = datAll)
ind2.qd <- lm(dep ~ poly(ind2, 2, raw = TRUE), data = df)
ind2.cb <- lm(dep ~ poly(ind2, 3, raw = TRUE), data = df)

ind3.lm <- lm(dep ~ ind3, data = df)
ind3.qd <- lm(dep ~ poly(ind3, 2, raw = TRUE), data = df)
ind3.cb <- lm(dep ~ poly(ind3, 3, raw = TRUE), data = df)

formula.list <- list(as.formula(ind1.lm), as.formula(ind1.qd),
    as.formula(ind1.cb), as.formula(ind2.lm), as.formula(ind2.qd),
    as.formula(ind2.cb), as.formula(ind3.lm), as.formula(ind3.qd),
    as.formula(ind3.cb))

 formula.list

Thanks in advance!

Body:
Define the independent variables and the formats of the formulas and from that we can get the formula strings.  Since lm accepts strings as formulas we can then apply over that giving a list of lm objects whose names are the formulas.

ind <- c("ind1", "ind2", "ind3")
fmt <- c("dep ~ %s",
         "dep ~ poly(%s, 2, raw=TRUE)",
         "dep ~ poly(%s, 3, raw=TRUE)")

fo.strings <- c(outer(fmt, ind, sprintf))

sapply(fo.strings, lm, data = df, simplify = FALSE)

Questions to SO should include reproducible code and df was omitted from the question but we can run it using the builtin anscombe data frame like this:

fmt <- c("y1~ %s",
         "y1~ poly(%s, 2, raw=TRUE)",
         "y1 ~ poly(%s, 2, raw=TRUE)")
ind <- c("x1", "x2", "x3")
fo.strings <- c(outer(fmt, ind, sprintf))
sapply(fo.strings, lm, data = anscombe, simplify = FALSE)


来源: stackexchange

问:
How can I access/process content within TensorFlow Datasets?
I am working with the cnn_dailymail dataset which is part of the TensorFlow Datasets.
I access it as follows:

```<code>import tensorflow_datasets as tfds
data, info = tfds.load('cnn_dailymail', with_info=True)
train_data, test_data = data['train'], data['test']
</code>```

To extract a single example from the dataset I use:

```<code>cnn_ex, = train_data.take(1)
cnn_ex['highlights'].numpy()
</code>```

This will return a string similar to this: "emma monaghan, 27, from glasgow, used to weigh 18st 5lbs .". I would like to apply some pre-processing steps to this dataset so I can use it as an input into a deep learning algorithm. The example above should look like this after preprocessing: "<start> emma monaghan, 27, from glasgow, used to weigh 18st 5lbs . <end>".

Is there a way to access and pre-process all the text (within train_data) at once without having to apply the take() function multiple times? For example converting the TensorFlow Dataset into a numpy array would already help. Thanks!

答:
It depends on your particular objective. Maybe tfds.as_numpy() is what you're looking for. You can apply it to train_data to get a generator_object. You can iterate over it directly, or apply any map function

```<code>train_data = train_data.map(map_func)
for i in tfds.as_numpy(train_data):
    print(i)
    ...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am working with the cnn_dailymail dataset which is part of the TensorFlow Datasets.
I access it as follows:

import tensorflow_datasets as tfds
data, info = tfds.load('cnn_dailymail', with_info=True)
train_data, test_data = data['train'], data['test']

To extract a single example from the dataset I use:

cnn_ex, = train_data.take(1)
cnn_ex['highlights'].numpy()

This will return a string similar to this: "emma monaghan, 27, from glasgow, used to weigh 18st 5lbs .". I would like to apply some pre-processing steps to this dataset so I can use it as an input into a deep learning algorithm. The example above should look like this after preprocessing: "<start> emma monaghan, 27, from glasgow, used to weigh 18st 5lbs . <end>".

Is there a way to access and pre-process all the text (within train_data) at once without having to apply the take() function multiple times? For example converting the TensorFlow Dataset into a numpy array would already help. Thanks!

Body:
It depends on your particular objective. Maybe tfds.as_numpy() is what you're looking for. You can apply it to train_data to get a generator_object. You can iterate over it directly, or apply any map function

train_data = train_data.map(map_func)
for i in tfds.as_numpy(train_data):
    print(i)
    ...


问:
How to update only one row in a table?
How to I can update only one record in a table?

Table:

```<code>name       name1       name2
----------------------------
xx         xy          xz
xx         xx          xx
xx         xx          xx
xx         xx          xx
xy         xx          zz
</code>```

Update query:

```<code>UPDATE table1
SET name2 = '01'
WHERE name1='xx'
</code>```

I need update only one row per time.

答:
Please use subquery operating on primary key for better performance</p>

```<code>-- INVALID, BUT EXPECTED: update "user" set email = 'login@com.com' where email = 'login2@com2.com' limit 1

update "user' set email = 'login2@com2.pl' where id = (select id from "user" where email = 'login@com.com' limit 1)
</code>```

Title: How to update only one row in a table?

Body:
How to I can update only one record in a table?

Table:

name       name1       name2
----------------------------
xx         xy          xz
xx         xx          xx
xx         xx          xx
xx         xx          xx
xy         xx          zz

Update query:

UPDATE table1
SET name2 = '01'
WHERE name1='xx'

I need update only one row per time.

Body:
Please use subquery operating on primary key for better performance

-- INVALID, BUT EXPECTED: update "user" set email = 'login@com.com' where email = 'login2@com2.com' limit 1

update "user' set email = 'login2@com2.pl' where id = (select id from "user" where email = 'login@com.com' limit 1)


问:
RAFT consensus protocol - Should entries be durable before commiting
I have the following query about implementation RAFT:

Consider the following scenario\implementation:

RAFT leader receives a command entry, it appends the entry to an
in-memory array It then sends the entries to followers (with the
heartbeat)

The followers receive the entry and append it to their
in-memory array and then send a response that it has received the
entry

The leader then commits the entry by writing it to a durable
store (file) The leader sends the latest commit index in the
heartbeat

The followers then commit the entries based on leader's
commit index by storing the entry to their durable store (file)

One of the implementations of RAFT (link: https://github.com/peterbourgon/raft/) seems to implement it this way.  I wanted to confirm if this fine.

Is it OK  if entries are maintained "in memory" by the leader and the followers until it is committed? In what circumstances might this scenario fail?

答:
I think entries should be durable before commiting.

Let's take the Figure 8(e) of the Raft extended paper as an example. If entries are durable when committed, then:

S1 replicates 4 to S2 and S3 then commit 2 and 4.

All servers crash. Because S2 and S3 don't know S1 has commited 2 and 4, they won't commit 2 and 4. Therefore S1 has commited 1,2,4, S2, S3, S4, S5 has commited 1.

All servers restart except S1.

Because only commited entries are durable, S2, S3, S4, S5 have the same single entry: 1.

S2 is elected as the leader.

S2 replicates a new entry to all other servers except the crashed S1.

S1 restarts. Because S2's entries are newer than S1, so S1's 2 and 4 are replaced by the previous new entry.

As a result, the commited entries 2 and 4 are lost. So I think the un-commited entries should be also durable.

ContentLicense: CC BY-SA 3.0


问:
Need to display the max price and company that has it
So, i just started working with python and i need to display the maximum price and the company that has it. I got the data from an CSV file that has multiple columns that describes some cars. I'm only interested in two of them: price and company.

I need to display the maximum price and the company that has it. Some advice?
This is what i tried and I don't know how to get the company too, not only the maximum price.

import pandas as pd
df = pd.read_csv("Automobile_data.csv")
for x in df['price']:
    if x == df['price'].max():
       print(x)
```

答:
That is how not to use Pandas. Pandas is made to avoid loops

```<code>import pandas as pd
df = pd.read_csv("Automobile_data.csv")

max_price = df[df['price'] == df['price'].max()]
print(max_price)
</code>```

That is how you would do it. If you only want price and company

```<code>print(max_price[['company','price']])
</code>```

Explanation: we create a boolean filter that true if the price is equal to maximum price. We use this as a mask to catch what we need.

Body:
That is how not to use Pandas. Pandas is made to avoid loops

import pandas as pd
df = pd.read_csv("Automobile_data.csv")

max_price = df[df['price'] == df['price'].max()]
print(max_price)

That is how you would do it. If you only want price and company

print(max_price[['company','price']])

Explanation: we create a boolean filter that true if the price is equal to maximum price. We use this as a mask to catch what we need.


问:
Problem with understanding usage of identify
i need to paint a graph using LakeHuron data in R, single paiting is easy just

```<code>df= data.frame(LakeHuron)
plot(df)
</code>```

but I need to use identify to sign the years where the point of water was the highest and the lowest

```<code>df=data.frame(LakeHuron)
df
plot(df)
minimum = min(df)
maximum = max(df)
</code>```

I got those minimum and maximum variables, but how can i use identify to point them on plot?

答:
If you are trying to label the years, it may be easiest to do that with text.

```<code>Xmin = which.min(df$LakeHuron)
Xmax = which.max(df$LakeHuron)
Years = 1875:1972

plot(df)
text(x=Years[c(Xmin, Xmax)], y = LakeHuron[c(Xmin, Xmax)],
    labels=Years[c(Xmin, Xmax)], pos=4)
</code>```

If you really want to use identify,  you can use

```<code>plot(df)
Years = 1875:1972
identify(x=Years, y=LakeHuron, labels=Years)
</code>```

Then click near the maximum and minimum. Right click and select "stop" when you are done.

Body:
i need to paint a graph using LakeHuron data in R, single paiting is easy just

df= data.frame(LakeHuron)
plot(df)

but I need to use identify to sign the years where the point of water was the highest and the lowest

df=data.frame(LakeHuron)
df
plot(df)
minimum = min(df)
maximum = max(df)

I got those minimum and maximum variables, but how can i use identify to point them on plot?

Body:
If you are trying to label the years, it may be easiest to do that with text.

Xmin = which.min(df$LakeHuron)
Xmax = which.max(df$LakeHuron)
Years = 1875:1972

plot(df)
text(x=Years[c(Xmin, Xmax)], y = LakeHuron[c(Xmin, Xmax)],
    labels=Years[c(Xmin, Xmax)], pos=4)

If you really want to use identify,  you can use

plot(df)
Years = 1875:1972
identify(x=Years, y=LakeHuron, labels=Years)

Then click near the maximum and minimum. Right click and select "stop" when you are done.


问:
It's posible to get a synchronous response using put method?
I'm connecting to a remote mq queue using pymqi. I'm using put method as normal but I would like to know if there are some way to set something symilar as JMSReplyTo on JMS system to get a synchronous response of my message.

The request queue and the response are created in the remote mq where I'm connecting.

答:
Yes you can set ReplyToQ (JMSReplyTo) and No, there is no one-call function for getting synchronous response.

Look example page or example in source

Is short:

```<code># Prepare a Message Descriptor for the request message.
md = pymqi.MD()
md.ReplyToQ = dyn_queue_name

# Send the message.
queue = pymqi.Queue(qmgr, request_queue)
queue.put(message, md)
</code>```

Body:
Yes you can set ReplyToQ (JMSReplyTo) and No, there is no one-call function for getting synchronous response.

Look example page or example in source

Is short:

# Prepare a Message Descriptor for the request message.
md = pymqi.MD()
md.ReplyToQ = dyn_queue_name

# Send the message.
queue = pymqi.Queue(qmgr, request_queue)
queue.put(message, md)


问:
enqueue a linked list - java
For an assignment (thats due pretty soon), I have to enqueue a linked list that I have implemented by hand (not using java's built in class). The linked list is as follows:

```<code>public class SnocList {
    private char c;
    private SnocList l;

    public SnocList(){
    }
    public SnocList (char x, SnocList y) {
        this.c = x;
        this.l = y;
    }
    public char getC(){
        return this.c;
    }
    public SnocList getL(){
        return this.l;
    }
    public void setNext(SnocList input){
        this.l = input;
    }

    public boolean isEmpty() {
        if (this.c == 0) return true;
        return false;
    }
}
</code>```

my Queue class is as follows:

```<code>public class SnocQueue {
    private SnocList list;

    public SnocQueue(){
        this.list = new SnocList();
    }

    public void enqueue(char c){
        //I don't know what to put here
    }
}
</code>```

I have no idea how to do this. It's apparently pretty simple but I don't know how to do it. for those of you that want to help, enqueue will add a new node to the list where the null reference (null pointer) of the previous list was.

[ 'a' | --]-->[ 'b' | --]-->[ 'c' | null ]     add new node here

答:
Create a SnocList head node - this is the first
SnocList node in the Linked List.

Create enqueue method

In enqueue method, first check if head SnocList is
empty (or == null). If so, just make the head
SnocList a new SnocList that contains your passed-in character and the reference to the l SnocList.
l would be null because there would be no other
SnocLists in the linked list. Then, return to end execution of the method.

If head exists (else), traverse the linked list using a while loop until you hit a SnocList whose reference to l is null.

Append a new SnocList to the end of the linked list by assigning a new SnocList object new SnocList(ch, curr.l) to the previously null curr.l.

```<code>public class SnocQueue {
 SnocList head;

 public void enqueue(char ch) {
      if(head == null) {
         head = new SnocList(ch, null);
         return;
      } else {
         SnocList curr = head;
         while (curr.l != null) {
             curr = curr.l;
         }
         curr.l = new SnocList(ch, curr.l);
      }
 }
}
</code>```

Title: enqueue a linked list - java

Body:
For an assignment (thats due pretty soon), I have to enqueue a linked list that I have implemented by hand (not using java's built in class). The linked list is as follows:

public class SnocList {
    private char c;
    private SnocList l;

    public SnocList(){
    }
    public SnocList (char x, SnocList y) {
        this.c = x;
        this.l = y;
    }
    public char getC(){
        return this.c;
    }
    public SnocList getL(){
        return this.l;
    }
    public void setNext(SnocList input){
        this.l = input;
    }

    public boolean isEmpty() {
        if (this.c == 0) return true;
        return false;
    }
}

my Queue class is as follows:

public class SnocQueue {
    private SnocList list;

    public SnocQueue(){
        this.list = new SnocList();
    }

    public void enqueue(char c){
        //I don't know what to put here
    }
}

I have no idea how to do this. It's apparently pretty simple but I don't know how to do it. for those of you that want to help, enqueue will add a new node to the list where the null reference (null pointer) of the previous list was.

[ 'a' | --]-->[ 'b' | --]-->[ 'c' | null ]     add new node here

Body:
Create a SnocList head node - this is the first
SnocList node in the Linked List.

Create enqueue method

In enqueue method, first check if head SnocList is
empty (or == null). If so, just make the head
SnocList a new SnocList that contains your passed-in character and the reference to the l SnocList.
l would be null because there would be no other
SnocLists in the linked list. Then, return to end execution of the method.

If head exists (else), traverse the linked list using a while loop until you hit a SnocList whose reference to l is null.

Append a new SnocList to the end of the linked list by assigning a new SnocList object new SnocList(ch, curr.l) to the previously null curr.l.

public class SnocQueue {
 SnocList head;

 public void enqueue(char ch) {
      if(head == null) {
         head = new SnocList(ch, null);
         return;
      } else {
         SnocList curr = head;
         while (curr.l != null) {
             curr = curr.l;
         }
         curr.l = new SnocList(ch, curr.l);
      }
 }
}


问:
Vue not showing a object
I have a javascript function that grabs the 10 last retrieved closed websites with a chrome api, and it then simplifies the list into an array of objects with the title, and url of each website.  Vue is displaying this array of objects fine when I initialize it myself, however it does not work when trying to use the function to get the array.  Why isn't Vue showing anything?

As previously said, I have tried initializing the array of objects myself and have had no issues with displaying it like that. However setting it up so that before the Vue is rendered, the function to generate the array is run will still not solve the issue.

```<code>var gotLast10;

function getLast10() {
  chrome.sessions.getRecentlyClosed({}, function (results){
    if (results.length > 10){
      results = results.slice(0, 10);
        var tempLast10 = [];
        results.forEach(
          function(eachSite) {
            var tempObject = { TITLE: eachSite.tab.title, URL: eachSite.tab.url}
            tempLast10.push(tempObject);
            gotLast10 = tempLast10;
          }
        );
    }
    });
    console.log(gotLast10);
}

$(document).ready(
  function() {
    getLast10();
    vm = new Vue({
      el: '#app',
      data: {
        gotLast10: gotLast10,
      }
    });
  }
);
        <div id=app>
          {{ gotLast10 }}
        </div>
</code>```

I expected Vue to display the object normally, but it just ends up displaying nothing

答:
Try updating the data through the Vue instance.

```<code>vm.gotLast10 = tempLast10
</code>```

Also, make sure you call getLast10() after your create your Vue.

Title: Vue not showing a object

Body:
I have a javascript function that grabs the 10 last retrieved closed websites with a chrome api, and it then simplifies the list into an array of objects with the title, and url of each website.  Vue is displaying this array of objects fine when I initialize it myself, however it does not work when trying to use the function to get the array.  Why isn't Vue showing anything?

As previously said, I have tried initializing the array of objects myself and have had no issues with displaying it like that. However setting it up so that before the Vue is rendered, the function to generate the array is run will still not solve the issue.

var gotLast10;

function getLast10() {
  chrome.sessions.getRecentlyClosed({}, function (results){
    if (results.length > 10){
      results = results.slice(0, 10);
        var tempLast10 = [];
        results.forEach(
          function(eachSite) {
            var tempObject = { TITLE: eachSite.tab.title, URL: eachSite.tab.url}
            tempLast10.push(tempObject);
            gotLast10 = tempLast10;
          }
        );
    }
    });
    console.log(gotLast10);
}

$(document).ready(
  function() {
    getLast10();
    vm = new Vue({
      el: '#app',
      data: {
        gotLast10: gotLast10,
      }
    });
  }
);

          {{ gotLast10 }}

I expected Vue to display the object normally, but it just ends up displaying nothing

Body:
Try updating the data through the Vue instance.

vm.gotLast10 = tempLast10

Also, make sure you call getLast10() after your create your Vue.


问:
How to fix "A dismissed Dismissible widget is still part of the tree." error in flutter
I am building a fluter app with dismissible widget, firebase and StreamBuilder and getting following error "A dismissed Dismissible widget is still part of the tree."

Please find the below code sniped for the same.

```<code>Expanded(
                  child: StreamBuilder(
                    stream: Firestore.instance
                        .document('/users/User1/Trips/${widget.tripId}')
                        .collection('TropDocs')
                        .snapshots(),
                    builder: (context, snapshot) {
                      if (!snapshot.hasData) return const Text("Loading....");
                      return ListView.builder(
                        itemExtent: 150.0,
                        itemCount: snapshot.data.documents.length,
                        itemBuilder: (context, index) {

final item = snapshot.data.documents[index];
                          final itemID =
                              snapshot.data.documents[index].documentID;
                          final list = snapshot.data.documents;
return Dismissible(
   key: Key(itemID),
              // We also need to provide a function that tells our app
              // what to do after an item has been swiped away.
              onDismissed: (direction) {
                // Remove the item from our data source.

                //fBtDoc.deleteTraveldoc(item);
                //Firestore.instance.collection('/users/User1/Trips/${widget.tripId}/TropDocs/').document('$itemID').delete();
                setState(() {
                  list.removeAt(index);
                });

                // Then show a snackbar!
                Scaffold.of(context)
                    .showSnackBar(SnackBar(content: Text("$item dismissed")));
              },
              // Show a red background as the item is swiped away
              background: Container(color: Colors.red),
              child: _buildlistitem(
                            context, snapshot.data.documents[index])
);

                        }
                      );
                    },
                  ),
                )
</code>```

答:
Remove setState block, streamBuilder will rebuild list by itself</p>

```<code> setState(() {
   list.removeAt(index);
 });
</code>```

Body:
I am building a fluter app with dismissible widget, firebase and StreamBuilder and getting following error "A dismissed Dismissible widget is still part of the tree."

Please find the below code sniped for the same.

Expanded(
                  child: StreamBuilder(
                    stream: Firestore.instance
                        .document('/users/User1/Trips/${widget.tripId}')
                        .collection('TropDocs')
                        .snapshots(),
                    builder: (context, snapshot) {
                      if (!snapshot.hasData) return const Text("Loading....");
                      return ListView.builder(
                        itemExtent: 150.0,
                        itemCount: snapshot.data.documents.length,
                        itemBuilder: (context, index) {

final item = snapshot.data.documents[index];
                          final itemID =
                              snapshot.data.documents[index].documentID;
                          final list = snapshot.data.documents;
return Dismissible(
   key: Key(itemID),
              // We also need to provide a function that tells our app
              // what to do after an item has been swiped away.
              onDismissed: (direction) {
                // Remove the item from our data source.

                //fBtDoc.deleteTraveldoc(item);
                //Firestore.instance.collection('/users/User1/Trips/${widget.tripId}/TropDocs/').document('$itemID').delete();
                setState(() {
                  list.removeAt(index);
                });

                // Then show a snackbar!
                Scaffold.of(context)
                    .showSnackBar(SnackBar(content: Text("$item dismissed")));
              },
              // Show a red background as the item is swiped away
              background: Container(color: Colors.red),
              child: _buildlistitem(
                            context, snapshot.data.documents[index])
);

                        }
                      );
                    },
                  ),
                )

Body:
Remove setState block, streamBuilder will rebuild list by itself

 setState(() {
   list.removeAt(index);
 });


问:
How can I count the number of days that match between a data frame with two vectors (start date and end date) and a vector of dates?
I have a very large data set (>12,000 rows) that contains two vectors of the start and end date of a measurement (relative growth rate). Each row has an individual, the date of the initial measurement, the date of the final measurement, and then the growth rate associated with that window. I want to count the number of days within each growth measurement that match dates that are in a separate vector. So ideally I would be adding a vector to the data frame that gives me a count of the number of matching days between the dates in the df and the external vector for each individual's growth rate.

Sample of what the data frame looks like, but in actuality it is much, much larger

```<code>individual <- c(1:5)
initialdate <- c("1990-03-01", "1991-05-07", "1992-05-02",
                 "1994-03-02", "1995-03-08")
enddate <- c("1991-08-05", "1993-02-17", "1995-06-22",
             "1995-09-12", "1997-08-18")
RGR <- c(0.25, 0.3, 0.09, 0.48, 0.34)
df <- data.frame(individual, initialdate, enddate, RGR)

DaysToMatch <- c("1991-03-30", "1993-12-18", ... )

countDays <- function(df$initialdate, df$enddate, DaysToMatch) {
    measurementwindow <- seq(as.Date(initialdate), as.Date(enddate), by="days")
    commonDays <- length(intersect(measurementwindow, DaysToMatch))
    return(commonDays)
}
</code>```

Error in seq.Date(as.Date(InitialDate), as.Date(ObsrvnDate), by = "days") :
    'from' must be of length 1

I also suspect that I am not indexing the vectors properly to calculate the commonDays for each row of the data frame.

Body:
I have a very large data set (>12,000 rows) that contains two vectors of the start and end date of a measurement (relative growth rate). Each row has an individual, the date of the initial measurement, the date of the final measurement, and then the growth rate associated with that window. I want to count the number of days within each growth measurement that match dates that are in a separate vector. So ideally I would be adding a vector to the data frame that gives me a count of the number of matching days between the dates in the df and the external vector for each individual's growth rate.

Sample of what the data frame looks like, but in actuality it is much, much larger

individual <- c(1:5)
initialdate <- c("1990-03-01", "1991-05-07", "1992-05-02",
                 "1994-03-02", "1995-03-08")
enddate <- c("1991-08-05", "1993-02-17", "1995-06-22",
             "1995-09-12", "1997-08-18")
RGR <- c(0.25, 0.3, 0.09, 0.48, 0.34)
df <- data.frame(individual, initialdate, enddate, RGR)

DaysToMatch <- c("1991-03-30", "1993-12-18", ... )

countDays <- function(df$initialdate, df$enddate, DaysToMatch) {
    measurementwindow <- seq(as.Date(initialdate), as.Date(enddate), by="days")
    commonDays <- length(intersect(measurementwindow, DaysToMatch))
    return(commonDays)
}

Error in seq.Date(as.Date(InitialDate), as.Date(ObsrvnDate), by = "days") :
    'from' must be of length 1

I also suspect that I am not indexing the vectors properly to calculate the commonDays for each row of the data frame.

Body:
We can use data.table join in an efficient and compact way

library(data.table)
n <-  data.table(date = DaysToMatch)[df, .N,
      on = .(date > initialdate, date <= enddate), by = .EACHI]$N
df$commonDays <- n
df
#  individual initialdate    enddate  RGR commonDays
#1          1  1990-03-01 1991-08-05 0.25          1
#2          2  1991-05-07 1993-02-17 0.30          0
#3          3  1992-05-02 1995-06-22 0.09          1
#4          4  1994-03-02 1995-09-12 0.48          0
#5          5  1995-03-08 1997-08-18 0.34          0

Or using tidyverse

library(tidyverse)
df %>%
   rowwise %>%
   mutate(commonDays = sum(between(DaysToMatch, initialdate, enddate)))
# A tibble: 5 x 5
#  individual initialdate enddate      RGR commonDays
#       <int> <date>      <date>     <dbl>      <int>
#1          1 1990-03-01  1991-08-05  0.25          1
#2          2 1991-05-07  1993-02-17  0.3           0
#3          3 1992-05-02  1995-06-22  0.09          1
#4          4 1994-03-02  1995-09-12  0.48          0
#5          5 1995-03-08  1997-08-18  0.34          0

data

df[2:3] <- lapply(df[2:3], as.Date)
DaysToMatch <- as.Date(c("1991-03-30", "1993-12-18"))


问:
Mongodb query use skip and limit function in first N documents
Can we make query which enable us to use skip and limit in first N documents?

Ex :

Suppose there are nearly 500 documents in a collection called teachers.

I want a query which restrict me to read first 300 documents only.

If I use skip(300) in that query it should display null.

```<code>db.teachers.find().pretty()

{
  id : 1,
  name : "teach001"
},
{
  id : 2,
  name : "teach002"
},
{
  id : 3,
  name : "teach003"
},
{
  id : 4,
  name : "teach004"
},
{
  id : 5,
  name : "teach005"
},
{
  id : 6,
  name : "teach006"
},
{
  id : 7,
  name : "teach007"
},
{
  id : 8,
  name : "teach008"
},
{
  id : 9,
  name : "teach009"
},
{
  id : 10,
  name : "teach0010"
}

 db.teachers.find({some query here to restrict access first 5 documents only }).skip(5).limit(5).pretty()
</code>```

答:
Aggregation

I don't think there is a way to do exactly what you are requesting.  If you are open to using the aggregation framework, it can be accomplished easily.

```<code>db.teachers.aggregate([{$limit: 5}, {$skip: 5}])
</code>```

View

If you are open to creating a view, you could even create a view that enforces the limit

```<code>db.createView('limitedTeachers', 'teachers', [{$limit: 5}])
</code>```

Then you can use find on the view:

```<code>db.limitedTeachers.find({}).skip(5)
</code>```

Two finds

If you cannot use aggregation, you have the option of using 2 finds in your query.  First, find the n number of Object IDs. Then, limit your second query to only those Object IDs.

```<code>var ids = [];
db.teachers.find({}, {_id: 1}).limit(5).forEach(function(doc){
    ids.push(doc._id);
});

db.teachers.find({ _id: {$in: ids} }).skip(5)
</code>```

Or as the same type of query but closer to the format you had in your question

```<code>db.teachers.find({$or: db.teachers.find({}, {_id: 1}).limit(5).toArray()}).skip(5)
</code>```

Body:
Can we make query which enable us to use skip and limit in first N documents?

Ex :

Suppose there are nearly 500 documents in a collection called teachers.

I want a query which restrict me to read first 300 documents only.

If I use skip(300) in that query it should display null.

db.teachers.find().pretty()

{
  id : 1,
  name : "teach001"
},
{
  id : 2,
  name : "teach002"
},
{
  id : 3,
  name : "teach003"
},
{
  id : 4,
  name : "teach004"
},
{
  id : 5,
  name : "teach005"
},
{
  id : 6,
  name : "teach006"
},
{
  id : 7,
  name : "teach007"
},
{
  id : 8,
  name : "teach008"
},
{
  id : 9,
  name : "teach009"
},
{
  id : 10,
  name : "teach0010"
}

 db.teachers.find({some query here to restrict access first 5 documents only }).skip(5).limit(5).pretty()

Body:
Aggregation

I don't think there is a way to do exactly what you are requesting.  If you are open to using the aggregation framework, it can be accomplished easily.

db.teachers.aggregate([{$limit: 5}, {$skip: 5}])

View

If you are open to creating a view, you could even create a view that enforces the limit

db.createView('limitedTeachers', 'teachers', [{$limit: 5}])

Then you can use find on the view:

db.limitedTeachers.find({}).skip(5)

Two finds

If you cannot use aggregation, you have the option of using 2 finds in your query.  First, find the n number of Object IDs. Then, limit your second query to only those Object IDs.

var ids = [];
db.teachers.find({}, {_id: 1}).limit(5).forEach(function(doc){
    ids.push(doc._id);
});

db.teachers.find({ _id: {$in: ids} }).skip(5)

Or as the same type of query but closer to the format you had in your question

db.teachers.find({$or: db.teachers.find({}, {_id: 1}).limit(5).toArray()}).skip(5)


问:
Selenium Wait for user to click on alert dialog box in python
I have created a dialog box in browser (this Happens when an error occurs in user input details). What I need is to wait until the user clicks on the dialog box before preceding with automatic execution (only for testing). Here is what I have

```<code># driver is a chrome web driver
driver.execute_script("alert('qwer');")
wait = WebDriverWait(driver, 10)
element = wait.until(EC.alert_is_present())
</code>```

I tried to search online but only got an answer when a user clicks on a button inside a webpage but not on a generated dialog box. How to do it (if possible)?

答:
```<code>from time import sleep
while EC.alert_is_present()(driver):
    sleep(30)
</code>```

If you simply want to alert the user then use pymsgbox or Telegram API to send him a message,

```<code>from pymsgbox import alert
alert("Hey User")
</code>```

Body:
I have created a dialog box in browser (this Happens when an error occurs in user input details). What I need is to wait until the user clicks on the dialog box before preceding with automatic execution (only for testing). Here is what I have

# driver is a chrome web driver
driver.execute_script("alert('qwer');")
wait = WebDriverWait(driver, 10)
element = wait.until(EC.alert_is_present())

I tried to search online but only got an answer when a user clicks on a button inside a webpage but not on a generated dialog box. How to do it (if possible)?

Body:
from time import sleep
while EC.alert_is_present()(driver):
    sleep(30)

If you simply want to alert the user then use pymsgbox or Telegram API to send him a message,

from pymsgbox import alert
alert("Hey User")


问:
Printing last element in an array using if statement
I am currently trying to learn about using pointers and functions together in C, which I don't think is easy.
I am trying to print the last element in an array, it actually does the opposite and prints the first element.
I know people normally use for loops, but I can't figure out how to do that with exactly this kind of problem and therefore I thought that I would try it out with an if statement instead.

Edit:
Why is if statement not working in this case? It seems logic that it should work...

My main.c file:

#include <stdio.h>
#include <stdlib.h>
#include "functions.h"
#define Size 7

int main(void)
{

    int array1[] = { 11, 88, 5, 9, 447, 8, 68, 4 };

    maxValue(array1, Size);

    return 0;
}
```

<p>My functions.h file:</p>

<pre class="lang-cpp prettyprint-override"><code>#pragma once

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

int maxValue(const int *, int);

#endif

</code>```

My functions.c file:

#include "functions.h"
#include <stdio.h>
#include <stdlib.h>

int maxValue(const int *array1, int Size)
{

    int max = array1[0];

    if (max < array1[Size]) {
        Size++;
        max = array1[Size];
    }

    printf("Max value: %d \n", max);
}

```

答:
The names maxValue() and max are misleading and confusing what you are trying to do.  lastValue() and last would make much more sense.

However what you are trying to do makes no sense in C because arrays are of known length, so you can access the last element directly:

```<code>int array1[] = { 11, 88, 5, 9, 447, 8, 68, 4 };
int array_length = sizeof(array1) / sizeof(*array1) ;
printf("Lastvalue: %d \n", array1[array_length - 1] ) ;
</code>```

However you cannot do this in a function because arrays are not first class data types in C and when passed to a function will "degrade" to a simple pointer without any information regarding the size of the array pointed to.  The calling function having the size information must pass that too (as you have done, but then appeared to get very confused):

```<code>void printLast( int* array, int length )
{
    printf( "Lastvalue: %d \n", array1[length - 1] ) ;
}
</code>```

It is difficult to see why you thought you might need any other code or what your maxValue() function is intended to achieve.  The "logic" which you say "should work" is thus:

If value of the first array element is less than the value of the last array element, then print the undefined value one past the end of the array; otherwise print the first element of the array.

If you wanted to print the last element, then you simply print it, the value of the first element has nothing to do do with it.  Either way you should not index past the end of the array - that value is undefined.

Body:
I am currently trying to learn about using pointers and functions together in C, which I don't think is easy.
I am trying to print the last element in an array, it actually does the opposite and prints the first element.
I know people normally use for loops, but I can't figure out how to do that with exactly this kind of problem and therefore I thought that I would try it out with an if statement instead.

Edit:
Why is if statement not working in this case? It seems logic that it should work...

My main.c file:

#include <stdio.h>
#include <stdlib.h>
#include "functions.h"
#define Size 7

int main(void)
{

    int array1[] = { 11, 88, 5, 9, 447, 8, 68, 4 };

    maxValue(array1, Size);

    return 0;
}

My functions.h file:

#pragma once

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

int maxValue(const int *, int);

#endif

My functions.c file:

#include "functions.h"
#include <stdio.h>
#include <stdlib.h>

int maxValue(const int *array1, int Size)
{

    int max = array1[0];

    if (max < array1[Size]) {
        Size++;
        max = array1[Size];
    }

    printf("Max value: %d \n", max);
}

Body:
The names maxValue() and max are misleading and confusing what you are trying to do.  lastValue() and last would make much more sense.

However what you are trying to do makes no sense in C because arrays are of known length, so you can access the last element directly:

int array1[] = { 11, 88, 5, 9, 447, 8, 68, 4 };
int array_length = sizeof(array1) / sizeof(*array1) ;
printf("Lastvalue: %d \n", array1[array_length - 1] ) ;

However you cannot do this in a function because arrays are not first class data types in C and when passed to a function will "degrade" to a simple pointer without any information regarding the size of the array pointed to.  The calling function having the size information must pass that too (as you have done, but then appeared to get very confused):

void printLast( int* array, int length )
{
    printf( "Lastvalue: %d \n", array1[length - 1] ) ;
}

It is difficult to see why you thought you might need any other code or what your maxValue() function is intended to achieve.  The "logic" which you say "should work" is thus:

If value of the first array element is less than the value of the last array element, then print the undefined value one past the end of the array; otherwise print the first element of the array.

If you wanted to print the last element, then you simply print it, the value of the first element has nothing to do do with it.  Either way you should not index past the end of the array - that value is undefined.


问:
I want to get the last 6 objects from an array
I have an array list of objects, and I only want to return the last 7 objects in the array. help pls

I have tried to use, filter, map and find, but I could not get the output I was expecting

var welcomeMessage = [{
    from: "Clement",
    text: "Welcome to Freeborn chat system!",
    id: 0
  },
  {
    from: "mark",
    text: "Hello",
    id: 1
  },
  {
    from: "clement",
    text: "welcome",
    id: 2
  },
  {
    from: "mark",
    text: "long time",
    id: 3
  },
  {
    from: "clement",
    text: "yeah, indeed",
    id: 4
  },
  {
    from: "mark",
    text: "real good to be hear",
    id: 5
  },
  {
    from: "clement",
    text: "you looking good",
    id: 7
  },
  {
    from: "mark",
    text: "Hello",
    id: 8
  },
  {
    from: "clement",
    text: "welcome",
    id: 9
  }
]

const messages = [welcomeMessage]

function latestMessage(messages, search) {
  let search = rquest.body;
  let messages = messages.length - 7
  const messages.filter(message => {
    return message
  })
}
```

答:
You could use Array#slice with a negative index from the end.

var welcomeMessage = [{ from: "Clement", text: "Welcome to Freeborn chat system!", id: 0 }, { from: "mark", text: "Hello", id: 1 }, { from: "clement", text: "welcome", id: 2 }, { from: "mark", text: "long time", id: 3 }, { from: "clement", text: "yeah, indeed", id: 4 }, { from: "mark", text: "real good to be hear", id: 5 }, { from: "clement", text: "you looking good", id: 7 }, { from: "mark", text: "Hello", id: 8 }, { from: "clement", text: "welcome", id: 9 }, { from: "mark", text: "long time", id: 10 }, { from: "clement", text: "yeah, indeed", id: 11 }];

console.log(welcomeMessage.slice(-6));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
You could use Array#slice with a negative index from the end.

var welcomeMessage = [{ from: "Clement", text: "Welcome to Freeborn chat system!", id: 0 }, { from: "mark", text: "Hello", id: 1 }, { from: "clement", text: "welcome", id: 2 }, { from: "mark", text: "long time", id: 3 }, { from: "clement", text: "yeah, indeed", id: 4 }, { from: "mark", text: "real good to be hear", id: 5 }, { from: "clement", text: "you looking good", id: 7 }, { from: "mark", text: "Hello", id: 8 }, { from: "clement", text: "welcome", id: 9 }, { from: "mark", text: "long time", id: 10 }, { from: "clement", text: "yeah, indeed", id: 11 }];

console.log(welcomeMessage.slice(-6));

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How to fetch api with javascript to display data?
I am trying to build an API with javascript to fetch data from this URL for json data: img, a, c . But below codes threw back an error of

application.js:10 Uncaught (in promise) TypeError: data.forEach is not a function

(why is the forEach method not defined) can you help? thanks

var results = document.getElementById("results");

fetch("https://www.mangaeden.com/api/list/0/")
  .then(response => response.json())
  .then((data) => {

    data.forEach((result) => {

      const movies = '

' + result.a + '

' + result.c + '

';
      results.insertAdjacentHTML("beforeend", movies);

    });
  });
```

<pre class="lang-js prettyprint-override"><code>{
  "a": "shoujo-apocalypse-adventure",
  "c": [
    "Adventure",
    "Drama",
    "Psychological",
    "Sci-fi",
    "Seinen",
    "Slice of Life",
    "Tragedy"
  ],
  "h": 156,
  "i": "5c410d31719a16035a4647cc",
  "im": "4a/4a1f2a595e0e84e62f6ceddf3946274478928ca99e8df86bc6511b6e.png",
  "ld": 1547822837.0,
  "s": 2,
  "t": "Shoujo Apocalypse Adventure"
},
</code>```

答:
The response is not an array ([]) but an object ({}) and object has no method forEach. I guess you meant to run the forEach on the entries, which in this case is under data.manga.

var results = document.getElementById("results");

fetch("https://www.mangaeden.com/api/list/0/", {
    mode: 'cors'
  })
  .then(response => response.json())
  .then((data) => {

    data.manga
      .filter(movie => movie.c.includes('Action') || movie.c.includes('Adventure'))
      .slice(0, 10).forEach((result) => {

      const movies = '

' + result.a + '

' + result.c + '

';
      results.insertAdjacentHTML("beforeend", movies);

    });
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="results"></ul></code>```

https://jsbin.com/gecusi/edit?html,js

Note: In the example I slice the array because there are ~6.7k movies and I don't want to block the browser.

Body:
I am trying to build an API with javascript to fetch data from this URL for json data: img, a, c . But below codes threw back an error of

application.js:10 Uncaught (in promise) TypeError: data.forEach is not a function

(why is the forEach method not defined) can you help? thanks

var results = document.getElementById("results");

fetch("https://www.mangaeden.com/api/list/0/")
  .then(response => response.json())
  .then((data) => {

    data.forEach((result) => {

      const movies = '

' + result.a + '

' + result.c + '

';
      results.insertAdjacentHTML("beforeend", movies);

    });
  });

{
  "a": "shoujo-apocalypse-adventure",
  "c": [
    "Adventure",
    "Drama",
    "Psychological",
    "Sci-fi",
    "Seinen",
    "Slice of Life",
    "Tragedy"
  ],
  "h": 156,
  "i": "5c410d31719a16035a4647cc",
  "im": "4a/4a1f2a595e0e84e62f6ceddf3946274478928ca99e8df86bc6511b6e.png",
  "ld": 1547822837.0,
  "s": 2,
  "t": "Shoujo Apocalypse Adventure"
},

Body:
The response is not an array ([]) but an object ({}) and object has no method forEach. I guess you meant to run the forEach on the entries, which in this case is under data.manga.

var results = document.getElementById("results");

fetch("https://www.mangaeden.com/api/list/0/", {
    mode: 'cors'
  })
  .then(response => response.json())
  .then((data) => {

    data.manga
      .filter(movie => movie.c.includes('Action') || movie.c.includes('Adventure'))
      .slice(0, 10).forEach((result) => {

      const movies = '<li><img src="https://cdn.mangaeden.com/mangasimg/' + result.im + '" alt=""><h3>' + result.a + '</h3><p>' + result.c + '</p></li>';
      results.insertAdjacentHTML("beforeend", movies);

    });
  });

<ul id="results"></ul>

https://jsbin.com/gecusi/edit?html,js

Note: In the example I slice the array because there are ~6.7k movies and I don't want to block the browser.


问:
How to boost::serialize pointers and reference?
I need serialize a class with fields: int, pointer to int, array, class object, pointer to class object, reference to class object, pointer to class object with virtual parent.

I tried to implement it. I managed to do for int and array. But I can not deal with pointers and references

```<code>class B() {};

class Person
{
 public:
int age; // work
    int *ageptr = &age; // not work
std::vector<int> favoriteNumbers; //work

    B b; // not work
    B *bptr = &b; // not work
    B &bref = b; // not work

Person();
~Person();

private:
    friend class boost::serialization::access;
    template <class Archive>
    void serialize(Archive &ar, const unsigned int version) {
        ar &BOOST_SERIALIZATION_NVP(age);
        ar &BOOST_SERIALIZATION_NVP(ageptr); // error
        ar &BOOST_SERIALIZATION_NVP(b); // error
        ar &BOOST_SERIALIZATION_NVP(bptr); // error
        ar &BOOST_SERIALIZATION_NVP(bref); // error
        ar &BOOST_SERIALIZATION_NVP(favoriteNumbers);
    }
};
</code>```

答:
In your particular case, since the references and pointers refer to member variables, they do not need to be serialized/deserialized. The constructor already set these members to correct values.

With regards to serializing pointers read Pointers section of serialization tutorial.

You cannot deserialize references in general, though, because they are aliases to other objects and they cannot be reassigned to refer to another object. Also, taking address and sizeof of a reference returns those of the object being referred. I would also recommend against using reference members at all.

Body:
I need serialize a class with fields: int, pointer to int, array, class object, pointer to class object, reference to class object, pointer to class object with virtual parent.

I tried to implement it. I managed to do for int and array. But I can not deal with pointers and references

class B() {};

class Person
{
 public:
int age; // work
    int *ageptr = &age; // not work
std::vector<int> favoriteNumbers; //work

    B b; // not work
    B *bptr = &b; // not work
    B &bref = b; // not work

Person();
~Person();

private:
    friend class boost::serialization::access;
    template <class Archive>
    void serialize(Archive &ar, const unsigned int version) {
        ar &BOOST_SERIALIZATION_NVP(age);
        ar &BOOST_SERIALIZATION_NVP(ageptr); // error
        ar &BOOST_SERIALIZATION_NVP(b); // error
        ar &BOOST_SERIALIZATION_NVP(bptr); // error
        ar &BOOST_SERIALIZATION_NVP(bref); // error
        ar &BOOST_SERIALIZATION_NVP(favoriteNumbers);
    }
};


问:
Setting global environment variables in Jenkinsfile on Windows
I a have Jenkins CI server running on top of a Windows system, and now I would like to set global environment variables for my pipeline.

I tried two different ways both without success:

```<code>node {
    environment {
        MY_PYTHON='D:\ProgramData\Anaconda3'
        PATH='%MY_PYTHON%;%MY_PYTHON%\Scripts;%PATH%'
    }
    stage ('Checkout and Build') {
        bat 'echo %MY_PYTHON%'
        bat 'echo %PATH%'
        bat 'python --version'
    }
}
</code>```

After starting the build it throws the following error:

```<code>org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:

WorkflowScript: 3: unexpected char: '\' @ line 3, column 22.

           MY_PYTHON='D:\ProgramData\Anaconda3'

                        ^
</code>```

Kinda straightforward so I tried doubling the backslashes like this:

```<code>environment {
    MY_PYTHON='D:\\ProgramData\\Anaconda3'
    PATH='%MY_PYTHON%;%MY_PYTHON%\\Scripts;%PATH%'
}
</code>```

So after restarting the build I got error only for the command python --version as python still cannot be found on path, and also I get back nothing for MY_PYTHON and for PATH I get all the predifined paths except those I wanted to add.

Got stuck, so any help would be appreciated!

答: Try that : MY_PYTHON='D:\\ProgramData\\Anaconda3'</p>

Body:
I a have Jenkins CI server running on top of a Windows system, and now I would like to set global environment variables for my pipeline.

I tried two different ways both without success:

node {
    environment {
        MY_PYTHON='D:\ProgramData\Anaconda3'
        PATH='%MY_PYTHON%;%MY_PYTHON%\Scripts;%PATH%'
    }
    stage ('Checkout and Build') {
        bat 'echo %MY_PYTHON%'
        bat 'echo %PATH%'
        bat 'python --version'
    }
}

After starting the build it throws the following error:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:

WorkflowScript: 3: unexpected char: '\' @ line 3, column 22.

           MY_PYTHON='D:\ProgramData\Anaconda3'

                        ^

Kinda straightforward so I tried doubling the backslashes like this:

environment {
    MY_PYTHON='D:\\ProgramData\\Anaconda3'
    PATH='%MY_PYTHON%;%MY_PYTHON%\\Scripts;%PATH%'
}

So after restarting the build I got error only for the command python --version as python still cannot be found on path, and also I get back nothing for MY_PYTHON and for PATH I get all the predifined paths except those I wanted to add.

Got stuck, so any help would be appreciated!


答: let lastSeven = welcomeMessage.slice(-7);</p>

Title: I want to get the last 6 objects from an array

Body:
I have an array list of objects, and I only want to return the last 7 objects in the array. help pls

I have tried to use, filter, map and find, but I could not get the output I was expecting

var welcomeMessage = [{
    from: "Clement",
    text: "Welcome to Freeborn chat system!",
    id: 0
  },
  {
    from: "mark",
    text: "Hello",
    id: 1
  },
  {
    from: "clement",
    text: "welcome",
    id: 2
  },
  {
    from: "mark",
    text: "long time",
    id: 3
  },
  {
    from: "clement",
    text: "yeah, indeed",
    id: 4
  },
  {
    from: "mark",
    text: "real good to be hear",
    id: 5
  },
  {
    from: "clement",
    text: "you looking good",
    id: 7
  },
  {
    from: "mark",
    text: "Hello",
    id: 8
  },
  {
    from: "clement",
    text: "welcome",
    id: 9
  }
]

const messages = [welcomeMessage]

function latestMessage(messages, search) {
  let search = rquest.body;
  let messages = messages.length - 7
  const messages.filter(message => {
    return message
  })
}


问:
Check if all points in a set lie on the same line
I'm given a list with coordinates of n points, let's say:

```<code>points = [(1, 2), (2, 3), (3, 4)]
</code>```

And I need to check if all of them lie on the same line. I also decided to consider 3 cases to avoid dividing by zero when x1 == x2.
So here's my code in Python:

```<code># 2 points always lie on a line
if n <= 2:
    print("yes")
else:
    # leave only unique points
    points = list(set(points))
    x1, y1 = points[0]
    x2, y2 = points[1]

    # if two points have the same x coordinate
    # then they lie on a vertical line and
    # all other points have to have the same x coordinate too
    if x2 == x1:
        for i in range(2, len(points)):
            if points[i][0] != x1:
                print("no")
                break
        else: print("yes")

    # same with a horizontal line
    elif y2 == y1:
        for i in range(2, len(points)):
            if points[i][1] != y1:
                print("no")
                break
        else: print("yes")

    else:
        a = (y2-y1)/(x2-x1)
        b = y2 - a * x2

        for i in range(2, len(points)):
            x, y = points[i]
            if (y != a * x + b):
                print("no")
                break
        else: print("yes")
</code>```

It seems that I have a mistake somewhere in the code but I don't really understand what it is.

答:
From any point in the list (e.g. first one) if all other points have the same slope with that one, then they are on the same line.</p>

```<code>def sameLine(points):
    x0,y0  = points[0]
    points = [ (x,y) for x,y in points if x != x0 or y != y0 ]      # Other points
    slopes = [ (y-y0)/(x-x0) if x!=x0 else None for x,y in points ] # None for vertical Line
    return all( s == slopes[0] for s in slopes)
</code>```

Body:
I'm given a list with coordinates of n points, let's say:

points = [(1, 2), (2, 3), (3, 4)]

And I need to check if all of them lie on the same line. I also decided to consider 3 cases to avoid dividing by zero when x1 == x2.
So here's my code in Python:

# 2 points always lie on a line
if n <= 2:
    print("yes")
else:
    # leave only unique points
    points = list(set(points))
    x1, y1 = points[0]
    x2, y2 = points[1]

    # if two points have the same x coordinate
    # then they lie on a vertical line and
    # all other points have to have the same x coordinate too
    if x2 == x1:
        for i in range(2, len(points)):
            if points[i][0] != x1:
                print("no")
                break
        else: print("yes")

    # same with a horizontal line
    elif y2 == y1:
        for i in range(2, len(points)):
            if points[i][1] != y1:
                print("no")
                break
        else: print("yes")

    else:
        a = (y2-y1)/(x2-x1)
        b = y2 - a * x2

        for i in range(2, len(points)):
            x, y = points[i]
            if (y != a * x + b):
                print("no")
                break
        else: print("yes")

It seems that I have a mistake somewhere in the code but I don't really understand what it is.

Body:
From any point in the list (e.g. first one) if all other points have the same slope with that one, then they are on the same line.

def sameLine(points):
    x0,y0  = points[0]
    points = [ (x,y) for x,y in points if x != x0 or y != y0 ]      # Other points
    slopes = [ (y-y0)/(x-x0) if x!=x0 else None for x,y in points ] # None for vertical Line
    return all( s == slopes[0] for s in slopes)


问:
How to remove the last character of a string in Golang?
I want to remove the very last character of a string, but before I do so I want to check if the last character is a "+". How can this be done?</p>

答:
Based on the comment of @KarthikGR the following example was added:

https://play.golang.org/p/ekDeT02ZXoq

```<code>package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Println(strings.TrimSuffix("Foo++", "+"))
}
</code>```

returns:

```<code>Foo+
</code>```

Body:
Based on the comment of @KarthikGR the following example was added:

https://play.golang.org/p/ekDeT02ZXoq

package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Println(strings.TrimSuffix("Foo++", "+"))
}

returns:

Foo+


答:
The problem is that you mixed the x and the y coordinates while fitting and plotting the fit. Since m is the x-coordinate (independent variable) and chi is the y-coordinate (dependent variable), pass them in the right order. The lines modified are indicated by a comment #

```<code>poly = np.polyfit(m, chi, deg = 4) # <-----
fit_fn = np.poly1d(poly)

f = plt.figure()
ax = f.add_subplot(111)
ax.plot(m, chi, 'rx', label = 'data') # <---- Just used x to plot symbols
ax.plot(m, fit_fn(m), 'b-', lw=2, label = 'adjust') # <-----
ax.set_xlabel('$m$')
ax.set_ylabel('$\chi^2$')
plt.legend()
plt.show()
plt.close()
</code>```

Title: np.polyfit does not fit the data

Body:
I can not find a curve that adjust the data (lists 'chi' and 'm'). I used polyfit to generate the curve but it was not enough to capture the behavior of the points.

The code ahead has a plot that shows the discrepancy between the data and the adjustment.

import matplotlib.pyplot as plt
import numpy as np

chi = [159.227326193538,157.045536099339,154.874421083320,152.714227953804,150.565205206850,148.427603026261,146.301673283577,144.187669538078,142.085847036787,139.996462714462,137.919775193605,135.856044784456,133.805533484994,131.768504980940,129.745224645753,127.735959540633,125.740978414520,123.760551704092,121.794951533770,119.844451715712,117.909327749816,115.989856823722,114.086317812809,112.198991280194,110.328159476736,108.474106341033,106.637117499424,104.817480265986,103.015483642536,101.231418318633,99.4655766715733,97.7182527663948,95.9897423558747,94.2803428805298,92.5903534686167,90.9200749361326,89.2698097868135,87.6398622121363,86.0305380913169,84.4421449913117,82.8749921668166,81.3293905602669,79.8056528018393,78.3040932094484,76.8250277887500,75.3687742331392,73.9356519237512,72.5259819294609,71.1400870068830,69.7782916003724,68.4409218420233,67.1283055516702,65.8407722368873,64.5786530929887,63.3422810030283,62.1319905377998,60.9481179558368,59.7910012034130,58.6609799145416,57.5583954109757,56.4835907022086,55.4369104854728,54.4187011457414,53.4293107557267,52.4690890758814,51.5383875543978,50.6375593272080,49.7669592179839,48.9269437381375,48.1178710868206,47.3401011509247,46.5939955050811,45.8799174116612,45.1982318207762,44.5493053702771,43.9335063857545,43.3512048805394,42.8027725557022,42.2885828000534,41.8090106901432,41.3644329902617,40.9552281524389,40.5817763164445,40.2444593097885,39.9436606477201,39.6797655332288,39.4531608570438,39.2642351976343,39.1133788212092,39.0009836817171,38.9274434208471,38.8931533680273,38.8985105404262,38.9439136429520,39.0297630682529,39.1564608967166,39.3244108964711,39.5340185233838,39.7856909210623,40.0798369208539,40.4168670418459,40.7971934908652,41.2212301624788,41.6893926389935,42.2020981904556,42.7597657746519,43.3628160371087,44.0116713110920,44.7067556176079,45.4484946654022,46.2373158509606,47.0736482585089,47.9579226600125,48.8905715151762,49.8720289714460,50.9027308640062,51.9831147157818,53.1136197374377,54.2946868273783,55.5267585717480,56.8102792444312,58.1456948070521,59.5334529089743,60.9740028873018,62.4677957668786,64.0152842602876,65.6169227678529,67.2731673776373,68.9844758654438,70.7513076948157,72.5741240170354,74.4533876711260,76.3895631838499,78.3831167697092,80.4345163309464,82.5442314575433,84.7127334272220,86.9404952054444,89.2279914454118,91.5756984880661,93.9840943620883,96.4536587839001,98.9848731576614,101.578220575274,104.234185816379,106.953255348357,109.735917326327,112.582661593151,115.493979679428,118.470364803498,121.512311871442,124.620317477080,127.794879901969,131.036499115411,134.345676774445,137.722916223849,141.168722496142,144.683602311584,148.268064078173,151.922617891649,155.647775535488,159.444050480909,163.311957886871,167.252014600072,171.264739154948,175.350651773679,179.510274366181,183.744130530113,188.052745550870,192.436646401591,196.896361743152,201.432421924170,206.045358981001,210.735706637743,215.504000306232,220.350777086043,225.276575764494,230.281936816639,235.367402405274,240.533516380936,245.780824281900,251.109873334181,256.521212451534,262.015392235454,267.592964975176,273.254484647676,279.000506917667,284.831589137604,290.748290347682,296.751171275834,302.840794337735,309.017723636798,315.282524964177,321.635765798766,328.078015307199,334.609844343848,341.231825450827,347.944532857988,354.748542482925,361.644431930971,368.632780495196]
m=[-1,-0.990000000000000,-0.980000000000000,-0.970000000000000,-0.960000000000000,-0.950000000000000,-0.940000000000000,-0.930000000000000,-0.920000000000000,-0.910000000000000,-0.900000000000000,-0.890000000000000,-0.880000000000000,-0.870000000000000,-0.860000000000000,-0.850000000000000,-0.840000000000000,-0.830000000000000,-0.820000000000000,-0.810000000000000,-0.800000000000000,-0.790000000000000,-0.780000000000000,-0.770000000000000,-0.760000000000000,-0.750000000000000,-0.740000000000000,-0.730000000000000,-0.720000000000000,-0.710000000000000,-0.700000000000000,-0.690000000000000,-0.680000000000000,-0.670000000000000,-0.660000000000000,-0.650000000000000,-0.640000000000000,-0.630000000000000,-0.620000000000000,-0.610000000000000,-0.600000000000000,-0.590000000000000,-0.580000000000000,-0.570000000000000,-0.560000000000000,-0.550000000000000,-0.540000000000000,-0.530000000000000,-0.520000000000000,-0.510000000000000,-0.500000000000000,-0.490000000000000,-0.480000000000000,-0.470000000000000,-0.460000000000000,-0.450000000000000,-0.440000000000000,-0.430000000000000,-0.420000000000000,-0.410000000000000,-0.400000000000000,-0.390000000000000,-0.380000000000000,-0.370000000000000,-0.360000000000000,-0.350000000000000,-0.340000000000000,-0.330000000000000,-0.320000000000000,-0.310000000000000,-0.300000000000000,-0.290000000000000,-0.280000000000000,-0.270000000000000,-0.260000000000000,-0.250000000000000,-0.240000000000000,-0.230000000000000,-0.220000000000000,-0.210000000000000,-0.200000000000000,-0.190000000000000,-0.180000000000000,-0.170000000000000,-0.160000000000000,-0.150000000000000,-0.140000000000000,-0.130000000000000,-0.120000000000000,-0.110000000000000,-0.100000000000000,-0.0900000000000000,-0.0800000000000000,-0.0700000000000000,-0.0599999999999999,-0.0499999999999999,-0.0400000000000000,-0.0300000000000000,-0.0200000000000000,-0.0100000000000000,0,0.0100000000000000,0.0200000000000000,0.0300000000000000,0.0400000000000000,0.0499999999999999,0.0599999999999999,0.0700000000000000,0.0800000000000000,0.0900000000000000,0.100000000000000,0.110000000000000,0.120000000000000,0.130000000000000,0.140000000000000,0.150000000000000,0.160000000000000,0.170000000000000,0.180000000000000,0.190000000000000,0.200000000000000,0.210000000000000,0.220000000000000,0.230000000000000,0.240000000000000,0.250000000000000,0.260000000000000,0.270000000000000,0.280000000000000,0.290000000000000,0.300000000000000,0.310000000000000,0.320000000000000,0.330000000000000,0.340000000000000,0.350000000000000,0.360000000000000,0.370000000000000,0.380000000000000,0.390000000000000,0.400000000000000,0.410000000000000,0.420000000000000,0.430000000000000,0.440000000000000,0.450000000000000,0.460000000000000,0.470000000000000,0.480000000000000,0.490000000000000,0.500000000000000,0.510000000000000,0.520000000000000,0.530000000000000,0.540000000000000,0.550000000000000,0.560000000000000,0.570000000000000,0.580000000000000,0.590000000000000,0.600000000000000,0.610000000000000,0.620000000000000,0.630000000000000,0.640000000000000,0.650000000000000,0.660000000000000,0.670000000000000,0.680000000000000,0.690000000000000,0.700000000000000,0.710000000000000,0.720000000000000,0.730000000000000,0.740000000000000,0.750000000000000,0.760000000000000,0.770000000000000,0.780000000000000,0.790000000000000,0.800000000000000,0.810000000000000,0.820000000000000,0.830000000000000,0.840000000000000,0.850000000000000,0.860000000000000,0.870000000000000,0.880000000000000,0.890000000000000,0.900000000000000,0.910000000000000,0.920000000000000,0.930000000000000,0.940000000000000,0.950000000000000,0.960000000000000,0.970000000000000,0.980000000000000,0.990000000000000,1]

poly = np.polyfit(chi, m, deg = 40)
fit_fn = np.poly1d(poly)

f = plt.figure()
ax = f.add_subplot(111)
ax.plot(m, chi, 'r-', label = 'data')
ax.plot(fit_fn(chi), chi, 'b-', label = 'adjust')
ax.set_xlabel('$m$')
ax.set_ylabel('$\chi^2$')
plt.legend()
plt.show()
plt.close()

Body:
The problem is that you mixed the x and the y coordinates while fitting and plotting the fit. Since m is the x-coordinate (independent variable) and chi is the y-coordinate (dependent variable), pass them in the right order. The lines modified are indicated by a comment #

poly = np.polyfit(m, chi, deg = 4) # <-----
fit_fn = np.poly1d(poly)

f = plt.figure()
ax = f.add_subplot(111)
ax.plot(m, chi, 'rx', label = 'data') # <---- Just used x to plot symbols
ax.plot(m, fit_fn(m), 'b-', lw=2, label = 'adjust') # <-----
ax.set_xlabel('$m$')
ax.set_ylabel('$\chi^2$')
plt.legend()
plt.show()
plt.close()


问:
Kivy, RecycleView Add and Delete rows
I'm trying to better understand how the RecycleView functions. Seems like only practical examples will teach me. Docs aren't helping. Kindly have a look at my current screen in the pic below.

Now following are what I'm trying to achieve.

Add/Remove new rows to/from the list.

The first column sl/no should maintain the order even after deleting from in between.

How to achieve 'sort' function? Is it by taking the data into python and do the sort and then update that to the RV again ?

Please find the both .py and .kv codes below.

rv_main.py

```<code>import os
os.environ['KIVY_GL_BACKEND'] = 'gl'
import kivy
kivy.require('1.11.0')

from kivy.uix.boxlayout import BoxLayout
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.recycleview import RecycleView
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.recyclegridlayout import RecycleGridLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.uix.recyclegridlayout import RecycleGridLayout
from kivy.uix.label import Label

from kivy.clock import Clock
from kivy.lang import Builder
from kivy.properties import StringProperty
from kivy.properties import ObjectProperty
from kivy.properties import ListProperty, BooleanProperty
from kivy.properties import NumericProperty

class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior, RecycleBoxLayout):

    ''' Adds selection and focus behaviour to the view. '''
#-----------------------------------------------------------------------
class RecycleViewRow(RecycleDataViewBehavior, BoxLayout):
    ''' Add selection support to the Label '''

    index = None
    selected = BooleanProperty(False)
    selectable = BooleanProperty(True)

    slno    = StringProperty('')
    typ     = StringProperty('')

    def refresh_view_attrs(self, rv, index, data):
        ''' Catch and handle the view changes '''
        self.index = index
        return super(RecycleViewRow, self).refresh_view_attrs(
            rv, index, data)

    def on_touch_down(self, touch):
        ''' Add selection on touch down '''
        if super(RecycleViewRow, self).on_touch_down(touch):
            return True
        if self.collide_point(*touch.pos) and self.selectable:
            return self.parent.select_with_touch(self.index, touch)

    def apply_selection(self, rv, index, is_selected):
        ''' Respond to the selection of items in the view. '''

        self.selected = is_selected

        if is_selected:
            pass
        else:
            pass

    def delete_row(self,rv, index, is_selected):
        if is_selected:
            rv.data.pop(index)
            rv.layout_manager.clear_selection()

#-----------------------------------------------------------------------
class RV(RecycleView):
    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        #fetch data from the database
        self.data = [{'slno': str(x+1),'typ': 'default'} for x in range(4)]

#-----------------------------------------------------------------------

class DataTable(BoxLayout):

    def addRow(self):
        pass

    def removeRow(self):
        pass

#-----------------------------------------------------------------------

class RvMainApp(App):
    def build(self):
        return DataTable()

if __name__ == '__main__':
    RvMainApp().run()
</code>```

rvmain.kv

```<code>#: kivy 1.11.0

<RecycleViewRow>:
    id: rv
    slno: ""
    typ: ""

    canvas.before:
        Color:
            rgba: (.0, 0.9, .1, .3) if self.selected else (0.4, 0.4, 0.4, 1)
        Rectangle:
            pos: self.pos
            size: self.size

    orientation: 'horizontal'
    size_hint: 1.0, 1.0

    Label:
        text: root.slno
        size_hint_x : 1.0

    Label:
        text: root.typ
        size_hint_x : 1.0

#----------------------------------------------------------------
<RV>:
    id : rv
    viewclass: 'RecycleViewRow'
    SelectableRecycleBoxLayout:
        default_size: None, dp(40)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'

#----------------------------------------------------------------
<DataTable>:
    orientation : 'vertical'

    Button:

    BoxLayout:
        Button:
        RV:
        Button:

    BoxLayout:
        Button:
            text: "Add"
            on_release: rv.data.append({"slno": "?", "typ": 'default'})

        Button:
            text: "Remove"
            on_release:
</code>```

答:
You edit the data list of the recycleview. The data will be sorted as it is sorted in that list.

So here is an example of the add remove feature:

```<code>from kivy.app import App
from kivy.lang import Builder

KV = '''

<Row@BoxLayout>:
    ind: 1
    Button:
        text: str(root.ind)
    Button:
        text: "default"

BoxLayout:
    ind: 1
    orientation: "vertical"
    Button:
    BoxLayout:
        Button:
        RecycleView:
            id: rv
            data: [{"text":"first","ind":1}]

            viewclass: 'Row'
            RecycleBoxLayout:
                default_size_hint: 1, None
                default_size: None, dp(56)
                size_hint_y: None
                height: self.minimum_height
                orientation: 'vertical'
        Button
    BoxLayout:
        Button:
            text: "Add"
            on_release:
                root.ind += 1
                rv.data.append({"ind": root.ind})
        Button:
            text: "Remove"
            on_release:
                root.ind = root.ind - 1 if root.ind > 0 else 0
                if len(rv.data): rv.data.pop(-1)

'''

class Test(App):
    def build(self):
        self.root = Builder.load_string(KV)
        return self.root

Test().run()
</code>```

And here is an example on how to sort the data list by some key. In this case ind.

```<code>from kivy.app import App
from kivy.lang import Builder

KV = '''
RecycleView:
    viewclass: 'Label'
    data: sorted([{"text":"!", "ind":3},{"text":"world", "ind":2},{"text":"hello", "ind":1}], key=lambda k: k["ind"])
    RecycleBoxLayout:
        id: layout
        default_size: None, dp(56)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
'''

class TestApp(App):
    def build(self):
        return Builder.load_string(KV)

if __name__ == '__main__':
    TestApp().run()
</code>```

Title: Kivy, RecycleView Add and Delete rows

Body:
I'm trying to better understand how the RecycleView functions. Seems like only practical examples will teach me. Docs aren't helping. Kindly have a look at my current screen in the pic below.

Now following are what I'm trying to achieve.

Add/Remove new rows to/from the list.

The first column sl/no should maintain the order even after deleting from in between.

How to achieve 'sort' function? Is it by taking the data into python and do the sort and then update that to the RV again ?

Please find the both .py and .kv codes below.

rv_main.py

import os
os.environ['KIVY_GL_BACKEND'] = 'gl'
import kivy
kivy.require('1.11.0')

from kivy.uix.boxlayout import BoxLayout
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.recycleview import RecycleView
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.recyclegridlayout import RecycleGridLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.uix.recyclegridlayout import RecycleGridLayout
from kivy.uix.label import Label

from kivy.clock import Clock
from kivy.lang import Builder
from kivy.properties import StringProperty
from kivy.properties import ObjectProperty
from kivy.properties import ListProperty, BooleanProperty
from kivy.properties import NumericProperty

class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior, RecycleBoxLayout):

    ''' Adds selection and focus behaviour to the view. '''
#-----------------------------------------------------------------------
class RecycleViewRow(RecycleDataViewBehavior, BoxLayout):
    ''' Add selection support to the Label '''

    index = None
    selected = BooleanProperty(False)
    selectable = BooleanProperty(True)

    slno    = StringProperty('')
    typ     = StringProperty('')

    def refresh_view_attrs(self, rv, index, data):
        ''' Catch and handle the view changes '''
        self.index = index
        return super(RecycleViewRow, self).refresh_view_attrs(
            rv, index, data)

    def on_touch_down(self, touch):
        ''' Add selection on touch down '''
        if super(RecycleViewRow, self).on_touch_down(touch):
            return True
        if self.collide_point(*touch.pos) and self.selectable:
            return self.parent.select_with_touch(self.index, touch)

    def apply_selection(self, rv, index, is_selected):
        ''' Respond to the selection of items in the view. '''

        self.selected = is_selected

        if is_selected:
            pass
        else:
            pass

    def delete_row(self,rv, index, is_selected):
        if is_selected:
            rv.data.pop(index)
            rv.layout_manager.clear_selection()

#-----------------------------------------------------------------------
class RV(RecycleView):
    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        #fetch data from the database
        self.data = [{'slno': str(x+1),'typ': 'default'} for x in range(4)]

#-----------------------------------------------------------------------

class DataTable(BoxLayout):

    def addRow(self):
        pass

    def removeRow(self):
        pass

#-----------------------------------------------------------------------

class RvMainApp(App):
    def build(self):
        return DataTable()

if __name__ == '__main__':
    RvMainApp().run()

rvmain.kv

#: kivy 1.11.0

<RecycleViewRow>:
    id: rv
    slno: ""
    typ: ""

    canvas.before:
        Color:
            rgba: (.0, 0.9, .1, .3) if self.selected else (0.4, 0.4, 0.4, 1)
        Rectangle:
            pos: self.pos
            size: self.size

    orientation: 'horizontal'
    size_hint: 1.0, 1.0

    Label:
        text: root.slno
        size_hint_x : 1.0

    Label:
        text: root.typ
        size_hint_x : 1.0

#----------------------------------------------------------------
<RV>:
    id : rv
    viewclass: 'RecycleViewRow'
    SelectableRecycleBoxLayout:
        default_size: None, dp(40)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'

#----------------------------------------------------------------
<DataTable>:
    orientation : 'vertical'

    Button:

    BoxLayout:
        Button:
        RV:
        Button:

    BoxLayout:
        Button:
            text: "Add"
            on_release: rv.data.append({"slno": "?", "typ": 'default'})

        Button:
            text: "Remove"
            on_release:

Body:
You edit the data list of the recycleview. The data will be sorted as it is sorted in that list.

So here is an example of the add remove feature:

from kivy.app import App
from kivy.lang import Builder

KV = '''

<Row@BoxLayout>:
    ind: 1
    Button:
        text: str(root.ind)
    Button:
        text: "default"

BoxLayout:
    ind: 1
    orientation: "vertical"
    Button:
    BoxLayout:
        Button:
        RecycleView:
            id: rv
            data: [{"text":"first","ind":1}]

            viewclass: 'Row'
            RecycleBoxLayout:
                default_size_hint: 1, None
                default_size: None, dp(56)
                size_hint_y: None
                height: self.minimum_height
                orientation: 'vertical'
        Button
    BoxLayout:
        Button:
            text: "Add"
            on_release:
                root.ind += 1
                rv.data.append({"ind": root.ind})
        Button:
            text: "Remove"
            on_release:
                root.ind = root.ind - 1 if root.ind > 0 else 0
                if len(rv.data): rv.data.pop(-1)

'''

class Test(App):
    def build(self):
        self.root = Builder.load_string(KV)
        return self.root

Test().run()

And here is an example on how to sort the data list by some key. In this case ind.

from kivy.app import App
from kivy.lang import Builder

KV = '''
RecycleView:
    viewclass: 'Label'
    data: sorted([{"text":"!", "ind":3},{"text":"world", "ind":2},{"text":"hello", "ind":1}], key=lambda k: k["ind"])
    RecycleBoxLayout:
        id: layout
        default_size: None, dp(56)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
'''

class TestApp(App):
    def build(self):
        return Builder.load_string(KV)

if __name__ == '__main__':
    TestApp().run()


问:
Conditional Insert
I want to fill a temporary table on happening of certain condition,
if a select statement return some result than that statement, else another statement will fill table
e.g;

if exists(select name from table where
  name='zain') insert into #table(name)
  --values from above select statement

else if exists(select name from table
  where name='ali')

insert into  #table(name)            --values from above select statement

答:
One way is:</p>

```<code>INSERT INTO #table (name)
SELECT name FROM table WHERE name='zain'

IF (@@ROWCOUNT = 0)
    BEGIN
        INSERT INTO #table (name)
        SELECT name FROM table WHERE name='ali'
    END
</code>```

Title: Conditional Insert

Body:
One way is:

INSERT INTO #table (name)
SELECT name FROM table WHERE name='zain'

IF (@@ROWCOUNT = 0)
    BEGIN
        INSERT INTO #table (name)
        SELECT name FROM table WHERE name='ali'
    END


问:
Problem with deleting files in Laravel and jquery
I'm beginner with Laravel and JQuery.

I have this code:

```<code><ul>
   <li class="file-id-46">- <a
      href="http://test.test/upload/other/1c186a1229c8c502c9bae2794b52a6f0.pdf"
      target="_blank">upload/other/1c186a1229c8c502c9bae2794b52a6f0.pdf</a>
      <a href="#" class="red removeThisFile"
         id="46">[delete file]</a>
   </li>
   <li class="file-id-47">- <a
      href="http://test.test/upload/other/65b13b47f09fc785d901e43e7864bab2.pdf"
      target="_blank">upload/other/65b13b47f09fc785d901e43e7864bab2.pdf</a>
      <a href="#" class="red removeThisFile"
         id="47">[delete file]</a>
   </li>
   <li class="file-id-48">- <a
      href="http://test.test/upload/other/19846324513791f79013fb8e5a7854d8.pdf"
      target="_blank">upload/other/19846324513791f79013fb8e5a7854d8.pdf</a>
      <a href="#" class="red removeThisFile"
         id="48">[delete file]</a>
   </li>
   <li class="file-id-49">- <a
      href="http://test.test/upload/other/fca69b7c02ae223cd167202368d3a555.pdf"
      target="_blank">upload/other/fca69b7c02ae223cd167202368d3a555.pdf</a>
      <a href="#" class="red removeThisFile"
         id="49">[delete file]</a>
   </li>
   <li class="file-id-50">- <a
      href="http://test.test/upload/other/2a1f88cd9f223a423a29594be3d8ce7a.pdf"
      target="_blank">upload/other/2a1f88cd9f223a423a29594be3d8ce7a.pdf</a>
      <a href="#" class="red removeThisFile"
         id="50">[delete file]</a>
   </li>
   <li class="file-id-51">- <a
      href="http://test.test/upload/other/dbe585a9716bd417437be6b0d5695a6a.pdf"
      target="_blank">upload/other/dbe585a9716bd417437be6b0d5695a6a.pdf</a>
      <a href="#" class="red removeThisFile"
         id="51">[delete file]</a>
   </li>
   <li class="file-id-52">- <a
      href="http://test.test/upload/other/585b8aa2cfd6a871eb3ed0e1c6d5e2b9.pdf"
      target="_blank">upload/other/585b8aa2cfd6a871eb3ed0e1c6d5e2b9.pdf</a>
      <a href="#" class="red removeThisFile"
         id="52">[delete file]</a>
   </li>
</ul>

$(".removeThisFile").click(function () {
                    var id = $(this).attr("id");
                    $('.file-id-' + id).hide();
                    $.ajax({
                        url: 'http://test.test/psCMS/removeOtherFile?id=52',
                        type: 'get',
                        dataType: 'json',
                        _token: $('meta[name="_token"]').attr('content'),
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                        },
                        cache: false,
                        success: function (response) {
                            $(this).hide();
                        }
                    });
</code>```

Generally, jquery correctly sends a query to php (Laravel).
The problem occurs in deleting files. The first file is deleted correctly. The next file can not be slept.
I suspect that I have an invalid X-CSRF-TOKEN token after deleting the previous file.

How can I fix this problem?

答:
Its possible that you may have some x-csrf issues, as this doesn't look like what I'm used to seeing (though it may work just fine).  You might have better luck using the @csrf in the top of your form, and calling a general header in an ajax setup method.

```<code>$.ajaxSetup({
 headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
 }
});
</code>```

However, to directly answer you question, I believe the issue is much easier - I think it is a typo. You've hard coded the id.  Try changing this line:

```<code>url: 'http://test.test/psCMS/removeOtherFile?id=52',
</code>```

to:

```<code>url: 'http://test.test/psCMS/removeOtherFile?id='+id, // <--- note the variable
</code>```

Body:
I'm beginner with Laravel and JQuery.

I have this code:

- upload/other/1c186a1229c8c502c9bae2794b52a6f0.pdf
      [delete file]

- upload/other/65b13b47f09fc785d901e43e7864bab2.pdf
      [delete file]

- upload/other/19846324513791f79013fb8e5a7854d8.pdf
      [delete file]

- upload/other/fca69b7c02ae223cd167202368d3a555.pdf
      [delete file]

- upload/other/2a1f88cd9f223a423a29594be3d8ce7a.pdf
      [delete file]

- upload/other/dbe585a9716bd417437be6b0d5695a6a.pdf
      [delete file]

- upload/other/585b8aa2cfd6a871eb3ed0e1c6d5e2b9.pdf
      [delete file]

$(".removeThisFile").click(function () {
                    var id = $(this).attr("id");
                    $('.file-id-' + id).hide();
                    $.ajax({
                        url: 'http://test.test/psCMS/removeOtherFile?id=52',
                        type: 'get',
                        dataType: 'json',
                        _token: $('meta[name="_token"]').attr('content'),
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                        },
                        cache: false,
                        success: function (response) {
                            $(this).hide();
                        }
                    });

Generally, jquery correctly sends a query to php (Laravel).
The problem occurs in deleting files. The first file is deleted correctly. The next file can not be slept.
I suspect that I have an invalid X-CSRF-TOKEN token after deleting the previous file.

How can I fix this problem?

Body:
Its possible that you may have some x-csrf issues, as this doesn't look like what I'm used to seeing (though it may work just fine).  You might have better luck using the @csrf in the top of your form, and calling a general header in an ajax setup method.

$.ajaxSetup({
 headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
 }
});

However, to directly answer you question, I believe the issue is much easier - I think it is a typo. You've hard coded the id.  Try changing this line:

url: 'http://test.test/psCMS/removeOtherFile?id=52',

to:

url: 'http://test.test/psCMS/removeOtherFile?id='+id, // <--- note the variable


问:
How to get the top level key with the highest value of a specific lower level key in json file?
My json file looks like:

```<code>{
    "One": {
        "action": "One",
        "delay": 1558834290.2415142,
        "seconds": 60,
        "score": 10,
        "delta": 1558828290.2415142,
        "grace_sec": 6060
    },
    "Two": {
        "action": "Two",
        "delay": 1558834292.6928985,
        "seconds": 60,
        "score": 9,
        "delta": 1558828292.6928985,
        "grace_sec": 6060
    }
}
</code>```

I want to get the top level key that has the highest value of score, so in this case I would want key One.

I've tried:

```<code>with open("streak.json", "r") as read_file:
                data = json.load(read_file)

highest = max(int(d['score'] for d in data.values()))
</code>```

but I get TypeError: int() argument must be a string, a bytes-like object or a number, not 'generator'

答:
Generate tuples of (inner_value, outer_key) to get the values that you want.

```<code>max((int(value['score']), key) for key, value in data.items())
</code>```

this should evaluate to this tuple

```<code>(10, 'One')
</code>```

which you can process as necessary.

Body:
My json file looks like:

{
    "One": {
        "action": "One",
        "delay": 1558834290.2415142,
        "seconds": 60,
        "score": 10,
        "delta": 1558828290.2415142,
        "grace_sec": 6060
    },
    "Two": {
        "action": "Two",
        "delay": 1558834292.6928985,
        "seconds": 60,
        "score": 9,
        "delta": 1558828292.6928985,
        "grace_sec": 6060
    }
}

I want to get the top level key that has the highest value of score, so in this case I would want key One.

I've tried:

with open("streak.json", "r") as read_file:
                data = json.load(read_file)

highest = max(int(d['score'] for d in data.values()))

but I get TypeError: int() argument must be a string, a bytes-like object or a number, not 'generator'

Body:
Generate tuples of (inner_value, outer_key) to get the values that you want.

max((int(value['score']), key) for key, value in data.items())

this should evaluate to this tuple

(10, 'One')

which you can process as necessary.


问:
Data is inserted and updated using SQL queries....then why do we need doGet,post and put method
In http requestvwe have get, put, post,delete methods..
Post is used for insertion and
Put is used for updating.
These operations are carried out using SQL queries....then what's the point in using doGet,doPost method?</p>

答:
You’re confusing two separate concepts. Http verbs are typically used as part of RESTful web services. So really, this question can be rephrased as “why do we interact with the outside world via web services rather than just giving them direct database access?”

That being the case, one of the most obvious reasons is security. It’s very hard to control how others interact with the data once they have direct access to the database - they can see data that you may not want to show them, and they can make inappropriate edits and deletions.

Also, people would have to understand your database structure as well as the the SQL variant that you’re using. The fact that I know Oracle PL/SQL doesn’t imply knowing how to use MySQL particularly well.

One final point: what makes you so sure that all RESTful services have a SQL database on their back end? Couldn’t they use Hadoop or MongoDB or something like that instead?

Either way, the database logic is an implementation detail. The HTTP verbs are a way for us to interact with each other programmatically without needing to know much about each other’s systems. I don’t care what my vendor’s database looks like - I just care how to call the endpoints they offer me.


问:
Remove grayscale from picture when hovering over a link
EDIT: I solved this problem by making the entire image a link, and the text (former link) that was on the picture i put - pointerevents: none. That way I sort of accomplished what I wanted.

I put image, im hovering over the link that is colored, I want the corresponding picture (top left) to remove grayscaleI have pictures on a page when you hover over them they turn from grayscale to normal colored picture. By default they are seen as grayscale.

Then I have links on that page as well. What I was is, when I hover mouse over link 1 id like the picture 1 to change from grayscale to normal. Same with link 2 and picture 2.

As if mouse was in 2 places at the same time, hovering on link and picture. How can I link them?

```<code><div class="image">
    <img src="images/martin.jpg" alt="kisat">
        <div class="linkcontainer"><a class="teksti" href="urheilija.html">URHEILIJA</a></div>
</div>
</code>```

答:
If the link is directly inside the picture:

```<code>#link:hover > #picture { gray-scale: 0; }
</code>```

If link is next to (after picture closing tag) the picture:

```<code>#link:hover + #picture { gray-scale: 0; }
</code>```

If the link is somewhere inside the picture:

```<code>#link:hover #picture { gray-scale: 0; }
</code>```

If the link is a sibling of the picture:

```<code>#link:hover ~ #picture { gray-scale: 0; }
</code>```

Solution example:

```<code><div class="image">
  <a href='...'>LINKTEXT</a>
  <img id="img" src="...">
</div>

<style>
  .image { position: relative; }
  .image a {
    position: absolute;
    bottom: 0px;
    left: 0;
    right: 0;
    text-align: center;
    z-index: 1;
  }
  a:hover + #img { filter: grayscale(0); }
  #img { filter: grayscale(1); }
</style>
</code>```

Body:
EDIT: I solved this problem by making the entire image a link, and the text (former link) that was on the picture i put - pointerevents: none. That way I sort of accomplished what I wanted.

I put image, im hovering over the link that is colored, I want the corresponding picture (top left) to remove grayscaleI have pictures on a page when you hover over them they turn from grayscale to normal colored picture. By default they are seen as grayscale.

Then I have links on that page as well. What I was is, when I hover mouse over link 1 id like the picture 1 to change from grayscale to normal. Same with link 2 and picture 2.

As if mouse was in 2 places at the same time, hovering on link and picture. How can I link them?

URHEILIJA

Body:
If the link is directly inside the picture:

#link:hover > #picture { gray-scale: 0; }

If link is next to (after picture closing tag) the picture:

#link:hover + #picture { gray-scale: 0; }

If the link is somewhere inside the picture:

#link:hover #picture { gray-scale: 0; }

If the link is a sibling of the picture:

#link:hover ~ #picture { gray-scale: 0; }

Solution example:

<div class="image">
  <a href='...'>LINKTEXT</a>
  <img id="img" src="...">
</div>

<style>
  .image { position: relative; }
  .image a {
    position: absolute;
    bottom: 0px;
    left: 0;
    right: 0;
    text-align: center;
    z-index: 1;
  }
  a:hover + #img { filter: grayscale(0); }
  #img { filter: grayscale(1); }
</style>


问:
Pass Data between route in Slim
I am new to slim and I want to pass Data between two routes (apps)</p>

```<code>$app->get('/answer', function (Request $request, Response $response) use($talk,$voiceName,$message){

    // submit this data
    $request = $request->withAttribute('username','XXXXXX');

    return $response->withJson($ncco);
});

$app->post('/webhooks/comfrimcardinput', function (Request $request, Response $response, $args) use($talk,$voiceName,$message){

    //  Get this data
    $foo = $request->getAttribute('username');

    return $response->withJson($ncco);
});
</code>```

答:
If i understand your question correctly, you want to pass information/data between two routes that get called individually.

Since the request and response objects are generated for each route and only available in the context of that route, it is not possible to attach data to that objects that will persist through page-loads/sessions.

You need to use some kind of storage for persistent data. There are several options for you available. Some store the information server-side, others store them in the browser/client-side. Which one the best solution for your use-case is depends on the kind of data you want to store.

Server-side:

Files

Database

Client-side:

sessionStorage (only available from javascript)

localStorage (only available from javascript)

Cookies (available from php & javascript)

Cookies in PHP:

// write a cookie
setcookie("TestCookie", $value, time()+3600);  /* valid for 1 hour (3600 secods) */

// read a cookie
$value = $_COOKIE["TestCookie"];
```

More Information on cookies in PHP: setcookie, $_COOKIE

Title: Pass Data between route in Slim

Body:
I am new to slim and I want to pass Data between two routes (apps)

$app->get('/answer', function (Request $request, Response $response) use($talk,$voiceName,$message){

    // submit this data
    $request = $request->withAttribute('username','XXXXXX');

    return $response->withJson($ncco);
});

$app->post('/webhooks/comfrimcardinput', function (Request $request, Response $response, $args) use($talk,$voiceName,$message){

    //  Get this data
    $foo = $request->getAttribute('username');

    return $response->withJson($ncco);
});

Body:
If i understand your question correctly, you want to pass information/data between two routes that get called individually.

Since the request and response objects are generated for each route and only available in the context of that route, it is not possible to attach data to that objects that will persist through page-loads/sessions.

You need to use some kind of storage for persistent data. There are several options for you available. Some store the information server-side, others store them in the browser/client-side. Which one the best solution for your use-case is depends on the kind of data you want to store.

Server-side:

Files

Database

Client-side:

sessionStorage (only available from javascript)

localStorage (only available from javascript)

Cookies (available from php & javascript)

Cookies in PHP:

// write a cookie
setcookie("TestCookie", $value, time()+3600);  /* valid for 1 hour (3600 secods) */

// read a cookie
$value = $_COOKIE["TestCookie"];

More Information on cookies in PHP: setcookie, $_COOKIE