问:
Is this TypeError normal?
I run my command and get this error:

```<code>(node:17432) UnhandledPromiseRejectionWarning: TypeError: (intermediate value).setColor(...).setDescription(...).then is not a function
    at Object.module.exports.run (C:\Users\eFhii\Desktop\Projects\Anastic\Bot\commands\warnc.js:19:63)
    at Client.<anonymous> (C:\Users\eFhii\Desktop\Projects\Anastic\Bot\index.js:61:34)
    at Client.emit (events.js:215:7)
    at MessageCreateAction.handle (C:\Users\eFhii\Desktop\Projects\Anastic\Bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (C:\Users\eFhii\Desktop\Projects\Anastic\Bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (C:\Users\eFhii\Desktop\Projects\Anastic\Bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
    at WebSocketShard.onPacket (C:\Users\eFhii\Desktop\Projects\Anastic\Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
    at WebSocketShard.onMessage (C:\Users\eFhii\Desktop\Projects\Anastic\Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
    at WebSocket.onMessage (C:\Users\eFhii\Desktop\Projects\Anastic\Bot\node_modules\ws\lib\event-target.js:125:16)
    at WebSocket.emit (events.js:210:5)
</code>```

And this is my code:

```<code>const Discord = require("discord.js")
const botconfig = require("../botconfig.json");
const colours = require("../colours.json");
const superagent = require("superagent")

module.exports.run = async(bot, message, args) => {
    if (!message.member.hasPermission(["VIEW_AUDIT_LOG"])) return message.channel.send(`**${message.author.username}**, ohne Berechtigung, wird dieser Befehl **nicht** ausgeführt!`)

    let warnMember = message.mentions.members.first() || message.guild.members.get(args[0])
    if (!warnMember) return message.channel.send(`**${message.author.username}**, bitte tagge einen User um diesen zu warnen!`)

    let reason = args.slice(1).join(" ");
    if (!reason) reason = "Kein Grund angegeben!"

    let embed = new Discord.MessageEmbed()
        .setColor(colours.maincolour)
        .setDescription(`✅ ${warnMember} erfolgreich gewarnt!`).then(m => m.delete(60000))
    message.channel.send(embed).then(m => m.delete(5000))

    let Sembed = new Discord.MessageEmbed()
        .setColor(colours.maincolour)
        .setAuthor(`Warnung!`, message.guild.iconURL)
        .setDescription(`Du wurdest aufgrund von **${reason}** gewarnt. Halte dich an die Richtlinien, andernfalls kann es zu einem CA (Community Ausschluss) führen!`)
    warnMember.send(Sembed)
}

module.exports.config = {
    name: "warn",
    description: "Warn a User",
    usage: "+warn",
    accessableby: "Administrators",
    aliases: ["w", "warning", "warnung"]
}
</code>```

My discord.js version: 12.2

答:
    const Discord = require("discord.js")
    const botconfig = require("../botconfig.json");
    const colours = require("../colours.json");
    const superagent = require("superagent")

    module.exports.run = async(bot, message, args) => {
        if (!message.member.hasPermission(["VIEW_AUDIT_LOG"])) return message.channel.send(`**${message.author.username}**, ohne Berechtigung, wird dieser Befehl **nicht** ausgeführt!`)

        let warnMember = message.mentions.members.first() || message.guild.members.get(args[0])
        if (!warnMember) return message.channel.send(`**${message.author.username}**, bitte tagge einen User um diesen zu warnen!`)

        let reason = args.slice(1).join(" ");
        if (!reason) reason = "Kein Grund angegeben!"

        let embed = new Discord.MessageEmbed()
            .setColor(colours.maincolour)
            .setDescription(`✅ ${warnMember} erfolgreich gewarnt!`);
        message.channel.send(embed).then(m => m.delete(5000))

        let Sembed = new Discord.MessageEmbed()
            .setColor(colours.maincolour)
            .setAuthor(`Warnung!`, message.guild.iconURL)
            .setDescription(`Du wurdest aufgrund von **${reason}** gewarnt. Halte dich an die Richtlinien, andernfalls kann es zu einem CA (Community Ausschluss) führen!`)
        warnMember.send(Sembed)
    }

    module.exports.config = {
        name: "warn",
        description: "Warn a User",
        usage: "+warn",
        accessableby: "Administrators",
        aliases: ["w", "warning", "warnung"]
    }
```

You aren't supposed to put a timer on the embed, leaving this here for anyone wondering how they fixed it :)

Title: Is this TypeError normal?

Body:
I run my command and get this error:

(node:17432) UnhandledPromiseRejectionWarning: TypeError: (intermediate value).setColor(...).setDescription(...).then is not a function
    at Object.module.exports.run (C:\Users\eFhii\Desktop\Projects\Anastic\Bot\commands\warnc.js:19:63)
    at Client.<anonymous> (C:\Users\eFhii\Desktop\Projects\Anastic\Bot\index.js:61:34)
    at Client.emit (events.js:215:7)
    at MessageCreateAction.handle (C:\Users\eFhii\Desktop\Projects\Anastic\Bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (C:\Users\eFhii\Desktop\Projects\Anastic\Bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (C:\Users\eFhii\Desktop\Projects\Anastic\Bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
    at WebSocketShard.onPacket (C:\Users\eFhii\Desktop\Projects\Anastic\Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
    at WebSocketShard.onMessage (C:\Users\eFhii\Desktop\Projects\Anastic\Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
    at WebSocket.onMessage (C:\Users\eFhii\Desktop\Projects\Anastic\Bot\node_modules\ws\lib\event-target.js:125:16)
    at WebSocket.emit (events.js:210:5)

And this is my code:

const Discord = require("discord.js")
const botconfig = require("../botconfig.json");
const colours = require("../colours.json");
const superagent = require("superagent")

module.exports.run = async(bot, message, args) => {
    if (!message.member.hasPermission(["VIEW_AUDIT_LOG"])) return message.channel.send(`**${message.author.username}**, ohne Berechtigung, wird dieser Befehl **nicht** ausgeführt!`)

    let warnMember = message.mentions.members.first() || message.guild.members.get(args[0])
    if (!warnMember) return message.channel.send(`**${message.author.username}**, bitte tagge einen User um diesen zu warnen!`)

    let reason = args.slice(1).join(" ");
    if (!reason) reason = "Kein Grund angegeben!"

    let embed = new Discord.MessageEmbed()
        .setColor(colours.maincolour)
        .setDescription(`✅ ${warnMember} erfolgreich gewarnt!`).then(m => m.delete(60000))
    message.channel.send(embed).then(m => m.delete(5000))

    let Sembed = new Discord.MessageEmbed()
        .setColor(colours.maincolour)
        .setAuthor(`Warnung!`, message.guild.iconURL)
        .setDescription(`Du wurdest aufgrund von **${reason}** gewarnt. Halte dich an die Richtlinien, andernfalls kann es zu einem CA (Community Ausschluss) führen!`)
    warnMember.send(Sembed)
}

module.exports.config = {
    name: "warn",
    description: "Warn a User",
    usage: "+warn",
    accessableby: "Administrators",
    aliases: ["w", "warning", "warnung"]
}

My discord.js version: 12.2

Body:
    const Discord = require("discord.js")
    const botconfig = require("../botconfig.json");
    const colours = require("../colours.json");
    const superagent = require("superagent")

    module.exports.run = async(bot, message, args) => {
        if (!message.member.hasPermission(["VIEW_AUDIT_LOG"])) return message.channel.send(`**${message.author.username}**, ohne Berechtigung, wird dieser Befehl **nicht** ausgeführt!`)

        let warnMember = message.mentions.members.first() || message.guild.members.get(args[0])
        if (!warnMember) return message.channel.send(`**${message.author.username}**, bitte tagge einen User um diesen zu warnen!`)

        let reason = args.slice(1).join(" ");
        if (!reason) reason = "Kein Grund angegeben!"

        let embed = new Discord.MessageEmbed()
            .setColor(colours.maincolour)
            .setDescription(`✅ ${warnMember} erfolgreich gewarnt!`);
        message.channel.send(embed).then(m => m.delete(5000))

        let Sembed = new Discord.MessageEmbed()
            .setColor(colours.maincolour)
            .setAuthor(`Warnung!`, message.guild.iconURL)
            .setDescription(`Du wurdest aufgrund von **${reason}** gewarnt. Halte dich an die Richtlinien, andernfalls kann es zu einem CA (Community Ausschluss) führen!`)
        warnMember.send(Sembed)
    }

    module.exports.config = {
        name: "warn",
        description: "Warn a User",
        usage: "+warn",
        accessableby: "Administrators",
        aliases: ["w", "warning", "warnung"]
    }

You aren't supposed to put a timer on the embed, leaving this here for anyone wondering how they fixed it :)


来源: stackexchange

问:
Merging two sorted linked list in c++
I am trying to code an algo to merge two sorted linked lists. I am not able to understand why this doesn't give me the correct answer. Why does the answer does not have memory of the earlier assignments, it just returns the most recent assignment being done. (i.e a linked list of length 1). I am creating an initial node called cur, then I am adding nexts to it depending on the values of l1 and l2 and doing cur.next every time. Thanks

```<code>struct ListNode {
  int val;
  ListNode* next;
  ListNode() : val(0), next(nullptr){};
  ListNode(int x) : val(x), next(nullptr){};
  ListNode(int x, ListNode* next) : val(x), next(next){};
};

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
  ListNode cur;
  ListNode* ans = new ListNode;
  ans = &cur;

  while (l1 && l2) {
    if (l1->val < l2->val) {
      ListNode temp(l1->val);
      cur.next = &temp;
      l1 = l1->next;
      cur = *(cur.next);
    } else {
      ListNode temp(l2->val);
      cur.next = &temp;
      l2 = l2->next;
      cur = *(cur.next);
    }
  }
  if (l1) {
    cur.next = (l1);
  }
  if (l2) {
    cur.next = (l2);
  }
  return ans->next;
};
</code>```

答:
The main issue is that you are not moving cur forward so that a new node can be appended to the list. As you have it now cur.next = &temp is just resetting the next pointer every time. Also, since the temp variable is local to the scope of the if branches, when you do cur.next = &temp you are setting the next pointer to an object that will disappear every time the if statement ends, causing a dangling pointer. It's better to dynamically allocate:

```<code>ListNode ans;
ListNode* cur = &ans;
while (l1 && l2) {
  if (l1->val < l2->val) {
    cur->next = new ListNode(l1->val);
    l1 = l1->next;
  } else {
    cur->next = new ListNode(l2->val);
    l2 = l2->next;
  }
  cur = cur->next;
}
if (l1)
  cur->next = l1;
