问:
How can I reset a struct in a function?
I declared a struct an inizialized it in the main.
Then through a function I want to reset this struct, but I can't seem to.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_NOME 20
#define MAX_COGNOME 20
#define MAX_PASSAPORTO 9
#define MAX_LUOGO_DI_NASCITA 15

#define MAX_GIORNO 2
#define MAX_MESE 2
#define MAX_ANNO 4

typedef struct {
    char giorno[MAX_GIORNO+1];
    char mese[MAX_MESE+1];
    char anno[MAX_ANNO+1];
} data; //struct data/*

typedef struct {
    char nome[MAX_NOME+1];
    char cognome[MAX_COGNOME+1];
    data datadinascita;
    char luogodinascita[MAX_LUOGO_DI_NASCITA+1];
    char numeropassaporto[MAX_PASSAPORTO+1];
    int id;
} passeggero; //struct passeggero

void resetUtente();

int main() {

    passeggero utenti;

    utenti.id = 1;
    strcpy(utenti.nome, "John");
    strcpy(utenti.cognome, "McCabe");
    strcpy(utenti.datadinascita.giorno, "12");
    strcpy(utenti.datadinascita.mese, "02");
    strcpy(utenti.datadinascita.anno, "1996");
    strcpy(utenti.luogodinascita, "London");
    strcpy(utenti.numeropassaporto, "AA1234567");

    printf("USER BEFORE RESET:");
    printf("\n%d ------> %s %s - Born %s-%s-%s in %s | PASSPORT NUMBER: %s\n",utenti.id, utenti.nome,
            utenti.cognome, utenti.datadinascita.giorno, utenti.datadinascita.mese, utenti.datadinascita.anno,
            utenti.luogodinascita, utenti.numeropassaporto);

    resetUtente();

    printf("USER AFTER RESET:");
    printf("\n%d ------> %s %s - Born %s-%s-%s in %s | PASSPORT NUMBER: %s\n",utenti.id, utenti.nome,
            utenti.cognome, utenti.datadinascita.giorno, utenti.datadinascita.mese, utenti.datadinascita.anno,
            utenti.luogodinascita, utenti.numeropassaporto);

    return 0;
}

void resetUtente() {

    passeggero utenti;
    int i = 0;

    utenti.id = 0;
    utenti.nome[0] = '\0';
    utenti.cognome[0] = '\0';
    utenti.datadinascita.giorno[0] = '\0';
    utenti.datadinascita.mese[0] = '\0';
    utenti.datadinascita.anno[0] = '\0';
    utenti.luogodinascita[0] = '\0';
    utenti.numeropassaporto[0] = '\0';

}
</code>```

The resetUtente() function, should set all the the fields of the struct to none, but the 2nd printf always prints "John McCabe - Born 12-02-1996 in London | PASSPORT NUMBER: AA1234567"

答:
```<code>void resetUtente(passeggero *u)
{
   memset(u, 0, sizeof(*u));
}
</code>```

And in the main

```<code> resetUtente(&utenti);
</code>```

Title: How can I reset a struct in a function?

Body:
I declared a struct an inizialized it in the main.
Then through a function I want to reset this struct, but I can't seem to.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_NOME 20
#define MAX_COGNOME 20
#define MAX_PASSAPORTO 9
#define MAX_LUOGO_DI_NASCITA 15

#define MAX_GIORNO 2
#define MAX_MESE 2
#define MAX_ANNO 4

typedef struct {
    char giorno[MAX_GIORNO+1];
    char mese[MAX_MESE+1];
    char anno[MAX_ANNO+1];
} data; //struct data/*

typedef struct {
    char nome[MAX_NOME+1];
    char cognome[MAX_COGNOME+1];
    data datadinascita;
    char luogodinascita[MAX_LUOGO_DI_NASCITA+1];
    char numeropassaporto[MAX_PASSAPORTO+1];
    int id;
} passeggero; //struct passeggero

void resetUtente();

int main() {

    passeggero utenti;

    utenti.id = 1;
    strcpy(utenti.nome, "John");
    strcpy(utenti.cognome, "McCabe");
    strcpy(utenti.datadinascita.giorno, "12");
    strcpy(utenti.datadinascita.mese, "02");
    strcpy(utenti.datadinascita.anno, "1996");
    strcpy(utenti.luogodinascita, "London");
    strcpy(utenti.numeropassaporto, "AA1234567");

    printf("USER BEFORE RESET:");
    printf("\n%d ------> %s %s - Born %s-%s-%s in %s | PASSPORT NUMBER: %s\n",utenti.id, utenti.nome,
            utenti.cognome, utenti.datadinascita.giorno, utenti.datadinascita.mese, utenti.datadinascita.anno,
            utenti.luogodinascita, utenti.numeropassaporto);

    resetUtente();

    printf("USER AFTER RESET:");
    printf("\n%d ------> %s %s - Born %s-%s-%s in %s | PASSPORT NUMBER: %s\n",utenti.id, utenti.nome,
            utenti.cognome, utenti.datadinascita.giorno, utenti.datadinascita.mese, utenti.datadinascita.anno,
            utenti.luogodinascita, utenti.numeropassaporto);

    return 0;
}

void resetUtente() {

    passeggero utenti;
    int i = 0;

    utenti.id = 0;
    utenti.nome[0] = '\0';
    utenti.cognome[0] = '\0';
    utenti.datadinascita.giorno[0] = '\0';
    utenti.datadinascita.mese[0] = '\0';
    utenti.datadinascita.anno[0] = '\0';
    utenti.luogodinascita[0] = '\0';
    utenti.numeropassaporto[0] = '\0';

}

The resetUtente() function, should set all the the fields of the struct to none, but the 2nd printf always prints "John McCabe - Born 12-02-1996 in London | PASSPORT NUMBER: AA1234567"

Body:
void resetUtente(passeggero *u)
{
   memset(u, 0, sizeof(*u));
}

And in the main

 resetUtente(&utenti);


来源: stackexchange

问:
How to show remaining characters if the textarea is prefilled?
If I have prefilled textarea, the 250 characters don't actually count the default words already in there. It only starts counting if you start typing something in it.

Also, how do I change the text color to yellow on "100 characters remaining" and change to red on "0 characters remaining"

Can someone help please?

function handle(){
  let element = document.getElementById('input')
  let value = element.value
  let maxLength = element.maxLength
  document.getElementById('remaining').innerText = `${maxLength - Number(value.length)} characters remaining`

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea col="8" rows="8" maxlength='250' onkeyup="handle()" id="input" value="">Hello World. Im born today.</textarea>
<p id='remaining'>250 characters remaining</p></code>```

答:
the 250 characters don't actually count the default words already in there. It only starts counting if you start typing something in it.

Just run your function once on page load:

function handle() {
  let element = document.getElementById('input')
  let value = element.value
  let maxLength = element.maxLength
  document.getElementById('remaining').innerText = `${maxLength - Number(value.length)} characters remaining`
}

handle();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea col="8" rows="8" maxlength='250' onkeyup="handle()" id="input" value="">Hello World. Im born today.</textarea>
<p id='remaining'>250 characters remaining</p></code>```

how do I change the text color to yellow on "100 characters remaining" and change to red on "0 characters remaining"

Do an if on each keyup:

function handle() {
  let element = document.getElementById('input');
  let value = element.value;
  let maxLength = element.maxLength;
  document.getElementById('remaining').innerText = `${maxLength - Number(value.length)} characters remaining`;

  if (maxLength - Number(value.length) == 0) {
    document.getElementById('remaining').style.color = "red";
  } else if (maxLength - Number(value.length) <= 100) {
    document.getElementById('remaining').style.color = "yellow";
  }
}

handle();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea col="8" rows="8" maxlength='250' onkeyup="handle()" id="input" value="">Hello World. Im born today.</textarea>
<p id='remaining'>250 characters remaining</p></code>```

ContentLicense: CC BY-SA 4.0

Body:
If I have prefilled textarea, the 250 characters don't actually count the default words already in there. It only starts counting if you start typing something in it.

Also, how do I change the text color to yellow on "100 characters remaining" and change to red on "0 characters remaining"

Can someone help please?

function handle(){
  let element = document.getElementById('input')
  let value = element.value
  let maxLength = element.maxLength
  document.getElementById('remaining').innerText = `${maxLength - Number(value.length)} characters remaining`

}

<textarea col="8" rows="8" maxlength='250' onkeyup="handle()" id="input" value="">Hello World. Im born today.</textarea>

250 characters remaining

Body:
the 250 characters don't actually count the default words already in there. It only starts counting if you start typing something in it.

Just run your function once on page load:

function handle() {
  let element = document.getElementById('input')
  let value = element.value
  let maxLength = element.maxLength
  document.getElementById('remaining').innerText = `${maxLength - Number(value.length)} characters remaining`
}

handle();

<textarea col="8" rows="8" maxlength='250' onkeyup="handle()" id="input" value="">Hello World. Im born today.</textarea>
<p id='remaining'>250 characters remaining</p>

how do I change the text color to yellow on "100 characters remaining" and change to red on "0 characters remaining"

Do an if on each keyup:

function handle() {
  let element = document.getElementById('input');
  let value = element.value;
  let maxLength = element.maxLength;
  document.getElementById('remaining').innerText = `${maxLength - Number(value.length)} characters remaining`;

  if (maxLength - Number(value.length) == 0) {
    document.getElementById('remaining').style.color = "red";
  } else if (maxLength - Number(value.length) <= 100) {
    document.getElementById('remaining').style.color = "yellow";
  }
}

handle();

<textarea col="8" rows="8" maxlength='250' onkeyup="handle()" id="input" value="">Hello World. Im born today.</textarea>
<p id='remaining'>250 characters remaining</p>


问:
sed recognizing only part of HEX sequence
Stubmled upon strange sed behaviour where only part of HEX sequence is recognized:

There's a string with weird characters that I'm trying to fix and when trying HEX replacement sed finds only first three chars.

xxd output of string with problematic characrets:

6965 7261 f480 8488 6e6f 7761 6e61 2031  iera....nowana 1

I'd like to replace this sequence f480 8488 with printable chars, but sed can recognize only first three:

```<code>sed 's/\xf4\x80\x84/00/g' | xxd
6965 7261 3030 886e 6f77 616e 6120 3136  iera00.nowana 16
</code>```

f480 84 was properly replaced with 3030

however

```<code>sed 's/\xf4\x80\x84\x88/00/g' | xxd
6965 7261 f480 8488 6e6f 7761 6e61 2031  iera....nowana 1
</code>```

doesn't find f480 8488

If I break if onto two sed statements sed 's/\xf4\x80/0/g' | sed 's/\x84\x88/0/g'everything works fine

I would understand if it was looking for pairs, but why only three not four characters in sequence?

答:
Following comment @tripleee and confirmed solution form @the.Legend

Setting LC_ALL=C is a working fix.
It is well documented here.

It forces applications to use the default language for output:

```<code> $ LC_ALL=es_ES man
 ¿Qué página de manual desea?

 $ LC_ALL=C man
 What manual page do you want?
</code>```

