问:
How to label all group records separately?
So I have records of each person spotted times in each store from this I want to label the groups differently based on time lag is 5 minutes or a new store id .The data is like below :

```<code>  DT1<-data.table(
  id=c(1,1,1,1,1,1,1,1),
  in_time=c("2017-11-01 08:37:35","2017-11-01 08:38:42","2017-11-01 08:39:45","2017-11-01 08:50:35","2017-11-01 08:51:35","2017-11-01 08:52:44","2017-11-01 08:53:16","2017-11-01 08:59:29"),
  store_id=c(1,1,1,1,1,2,2,2)

  )
  DT1[,in_time:=ymd_hms(in_time)]
</code>```

Then I use the below code to separate each groups.

```<code>DT1[,group:= cumsum(difftime(in_time, shift(in_time, fill=-Inf), units="mins") > 5), by=list(id,store_id)]
</code>```

But then I get the same group again for same id. Is there any way to get different group ids for different groups (you can see group 1 repeating again at 2017-11-01 08:52:44).
Also, I have more than one id so that's why I group by id and store id.

Any help is appreciated.

Body:
So I have records of each person spotted times in each store from this I want to label the groups differently based on time lag is 5 minutes or a new store id .The data is like below :

  DT1<-data.table(
  id=c(1,1,1,1,1,1,1,1),
  in_time=c("2017-11-01 08:37:35","2017-11-01 08:38:42","2017-11-01 08:39:45","2017-11-01 08:50:35","2017-11-01 08:51:35","2017-11-01 08:52:44","2017-11-01 08:53:16","2017-11-01 08:59:29"),
  store_id=c(1,1,1,1,1,2,2,2)

  )
  DT1[,in_time:=ymd_hms(in_time)]

Then I use the below code to separate each groups.

DT1[,group:= cumsum(difftime(in_time, shift(in_time, fill=-Inf), units="mins") > 5), by=list(id,store_id)]

But then I get the same group again for same id. Is there any way to get different group ids for different groups (you can see group 1 repeating again at 2017-11-01 08:52:44).
Also, I have more than one id so that's why I group by id and store id.

Any help is appreciated.

Body:
You can try using rleid to get a unique index and include store_id in it.

library(data.table)
DT1[, group := rleid(store_id, cumsum(difftime(in_time,
                shift(in_time, fill = first(in_time)), units = "mins") > 5)), id]

DT1

#   id             in_time store_id group
#1:  1 2017-11-01 08:37:35        1     1
#2:  1 2017-11-01 08:38:42        1     1
#3:  1 2017-11-01 08:39:45        1     1
#4:  1 2017-11-01 08:50:35        1     2
#5:  1 2017-11-01 08:51:35        1     2
#6:  1 2017-11-01 08:52:44        2     3
#7:  1 2017-11-01 08:53:16        2     3
#8:  1 2017-11-01 08:59:29        2     4


来源: stackexchange

问:
What is the difference between $lt and $not $gt in MongoDB?
db.restaurants.find( { "grades.score": { $not: { $gt: 10 }}}, { "grades.score": 1})

and

db.restaurants.find( { "grades.score": { $lt: 10 }}, { "grades.score": 1})

What would be the difference between these two queries? (i.e. less than 10, and not greater than 10)

答:
Query operators in MongoDB are type sensitive.  If the value in the document is a different type than the argument in the query, it will not match.

This can be leveraged using the $not operator to query specific types

Such as:

{$gte: ""} will match all string values, but not other types