else
  cur->next = l2;
return ans.next;
</code>```

ContentLicense: CC BY-SA 4.0

Title: Merging two sorted linked list in c++

Body:
I am trying to code an algo to merge two sorted linked lists. I am not able to understand why this doesn't give me the correct answer. Why does the answer does not have memory of the earlier assignments, it just returns the most recent assignment being done. (i.e a linked list of length 1). I am creating an initial node called cur, then I am adding nexts to it depending on the values of l1 and l2 and doing cur.next every time. Thanks

struct ListNode {
  int val;
  ListNode* next;
  ListNode() : val(0), next(nullptr){};
  ListNode(int x) : val(x), next(nullptr){};
  ListNode(int x, ListNode* next) : val(x), next(next){};
};

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
  ListNode cur;
  ListNode* ans = new ListNode;
  ans = &cur;

  while (l1 && l2) {
    if (l1->val < l2->val) {
      ListNode temp(l1->val);
      cur.next = &temp;
      l1 = l1->next;
      cur = *(cur.next);
    } else {
      ListNode temp(l2->val);
      cur.next = &temp;
      l2 = l2->next;
      cur = *(cur.next);
    }
  }
  if (l1) {
    cur.next = (l1);
  }
  if (l2) {
    cur.next = (l2);
  }
  return ans->next;
};

Body:
The main issue is that you are not moving cur forward so that a new node can be appended to the list. As you have it now cur.next = &temp is just resetting the next pointer every time. Also, since the temp variable is local to the scope of the if branches, when you do cur.next = &temp you are setting the next pointer to an object that will disappear every time the if statement ends, causing a dangling pointer. It's better to dynamically allocate:

ListNode ans;
ListNode* cur = &ans;
while (l1 && l2) {
  if (l1->val < l2->val) {
    cur->next = new ListNode(l1->val);
    l1 = l1->next;
  } else {
    cur->next = new ListNode(l2->val);
    l2 = l2->next;
  }
  cur = cur->next;
}
if (l1)
  cur->next = l1;
else
  cur->next = l2;
return ans.next;


问:
Remove all posible spaces in JSON message with Mule 4 dataweave
I have a JSON message where I need to remove all format spaces keeping values untouched. This is required before running a hash function over the full payload so it needs to be precise.

I started with the indent=false in the Dataweave writer configuration but I got a space after each colon like this:

```<code>{"text": "number\": 1 | array\": [ | number\": 1","number": 1,"array": [1,"as",[],{}]}
</code>```

Any suggested elegant solution to remove the spaces left before entering in the RegEx world? If not, any RegEx solution?

答:
I have got this solution following @SalimKhan (thanks for that!) suggested post. Basically I just wrote a full JSON custom writer on DataWeave.</p>

```<code>fun jsonWrite(item) = item match {
    case is Array -> "[" ++ joinBy($ map jsonWrite($), ",") ++ "]"
    case is Object -> "{" ++ joinBy($ pluck ("\"" ++ $$ ++ "\":" ++
        ($ match {
            case is String -> "\"" ++ ($ replace "\"" with "\\\"") ++ "\""
            case is Object -> jsonWrite($)
            case is Array -> "[" ++ joinBy($ map jsonWrite($), ",") ++ "]"
            else -> $
        })),",") ++ "}"
    case is String -> "\"" ++ ($ replace "\"" with "\\\"") ++ "\""
    else -> $
}
</code>```

Body:
I have a JSON message where I need to remove all format spaces keeping values untouched. This is required before running a hash function over the full payload so it needs to be precise.

I started with the indent=false in the Dataweave writer configuration but I got a space after each colon like this:

{"text": "number\": 1 | array\": [ | number\": 1","number": 1,"array": [1,"as",[],{}]}

Any suggested elegant solution to remove the spaces left before entering in the RegEx world? If not, any RegEx solution?

Body:
I have got this solution following @SalimKhan (thanks for that!) suggested post. Basically I just wrote a full JSON custom writer on DataWeave.

fun jsonWrite(item) = item match {
    case is Array -> "[" ++ joinBy($ map jsonWrite($), ",") ++ "]"
    case is Object -> "{" ++ joinBy($ pluck ("\"" ++ $$ ++ "\":" ++
        ($ match {
            case is String -> "\"" ++ ($ replace "\"" with "\\\"") ++ "\""
            case is Object -> jsonWrite($)
            case is Array -> "[" ++ joinBy($ map jsonWrite($), ",") ++ "]"
            else -> $
        })),",") ++ "}"
    case is String -> "\"" ++ ($ replace "\"" with "\\\"") ++ "\""
    else -> $
}


问:
How to get counts from AlterRow transformation in Azure Data Factory
I have an AlterRow transformation that marks each row with the appropriate CRUD operation in an ADFv2 data flow.  I don't see any output variables on this activity that will give me the total inserts, updates, etc.  I do, however, see methods in the expression syntax to tell me if a particular row is an IsInsert(), IsUpdate(), etc.

Would the correct way to get counts be to

Add another output from the AlterRow transformation

Add derived column that uses the expression syntax IsInsert(), IsUpdate() to set operation type (I, U, D)

Add an aggregate to group by this column to get total counts for each operation

When creating the aggregate, I don't see any metadata that would allow me to group by the CRUD operation type so I assume I would have to create this myself, but it seems like it should already be there since that's the purpose of the AlterRow transformation.  Am I working too hard to get these counts?

答: Add an aggregate after your AlterRow with no group-by and use these formulas:


问:
Saving in a DB the path of a photo chosen from the gallery
In my app, I would allow the user to pick a photo from the gallery (or snap a photo/video with the camera).

I need to save the path in a db to retrieve it later, but I don't understand how I can do it.

** EDIT **

I didnt' resolve this issue, so now I save the images locally and I save the local path in the db.

答:
I've never used UIImagePickerControllerReferenceURL, but I'd assume that you use it as any other URL:

```<code>[UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've never used UIImagePickerControllerReferenceURL, but I'd assume that you use it as any other URL:

[UIImage imageWithData:[NSData dataWithContentsOfURL:url]];


问:
How should I set up my security groups so that hackers will not infiltrate so easily
So I have an EC2 instance on AWS and it runs Mongodb. I have been having issues with hackers for a few months now and I can't seem to figure out how to keep them out. Luckily, I don't have anything important on there.

I did notice that my security group on AWS is basically open to all. For example, my inbound rules:

Port 80, tcp, 0.0.0.0/0
Port 8080, tcp, 0.0.0.0/0
Port all, tcp, 0.0.0.0/0
Port 22, tcp, 0.0.0.0/0
Port 27017, tcp, 0.0.0.0/0
Port 443, tcp, 0.0.0.0/0

If i change the source is there a convention I should follow? How should I set the source? I am new to this as I did not set up my security groups. Just trying to figure out how I can keep out the hackers. They have been going at it for a while now.

答:
If you are the only one accessing the EC2 instance, you can edit your security group and choose "My IP" as the Source, and then only you would be able to access it and the hackers will not.

It is best practice to limit command and control ports (22, 3389, etc) to only be accessible from known networks, such as your home, VPN IP pool, or corporate network.


问:
how do I select one word from array list like this one?
I have this

```<code>$words = array("Car", "Dog", "Ship");
</code>```

now I want to randomly select only one word, please help!

答:
You can use array_rand() function to get more than one random index.
array_rand(array, number)</p>

```<code><?php
    $words=array("Car", "Dog", "Ship");
    $random_keys=array_rand($words,3);
    echo $words[$random_keys[0]]."<br>";
    echo $words[$random_keys[1]]."<br>";
    echo $words[$random_keys[2]];
?>
</code>```

Body:
I have this

$words = array("Car", "Dog", "Ship");

now I want to randomly select only one word, please help!

Body:
You can use array_rand() function to get more than one random index.
array_rand(array, number)

<?php
    $words=array("Car", "Dog", "Ship");
    $random_keys=array_rand($words,3);
    echo $words[$random_keys[0]]."<br>";
    echo $words[$random_keys[1]]."<br>";
    echo $words[$random_keys[2]];
?>


问:
geojson to Elasticsearch : Failed to parse field [geometry.coordinates] of type [geo_shape]
I am trying to indexing geojson file into elasticsearch (version 7.6.2) using Python.

Here is the mapping I defined in elasticsearch.

```<code>'mappings': {
  "properties": {
    "geometry": {
      "properties": {
        "coordinates": {
          "type": "geo_shape"
        },
        "type": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        }
      }
    },
 }
}
</code>```

The geojson file looks like this:

```<code>{
"type": "FeatureCollection",
"name": "testting",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "LEGEND": "x_1", "THRESHOLD": -109, "COLOR": "0 0 255", "Prediction": "Coverage" }, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ 151.20061069847705, -33.886918725260998 ], [ 151.200620164862698, -33.886467994010133 ].....
</code>```

However, when I write the file to Elasticsearch, inspired from this link:

How to index geojson file in elasticsearch?

```<code>def geojson2es(gj):
    for feature in gj['features']:
        yield feature

with open(input_path+'/'+ data) as f:
    gj = json.load(f)

    es = Elasticsearch(hosts=[{'host': 'localhost', 'port': 9200}])

    k = [{
        "_index": "test",
        "_source": feature,
    } for feature in geojson2es(gj)]

    helpers.bulk(es, k)
</code>```

I have got this error:

{'type': 'mapper_parsing_exception',
'reason': 'failed to parse field [geometry.coordinates] of type [geo_shape]', '
caused_by':
{'type': 'parse_exception', 'reason': 'shape must be an object consisting of type and coordinates'}}

Did anyone encounter a similar issue? How can I fix it?

答:
Your mapping is not correct. The geo_shape type already implies type and coordinates, so you don't need to declare them again.

So your mapping should be like this instead, i.e. each feature has a type (e.g. Feature, a hash of properties and a geometry of type geo_shape):

```<code>{
  "mappings": {
    "properties": {
      "type": {
        "type": "keyword"
      },
      "properties": {
        "type": "object"
      },
      "geometry": {
        "type": "geo_shape"
      }
    }
  }
}
</code>```

Body:
I am trying to indexing geojson file into elasticsearch (version 7.6.2) using Python.

Here is the mapping I defined in elasticsearch.

'mappings': {
  "properties": {
    "geometry": {
      "properties": {
        "coordinates": {
          "type": "geo_shape"
        },
        "type": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        }
      }
    },
 }
}