Body:
Stubmled upon strange sed behaviour where only part of HEX sequence is recognized:

There's a string with weird characters that I'm trying to fix and when trying HEX replacement sed finds only first three chars.

xxd output of string with problematic characrets:

6965 7261 f480 8488 6e6f 7761 6e61 2031  iera....nowana 1

I'd like to replace this sequence f480 8488 with printable chars, but sed can recognize only first three:

sed 's/\xf4\x80\x84/00/g' | xxd
6965 7261 3030 886e 6f77 616e 6120 3136  iera00.nowana 16

f480 84 was properly replaced with 3030

however

sed 's/\xf4\x80\x84\x88/00/g' | xxd
6965 7261 f480 8488 6e6f 7761 6e61 2031  iera....nowana 1

doesn't find f480 8488

If I break if onto two sed statements sed 's/\xf4\x80/0/g' | sed 's/\x84\x88/0/g'everything works fine

I would understand if it was looking for pairs, but why only three not four characters in sequence?

Body:
Following comment @tripleee and confirmed solution form @the.Legend

Setting LC_ALL=C is a working fix.
It is well documented here.

It forces applications to use the default language for output:

 $ LC_ALL=es_ES man
 ¿Qué página de manual desea?

 $ LC_ALL=C man
 What manual page do you want?


问:
How to return only the updated subdocument inside of array after an update
I have a user model with the following schema

```<code>{
  _id: userId,
  inbox: {
    inbox: [Array of message documents],
    sent: [Array of message documents],
  }
}
</code>```

Is there a way to get only the updated subdocument after an update in mongodb / mongoose ?

The update is good i just want to return the updated subdocument instead of querying the db again

```<code>db.getCollection("users").findOneAndUpdate(
  { "inbox.sent._id": ObjectId("5cea23be8c03c800d43a8376") },
  { "$set": { "inbox.sent.$.inTrash": false } },
  { "inbox.sent.$": 1 } <-- how to return only the subdocument like in a query
);
</code>```

expected output the array at inbox.sent with only the updated doc

```<code>{
  _id: userId,
  inbox: {
    sent: [{ updated doc}]
  }
}
</code>```

答:
You need to apply a callback to the findOneAndUpdate function

e.g:

```<code>db.getCollection("users").findOneAndUpdate(
  { "inbox.sent._id": ObjectId("5cea23be8c03c800d43a8376") },
  { "$set": { "inbox.sent.$.inTrash": false } },
  { "inbox.sent.$": 1 },
  function (err, res) {
    //here you have the res, which will be the affected record
  }
);
</code>```

Body:
I have a user model with the following schema

{
  _id: userId,
  inbox: {
    inbox: [Array of message documents],
    sent: [Array of message documents],
  }
}

Is there a way to get only the updated subdocument after an update in mongodb / mongoose ?

The update is good i just want to return the updated subdocument instead of querying the db again

db.getCollection("users").findOneAndUpdate(
  { "inbox.sent._id": ObjectId("5cea23be8c03c800d43a8376") },
  { "$set": { "inbox.sent.$.inTrash": false } },
  { "inbox.sent.$": 1 } <-- how to return only the subdocument like in a query
);

expected output the array at inbox.sent with only the updated doc

{
  _id: userId,
  inbox: {
    sent: [{ updated doc}]
  }
}

Body:
You need to apply a callback to the findOneAndUpdate function

e.g:

db.getCollection("users").findOneAndUpdate(
  { "inbox.sent._id": ObjectId("5cea23be8c03c800d43a8376") },
  { "$set": { "inbox.sent.$.inTrash": false } },
  { "inbox.sent.$": 1 },
  function (err, res) {
    //here you have the res, which will be the affected record
  }
);


问:
can't render the Data in *ngFor but it already show in console in angular 7
I'm trying to render the data that I get from API to show it in my html page. But, i can't render the data to my html page even though it already show when I'm using console.log()

I already try some of this answer from this topic but it still not solve my problem:

I am getting Data in Console Using Angular but I can't render it in html

Angular - How ngFor works?

this is my body.component.ts:

```<code>import { Component, OnInit } from '@angular/core';
import { TimelineService } from 'src/app/services/timeline.service';

@Component({
  selector: 'app-body-homepage',
  templateUrl: './body.component.html',
  styleUrls: ['./body.component..scss']
})
export class BodyComponent implements OnInit {

  constructor(public timeline: TimelineService) {   }

  ngOnInit() {
    this.getTimeline();
  }

  getTimeline(){
    this.timeline.timeline().subscribe((data)=>{
      let timelines = [];
      let i;

      for (i=0; i < data.timelines.length; i++) {
        let id = data.timelines[i]._id;
        let date = data.timelines[i].date;
        let title = data.timelines[i].title;

        timelines.push({"id": id, "date": date, "title": title})
      }
      console.log("Cek Timelines : ", timelines);
    });
  }

  scrollToElement($element): void {
    console.log($element);
    $element.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});
  }
}

</code>```

this is the response data in console:

```<code>[{
    "_id": "5ce8122d7e55260d3d9dd78a",
    "title": "Kumpul Perdana",
    "body": "Kumpul Perdana MPKMB 56",
    "date": "2019-08-29T17:00:00.000Z",
    "__v": 0
  },
  {
    "_id": "5ce812b27e55260d3d9dd78b",
    "title": "Pembagian Kelompok Besar",
    "body": "Pembagian Kelompok Besar",
    "date": "2019-09-15T17:00:00.000Z",
    "__v": 0
  }
]
</code>```

this is my html code:

```<code><div class="row">
  <div class="col-12 col-md-12 col-lg-12">
    <ul>
      <li *ngFor="let item of timelines">
        {{item.date}}. {{item.title}}
      </li>
    </ul>
  </div>
</div>
</code>```

but when I try to use the data normally without using API like this:

ts:

```<code>items = [{
    "_id": "5ce8122d7e55260d3d9dd78a",
    "title": "Kumpul Perdana",
    "body": "Kumpul Perdana MPKMB 56",
    "date": "2019-08-29T17:00:00.000Z",
    "__v": 0
  },
  {
    "_id": "5ce812b27e55260d3d9dd78b",
    "title": "Pembagian Kelompok Besar",
    "body": "Pembagian Kelompok Besar",
    "date": "2019-09-15T17:00:00.000Z",
    "__v": 0
  }
]
</code>```

html:

```<code><div class="row">
  <div class="col-12 col-md-12 col-lg-12">
    <ul>
      <li *ngFor="let item of items">
        {{item.date}}. {{item.title}}
      </li>
    </ul>
  </div>
</div>
</code>```

it works fine

can someone help me to solve this problem? i feel i miss something to solve it but i can't figure it which the problem is

答:
Within the html you call timelines variable. But you have never declared it as a variable, it is only known within the function.

So, what you need to do is declare it as a variable outside the function:

```<code>timelines = [];
</code>```

Body:
I'm trying to render the data that I get from API to show it in my html page. But, i can't render the data to my html page even though it already show when I'm using console.log()

I already try some of this answer from this topic but it still not solve my problem:

I am getting Data in Console Using Angular but I can't render it in html

Angular - How ngFor works?

this is my body.component.ts:

import { Component, OnInit } from '@angular/core';
import { TimelineService } from 'src/app/services/timeline.service';

@Component({
  selector: 'app-body-homepage',
  templateUrl: './body.component.html',
  styleUrls: ['./body.component..scss']
})
export class BodyComponent implements OnInit {

  constructor(public timeline: TimelineService) {   }

  ngOnInit() {
    this.getTimeline();
  }

  getTimeline(){
    this.timeline.timeline().subscribe((data)=>{
      let timelines = [];
      let i;

      for (i=0; i < data.timelines.length; i++) {
        let id = data.timelines[i]._id;
        let date = data.timelines[i].date;
        let title = data.timelines[i].title;

        timelines.push({"id": id, "date": date, "title": title})
      }
      console.log("Cek Timelines : ", timelines);
    });
  }

  scrollToElement($element): void {
    console.log($element);
    $element.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});
  }
}

this is the response data in console:

[{
    "_id": "5ce8122d7e55260d3d9dd78a",
    "title": "Kumpul Perdana",
    "body": "Kumpul Perdana MPKMB 56",
    "date": "2019-08-29T17:00:00.000Z",
    "__v": 0
  },
  {
    "_id": "5ce812b27e55260d3d9dd78b",
    "title": "Pembagian Kelompok Besar",
    "body": "Pembagian Kelompok Besar",
    "date": "2019-09-15T17:00:00.000Z",
    "__v": 0
  }
]

this is my html code:

        {{item.date}}. {{item.title}}

but when I try to use the data normally without using API like this:

ts:

items = [{
    "_id": "5ce8122d7e55260d3d9dd78a",
    "title": "Kumpul Perdana",
    "body": "Kumpul Perdana MPKMB 56",
    "date": "2019-08-29T17:00:00.000Z",
    "__v": 0
  },
  {
    "_id": "5ce812b27e55260d3d9dd78b",
    "title": "Pembagian Kelompok Besar",
    "body": "Pembagian Kelompok Besar",
    "date": "2019-09-15T17:00:00.000Z",
    "__v": 0
  }
]

html:

        {{item.date}}. {{item.title}}

it works fine

can someone help me to solve this problem? i feel i miss something to solve it but i can't figure it which the problem is

Body:
Within the html you call timelines variable. But you have never declared it as a variable, it is only known within the function.

So, what you need to do is declare it as a variable outside the function:

timelines = [];


问:
I am trying to Return the first node holding the value item or return NULL if none found
I am trying Return the first node holding the value item or return NULL if none found. I have written 2 logic which according to me are the same. But Why I am getting wrong output in one of them.</p>

```<code>//THIS IS GIVING ME THE CORRECT OUTPUT
struct nodeStruct* List_findNode(struct nodeStruct *head, int item){

    struct nodeStruct *temp_node=head;

    while (temp_node!=NULL)
    {
        if (temp_node->item == item)
        {
            return temp_node;

        }
        temp_node=temp_node->next;

    }
    return NULL;
}

//BUT ACCORDING ME THIS IS THE SAME LOGIC BUT IT'S GIVING WRONG OUTPUT.
struct nodeStruct* List_findNode(struct nodeStruct *head, int item){

    struct nodeStruct *temp_node=head;

    while (temp_node!=NULL)
    {
        if (temp_node->item != item)
        {

            temp_node=temp_node->next;

        }
        return temp_node;

    }
    return NULL;
}
</code>```

答:
In the later case you need a continue or your function will return always

```<code>while (temp_node!=NULL)
{
    if (temp_node->item != item)
    {

        temp_node=temp_node->next;
        continue; // here
    }
    return temp_node;
}
</code>```

That said you could also use a for loop:

```<code>struct nodeStruct* List_findNode(struct nodeStruct *head, int item) {
    for (struct nodeStruct *temp_node = head;
         temp_node != NULL;
         temp_node = temp_node->next) {
        if (temp_node->item == item) {
            return temp_node;
        }
    }
    return NULL;
}
</code>```

Body:
I am trying Return the first node holding the value item or return NULL if none found. I have written 2 logic which according to me are the same. But Why I am getting wrong output in one of them.