{$not: {$gte: ""} will match all non-string values

For example, if you had these documents in the collection:

```<code>{value: 10},
{value: 5},
{value: 'A'},
{value: 'B'},
{value: null},
{}, //value is missing
</code>```

```<code>A query for            Would match

{value: {$gt:7}}       {value: 10}

{value: {$lt:7}}       {value: 5}

{value: {$not:{$gt:7}} {value: 5},
                       {value: 'A'},
                       {value: 'B'},
                       {value: null},
                       {}
</code>```

Whether this is useful depends very much on how the data is structured and inserted.

ContentLicense: CC BY-SA 4.0

Body:
Query operators in MongoDB are type sensitive.  If the value in the document is a different type than the argument in the query, it will not match.

This can be leveraged using the $not operator to query specific types

Such as:

{$gte: ""} will match all string values, but not other types

{$not: {$gte: ""} will match all non-string values

For example, if you had these documents in the collection:

{value: 10},
{value: 5},
{value: 'A'},
{value: 'B'},
{value: null},
{}, //value is missing

A query for            Would match

{value: {$gt:7}}       {value: 10}

{value: {$lt:7}}       {value: 5}

{value: {$not:{$gt:7}} {value: 5},
                       {value: 'A'},
                       {value: 'B'},
                       {value: null},
                       {}

Whether this is useful depends very much on how the data is structured and inserted.


问:
Can someone explain what will happen in the following function if the array is out of index?
```<code>function remove(items, item){
    for (let i =0; i < items.length; i++) {
        if (items[i] === item){
            return [ ...items.slice(0, i), ...items.slice(i+1)]
        }
    }
}
</code>```

My code is above. I'm curious about the return statement.

答:
The return statement will be executed only if there is a matched case of item inside items.

If item matches then the function is making a new array consisting with the element of the previous values and the next values of the item. That means return array contains all the array elements from the passed array except the item that matched.

This function is buggy in a sense that it does not remove all the item from items array, and does not return anything when there is no match.

Here is a updated version:

```<code>function remove(items, item) {
  let newItems = [];
  for (let i = 0; i < items.length; i++) {
    if (items[i] !== item) {
        // if current item is not equal to searching item, than it
        // should be in the returned array.
        newItems.push(items[i];
    }
    // you should not return if there is match, in that case multiple
    // matching item would not be removed from items array
  }
  // always return the result array whether there is a match or not.
  return newItems;
}
</code>```

Body:
function remove(items, item){
    for (let i =0; i < items.length; i++) {
        if (items[i] === item){
            return [ ...items.slice(0, i), ...items.slice(i+1)]
        }
    }
}

My code is above. I'm curious about the return statement.

Body:
The return statement will be executed only if there is a matched case of item inside items.

If item matches then the function is making a new array consisting with the element of the previous values and the next values of the item. That means return array contains all the array elements from the passed array except the item that matched.

This function is buggy in a sense that it does not remove all the item from items array, and does not return anything when there is no match.

Here is a updated version:

function remove(items, item) {
  let newItems = [];
  for (let i = 0; i < items.length; i++) {
    if (items[i] !== item) {
        // if current item is not equal to searching item, than it
        // should be in the returned array.
        newItems.push(items[i];
    }
    // you should not return if there is match, in that case multiple
    // matching item would not be removed from items array
  }
  // always return the result array whether there is a match or not.
  return newItems;
}


问:
How to Change Class Name Based on Array's Elements?
I'm a JavaScript newbie so kindly use accessible language.

From the code below, I want to change the class name on certain array elements;
that is for elements orange, yellow, violet to use class btn btn-outline-dark instead. Also, can this be done without adding id or class attributes that's not Bootstrap inside the html (something like document.getElementById() is not desirable)?

I tried:

```<code>function Rainbow(){
    body.style.backgroundColor = colors[index % colors.length]
    index++
    if(index=1,index=2,index=5){
        button.className = 'btn btn-outline-dark'
    }
}
</code>```

but it doesn't work.

Full code (also feel free to improve/fix anything else inside):

```<code><!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
        <title>Rainbow Colors</title>
    </head>
    <body>
        <div class="container">
            <div class="row vh-100 d-flex align-items-center">
                <div class="col text-center">
                    <button class="btn btn-outline-light">Rainbow</button>
                </div>
            </div>
        </div>

        <script>
            const colors = ['red','orange','yellow','green','blue','violet'],
            body = document.querySelector('body'),
            button = document.querySelector('button')
            let index = 1

            body.style.backgroundColor = colors[0]
            button.onclick = Rainbow

            function Rainbow(){
                body.style.backgroundColor = colors[index % colors.length]
                index++
            }
        </script>
    </body>
</html>
</code>```

答:
I suspect this line:

```<code>if(index=1,index=2,index=5){
</code>```

doesn't do what you think it does. = is the assignment operator and , creates compound expressions, neither of which will help with what you likely intend.

Try this instead:

```<code>if(index == 1 || index == 2 || index == 5){
</code>```

|| is the logical or operator and == is the comparison operator.

Body:
I'm a JavaScript newbie so kindly use accessible language.

From the code below, I want to change the class name on certain array elements;
that is for elements orange, yellow, violet to use class btn btn-outline-dark instead. Also, can this be done without adding id or class attributes that's not Bootstrap inside the html (something like document.getElementById() is not desirable)?

I tried:

function Rainbow(){
    body.style.backgroundColor = colors[index % colors.length]
    index++
    if(index=1,index=2,index=5){
        button.className = 'btn btn-outline-dark'
    }
}

but it doesn't work.

Full code (also feel free to improve/fix anything else inside):

<!doctype html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
        <title>Rainbow Colors</title>

                    <button class="btn btn-outline-light">Rainbow</button>

Body:
I suspect this line:

if(index=1,index=2,index=5){

doesn't do what you think it does. = is the assignment operator and , creates compound expressions, neither of which will help with what you likely intend.

Try this instead:

if(index == 1 || index == 2 || index == 5){

|| is the logical or operator and == is the comparison operator.


问:
Creating nested array from flat array - Data Structure
I need to create a nested array using the path as reference for the children.
E.g: 4.1 is a child of 4, 4.1.1 is a child of 4.1, 4.2 is a child of 4...
I have this flat array, with all the data and paths. How would be the best approach to create a nested array where the children are nested to its parent based on its path.

Input:

```<code>const list = [
  {
    location: 1,
    path: '4'
  },
  {
    location: 2,
    path: '4.1'
  },
  {
    location: 3,
    path: '4.1.1'
  },
  {
    location: 4,
    path: '4.1.2'
  },
  {
    location: 5,
    path: '4.2'
  },
  {
    location: 6,
    path: '4.2.1'
  },
  {
    location: 7,
    path: '4.3'
  },
  {
    location: 8,
    path: '4.3.1'
  }
];
</code>```

Output:

```<code>const  list = [
  {
    location: 1,
    path: '4',
        children: [
            {
            location: 2,
            path: '4.1',
            children: [
                {
                    location: 3,
                    path: '4.1.1'
                },
                {
                    location: 4,
                    path: '4.1.2'
                },
            ]
        },
            {
                location: 5,
                path: '4.2',
                children: [
                    {
                        location: 6,
                        path: '4.2.1'
                    },
                ]
            },
            {
                location: 7,
                path: '4.3',
                children: [
                    {
                        location: 8,
                        path: '4.3.1'
                    }
                ]
            },
        ]
  },
];
</code>```

The best approach would be something recursive.
Any suggestions for this algorithm?

答:
You can first sort the array of objects by path so that the parent will always be before it's children in the sorted array.
eg: '4' will be before '4.1'

Now, you can create an object where the keys are the paths. Let's assume '4' is already inserted in our object.

```<code>obj = {
  '4': {
    "location": 1,
    "path": "4",
  }
}
</code>```

When we process '4.1', we first check if '4' is present in our object. If yes, we now go into its children (if the key 'children' isn't present, we create a new empty object) and check if '4.1' is present. If not, we insert '4.1'

```<code>obj = {
  '4': {
    "location": 1,
    "path": "4",
    "children": {
      "4.1": {
        "location": 2,
        "path": "4.1"
      }
    }
  }
}
</code>```

We repeat this process for each element in list. Finally, we just have to recursively convert this object into an array of objects.

Final code:

```<code>list.sort(function(a, b) {
  return a.path - b.path;
})

let obj = {}

list.forEach(x => {
  let cur = obj;
  for (let i = 0; i < x.path.length; i += 2) {
    console.log(x.path.substring(0, i + 1))
    if (x.path.substring(0, i + 1) in cur) {
      cur = cur[x.path.substring(0, i + 1)]
      if (!('children' in cur)) {
        cur['children'] = {}
      }
      cur = cur['children']
    } else {
      break;
    }
  }
  cur[x.path] = x;
})

function recurse (obj) {
  let res = [];
  Object.keys(obj).forEach((key) => {
    if (obj[key]['children'] !== null && typeof obj[key]['children'] === 'object') {
      obj[key]['children'] = recurse(obj[key]['children'])
    }
    res.push(obj[key])
  })
  return res;
}

console.log(recurse(obj));
</code>```

Body:
I need to create a nested array using the path as reference for the children.
E.g: 4.1 is a child of 4, 4.1.1 is a child of 4.1, 4.2 is a child of 4...
I have this flat array, with all the data and paths. How would be the best approach to create a nested array where the children are nested to its parent based on its path.

Input:

const list = [
  {
    location: 1,
    path: '4'
  },
  {
    location: 2,
    path: '4.1'
  },
  {
    location: 3,
    path: '4.1.1'
  },
  {
    location: 4,
    path: '4.1.2'
  },
  {
    location: 5,
    path: '4.2'
  },
  {
    location: 6,
    path: '4.2.1'
  },
  {
    location: 7,
    path: '4.3'
  },
  {
    location: 8,
    path: '4.3.1'
  }
];

Output:

const  list = [
  {
    location: 1,
    path: '4',
        children: [
            {
            location: 2,
            path: '4.1',
            children: [
                {
                    location: 3,
                    path: '4.1.1'
                },
                {
                    location: 4,
                    path: '4.1.2'
                },
            ]
        },
            {
                location: 5,
                path: '4.2',
                children: [
                    {
                        location: 6,
                        path: '4.2.1'
                    },
                ]
            },
            {
                location: 7,
                path: '4.3',
                children: [
                    {
                        location: 8,
                        path: '4.3.1'
                    }
                ]
            },
        ]
  },
];

The best approach would be something recursive.
Any suggestions for this algorithm?

Body:
You can first sort the array of objects by path so that the parent will always be before it's children in the sorted array.
eg: '4' will be before '4.1'

Now, you can create an object where the keys are the paths. Let's assume '4' is already inserted in our object.

obj = {
  '4': {
    "location": 1,
    "path": "4",
  }
}

When we process '4.1', we first check if '4' is present in our object. If yes, we now go into its children (if the key 'children' isn't present, we create a new empty object) and check if '4.1' is present. If not, we insert '4.1'

obj = {
  '4': {
    "location": 1,
    "path": "4",
    "children": {
      "4.1": {
        "location": 2,
        "path": "4.1"
      }
    }
  }
}

We repeat this process for each element in list. Finally, we just have to recursively convert this object into an array of objects.

Final code:

list.sort(function(a, b) {
  return a.path - b.path;
})

let obj = {}

list.forEach(x => {
  let cur = obj;
  for (let i = 0; i < x.path.length; i += 2) {
    console.log(x.path.substring(0, i + 1))
    if (x.path.substring(0, i + 1) in cur) {
      cur = cur[x.path.substring(0, i + 1)]
      if (!('children' in cur)) {
        cur['children'] = {}
      }
      cur = cur['children']
    } else {
      break;
    }
  }
  cur[x.path] = x;
})

function recurse (obj) {
  let res = [];
  Object.keys(obj).forEach((key) => {
    if (obj[key]['children'] !== null && typeof obj[key]['children'] === 'object') {
      obj[key]['children'] = recurse(obj[key]['children'])
    }
    res.push(obj[key])
  })
  return res;
}

console.log(recurse(obj));


问:
React State with object
I am trying to update my state from my react dynamically, this is my current state.

```<code>this.state = {
      title: "",
      image: "",
      imageFile: "",
      formTitle: "",
      formMessage: "",
      formImage: "",
      Item: {
        name: "Name",
        price: "",
        quantity: "",
        discount: "",
        shipping: "",
        image: "",
        formType: ""
      }
    }
</code>```

How do I update in my Textbox dynamically instead of one by one?

```<code> setItemName = (name) => {
    this.setState({
      Item: {
        ...this.state.Item,
        name
      }
    });
  };
</code>```

this is my attempt at solving this

and this is my Textbox using material UI

```<code><TextField
                      className="my-24"
                      label="Item Name"
                      autoFocus
                      id="itemName"
                      name="itemName"
                      width={1}
                      value={this.state.Item.name}
                      onChange={this.setItemName}
                      variant="outlined"
                    />

</code>```

Thanks!!

答:
```<code>setItem = (key, value) => {
  this.setState({
    Item: {
      ...this.state.Item,
      [key]: value
    }
  });
});
</code>```

Title: React State with object

Body:
I am trying to update my state from my react dynamically, this is my current state.

this.state = {
      title: "",
      image: "",
      imageFile: "",
      formTitle: "",
      formMessage: "",
      formImage: "",
      Item: {
        name: "Name",
        price: "",
        quantity: "",
        discount: "",
        shipping: "",
        image: "",
        formType: ""
      }
    }

How do I update in my Textbox dynamically instead of one by one?

 setItemName = (name) => {
    this.setState({
      Item: {
        ...this.state.Item,
        name
      }
    });
  };

this is my attempt at solving this

and this is my Textbox using material UI

<TextField
                      className="my-24"
                      label="Item Name"
                      autoFocus
                      id="itemName"
                      name="itemName"
                      width={1}
                      value={this.state.Item.name}
                      onChange={this.setItemName}
                      variant="outlined"
                    />

Thanks!!


问:
using @ symbol with ftp stream in DirectoryIterator
I'm using DirectoryIterator class to list ftp content:
$a = new DirectoryIterator('ftp://user:password@host');

If there is an at "@" character in login, i get an error:
failed to open dir: operation failed

How i can escape @ symbol in login?

I try:
%40,
+
\@

答:
I am not that sure you can use DirectoryIterator as FTP client

You may want to learn how to use ftp_rawlist to get a list of the given directory

ContentLicense: CC BY-SA 3.0


问:
Convert capacitor Camera result to Blob
I need to convert the result from the Capacitor Camera plugin to a Blob for upload to Firebase Storage.

I could upload the Base64 string but I already upload Blobs/Files from a Browse button's FileList so I'd like not to change the design of this.

The Camera plugin provides the image data as a Base64 encoded string representing a PNG image.

I've tried the following:

const { Camera } = Plugins;

const image = await Camera.getPhoto({
  quality: 90,
  allowEditing: true,
  resultType: CameraResultType.Base64
});

const rawData = atob(image.base64String);
const blob = new Blob([rawData], { type: 'image/png' });
```

But the blob ends up not being a valid image.

Any help is appreciated.

Using: @angular/core: 9.1.4, @ionic/angular: 5.1.0, @capacitor/core: 2.1.1

答:
You need to take the byte characters provided by atob and convert it to a byte array, which can then be used to generate a Blob:

const rawData = atob(image.base64String);
const bytes = new Array(rawData.length);
for (var x = 0; x < rawData.length; x++) {
    bytes[x] = rawData.charCodeAt(x);
}
const arr = new Uint8Array(bytes);
const blob = new Blob([arr], {type: 'image/png'});
```

Title: Convert capacitor Camera result to Blob

Body:
I need to convert the result from the Capacitor Camera plugin to a Blob for upload to Firebase Storage.

I could upload the Base64 string but I already upload Blobs/Files from a Browse button's FileList so I'd like not to change the design of this.

The Camera plugin provides the image data as a Base64 encoded string representing a PNG image.

I've tried the following:

const { Camera } = Plugins;

const image = await Camera.getPhoto({
  quality: 90,
  allowEditing: true,
  resultType: CameraResultType.Base64
});

const rawData = atob(image.base64String);
const blob = new Blob([rawData], { type: 'image/png' });

But the blob ends up not being a valid image.

Any help is appreciated.

Using: @angular/core: 9.1.4, @ionic/angular: 5.1.0, @capacitor/core: 2.1.1


问:
How to use db.subtract after time using glitch.com, discord.js
Basically im trying to run this code

```<code>const Discord = require('discord.js');
const fs = require('fs');
const db = require("quick.db");

module.exports.run = async (bot, message, args) => {
let user = message.member;

 let vic = db.get(`vic_${user.id}`);
    console.log("Activating auto start command!");

    let intro = new Discord.RichEmbed()
    .setTitle("You have dosed on vicodin and you are now immune to all shots")
    .setColor('#00cc00');
  let nopill = new Discord.RichEmbed()
  .setTitle("You do not own this drug")
  .addField("Error", "<:bluepill:713790607901982780> --- **You do not own any `Vicodin Pills`, please purchase off of the black market** --- <:bluepill:713790607901982780>")
  .setFooter("Must own first")
   let pill = new Discord.RichEmbed()
  .setTitle("You have already dosed")
  .addField("Error", "<:bluepill:713790607901982780> --- **You have already dosed on `Vicodin Pills`, please wait until the effect wear off to dose again** --- <:bluepill:713790607901982780>")
  .setFooter("Already dosed")
   if (args[0].startsWith("testing")) {
      if (vic === null) return  message.channel.send(nopill)
   } else if (args[0].startsWith("vicodin")) {

   if (vic === 0) return  message.channel.send(nopill)
 if (vic === 2) return message.channel.send(pill)

      message.channel.send(intro)

       db.set(`vic_${user.id}`, 2)
  console.log(`${user} just dosed vicodine`);
    setTimeout(() => {
          console.log(`this is a test by zuc`)
          db.set(`vic_${user.id}`, 0)

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

What it dose is when a user run the Dose command it makes them dose on the pill, im trying to make the pill/dose remove after a certain amount of time using  db.subtract, since im using glitch.com to do this, the setTimeout isnt doing what i want it to after that time.

答:
Change the timeout code to:

    setTimeout(() => {
     console.log(`this is a test by zuc`)
      db.delete(`vic_${user.id}`);
      db.add(`vic_${user.id}`, 0);
    }, 1800000);
```

Body:
Basically im trying to run this code

const Discord = require('discord.js');
const fs = require('fs');
const db = require("quick.db");

module.exports.run = async (bot, message, args) => {
let user = message.member;

 let vic = db.get(`vic_${user.id}`);
    console.log("Activating auto start command!");

    let intro = new Discord.RichEmbed()
    .setTitle("You have dosed on vicodin and you are now immune to all shots")
    .setColor('#00cc00');
  let nopill = new Discord.RichEmbed()
  .setTitle("You do not own this drug")
  .addField("Error", "<:bluepill:713790607901982780> --- **You do not own any `Vicodin Pills`, please purchase off of the black market** --- <:bluepill:713790607901982780>")
  .setFooter("Must own first")
   let pill = new Discord.RichEmbed()
  .setTitle("You have already dosed")
  .addField("Error", "<:bluepill:713790607901982780> --- **You have already dosed on `Vicodin Pills`, please wait until the effect wear off to dose again** --- <:bluepill:713790607901982780>")
  .setFooter("Already dosed")
   if (args[0].startsWith("testing")) {
      if (vic === null) return  message.channel.send(nopill)
   } else if (args[0].startsWith("vicodin")) {

   if (vic === 0) return  message.channel.send(nopill)
 if (vic === 2) return message.channel.send(pill)

      message.channel.send(intro)

       db.set(`vic_${user.id}`, 2)
  console.log(`${user} just dosed vicodine`);
    setTimeout(() => {
          console.log(`this is a test by zuc`)
          db.set(`vic_${user.id}`, 0)

            }, 1800000);
        }
    }

What it dose is when a user run the Dose command it makes them dose on the pill, im trying to make the pill/dose remove after a certain amount of time using  db.subtract, since im using glitch.com to do this, the setTimeout isnt doing what i want it to after that time.


问:
How to set Javascript's variable value inside <input value=''">
I do not know how to formulate this question but it is near close to my issue. I am trying to make a Point of sale system so when client clicks in each product it adds in the table. There are no issues in my code but I do not know how to set the product's price using a textbox when using .append.

This is my code:

```<code>$(".agregarListaF").click(function (e) {
  e.preventDefault();
  var padre = $(this);
  var hijos = padre.children().children("span");
  var i = 0;
  var datos = new Array();

  hijos.each(function () {
    switch (i) {
      case 0:
        datos[0] = $(this).text();
        break;

      case 1:
        padre;
        datos[1] = $(this).text();
        break;

      case 2:
        padre;
        datos[2] = $(this).text();
        break;
    }

    i++;
  });
  console.log(datos[0]);
  console.log(datos[1]);

  $(".detallefactura").append(
    "<tr>" +
      "<td>" +
      datos[0] +
      "</td>" +
      "<td>" +
      datos[1] +
      "</td>" +
      "<td>" +
      "<input type='text' class='form-control text-center' value='1'>" +
      "</td>" +
      "<td>" +
      "<input type='text' class='form-control text-center' value=''>" +
      "</td>" +
      "<td class='tota-sub-fila'>" +
      parseFloat(Math.floor(datos[2]) * parseFloat(1)).toFixed(2) +
      "</td>"
  );
});
</code>```

My issue is in the line:

```<code> + "<td>" + "<input type='text' class='form-control text-center' value=''>" + "</td>"
</code>```

I want to add javascript value variable inside * input value=''* but I know It wont work but I tried it:

```<code>+ "<td>" + "<input type='text' class='form-control text-center' value='datos[2]'>" + "</td>"
</code>```

This is my point of sale view:

In the column precio is where I want to set the price inside that textbox.

How do I solve this?

答:
Follow this using template literals

```<code> const html = `<tr>
    <td>${datos[0]}</td>
    <td>${datos[1]}</td>
    <td><input type="text" class="form-control text-center" value="${datos[3]}"></td>
    <td><input type="text" class="form-control text-center" value="${datos[4]}"</td>
    <td class="tota-sub-fila">${parseFloat((Math.floor(datos[2])) * parseFloat(1)).toFixed(2)}</td>
 </tr>`;

$(.detallefactura").append(html);
</code>```

Body:
I do not know how to formulate this question but it is near close to my issue. I am trying to make a Point of sale system so when client clicks in each product it adds in the table. There are no issues in my code but I do not know how to set the product's price using a textbox when using .append.

This is my code:

$(".agregarListaF").click(function (e) {
  e.preventDefault();
  var padre = $(this);
  var hijos = padre.children().children("span");
  var i = 0;
  var datos = new Array();

  hijos.each(function () {
    switch (i) {
      case 0:
        datos[0] = $(this).text();
        break;

      case 1:
        padre;
        datos[1] = $(this).text();
        break;

      case 2:
        padre;
        datos[2] = $(this).text();
        break;
    }

    i++;
  });
  console.log(datos[0]);
  console.log(datos[1]);

  $(".detallefactura").append(
    "
" +
      "" +
      datos[0] +
      "	" +
      "" +
      datos[1] +
      "	" +
      "" +
      "<input type='text' class='form-control text-center' value='1'>" +
      "	" +
      "" +
      "<input type='text' class='form-control text-center' value=''>" +
      "	" +
      "" +
      parseFloat(Math.floor(datos[2]) * parseFloat(1)).toFixed(2) +
      "	"
  );
});

My issue is in the line:

 + "" + "<input type='text' class='form-control text-center' value=''>" + "	"

I want to add javascript value variable inside * input value=''* but I know It wont work but I tried it:

+ "" + "<input type='text' class='form-control text-center' value='datos[2]'>" + "	"

This is my point of sale view:

In the column precio is where I want to set the price inside that textbox.

How do I solve this?

Body:
Follow this using template literals

 const html = `<tr>
    <td>${datos[0]}</td>
    <td>${datos[1]}</td>
    <td><input type="text" class="form-control text-center" value="${datos[3]}"></td>
    <td><input type="text" class="form-control text-center" value="${datos[4]}"</td>
    <td class="tota-sub-fila">${parseFloat((Math.floor(datos[2])) * parseFloat(1)).toFixed(2)}</td>
 </tr>`;

$(.detallefactura").append(html);


问:
Product reference is undefiend
I have a model named order. The order model is having a field name product which is a reference to the product model.
My Order model is like

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
const { ObjectId } = mongoose.Schema;
const ProductCartSchema = new Schema({
  product: {
    type: ObjectId,
    ref: Product,
  },
  name: String,
  count: Number,
  price: Number,
});

const orderSchema = new Schema(
  {
    products: [ProductCartSchema],
    transaction_id: {},
    amount: { type: Number },
    address: { type: String },
    updated: Date,
    user: {
      type: ObjectId,
      ref: User,
    },
  },
  { timestamps: true }
);

var Order = mongoose.model('Order', orderSchema);
var ProductCart = mongoose.model('ProductCart', ProductCartSchema);

module.exports = { Order, ProductCart };
</code>```

And my product model schema is like

```<code>    var mongoose = require(mongoose);
var Schema = mongoose.Schema;
const { ObjectId } = mongoose.Schema;
const productSchema = new Schema(
  {
    name: {
      type: String,
      required: true,
      maxlength: 32,
      trim: true,
    },
    description: {
      type: String,
      required: true,
      maxlength: 2000,
      trim: true,
    },
    price: {
      type: Number,
      required: true,
      maxlength: 32,
      trim: true,
    },
    category: {
      type: ObjectId,
      ref: 'Category',
      required: true,
    },
    stock: {
      type: Number,
    },
    sold: {
      type: Number,
      default: 0,
    },
    photo: {
      type: Buffer,
      contentType: String,
    },
  },
  { timestamps: true }
);
module.exports = mongoose.model('Product', productSchema);
</code>```

It's giving me error

Product is not defined on order.js line no 7

Am I need to import product model in this if yes then how I can do that and if not then where is the error

答:
In order to use Product reference in your Order.js Schema, you need to import it.</p>

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
const { ObjectId } = mongoose.Schema;
var Product = require('Product'); <----------------------------------- Import this
const ProductCartSchema = new Schema({
  product: {
    type: ObjectId,
    ref: Product,
  },
  name: String,
  count: Number,
  price: Number,
});

const orderSchema = new Schema(
  {
    products: [ProductCartSchema],
    transaction_id: {},
    amount: { type: Number },
    address: { type: String },
    updated: Date,
    user: {
      type: ObjectId,
      ref: User,
    },
  },
  { timestamps: true }
);

var Order = mongoose.model('Order', orderSchema);
var ProductCart = mongoose.model('ProductCart', ProductCartSchema);

module.exports = { Order, ProductCart };
</code>```

Title: Product reference is undefiend

Body:
I have a model named order. The order model is having a field name product which is a reference to the product model.
My Order model is like

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
const { ObjectId } = mongoose.Schema;
const ProductCartSchema = new Schema({
  product: {
    type: ObjectId,
    ref: Product,
  },
  name: String,
  count: Number,
  price: Number,
});

const orderSchema = new Schema(
  {
    products: [ProductCartSchema],
    transaction_id: {},
    amount: { type: Number },
    address: { type: String },
    updated: Date,
    user: {
      type: ObjectId,
      ref: User,
    },
  },
  { timestamps: true }
);

var Order = mongoose.model('Order', orderSchema);
var ProductCart = mongoose.model('ProductCart', ProductCartSchema);

module.exports = { Order, ProductCart };

And my product model schema is like

    var mongoose = require(mongoose);
var Schema = mongoose.Schema;
const { ObjectId } = mongoose.Schema;
const productSchema = new Schema(
  {
    name: {
      type: String,
      required: true,
      maxlength: 32,
      trim: true,
    },
    description: {
      type: String,
      required: true,
      maxlength: 2000,
      trim: true,
    },
    price: {
      type: Number,
      required: true,
      maxlength: 32,
      trim: true,
    },
    category: {
      type: ObjectId,
      ref: 'Category',
      required: true,
    },
    stock: {
      type: Number,
    },
    sold: {
      type: Number,
      default: 0,
    },
    photo: {
      type: Buffer,
      contentType: String,
    },
  },
  { timestamps: true }
);
module.exports = mongoose.model('Product', productSchema);

It's giving me error

Product is not defined on order.js line no 7

Am I need to import product model in this if yes then how I can do that and if not then where is the error

Body:
In order to use Product reference in your Order.js Schema, you need to import it.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
const { ObjectId } = mongoose.Schema;
var Product = require('Product'); <----------------------------------- Import this
const ProductCartSchema = new Schema({
  product: {
    type: ObjectId,
    ref: Product,
  },
  name: String,
  count: Number,
  price: Number,
});

const orderSchema = new Schema(
  {
    products: [ProductCartSchema],
    transaction_id: {},
    amount: { type: Number },
    address: { type: String },
    updated: Date,
    user: {
      type: ObjectId,
      ref: User,
    },
  },
  { timestamps: true }
);

var Order = mongoose.model('Order', orderSchema);
var ProductCart = mongoose.model('ProductCart', ProductCartSchema);

module.exports = { Order, ProductCart };


问:
How to replace parameter of a json file by a shell script?
Let's say 123.json with below content:

```<code>{
  "LINE" : {
    "A_serial" : "1234",
    "B_serial" : "2345",
    "C_serial" : "3456",
    "X_serial" : "76"
  }
}
</code>```

If I want to use a shell script to change the parameter of X_serial by the original number +1 which is 77 in this example.
I have tried the below script to take out the parameter of X_serial:

```<code>grep "X_serial" 123.json | awk {print"$3"}
</code>```

which outputs 76. But then I don't know how to make it into 77 and then put it back to the parameter of X_serial.

答:
sed or perl, depending on whether you just need string substitution or something more sophisticated, like arithmetic.

Since you tried grep and awk, let's start with sed:

In all lines that contain TEXT, replace foo with bar

```<code>sed -n '/TEXT/ s/foo/bar/ p'
</code>```

So in your case, something like:

```<code>sed -n '/X_serial/ s/\"76\"/\"77\"/ p'
</code>```

or

```<code>$ cat 123.json | sed  '/X_serial/ s/\"76\"/\"77\"/' > new.json
</code>```

This performs a literal substiution: "76" -> "77"

If you would like to perform arithmetic, like "+1" or "+10" then use perl not sed:

```<code>$ cat 123.json | perl -pe 's/\d+/$&+10/e if /X_serial/'
{
  "LINE" : {
    "A_serial" : "1234",
    "B_serial" : "2345",
    "C_serial" : "3456",
    "X_serial" : "86"
  }
}
</code>```

This operates on all lines containing X_serial (whether under "LINE" or under something else), as it is not a json parser.

Body:
Let's say 123.json with below content:

{
  "LINE" : {
    "A_serial" : "1234",
    "B_serial" : "2345",
    "C_serial" : "3456",
    "X_serial" : "76"
  }
}

If I want to use a shell script to change the parameter of X_serial by the original number +1 which is 77 in this example.
I have tried the below script to take out the parameter of X_serial:

grep "X_serial" 123.json | awk {print"$3"}

which outputs 76. But then I don't know how to make it into 77 and then put it back to the parameter of X_serial.

Body:
sed or perl, depending on whether you just need string substitution or something more sophisticated, like arithmetic.

Since you tried grep and awk, let's start with sed:

In all lines that contain TEXT, replace foo with bar

sed -n '/TEXT/ s/foo/bar/ p'

So in your case, something like:

sed -n '/X_serial/ s/\"76\"/\"77\"/ p'

or

$ cat 123.json | sed  '/X_serial/ s/\"76\"/\"77\"/' > new.json

This performs a literal substiution: "76" -> "77"

If you would like to perform arithmetic, like "+1" or "+10" then use perl not sed:

$ cat 123.json | perl -pe 's/\d+/$&+10/e if /X_serial/'
{
  "LINE" : {
    "A_serial" : "1234",
    "B_serial" : "2345",
    "C_serial" : "3456",
    "X_serial" : "86"
  }
}

This operates on all lines containing X_serial (whether under "LINE" or under something else), as it is not a json parser.


问:
PHP variable in Javascript
Consider this simple example;

```<code><?php $text = test; ?>

<script type="text/javascript" defer="defer">

var test;

test = "<?php echo $text; ?>"

$(document).ready(function(){
alert(test);
});

</script>
</code>```

This works fine. Creating the alert with the text from the php var. However, if I place;

```<code><?php $text = test; ?>
</code>```

below the script - it does not work. I've tried the defer function. What am I doing wrong?

Cheers

答:
Seems like you are trying to assign a client-side variable to a server-side variable?

Due to my knowledge, server-side variables can NOT "interact" directly with client-sider variables without anything in between. This means <?php $test = test; ?> doesn't work properly since variables that are included in <?php ?> will be treated as server-side variables, and thus, your client-side variable test is either considered as

an undefined constant, or

a string without quotes ''

Title: PHP variable in Javascript

Body:
Consider this simple example;

<?php $text = test; ?>

This works fine. Creating the alert with the text from the php var. However, if I place;

<?php $text = test; ?>

below the script - it does not work. I've tried the defer function. What am I doing wrong?

Cheers


问:
Cloudflare or WAF for blocking wp-loign.php but allowing wp-login.php?foo=bar
Im new to waf rules and wondering how I would go about blocking wp-login.php but allow parameter strings after wp-login.php.

Hopefully via cloudflare rules.

Im using a hide login page plugin and it 403s wp-login.php  but allows wp-login.php?parameters, but I would also like to waf it so it doesn't eat up my bandwidth.

答:
Why not matching /*wp-login.php*?

It will match:

wp-login.php?parameter as you wish.

//wp-login.php (I used to see bot using this URL to bypass some weak rules).


问:
Node.js express: trying to get text from HTML form, req.body empty
I'm trying to build a basic text to speech form, but I cannot grab the text from the form.
I'm trying to get text from an HTML form using an express server and req.body turns up empty every time. I've tried using body-parser and changing the enctype on the form, nothing seems to work.

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>index.html</title>
  </head>
  <body>

    <h1>Speech!!</h1>
    <main>
        <form action="/speak" method="POST" id="speak-form" enctype="multipart/form-data">
            <div id="text-container">
                <label for="text-box">Text to Speech!</label>
                <input type="text" id="text-box" title="text" placeholder="Type what you want to say here!"/>
            </div>
            <div class="button-container">
                <button type="submit" id="submit-button">Speak!</button>
            </div>
            <div class="button-container">
                <button type="reset" id="clear-form">Clear Text</button>
            </div>
        </form>
    </main>
  </body>
</html>
</code>```

app.js

```<code>    const express = require("express");
    const bodyParser = require('body-parser');
    const app = express();
    const configRoutes = require("./routes");

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));

    configRoutes(app);

    app.listen(3000, () => {
      console.log("Speech Server");
    });
</code>```

index.js

```<code>const express = require("express");
const speakRoutes = require("./speak");

const constructorMethod = (app) => {
    app.use("/speak",speakRoutes);

    app.use("*", (req,res) => {
        res.sendFile("index.html", { root: "./public" });
    });
};

module.exports = constructorMethod;
</code>```

speak.js

```<code>const express = require("express");
const router = express.Router();

router.post("/", async (req,res) => {
    console.log("POST");
    console.log(req.body);
    res.sendFile("index.html", { root: "./public" });
});

module.exports = router;
</code>```

I would greatly appreciate some help! Thank you!

答: I fixed my own issue! It worked by changing post to get in the route and the html form method, and req.body to req.query

Body:
I'm trying to build a basic text to speech form, but I cannot grab the text from the form.
I'm trying to get text from an HTML form using an express server and req.body turns up empty every time. I've tried using body-parser and changing the enctype on the form, nothing seems to work.

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>index.html</title>

Speech!!

        <form action="/speak" method="POST" id="speak-form" enctype="multipart/form-data">

                Text to Speech!
                <input type="text" id="text-box" title="text" placeholder="Type what you want to say here!"/>

                <button type="submit" id="submit-button">Speak!</button>

                <button type="reset" id="clear-form">Clear Text</button>

        </form>

app.js

    const express = require("express");
    const bodyParser = require('body-parser');
    const app = express();
    const configRoutes = require("./routes");

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));

    configRoutes(app);

    app.listen(3000, () => {
      console.log("Speech Server");
    });

index.js

const express = require("express");
const speakRoutes = require("./speak");

const constructorMethod = (app) => {
    app.use("/speak",speakRoutes);

    app.use("*", (req,res) => {
        res.sendFile("index.html", { root: "./public" });
    });
};

module.exports = constructorMethod;

speak.js

const express = require("express");
const router = express.Router();

router.post("/", async (req,res) => {
    console.log("POST");
    console.log(req.body);
    res.sendFile("index.html", { root: "./public" });
});

module.exports = router;

I would greatly appreciate some help! Thank you!


问:
Perl try catch for user defined exceptions
I want to know if perl has some try catch mechanism similar to python where i can raise user defined exceptions and handle accordingly.

PythonCode:

```<code>   try:
       number = 6
       i_num = 3
       if i_num < number:
           raise ValueTooSmallError
       elif i_num > number:
           raise ValueTooLargeError
       break
   except ValueTooSmallError:
       print("This value is too small, try again!")
       print()
   except ValueTooLargeError:
       print("This value is too large, try again!")
       print()
</code>```

I know perl has try catch mechnism like below:

```<code>sub method_one {
    try {
        if ("number" eq "one") {
            die("one");
        } else {
            die("two");
        }
    } catch {
        if ($@ eq "one") {
            print "Failed at one";
        }
    }
}
</code>```

OR

```<code>eval {
    open(FILE, $file) ||
      die MyFileException->new("Unable to open file - $file");
  };

  if ($@) {
    # now $@ contains the exception object of type MyFileException
    print $@->getErrorMessage();
    # where getErrorMessage() is a method in MyFileException class
  }
</code>```

I am concentrating more on the if checks on the catch. Is there a way i can avoid the checks for the different kind of errors i catch.

答:
Like @daxim pointed out, there is TryCatch, but I am writing this for all those who would see this and to alert them that unfortunately TryCatch is now broken since the version 0.006020 of Devel::Declare on which TryCatch relies.

In replacement, there is Nice::Try which is quite unique and provides all the features like in other programming languages.

It supports exception variable assignment, exception class like the OP requested, clean-up with finally block, embedded try-catch blocks.

Full disclosure: I have developed Nice::Try when TryCatch got broken.

Body:
I want to know if perl has some try catch mechanism similar to python where i can raise user defined exceptions and handle accordingly.

PythonCode:

   try:
       number = 6
       i_num = 3
       if i_num < number:
           raise ValueTooSmallError
       elif i_num > number:
           raise ValueTooLargeError
       break
   except ValueTooSmallError:
       print("This value is too small, try again!")
       print()
   except ValueTooLargeError:
       print("This value is too large, try again!")
       print()

I know perl has try catch mechnism like below:

sub method_one {
    try {
        if ("number" eq "one") {
            die("one");
        } else {
            die("two");
        }
    } catch {
        if ($@ eq "one") {
            print "Failed at one";
        }
    }
}

OR

eval {
    open(FILE, $file) ||
      die MyFileException->new("Unable to open file - $file");
  };

  if ($@) {
    # now $@ contains the exception object of type MyFileException
    print $@->getErrorMessage();
    # where getErrorMessage() is a method in MyFileException class
  }

I am concentrating more on the if checks on the catch. Is there a way i can avoid the checks for the different kind of errors i catch.


问:
Reading rows from Google sheets but the returning array is null
I would like to read data from google sheets and then write cell values to input type text fields. Firefox returns an error "TypeError: conteudo is null" when I try to access an array returning data from GSheets.
This is the link to my google sheets example.

Sample data

```
Nome: Name
Data_Nascimento: 20/07/1950
CPF: 12345678
```

See below my code.

File: code.gs

```<code>function doGet(request) {
    setPage('index');
    return HtmlService
    .createTemplateFromFile('index')
    .evaluate()
    .addMetaTag('viewport', 'width=device-width, initial-scale=1')
    .setTitle("teste");
  }

function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename).getContent();
}

var urlss = "https://docs.google.com/spreadsheets/d/1q8kz2L2q4u99dvR0zeDuCghSgtlNKMpbmZgCRHC3hn0/edit?usp=sharing";

function setPage(page) {
  var ps=PropertiesService.getUserProperties();
  ps.setProperty('PageTitle', page);
  return ps.getProperty('PageTitle');
}

function getConsultaPacientes() {

  var ss = SpreadsheetApp.openByUrl(urlss);
  var ws = ss.getSheetByName("lista");
  var dadosPaciente = ws.getRange(2,1,ws.getLastRow()-1,3).getValues();

  var listaNomePaciente = dadosPaciente.map(function(param) { return param[0];});
  var listaDtNascPaciente = dadosPaciente.map(function(param) { return param[1];});
  var listaCPFPaciente = dadosPaciente.map(function(param) { return param[2];});

  pacienteEncontrado = [listaNomePaciente,listaCPFPaciente,listaDtNascPaciente];
  return pacienteEncontrado;
 }
</code>```

File: page_js

```<code><script>

document.getElementById("btconsultaPaciente").addEventListener("click",objConsultaPaciente);

function objConsultaPaciente(){
   google.script.run.withSuccessHandler(populateDadosPacientes).getConsultaPacientes();
}

function populateDadosPacientes(conteudo) {
   document.getElementById("idnome").value=conteudo[0];
   document.getElementById("idcpf").value=conteudo[1];
   document.getElementById("iddtnascimento").value=conteudo[2];
   M.updateTextFields();

   }

</script>
</code>```

File: index.html

```<code><!DOCTYPE html>
  <html>
    <head>
      <!--Import Google Icon Font-->
      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
      <!-- Compiled and minified CSS -->
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
      <!--Let browser know website is optimized for mobile-->
      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
      <!-- <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1.0, maximum-scale=1.0"> -->
    </head>

    <body>
         <div class="container">

               <div class="row">
                  <div class="input-field col s12 m2 l2">
                     <button id="btconsultaPaciente" class="btn tooltipped" data-position="bottom" data-tooltip="Consultar Paciente">Populate</button>
                  </div>
               </div> <!-- CLOSE ROW -->

               <div class="divider"></div>

               <br>

               <div class="row">
                  <div class="input-field col s12 m4 l4">
                     <input type="text" id="idnome" class="validate">
                     <label class="active" for="idnome">Nome</label>
                  </div>
                  <div class="input-field col s12 m4 l4">
                     <input type="text" id="iddtnascimento" class="datepicker">
                     <label>Data de Nascimento</label>
                  </div>
                  <div class="input-field col s12 m4 l4">
                     <input type="text" id="idcpf" class="validate">
                     <label for="idcpf">CPF</label>
                  </div>
               </div> <!-- CLOSE ROW -->

               <div class="row">
                  <div class="col">

                  </div>
               </div> <!-- CLOSE ROW -->

         </div> <!-- CLOSE CONTAINER -->

      <!-- Compiled and minified JavaScript -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
      <?!= include('index_js'); ?>
    </body>
</html>
</code>```

答:
I believe your situation and goal are as follows.

There are the values of "Name", "20/07/1950" and "12345678" in the columns "A" to "C" on Google Spreadsheet.

"20/07/1950" is the date object.

You want to put above 3 values to idnome, iddtnascimento and idcpf.

When the script is run by clicking the button, an error of TypeError: conteudo is null occurs.

You want to know the reason of this error and remove it.

If my understanding for above situation and goal is correct, I think that your script of Google Apps Script is required to be modified as follows.

Modification points:

If "20/07/1950" is the date object on Spreadsheet, the value of conteudo returned by google.script.run.withSuccessHandler(populateDadosPacientes).getConsultaPacientes() becomes null.

From your sample values and the error message of TypeError: conteudo is null, I thought that this might be the reason of your issue.

When your script is modified, it becomeas as follows.

Modified script:

Please modify the function getConsultaPacientes() at Google Apps Script side as follows.

From:

```<code>var dadosPaciente = ws.getRange(2,1,ws.getLastRow()-1,3).getValues();
</code>```

To:

```<code>var dadosPaciente = ws.getRange(2,1,ws.getLastRow()-1,3).getDisplayValues();
</code>```

or

From:

```<code>var listaDtNascPaciente = dadosPaciente.map(function(param) { return param[1];});
</code>```

To:

```<code>var listaDtNascPaciente = dadosPaciente.map(function(param) { return param[1].toISOString()});
</code>```

Note:

If you want to use the value which can be seen at Spreadsheet, the modification using getDisplayValues() might be suitable.

In your script, Web Apps is used. So when the script of Web Apps is modified, please redeploy the Web Apps as new version. By this, the latest script is reflected to it. Please be careful this.

References:

getDisplayValues()

toISOString()

Body:
I would like to read data from google sheets and then write cell values to input type text fields. Firefox returns an error "TypeError: conteudo is null" when I try to access an array returning data from GSheets.
This is the link to my google sheets example.

Sample data

Nome: Name
Data_Nascimento: 20/07/1950
CPF: 12345678

See below my code.

File: code.gs

function doGet(request) {
    setPage('index');
    return HtmlService
    .createTemplateFromFile('index')
    .evaluate()
    .addMetaTag('viewport', 'width=device-width, initial-scale=1')
    .setTitle("teste");
  }

function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename).getContent();
}

var urlss = "https://docs.google.com/spreadsheets/d/1q8kz2L2q4u99dvR0zeDuCghSgtlNKMpbmZgCRHC3hn0/edit?usp=sharing";

function setPage(page) {
  var ps=PropertiesService.getUserProperties();
  ps.setProperty('PageTitle', page);
  return ps.getProperty('PageTitle');
}

function getConsultaPacientes() {

  var ss = SpreadsheetApp.openByUrl(urlss);
  var ws = ss.getSheetByName("lista");
  var dadosPaciente = ws.getRange(2,1,ws.getLastRow()-1,3).getValues();

  var listaNomePaciente = dadosPaciente.map(function(param) { return param[0];});
  var listaDtNascPaciente = dadosPaciente.map(function(param) { return param[1];});
  var listaCPFPaciente = dadosPaciente.map(function(param) { return param[2];});

  pacienteEncontrado = [listaNomePaciente,listaCPFPaciente,listaDtNascPaciente];
  return pacienteEncontrado;
 }

File: page_js

File: index.html

<!DOCTYPE html>

      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

                     <button id="btconsultaPaciente" class="btn tooltipped" data-position="bottom" data-tooltip="Consultar Paciente">Populate</button>

                     <input type="text" id="idnome" class="validate">
                     Nome

                     <input type="text" id="iddtnascimento" class="datepicker">
                     Data de Nascimento

                     <input type="text" id="idcpf" class="validate">
                     CPF

      <?!= include('index_js'); ?>

Body:
I believe your situation and goal are as follows.

There are the values of "Name", "20/07/1950" and "12345678" in the columns "A" to "C" on Google Spreadsheet.

"20/07/1950" is the date object.

You want to put above 3 values to idnome, iddtnascimento and idcpf.

When the script is run by clicking the button, an error of TypeError: conteudo is null occurs.

You want to know the reason of this error and remove it.

If my understanding for above situation and goal is correct, I think that your script of Google Apps Script is required to be modified as follows.

Modification points:

If "20/07/1950" is the date object on Spreadsheet, the value of conteudo returned by google.script.run.withSuccessHandler(populateDadosPacientes).getConsultaPacientes() becomes null.

From your sample values and the error message of TypeError: conteudo is null, I thought that this might be the reason of your issue.

When your script is modified, it becomeas as follows.

Modified script:

Please modify the function getConsultaPacientes() at Google Apps Script side as follows.

From:

var dadosPaciente = ws.getRange(2,1,ws.getLastRow()-1,3).getValues();

To:

var dadosPaciente = ws.getRange(2,1,ws.getLastRow()-1,3).getDisplayValues();

or

From:

var listaDtNascPaciente = dadosPaciente.map(function(param) { return param[1];});

To:

var listaDtNascPaciente = dadosPaciente.map(function(param) { return param[1].toISOString()});

Note:

If you want to use the value which can be seen at Spreadsheet, the modification using getDisplayValues() might be suitable.

In your script, Web Apps is used. So when the script of Web Apps is modified, please redeploy the Web Apps as new version. By this, the latest script is reflected to it. Please be careful this.

References:

getDisplayValues()

toISOString()


问:
Composite Key for Shopping Cart, SQL, Logic Model
I am making a logic model for a shopping cart project and I got to the next question.
What would happen if I want to add 2 equal products (examples: 2 pencils)?

logical model: enter image description here
physical model:enter image description here

A solution I thought is to make a compound key or compound attribute that stores in the first part an incremental int attribute and in the second part the product id, so you could enter the cart 2 products that despite having the same product_id in the second part are different in the first part which is incremental.

What do you think? Is it a good idea or does someone have a better solution?

```<code>CREATE TABLE Carro
(
 id_carro INTEGER NOT NULL
)
ALTER TABLE Carro ADD CONSTRAINT Carro_PK PRIMARY KEY CLUSTERED (id_carro)
 WITH (
 ALLOW_PAGE_LOCKS = ON ,
 ALLOW_ROW_LOCKS = ON )

CREATE TABLE Orden_Detalle
(
 id_ord_det INTEGER IDENTITY NOT NULL ,
 Carro_id_carro INTEGER NOT NULL ,
 Producto_id_prod INTEGER NOT NULL
)

ALTER TABLE Orden_Detalle ADD CONSTRAINT Orden_Detalle_PK PRIMARY KEY CLUSTERED (id_ord_det, Producto_id_prod)
 WITH (
 ALLOW_PAGE_LOCKS = ON ,
 ALLOW_ROW_LOCKS = ON )

CREATE TABLE Producto
(
 id_prod INTEGER NOT NULL ,
 name_prod VARCHAR (20) ,
 value_prod INTEGER
)
ALTER TABLE Producto ADD CONSTRAINT Producto_PK PRIMARY KEY CLUSTERED (id_prod)
 WITH (
 ALLOW_PAGE_LOCKS = ON ,
 ALLOW_ROW_LOCKS = ON )

ALTER TABLE Orden_Detalle
ADD CONSTRAINT Orden_Detalle_Carro_FK FOREIGN KEY
(
 Carro_id_carro
)
REFERENCES Carro
(
 id_carro
)

ALTER TABLE Orden_Detalle
ADD CONSTRAINT Orden_Detalle_Producto_FK FOREIGN KEY
(
 Producto_id_prod
)
REFERENCES Producto
(
 id_prod
)
</code>```

答:
I would suggest you to have two tables for Orders: OrderMaster, OrderDetails. This way, you can see all the details for a specific Order. I am  assuming that every order has got one-one mapping with cart.

For your question, you don't need composite key. Just incremental Order details Id is enough. You can find order details for an order using OrderId.

OrderMaster : OrderId(Incremental, PK),CartId(FK)

OrderDetails: OrderDetailsId(Incremental, PK),OrderId(FK),ProductId(FK)

Cart:   CartId(PK), CartName, ...

Product: ProductId(PK), ProductName, ProductValue ...

Body:
I am making a logic model for a shopping cart project and I got to the next question.
What would happen if I want to add 2 equal products (examples: 2 pencils)?

logical model: enter image description here
physical model:enter image description here

A solution I thought is to make a compound key or compound attribute that stores in the first part an incremental int attribute and in the second part the product id, so you could enter the cart 2 products that despite having the same product_id in the second part are different in the first part which is incremental.

What do you think? Is it a good idea or does someone have a better solution?

CREATE TABLE Carro
(
 id_carro INTEGER NOT NULL
)
ALTER TABLE Carro ADD CONSTRAINT Carro_PK PRIMARY KEY CLUSTERED (id_carro)
 WITH (
 ALLOW_PAGE_LOCKS = ON ,
 ALLOW_ROW_LOCKS = ON )

CREATE TABLE Orden_Detalle
(
 id_ord_det INTEGER IDENTITY NOT NULL ,
 Carro_id_carro INTEGER NOT NULL ,
 Producto_id_prod INTEGER NOT NULL
)

ALTER TABLE Orden_Detalle ADD CONSTRAINT Orden_Detalle_PK PRIMARY KEY CLUSTERED (id_ord_det, Producto_id_prod)
 WITH (
 ALLOW_PAGE_LOCKS = ON ,
 ALLOW_ROW_LOCKS = ON )

CREATE TABLE Producto
(
 id_prod INTEGER NOT NULL ,
 name_prod VARCHAR (20) ,
 value_prod INTEGER
)
ALTER TABLE Producto ADD CONSTRAINT Producto_PK PRIMARY KEY CLUSTERED (id_prod)
 WITH (
 ALLOW_PAGE_LOCKS = ON ,
 ALLOW_ROW_LOCKS = ON )

ALTER TABLE Orden_Detalle
ADD CONSTRAINT Orden_Detalle_Carro_FK FOREIGN KEY
(
 Carro_id_carro
)
REFERENCES Carro
(
 id_carro
)

ALTER TABLE Orden_Detalle
ADD CONSTRAINT Orden_Detalle_Producto_FK FOREIGN KEY
(
 Producto_id_prod
)
REFERENCES Producto
(
 id_prod
)


问:
SwiftUI inverse animation delay on removal
I am trying to choreograph animations in SwiftUI.  I want two colored bars to move in to the view with a delay between them and then move out of the view with the delays switched so that the removal is the reverse of the insertion.

I think I understand why the below code doesn't work, but I can't figure out how to make it do what I need:

```<code>import SwiftUI

struct TestAnimControl: View {
    @State var show: Bool = false
    @State var reverseDelay: Bool = false

    var body: some View {
        VStack {
            Button(action:{
                self.show.toggle()
            }) {
                Text("Animate")
                    .font(.largeTitle)
            }
            if show {
                Rectangle()
                    .foregroundColor(.blue)
                    .frame(height: 100)
                    .transition(.move(edge: .trailing))
                    .animation(Animation.spring().delay(show ? 0.3 : 0.5))
                Rectangle()
                    .foregroundColor(.red)
                    .frame(height: 100)
                    .transition(.move(edge: .trailing))
                    .animation(Animation.spring().delay(show ? 0.5 : 0.3))
            }
        }
    }
}
</code>```

When you run this and hit the button, the blue bar moves in and then the red bar moves in.  Hit the button again and the blue bar moves out and then the red bar moves out.  What I want is when you hit the button for removal, the red bar moves out and then the blue bar moves out, reverse of the way the bars came in.  In this code I believe the ternary doesn't work because the animation is set when the Rectangle is created and the delay can't change after that.  I may be wrong, but either way is there a way to do what I am trying to do?

答:
Update: Xcode 13.4 / iOS 15.5

A proposed solution now is based on explicit animation with modification in every transaction so each transition have own parametrised variant of animation.

Main part:

```<code>Button(action:{
    withAnimation {
        self.show.toggle()
    }
}) {
    Text("Animate")
        .font(.largeTitle)
}
if show {
    Rectangle()
        .foregroundColor(.blue)
        .frame(height: 100)
        .transition(.move(edge: .trailing))
        .transaction {
            $0.animation = Animation.spring().delay(delay1)
        }
        .onAppear { self.delay1 = 0.5 }
        .onDisappear { self.delay1 = 0.3 }
    Rectangle()
        .foregroundColor(.yellow)
        .frame(height: 100)
        .transition(.move(edge: .trailing))
        .transaction {
            $0.animation = Animation.spring().delay(delay2)
        }
        .onAppear { self.delay2 = 0.3 }
        .onDisappear { self.delay2 = 0.5 }
}
</code>```

Test code on GitHub

Original:

!!! It does not work anymore with modern OS

Here is a solution - based on applied implicit animations to every transition. Tested with Xcode 11.4 / iOS 13.4

```<code>struct TestAnimControl: View {
    @State var show: Bool = false
    @State var reverseDelay: Bool = false

    @State var blueDelay = 0.3
    @State var redDelay = 0.5
    var body: some View {
        VStack {
            Button(action:{
                self.show.toggle()
            }) {
                Text("Animate")
                    .font(.largeTitle)
            }
            if show {
                Rectangle()
                    .foregroundColor(.blue)
                    .frame(height: 100)
                    .transition(.move(edge: .trailing))
                    .animation(Animation.spring().delay(blueDelay))//(show ? 0.3 : 0.5))
                    .onAppear { self.blueDelay = 0.5 }
                    .onDisappear { self.blueDelay = 0.3 }
                Rectangle()
                    .foregroundColor(.red)
                    .frame(height: 100)
                    .transition(.move(edge: .trailing))
                    .animation(Animation.spring().delay(redDelay))//(show ? 0.5 : 0.3))
                    .onAppear { self.redDelay = 0.3 }
                    .onDisappear { self.redDelay = 0.5 }
            }
        }
    }
}
</code>```

Body:
I am trying to choreograph animations in SwiftUI.  I want two colored bars to move in to the view with a delay between them and then move out of the view with the delays switched so that the removal is the reverse of the insertion.

I think I understand why the below code doesn't work, but I can't figure out how to make it do what I need:

import SwiftUI

struct TestAnimControl: View {
    @State var show: Bool = false
    @State var reverseDelay: Bool = false

    var body: some View {
        VStack {
            Button(action:{
                self.show.toggle()
            }) {
                Text("Animate")
                    .font(.largeTitle)
            }
            if show {
                Rectangle()
                    .foregroundColor(.blue)
                    .frame(height: 100)
                    .transition(.move(edge: .trailing))
                    .animation(Animation.spring().delay(show ? 0.3 : 0.5))
                Rectangle()
                    .foregroundColor(.red)
                    .frame(height: 100)
                    .transition(.move(edge: .trailing))
                    .animation(Animation.spring().delay(show ? 0.5 : 0.3))
            }
        }
    }
}

When you run this and hit the button, the blue bar moves in and then the red bar moves in.  Hit the button again and the blue bar moves out and then the red bar moves out.  What I want is when you hit the button for removal, the red bar moves out and then the blue bar moves out, reverse of the way the bars came in.  In this code I believe the ternary doesn't work because the animation is set when the Rectangle is created and the delay can't change after that.  I may be wrong, but either way is there a way to do what I am trying to do?

Body:
Update: Xcode 13.4 / iOS 15.5

A proposed solution now is based on explicit animation with modification in every transaction so each transition have own parametrised variant of animation.

Main part:

Button(action:{
    withAnimation {
        self.show.toggle()
    }
}) {
    Text("Animate")
        .font(.largeTitle)
}
if show {
    Rectangle()
        .foregroundColor(.blue)
        .frame(height: 100)
        .transition(.move(edge: .trailing))
        .transaction {
            $0.animation = Animation.spring().delay(delay1)
        }
        .onAppear { self.delay1 = 0.5 }
        .onDisappear { self.delay1 = 0.3 }
    Rectangle()
        .foregroundColor(.yellow)
        .frame(height: 100)
        .transition(.move(edge: .trailing))
        .transaction {
            $0.animation = Animation.spring().delay(delay2)
        }
        .onAppear { self.delay2 = 0.3 }
        .onDisappear { self.delay2 = 0.5 }
}

Test code on GitHub

Original:

!!! It does not work anymore with modern OS

Here is a solution - based on applied implicit animations to every transition. Tested with Xcode 11.4 / iOS 13.4

struct TestAnimControl: View {
    @State var show: Bool = false
    @State var reverseDelay: Bool = false

    @State var blueDelay = 0.3
    @State var redDelay = 0.5
    var body: some View {
        VStack {
            Button(action:{
                self.show.toggle()
            }) {
                Text("Animate")
                    .font(.largeTitle)
            }
            if show {
                Rectangle()
                    .foregroundColor(.blue)
                    .frame(height: 100)
                    .transition(.move(edge: .trailing))
                    .animation(Animation.spring().delay(blueDelay))//(show ? 0.3 : 0.5))
                    .onAppear { self.blueDelay = 0.5 }
                    .onDisappear { self.blueDelay = 0.3 }
                Rectangle()
                    .foregroundColor(.red)
                    .frame(height: 100)
                    .transition(.move(edge: .trailing))
                    .animation(Animation.spring().delay(redDelay))//(show ? 0.5 : 0.3))
                    .onAppear { self.redDelay = 0.3 }
                    .onDisappear { self.redDelay = 0.5 }
            }
        }
    }
}


问:
BTS tree search function C++
This program reads a CSV file and enters it into a binary search tree. So far I have managed to insert a new node, put it in order, however, internally, perform a search asking for the Varibale Key but I have not managed to get it to work, could someone help me?

The CSV file is reading a file that includes:

1, name1,123456

2, name2,165151

3, name3,1566516

```<code>#include <iostream>
#include <iomanip>
#include <fstream>
#include <memory>
#include <string>
#include <sstream>
#include <vector>

struct Person {
  int key;
  std::string name;
  int num;
};

struct Node : Person {
  Node(const Person &person) : Person(person) {}
  std::unique_ptr<Node> left, right;
  void insert(const Person &person);
};

void Node::insert(const Person &person) {
  /* recur down the tree */
  if (key > person.key) {
    if (left)
        left->insert(person);
    else
        left = std::make_unique<Node>(person);
  } else if (key < person.key) {
    if (right)
        right->insert(person);
    else
        right = std::make_unique<Node>(person);
  }
}

std::vector<Person> persons;

void inorder(Node *root) {
  if (root) {
    // cout<<"\t";

    inorder(root->left.get());
    std::cout << '\t' << root->key << ' ' << root->name << ' ' << root->num << '\n';
    inorder(root->right.get());
  }
}

Node *minValueNode(Node *node) {
  Node *current = node;

  /* loop down to find the leftmost leaf */
  while (current && current->left) current = current->left.get();

  return current;
}

int main() {
  std::unique_ptr<Node> root;
  std::ifstream fin("data.txt");
  if (!fin) {
    std::cout << "File not open\n";
    return 1;
  }

  std::string line;
  const char delim = ',';

  while (std::getline(fin, line)) {
    std::istringstream ss(line);
    Person person;
    ss >> person.key;
    ss.ignore(10, delim);
    std::getline(ss, person.name, delim);
    ss >> person.num;
    if (ss) persons.push_back(person);
  }

  for (unsigned int i = 0; i < persons.size(); i++) {
    std::cout << std::setw(5) << persons[i].key << std::setw(20)
              << persons[i].name << std::setw(15) << persons[i].num << '\n';
    if (!root) root = std::make_unique<Node>(persons[i]);
    else root->insert(persons[i]);
  }

  std::cout << "\n\nInorder:\n";
  //    cout<<node.name;

  inorder(root.get());

  return 0;
}
</code>```

```<code>/*bool busqueda(Node *root, int dato)
{

    if(root){
    return false;
    }
    else if(root->key==dato){
        return true;
    }
    else if(dato<root->key){
       busqueda(root->left.get(),dato);
    }
    else{
        return busqueda(root->right.get(),dato);
    }

   }*/
</code>```

答:
Presuming that this is the function you need help with:

```<code>bool busqueda(Node *root, int dato) {
    if(root){
    return false;
    }
    else if(root->key==dato){
        return true;
    }
    else if(dato<root->key){
       busqueda(root->left.get(),dato);
    }
    else{
        return busqueda(root->right.get(),dato);
    }
}
</code>```

There are a few issues here:

```<code>if(root) {
</code>```

This is testing if root is not nullptr, so you're going to immediately bail if root points at something.  Meaning, you will immediately return false if any tree is provided, which is the opposite of what you want.  Even worse, if root is null you will proceed and try to dereference a null pointer, which will crash the program.  Change this line to if (root != nullptr) {.

```<code>else if(dato<root->key){
    busqueda(root->left.get(),dato);
}
</code>```

This recursive call looks right except you don't return the result meaning that you will reach the end of a function returning bool without actually returning anything meaningful.  Just add return before this function call.

You can mostly express this function using boolean logic as well:

```<code>bool busqueda(Node *root, int dato) {
    return root != nullptr && (
        root->key == dato ||
        busqueda((dato < root->key ? root->left : root->right).get(), dato)
    );
}
</code>```

This makes it impossible to forget to return something.

As a side note, enable all compiler warnings -- it would have warned you about reaching the end of a non-void function without returning a value.

Title: BTS tree search function C++

Body:
This program reads a CSV file and enters it into a binary search tree. So far I have managed to insert a new node, put it in order, however, internally, perform a search asking for the Varibale Key but I have not managed to get it to work, could someone help me?

The CSV file is reading a file that includes:

1, name1,123456

2, name2,165151

3, name3,1566516

#include <iostream>
#include <iomanip>
#include <fstream>
#include <memory>
#include <string>
#include <sstream>
#include <vector>

struct Person {
  int key;
  std::string name;
  int num;
};

struct Node : Person {
  Node(const Person &person) : Person(person) {}
  std::unique_ptr<Node> left, right;
  void insert(const Person &person);
};

void Node::insert(const Person &person) {
  /* recur down the tree */
  if (key > person.key) {
    if (left)
        left->insert(person);
    else
        left = std::make_unique<Node>(person);
  } else if (key < person.key) {
    if (right)
        right->insert(person);
    else
        right = std::make_unique<Node>(person);
  }
}

std::vector<Person> persons;

void inorder(Node *root) {
  if (root) {
    // cout<<"\t";

    inorder(root->left.get());
    std::cout << '\t' << root->key << ' ' << root->name << ' ' << root->num << '\n';
    inorder(root->right.get());
  }
}

Node *minValueNode(Node *node) {
  Node *current = node;

  /* loop down to find the leftmost leaf */
  while (current && current->left) current = current->left.get();

  return current;
}

int main() {
  std::unique_ptr<Node> root;
  std::ifstream fin("data.txt");
  if (!fin) {
    std::cout << "File not open\n";
    return 1;
  }

  std::string line;
  const char delim = ',';

  while (std::getline(fin, line)) {
    std::istringstream ss(line);
    Person person;
    ss >> person.key;
    ss.ignore(10, delim);
    std::getline(ss, person.name, delim);
    ss >> person.num;
    if (ss) persons.push_back(person);
  }

  for (unsigned int i = 0; i < persons.size(); i++) {
    std::cout << std::setw(5) << persons[i].key << std::setw(20)
              << persons[i].name << std::setw(15) << persons[i].num << '\n';
    if (!root) root = std::make_unique<Node>(persons[i]);
    else root->insert(persons[i]);
  }

  std::cout << "\n\nInorder:\n";
  //    cout<<node.name;

  inorder(root.get());

  return 0;
}

/*bool busqueda(Node *root, int dato)
{

    if(root){
    return false;
    }
    else if(root->key==dato){
        return true;
    }
    else if(dato<root->key){
       busqueda(root->left.get(),dato);
    }
    else{
        return busqueda(root->right.get(),dato);
    }

   }*/

Body:
Presuming that this is the function you need help with:

bool busqueda(Node *root, int dato) {
    if(root){
    return false;
    }
    else if(root->key==dato){
        return true;
    }
    else if(dato<root->key){
       busqueda(root->left.get(),dato);
    }
    else{
        return busqueda(root->right.get(),dato);
    }
}

There are a few issues here:

if(root) {

This is testing if root is not nullptr, so you're going to immediately bail if root points at something.  Meaning, you will immediately return false if any tree is provided, which is the opposite of what you want.  Even worse, if root is null you will proceed and try to dereference a null pointer, which will crash the program.  Change this line to if (root != nullptr) {.

else if(dato<root->key){
    busqueda(root->left.get(),dato);
}

This recursive call looks right except you don't return the result meaning that you will reach the end of a function returning bool without actually returning anything meaningful.  Just add return before this function call.

You can mostly express this function using boolean logic as well:

bool busqueda(Node *root, int dato) {
    return root != nullptr && (
        root->key == dato ||
        busqueda((dato < root->key ? root->left : root->right).get(), dato)
    );
}

This makes it impossible to forget to return something.

As a side note, enable all compiler warnings -- it would have warned you about reaching the end of a non-void function without returning a value.


问:
How to post dicts with lists using requests in Python?
I need to send nested request. Here is example of dict:

```<code>data = {
        "customer_id": "customer_1",
        "time": get_timestamp(),
        "data_1": ["1", "2"],
        "data_2": ["6", "7"],
    }
</code>```

There can be larger amount of elements in lists and more lists, this is just an example.
When sending r = requests.post(url, data=data) or r = requests.post(url, json=data) or r = requests.post(url, data=json.dumps(data))

I get a validation message that there a no required fields and I checked that data hasn't been sent. However, if I send it like this it works:

```<code>data = {
        "customer_id": "customer_1",
        "time": get_timestamp(),
        "data_1[0]": "1",
        "data_1[1]": "2",
        "data_2[0]": "6",
        "data_2[1]": "7"
    }
</code>```

Is there a way to send lists using requests without having to put every element as different key?

Edit. I forgot to mention that I need to send files together too. At first I hasn't thought that files can be a problem, but they of course can (I wanted to simplify question as much as possible). I add files: files = {"files": open(path_to_file, "rb")} and send adding files=files to POST request. So the whole code would look like this:

```<code>url = ""
token = "token"
headers = {"Authorization": "Bearer " + token}
data = {
    "customer_id": "customer_1",
    "time": get_timestamp(),
    "data_1": ["1", "2"],
    "data_2": ["6", "7"],
}
path_to_file = "file.jpg"
files = {"files": open(path_to_file, "rb")}
r = requests.post(url, data=data, files=files, headers=headers, verify=False)
</code>```

I have a postman specification for that:

答:
If your server requires you to include values in a list as individual items with an index (i.e. "data_1[0]": "1" and "data_1[1]": "2" instead of "data_1":["1", "2"]), then there's really nothing anyone here can tell you that will change that. Whether that's actually true is not something anyone here can validate if you don't share more information about the server or the protocol.

Of course it's pretty easy to map the data structure you'd like onto the data structure the server needs:

```<code>def get_what_you_need(data, unpack_lists):
    result = dict(data)
    for unpack_list in unpack_lists:
        assert unpack_list in data
        for key, value in enumerate(data[unpack_list]):
            result[f'{unpack_list}[{key}]'] = value
        del result[unpack_list]
    return result

you_like = {
    "customer_id": "customer_1",
    "time": get_timestamp(),
    "data_1": ["1", "2"],
    "data_2": ["6", "7"],
}

you_need = get_what_you_need(you_like, ['data_1', 'data_2'])
print(you_need)
</code>```

As for files, it doesn't appear you actually have a question there and it doesn't have any bearing on the above.

Body:
I need to send nested request. Here is example of dict:

data = {
        "customer_id": "customer_1",
        "time": get_timestamp(),
        "data_1": ["1", "2"],
        "data_2": ["6", "7"],
    }

There can be larger amount of elements in lists and more lists, this is just an example.
When sending r = requests.post(url, data=data) or r = requests.post(url, json=data) or r = requests.post(url, data=json.dumps(data))

I get a validation message that there a no required fields and I checked that data hasn't been sent. However, if I send it like this it works:

data = {
        "customer_id": "customer_1",
        "time": get_timestamp(),
        "data_1[0]": "1",
        "data_1[1]": "2",
        "data_2[0]": "6",
        "data_2[1]": "7"
    }

Is there a way to send lists using requests without having to put every element as different key?

Edit. I forgot to mention that I need to send files together too. At first I hasn't thought that files can be a problem, but they of course can (I wanted to simplify question as much as possible). I add files: files = {"files": open(path_to_file, "rb")} and send adding files=files to POST request. So the whole code would look like this:

url = ""
token = "token"
headers = {"Authorization": "Bearer " + token}
data = {
    "customer_id": "customer_1",
    "time": get_timestamp(),
    "data_1": ["1", "2"],
    "data_2": ["6", "7"],
}
path_to_file = "file.jpg"
files = {"files": open(path_to_file, "rb")}
r = requests.post(url, data=data, files=files, headers=headers, verify=False)

I have a postman specification for that:

Body:
If your server requires you to include values in a list as individual items with an index (i.e. "data_1[0]": "1" and "data_1[1]": "2" instead of "data_1":["1", "2"]), then there's really nothing anyone here can tell you that will change that. Whether that's actually true is not something anyone here can validate if you don't share more information about the server or the protocol.

Of course it's pretty easy to map the data structure you'd like onto the data structure the server needs:

def get_what_you_need(data, unpack_lists):
    result = dict(data)
    for unpack_list in unpack_lists:
        assert unpack_list in data
        for key, value in enumerate(data[unpack_list]):
            result[f'{unpack_list}[{key}]'] = value
        del result[unpack_list]
    return result

you_like = {
    "customer_id": "customer_1",
    "time": get_timestamp(),
    "data_1": ["1", "2"],
    "data_2": ["6", "7"],
}

you_need = get_what_you_need(you_like, ['data_1', 'data_2'])
print(you_need)

As for files, it doesn't appear you actually have a question there and it doesn't have any bearing on the above.


问:
How can I find the isnull() value in CSV file?
```<code>In[17]: train_data.isnull()
Out[17]:
       Category  Title
0         False  False
1         False  False
2         False  False
3         False  False
4         False  False
        ...    ...
98013     False  False
98014     False  False
98015     False  False
98016     False  False
98017     False  False

[98018 rows x 2 columns]

In [18]: print(train_data.isnull().sum())
Category    0
Title       1
dtype: int64
</code>```

In train_data, there is one null value in csv file.
I need to find a null value and remove it.

答:
I catch the type of NaN is float.
So I use it.</p>

```<code>for i in range(len(train_data)):
    if type(train_data.Title[i]) == float:
        print(i)
</code>```

Body:
In[17]: train_data.isnull()
Out[17]:
       Category  Title
0         False  False
1         False  False
2         False  False
3         False  False
4         False  False
        ...    ...
98013     False  False
98014     False  False
98015     False  False
98016     False  False
98017     False  False

[98018 rows x 2 columns]

In [18]: print(train_data.isnull().sum())
Category    0
Title       1
dtype: int64

In train_data, there is one null value in csv file.
I need to find a null value and remove it.

Body:
I catch the type of NaN is float.
So I use it.

for i in range(len(train_data)):
    if type(train_data.Title[i]) == float:
        print(i)


问:
How to change Database connection string runtime in Mobile Service TableController API
I have develop mobile app in xamarin forms and successfully login with Azure B2C. I Create a Web api using Microsoft.Azure.Mobile.Server TableController.
and it works fine.
I want to change database connection string runtime.

for example,

if (UserName == "ABC")

connectionstring = "..."

else if(UserName == "XYZ")

connectionstring = "..."

How to change Database connection string runtime in Mobile Service  TableController API ?.

答:
Freinds, I Got the solution.may be it is useful to someone.

In my MobileServiceClient API Startup.Mobile.cs, dbcontext is intialize as below

```<code>public partial class Startup
{

    public async static void ConfigureMobileApp(IAppBuilder app)

    {
        GlobalVars.ConnectionString = @"Data Source = tcp:stronginventoryapidbserver.database.windows.net, 1433; Initial Catalog = StrongInventoryAPI_db; User ID = strong; Password=Tapsid_het1;";

        Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationContext, StrongInventoryAPI.Migrations.Configuration>());

        app.UseWebApi(config);

    }
}
</code>```

then, i create a ConnectionMstController to change the connection string. Below is Initailize method of Controller.

```<code>    protected override void Initialize(HttpControllerContext controllerContext)
    {
        base.Initialize(controllerContext);
        GlobalVars.SID = ((ClaimsPrincipal)User).FindFirst(ClaimTypes.NameIdentifier).Value;
        if ( GlobalVars.SID.Contains("2e3c2d2a-14e7-4e03-bc5e-b9f6b2b09617"))
            GlobalVars.ConnectionString = @"Data Source = tcp:xxxxxxxxapidbserver.database.windows.net, 1433; Initial Catalog = Drona_db; User ID = strong; Password=xxxxxx;";
        ApplicationContext context = new ApplicationContext(GlobalVars.ConnectionString);
        DomainManager = new EntityDomainManager<ConnectionMst>(context, Request);

    }
</code>```

Remember to add contructor in your context in my case Application Context. my ApplicationConext is,

```<code>public class ApplicationContext : DbContext
{
    // You can add custom code to this file. Changes will not be overwritten.
    //
    // If you want Entity Framework to alter your database
    // automatically whenever you change your model schema, please use data migrations.
    // For more information refer to the documentation:
    // http://msdn.microsoft.com/en-us/data/jj591621.aspx
    //private const string connectionStringName = "Name=MyDbConnection";
    public ApplicationContext() : base(GlobalVars.ConnectionString)
    {
    }
    //start
    public ApplicationContext(string ConnectionString)   //connection string change in ConnectionMstController
        : base(ConnectionString)
    {
    }
    //end
    public DbSet<ScheduleMst> ScheduleMsts { get; set; }
    public DbSet<AccMst> AccMsts { get; set; }
    public DbSet<ConnectionMst> ConnectionMsts { get; set; }
    public DbSet<ItemGrpMst> ItemSubGrpMsts { get; set; }
    public DbSet<ItemSubGrpMst> ItemSubSubGrpMsts { get; set; }
    public DbSet<LotMst> LotMsts { get; set; }
    public DbSet<UnitMst> UnitMsts { get; set; }
    public DbSet<ItemMst> ItemMsts { get; set; }
    public DbSet<SaleOrdMst> SaleOrdMsts { get; set; }
    public DbSet<SaleOrdDet> SaleOrdDets { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Add(
            new AttributeToColumnAnnotationConvention<TableColumnAttribute, string>(
                "ServiceTableColumn", (property, attributes) => attributes.Single().ColumnType.ToString()));
    }
</code>```

Body:
Freinds, I Got the solution.may be it is useful to someone.

In my MobileServiceClient API Startup.Mobile.cs, dbcontext is intialize as below

public partial class Startup
{

    public async static void ConfigureMobileApp(IAppBuilder app)

    {
        GlobalVars.ConnectionString = @"Data Source = tcp:stronginventoryapidbserver.database.windows.net, 1433; Initial Catalog = StrongInventoryAPI_db; User ID = strong; Password=Tapsid_het1;";

        Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationContext, StrongInventoryAPI.Migrations.Configuration>());

        app.UseWebApi(config);

    }
}

then, i create a ConnectionMstController to change the connection string. Below is Initailize method of Controller.

    protected override void Initialize(HttpControllerContext controllerContext)
    {
        base.Initialize(controllerContext);
        GlobalVars.SID = ((ClaimsPrincipal)User).FindFirst(ClaimTypes.NameIdentifier).Value;
        if ( GlobalVars.SID.Contains("2e3c2d2a-14e7-4e03-bc5e-b9f6b2b09617"))
            GlobalVars.ConnectionString = @"Data Source = tcp:xxxxxxxxapidbserver.database.windows.net, 1433; Initial Catalog = Drona_db; User ID = strong; Password=xxxxxx;";
        ApplicationContext context = new ApplicationContext(GlobalVars.ConnectionString);
        DomainManager = new EntityDomainManager<ConnectionMst>(context, Request);

    }

Remember to add contructor in your context in my case Application Context. my ApplicationConext is,

public class ApplicationContext : DbContext
{
    // You can add custom code to this file. Changes will not be overwritten.
    //
    // If you want Entity Framework to alter your database
    // automatically whenever you change your model schema, please use data migrations.
    // For more information refer to the documentation:
    // http://msdn.microsoft.com/en-us/data/jj591621.aspx
    //private const string connectionStringName = "Name=MyDbConnection";
    public ApplicationContext() : base(GlobalVars.ConnectionString)
    {
    }
    //start
    public ApplicationContext(string ConnectionString)   //connection string change in ConnectionMstController
        : base(ConnectionString)
    {
    }
    //end
    public DbSet<ScheduleMst> ScheduleMsts { get; set; }
    public DbSet<AccMst> AccMsts { get; set; }
    public DbSet<ConnectionMst> ConnectionMsts { get; set; }
    public DbSet<ItemGrpMst> ItemSubGrpMsts { get; set; }
    public DbSet<ItemSubGrpMst> ItemSubSubGrpMsts { get; set; }
    public DbSet<LotMst> LotMsts { get; set; }
    public DbSet<UnitMst> UnitMsts { get; set; }
    public DbSet<ItemMst> ItemMsts { get; set; }
    public DbSet<SaleOrdMst> SaleOrdMsts { get; set; }
    public DbSet<SaleOrdDet> SaleOrdDets { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Add(
            new AttributeToColumnAnnotationConvention<TableColumnAttribute, string>(
                "ServiceTableColumn", (property, attributes) => attributes.Single().ColumnType.ToString()));
    }


问:
Copy selected multiple values to the textbox from more than one drop down
I have tow drop downs as below.

```<code><select id="checkOwner"  multiple="multiple" onchange="copyValue1(this)">
       <option value="FirstName">First Name</option>
       <option value="SecondName">Last Name</option>
      </select>
      <select id="checkMember" multiple="multiple" onchange="copyValue2(this)>
       <option value="FirstName">First Name</option>
       <option value="SecondName">Last Name</option>
      </select>
</code>```

I have below javascript to print selected multiple values from dropdowns.

```<code>function copyValue() {

  var str = "";
  for (var option of document.getElementById('checkOwner').options) {
if (option.selected) {
  str+= option.value+" ";
}

document.getElementById('mytextbox').value = str;
  }
}

function copyValue2() {

  var str = "";
  for (var option of document.getElementById('checkMember').options) {
if (option.selected) {
  str+= option.value+" ";
}

document.getElementById('mytextbox').value = str;
  }
}
</code>```

The problem is when I select values from first that value print in text box. But I select value from second dropdown First printed values disappeared and second dropdown box values are printed. But I want to keep all and when I untick I want to remove this value also. How can I do this.

答:
If you accepting duplicate values then, this is the solution:
I updated your HTML code to suit your needs by adding real values to your dropdown lists instead of using "FirstName,LastName".</p>

```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<select id="checkOwner" multiple="multiple" onchange="copyValue()">
       <option value="John">John</option>
       <option value="Abeer">Abeer</option>
     </select>
    <br>

    <select id="checkMember" multiple="multiple" onchange="copyValue2()">
       <option value="Doe">Doe</option>
       <option value="Trump">Trump</option>
       <option value="Abeer">Abeer</option>
     </select>
    <br>
     <input type="text" name="mytextbox" id="mytextbox" size="200">

</body>

<script type="text/javascript">

function getOld(currentSelect)
{
  var x = [];
  for (var option of document.getElementById(currentSelect).options) {
   if (option.selected) {

       x.push(option.value);
     }
   }

   return x;
}

function copyValue() {

  x = getOld('checkMember');
  y = [];
  for (var option of document.getElementById('checkOwner').options) {
    if (option.selected) {
          y.push(option.value);
    }
    else
    {
        y = y.filter(value => value != option.value );
    }
  }
  x = x.concat(y);
   document.getElementById('mytextbox').value = x.join(' ');
}

function copyValue2() {
  x = getOld('checkOwner');
  y = [];
  for (var option of document.getElementById('checkMember').options) {
   if (option.selected) {
      y.push(option.value);
   }
    else
    {
        y = y.filter(value => value != option.value );
    }
  }
    x = x.concat(y);
   document.getElementById('mytextbox').value = x.join(' ');
}

</script>
</html>
</code>```

Body:
I have tow drop downs as below.

<select id="checkOwner"  multiple="multiple" onchange="copyValue1(this)">
       <option value="FirstName">First Name</option>
       <option value="SecondName">Last Name</option>
      </select>
      <select id="checkMember" multiple="multiple" onchange="copyValue2(this)>
       <option value="FirstName">First Name</option>
       <option value="SecondName">Last Name</option>
      </select>

I have below javascript to print selected multiple values from dropdowns.

function copyValue() {

  var str = "";
  for (var option of document.getElementById('checkOwner').options) {
if (option.selected) {
  str+= option.value+" ";
}

document.getElementById('mytextbox').value = str;
  }
}

function copyValue2() {

  var str = "";
  for (var option of document.getElementById('checkMember').options) {
if (option.selected) {
  str+= option.value+" ";
}

document.getElementById('mytextbox').value = str;
  }
}

The problem is when I select values from first that value print in text box. But I select value from second dropdown First printed values disappeared and second dropdown box values are printed. But I want to keep all and when I untick I want to remove this value also. How can I do this.

Body:
If you accepting duplicate values then, this is the solution:
I updated your HTML code to suit your needs by adding real values to your dropdown lists instead of using "FirstName,LastName".

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<select id="checkOwner" multiple="multiple" onchange="copyValue()">
       <option value="John">John</option>
       <option value="Abeer">Abeer</option>
     </select>
    <br>

    <select id="checkMember" multiple="multiple" onchange="copyValue2()">
       <option value="Doe">Doe</option>
       <option value="Trump">Trump</option>
       <option value="Abeer">Abeer</option>
     </select>
    <br>
     <input type="text" name="mytextbox" id="mytextbox" size="200">

</body>

<script type="text/javascript">

function getOld(currentSelect)
{
  var x = [];
  for (var option of document.getElementById(currentSelect).options) {
   if (option.selected) {

       x.push(option.value);
     }
   }

   return x;
}

function copyValue() {

  x = getOld('checkMember');
  y = [];
  for (var option of document.getElementById('checkOwner').options) {
    if (option.selected) {
          y.push(option.value);
    }
    else
    {
        y = y.filter(value => value != option.value );
    }
  }
  x = x.concat(y);
   document.getElementById('mytextbox').value = x.join(' ');
}

function copyValue2() {
  x = getOld('checkOwner');
  y = [];
  for (var option of document.getElementById('checkMember').options) {
   if (option.selected) {
      y.push(option.value);
   }
    else
    {
        y = y.filter(value => value != option.value );
    }
  }
    x = x.concat(y);
   document.getElementById('mytextbox').value = x.join(' ');
}

</script>
</html>