The geojson file looks like this:

{
"type": "FeatureCollection",
"name": "testting",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "LEGEND": "x_1", "THRESHOLD": -109, "COLOR": "0 0 255", "Prediction": "Coverage" }, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ 151.20061069847705, -33.886918725260998 ], [ 151.200620164862698, -33.886467994010133 ].....

However, when I write the file to Elasticsearch, inspired from this link:

How to index geojson file in elasticsearch?

def geojson2es(gj):
    for feature in gj['features']:
        yield feature

with open(input_path+'/'+ data) as f:
    gj = json.load(f)

    es = Elasticsearch(hosts=[{'host': 'localhost', 'port': 9200}])

    k = [{
        "_index": "test",
        "_source": feature,
    } for feature in geojson2es(gj)]

    helpers.bulk(es, k)

I have got this error:

{'type': 'mapper_parsing_exception',
'reason': 'failed to parse field [geometry.coordinates] of type [geo_shape]', '
caused_by':
{'type': 'parse_exception', 'reason': 'shape must be an object consisting of type and coordinates'}}

Did anyone encounter a similar issue? How can I fix it?

Body:
Your mapping is not correct. The geo_shape type already implies type and coordinates, so you don't need to declare them again.

So your mapping should be like this instead, i.e. each feature has a type (e.g. Feature, a hash of properties and a geometry of type geo_shape):

{
  "mappings": {
    "properties": {
      "type": {
        "type": "keyword"
      },
      "properties": {
        "type": "object"
      },
      "geometry": {
        "type": "geo_shape"
      }
    }
  }
}


问:
Get related objects into a single queryset?
I have 3 models. Module, Task, and Lesson. Lesson is related to Module through an FK. Task is connected to Lesson through FK. I am trying to get all the lessons and tasks in a single queryset of a particular module.

```<code>class Module(models.Model):
    name = models.CharField(max_length=255)

class Lesson(models.Model):
    name = models.CharField(max_length=255)
    module = models.ForeignKey('module', on_delete=models.CASCADE)

class Task(models.Model):
    name = models.CharField(max_length=255)
    lesson = models.ForeignKey('lesson', on_delete=models.CASCADE)
</code>```

I want to get all the related Lessons to a module and the tasks related to it in a single queryset.

This is what I have tried

```<code>module = Module.objects.get(id=57)
lessons = Lesson.objects.filter(module=module)
tasks = Task.objects.filter(lesson__id__in=[lesson.id for lesson in lessons])
</code>```

答:
Okay so I went through the documentation and apparently I don't need to create a separate object that holds lessons and all it tasks because lessons = Lesson.objects.filter(module=module)  already has tasks which can be accessed with something like this

```<code>for lesson in lessons:
    print(lesson.task_set.all())
</code>```

or in jinja2 template like this

```<code>{% for task in lessons.task.all %}
    {{ lesson }}
{% endfor %}
</code>```

Body:
I have 3 models. Module, Task, and Lesson. Lesson is related to Module through an FK. Task is connected to Lesson through FK. I am trying to get all the lessons and tasks in a single queryset of a particular module.

class Module(models.Model):
    name = models.CharField(max_length=255)

class Lesson(models.Model):
    name = models.CharField(max_length=255)
    module = models.ForeignKey('module', on_delete=models.CASCADE)

class Task(models.Model):
    name = models.CharField(max_length=255)
    lesson = models.ForeignKey('lesson', on_delete=models.CASCADE)

I want to get all the related Lessons to a module and the tasks related to it in a single queryset.

This is what I have tried

module = Module.objects.get(id=57)
lessons = Lesson.objects.filter(module=module)
tasks = Task.objects.filter(lesson__id__in=[lesson.id for lesson in lessons])

Body:
Okay so I went through the documentation and apparently I don't need to create a separate object that holds lessons and all it tasks because lessons = Lesson.objects.filter(module=module)  already has tasks which can be accessed with something like this

for lesson in lessons:
    print(lesson.task_set.all())

or in jinja2 template like this

{% for task in lessons.task.all %}
    {{ lesson }}
{% endfor %}


问:
Is there a way to open multiple instances of CMD's with Azure-Pipelines?
I'm using Azure-Pipelines for my CI. In my pipeline, I need to use multiple instances of a CMD (Windows). For example, one CMD needs to start and continuously run a server, while the other needs to then deploy an app while the server is still running.

When using the CMD task, it only uses one instance of the CMD, so when I run the server, it never finishes and never gets to running the app.

Is there a way to run multiple instances of a CMD with Azure-Pipelines?

答:
You can start cmd.exe on the agent machine from a powershell task using Start-Process command.

So you can add multiple powershell tasks to start multiple CMD instances on the agent machine. Or you can start multiple CMD instances in one powershell task. Se below example:

```<code>steps:
  - powershell: |
    'Start-Process -FilePath "C:\Windows\System32\cmd.exe" -verb runas -ArgumentList {/k echo "hello"}'
  - powershell: |
    'Start-Process -FilePath "C:\Windows\System32\cmd.exe" -verb runas -ArgumentList {/k echo "world"}'
</code>```

Body:
You can start cmd.exe on the agent machine from a powershell task using Start-Process command.

So you can add multiple powershell tasks to start multiple CMD instances on the agent machine. Or you can start multiple CMD instances in one powershell task. Se below example:

steps:
  - powershell: |
    'Start-Process -FilePath "C:\Windows\System32\cmd.exe" -verb runas -ArgumentList {/k echo "hello"}'
  - powershell: |
    'Start-Process -FilePath "C:\Windows\System32\cmd.exe" -verb runas -ArgumentList {/k echo "world"}'