//THIS IS GIVING ME THE CORRECT OUTPUT
struct nodeStruct* List_findNode(struct nodeStruct *head, int item){

    struct nodeStruct *temp_node=head;

    while (temp_node!=NULL)
    {
        if (temp_node->item == item)
        {
            return temp_node;

        }
        temp_node=temp_node->next;

    }
    return NULL;
}

//BUT ACCORDING ME THIS IS THE SAME LOGIC BUT IT'S GIVING WRONG OUTPUT.
struct nodeStruct* List_findNode(struct nodeStruct *head, int item){

    struct nodeStruct *temp_node=head;

    while (temp_node!=NULL)
    {
        if (temp_node->item != item)
        {

            temp_node=temp_node->next;

        }
        return temp_node;

    }
    return NULL;
}

Body:
In the later case you need a continue or your function will return always

while (temp_node!=NULL)
{
    if (temp_node->item != item)
    {

        temp_node=temp_node->next;
        continue; // here
    }
    return temp_node;
}

That said you could also use a for loop:

struct nodeStruct* List_findNode(struct nodeStruct *head, int item) {
    for (struct nodeStruct *temp_node = head;
         temp_node != NULL;
         temp_node = temp_node->next) {
        if (temp_node->item == item) {
            return temp_node;
        }
    }
    return NULL;
}


问:
Setting transparency color on sprite bitmap makes my non-sprite quads vanish!
Writing a simple game to help learn OpenGL.  In the current version, my render method draws some geometry quads with code defined colors and then renders some sprites.  So far, everything is normal and working as intended. My sprites have as their background the color Auqua which I've been meaning to set to transparent, but haven't yet.  So for the moment the game looks normal except for the fact that all sprites appear bounded by the color blue.  I'm at the point where I want the blue to vanish and instead be transparent, so I modify my OnLoad method to be:

```<code>...
Bitmap bitmap = new Bitmap("RockTexture.bmp"); // existing line
bitmap.MakeTransparent(Color.Aqua);  // new line
...
</code>```

However, now when I run my game all the geometry quads vanish from the screen!  My sprites do remain and appear appropriately transparent.

I'm not sure why this is happening.  Here is my render method:

```<code>    protected override void OnRenderFrame(FrameEventArgs e)
    {
        base.OnRenderFrame(e);

        GL.Clear(ClearBufferMask.ColorBufferBit);

        GL.Begin(BeginMode.Quads);
        Color prevColor = default(Color);

        foreach (var quad in _view.GeomitryList)
        {

            if (prevColor != quad.Color)
            {
                GL.Color4(quad.Color);
                prevColor = quad.Color;
            }

            GL.Vertex2(quad.UpperLeftBound.X, quad.UpperLeftBound.Y);
            GL.Vertex2(quad.LowerRightBound.X, quad.UpperLeftBound.Y);
            GL.Vertex2(quad.LowerRightBound.X, quad.LowerRightBound.Y);
            GL.Vertex2(quad.UpperLeftBound.X, quad.LowerRightBound.Y);

        }

        GL.Color4(_unitColor); // reset color multiplier to not scew textures
        prevColor = _unitColor;

        GL.BindTexture(TextureTarget.Texture2D, _rockTextureId);

        foreach (var sprite in _view.SpriteList)
        {
            float ulX = sprite.UpperLeftBound.X;
            float ulY = sprite.UpperLeftBound.Y;
            float lrX = sprite.LowerRightBound.X;
            float lrY = sprite.LowerRightBound.Y;

            GL.TexCoord2(0, 0); GL.Vertex2(ulX, ulY);
            GL.TexCoord2(1, 0); GL.Vertex2(lrX, ulY);
            GL.TexCoord2(1, 1); GL.Vertex2(lrX, lrY);
            GL.TexCoord2(0, 1); GL.Vertex2(ulX, lrY);
        }

        RenderDashboard(ref prevColor);

        GL.End();

        GL.Flush();
        SwapBuffers();
    }
</code>```

答:
Supposing you're setting the alpha channel in your MakeTransparent function, you also need to enable blending:

protected override void OnRenderFrame(FrameEventArgs e)
    {
        base.OnRenderFrame(e);

```<code>    GL.Clear(ClearBufferMask.ColorBufferBit);

    GL.Begin(BeginMode.Quads);
    Color prevColor = default(Color);

    foreach (var quad in _view.GeomitryList)
    {

        if (prevColor != quad.Color)
        {
            GL.Color4(quad.Color);
            prevColor = quad.Color;
        }

        GL.Vertex2(quad.UpperLeftBound.X, quad.UpperLeftBound.Y);
        GL.Vertex2(quad.LowerRightBound.X, quad.UpperLeftBound.Y);
        GL.Vertex2(quad.LowerRightBound.X, quad.LowerRightBound.Y);
        GL.Vertex2(quad.UpperLeftBound.X, quad.LowerRightBound.Y);

    }
</code>```

vvv

```<code>    GL.Enable(GL_BLEND);
</code>```

^^^

```<code>    GL.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    GL.Color4(_unitColor); // reset color multiplier to not scew textures
    prevColor = _unitColor;

    GL.BindTexture(TextureTarget.Texture2D, _rockTextureId);

    foreach (var sprite in _view.SpriteList)
    {
        float ulX = sprite.UpperLeftBound.X;
        float ulY = sprite.UpperLeftBound.Y;
        float lrX = sprite.LowerRightBound.X;
        float lrY = sprite.LowerRightBound.Y;

        GL.TexCoord2(0, 0); GL.Vertex2(ulX, ulY);
        GL.TexCoord2(1, 0); GL.Vertex2(lrX, ulY);
        GL.TexCoord2(1, 1); GL.Vertex2(lrX, lrY);
        GL.TexCoord2(0, 1); GL.Vertex2(ulX, lrY);
    }

    GL.End(); // I think this should go here.

    GL.Disable(GL_BLEND); // enable and disable on a as-needed base

    RenderDashboard(ref prevColor);

    GL.Flush();
    SwapBuffers();
</code>```

BTW: You're using immediate mode calls there (glBegin(...), glVertex(...), glEnd()), you should abandon them and use Vertex Arrays and Vertex Buffer Objects instead. Immediate mode is deprecated, no longer available in OpenGL-3 and later outside the compatibility profile.

ContentLicense: CC BY-SA 3.0

Body:
Writing a simple game to help learn OpenGL.  In the current version, my render method draws some geometry quads with code defined colors and then renders some sprites.  So far, everything is normal and working as intended. My sprites have as their background the color Auqua which I've been meaning to set to transparent, but haven't yet.  So for the moment the game looks normal except for the fact that all sprites appear bounded by the color blue.  I'm at the point where I want the blue to vanish and instead be transparent, so I modify my OnLoad method to be:

...
Bitmap bitmap = new Bitmap("RockTexture.bmp"); // existing line
bitmap.MakeTransparent(Color.Aqua);  // new line
...

However, now when I run my game all the geometry quads vanish from the screen!  My sprites do remain and appear appropriately transparent.

I'm not sure why this is happening.  Here is my render method:

    protected override void OnRenderFrame(FrameEventArgs e)
    {
        base.OnRenderFrame(e);

        GL.Clear(ClearBufferMask.ColorBufferBit);

        GL.Begin(BeginMode.Quads);
        Color prevColor = default(Color);

        foreach (var quad in _view.GeomitryList)
        {

            if (prevColor != quad.Color)
            {
                GL.Color4(quad.Color);
                prevColor = quad.Color;
            }

            GL.Vertex2(quad.UpperLeftBound.X, quad.UpperLeftBound.Y);
            GL.Vertex2(quad.LowerRightBound.X, quad.UpperLeftBound.Y);
            GL.Vertex2(quad.LowerRightBound.X, quad.LowerRightBound.Y);
            GL.Vertex2(quad.UpperLeftBound.X, quad.LowerRightBound.Y);

        }

        GL.Color4(_unitColor); // reset color multiplier to not scew textures
        prevColor = _unitColor;

        GL.BindTexture(TextureTarget.Texture2D, _rockTextureId);

        foreach (var sprite in _view.SpriteList)
        {
            float ulX = sprite.UpperLeftBound.X;
            float ulY = sprite.UpperLeftBound.Y;
            float lrX = sprite.LowerRightBound.X;
            float lrY = sprite.LowerRightBound.Y;

            GL.TexCoord2(0, 0); GL.Vertex2(ulX, ulY);
            GL.TexCoord2(1, 0); GL.Vertex2(lrX, ulY);
            GL.TexCoord2(1, 1); GL.Vertex2(lrX, lrY);
            GL.TexCoord2(0, 1); GL.Vertex2(ulX, lrY);
        }

        RenderDashboard(ref prevColor);

        GL.End();

        GL.Flush();
        SwapBuffers();
    }

Body:
Supposing you're setting the alpha channel in your MakeTransparent function, you also need to enable blending:

protected override void OnRenderFrame(FrameEventArgs e)
    {
        base.OnRenderFrame(e);

    GL.Clear(ClearBufferMask.ColorBufferBit);

    GL.Begin(BeginMode.Quads);
    Color prevColor = default(Color);

    foreach (var quad in _view.GeomitryList)
    {

        if (prevColor != quad.Color)
        {
            GL.Color4(quad.Color);
            prevColor = quad.Color;
        }

        GL.Vertex2(quad.UpperLeftBound.X, quad.UpperLeftBound.Y);
        GL.Vertex2(quad.LowerRightBound.X, quad.UpperLeftBound.Y);
        GL.Vertex2(quad.LowerRightBound.X, quad.LowerRightBound.Y);
        GL.Vertex2(quad.UpperLeftBound.X, quad.LowerRightBound.Y);

    }

vvv

    GL.Enable(GL_BLEND);

^^^

    GL.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    GL.Color4(_unitColor); // reset color multiplier to not scew textures
    prevColor = _unitColor;

    GL.BindTexture(TextureTarget.Texture2D, _rockTextureId);

    foreach (var sprite in _view.SpriteList)
    {
        float ulX = sprite.UpperLeftBound.X;
        float ulY = sprite.UpperLeftBound.Y;
        float lrX = sprite.LowerRightBound.X;
        float lrY = sprite.LowerRightBound.Y;

        GL.TexCoord2(0, 0); GL.Vertex2(ulX, ulY);
        GL.TexCoord2(1, 0); GL.Vertex2(lrX, ulY);
        GL.TexCoord2(1, 1); GL.Vertex2(lrX, lrY);
        GL.TexCoord2(0, 1); GL.Vertex2(ulX, lrY);
    }

    GL.End(); // I think this should go here.

    GL.Disable(GL_BLEND); // enable and disable on a as-needed base

    RenderDashboard(ref prevColor);

    GL.Flush();
    SwapBuffers();

BTW: You're using immediate mode calls there (glBegin(...), glVertex(...), glEnd()), you should abandon them and use Vertex Arrays and Vertex Buffer Objects instead. Immediate mode is deprecated, no longer available in OpenGL-3 and later outside the compatibility profile.


问:
updateOne command in mongoose 5.5.11 every time I execute, I get response { "n": 0, "nModified": 0, "ok": 1 } ! what's going wrong?
I 'm trying to update a MongoDB document by mongoose model.updateOne command, But every time I execute the command, it responds {ok:1, n:0, nModified:0}

Mongoose model :

```<code>var mongoose = require('mongoose');
var measurepropsSchema = new mongoose.Schema({
  measureTitle: {
    type: String,
    unique: true,
    required: true
  },
  measureDescription: {
      type:String,
      required:false
  },
  measureSymbol: {
      type: String,
      required:false,
  }
});
var collectionName = 'measureParams'
mongoose.model('Mp', measurepropsSchema, collectionName);
</code>```

router :

```<code>routerm.put('/editbyid/:id', ctrlMeasProps.edit);
</code>```

Route configuration :

```<code>var routesMea = require('./api/routes/measures');
app.use('/mea', routesMea);
</code>```

and finally edit function :

```<code>var Mp = mongoose.model('Mp');
module.exports.edit = function (req, res) {
    var measureParams = new Mp();
    console.log(req.body);
    try{
    measureParams.updateOne(
        { _id: req.params.id },
        {
            measureTitle: req.body.title,
            measureDescription: req.body.description,
            measureSymbol: req.body.symbol
        },
        (err, docu) => {
            console.log(measureParams);
            console.log(err);
            console.log('fin');
            if (err)
                return res.status(500).send(err);
            return res.send(docu);
        }
    )
    }catch(e){
        console.log(e);
    }
};
</code>```

I requested the below link,

```<code>http://localhost:3000/mea/editbyid/5ce8e8555647bf5fb1b51803
</code>```

requested body is a JSON object like this :

```<code>{
    "title": "sth",
    "description": "It`s sth",
    "symbol": "$0"
}
</code>```

and it responds :

```<code>{
    "n": 0,
    "nModified": 0,
    "ok": 1
}
</code>```

Here is collection "measureParams" data:

```<code>{ "_id" : ObjectId("5ce8e8375647bf5fb1b51802"), "measureTitle" : "AAAA", "measureDescription" : "It`s AAAA", "measureSymbol" : "%$" }
{ "_id" : ObjectId("5ce8e8555647bf5fb1b51803"), "measureTitle" : "BBBB", "measureDescription" : "It`s BBBB", "measureSymbol" : "@@" }
{ "_id" : ObjectId("5ce8f3b96bcf65fade7c5bcf"), "measureTitle" : "CCCC", "measureDescription" : "It`s CCCC", "measureSymbol" : "$$" }
{ "_id" : ObjectId("5ce90bb3b78b6fbd4b9781ed"), "measureTitle" : "DDDD", "measureDescription" : "It`s DDDD", "measureSymbol" : "#$" }
{ "_id" : ObjectId("5ce90ed9de934a056c00a383"), "measureSymbol" : "Or", "measureDescription" : "It`s EEEE", "measureTitle" : "EEEE", "__v" : 0 }
{ "_id" : ObjectId("5ce912bc5a52000e009b6f2e"), "measureSymbol" : "Ol", "measureDescription" : "It`s FFFF", "measureTitle" : "FFFF", "__v" : 0 }
{ "_id" : ObjectId("5ce937907d656012902702cb"), "measureTitle" : "GGGG", "measureDescription" : "It`s GGGG", "measureSymbol" : "QS", "__v" : 0 }
</code>```

It should update collection by ObjectId 5ce8e8555647bf5fb1b51803 with new values mentioned in json body, but it does't.
I don't know what is the problem?
Do you have any idea?

答:
updateOne works with model name , try to update your edit function and schema file :

update last line in schema file to this :

```<code> var Mp = module.exports = mongoose.model('Mp', measurepropsSchema, collectionName);
</code>```

And Edit function should look like this:

```<code>var Mp = require('/path/to/Mp/schema/file');
module.exports.edit = function (req, res) {
    console.log(req.body);
    try{
    Mp.updateOne(
        { _id: req.params.id },
        {
            measureTitle: req.body.title,
            measureDescription: req.body.description,
            measureSymbol: req.body.symbol
        },
        (err, docu) => {
           console.log(err);
           console.log('fin');
           if (err)
               return res.status(500).send(err);
           return res.send(docu);
        }
     )
    }catch(e){
       console.log(e);
   }
};
</code>```

Body:
I 'm trying to update a MongoDB document by mongoose model.updateOne command, But every time I execute the command, it responds {ok:1, n:0, nModified:0}

Mongoose model :

var mongoose = require('mongoose');
var measurepropsSchema = new mongoose.Schema({
  measureTitle: {
    type: String,
    unique: true,
    required: true
  },
  measureDescription: {
      type:String,
      required:false
  },
  measureSymbol: {
      type: String,
      required:false,
  }
});
var collectionName = 'measureParams'
mongoose.model('Mp', measurepropsSchema, collectionName);

router :

routerm.put('/editbyid/:id', ctrlMeasProps.edit);

Route configuration :

var routesMea = require('./api/routes/measures');
app.use('/mea', routesMea);

and finally edit function :

var Mp = mongoose.model('Mp');
module.exports.edit = function (req, res) {
    var measureParams = new Mp();
    console.log(req.body);
    try{
    measureParams.updateOne(
        { _id: req.params.id },
        {
            measureTitle: req.body.title,
            measureDescription: req.body.description,
            measureSymbol: req.body.symbol
        },
        (err, docu) => {
            console.log(measureParams);
            console.log(err);
            console.log('fin');
            if (err)
                return res.status(500).send(err);
            return res.send(docu);
        }
    )
    }catch(e){
        console.log(e);
    }
};

I requested the below link,

http://localhost:3000/mea/editbyid/5ce8e8555647bf5fb1b51803

requested body is a JSON object like this :

{
    "title": "sth",
    "description": "It`s sth",
    "symbol": "$0"
}

and it responds :

{
    "n": 0,
    "nModified": 0,
    "ok": 1
}

Here is collection "measureParams" data:

{ "_id" : ObjectId("5ce8e8375647bf5fb1b51802"), "measureTitle" : "AAAA", "measureDescription" : "It`s AAAA", "measureSymbol" : "%$" }
{ "_id" : ObjectId("5ce8e8555647bf5fb1b51803"), "measureTitle" : "BBBB", "measureDescription" : "It`s BBBB", "measureSymbol" : "@@" }
{ "_id" : ObjectId("5ce8f3b96bcf65fade7c5bcf"), "measureTitle" : "CCCC", "measureDescription" : "It`s CCCC", "measureSymbol" : "$$" }
{ "_id" : ObjectId("5ce90bb3b78b6fbd4b9781ed"), "measureTitle" : "DDDD", "measureDescription" : "It`s DDDD", "measureSymbol" : "#$" }
{ "_id" : ObjectId("5ce90ed9de934a056c00a383"), "measureSymbol" : "Or", "measureDescription" : "It`s EEEE", "measureTitle" : "EEEE", "__v" : 0 }
{ "_id" : ObjectId("5ce912bc5a52000e009b6f2e"), "measureSymbol" : "Ol", "measureDescription" : "It`s FFFF", "measureTitle" : "FFFF", "__v" : 0 }
{ "_id" : ObjectId("5ce937907d656012902702cb"), "measureTitle" : "GGGG", "measureDescription" : "It`s GGGG", "measureSymbol" : "QS", "__v" : 0 }

It should update collection by ObjectId 5ce8e8555647bf5fb1b51803 with new values mentioned in json body, but it does't.
I don't know what is the problem?
Do you have any idea?

Body:
updateOne works with model name , try to update your edit function and schema file :

update last line in schema file to this :

 var Mp = module.exports = mongoose.model('Mp', measurepropsSchema, collectionName);

And Edit function should look like this:

var Mp = require('/path/to/Mp/schema/file');
module.exports.edit = function (req, res) {
    console.log(req.body);
    try{
    Mp.updateOne(
        { _id: req.params.id },
        {
            measureTitle: req.body.title,
            measureDescription: req.body.description,
            measureSymbol: req.body.symbol
        },
        (err, docu) => {
           console.log(err);
           console.log('fin');
           if (err)
               return res.status(500).send(err);
           return res.send(docu);
        }
     )
    }catch(e){
       console.log(e);
   }
};


问:
Dockerizing Django application: ModuleNotFoundError: No module named 'X"
I've been trying to follow this guide to Dockerize a project:

Deploy and Run Django in Dokcer Container

This is the base file structure:

```<code>WFMBCM
|-WFMBCM
| |-__init__.py
| |-__pycache__
| |-setting.py
| |-url.py
| |-wsgi.py
|
|-WFMBCM_App
|-WFMBCM_db
|-manage.py
|-Dockerfile
|-requirements.txt
|-runWFMBCM.sh
</code>```

Dockerfile:

```<code>FROM python:3.7
ADD WFMBCM /usr/src/app
ADD WFMBCM_App /usr/src/app
ADD WFMBCM_db /usr/src/app
ADD manage.py /usr/src/app
WORKDIR /usr/src/app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
EXPOSE 8000
CMD exec gunicorn wfmbcm.wsgi:application --bind 0.0.0.0:8000 --workers 3
</code>```

requirements.txt:

```<code>Django==2.2.1
gunicorn==19.9.0
</code>```

runWFMBCM.sh:

```<code>cd /home/admin/WFMBCM
echo -e "\033[0;34mGo to WFMBCM directory.\n \033[0;37m"
echo -e "\033[0;34mRemove old WFMBCM container\n \033[0;37m"
docker rm -v wfmbcm_container
echo -e "\033[0;34m\nBuild WFMBCM Docker image.\n \033[0;37m"
sudo docker build -t wfmbcm .
echo -e "\033[0;34m\nRun WFMBCM Docker image.\n \033[0;37m"
sudo docker run --name wfmbcm_container -p 8000:8000 -i -t wfmbcm
echo -e "\033[0;34m\n\nWFMBCM run-script ended!.\n \033[0;37m"
</code>```

When I run runWFMBCM.sh I get the following output:

```<code>Go to WFMBCM directory.

Remove old WFMBCM container

Error response from daemon: No such container: wfmbcm_container

Build WFMBCM Docker image.

Sending build context to Docker daemon  265.2kB
Step 1/10 : FROM python:3.7
 ---> cc971a68c3e4
Step 2/10 : ADD WFMBCM /usr/src/app
 ---> Using cache
 ---> 302346d017e2
Step 3/10 : ADD WFMBCM_App /usr/src/app
 ---> Using cache
 ---> 18bc8eb69946
Step 4/10 : ADD WFMBCM_db /usr/src/app
 ---> Using cache
 ---> 0835393b22dc
Step 5/10 : ADD manage.py /usr/src/app
 ---> Using cache
 ---> 3ef5477e4b26
Step 6/10 : WORKDIR /usr/src/app
 ---> Using cache
 ---> 2edb019a8257
Step 7/10 : COPY requirements.txt ./
 ---> Using cache
 ---> df3ac922b7a0
Step 8/10 : RUN pip install --no-cache-dir -r requirements.txt
 ---> Using cache
 ---> ba6cf54e7dcc
Step 9/10 : EXPOSE 8000
 ---> Using cache
 ---> 94f3f4fb38c0
Step 10/10 : CMD exec gunicorn wfmbcm.wsgi:application --bind 0.0.0.0:8000 --workers 3
 ---> Using cache
 ---> db6cf2149949
Successfully built db6cf2149949
Successfully tagged wfmbcm:latest

Run WFMBCM Docker image.

[2019-05-26 09:59:36 +0000] [1] [INFO] Starting gunicorn 19.9.0
[2019-05-26 09:59:36 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1)
[2019-05-26 09:59:36 +0000] [1] [INFO] Using worker: sync
[2019-05-26 09:59:36 +0000] [9] [INFO] Booting worker with pid: 9
[2019-05-26 09:59:36 +0000] [10] [INFO] Booting worker with pid: 10
[2019-05-26 09:59:36 +0000] [9] [ERROR] Exception in worker process
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
    worker.init_process()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_process
    self.load_wsgi()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
    return self.load_wsgiapp()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app
    __import__(module)
ModuleNotFoundError: No module named 'wfmbcm'
[2019-05-26 09:59:36 +0000] [9] [INFO] Worker exiting (pid: 9)
[2019-05-26 09:59:36 +0000] [11] [INFO] Booting worker with pid: 11
[2019-05-26 09:59:36 +0000] [10] [ERROR] Exception in worker process
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
    worker.init_process()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_process
    self.load_wsgi()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
    return self.load_wsgiapp()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app
    __import__(module)
ModuleNotFoundError: No module named 'wfmbcm'
[2019-05-26 09:59:36 +0000] [10] [INFO] Worker exiting (pid: 10)
[2019-05-26 09:59:36 +0000] [11] [ERROR] Exception in worker process
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
    worker.init_process()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_process
    self.load_wsgi()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
    return self.load_wsgiapp()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app
    __import__(module)
ModuleNotFoundError: No module named 'wfmbcm'
[2019-05-26 09:59:36 +0000] [11] [INFO] Worker exiting (pid: 11)
[2019-05-26 09:59:37 +0000] [1] [INFO] Shutting down: Master
[2019-05-26 09:59:37 +0000] [1] [INFO] Reason: Worker failed to boot.

WFMBCM run-script ended!.
</code>```

Why can't it find wfmbcm module? I've been staring crazy and googling without success and looking at different stack overflow questions.

答:
Changing my DockerFile to this solved my issue:</p>

```<code>FROM python:3.7
ADD WFMBCM /usr/src/app/WFMBCM
ADD WFMBCM_App /usr/src/app/WFMBCM_App
ADD WFMBCM_db /usr/src/app/WFMBCM_db
ADD manage.py /usr/src/app
WORKDIR /usr/src/app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
EXPOSE 8000
CMD manage.py migrate
CMD exec gunicorn WFMBCM.wsgi:application --bind 0.0.0.0:8000 --workers 10
</code>```

Body:
I've been trying to follow this guide to Dockerize a project:

Deploy and Run Django in Dokcer Container

This is the base file structure:

WFMBCM
|-WFMBCM
| |-__init__.py
| |-__pycache__
| |-setting.py
| |-url.py
| |-wsgi.py
|
|-WFMBCM_App
|-WFMBCM_db
|-manage.py
|-Dockerfile
|-requirements.txt
|-runWFMBCM.sh

Dockerfile:

FROM python:3.7
ADD WFMBCM /usr/src/app
ADD WFMBCM_App /usr/src/app
ADD WFMBCM_db /usr/src/app
ADD manage.py /usr/src/app
WORKDIR /usr/src/app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
EXPOSE 8000
CMD exec gunicorn wfmbcm.wsgi:application --bind 0.0.0.0:8000 --workers 3

requirements.txt:

Django==2.2.1
gunicorn==19.9.0

runWFMBCM.sh:

cd /home/admin/WFMBCM
echo -e "\033[0;34mGo to WFMBCM directory.\n \033[0;37m"
echo -e "\033[0;34mRemove old WFMBCM container\n \033[0;37m"
docker rm -v wfmbcm_container
echo -e "\033[0;34m\nBuild WFMBCM Docker image.\n \033[0;37m"
sudo docker build -t wfmbcm .
echo -e "\033[0;34m\nRun WFMBCM Docker image.\n \033[0;37m"
sudo docker run --name wfmbcm_container -p 8000:8000 -i -t wfmbcm
echo -e "\033[0;34m\n\nWFMBCM run-script ended!.\n \033[0;37m"

When I run runWFMBCM.sh I get the following output:

Go to WFMBCM directory.

Remove old WFMBCM container

Error response from daemon: No such container: wfmbcm_container

Build WFMBCM Docker image.

Sending build context to Docker daemon  265.2kB
Step 1/10 : FROM python:3.7
 ---> cc971a68c3e4
Step 2/10 : ADD WFMBCM /usr/src/app
 ---> Using cache
 ---> 302346d017e2
Step 3/10 : ADD WFMBCM_App /usr/src/app
 ---> Using cache
 ---> 18bc8eb69946
Step 4/10 : ADD WFMBCM_db /usr/src/app
 ---> Using cache
 ---> 0835393b22dc
Step 5/10 : ADD manage.py /usr/src/app
 ---> Using cache
 ---> 3ef5477e4b26
Step 6/10 : WORKDIR /usr/src/app
 ---> Using cache
 ---> 2edb019a8257
Step 7/10 : COPY requirements.txt ./
 ---> Using cache
 ---> df3ac922b7a0
Step 8/10 : RUN pip install --no-cache-dir -r requirements.txt
 ---> Using cache
 ---> ba6cf54e7dcc
Step 9/10 : EXPOSE 8000
 ---> Using cache
 ---> 94f3f4fb38c0
Step 10/10 : CMD exec gunicorn wfmbcm.wsgi:application --bind 0.0.0.0:8000 --workers 3
 ---> Using cache
 ---> db6cf2149949
Successfully built db6cf2149949
Successfully tagged wfmbcm:latest

Run WFMBCM Docker image.

[2019-05-26 09:59:36 +0000] [1] [INFO] Starting gunicorn 19.9.0
[2019-05-26 09:59:36 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1)
[2019-05-26 09:59:36 +0000] [1] [INFO] Using worker: sync
[2019-05-26 09:59:36 +0000] [9] [INFO] Booting worker with pid: 9
[2019-05-26 09:59:36 +0000] [10] [INFO] Booting worker with pid: 10
[2019-05-26 09:59:36 +0000] [9] [ERROR] Exception in worker process
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
    worker.init_process()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_process
    self.load_wsgi()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
    return self.load_wsgiapp()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app
    __import__(module)
ModuleNotFoundError: No module named 'wfmbcm'
[2019-05-26 09:59:36 +0000] [9] [INFO] Worker exiting (pid: 9)
[2019-05-26 09:59:36 +0000] [11] [INFO] Booting worker with pid: 11
[2019-05-26 09:59:36 +0000] [10] [ERROR] Exception in worker process
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
    worker.init_process()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_process
    self.load_wsgi()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
    return self.load_wsgiapp()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app
    __import__(module)
ModuleNotFoundError: No module named 'wfmbcm'
[2019-05-26 09:59:36 +0000] [10] [INFO] Worker exiting (pid: 10)
[2019-05-26 09:59:36 +0000] [11] [ERROR] Exception in worker process
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
    worker.init_process()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_process
    self.load_wsgi()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
    return self.load_wsgiapp()
  File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app
    __import__(module)
ModuleNotFoundError: No module named 'wfmbcm'
[2019-05-26 09:59:36 +0000] [11] [INFO] Worker exiting (pid: 11)
[2019-05-26 09:59:37 +0000] [1] [INFO] Shutting down: Master
[2019-05-26 09:59:37 +0000] [1] [INFO] Reason: Worker failed to boot.

WFMBCM run-script ended!.

Why can't it find wfmbcm module? I've been staring crazy and googling without success and looking at different stack overflow questions.

Body:
Changing my DockerFile to this solved my issue:

FROM python:3.7
ADD WFMBCM /usr/src/app/WFMBCM
ADD WFMBCM_App /usr/src/app/WFMBCM_App
ADD WFMBCM_db /usr/src/app/WFMBCM_db
ADD manage.py /usr/src/app
WORKDIR /usr/src/app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
EXPOSE 8000
CMD manage.py migrate
CMD exec gunicorn WFMBCM.wsgi:application --bind 0.0.0.0:8000 --workers 10


问:
Sending Mail with Sendmail Driver not Working and No Errors Laravel 5.5
I'm trying to send emails with sendmail driver but it isn't working and I got no errors.

My .env file:

```<code>MAIL_DRIVER=sendmail
MAIL_HOST=
MAIL_PORT=587
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
</code>```

My mail.php file:

```<code><?php

return [

    /*
    |--------------------------------------------------------------------------
    | Mail Driver
    |--------------------------------------------------------------------------
    |
    | Laravel supports both SMTP and PHP's "mail" function as drivers for the
    | sending of e-mail. You may specify which one you're using throughout
    | your application here. By default, Laravel is setup for SMTP mail.
    |
    | Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses",
    |            "sparkpost", "log", "array"
    |
    */

    'driver' => env('MAIL_DRIVER', 'sendmail'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Address
    |--------------------------------------------------------------------------
    |
    | Here you may provide the host address of the SMTP server used by your
    | applications. A default option is provided that is compatible with
    | the Mailgun mail service which will provide reliable deliveries.
    |
    */

    'host' => env('MAIL_HOST', ''),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Port
    |--------------------------------------------------------------------------
    |
    | This is the SMTP port used by your application to deliver e-mails to
    | users of the application. Like the host we have set this value to
    | stay compatible with the Mailgun e-mail application by default.
    |
    */

    'port' => env('MAIL_PORT', 587),

    /*
    |--------------------------------------------------------------------------
    | Global "From" Address
    |--------------------------------------------------------------------------
    |
    | You may wish for all e-mails sent by your application to be sent from
    | the same address. Here, you may specify a name and address that is
    | used globally for all e-mails that are sent by your application.
    |
    */

    'from' => [
        'address' => env('MAIL_FROM_ADDRESS', 'no-reply@domainexample.com'),
        'name' => env('MAIL_FROM_NAME', 'INSP Virtual'),
    ],

    /*
    |--------------------------------------------------------------------------
    | E-Mail Encryption Protocol
    |--------------------------------------------------------------------------
    |
    | Here you may specify the encryption protocol that should be used when
    | the application send e-mail messages. A sensible default using the
    | transport layer security protocol should provide great security.
    |
    */

    'encryption' => env('MAIL_ENCRYPTION', 'tls'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Server Username
    |--------------------------------------------------------------------------
    |
    | If your SMTP server requires a username for authentication, you should
    | set it here. This will get used to authenticate with your server on
    | connection. You may also set the "password" value below this one.
    |
    */

    'username' => env('MAIL_USERNAME', null),

    'password' => env('MAIL_PASSWORD', null),

    /*
    |--------------------------------------------------------------------------
    | Sendmail System Path
    |--------------------------------------------------------------------------
    |
    | When using the "sendmail" driver to send e-mails, we will need to know
    | the path to where Sendmail lives on this server. A default path has
    | been provided here, which will work well on most of your systems.
    |
    */

    'sendmail' => '/usr/sbin/sendmail -bs',

    /*
    |--------------------------------------------------------------------------
    | Markdown Mail Settings
    |--------------------------------------------------------------------------
    |
    | If you are using Markdown based email rendering, you may configure your
    | theme and component paths here, allowing you to customize the design
    | of the emails. Or, you may simply stick with the Laravel defaults!
    |
    */

    'markdown' => [
        'theme' => 'default',

        'paths' => [
            resource_path('views/vendor/mail'),
        ],
    ],

];
</code>```