问:
Elements in the array not recognized

    var userInput = prompt('Which fruit would you like?');
      var fruitList = ["banana", 'strawberries', "mango"];

      for(var i=0; i<fruitList.length; i++);
        if(userInput == fruitList[i]){
          alert("Sorry, we are out of " + userInput);
        }else{
          var userFruit = document.createElement('li');
          userFruit.textContent = userInput;
          var fruits = document.getElementById('list');
          fruits.appendChild(userFruit);
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div id="list"></div></code>```

It looks like for loop is not working as it's adding the user input into the list but it doesn't recognize elements from the array. The list which I didn't add here has id="list" and it has the three elements from the array. Thank you!

```<code>  var userInput = prompt('Which fruit would you like?');
  var fruitList = ["banana", 'strawberries', "mango"];

  for(var i=0; i<fruitList.length; i++);
    if(userInput == fruitList[i]){
      alert("Sorry, we are out of " + userInput);
    }else{
      var userFruit = document.createElement('li');
      userFruit.textContent = userInput;
      var fruits = document.getElementById('list');
      fruits.appendChild(userFruit);
    }
</code>```

答:
I edited your code more make sense.

Is it similar to what you expect?

var userInput = prompt('Which fruit would you like?');
var fruitList = ["banana", 'strawberries', "mango"];
let newItem = false;
for (let i = 0; i < fruitList.length; i++) {
  if (userInput == fruitList[i]) {
    newItem = false;
    alert("Sorry, we are out of " + userInput);
  } else {
    newItem = true;
  }
}
if (newItem) {

  let userFruit = document.createElement('li');
  userFruit.innerHTML = userInput
  let fruits = document.getElementById('list');
  fruits.appendChild(userFruit);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="list">

</ul></code>```

Title: Elements in the array not recognized

Body:
    var userInput = prompt('Which fruit would you like?');
      var fruitList = ["banana", 'strawberries', "mango"];

      for(var i=0; i<fruitList.length; i++);
        if(userInput == fruitList[i]){
          alert("Sorry, we are out of " + userInput);
        }else{
          var userFruit = document.createElement('li');
          userFruit.textContent = userInput;
          var fruits = document.getElementById('list');
          fruits.appendChild(userFruit);
        }

It looks like for loop is not working as it's adding the user input into the list but it doesn't recognize elements from the array. The list which I didn't add here has id="list" and it has the three elements from the array. Thank you!

  var userInput = prompt('Which fruit would you like?');
  var fruitList = ["banana", 'strawberries', "mango"];

  for(var i=0; i<fruitList.length; i++);
    if(userInput == fruitList[i]){
      alert("Sorry, we are out of " + userInput);
    }else{
      var userFruit = document.createElement('li');
      userFruit.textContent = userInput;
      var fruits = document.getElementById('list');
      fruits.appendChild(userFruit);
    }

Body:
I edited your code more make sense.

Is it similar to what you expect?

var userInput = prompt('Which fruit would you like?');
var fruitList = ["banana", 'strawberries', "mango"];
let newItem = false;
for (let i = 0; i < fruitList.length; i++) {
  if (userInput == fruitList[i]) {
    newItem = false;
    alert("Sorry, we are out of " + userInput);
  } else {
    newItem = true;
  }
}
if (newItem) {

  let userFruit = document.createElement('li');
  userFruit.innerHTML = userInput
  let fruits = document.getElementById('list');
  fruits.appendChild(userFruit);
}

<ul id="list">

</ul>


问:
Multiple objects fail to render?
My should display two squares on the screen but when I run it all I see is a screen of nothingness.

```<code>#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>

struct Shaderprogramsource
{
std::string VertexSouce;
std::string FragmentSource;
};

static Shaderprogramsource Parseshader(const std::string& filepath)
{
std::ifstream stream(filepath);

enum class Shadertype
{
    VERTEX = 0,
    FRAGMENT = 1,
    NONE = 5
};

std::string line;
std::stringstream ss[3];

Shadertype type = Shadertype::NONE;

while (getline(stream, line))
{
    if (line.find("#shader") != std::string::npos)
    {
        if (line.find("vertex") != std::string::npos)
            type = Shadertype::VERTEX;

        else if (line.find("fragment") != std::string::npos)
            type = Shadertype::FRAGMENT;
    }
    else
    {
        ss[(int)type] << line << "\n";
    }
}

return Shaderprogramsource{ ss[0].str(), ss[1].str() };
}

static int CompileShader(unsigned int type, const std::string& Source)
{
unsigned int id = glCreateShader(type);
const char* src = Source.c_str();
glShaderSource(id, 1, &src, nullptr);
glCompileShader(id);

int result;
glGetShaderiv(id, GL_COMPILE_STATUS, &result);

if (result == GL_FALSE)
{
    int length;
    glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length);

    char* message = (char*)alloca(length * sizeof(char));
    glGetShaderInfoLog(id, length, &length, message);

    std::cout << message;

    return 0;
}

return id;
}

static unsigned int CreateShader(
const std::string& Vertexshader,
const std::string& Fragmentshader)
{
unsigned int program = glCreateProgram();
unsigned int vertex = CompileShader(GL_VERTEX_SHADER, Vertexshader);
unsigned int fragment = CompileShader(GL_FRAGMENT_SHADER, Fragmentshader);

glAttachShader(program, vertex);
glAttachShader(program, fragment);

glLinkProgram(program);
glValidateProgram(program);

return program;
}

int main(void)
{
GLFWwindow* window;

/* Initialize the library */
if (!glfwInit())
    return -1;

glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(800, 800, "Hello World", NULL, NULL);
if (!window)
{
    glfwTerminate();
    return -1;
}

/* Make the window's context current */
glfwMakeContextCurrent(window);

if (GLEW_OK == glewInit())
{
}

float vertices[] = { -0.1, -0.1,
                      0.1, -0.1,
                      0.1, 0.1,
                     -0.1, 0.1 };

float vertices2[] = { -0.1,0.1,
                      0.1, 0.1,
                      0.1, 0.3,
                     -0.1, 0.3 };

unsigned int indices[] = {

    0, 1, 2,
    2, 3, 0

};

unsigned int vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);

unsigned int vao2;
glGenVertexArrays(1, &vao2);
glBindVertexArray(vao2);

unsigned int buffer1;

unsigned int vbo;

glGenBuffers(1, &buffer1);
glBindBuffer(GL_ARRAY_BUFFER, buffer1);
glBufferData(GL_ARRAY_BUFFER, 4 * 2 * sizeof(float), vertices, GL_STATIC_DRAW);

glEnableVertexAttribArray(0);

glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);

glEnableVertexAttribArray(1);

glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);

glGenBuffers(1, &vbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * sizeof(unsigned int), indices, GL_STATIC_DRAW);

Shaderprogramsource source = Parseshader("res/shaders/Basic.Shader");

unsigned int shader =
    CreateShader(source.VertexSouce, source.FragmentSource);

glUseProgram(shader);

int location = glGetUniformLocation(shader, "Color_u");
if (location > -1) {
    glUniform4f(location, 0.8f, 0.0f, 0.0f, 1.0f);

}

std::cout << source.VertexSouce;

glUseProgram(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
    /* Render here */

    glClear(GL_COLOR_BUFFER_BIT);

    glUseProgram(shader);
    glBindBuffer(GL_ARRAY_BUFFER, vao);
    glBindBuffer(GL_ARRAY_BUFFER, vao2);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo);

    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);

    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);

    glEnableVertexAttribArray(0);

    glEnableVertexAttribArray(1);

    glUseProgram(shader);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);

    /* Swap front and back buffers */
    glfwSwapBuffers(window);

    /* Poll for and process events */
    glfwPollEvents();
}

glDeleteProgram(shader);

glfwTerminate();
return 0;
}
</code>```

Shaders:

```<code>#shader vertex
#version 330 core

layout(location = 0) in vec3 position;

void main()
{
gl_Position = vec4(position.x, position.y, position.z, 1.0);
};

#shader fragment
#version 330 core

layout(location = 0) out vec4 color;

uniform vec4 Color_u;

void main()
{
color = Color_u;
};
</code>```

答:
All sorts of wonk-a-donk:

Parseshader() is broken if the first line starts with anything other than the magic #shader directive, since NONE is set to 5 and the ss[(int)type] index + assignment will walk right off the end of the 3-element ss array.  Drop NONE down to 2.

You only have a single vertex attribute in your shader (0) yet you're trying to set up 1.

That's not how VAOs work at all.  A VAO has never been a valid argument to glBindBuffer().  Intead, bind a VAO & then set up your vertex attribute bindings/layouts:

```<code>unsigned int vao1 = 0;
glGenVertexArrays(1, &vao1);
glBindVertexArray(vao1);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBindBuffer(GL_ARRAY_BUFFER, buffer1);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);
glEnableVertexAttribArray(0);
</code>```

Then later when you want to draw you can re-bind the VAO and immediately draw, skipping all the glBindBuffer()/glVertexAttribPointer()/glEnableVertexAttribArray() setup.

All together:

// g++ -g main.cpp `pkg-config --cflags --libs glfw3 glew`
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <sstream>
#include <string>

const char* const shaderSource = R"GLSL(
#shader vertex
#version 330 core
layout(location = 0) in vec3 position;
void main()
{
    gl_Position = vec4(position.x, position.y, position.z, 1.0);
};

#shader fragment
#version 330 core
layout(location = 0) out vec4 color;
uniform vec4 Color_u;
void main()
{
    color = Color_u;
};
)GLSL";

struct Shaderprogramsource
{
    std::string VertexSouce;
    std::string FragmentSource;
};

static Shaderprogramsource Parseshader(const std::string& shaderString)
{
    std::stringstream stream( shaderString );

    enum class Shadertype
    {
        VERTEX = 0,
        FRAGMENT = 1,
        NONE = 2
    };

    std::string line;
    std::stringstream ss[3];

    Shadertype type = Shadertype::NONE;

    while( std::getline(stream, line) )
    {
        if (line.find("#shader") != std::string::npos)
        {
            if (line.find("vertex") != std::string::npos)
                type = Shadertype::VERTEX;

            else if (line.find("fragment") != std::string::npos)
                type = Shadertype::FRAGMENT;
        }
        else
        {
            ss[(int)type] << line << '\n';
        }
    }

    return Shaderprogramsource{ ss[0].str(), ss[1].str() };
    }