Since I got no errors, even in laravel.log file I don't know even where to start checking, I have checked for the correct sendmail path though, and it was correct, what am I missing?

I also read that you have to change some things in /etc/hosts I changed it a bit adding "domainexample.com":

```<code>127.0.0.1   domainexample.com localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
</code>```

Is this last thing correct?

答:
MAIL_DRIVER=sendmail
MAIL_HOST=
MAIL_PORT=587
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
```

Fill all the details as provided by the mailing services.
if not have you tried using mailtrap and see if you can send a message. Mailtrap can be useful for development.

Documentation of Laravel for mail gives a clear view of what you should be doing.

Body:
I'm trying to send emails with sendmail driver but it isn't working and I got no errors.

My .env file:

MAIL_DRIVER=sendmail
MAIL_HOST=
MAIL_PORT=587
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

My mail.php file:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Mail Driver
    |--------------------------------------------------------------------------
    |
    | Laravel supports both SMTP and PHP's "mail" function as drivers for the
    | sending of e-mail. You may specify which one you're using throughout
    | your application here. By default, Laravel is setup for SMTP mail.
    |
    | Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses",
    |            "sparkpost", "log", "array"
    |
    */

    'driver' => env('MAIL_DRIVER', 'sendmail'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Address
    |--------------------------------------------------------------------------
    |
    | Here you may provide the host address of the SMTP server used by your
    | applications. A default option is provided that is compatible with
    | the Mailgun mail service which will provide reliable deliveries.
    |
    */

    'host' => env('MAIL_HOST', ''),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Port
    |--------------------------------------------------------------------------
    |
    | This is the SMTP port used by your application to deliver e-mails to
    | users of the application. Like the host we have set this value to
    | stay compatible with the Mailgun e-mail application by default.
    |
    */

    'port' => env('MAIL_PORT', 587),

    /*
    |--------------------------------------------------------------------------
    | Global "From" Address
    |--------------------------------------------------------------------------
    |
    | You may wish for all e-mails sent by your application to be sent from
    | the same address. Here, you may specify a name and address that is
    | used globally for all e-mails that are sent by your application.
    |
    */

    'from' => [
        'address' => env('MAIL_FROM_ADDRESS', 'no-reply@domainexample.com'),
        'name' => env('MAIL_FROM_NAME', 'INSP Virtual'),
    ],

    /*
    |--------------------------------------------------------------------------
    | E-Mail Encryption Protocol
    |--------------------------------------------------------------------------
    |
    | Here you may specify the encryption protocol that should be used when
    | the application send e-mail messages. A sensible default using the
    | transport layer security protocol should provide great security.
    |
    */

    'encryption' => env('MAIL_ENCRYPTION', 'tls'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Server Username
    |--------------------------------------------------------------------------
    |
    | If your SMTP server requires a username for authentication, you should
    | set it here. This will get used to authenticate with your server on
    | connection. You may also set the "password" value below this one.
    |
    */

    'username' => env('MAIL_USERNAME', null),

    'password' => env('MAIL_PASSWORD', null),

    /*
    |--------------------------------------------------------------------------
    | Sendmail System Path
    |--------------------------------------------------------------------------
    |
    | When using the "sendmail" driver to send e-mails, we will need to know
    | the path to where Sendmail lives on this server. A default path has
    | been provided here, which will work well on most of your systems.
    |
    */

    'sendmail' => '/usr/sbin/sendmail -bs',

    /*
    |--------------------------------------------------------------------------
    | Markdown Mail Settings
    |--------------------------------------------------------------------------
    |
    | If you are using Markdown based email rendering, you may configure your
    | theme and component paths here, allowing you to customize the design
    | of the emails. Or, you may simply stick with the Laravel defaults!
    |
    */

    'markdown' => [
        'theme' => 'default',

        'paths' => [
            resource_path('views/vendor/mail'),
        ],
    ],

];

Since I got no errors, even in laravel.log file I don't know even where to start checking, I have checked for the correct sendmail path though, and it was correct, what am I missing?

I also read that you have to change some things in /etc/hosts I changed it a bit adding "domainexample.com":

127.0.0.1   domainexample.com localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

Is this last thing correct?

Body:
MAIL_DRIVER=sendmail
MAIL_HOST=
MAIL_PORT=587
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

Fill all the details as provided by the mailing services.
if not have you tried using mailtrap and see if you can send a message. Mailtrap can be useful for development.

Documentation of Laravel for mail gives a clear view of what you should be doing.


问:
Is it possible to link a shared static library built in VS2019 with a VS2010 project?
I need a regex library that can return submatches for a project that has to be built on VS 2010. By submatches, I mean for this regex: "(\w+):(\d+)" applied to this input string "deer:1234", the match state is true and I want to retrieve the contents of the two submatches -- "deer" and "1234".  Visual Studio 2010 does not have regex so I tried building Google RE2 in Visual Studio 2019 as a shared static library and then making a simple interface (see below) to provide me with the bare minimum functionality that I needed.  It obviously builds fine in Visual Studio 2019, but when I copy over the re2.lib and the header shown below and try to compile it into my 2010 project, I get this error:

error LNK2038: mismatch detected for '_MSC_VER': value '1900' doesn't match value '1600'

Note that my interface below does not use any C++ standard library.  It's just a simple class with character array inputs.  I was thinking that if I compile the re2.lib as a shared statically-linked library and then link it with my 2010 project, it should work. But after spending almost 2 days trying to get this to work, I'm open to other solutions.  Will my approach work or if not can anyone recommend a good regex library that compiles in Visual Studio 2010?

```<code>class RE2;

class __declspec(dllexport) BasicRegex {
public:
    BasicRegex(const char* str);
    ~BasicRegex();

    bool fullMatch(const char* str, char**& submatches, int numsubmatches);
    bool fullMatch(const char* str);
    bool partialMatch(const char* str, char**& submatches, int numsubmatches);
    bool partialMatch(const char* str);

private:
    RE2* gre2;
};
</code>```

答:
The message is result of trying to link export  .lib created in  VS2010 with code in VS2019. Since VS2012 it's no longer supported.

Possible solutions to use the .dll are:

Recompile .dll or export .lib using new compiler.

Load library dynamically.

The former needs source availability and the latter requires that all dependent libraries  were present also may pose problem of finding name for imported functions.

Body:
I need a regex library that can return submatches for a project that has to be built on VS 2010. By submatches, I mean for this regex: "(\w+):(\d+)" applied to this input string "deer:1234", the match state is true and I want to retrieve the contents of the two submatches -- "deer" and "1234".  Visual Studio 2010 does not have regex so I tried building Google RE2 in Visual Studio 2019 as a shared static library and then making a simple interface (see below) to provide me with the bare minimum functionality that I needed.  It obviously builds fine in Visual Studio 2019, but when I copy over the re2.lib and the header shown below and try to compile it into my 2010 project, I get this error:

error LNK2038: mismatch detected for '_MSC_VER': value '1900' doesn't match value '1600'

Note that my interface below does not use any C++ standard library.  It's just a simple class with character array inputs.  I was thinking that if I compile the re2.lib as a shared statically-linked library and then link it with my 2010 project, it should work. But after spending almost 2 days trying to get this to work, I'm open to other solutions.  Will my approach work or if not can anyone recommend a good regex library that compiles in Visual Studio 2010?

class RE2;

class __declspec(dllexport) BasicRegex {
public:
    BasicRegex(const char* str);
    ~BasicRegex();

    bool fullMatch(const char* str, char**& submatches, int numsubmatches);
    bool fullMatch(const char* str);
    bool partialMatch(const char* str, char**& submatches, int numsubmatches);
    bool partialMatch(const char* str);

private:
    RE2* gre2;
};


问:
c#.net function
```<code>namespace csfunction
{
    class Program
    {
        static void Main(string[] args)
        {
            public int AddNumbers(int number1, int number2)
            {
                int result = AddNumbers(10, 5);
                Console.WriteLine(result);
            }
        }
    }
}
</code>```

is my code...am getting error like.....Error Type or namespace definition, or end-of-file expected

..hw can i over come this error

答:
The function AddNumbers should be outside the Main method</p>

```<code>namespace csfunction
{
  class Program
  {
    static void Main(string[] args)
    {

        int result = AddNumbers(10, 5);
        Console.WriteLine(result);
    }

      static int AddNumbers(int number1, int number2)
      {
          return number1 + number2;
      }
  }
}
</code>```

Title: c#.net function

Body:
namespace csfunction
{
    class Program
    {
        static void Main(string[] args)
        {
            public int AddNumbers(int number1, int number2)
            {
                int result = AddNumbers(10, 5);
                Console.WriteLine(result);
            }
        }
    }
}

is my code...am getting error like.....Error Type or namespace definition, or end-of-file expected

..hw can i over come this error

Body:
The function AddNumbers should be outside the Main method

namespace csfunction
{
  class Program
  {
    static void Main(string[] args)
    {

        int result = AddNumbers(10, 5);
        Console.WriteLine(result);
    }

      static int AddNumbers(int number1, int number2)
      {
          return number1 + number2;
      }
  }
}


问:
Transition to UITabBarController
I need help with bug fix. I'm use segue to transit between ViewControllers.

I have UITabBarController with one UIViewController. When I click on button in my vc I move to second vc. My second vc doesn't have TabBar. (use segue). In my second vc I have button and UIAlertController. When I click on button or alert I must transit to first vc with TabBar, but my TabBar doesn't displayed. How to fix this ? I don't need to use NavigationController.

```<code>let alert = UIAlertController(title: "Поздравляю", message: "Тренировка окончена", preferredStyle: UIAlertController.Style.alert)
        alert.addAction(UIAlertAction(title: "Click", style: UIAlertAction.Style.default, handler: { action in self.performSegue(withIdentifier: "backSegue", sender: self) }))
        self.present(alert, animated: true, completion: nil)
</code>```

StoryBoard

答:
Add below code to your FirstViewController from where you are moving to NextController via segue.

```<code>- (IBAction)unwindToFirst:(UIStoryboardSegue *)unwindSegue {

    UIViewController* sourceViewController = unwindSegue.sourceViewController;

    if ([sourceViewController isKindOfClass:[SecondViewController class]]) {
         NSLog(@"Coming from SECOND!");
    } else {
         NSLog(@"Handle Error");
    }
}
</code>```

And go to storyboard, right click and hold and drag from Button on NextController to Exit responder.

And you method name appears, connect to that.

Please refer this answer : What are Unwind segues for and how do you use them?

Title: Transition to UITabBarController

Body:
I need help with bug fix. I'm use segue to transit between ViewControllers.

I have UITabBarController with one UIViewController. When I click on button in my vc I move to second vc. My second vc doesn't have TabBar. (use segue). In my second vc I have button and UIAlertController. When I click on button or alert I must transit to first vc with TabBar, but my TabBar doesn't displayed. How to fix this ? I don't need to use NavigationController.

let alert = UIAlertController(title: "Поздравляю", message: "Тренировка окончена", preferredStyle: UIAlertController.Style.alert)
        alert.addAction(UIAlertAction(title: "Click", style: UIAlertAction.Style.default, handler: { action in self.performSegue(withIdentifier: "backSegue", sender: self) }))
        self.present(alert, animated: true, completion: nil)

StoryBoard

Body:
Add below code to your FirstViewController from where you are moving to NextController via segue.

- (IBAction)unwindToFirst:(UIStoryboardSegue *)unwindSegue {

    UIViewController* sourceViewController = unwindSegue.sourceViewController;

    if ([sourceViewController isKindOfClass:[SecondViewController class]]) {
         NSLog(@"Coming from SECOND!");
    } else {
         NSLog(@"Handle Error");
    }
}

And go to storyboard, right click and hold and drag from Button on NextController to Exit responder.

And you method name appears, connect to that.

Please refer this answer : What are Unwind segues for and how do you use them?


问:
SQL - 2 Selects at once. Union doesn't work as expected
I have a table containing flights to London.
Each connection has it's specific ID. There can be multiple records with different prices for each ID every day. I'm looking for maximum price of the connection for each day + average price of ANY flight to London each day.

This is my query:

```<code>SELECT entryDate, MAX(totalPrice) AS totalPrice
FROM flights
WHERE connectionID = 'xyz123'
GROUP BY entryDate
UNION ALL
SELECT entryDate, AVG(totalPrice) AS averagePrice
FROM flights
WHERE destination = 'London'
GROUP BY entryDate
ORDER BY entryDate ASC
LIMIT 90
</code>```

This is the result:

```<code>entryDate      totalPrice
2019-05-16     1159.8462
2019-05-16     553.0000
2019-05-17     1164.5736
2019-05-17     553.0000
2019-05-18     1101.8872
2019-05-18     634.0000
2019-05-19     1081.9766
2019-05-19     634.0000
2019-05-20     1119.6250
2019-05-20     634.0000
2019-05-21     1074.5781
2019-05-22     1079.2923
2019-05-23     1060.1641
2019-05-24     1116.1550
</code>```

Note that in last 4 days (21~24) the result from MAX(totalPrice) is not available, because the specific connection 'xyz123' was not in operation.

Anyway, my intention is to get this result:

```<code>entryDate      totalPrice      averagePrice
2019-05-16     553.0000        1159.8462
2019-05-17     553.0000        1164.5736
2019-05-18     634.0000        1101.8872
2019-05-19     634.0000        1081.9766
2019-05-20     634.0000        1119.6250
</code>```

答:
Use conditional aggregation:

```<code>SELECT entryDate,
       MAX(CASE WHEN connectionID = 'xyz123' THEN totalPrice END) AS totalPrice,
       AVG(CASE WHEN destination = 'London' THEN totalPrice END) as averagePrice
FROM flights f
GROUP BY entryDate;
</code>```

If you want only days with both values:

```<code>SELECT entryDate,
       MAX(CASE WHEN connectionID = 'xyz123' THEN totalPrice END) AS totalPrice,
       AVG(CASE WHEN destination = 'London' THEN totalPrice END) as averagePrice
FROM flights f
WHERE connectionID = 'xyz123' OR
      destination = 'London'
GROUP BY entryDate
HAVING SUM( connectionID = 'xyz123' ) > 0 AND
       SUM( destination = 'London' ) > 0;