static int CompileShader(unsigned int type, const std::string& Source)
{
    unsigned int id = glCreateShader(type);
    const char* src = Source.c_str();
    glShaderSource(id, 1, &src, nullptr);
    glCompileShader(id);

    int result;
    glGetShaderiv(id, GL_COMPILE_STATUS, &result);

    if (result == GL_FALSE)
    {
        int length;
        glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length);

        char* message = (char*)alloca(length * sizeof(char));
        glGetShaderInfoLog(id, length, &length, message);

        std::cout << message;

        return 0;
    }

    return id;
}

static unsigned int CreateShader( const std::string& Vertexshader, const std::string& Fragmentshader )
{
    unsigned int program = glCreateProgram();
    unsigned int vertex = CompileShader(GL_VERTEX_SHADER, Vertexshader);
    unsigned int fragment = CompileShader(GL_FRAGMENT_SHADER, Fragmentshader);

    glAttachShader(program, vertex);
    glAttachShader(program, fragment);

    glLinkProgram(program);
    glValidateProgram(program);

    return program;
}

int main( int argc, char** argv )
{
    if (!glfwInit())
        return -1;

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    GLFWwindow* window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    /* Make the window's context current */
    glfwMakeContextCurrent(window);

    if (GLEW_OK == glewInit())
    {
    }

    unsigned int buffer1;
    glGenBuffers(1, &buffer1);
    glBindBuffer(GL_ARRAY_BUFFER, buffer1);
    float vertices1[] =
    {
        -0.1, -0.1,
        0.1, -0.1,
        0.1, 0.1,
        -0.1, 0.1,
    };
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices1), vertices1, GL_STATIC_DRAW);

    unsigned int buffer2;
    glGenBuffers(1, &buffer2);
    glBindBuffer(GL_ARRAY_BUFFER, buffer2);
    float vertices2[] =
    {
        -0.1, 0.1,
        0.1, 0.1,
        0.1, 0.3,
        -0.1, 0.3,
    };
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices2), vertices2, GL_STATIC_DRAW);

    unsigned int ebo;
    glGenBuffers(1, &ebo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    unsigned int indices[] =
    {
        0, 1, 2,
        2, 3, 0,
    };
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

    unsigned int vao1 = 0;
    glGenVertexArrays(1, &vao1);
    glBindVertexArray(vao1);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glBindBuffer(GL_ARRAY_BUFFER, buffer1);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);
    glEnableVertexAttribArray(0);

    unsigned int vao2 = 0;
    glGenVertexArrays(1, &vao2);
    glBindVertexArray(vao2);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glBindBuffer(GL_ARRAY_BUFFER, buffer2);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);
    glEnableVertexAttribArray(0);

    Shaderprogramsource source = Parseshader( shaderSource );
    unsigned int shader = CreateShader(source.VertexSouce, source.FragmentSource);
    glUseProgram(shader);
    int location = glGetUniformLocation(shader, "Color_u");

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        glfwPollEvents();

        glClear(GL_COLOR_BUFFER_BIT);

        glUseProgram(shader);

        if (location > -1)
        {
            glUniform4f(location, 0.8f, 0.0f, 0.0f, 1.0f);
        }
        glBindVertexArray(vao1);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);

        if (location > -1)
        {
            glUniform4f(location, 0.0f, 0.8f, 0.0f, 1.0f);
        }
        glBindVertexArray(vao2);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);

        glfwSwapBuffers(window);
    }

    glDeleteProgram(shader);

    glfwTerminate();
    return 0;
}
```

Title: Multiple objects fail to render?

Body:
My should display two squares on the screen but when I run it all I see is a screen of nothingness.

#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>

struct Shaderprogramsource
{
std::string VertexSouce;
std::string FragmentSource;
};

static Shaderprogramsource Parseshader(const std::string& filepath)
{
std::ifstream stream(filepath);

enum class Shadertype
{
    VERTEX = 0,
    FRAGMENT = 1,
    NONE = 5
};

std::string line;
std::stringstream ss[3];

Shadertype type = Shadertype::NONE;

while (getline(stream, line))
{
    if (line.find("#shader") != std::string::npos)
    {
        if (line.find("vertex") != std::string::npos)
            type = Shadertype::VERTEX;

        else if (line.find("fragment") != std::string::npos)
            type = Shadertype::FRAGMENT;
    }
    else
    {
        ss[(int)type] << line << "\n";
    }
}

return Shaderprogramsource{ ss[0].str(), ss[1].str() };
}

static int CompileShader(unsigned int type, const std::string& Source)
{
unsigned int id = glCreateShader(type);
const char* src = Source.c_str();
glShaderSource(id, 1, &src, nullptr);
glCompileShader(id);

int result;
glGetShaderiv(id, GL_COMPILE_STATUS, &result);

if (result == GL_FALSE)
{
    int length;
    glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length);

    char* message = (char*)alloca(length * sizeof(char));
    glGetShaderInfoLog(id, length, &length, message);

    std::cout << message;

    return 0;
}

return id;
}

static unsigned int CreateShader(
const std::string& Vertexshader,
const std::string& Fragmentshader)
{
unsigned int program = glCreateProgram();
unsigned int vertex = CompileShader(GL_VERTEX_SHADER, Vertexshader);
unsigned int fragment = CompileShader(GL_FRAGMENT_SHADER, Fragmentshader);

glAttachShader(program, vertex);
glAttachShader(program, fragment);

glLinkProgram(program);
glValidateProgram(program);

return program;
}

int main(void)
{
GLFWwindow* window;

/* Initialize the library */
if (!glfwInit())
    return -1;

glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(800, 800, "Hello World", NULL, NULL);
if (!window)
{
    glfwTerminate();
    return -1;
}

/* Make the window's context current */
glfwMakeContextCurrent(window);

if (GLEW_OK == glewInit())
{
}

float vertices[] = { -0.1, -0.1,
                      0.1, -0.1,
                      0.1, 0.1,
                     -0.1, 0.1 };

float vertices2[] = { -0.1,0.1,
                      0.1, 0.1,
                      0.1, 0.3,
                     -0.1, 0.3 };

unsigned int indices[] = {

    0, 1, 2,
    2, 3, 0

};

unsigned int vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);

unsigned int vao2;
glGenVertexArrays(1, &vao2);
glBindVertexArray(vao2);

unsigned int buffer1;

unsigned int vbo;

glGenBuffers(1, &buffer1);
glBindBuffer(GL_ARRAY_BUFFER, buffer1);
glBufferData(GL_ARRAY_BUFFER, 4 * 2 * sizeof(float), vertices, GL_STATIC_DRAW);

glEnableVertexAttribArray(0);

glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);

glEnableVertexAttribArray(1);

glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);

glGenBuffers(1, &vbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * sizeof(unsigned int), indices, GL_STATIC_DRAW);

Shaderprogramsource source = Parseshader("res/shaders/Basic.Shader");

unsigned int shader =
    CreateShader(source.VertexSouce, source.FragmentSource);

glUseProgram(shader);

int location = glGetUniformLocation(shader, "Color_u");
if (location > -1) {
    glUniform4f(location, 0.8f, 0.0f, 0.0f, 1.0f);

}

std::cout << source.VertexSouce;

glUseProgram(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
    /* Render here */

    glClear(GL_COLOR_BUFFER_BIT);

    glUseProgram(shader);
    glBindBuffer(GL_ARRAY_BUFFER, vao);
    glBindBuffer(GL_ARRAY_BUFFER, vao2);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo);

    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);

    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);

    glEnableVertexAttribArray(0);

    glEnableVertexAttribArray(1);

    glUseProgram(shader);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);

    /* Swap front and back buffers */
    glfwSwapBuffers(window);

    /* Poll for and process events */
    glfwPollEvents();
}

glDeleteProgram(shader);

glfwTerminate();
return 0;
}

Shaders:

#shader vertex
#version 330 core

layout(location = 0) in vec3 position;

void main()
{
gl_Position = vec4(position.x, position.y, position.z, 1.0);
};

#shader fragment
#version 330 core

layout(location = 0) out vec4 color;

uniform vec4 Color_u;

void main()
{
color = Color_u;
};

Body:
All sorts of wonk-a-donk:

Parseshader() is broken if the first line starts with anything other than the magic #shader directive, since NONE is set to 5 and the ss[(int)type] index + assignment will walk right off the end of the 3-element ss array.  Drop NONE down to 2.

You only have a single vertex attribute in your shader (0) yet you're trying to set up 1.

That's not how VAOs work at all.  A VAO has never been a valid argument to glBindBuffer().  Intead, bind a VAO & then set up your vertex attribute bindings/layouts:

unsigned int vao1 = 0;
glGenVertexArrays(1, &vao1);
glBindVertexArray(vao1);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBindBuffer(GL_ARRAY_BUFFER, buffer1);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);
glEnableVertexAttribArray(0);

Then later when you want to draw you can re-bind the VAO and immediately draw, skipping all the glBindBuffer()/glVertexAttribPointer()/glEnableVertexAttribArray() setup.

All together:

// g++ -g main.cpp `pkg-config --cflags --libs glfw3 glew`
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <sstream>
#include <string>

const char* const shaderSource = R"GLSL(
#shader vertex
#version 330 core
layout(location = 0) in vec3 position;
void main()
{
    gl_Position = vec4(position.x, position.y, position.z, 1.0);
};

#shader fragment
#version 330 core
layout(location = 0) out vec4 color;
uniform vec4 Color_u;
void main()
{
    color = Color_u;
};
)GLSL";

struct Shaderprogramsource
{
    std::string VertexSouce;
    std::string FragmentSource;
};

static Shaderprogramsource Parseshader(const std::string& shaderString)
{
    std::stringstream stream( shaderString );

    enum class Shadertype
    {
        VERTEX = 0,
        FRAGMENT = 1,
        NONE = 2
    };

    std::string line;
    std::stringstream ss[3];

    Shadertype type = Shadertype::NONE;

    while( std::getline(stream, line) )
    {
        if (line.find("#shader") != std::string::npos)
        {
            if (line.find("vertex") != std::string::npos)
                type = Shadertype::VERTEX;

            else if (line.find("fragment") != std::string::npos)
                type = Shadertype::FRAGMENT;
        }
        else
        {
            ss[(int)type] << line << '\n';
        }
    }

    return Shaderprogramsource{ ss[0].str(), ss[1].str() };
    }

static int CompileShader(unsigned int type, const std::string& Source)
{
    unsigned int id = glCreateShader(type);
    const char* src = Source.c_str();
    glShaderSource(id, 1, &src, nullptr);
    glCompileShader(id);

    int result;
    glGetShaderiv(id, GL_COMPILE_STATUS, &result);

    if (result == GL_FALSE)
    {
        int length;
        glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length);

        char* message = (char*)alloca(length * sizeof(char));
        glGetShaderInfoLog(id, length, &length, message);

        std::cout << message;

        return 0;
    }

    return id;
}

static unsigned int CreateShader( const std::string& Vertexshader, const std::string& Fragmentshader )
{
    unsigned int program = glCreateProgram();
    unsigned int vertex = CompileShader(GL_VERTEX_SHADER, Vertexshader);
    unsigned int fragment = CompileShader(GL_FRAGMENT_SHADER, Fragmentshader);

    glAttachShader(program, vertex);
    glAttachShader(program, fragment);

    glLinkProgram(program);
    glValidateProgram(program);

    return program;
}

int main( int argc, char** argv )
{
    if (!glfwInit())
        return -1;

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    GLFWwindow* window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    /* Make the window's context current */
    glfwMakeContextCurrent(window);

    if (GLEW_OK == glewInit())
    {
    }

    unsigned int buffer1;
    glGenBuffers(1, &buffer1);
    glBindBuffer(GL_ARRAY_BUFFER, buffer1);
    float vertices1[] =
    {
        -0.1, -0.1,
        0.1, -0.1,
        0.1, 0.1,
        -0.1, 0.1,
    };
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices1), vertices1, GL_STATIC_DRAW);

    unsigned int buffer2;
    glGenBuffers(1, &buffer2);
    glBindBuffer(GL_ARRAY_BUFFER, buffer2);
    float vertices2[] =
    {
        -0.1, 0.1,
        0.1, 0.1,
        0.1, 0.3,
        -0.1, 0.3,
    };
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices2), vertices2, GL_STATIC_DRAW);

    unsigned int ebo;
    glGenBuffers(1, &ebo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    unsigned int indices[] =
    {
        0, 1, 2,
        2, 3, 0,
    };
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

    unsigned int vao1 = 0;
    glGenVertexArrays(1, &vao1);
    glBindVertexArray(vao1);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glBindBuffer(GL_ARRAY_BUFFER, buffer1);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);
    glEnableVertexAttribArray(0);

    unsigned int vao2 = 0;
    glGenVertexArrays(1, &vao2);
    glBindVertexArray(vao2);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glBindBuffer(GL_ARRAY_BUFFER, buffer2);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);
    glEnableVertexAttribArray(0);

    Shaderprogramsource source = Parseshader( shaderSource );
    unsigned int shader = CreateShader(source.VertexSouce, source.FragmentSource);
    glUseProgram(shader);
    int location = glGetUniformLocation(shader, "Color_u");

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        glfwPollEvents();

        glClear(GL_COLOR_BUFFER_BIT);

        glUseProgram(shader);

        if (location > -1)
        {
            glUniform4f(location, 0.8f, 0.0f, 0.0f, 1.0f);
        }
        glBindVertexArray(vao1);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);

        if (location > -1)
        {
            glUniform4f(location, 0.0f, 0.8f, 0.0f, 1.0f);
        }
        glBindVertexArray(vao2);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);

        glfwSwapBuffers(window);
    }

    glDeleteProgram(shader);

    glfwTerminate();
    return 0;
}


问:
Adding localStorage items in the order it was added
I want to sort localStorage items by the order it was added. The code works just fine, where i am able to add items to the localStorage array and loop through the array as HTML code.

If I add the 3rd item to my array, it will become the 2nd item on the list. I don't understand why the items have a completely random order?

Here is my code down below.

```<code><body>

        <h2>Local Storage - JavaScript</h2>

        <form method="post" action="index.html" id="form">
            <fieldset>
                <legend>Insert Data</legend>
                <input id="enterKey" type="text" placeholder="Enter Key...">
                <input id="enterValue" type="text" placeholder="Enter Value...">
                <input type="submit" value="Set Reminder">
            </fieldset>
        </form>

        <ul id="output">
        </ul>

    </body>

    <script>
        form.addEventListener('submit', function(e) {

            const key = enterKey.value;
            const value = enterValue.value;

            if (key && value) {
                localStorage.setItem(key, value);
            }

        })

        for (let i = 0; i < localStorage.length; i++) {

            const key = localStorage.key(i);
            const value = localStorage.getItem(key);

            var li = document.createElement("li");
            li.textContent = `${key}: ${value}</li>`;
            output.appendChild(li);

        }
   </script>
</code>```

答:
The order is random because localStorage is stored as key-value pairs, and such objects do not guarantee ordering. In fact some languages deliberately randomise the ordering so that programmers won't rely on the items being in any particular order. So if you want to have ordering, you will need to introduce the ordering key into the data itself, and then read all the items and sort on the key after that.

Something like:

```<code>form.addEventListener('submit', function (e) {
  const key = enterKey.value;
  const value = enterValue.value;
  if (key && value) {
    const count = localStorage.length;
    const val = {
      value,
      order: count,
    }
    localStorage.setItem(key, val);
  }

})

const items = [];
for (let i = 0; i < localStorage.length; i++) {
  const key = localStorage.key(i);
  const value = localStorage.getItem(key);
  items.push({key, value});
}
items.sort((a, b) => a.value.order - b.value.order).forEach(item => {
  var li = document.createElement("li");
  li.textContent = `${item.key}: ${item.value.value}</li>`;
  output.appendChild(li);
});
</code>```

Body:
I want to sort localStorage items by the order it was added. The code works just fine, where i am able to add items to the localStorage array and loop through the array as HTML code.

If I add the 3rd item to my array, it will become the 2nd item on the list. I don't understand why the items have a completely random order?

Here is my code down below.

Local Storage - JavaScript

        <form method="post" action="index.html" id="form">
            <fieldset>
                <legend>Insert Data</legend>
                <input id="enterKey" type="text" placeholder="Enter Key...">
                <input id="enterValue" type="text" placeholder="Enter Value...">
                <input type="submit" value="Set Reminder">
            </fieldset>
        </form>

Body:
The order is random because localStorage is stored as key-value pairs, and such objects do not guarantee ordering. In fact some languages deliberately randomise the ordering so that programmers won't rely on the items being in any particular order. So if you want to have ordering, you will need to introduce the ordering key into the data itself, and then read all the items and sort on the key after that.

Something like:

form.addEventListener('submit', function (e) {
  const key = enterKey.value;
  const value = enterValue.value;
  if (key && value) {
    const count = localStorage.length;
    const val = {
      value,
      order: count,
    }
    localStorage.setItem(key, val);
  }

})

const items = [];
for (let i = 0; i < localStorage.length; i++) {
  const key = localStorage.key(i);
  const value = localStorage.getItem(key);
  items.push({key, value});
}
items.sort((a, b) => a.value.order - b.value.order).forEach(item => {
  var li = document.createElement("li");
  li.textContent = `${item.key}: ${item.value.value}</li>`;
  output.appendChild(li);
});


问:
Taking data out of JSONP
Using the url:
http://www.remote_host.com/feed.php?callback=jsonpCallback

I get back:

```<code>jsonpCallback({
    "rss": {
        "channels": [
            {
                "title": "title goes here",
                "link": "http://www.remote_server.com/feed.php",
                "description": "description goes here",
                "items": [
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    }
                ]
            }
        ]
    } })