</code>```

Leave out the HAVING clause if you are content with just one value on the date.

Body:
I have a table containing flights to London.
Each connection has it's specific ID. There can be multiple records with different prices for each ID every day. I'm looking for maximum price of the connection for each day + average price of ANY flight to London each day.

This is my query:

SELECT entryDate, MAX(totalPrice) AS totalPrice
FROM flights
WHERE connectionID = 'xyz123'
GROUP BY entryDate
UNION ALL
SELECT entryDate, AVG(totalPrice) AS averagePrice
FROM flights
WHERE destination = 'London'
GROUP BY entryDate
ORDER BY entryDate ASC
LIMIT 90

This is the result:

entryDate      totalPrice
2019-05-16     1159.8462
2019-05-16     553.0000
2019-05-17     1164.5736
2019-05-17     553.0000
2019-05-18     1101.8872
2019-05-18     634.0000
2019-05-19     1081.9766
2019-05-19     634.0000
2019-05-20     1119.6250
2019-05-20     634.0000
2019-05-21     1074.5781
2019-05-22     1079.2923
2019-05-23     1060.1641
2019-05-24     1116.1550

Note that in last 4 days (21~24) the result from MAX(totalPrice) is not available, because the specific connection 'xyz123' was not in operation.

Anyway, my intention is to get this result:

entryDate      totalPrice      averagePrice
2019-05-16     553.0000        1159.8462
2019-05-17     553.0000        1164.5736
2019-05-18     634.0000        1101.8872
2019-05-19     634.0000        1081.9766
2019-05-20     634.0000        1119.6250

Body:
Use conditional aggregation:

SELECT entryDate,
       MAX(CASE WHEN connectionID = 'xyz123' THEN totalPrice END) AS totalPrice,
       AVG(CASE WHEN destination = 'London' THEN totalPrice END) as averagePrice
FROM flights f
GROUP BY entryDate;

If you want only days with both values:

SELECT entryDate,
       MAX(CASE WHEN connectionID = 'xyz123' THEN totalPrice END) AS totalPrice,
       AVG(CASE WHEN destination = 'London' THEN totalPrice END) as averagePrice
FROM flights f
WHERE connectionID = 'xyz123' OR
      destination = 'London'
GROUP BY entryDate
HAVING SUM( connectionID = 'xyz123' ) > 0 AND
       SUM( destination = 'London' ) > 0;

Leave out the HAVING clause if you are content with just one value on the date.


问:
(Twig) How to check if value taken from translation key (as string or array?) exists within product variant title
(Twig) How can I check to see if a product variant title (which is used multi-lingual) in Twig exists within a translation key (which is a string, but I could change this to an array)?

For a webshop theme, I want to replace the "product.variant" variable (which is a platform variable and contains a variant title) with a CSS color swatch. The ecommerce platform doesnt provide a default way to do this, so I have to build a workaround which should work multi-lingual. Webshop-owners can enter their own label (name) for the color variant, so if webshop-owners use the string "Color", or "color", or "Farbe" (german) or whatever label name in whatever language, my workaround should be able to detect that "color label name" and replace this label value with a color swatch (via CSS, for this I need to know the label value, which is a color name like "blue", and in my CSS I guess I'll have to sum up all color names in as many languages as possible to make it work, I'm afraid, but this is ok). In my thinking I need to use a custom translation key so webshop-owners can enter the color name labels they want to work with, and compare these values with the "product variant" variables which are derived from the ecommerce platform. Can't figure out the right way to do so, anybody who can help me out? Much obliged!

This I tried:

```<code>{% for variant in product.variants %}
{% if theme.cstm_translkey_colorswatch_labelname | split(';') in variant.title %}
    <p style="background-color: green;color: yellow">Hi, show me a color swatch please!</p>
{% endif %}
{% endfor %}
</code>```

This code below works, but it uses just 1 variant label name ('Color:'), and I need it multi-lingual):

```<code>{% for variant in product.variants %}
    {% if 'Color:' in variant.title or 'color:' in variant.title %}
    {% set colorSwatches = true %}
    {% set colorName = variant.title | trim('"Color: ') %}
    {% if colorName not in colorNamesArray %}
        {% set colorNamesArray = colorNamesArray | merge([colorName]) %}
    {% endif %}
 {% endif %}
{% endfor %}
</code>```

My goal is to have an array of color names that works in all languages that the webshop runs (and where each color name exists just once) that I can replace with a CSS color swatch (this last part is not so much the problem).

(added:)
Variant.title is the system variable for product variants to work with, it's a string that can look like a simple "Size: L", but can also consist of 2 or more attributes, like "Size: L, Color: Blue, Occasion: Casual" (like a matrix of variants). From this value I need to derive whether there's a "color" attribute (but: in all languages the shop offers), and if so, replace this color attribute with  a CSS color swatch in the color of the color attribute value (the part after "Color: "), while the order for the attributes can differ (first "Color", or maybe last or in the middle?). That is because web merchants can enter their own variant names/labels, in any order they want, that's what makes it complicated  (for me ;).

The other variable "theme.cstm_translkey_colorswatch_labelname"  is my own effort to try to work with a custom translation key for webmerchants to define which keys they want to use (and also in what languages) to use as label name for the color variants, so I can use this to compare that to the product "variant.title". They can enter the value (string) for this translation key in the backoffice. But not sure if this is the way to go...

答:
The split will transform the string into an array. This means you can't use instraight away. You would need to loop all "languages":

```<code>{% for color in label|split(';') %}
    {% for title in titles %}
        {% if color|lower in title|lower %}
            {{ title }}
        {% endif %}
    {% endfor %}
{% endfor %}
</code>```

demo

Do note this would be easier if you would split up the attributes in title in seperate fields or use somthing like trans to translate color on the fly.

Body:
(Twig) How can I check to see if a product variant title (which is used multi-lingual) in Twig exists within a translation key (which is a string, but I could change this to an array)?

For a webshop theme, I want to replace the "product.variant" variable (which is a platform variable and contains a variant title) with a CSS color swatch. The ecommerce platform doesnt provide a default way to do this, so I have to build a workaround which should work multi-lingual. Webshop-owners can enter their own label (name) for the color variant, so if webshop-owners use the string "Color", or "color", or "Farbe" (german) or whatever label name in whatever language, my workaround should be able to detect that "color label name" and replace this label value with a color swatch (via CSS, for this I need to know the label value, which is a color name like "blue", and in my CSS I guess I'll have to sum up all color names in as many languages as possible to make it work, I'm afraid, but this is ok). In my thinking I need to use a custom translation key so webshop-owners can enter the color name labels they want to work with, and compare these values with the "product variant" variables which are derived from the ecommerce platform. Can't figure out the right way to do so, anybody who can help me out? Much obliged!

This I tried:

{% for variant in product.variants %}
{% if theme.cstm_translkey_colorswatch_labelname | split(';') in variant.title %}

Hi, show me a color swatch please!

{% endif %}
{% endfor %}

This code below works, but it uses just 1 variant label name ('Color:'), and I need it multi-lingual):

{% for variant in product.variants %}
    {% if 'Color:' in variant.title or 'color:' in variant.title %}
    {% set colorSwatches = true %}
    {% set colorName = variant.title | trim('"Color: ') %}
    {% if colorName not in colorNamesArray %}
        {% set colorNamesArray = colorNamesArray | merge([colorName]) %}
    {% endif %}
 {% endif %}
{% endfor %}

My goal is to have an array of color names that works in all languages that the webshop runs (and where each color name exists just once) that I can replace with a CSS color swatch (this last part is not so much the problem).

(added:)
Variant.title is the system variable for product variants to work with, it's a string that can look like a simple "Size: L", but can also consist of 2 or more attributes, like "Size: L, Color: Blue, Occasion: Casual" (like a matrix of variants). From this value I need to derive whether there's a "color" attribute (but: in all languages the shop offers), and if so, replace this color attribute with  a CSS color swatch in the color of the color attribute value (the part after "Color: "), while the order for the attributes can differ (first "Color", or maybe last or in the middle?). That is because web merchants can enter their own variant names/labels, in any order they want, that's what makes it complicated  (for me ;).

The other variable "theme.cstm_translkey_colorswatch_labelname"  is my own effort to try to work with a custom translation key for webmerchants to define which keys they want to use (and also in what languages) to use as label name for the color variants, so I can use this to compare that to the product "variant.title". They can enter the value (string) for this translation key in the backoffice. But not sure if this is the way to go...

Body:
The split will transform the string into an array. This means you can't use instraight away. You would need to loop all "languages":

{% for color in label|split(';') %}
    {% for title in titles %}
        {% if color|lower in title|lower %}
            {{ title }}
        {% endif %}
    {% endfor %}
{% endfor %}

demo

Do note this would be easier if you would split up the attributes in title in seperate fields or use somthing like trans to translate color on the fly.


问:
Message (alert) asking for confirmation
I'm beginner in JS.

I have this code:

```<code>            var fileLimit = parseInt(1);

            function refreshFileList() {
                $(".dz-preview").remove();
                $.ajax({
                    url: 'http://test/admin/showFilesDJS?type=SplashImage&id=1',
                    type: 'get',
                    dataType: 'json',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                    },
                    cache: false,
                    success: function (response) {

                        $.each(response, function (key, value) {
                            var mockFile = {
                                name: value.name,
                                size: value.size
                            };
                            dpzMultipleFiles.emit('addedfile', mockFile);
                            dpzMultipleFiles.emit('thumbnail', mockFile, value.path);
                            dpzMultipleFiles.emit('complete', mockFile)
                        })
                    },
                    error: function (response) {
                        alert('Nastąpił problem z JSON. Proszę o kontakt z administratorem serwisu.');
                    }
                });
            }

            Dropzone.options.dpzMultipleFiles =
                {
                    maxFiles: fileLimit,
                    clickable: true,
                    thumbnailWidth: 250,
                    thumbnailHeight: 250,
                    autoProcessQueue: true,
                    dictDefaultMessage: '',
                    uploadMultiple: true,
                    paramName: "myFile",
                    acceptedFiles: ".jpg,.jpeg",
                    addRemoveLinks: true,
                    timeout: 50000,
                    dictRemoveFile: 'Usuń plik',

                    init: function () {
                        dpzMultipleFiles = this;
                        refreshFileList();

                        this.on("thumbnail", function (file, dataUrl) {
                            $('.dz-image').last().find('img').attr({width: '100%', height: '100%'});
                        }),

                            this.on('completemultiple', function (file, json) {
                                //$('.sortable').sortable('enable');
                            });
                        this.on('success', function (file, json) {
                            //alert('aa');
                        });

                        this.on('addedfile', function (file) {
                            fileLimit = fileLimit - 1;
                        });

                        this.on('drop', function (file) {
                            fileLimit = fileLimit + 1;
                        });

                        this.on("maxfilesexceeded", function (file) {
                            alert('Plik ' + file.name + ' nie został wysłany na serwer. Limit plików został przekroczony!')
                            this.removeFile(file);
                        });
                    },

                    removedfile: function (file) {
                        $.ajax({
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                            },
                            cache: false,
                            type: 'POST',
                            url: 'http://test/admin/deleteDJS?id=' + file.name + 'type=SplashImage',
                            data: {filename: file.name, id: file.name, type: 'SplashImage'},
                            success: function (data) {
                                console.log("File has been successfully removed!!");
                                //refreshFileList();
                            },
                            error: function (e) {
                                console.log(e);
                            }
                        });

                        var fileRef;
                        return (fileRef = file.previewElement) != null ?
                            fileRef.parentNode.removeChild(file.previewElement) : void 0;
                    }
                };
            $(function () {
                $(".dropzone").sortable({
                    items: '.dz-preview',
                    cursor: 'move',
                    opacity: 0.5,
                    containment: '.dropzone',
                    distance: 20,
                    tolerance: 'pointer',
                    update: function (event, ui) {
                        $(".dz-filename span").each(function (index) {
                            $.ajax({
                                headers: {
                                    'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                                },
                                url: 'http://test/admin/changeOrderFilesDJS?type=SplashImage&id=1&index='+index+'&file='+ $(this).text(),
                                dataType: 'text',
                                type: 'post',
                                cache: false,
                                data: $(this).serialize(),
                                success: function (data, textStatus, jQxhr) {
                                },
                                error: function (jqXhr, textStatus, errorThrown) {
                                    alert('Nastąpił problem z JSON. Proszę o kontakt z administratorem serwisu.');
                                }
                            });
                        });
                    }
                });
            });
</code>```

This is Dropzone.JS. This code work fine.

I would like to add after clicking on the button remove (usuń plik) - the question: do you really want to delete this file? Only after clicking on YES the file would be deleted.

How to do it? I need a simple alert with a question in JS

答:
I think what you are looking for is a confirm().

```<code>if (confirm('Are you sure?')) {
    console.log('confirmed');
} else {
    console.log('declined');
}
</code>```

Title: Message (alert) asking for confirmation

Body:
I'm beginner in JS.

I have this code:

            var fileLimit = parseInt(1);

            function refreshFileList() {
                $(".dz-preview").remove();
                $.ajax({
                    url: 'http://test/admin/showFilesDJS?type=SplashImage&id=1',
                    type: 'get',
                    dataType: 'json',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                    },
                    cache: false,
                    success: function (response) {

                        $.each(response, function (key, value) {
                            var mockFile = {
                                name: value.name,
                                size: value.size
                            };
                            dpzMultipleFiles.emit('addedfile', mockFile);
                            dpzMultipleFiles.emit('thumbnail', mockFile, value.path);
                            dpzMultipleFiles.emit('complete', mockFile)
                        })
                    },
                    error: function (response) {
                        alert('Nastąpił problem z JSON. Proszę o kontakt z administratorem serwisu.');
                    }
                });
            }

            Dropzone.options.dpzMultipleFiles =
                {
                    maxFiles: fileLimit,
                    clickable: true,
                    thumbnailWidth: 250,
                    thumbnailHeight: 250,
                    autoProcessQueue: true,
                    dictDefaultMessage: '',
                    uploadMultiple: true,
                    paramName: "myFile",
                    acceptedFiles: ".jpg,.jpeg",
                    addRemoveLinks: true,
                    timeout: 50000,
                    dictRemoveFile: 'Usuń plik',

                    init: function () {
                        dpzMultipleFiles = this;
                        refreshFileList();

                        this.on("thumbnail", function (file, dataUrl) {
                            $('.dz-image').last().find('img').attr({width: '100%', height: '100%'});
                        }),

                            this.on('completemultiple', function (file, json) {
                                //$('.sortable').sortable('enable');
                            });
                        this.on('success', function (file, json) {
                            //alert('aa');
                        });

                        this.on('addedfile', function (file) {
                            fileLimit = fileLimit - 1;
                        });

                        this.on('drop', function (file) {
                            fileLimit = fileLimit + 1;
                        });

                        this.on("maxfilesexceeded", function (file) {
                            alert('Plik ' + file.name + ' nie został wysłany na serwer. Limit plików został przekroczony!')
                            this.removeFile(file);
                        });
                    },

                    removedfile: function (file) {
                        $.ajax({
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                            },
                            cache: false,
                            type: 'POST',
                            url: 'http://test/admin/deleteDJS?id=' + file.name + 'type=SplashImage',
                            data: {filename: file.name, id: file.name, type: 'SplashImage'},
                            success: function (data) {
                                console.log("File has been successfully removed!!");
                                //refreshFileList();
                            },
                            error: function (e) {
                                console.log(e);
                            }
                        });

                        var fileRef;
                        return (fileRef = file.previewElement) != null ?
                            fileRef.parentNode.removeChild(file.previewElement) : void 0;
                    }
                };
            $(function () {
                $(".dropzone").sortable({
                    items: '.dz-preview',
                    cursor: 'move',
                    opacity: 0.5,
                    containment: '.dropzone',
                    distance: 20,
                    tolerance: 'pointer',
                    update: function (event, ui) {
                        $(".dz-filename span").each(function (index) {
                            $.ajax({
                                headers: {
                                    'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                                },
                                url: 'http://test/admin/changeOrderFilesDJS?type=SplashImage&id=1&index='+index+'&file='+ $(this).text(),
                                dataType: 'text',
                                type: 'post',
                                cache: false,
                                data: $(this).serialize(),
                                success: function (data, textStatus, jQxhr) {
                                },
                                error: function (jqXhr, textStatus, errorThrown) {
                                    alert('Nastąpił problem z JSON. Proszę o kontakt z administratorem serwisu.');
                                }
                            });
                        });
                    }
                });
            });

This is Dropzone.JS. This code work fine.

I would like to add after clicking on the button remove (usuń plik) - the question: do you really want to delete this file? Only after clicking on YES the file would be deleted.

How to do it? I need a simple alert with a question in JS

Body:
I think what you are looking for is a confirm().

if (confirm('Are you sure?')) {
    console.log('confirmed');
} else {
    console.log('declined');
}


问:
get text area and text field data - jquery
I have 2 text areas in my page as;

```<code><input type="text" id="a1"/>
<textarea id="b2"></textarea>
<a id="button">button</a>
</code>```

When user click the button link, I want to alert the data entered in a1 and b2.

How can I do this?? Here is there demo

Thanks in advance...:)

blasteralfred

答:
Do like this :

```<code>window.alert($("#a1").val());
window.alert($("#a2").val());
</code>```

Your code should appear likt this :

```<code><input type="text" id="a1"/>
<textarea id="b2"></textarea>
<a id="button" onclick="window.alert($('#a1').val());window.alert($('#a2').val());return false;">button</a>
</code>```

Body:
I have 2 text areas in my page as;

<input type="text" id="a1"/>
<textarea id="b2"></textarea>
button

When user click the button link, I want to alert the data entered in a1 and b2.

How can I do this?? Here is there demo

Thanks in advance...:)

blasteralfred

Body:
Do like this :

window.alert($("#a1").val());
window.alert($("#a2").val());

Your code should appear likt this :

<input type="text" id="a1"/>
<textarea id="b2"></textarea>
<a id="button" onclick="window.alert($('#a1').val());window.alert($('#a2').val());return false;">button</a>