</code>```

At clientside, I have the following script:

```<code>$(document).ready(function() {
    get_jsonp_feed();

    function get_jsonp_feed() {
        $.ajax({
            url: 'http://www.remote_host.co.uk/feed.php',
            type: 'GET',
            dataType: 'jsonp',
            jsonp: 'callback',
            jsonpCallback: 'jsonpCallback',
            error: function(xhr, status, error) {
                alert("error");
            },
            success: function(jsonp) {
                alert("success");
            }
        });
    }
});
</code>```

How do I write some of the jsonp content to the screen, i.e.

```<code>channel title: title goes here<br /><br />

item title: title goes here<br />
item link: link goes here<br />
item date: date goes here<br />
item description: description goes here<br /><br />

item title: title goes here<br />
item link: link goes here<br />
item date: date goes here<br />
item description: description goes here<br /><br />

item title: title goes here<br />
item link: link goes here<br />
item date: date goes here<br />
item description: description goes here<br /><br />
</code>```

instead of alerting "success"?

答:
You could have the callback function something like this:

```<code>function jsonpCallback(data){
    $.each(data.rss.channels,function(d,c){
        var html = "channel title: "+c.title+"<br /><br />";

        $('#content').html($('#content').html()+html);
        $.each(c.items,function(i,e){

        var html = "item title: "+e.title+"<br />item link: "+e.link+"<br />item date: "+e.pubDate+"<br />item description: "+e.description+"<br /><br />";
        $('#content').html($('#content').html()+html);

    });

    });

}
</code>```

Example: http://jsfiddle.net/niklasvh/tYgzw/

Title: Taking data out of JSONP

Body:
Using the url:
http://www.remote_host.com/feed.php?callback=jsonpCallback

I get back:

jsonpCallback({
    "rss": {
        "channels": [
            {
                "title": "title goes here",
                "link": "http://www.remote_server.com/feed.php",
                "description": "description goes here",
                "items": [
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    },
                    {
                        "title": "item title goes here",
                        "link": "item link goes here",
                        "pubDate": "item date goes here",
                        "description": "item description goes here"
                    }
                ]
            }
        ]
    } })

At clientside, I have the following script:

$(document).ready(function() {
    get_jsonp_feed();

    function get_jsonp_feed() {
        $.ajax({
            url: 'http://www.remote_host.co.uk/feed.php',
            type: 'GET',
            dataType: 'jsonp',
            jsonp: 'callback',
            jsonpCallback: 'jsonpCallback',
            error: function(xhr, status, error) {
                alert("error");
            },
            success: function(jsonp) {
                alert("success");
            }
        });
    }
});

How do I write some of the jsonp content to the screen, i.e.

channel title: title goes here

item title: title goes here

item link: link goes here

item date: date goes here

item description: description goes here

item title: title goes here

item link: link goes here

item date: date goes here

item description: description goes here

item title: title goes here

item link: link goes here

item date: date goes here

item description: description goes here

instead of alerting "success"?

Body:
You could have the callback function something like this:

function jsonpCallback(data){
    $.each(data.rss.channels,function(d,c){
        var html = "channel title: "+c.title+"<br /><br />";

        $('#content').html($('#content').html()+html);
        $.each(c.items,function(i,e){

        var html = "item title: "+e.title+"<br />item link: "+e.link+"<br />item date: "+e.pubDate+"<br />item description: "+e.description+"<br /><br />";
        $('#content').html($('#content').html()+html);

    });

    });

}

Example: http://jsfiddle.net/niklasvh/tYgzw/


问:
How to retrieve metadata from firebase storage?
```<code>info(String choice) async {
    print(choice);
    if (choice == 'Created on') {
      print('hii');
      StorageReference imageRef = storageRef.child(imageLocation);
      await imageRef
          .getMetadata()
          .then((value) => print(value.creationTimeMillis));
      int created = 3;
      String create = timeago.format(
        DateTime.fromMillisecondsSinceEpoch(created),
      );

      print(create);
    }
    Scaffold.of(context).showSnackBar(
      SnackBar(
        content: Text(" hiii"),
      ),
    );
  }
</code>```

I have used this method but it doesn't seems to work
what is the method if above on

答:
I think you're looking for this:

```<code>StorageReference imageRef = storageRef.child(imageLocation);
imageRef
    .getMetadata()
    .then((value) => {
        String create = timeago.format(
          DateTime.fromMillisecondsSinceEpoch(value.creationTimeMillis),
        );
        print(create);
    })
</code>```

All code that needs the metadata needs to be in the then block.

Alternatively if you want to use await, you don't need then():

```<code>StorageReference imageRef = storageRef.child(imageLocation);
var value = await imageRef.getMetadata()
String create = timeago.format(
  DateTime.fromMillisecondsSinceEpoch(value.creationTimeMillis),
);
print(create);
</code>```

Body:
info(String choice) async {
    print(choice);
    if (choice == 'Created on') {
      print('hii');
      StorageReference imageRef = storageRef.child(imageLocation);
      await imageRef
          .getMetadata()
          .then((value) => print(value.creationTimeMillis));
      int created = 3;
      String create = timeago.format(
        DateTime.fromMillisecondsSinceEpoch(created),
      );

      print(create);
    }
    Scaffold.of(context).showSnackBar(
      SnackBar(
        content: Text(" hiii"),
      ),
    );
  }

I have used this method but it doesn't seems to work
what is the method if above on

Body:
I think you're looking for this:

StorageReference imageRef = storageRef.child(imageLocation);
imageRef
    .getMetadata()
    .then((value) => {
        String create = timeago.format(
          DateTime.fromMillisecondsSinceEpoch(value.creationTimeMillis),
        );
        print(create);
    })

All code that needs the metadata needs to be in the then block.

Alternatively if you want to use await, you don't need then():

StorageReference imageRef = storageRef.child(imageLocation);
var value = await imageRef.getMetadata()
String create = timeago.format(
  DateTime.fromMillisecondsSinceEpoch(value.creationTimeMillis),
);
print(create);


问:
The provider 'Microsoft.Jet.OLEDB.4.0' is not registered on the local computer, help me
his is my code developed with c # and it does not connect me to the database dont know why, i am using everything correctly, the error is The provider 'Microsoft.Jet.OLEDB.4.0' is not registered on the local computer.</p>

```<code>enter code here
static public void conectar()
    {
        try {

            string gsPatchUbicar = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            gsPatchUbicar = gsPatchUbicar.Substring(6);
            DireccionBD = gsPatchUbicar + "\\db_deportes.mdb";
            string stringconeccion = string.Format(@"PROVIDER=Microsoft.Jet.OLEBD.4.0;Data Source={0}; Jet OLEBD:Database Password={1}", DireccionBD, PasswordBD);
            getConexion = new OleDbConnection(stringconeccion);
            getConexion.Open();
            MessageBox.Show("Conexion a base de datos exitosa!!", "ok", MessageBoxButtons.OK, MessageBoxIcon.Information);
        } catch (Exception H)
        {
            MessageBox.Show("hay un error en la conexion de base de datos");
        }

    }
</code>```

答:
There is indeed no 64 bit version of Jet - and no plans (apparently) to produce one.

You might be able to use the ACE 64 bit driver: http://www.microsoft.com/en-us/download/details.aspx?displaylang=en&id=23734[^] - but I have no idea how that would work if you need to go back to Jet for your 32 bit apps.

However, you may be able to switch the project to 32bit in the Express version (I haven't tried and don't have 2008 installed in any flavour anymore) - there is a thread here that talks about it: http://xboxforums.create.msdn.com/forums/t/4377.aspx#22601[^]

Maybe it's time to scrap Access databases altogether, bite the bullet and go for SQL server instead?

Body:
his is my code developed with c # and it does not connect me to the database dont know why, i am using everything correctly, the error is The provider 'Microsoft.Jet.OLEDB.4.0' is not registered on the local computer.

enter code here
static public void conectar()
    {
        try {

            string gsPatchUbicar = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            gsPatchUbicar = gsPatchUbicar.Substring(6);
            DireccionBD = gsPatchUbicar + "\\db_deportes.mdb";
            string stringconeccion = string.Format(@"PROVIDER=Microsoft.Jet.OLEBD.4.0;Data Source={0}; Jet OLEBD:Database Password={1}", DireccionBD, PasswordBD);
            getConexion = new OleDbConnection(stringconeccion);
            getConexion.Open();
            MessageBox.Show("Conexion a base de datos exitosa!!", "ok", MessageBoxButtons.OK, MessageBoxIcon.Information);
        } catch (Exception H)
        {
            MessageBox.Show("hay un error en la conexion de base de datos");
        }

    }


问:
Tf objection detection API deployment on django
I am currently trying to serve into a webapp build in Django however I am facing some difficulties.
1. I have succesfully trained my model and I have the precious frozen_inference_graph.
2. I am creating the webapp on django.

I would like to call my model directly from my webapp folder. However, when using the inference method from my webapp folder, no inference is done: there is not bug and the script does nothing . In my tf folder, the script does the proper inference.

Do you have any clues? Also I have not found any tutorial for serving tensorflow on Django, are you aware of some?

Thanks,
Have a nice day !

答:
You could serving your model.

TensorFlow Serving is a flexible, high-performance serving system for machine learning models, designed for production environments. TensorFlow Serving makes it easy to deploy new algorithms and experiments, while keeping the same server architecture and APIs. TensorFlow Serving provides out-of-the-box integration with TensorFlow models, but can be easily extended to serve other types of models and data.

https://www.tensorflow.org/tfx/guide/serving

good luck!


问:
iphone to flash communication
I was looking this new game (http://kijjaa.com/air/) that uses the iPhone as a control pad for a flash game in your computer browser. I tried to monitor the HTTP activity of the browser but it doesn't seem to be using the HTTP protocol.

Do you know how does this works? It's sockets programming? Can the flash movie become a socket server?

答:
I would say, they are using something similar to this:

@tomkrcha
  Videotutorial: Controlling
  the desktop with your mobile device
  via P2P http://bit.ly/mAg8rD For iOS,
  Playbook, Android. #AIR

Title: iphone to flash communication


问:
ifelse not returning a vector in BASE R
Maybe this is too basic of a question. But in my function foo below, I expected that because of using ifelse when I input a vector for the input values, I get a vector output.

But I wonder why in the example below instead of getting > [1] 1   6 in the output, I just get > [1] 1 as the output?

```<code>foo <- function(mpre = NA, mpos = NA, mdif = NA){
ifelse(!is.na(mdif), mdif, ifelse(!is.na(mpre) & !is.na(mpre) & is.na(mdif), mpos - mpre, NA))
}
## EXAMPLE:

foo(c(1,3), c(2,9))
</code>```

答:
ifelse returns output of same length as input (test). From ?ifelse

ifelse returns a value with the same shape as test

Since mdif is of length 1 it returns output of same length i.e [1] 1. Use if for scalars and ifelse for vectors.

```<code>foo <- function(mpre, mpos, mdif = NA){

   if(!is.na(mdif)) mdif
     else ifelse(!is.na(mpre) & !is.na(mpre) & is.na(mdif), mpos - mpre, NA)
}

foo(c(1,3), c(2,9))
#[1] 1 6
</code>```

Title: ifelse not returning a vector in BASE R

Body:
Maybe this is too basic of a question. But in my function foo below, I expected that because of using ifelse when I input a vector for the input values, I get a vector output.

But I wonder why in the example below instead of getting > [1] 1   6 in the output, I just get > [1] 1 as the output?

foo <- function(mpre = NA, mpos = NA, mdif = NA){
ifelse(!is.na(mdif), mdif, ifelse(!is.na(mpre) & !is.na(mpre) & is.na(mdif), mpos - mpre, NA))
}
## EXAMPLE:

foo(c(1,3), c(2,9))

Body:
ifelse returns output of same length as input (test). From ?ifelse

ifelse returns a value with the same shape as test

Since mdif is of length 1 it returns output of same length i.e [1] 1. Use if for scalars and ifelse for vectors.

foo <- function(mpre, mpos, mdif = NA){

   if(!is.na(mdif)) mdif
     else ifelse(!is.na(mpre) & !is.na(mpre) & is.na(mdif), mpos - mpre, NA)
}

foo(c(1,3), c(2,9))
#[1] 1 6


问:
Iterate sub-items Ansible with sublements
Have task which copies each user's key

```<code>- name: SSH Keys
  authorized_key:
    user: "{{ item.0.name }}"
    key: "{{ item.0.ssh_key.0.key }}"
    state: "{{ item.0.ssh_key.0.state }}"
  when:
    - item.1 == 'all' or item.1 in group_names or item.1 == inventory_hostname
  with_subelements:
    - "{{ users }}"
    - servers
</code>```

Var list:

```<code>users:
  - name: user1
    ssh_key:
      - key:
        - "key1.user1"
        - "key2.user1"
        - "key3.user1"
        state: present
    servers:
      - server1
  - name: user2
    ssh_key:
      - key:
        - "key1.user2"
        - "key2.user2"
        state: present
    servers:
      - all
</code>```

QUESTION: How can we allow users to copy multiple keys? Without deleting servers from with_subelements.
When starting the task, either the last key or an array with keys is copied, depending on how we write it in var list.
In this format copied last key.

```<code>- key: "key1.user1"
- key: "key2.user1"
- key: "key3.user1"
</code>```

In this array.

```<code>- key:
  - "key1"
  - "key2"
</code>```

答:
Let's fit the structure of the data to this purpose. For example,

users:
  - name: user1
    ssh_key:
      - "key1.user1"
      - "key2.user1"
      - "key3.user1"
    state: present
    servers:
      - server1
...

```

<p>It's possible to loop <code>include_tasks</code>. For example, create the task (test it with <code>debug</code> first)</p>

<pre class="lang-yaml prettyprint-override"><code>shell> cat conf_authorized_key.yml
- name: SSH Keys
# authorized_key:
  debug:
    msg:
      - "user: {{ item.0.name }}"
      - "state: {{ item.0.state }}"
      - "key: {{ iitem }}"
  loop: "{{ item.0.ssh_key }}"
  loop_control:
    loop_var: iitem
</code>```

Then include it in the playbook

shell> cat playbook.yml
- hosts: localhost

  vars:
    users:
      - name: user1
        ssh_key:
          - "key1.user1"
          - "key2.user1"
          - "key3.user1"
        state: present
        servers:
          - server1
      - name: user2
        ssh_key:
          - "key1.user2"
          - "key2.user2"
        state: present
        servers:
          - all

  tasks:
    - name: Loop include_task
      include_tasks: conf_authorized_key.yml
      loop: "{{ users|subelements('servers') }}"
      loop_control:
        label: "{{ item.1 }}"
      when: (item.1 == 'all') or
            (item.1 in group_names) or
            (item.1 == inventory_hostname)
```

<p>gives</p>

<pre class="lang-yaml prettyprint-override"><code>shell> ansible-playbook playbook.yml

PLAY [localhost] ****

TASK [Loop include_task] ****
skipping: [localhost] => (item=server1)
included: /export/scratch/tmp/conf_authorized_key.yml for localhost

TASK [SSH Keys] ****
ok: [localhost] => (item=key1.user2) => {
    "msg": [
        "user: user2",
        "state: present",
        "key: key1.user2"
    ]
}
ok: [localhost] => (item=key2.user2) => {
    "msg": [
        "user: user2",
        "state: present",
        "key: key2.user2"
    ]
}

PLAY RECAP ****
localhost: ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
</code>```

Body:
Have task which copies each user's key

- name: SSH Keys
  authorized_key:
    user: "{{ item.0.name }}"
    key: "{{ item.0.ssh_key.0.key }}"
    state: "{{ item.0.ssh_key.0.state }}"
  when:
    - item.1 == 'all' or item.1 in group_names or item.1 == inventory_hostname
  with_subelements:
    - "{{ users }}"
    - servers

Var list:

users:
  - name: user1
    ssh_key:
      - key:
        - "key1.user1"
        - "key2.user1"
        - "key3.user1"
        state: present
    servers:
      - server1
  - name: user2
    ssh_key:
      - key:
        - "key1.user2"
        - "key2.user2"
        state: present
    servers:
      - all

QUESTION: How can we allow users to copy multiple keys? Without deleting servers from with_subelements.
When starting the task, either the last key or an array with keys is copied, depending on how we write it in var list.
In this format copied last key.

- key: "key1.user1"
- key: "key2.user1"
- key: "key3.user1"

In this array.

- key:
  - "key1"
  - "key2"

Body:
Let's fit the structure of the data to this purpose. For example,

users:
  - name: user1
    ssh_key:
      - "key1.user1"
      - "key2.user1"
      - "key3.user1"
    state: present
    servers:
      - server1
...

It's possible to loop include_tasks. For example, create the task (test it with debug first)

shell> cat conf_authorized_key.yml
- name: SSH Keys
# authorized_key:
  debug:
    msg:
      - "user: {{ item.0.name }}"
      - "state: {{ item.0.state }}"
      - "key: {{ iitem }}"
  loop: "{{ item.0.ssh_key }}"
  loop_control:
    loop_var: iitem

Then include it in the playbook

shell> cat playbook.yml
- hosts: localhost

  vars:
    users:
      - name: user1
        ssh_key:
          - "key1.user1"
          - "key2.user1"
          - "key3.user1"
        state: present
        servers:
          - server1
      - name: user2
        ssh_key:
          - "key1.user2"
          - "key2.user2"
        state: present
        servers:
          - all

  tasks:
    - name: Loop include_task
      include_tasks: conf_authorized_key.yml
      loop: "{{ users|subelements('servers') }}"
      loop_control:
        label: "{{ item.1 }}"
      when: (item.1 == 'all') or
            (item.1 in group_names) or
            (item.1 == inventory_hostname)

gives

shell> ansible-playbook playbook.yml

PLAY [localhost] ****

TASK [Loop include_task] ****
skipping: [localhost] => (item=server1)
included: /export/scratch/tmp/conf_authorized_key.yml for localhost

TASK [SSH Keys] ****
ok: [localhost] => (item=key1.user2) => {
    "msg": [
        "user: user2",
        "state: present",
        "key: key1.user2"
    ]
}
ok: [localhost] => (item=key2.user2) => {
    "msg": [
        "user: user2",
        "state: present",
        "key: key2.user2"
    ]
}

PLAY RECAP ****
localhost: ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0