问:
What is the best method to sort a dynamic array of c-strings in a class in c++?
In my current programming class I've been tasked with creating a program that takes user input course (Consisting of course name, course grade, course units variables) and storing them in a dynamically generated array with a maximum size of 10.

Due to my unfamiliarity with object oriented programming and classes however I'm finding anything beyond the pure creation of the classes to be very difficult. I've figured out a way to create the entries, as well as how to edit them after they've been created using friend functions (I think that's the name?) stored in my programs header file.

However now that I've needed to perform a sort on the data (by the name variable of every entry) as well as to then search it I'm finding it very difficult to proceed. I understand how to make functions that can do both of these things (As I have done it for my previous class), but doing it with classes being involved is proving challenging.

My header file:

```<code>#ifndef COURSE_H
#define COURSE_H

#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <cstdlib>
#include <vector>

class Course
{
private:
    char name[10] = ""; //name of course
    char grade; //grade in course
    int units; //units in course

public:
    Course()
    {
        name;
        grade;
        units;
    }

    void read() //Initializes course and collects information from user
    {
        std::cout << "\nEnter course name: ";
        std::cin.getline(name, 10, '\n');
        std::cout << "\nEnter number of units: ";
        std::cin >> units;
        std::cout << "\nEnter grade received: ";
        std::cin >> grade;
        std::cin.ignore();
    }

    void display() const //Displays course to user
    {
        std::cout << name << ' ' << units << ' ' << grade << std::endl;
    }

    ~Course() //Destructor frees allocated dynamic memory
    {
        std::cout << "\nDeleting any dynamically created object";
    }
};

#endif // COURSE_H
</code>```

My main source file:

```<code>#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <cstdlib>
#include <vector>
#include "courses.h"

int menu();
void add(Course* co_ptr[], int& size);
void edit(Course* co_ptr[], int size);
void swap_ptrs(Course*& pt1, Course*& pt2);

int main()
{
    Course* courses[10] = {};
    int selection;

    int size = 0;
    do
    {
        selection = menu();

        if (selection == 1)
        {
            if (size < 10)
                add(courses, size);
            else
                std::cout << "\nUnable to add more classes.";
        }
        else if (selection == 2)
        {
            edit(courses, size);
        }
        else if (selection == 3)
        {

        }
        else if (selection == 4)
        {

        }
        else if (selection == 5)
        {

        }
        else if (selection == 6)
        {

        }
        else if (selection == 7)
        {
            break;
        }
        else
        {
            std::cout << "\nInvalid selection.";
        }
    } while (selection != 7);

    std::cout << "\nPress any key to exit.";
    (void)_getch();
    return 0;
}
</code>```

My functions source file:

```<code>#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <cstdlib>
#include <vector>
#include "courses.h"

int menu()
{
    int selection;

    std::cout << "\nSelect one of the following actions: " << std::endl
        << "1. Add new course" << std::endl
        << "2. Edit an existing course" << std::endl
        << "3. Display a course" << std::endl
        << "4. List all courses" << std::endl
        << "5. Display GPA" << std::endl
        << "6. Delete all courses" << std::endl
        << "7. Quit";
    std::cout << "\nEnter selection number: ";
    std::cin >> selection;
    std::cin.ignore();

    return selection;
}

void add(Course* co_ptr[], int& size)
{
    co_ptr[size] = new Course;
    co_ptr[size]->read();
    size++;
}

void edit(Course* co_ptr[], int size)
{
    int selection;
    for (int i = 0; i < size; i++)
    {
        std::cout << std::endl << i << ". ";
        co_ptr[i]->display();
    }

    std::cout << "Enter your selection: ";
    std::cin >> selection;
    std::cin.ignore();

    co_ptr[selection]->read();
}
</code>```

My last attempt at making a sort function (I tried to create it within the header as whenever I ported in my old sorting code as a normal function it couldn't access the data it needed on account of those variables being "private")

```<code>void Course::sort_name(Course* co_ptr[], int size) //has to be apart of the class (Course::) to have access to the name data
{
    bool swap;

    do
    {
        swap = false;
        for (int i = 0; i < size - 1; i++)
        {
            if (strcmp(co_ptr[i]->name, co_ptr[i + 1]->name) > 0) //We're now comparing and swapping pointers
            {
                swap_ptrs(co_ptr[i], co_ptr[i + 1]);
                swap = true;
            }
        }
    } while (swap);
}
</code>```

Lastly my swap_ptrs function which was also in the function source file:

```<code>void swap_ptrs(Course*& pt1, Course*& pt2) //Passes the pointers by reference
{
    Course* tmp = pt1;
    pt1 = pt2;
    pt2 = tmp;
}
</code>```

I'm sorry for such a long post but this project has been a real struggle and I'm feeling like I'm not making any headway.

答:
For sorting, std::sort() can be used.

Of course, there is something else necessary – a less predicate which provides the intended order – the Course*s sorted by name members.

Such a predicate could be:

```<code>auto lessCourse
    = [](const Course *pCourse1, const Course *pCourse2)
    {
      return strcmp(pCourse1->getName(), pCourse2->getName()) < 0;
    };
</code>```

which is lambda (and could be provided as third argument to std::sort() directly).

(A function with same signature would do as well.)

A small demo for illustration:

```<code>#include <iostream>
#include <cstring>
#include <algorithm>

class Course {
  private:
    char name[10] = ""; //name of course
    char grade; //grade in course
    int units; //units in course

  public:
    explicit Course(const char *name = "", char grade = ' ', int units = 0):
      grade(grade), units(units)
    {
      strncpy(this->name, name, 9);
      this->name[9] = '\0';
    }

    ~Course() = default;
    Course(const Course&) = delete;
    Course& operator=(const Course&) = delete;

    const char* getName() const { return name; }
};

void add(
  Course *pCourses[], unsigned &n,
  const char *name = "", char grade = ' ', int units = 0)
{
  pCourses[n++] = new Course(name, grade, units);
}

int main()
{
  Course *pCourses[10];
  unsigned nCourses = 0;
  // make sample
  add(pCourses, nCourses, "Peter");
  add(pCourses, nCourses, "Carla");
  add(pCourses, nCourses, "Anna");
  add(pCourses, nCourses, "Dieter");
  add(pCourses, nCourses, "Berta");
  // sort sample
  // make a less predicate to compare Course instances by name
  auto lessCourse
    = [](const Course *pCourse1, const Course *pCourse2)
    {
      return strcmp(pCourse1->getName(), pCourse2->getName()) < 0;
    };
  // use std::sort() with that less predicate
  std::sort(pCourses, pCourses + nCourses, lessCourse);
  // output
  for (unsigned i = 0; i < nCourses; ++i) {
    const Course *pCourse = pCourses[i];
    std::cout
      << pCourse->getName() << ", "
      << pCourse->getName() << ", oh "
      << pCourse->getName() << ".\n";
  }
}
</code>```

Output:

Anna, Anna, oh Anna.
Berta, Berta, oh Berta.
Carla, Carla, oh Carla.
Dieter, Dieter, oh Dieter.
Peter, Peter, oh Peter.
```

Live Demo on coliru

Trivia:

Concerning the unusual output format, I used:

Trio - Anna - Lassmichrein Lassmichraus

Body:
In my current programming class I've been tasked with creating a program that takes user input course (Consisting of course name, course grade, course units variables) and storing them in a dynamically generated array with a maximum size of 10.

Due to my unfamiliarity with object oriented programming and classes however I'm finding anything beyond the pure creation of the classes to be very difficult. I've figured out a way to create the entries, as well as how to edit them after they've been created using friend functions (I think that's the name?) stored in my programs header file.

However now that I've needed to perform a sort on the data (by the name variable of every entry) as well as to then search it I'm finding it very difficult to proceed. I understand how to make functions that can do both of these things (As I have done it for my previous class), but doing it with classes being involved is proving challenging.

My header file:

#ifndef COURSE_H
#define COURSE_H

#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <cstdlib>
#include <vector>

class Course
{
private:
    char name[10] = ""; //name of course
    char grade; //grade in course
    int units; //units in course

public:
    Course()
    {
        name;
        grade;
        units;
    }

    void read() //Initializes course and collects information from user
    {
        std::cout << "\nEnter course name: ";
        std::cin.getline(name, 10, '\n');
        std::cout << "\nEnter number of units: ";
        std::cin >> units;
        std::cout << "\nEnter grade received: ";
        std::cin >> grade;
        std::cin.ignore();
    }

    void display() const //Displays course to user
    {
        std::cout << name << ' ' << units << ' ' << grade << std::endl;
    }

    ~Course() //Destructor frees allocated dynamic memory
    {
        std::cout << "\nDeleting any dynamically created object";
    }
};

#endif // COURSE_H

My main source file:

#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <cstdlib>
#include <vector>
#include "courses.h"

int menu();
void add(Course* co_ptr[], int& size);
void edit(Course* co_ptr[], int size);
void swap_ptrs(Course*& pt1, Course*& pt2);

int main()
{
    Course* courses[10] = {};
    int selection;

    int size = 0;
    do
    {
        selection = menu();

        if (selection == 1)
        {
            if (size < 10)
                add(courses, size);
            else
                std::cout << "\nUnable to add more classes.";
        }
        else if (selection == 2)
        {
            edit(courses, size);
        }
        else if (selection == 3)
        {

        }
        else if (selection == 4)
        {

        }
        else if (selection == 5)
        {

        }
        else if (selection == 6)
        {

        }
        else if (selection == 7)
        {
            break;
        }
        else
        {
            std::cout << "\nInvalid selection.";
        }
    } while (selection != 7);

    std::cout << "\nPress any key to exit.";
    (void)_getch();
    return 0;
}

My functions source file:

#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <cstdlib>
#include <vector>
#include "courses.h"

int menu()
{
    int selection;

    std::cout << "\nSelect one of the following actions: " << std::endl
        << "1. Add new course" << std::endl
        << "2. Edit an existing course" << std::endl
        << "3. Display a course" << std::endl
        << "4. List all courses" << std::endl
        << "5. Display GPA" << std::endl
        << "6. Delete all courses" << std::endl
        << "7. Quit";
    std::cout << "\nEnter selection number: ";
    std::cin >> selection;
    std::cin.ignore();

    return selection;
}

void add(Course* co_ptr[], int& size)
{
    co_ptr[size] = new Course;
    co_ptr[size]->read();
    size++;
}

void edit(Course* co_ptr[], int size)
{
    int selection;
    for (int i = 0; i < size; i++)
    {
        std::cout << std::endl << i << ". ";
        co_ptr[i]->display();
    }

    std::cout << "Enter your selection: ";
    std::cin >> selection;
    std::cin.ignore();

    co_ptr[selection]->read();
}

My last attempt at making a sort function (I tried to create it within the header as whenever I ported in my old sorting code as a normal function it couldn't access the data it needed on account of those variables being "private")

void Course::sort_name(Course* co_ptr[], int size) //has to be apart of the class (Course::) to have access to the name data
{
    bool swap;

    do
    {
        swap = false;
        for (int i = 0; i < size - 1; i++)
        {
            if (strcmp(co_ptr[i]->name, co_ptr[i + 1]->name) > 0) //We're now comparing and swapping pointers
            {
                swap_ptrs(co_ptr[i], co_ptr[i + 1]);
                swap = true;
            }
        }
    } while (swap);
}

Lastly my swap_ptrs function which was also in the function source file:

void swap_ptrs(Course*& pt1, Course*& pt2) //Passes the pointers by reference
{
    Course* tmp = pt1;
    pt1 = pt2;
    pt2 = tmp;
}

I'm sorry for such a long post but this project has been a real struggle and I'm feeling like I'm not making any headway.

Body:
For sorting, std::sort() can be used.

Of course, there is something else necessary – a less predicate which provides the intended order – the Course*s sorted by name members.

Such a predicate could be:

auto lessCourse
    = [](const Course *pCourse1, const Course *pCourse2)
    {
      return strcmp(pCourse1->getName(), pCourse2->getName()) < 0;
    };

which is lambda (and could be provided as third argument to std::sort() directly).

(A function with same signature would do as well.)

A small demo for illustration:

#include <iostream>
#include <cstring>
#include <algorithm>

class Course {
  private:
    char name[10] = ""; //name of course
    char grade; //grade in course
    int units; //units in course

  public:
    explicit Course(const char *name = "", char grade = ' ', int units = 0):
      grade(grade), units(units)
    {
      strncpy(this->name, name, 9);
      this->name[9] = '\0';
    }

    ~Course() = default;
    Course(const Course&) = delete;
    Course& operator=(const Course&) = delete;

    const char* getName() const { return name; }
};

void add(
  Course *pCourses[], unsigned &n,
  const char *name = "", char grade = ' ', int units = 0)
{
  pCourses[n++] = new Course(name, grade, units);
}

int main()
{
  Course *pCourses[10];
  unsigned nCourses = 0;
  // make sample
  add(pCourses, nCourses, "Peter");
  add(pCourses, nCourses, "Carla");
  add(pCourses, nCourses, "Anna");
  add(pCourses, nCourses, "Dieter");
  add(pCourses, nCourses, "Berta");
  // sort sample
  // make a less predicate to compare Course instances by name
  auto lessCourse
    = [](const Course *pCourse1, const Course *pCourse2)
    {
      return strcmp(pCourse1->getName(), pCourse2->getName()) < 0;
    };
  // use std::sort() with that less predicate
  std::sort(pCourses, pCourses + nCourses, lessCourse);
  // output
  for (unsigned i = 0; i < nCourses; ++i) {
    const Course *pCourse = pCourses[i];
    std::cout
      << pCourse->getName() << ", "
      << pCourse->getName() << ", oh "
      << pCourse->getName() << ".\n";
  }
}

Output:

Anna, Anna, oh Anna.
Berta, Berta, oh Berta.
Carla, Carla, oh Carla.
Dieter, Dieter, oh Dieter.
Peter, Peter, oh Peter.

Live Demo on coliru

Trivia:

Concerning the unusual output format, I used:

Trio - Anna - Lassmichrein Lassmichraus


来源: stackexchange

问:
How to make mozilla sign my updater xpi file which has the same UID hsa my main xpi file?
I want to be able to update my self-distribution firefox addon.  I have so far signed my  xpi file containing UID: xyz@text.com. But, in order for updates to work, my updater .xpi file should also have the same UID:xyz@text.com. I am able to update on firefox developer mode by turning off xpinstall.signatures.required to False. This is not reliable and I wish there is an easy to way to have mozilla sign my updater .xpi file as well without throwing the Duplicate UID found.

I looked at the two other ways to update and they seem complex. i.e via Signing API and web-ext sign.

```<code>In my main .xpi's manifest file, I have the below.
  "version": "1.0",
"browser_specific_settings": {
    "gecko": {
      "id": "xyz@text.com",
      "update_url": "https://mydomain/files/updates.json"
    }
</code>```

```<code>In my updater .xpi file, I have this.
  "version": "1.2",
"browser_specific_settings": {
    "gecko": {
      "id": "xyz@text.com",
      "update_url": "https://mydomain/files/updates.json"
    }
</code>```

答: I got it. The answer was staring at my face. Use the "Upload New Version" and then we can upload the updater.xpi file containing the same UUID and it won't say "duplicate blahblah". </p>

ContentLicense: CC BY-SA 4.0

Body:
I want to be able to update my self-distribution firefox addon.  I have so far signed my  xpi file containing UID: xyz@text.com. But, in order for updates to work, my updater .xpi file should also have the same UID:xyz@text.com. I am able to update on firefox developer mode by turning off xpinstall.signatures.required to False. This is not reliable and I wish there is an easy to way to have mozilla sign my updater .xpi file as well without throwing the Duplicate UID found.

I looked at the two other ways to update and they seem complex. i.e via Signing API and web-ext sign.

In my main .xpi's manifest file, I have the below.
  "version": "1.0",
"browser_specific_settings": {
    "gecko": {
      "id": "xyz@text.com",
      "update_url": "https://mydomain/files/updates.json"
    }

In my updater .xpi file, I have this.
  "version": "1.2",
"browser_specific_settings": {
    "gecko": {
      "id": "xyz@text.com",
      "update_url": "https://mydomain/files/updates.json"
    }


问:
Should I submit something to YQL without first encoding it?
If I'm sending a query like:

```<code>$.getScript('http://query.yahooapis.com/v1/public/yql?q=select * from html ' +
    'where url="..."&callback=cb')
</code>```

Is it safe to send it without encoding it or should I encode it someway?

答:
Have you tried it? I haven't tried getScript(), just a simple get() instead, but it works for me in FF4.0.1 and Chrome 11.

However, I would still recommending using encodeURIComponent() on the query string to avoid being dependent on browser behaviour:

```<code>$.getScript('http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="..."') + '&callback=cb');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If I'm sending a query like:

$.getScript('http://query.yahooapis.com/v1/public/yql?q=select * from html ' +
    'where url="..."&callback=cb')

Is it safe to send it without encoding it or should I encode it someway?

Body:
Have you tried it? I haven't tried getScript(), just a simple get() instead, but it works for me in FF4.0.1 and Chrome 11.

However, I would still recommending using encodeURIComponent() on the query string to avoid being dependent on browser behaviour:

$.getScript('http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="..."') + '&callback=cb');


问:
SQL Server is not a valid installation folder how to fix location
I want to install SQL server on my pc, but when I am try to give path for installation, I am getting this error, the C:\Program Files (x86)\Microsoft SQL Server\ is not valid installation folder, I tried other drives but still no result.

Here is the image of SQL Server installation center with the error path
SQL Server installation center with the error path

答:
Ah!  New information comes to light!  Initially, my .exe file was located here:

```<code>C:\
</code>```

I just moved my .exe file to a new location, which is here:

```<code>C:\Program Files (x86)\Microsoft SQL Server\
</code>```

Body:
Ah!  New information comes to light!  Initially, my .exe file was located here:

C:\

I just moved my .exe file to a new location, which is here:

C:\Program Files (x86)\Microsoft SQL Server\


问:
How to save selected item in tableviewcell
I want to ask how can save selected all item in tableViewCell like this picture below. so later I can post it with with alamofire, I don't have any experience with posting data before. here is what have I done.

this is my button so I can later post in with alamofire, so far I want to test it.

```<code>    @objc func handleSubmit() {
        var data: [String] = []
        for (index, value) in attendance.enumerated() {
            print("index attendance: \(index), value attendance: \(value.status)")
            let cell = tableView.cellForRow(at: IndexPath(item: index, section: 0)) as? GStudentAbsenceCell
        UserServices.shared.postUserAttendances(status: cell?.status ?? "")
            data.append(cell?.status ?? String(index))
        }
        print(data)
    }

// In My UITableViewCell
var status: String?

statusLbl.didSelect { (selectedText , index ,id) in
               if selectedText == "Sakit" || selectedText == "Izin" || selectedText == "Alpha" {
                self.status = selectedText
                   self.statusLbl.backgroundColor = #colorLiteral(red: 0.8666666667, green: 0.4078431373, blue: 0.2705882353, alpha: 0.2)
                   self.statusLbl.textColor = #colorLiteral(red: 0.8666666667, green: 0.4078431373, blue: 0.2705882353, alpha: 1)
               }
           }
</code>```

答:
You cannot safely store your data models state in a table view cell, because upon scrolling the cell will likely to be reused for newly visible rows, hence it will store the state for a different row and therefore will lose the "old" state.

You need to store the state in your model; if it's not feasible to use your existing model, you might create a transient dictionary which maps the IndexPath to the state

What you could do is the following:

Extend your Cell with a custom callback handler, which is called when the status is changed.

When you set up your cell, hand in a closure that will deal with those status changes

In that closure, update the model

Some pseudo code might help you:

```<code>// in your custom cell
typealias Handler: (String) -> ()
class CustomTableViewCell : UITableViewCell {
     var selectionHandler:Handler?
     func didSelect(...) {
          selectionHandler?(lblStatus.text)
     }

}

// in your view controller
// in rowForCellatIndexPath:

func  tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {
     let cell = /* dequeue */ as! CustomTableViewCell

     cell.selectionHandler = { statusText in
          let row = indexPath.row
          attendance[row].status = statusText /* get the status from the cell */
     }

     return cell
}
</code>```

Body:
I want to ask how can save selected all item in tableViewCell like this picture below. so later I can post it with with alamofire, I don't have any experience with posting data before. here is what have I done.

this is my button so I can later post in with alamofire, so far I want to test it.

    @objc func handleSubmit() {
        var data: [String] = []
        for (index, value) in attendance.enumerated() {
            print("index attendance: \(index), value attendance: \(value.status)")
            let cell = tableView.cellForRow(at: IndexPath(item: index, section: 0)) as? GStudentAbsenceCell
        UserServices.shared.postUserAttendances(status: cell?.status ?? "")
            data.append(cell?.status ?? String(index))
        }
        print(data)
    }

// In My UITableViewCell
var status: String?

statusLbl.didSelect { (selectedText , index ,id) in
               if selectedText == "Sakit" || selectedText == "Izin" || selectedText == "Alpha" {
                self.status = selectedText
                   self.statusLbl.backgroundColor = #colorLiteral(red: 0.8666666667, green: 0.4078431373, blue: 0.2705882353, alpha: 0.2)
                   self.statusLbl.textColor = #colorLiteral(red: 0.8666666667, green: 0.4078431373, blue: 0.2705882353, alpha: 1)
               }
           }

Body:
You cannot safely store your data models state in a table view cell, because upon scrolling the cell will likely to be reused for newly visible rows, hence it will store the state for a different row and therefore will lose the "old" state.

You need to store the state in your model; if it's not feasible to use your existing model, you might create a transient dictionary which maps the IndexPath to the state

What you could do is the following:

Extend your Cell with a custom callback handler, which is called when the status is changed.

When you set up your cell, hand in a closure that will deal with those status changes

In that closure, update the model

Some pseudo code might help you:

// in your custom cell
typealias Handler: (String) -> ()
class CustomTableViewCell : UITableViewCell {
     var selectionHandler:Handler?
     func didSelect(...) {
          selectionHandler?(lblStatus.text)
     }

}

// in your view controller
// in rowForCellatIndexPath:

func  tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {
     let cell = /* dequeue */ as! CustomTableViewCell

     cell.selectionHandler = { statusText in
          let row = indexPath.row
          attendance[row].status = statusText /* get the status from the cell */
     }

     return cell
}


问:
kubernetes multi domain dynamic routing
Hello I would like to know how to dynamically route multiple domains to different services in Kubernetes, I'm trying to let my users add a domain to their accounts and based on that domain route to a specific service to render their webpage but with their domain. I have no idea where to start and would like to know if this is possible with Kubernetes.</p>

答:
assuming that all these services are HTTP(s) based 2 things need to happen:

an ingress object should be created that routes a given domain to an appropriate service (see https://kubernetes.io/docs/concepts/services-networking/ingress/)

proper records must be added to the DNS configuration of a given domain, (proabably a CNAME record pointing to your cluster, but it depends whether all traffic is supposed to be handled by your service or just a part of it)

Title: kubernetes multi domain dynamic routing


问:
Postgres Node search query using LIKE, how to set %
I have a weird problem I encountered using Postgresql and Node. I would like to use LIKE in my query together with % at the beginning and end of searched term. I have no issue using it in the plain SQL:

THIS WORKS:

```<code>SELECT * FROM vehicle WHERE module_imei LIKE '%searchterm%' OR custom_id LIKE '%searchterm%'
</code>```

However, using it in Node is a bit of challenge. I haven't been successful in resolving it yet:
THIS DOES NOT WORK:

```<code>  getVehiclesSearch: async function({ search }) {
    let response;
    try {
      response = await pool.query(`SELECT * FROM vehicle WHERE module_imei LIKE %$1% OR custom_id LIKE %$1%`, [search]);
      if(response) return response.rows;
    } catch(error) {
      // handle error
      console.error(error);
      // do not throw anything
    }
  },
</code>```

Doing above will produce: syntax error at or near "%"

```<code>SELECT * FROM vehicle WHERE module_imei LIKE '%${$1}%' OR custom_id LIKE '%${$1}%
</code>```

Doing above will produce: $1 is not defined

```<code>SELECT * FROM vehicle WHERE module_imei LIKE '%$1%' OR custom_id LIKE '%$1%'
</code>```

Doing above will produce: bind message supplies 1 parameters, but prepared statement "" requires 0

I kind of struggle factoring the % in so it won't crash the query. Simply run out of ideas after trying above and variables of those. Thanks for your kind help.

答:
This has been already answered over here:
Go postgresql LIKE query

In this particular case:

```<code>      response = await pool.query(`SELECT * FROM vehicle WHERE module_imei LIKE '%'||$1||'%' OR custom_id LIKE '%'||$1||'%'`, [search]);
</code>```

This would work.

Body:
I have a weird problem I encountered using Postgresql and Node. I would like to use LIKE in my query together with % at the beginning and end of searched term. I have no issue using it in the plain SQL:

THIS WORKS:

SELECT * FROM vehicle WHERE module_imei LIKE '%searchterm%' OR custom_id LIKE '%searchterm%'

However, using it in Node is a bit of challenge. I haven't been successful in resolving it yet:
THIS DOES NOT WORK:

  getVehiclesSearch: async function({ search }) {
    let response;
    try {
      response = await pool.query(`SELECT * FROM vehicle WHERE module_imei LIKE %$1% OR custom_id LIKE %$1%`, [search]);
      if(response) return response.rows;
    } catch(error) {
      // handle error
      console.error(error);
      // do not throw anything
    }
  },

Doing above will produce: syntax error at or near "%"

SELECT * FROM vehicle WHERE module_imei LIKE '%${$1}%' OR custom_id LIKE '%${$1}%

Doing above will produce: $1 is not defined

SELECT * FROM vehicle WHERE module_imei LIKE '%$1%' OR custom_id LIKE '%$1%'

Doing above will produce: bind message supplies 1 parameters, but prepared statement "" requires 0

I kind of struggle factoring the % in so it won't crash the query. Simply run out of ideas after trying above and variables of those. Thanks for your kind help.

Body:
This has been already answered over here:
Go postgresql LIKE query

In this particular case:

      response = await pool.query(`SELECT * FROM vehicle WHERE module_imei LIKE '%'||$1||'%' OR custom_id LIKE '%'||$1||'%'`, [search]);

This would work.


问:
Deallocated view controller causing EXC_BAD_ACCESS because of fetched results controller update
I have a navigation app with 3 view controllers on the stack.  The navigation root pushes AvailableItemsViewController, passing a managed object context to it.

This view, which is a table view that uses a fetched results controller to populate it, has an add button which pushes another controller (CreateNewItemViewController) I pass that context off to it.

In CreateNewItemViewController I create a managed object, save it to the context, then pop the view controller.

I can go back and forth saving items to the AvailableItemsViewController until I go back to the navigation root. (The AvailableItemsViewController gets deallocated).

After this if I drill back down to the third controller and try to save I get this:

Here's my error (zombies enabled:)

-[AvailableItemsViewController controllerWillChangeContent:]: message sent to deallocated instance 0x1f6500

and without zombies

-[__NSArrayM controllerWillChangeContent:]: unrecognized selector sent to instance 0x4ecdee0

(i've gotten a lot of different random output on this, it seems that the destination of the controllerWillChangeContent: message is random)

all controllers are setting their properties to nil and releasing ivars in viewDidUnload and dealloc respectively.

When stepping through the crash happens at [self.managedObjectContext save:&error] in the third controller (CreateNewItemViewController)

答: You're leaking the NSFetchedResultsController. This means that it stays alive, and when something changes the data store it does its job and tries to signal the change. But since the delegate has been deallocated, you get EXC_BAD_ACCESS or messages sent to whatever random object happens to have been allocated at that memory location.</p>


问:
PHP / MySQL: Undefined index after user update a data
Currently, I develop a system that required an update function. The flow of the system will be like this:

1) list of data row in dashboard.php

2) User can select one of the data to view the details. It will redirect to view_task.php

3) At view_task.php, user can update the task name and click 'save' button to save.

The problem is. After I click button save, It will show the error 'undefined index: report id at line 7' and "undefined variable: task_name at line 55"

below is my current code:

view_task.php

```<code><?php

  require_once "../../../../config/configPDO.php";
  require_once "../../../../config/check.php";

  $report_id = $_GET['report_id']; //line 7

  $sql = "SELECT * FROM ot_report WHERE report_id = :report_id";
  $query = $conn->prepare($sql);
  $query->execute(array(':report_id' => $report_id));
  while($row = $query->fetch(PDO::FETCH_ASSOC)){

      $report_id = $row["report_id"];
      $task_name = $row["task_name"];
  }

?>

<form action="update_task_name.php" method="POST">
  <td><b>Task Name</b></td>
  <td colspan = '2'><input type="text" class="form-control" name="task_name" value="<?php echo $task_name; ?>"/></td> //line 55
  <input type="hidden" name="report_id" value="<?php echo $report_id ?>">
  <td><input type="submit" class="btn btn-primary btn-block" value = "Save" onclick="confirm('Are you sure?')"></td>
</form>
</code>```

update_task_name.php

```<code><?php

    require_once '../../../../config/configPDO.php';

    $update = "UPDATE ot_report SET task_name = :task_name WHERE report_id = :report_id";
    $stmt = $conn->prepare($update);
    $stmt->bindParam(':task_name', $_POST['task_name']);
    $stmt->bindParam(':report_id', $_POST['report_id']);
    $stmt->execute();

    class Result {}
    $response = new Result();
    $response->result = 'OK';
    $response->message = 'Update successful';
    header("Location: view_task.php");

?>
</code>```

Although get the error at view_task.php, but the data successfully save!

Can anyone know what is the error?

答:
This all is overly complex, because it is quite simple:</p>

```<code>/* initialize variables before already */
$report_id = -1;
$task_name = '';

/* check if the $_GET has a numerical report_id */
if(isset($_GET['report_id']) && is_numeric($_GET['report_id'])) {

    /* then dare to access $_GET['report_id'] */
    $report_id = $_GET['report_id']; //line 7

    $sql = "SELECT * FROM ot_report WHERE report_id = :report_id";
    $query = $conn->prepare($sql);
    $query->execute(array(':report_id' => $report_id));
    while($row = $query->fetch(PDO::FETCH_ASSOC)){
        $task_name = $row["task_name"];
    }
}

...
</code>```

Body:
Currently, I develop a system that required an update function. The flow of the system will be like this:

1) list of data row in dashboard.php

2) User can select one of the data to view the details. It will redirect to view_task.php

3) At view_task.php, user can update the task name and click 'save' button to save.

The problem is. After I click button save, It will show the error 'undefined index: report id at line 7' and "undefined variable: task_name at line 55"

below is my current code:

view_task.php

<?php

  require_once "../../../../config/configPDO.php";
  require_once "../../../../config/check.php";

  $report_id = $_GET['report_id']; //line 7

  $sql = "SELECT * FROM ot_report WHERE report_id = :report_id";
  $query = $conn->prepare($sql);
  $query->execute(array(':report_id' => $report_id));
  while($row = $query->fetch(PDO::FETCH_ASSOC)){

      $report_id = $row["report_id"];
      $task_name = $row["task_name"];
  }

?>

<form action="update_task_name.php" method="POST">
  Task Name
  <input type="text" class="form-control" name="task_name" value="<?php echo $task_name; ?>"/>	 //line 55
  <input type="hidden" name="report_id" value="<?php echo $report_id ?>">
  <input type="submit" class="btn btn-primary btn-block" value = "Save" onclick="confirm('Are you sure?')">
</form>

update_task_name.php

<?php

    require_once '../../../../config/configPDO.php';

    $update = "UPDATE ot_report SET task_name = :task_name WHERE report_id = :report_id";
    $stmt = $conn->prepare($update);
    $stmt->bindParam(':task_name', $_POST['task_name']);
    $stmt->bindParam(':report_id', $_POST['report_id']);
    $stmt->execute();

    class Result {}
    $response = new Result();
    $response->result = 'OK';
    $response->message = 'Update successful';
    header("Location: view_task.php");

?>

Although get the error at view_task.php, but the data successfully save!

Can anyone know what is the error?

Body:
This all is overly complex, because it is quite simple:

/* initialize variables before already */
$report_id = -1;
$task_name = '';

/* check if the $_GET has a numerical report_id */
if(isset($_GET['report_id']) && is_numeric($_GET['report_id'])) {

    /* then dare to access $_GET['report_id'] */
    $report_id = $_GET['report_id']; //line 7

    $sql = "SELECT * FROM ot_report WHERE report_id = :report_id";
    $query = $conn->prepare($sql);
    $query->execute(array(':report_id' => $report_id));
    while($row = $query->fetch(PDO::FETCH_ASSOC)){
        $task_name = $row["task_name"];
    }
}

...


问:
I have error check manual corresponding mysql server version
Repository:

package com.apsilabs.meterwebapi.repository;

```<code>import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import com.apsilabs.meterwebapi.model.ActualsBlockLoad;
import com.apsilabs.meterwebapi.viewmodel.ActualsBlock;

@Repository
public interface ActualsBlockLoadRepository extends JpaRepository<ActualsBlockLoad, Long> {
    @Query(nativeQuery=true,value= "SELECT NEW com.apsilabs.meterwebapi.viewmodel.ActualsBlock(CONVERT(hour(rtc), CHAR(50)) as hours,CONVERT(date(rtc), CHAR(50)) as dates,CONVERT(IFNULL(avg(JSON_EXTRACT(JSON_UNQUOTE(data),'$.\\\"1012270255\\\"')),0),CHAR(50)) as voltage) from actuals_block_load  group by hours,dates order by dates,hours")
    public List<ActualsBlock> getActualsBlockLoad();

}
</code>```

I have an error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.apsilabs.meterwebapi.viewmodel.ActualsBlock(CONVERT(hour(rtc), CHAR(50)) as hou' at line 1

New Class:

```<code>package com.apsilabs.meterwebapi.viewmodel;

public class ActualsBlock {
    private String hours;
    private String dates;
    private String voltage;

    public String getHours() {
        return hours;
    }

    public void setHours(String hours) {
        this.hours = hours;
    }

    public String getDates() {
        return dates;
    }

    public void setDates(String dates) {
        this.dates = dates;
    }

    public String getVoltage() {
        return voltage;
    }

    public void setVoltage(String voltage) {
        this.voltage = voltage;
    }

    public ActualsBlock(String hours, String dates, String voltage) {
        super();
        this.hours = hours;
        this.dates = dates;
        this.voltage = voltage;
    }

    public ActualsBlock() {
        super();
    }

}
</code>```

答:
You have used nativeQuery=true and this query is not native.

```<code>SELECT NEW com.apsilabs.meterwebapi.viewmodel.ActualsBlock(CONVERT(hour(rtc), CHAR(50)) as hours,CONVERT(date(rtc), CHAR(50)) as dates,CONVERT(IFNULL(avg(JSON_EXTRACT(JSON_UNQUOTE(data),'$.\\\"1012270255\\\"')),0),CHAR(50)) as voltage) from actuals_block_load  group by hours,dates order by dates,hours.
</code>```

Why you are uisng NEW com.apsilabs.meterwebapi.viewmodel.ActualsBlock(CONVERT.... if is is a native query

Body:
Repository:

package com.apsilabs.meterwebapi.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import com.apsilabs.meterwebapi.model.ActualsBlockLoad;
import com.apsilabs.meterwebapi.viewmodel.ActualsBlock;

@Repository
public interface ActualsBlockLoadRepository extends JpaRepository<ActualsBlockLoad, Long> {
    @Query(nativeQuery=true,value= "SELECT NEW com.apsilabs.meterwebapi.viewmodel.ActualsBlock(CONVERT(hour(rtc), CHAR(50)) as hours,CONVERT(date(rtc), CHAR(50)) as dates,CONVERT(IFNULL(avg(JSON_EXTRACT(JSON_UNQUOTE(data),'$.\\\"1012270255\\\"')),0),CHAR(50)) as voltage) from actuals_block_load  group by hours,dates order by dates,hours")
    public List<ActualsBlock> getActualsBlockLoad();

}

I have an error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.apsilabs.meterwebapi.viewmodel.ActualsBlock(CONVERT(hour(rtc), CHAR(50)) as hou' at line 1

New Class:

package com.apsilabs.meterwebapi.viewmodel;

public class ActualsBlock {
    private String hours;
    private String dates;
    private String voltage;

    public String getHours() {
        return hours;
    }

    public void setHours(String hours) {
        this.hours = hours;
    }

    public String getDates() {
        return dates;
    }

    public void setDates(String dates) {
        this.dates = dates;
    }

    public String getVoltage() {
        return voltage;
    }

    public void setVoltage(String voltage) {
        this.voltage = voltage;
    }

    public ActualsBlock(String hours, String dates, String voltage) {
        super();
        this.hours = hours;
        this.dates = dates;
        this.voltage = voltage;
    }

    public ActualsBlock() {
        super();
    }

}

Body:
You have used nativeQuery=true and this query is not native.

SELECT NEW com.apsilabs.meterwebapi.viewmodel.ActualsBlock(CONVERT(hour(rtc), CHAR(50)) as hours,CONVERT(date(rtc), CHAR(50)) as dates,CONVERT(IFNULL(avg(JSON_EXTRACT(JSON_UNQUOTE(data),'$.\\\"1012270255\\\"')),0),CHAR(50)) as voltage) from actuals_block_load  group by hours,dates order by dates,hours.

Why you are uisng NEW com.apsilabs.meterwebapi.viewmodel.ActualsBlock(CONVERT.... if is is a native query


问:
Sniff Packets using Charles Proxy and Visual Code
I need to sniff packets that my node.js app is sending. I'm running Visual Code 1.36.1.

I in a corporate environment with all sorts of SSL proxies. I have Charles setup correctly, it sees Postman request. But requests made from my Visual code node.js app are not intercepted.

I'd be happy with a Charles set up or even a Visual Code menu.

The answers in How to view network traffic in Visual Studio don't seem to apply either because I'm on a Macintosh or because Visual Code has been updated since that question was answered.

答:
Adding environment variable

NODE_TLS_REJECT_UNAUTHORIZED=0

fixed it.

Took this answer from here:
Ignore invalid self-signed ssl certificate in node.js with https.request?


问:
Can I use the WP_List_Table class to render tables on a page?
I am currently using shortcodes to display a list of items obtained from a table and displaying it on a page of my website but since the list of information is very large, I want to add a page and in the future a small filtering menu for the records.

I found the WP_List_Table class in the worpdress documentation which, from what I understood, is a class that allows you to create tables with a list of elements but I have also read in some tutorials like this or this one in which they indicate that this class is used to create a list of elements but for the wordpress admin.

Can I use this class normally in the function my shortcode will render? Or is there any other class that is more appropriate, taking into account the functionalities that I wish to add in the future?

The function and the shortcode that I use to render the information is this:

```<code>function opt_menu_cactaceas_frontend() {

    global $wpdb;
    $tabla_cactaceas = $wpdb->prefix . 'cactaceas2';
    $aspirantes = $wpdb->get_results("SELECT * FROM $tabla_cactaceas");

    //echo '<table class="wp-list-table widefat fixed striped">';
    echo '<table>';
    echo '<thead><tr><th width="70%">Nombre Cientifico</th><th width="30%">Imagen</th></tr></thead>';
    echo '<tbody id="the-list">';

    foreach ( $aspirantes as $aspirante ) {

        $genero = esc_textarea($aspirante->genero);
        $especie = esc_textarea($aspirante->especie);
        $subespecie = esc_textarea($aspirante->subespecie);
        $autor = esc_textarea($aspirante->autor);

        if ( $subespecie == '' ):

            $nombreCactacea = "<i>$genero $especie</i> $autor";
        else:
            $nombreCactacea = "<i>$genero $especie</i> subsp. <i>$subespecie</i> $autor";

        endif;

        $imagen_cactus = wp_get_attachment_image( 263, 'thumbnail' );

        echo "<tr><td><a href='#' title='$motivacion'>$nombreCactacea</a></td><td>$imagen_cactus</td></tr>";
    }
    echo '</tbody></table>';
}

//funcion - agrega el shortcode en la pagina que se le llame
add_shortcode('srt_code_add_list_cactaceas', 'formulario_registro');
</code>```

The table so far is rendered like this:

答:
The WP_List_Table mainly used for WordPress backend. If you want to render the table and want to look as same as the backend, then make sure that you have included proper resources like the admin does (eg. list-tables).
Otherwise, you can use bootstrap data-table as well or you can try below plugin.

https://wordpress.org/plugins/custom-list-table-example/

Body:
I am currently using shortcodes to display a list of items obtained from a table and displaying it on a page of my website but since the list of information is very large, I want to add a page and in the future a small filtering menu for the records.

I found the WP_List_Table class in the worpdress documentation which, from what I understood, is a class that allows you to create tables with a list of elements but I have also read in some tutorials like this or this one in which they indicate that this class is used to create a list of elements but for the wordpress admin.

Can I use this class normally in the function my shortcode will render? Or is there any other class that is more appropriate, taking into account the functionalities that I wish to add in the future?

The function and the shortcode that I use to render the information is this:

function opt_menu_cactaceas_frontend() {

    global $wpdb;
    $tabla_cactaceas = $wpdb->prefix . 'cactaceas2';
    $aspirantes = $wpdb->get_results("SELECT * FROM $tabla_cactaceas");

    //echo '
';
    echo '
';
    echo '

Nombre Cientifico	Imagen

';
    echo '
';

    foreach ( $aspirantes as $aspirante ) {

        $genero = esc_textarea($aspirante->genero);
        $especie = esc_textarea($aspirante->especie);
        $subespecie = esc_textarea($aspirante->subespecie);
        $autor = esc_textarea($aspirante->autor);

        if ( $subespecie == '' ):

            $nombreCactacea = "$genero $especie $autor";
        else:
            $nombreCactacea = "$genero $especie subsp. $subespecie $autor";

        endif;

        $imagen_cactus = wp_get_attachment_image( 263, 'thumbnail' );

        echo "
$nombreCactacea	$imagen_cactus
";
    }
    echo '

';
}

//funcion - agrega el shortcode en la pagina que se le llame
add_shortcode('srt_code_add_list_cactaceas', 'formulario_registro');

The table so far is rendered like this:


问:
BFS in binary tree
I'm trying to write the codes for breadth-first search in binary tree. I've stored all the data in a queue, but I can't figure out how to travel to all nodes and consume all their children.

Here's my code in C:

```<code>void breadthFirstSearch (btree *bt, queue **q) {
   if (bt != NULL) {

      //store the data to queue if there is

      if (bt->left != NULL) enqueue (q, bt->left->data);
      if (bt->right != NULL) enqueue (q, bt->right->data);

      //recursive

      if (bt->left != NULL) breadthFirstSearch (bt->left, q);
      if (bt->right != NULL) breadthFirstSearch (bt->right, q);
   }
}
</code>```

I've already enqueued the root data, but it's still not working.
Can anyone point out my mistake?

答:
You are not doing a breadth first traversal here. Instead you are enqueuing the left and right element inside the queue and moving to the left subtree. You are exhausting the left subtree first and then moving on to the right subtree.

Write a procedure to enqueue the node instead.

```<code>void breadthFirstSearch (btree *bt, queue **q) {
 btree *tmpNode;
 enqueue(q,bt); //Assuming your root node has data

 while (!isempty(q)) //Assume isempty returns false when queue is not empty
 {
  tmpNode = dequeue(q);
  //Do whatever you want to do with tmpNode->data
  enqueue(tmpNode->left);
  enqueue(tmpNode->right);
  /* If this is a acyclic graph(tree) then this procedure should do, else you have to mark the nodes you have visited in-order not to end in a cycle */
 }

}

int main()
{
breadthFirstSearch(bt,q)
return 0
}
</code>```

Title: BFS in binary tree

Body:
I'm trying to write the codes for breadth-first search in binary tree. I've stored all the data in a queue, but I can't figure out how to travel to all nodes and consume all their children.

Here's my code in C:

void breadthFirstSearch (btree *bt, queue **q) {
   if (bt != NULL) {

      //store the data to queue if there is

      if (bt->left != NULL) enqueue (q, bt->left->data);
      if (bt->right != NULL) enqueue (q, bt->right->data);

      //recursive

      if (bt->left != NULL) breadthFirstSearch (bt->left, q);
      if (bt->right != NULL) breadthFirstSearch (bt->right, q);
   }
}

I've already enqueued the root data, but it's still not working.
Can anyone point out my mistake?

Body:
You are not doing a breadth first traversal here. Instead you are enqueuing the left and right element inside the queue and moving to the left subtree. You are exhausting the left subtree first and then moving on to the right subtree.

Write a procedure to enqueue the node instead.

void breadthFirstSearch (btree *bt, queue **q) {
 btree *tmpNode;
 enqueue(q,bt); //Assuming your root node has data

 while (!isempty(q)) //Assume isempty returns false when queue is not empty
 {
  tmpNode = dequeue(q);
  //Do whatever you want to do with tmpNode->data
  enqueue(tmpNode->left);
  enqueue(tmpNode->right);
  /* If this is a acyclic graph(tree) then this procedure should do, else you have to mark the nodes you have visited in-order not to end in a cycle */
 }

}

int main()
{
breadthFirstSearch(bt,q)
return 0
}


问:
jQuery does not find IMG component by its ID
I have a webpage which contains such code:

```<code><img class="img-qrcode" id="img_123.000.00.01"
     src="http://localhost:7777/data/code_img\123.000.00.01.png"
     alt="./data/code_img\123.000.00.01.png" style="display:none">
</code>```

I want to locate it with jQuery. For some reason jQuery does not find it by ID, with the code:

```<code>$("#img_123.000.00.01")
</code>```

The added screenshot shows that it returns an empty array.

Why does it not find the element with ID ?

答:
Using an attribute selector for id, you don't have to worry about escaping the class selector (.)

let img = $("img[id='img_123.000.00.01']");
console.log(img.attr('src'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="img-qrcode" id="img_123.000.00.01"
     src="http://localhost:7777/data/code_img\123.000.00.01.png"
     alt="./data/code_img\123.000.00.01.png" style="display:none"></code>```

Body:
I have a webpage which contains such code:

I want to locate it with jQuery. For some reason jQuery does not find it by ID, with the code:

$("#img_123.000.00.01")

The added screenshot shows that it returns an empty array.

Why does it not find the element with ID ?

Body:
Using an attribute selector for id, you don't have to worry about escaping the class selector (.)

let img = $("img[id='img_123.000.00.01']");
console.log(img.attr('src'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="img-qrcode" id="img_123.000.00.01"
     src="http://localhost:7777/data/code_img\123.000.00.01.png"
     alt="./data/code_img\123.000.00.01.png" style="display:none">


问:
CMake Error: Variables are set to NOTFOUND
I installed cuda first using cuda-repo-ubuntu1604-9-0-local_9.0.176-1_amd64.deb. Now I'm trying to install OpenCV 3.3.0 But i'm getting CMake Error:

```<code>CMake Error: The following variables are used in this project, but they are set to NOTFOUND.
Please set them or make sure they are set and tested correctly in the CMake files:
CUDA_nppi_LIBRARY (ADVANCED)
</code>```

And then a very long list of targets like so:

```<code>linked by target "opencv_cudev" in directory /home/jjros/opencv-3.3.0/modules/cudev
</code>```

I'm using this command to compile the library:

```<code>cmake

-D CMAKE_C_COMPILER=/usr/bin/gcc-5 \
-D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D WITH_CUDA=ON \
-D WITH_CUBLAS=ON \
-D WITH_TBB=ON \
-D WITH_V4L=ON \
-D WITH_QT=ON \
-D WITH_OPENGL=ON \
-D ENABLE_FAST_MATH=1 \
-D CUDA_FAST_MATH=1 \
-D WITH_CUBLAS=1 \
-D INSTALL_C_EXAMPLES=OFF \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D BUILD_SHARED_LIBS=ON \
-D WITH_GTK=ON \
-D BUILD_EXAMPLES=ON \
-D  CUDA_NVCC_FLAGS="-D_FORCE_INLINES" ..
</code>```

How can set my CMakeLists? What's going wrong?

答:
I met the same problem here when installing opencv4.2 with cuda.

My cmake version is 3.16.2 at first. However, this version doesn't support HTTP download so that you might meet the download fail problem.

So I re-installed my cmake to version 3.9, which support HTTP protocal and the download problem was solved.

But the new problem was the same as @ja_cpp mentioned above.
(CUDA_nppi_LIBRARY (ADVANCED) not found when cmake)

I followed @api55's method and modified FindCUDA.cmake and OpenCVDetectCUDA.cmake,
but the problem was still there.

And because I was installing opencv4.2 not opecv3 so I think that's why the modification didn't work.

The most tricky thing is, I updated back my cmake version to 3.16.2, and cmake again with non-modified files again, and it worked!

I used this command.

```<code>cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D INSTALL_PYTHON_EXAMPLES=ON -D INSTALL_C_EXAMPLES=OFF -D OPENCV_ENABLE_NONFREE=ON -D WITH_CUDA=ON -D WITH_CUDNN=ON -D OPENCV_DNN_CUDA=ON -D ENABLE_FAST_MATH=1 -D CUDA_FAST_MATH=1 -D CUDA_ARCH_BIN=6.1 -D WITH_CUBLAS=1 -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules -D HAVE_opencv_python3=ON -D PYTHON_EXECUTABLE=~/pengwenchen/anaconda3/envs/pytorch/bin/python -D BUILD_EXAMPLES=ON ..
</code>```

My environment: GPU-1080, cmake version 3.16.2, cuda version 10.0

Hope this answer could help those who are installing opencv4.2 with cuda. :)

Body:
I installed cuda first using cuda-repo-ubuntu1604-9-0-local_9.0.176-1_amd64.deb. Now I'm trying to install OpenCV 3.3.0 But i'm getting CMake Error:

CMake Error: The following variables are used in this project, but they are set to NOTFOUND.
Please set them or make sure they are set and tested correctly in the CMake files:
CUDA_nppi_LIBRARY (ADVANCED)

And then a very long list of targets like so:

linked by target "opencv_cudev" in directory /home/jjros/opencv-3.3.0/modules/cudev

I'm using this command to compile the library:

cmake

-D CMAKE_C_COMPILER=/usr/bin/gcc-5 \
-D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D WITH_CUDA=ON \
-D WITH_CUBLAS=ON \
-D WITH_TBB=ON \
-D WITH_V4L=ON \
-D WITH_QT=ON \
-D WITH_OPENGL=ON \
-D ENABLE_FAST_MATH=1 \
-D CUDA_FAST_MATH=1 \
-D WITH_CUBLAS=1 \
-D INSTALL_C_EXAMPLES=OFF \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D BUILD_SHARED_LIBS=ON \
-D WITH_GTK=ON \
-D BUILD_EXAMPLES=ON \
-D  CUDA_NVCC_FLAGS="-D_FORCE_INLINES" ..

How can set my CMakeLists? What's going wrong?

Body:
I met the same problem here when installing opencv4.2 with cuda.

My cmake version is 3.16.2 at first. However, this version doesn't support HTTP download so that you might meet the download fail problem.

So I re-installed my cmake to version 3.9, which support HTTP protocal and the download problem was solved.

But the new problem was the same as @ja_cpp mentioned above.
(CUDA_nppi_LIBRARY (ADVANCED) not found when cmake)

I followed @api55's method and modified FindCUDA.cmake and OpenCVDetectCUDA.cmake,
but the problem was still there.

And because I was installing opencv4.2 not opecv3 so I think that's why the modification didn't work.

The most tricky thing is, I updated back my cmake version to 3.16.2, and cmake again with non-modified files again, and it worked!

I used this command.

cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D INSTALL_PYTHON_EXAMPLES=ON -D INSTALL_C_EXAMPLES=OFF -D OPENCV_ENABLE_NONFREE=ON -D WITH_CUDA=ON -D WITH_CUDNN=ON -D OPENCV_DNN_CUDA=ON -D ENABLE_FAST_MATH=1 -D CUDA_FAST_MATH=1 -D CUDA_ARCH_BIN=6.1 -D WITH_CUBLAS=1 -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules -D HAVE_opencv_python3=ON -D PYTHON_EXECUTABLE=~/pengwenchen/anaconda3/envs/pytorch/bin/python -D BUILD_EXAMPLES=ON ..

My environment: GPU-1080, cmake version 3.16.2, cuda version 10.0

Hope this answer could help those who are installing opencv4.2 with cuda. :)


问:
Is there something in c# similar to java's @override annotation?
I've used the @Override in java and has come in quite handy. Is there anything similar in c#?</p>

答:
No, yes. It makesn o sesne to have an anotation because in C# there is an  override kkeyword in the langauge and the compiler warnds if you "hide" a method. So, either you say "new" or "override" directly as part of the method.

Java basically uses the annotation to hide a mistake in the langauge specifications.

Please read the language specificastions for C#. Completely.


问:
Changing Payment Method From In-App Purchase to Third-Party Gateway in Android and iOS
In my Android and iOS apps I'm using in_app purchase to unlock app content. Now I want to move to a third-party payment system (Braintree) that integrates with a web version of the app, and move from one-time payment to subscription (subscription will apply to an account that can be used cross-platform, and so can be used more widely than just in the app itself). However, I still need to use the old in-app purchase code to check for those users that purchased by the legacy method (those purchases will still be valid). My concern is that we are using the Google Play/App Store in-app purchase code, but without allowing new purchases using that method. Do you think we will run into issues due to this?</p>

答: No it won't get any problem, you can check Netflix & Spotify are also doing same</p>


问:
How to add external JS scripts to VueJS Components?
I've to use two external scripts for the payment gateways.

Right now both are put in the index.html file.

However, I don't want to load these files at the beginning itself.

The payment gateway is needed only in when user open a specific component (using router-view).

Is there anyway to achieve this?

Thanks.

答:
This can be simply done like this. </p>

```<code>  created() {
    var scripts = [
      "https://cloudfront.net/js/jquery-3.4.1.min.js",
      "js/local.js"
    ];
    scripts.forEach(script => {
      let tag = document.createElement("script");
      tag.setAttribute("src", script);
      document.head.appendChild(tag);
    });
  }
</code>```

Body:
This can be simply done like this.

  created() {
    var scripts = [
      "https://cloudfront.net/js/jquery-3.4.1.min.js",
      "js/local.js"
    ];
    scripts.forEach(script => {
      let tag = document.createElement("script");
      tag.setAttribute("src", script);
      document.head.appendChild(tag);
    });
  }


问:
Why doesn't this RegEx work with `git grep`?
The input is Unicode texts.

input

```<code>あいうえお
</code>```

command

Execution environment is macOS.

```<code>git grep '[い]' # -> matched
grep 'あ[い]う' # -> matched

git grep 'あ[い]う' # -> not matched
</code>```

Why doesn't the RegEx work in git grep when normal grep is works?

environment

OS: macOS

Locale: ja_JP.UTF-8

Input file encoding is 'UTF-8'.

答:
All of my experiments show that git grep uses ASCII-8BIT encoding:

```<code>git grep 'あ[い][い][い]う'
# matches (because \xE3, \x81 and \x84 match [\xe3\x81\x84])
git grep 'あ[か]'
# matches (because \xE3, the first byte of い, matches [\xe3\x81\x8b])
</code>```

The last one even explicitly shows you matched bytes.

Since character class ([...]) is the only construct in RegExp that considers individual characters and not strings, and since all character class regexps can trivially be rewritten into alternation regexps, here's a workaround: if regexp were '上[げが]る', you can write

```<code>git grep '上\(げ\|が\)る'  # (alternation instead of character class)
git grep -E '上(げ|が)る'  # (prettier with extended regexp syntax)
</code>```

Body:
The input is Unicode texts.

input

あいうえお

command

Execution environment is macOS.

git grep '[い]' # -> matched
grep 'あ[い]う' # -> matched

git grep 'あ[い]う' # -> not matched

Why doesn't the RegEx work in git grep when normal grep is works?

environment

OS: macOS

Locale: ja_JP.UTF-8

Input file encoding is 'UTF-8'.

Body:
All of my experiments show that git grep uses ASCII-8BIT encoding:

git grep 'あ[い][い][い]う'
# matches (because \xE3, \x81 and \x84 match [\xe3\x81\x84])
git grep 'あ[か]'
# matches (because \xE3, the first byte of い, matches [\xe3\x81\x8b])

The last one even explicitly shows you matched bytes.

Since character class ([...]) is the only construct in RegExp that considers individual characters and not strings, and since all character class regexps can trivially be rewritten into alternation regexps, here's a workaround: if regexp were '上[げが]る', you can write

git grep '上\(げ\|が\)る'  # (alternation instead of character class)
git grep -E '上(げ|が)る'  # (prettier with extended regexp syntax)


问:
add a SortedSet directly to a Map
i want to add a SortedSet directly into a map.

my Map looks as follows:

```<code>Map<Integer, SortedSet<String>> categorizedResult = new HashMap<>();
</code>```

currently i'm adding the SortedSet as follows:

```<code>SortedSet<String> sSOne = new TreeSet<>();
SortedSet<String> sSTwo = new TreeSet<>();

sSOne.add("Some String in Set one");
sSTwo.add("Some String in Set two");

categorizedResult.put(1, sSOne);
categorizedResult.put(2, sSTwo);

// return Map or something...

</code>```

Now imagine a Map with atleast 10 SortedSets. Obviously the process of adding all of these 10 SortedSets gets confusing and annoying quite fast.
Is there a way to directly add the SortedSet into the Map without the more or less redundant SortedSets(sSOne, sSTwo)? Overwriting the previous value is not desired. The above code is executed in a loop.
Im thinking of something like this:

```<code>Map<Integer, SortedSet<String>> categorizedResult = new HashMap<>();

categorizedResult.put(1, addDirectlyToMap("Some String in Set one");
categorizedResult.put(2, addDirectlyToMap("Some String in Set two");

</code>```

Thanks in advance

答:
You can write something like this:

```<code>categorizedResult.put(1, new TreeSet<String>(Set.of("Some String in Set one")));
</code>```

Or, if you're using an older Java version that doesn't have Set.of():

```<code>categorizedResult.put(1, new TreeSet<String>(Arrays.asList("Some String in Set one")));
</code>```

To avoid overwriting an existing value, use computeIfAbsent():

```<code>categorizedResult.computeIfAbsent(1, x -> new TreeSet<String>()).add("Some String in Set one");
categorizedResult.computeIfAbsent(1, x -> new TreeSet<String>()).add("Another String in Set one");
</code>```

This will result in a Map having a single key (1) mapped to a SortedSet having two elements.

Title: add a SortedSet directly to a Map

Body:
i want to add a SortedSet directly into a map.

my Map looks as follows:

Map<Integer, SortedSet<String>> categorizedResult = new HashMap<>();

currently i'm adding the SortedSet as follows:

SortedSet<String> sSOne = new TreeSet<>();
SortedSet<String> sSTwo = new TreeSet<>();

sSOne.add("Some String in Set one");
sSTwo.add("Some String in Set two");

categorizedResult.put(1, sSOne);
categorizedResult.put(2, sSTwo);

// return Map or something...

Now imagine a Map with atleast 10 SortedSets. Obviously the process of adding all of these 10 SortedSets gets confusing and annoying quite fast.
Is there a way to directly add the SortedSet into the Map without the more or less redundant SortedSets(sSOne, sSTwo)? Overwriting the previous value is not desired. The above code is executed in a loop.
Im thinking of something like this:

Map<Integer, SortedSet<String>> categorizedResult = new HashMap<>();

categorizedResult.put(1, addDirectlyToMap("Some String in Set one");
categorizedResult.put(2, addDirectlyToMap("Some String in Set two");

Thanks in advance

Body:
You can write something like this:

categorizedResult.put(1, new TreeSet<String>(Set.of("Some String in Set one")));

Or, if you're using an older Java version that doesn't have Set.of():

categorizedResult.put(1, new TreeSet<String>(Arrays.asList("Some String in Set one")));

To avoid overwriting an existing value, use computeIfAbsent():

categorizedResult.computeIfAbsent(1, x -> new TreeSet<String>()).add("Some String in Set one");
categorizedResult.computeIfAbsent(1, x -> new TreeSet<String>()).add("Another String in Set one");

This will result in a Map having a single key (1) mapped to a SortedSet having two elements.


问:
Insert json file into mongodb
I am new to MongoDB. After installing MongoDB in Windows I am trying to insert a simple json file using the following command:

```<code>C:\>mongodb\bin\mongoimport --db test --collection docs < example2.json
</code>```

I am getting the following error:

```<code>connected to: 127.0.0.1
Fri Oct 18 09:05:43.749 exception:BSON representation of supplied JSON is too large: code FailedToParse: FailedToParse: Field name expected: offset:43
Fri Oct 18 09:05:43.750
Fri Oct 18 09:05:43.750 exception:BSON representation of supplied JSON is too large: code FailedToParse: FailedToParse: Expecting '{': offset:0
Fri Oct 18 09:05:43.751
Fri Oct 18 09:05:43.751 exception:BSON representation of supplied JSON is too large: code FailedToParse: FailedToParse: Field name expected: offset:42
Fri Oct 18 09:05:43.751
Fri Oct 18 09:05:43.751 exception:BSON representation of supplied JSON is too large: code FailedToParse: FailedToParse: Expecting '{': offset:0
Fri Oct 18 09:05:43.751
Fri Oct 18 09:05:43.752 exception:BSON representation of supplied JSON is too large: code FailedToParse: FailedToParse: Field name expected: offset:44
Fri Oct 18 09:05:43.752
Fri Oct 18 09:05:43.752 exception:BSON representation of supplied JSON is too large: code FailedToParse: FailedToParse: Expecting '{': offset:0
Fri Oct 18 09:05:43.752
Fri Oct 18 09:05:43.752 check 0 0
Fri Oct 18 09:05:43.752 imported 0 objects
Fri Oct 18 09:05:43.752 ERROR: encountered 6 error(s)s
</code>```

example2.json

```<code>{"FirstName": "Bruce", "LastName": "Wayne",
"Email": "bwayne@Wayneenterprises.com"}
{"FirstName": "Lucius", "LastName": "Fox",
"Email": "lfox@Wayneenterprises.com"}
{"FirstName": "Dick", "LastName": "Grayson",
"Email": "dgrayson@Wayneenterprises.com"}
</code>```

What do I need to do to import new json file into mongodb?

答:
Open command prompt separately
and check:

C:\mongodb\bin\mongoimport --db db_name --collection collection_name< filename.json

Title: Insert json file into mongodb

Body:
I am new to MongoDB. After installing MongoDB in Windows I am trying to insert a simple json file using the following command:

C:\>mongodb\bin\mongoimport --db test --collection docs < example2.json

I am getting the following error:

connected to: 127.0.0.1
Fri Oct 18 09:05:43.749 exception:BSON representation of supplied JSON is too large: code FailedToParse: FailedToParse: Field name expected: offset:43
Fri Oct 18 09:05:43.750
Fri Oct 18 09:05:43.750 exception:BSON representation of supplied JSON is too large: code FailedToParse: FailedToParse: Expecting '{': offset:0
Fri Oct 18 09:05:43.751
Fri Oct 18 09:05:43.751 exception:BSON representation of supplied JSON is too large: code FailedToParse: FailedToParse: Field name expected: offset:42
Fri Oct 18 09:05:43.751
Fri Oct 18 09:05:43.751 exception:BSON representation of supplied JSON is too large: code FailedToParse: FailedToParse: Expecting '{': offset:0
Fri Oct 18 09:05:43.751
Fri Oct 18 09:05:43.752 exception:BSON representation of supplied JSON is too large: code FailedToParse: FailedToParse: Field name expected: offset:44
Fri Oct 18 09:05:43.752
Fri Oct 18 09:05:43.752 exception:BSON representation of supplied JSON is too large: code FailedToParse: FailedToParse: Expecting '{': offset:0
Fri Oct 18 09:05:43.752
Fri Oct 18 09:05:43.752 check 0 0
Fri Oct 18 09:05:43.752 imported 0 objects
Fri Oct 18 09:05:43.752 ERROR: encountered 6 error(s)s

example2.json

{"FirstName": "Bruce", "LastName": "Wayne",
"Email": "bwayne@Wayneenterprises.com"}
{"FirstName": "Lucius", "LastName": "Fox",
"Email": "lfox@Wayneenterprises.com"}
{"FirstName": "Dick", "LastName": "Grayson",
"Email": "dgrayson@Wayneenterprises.com"}

What do I need to do to import new json file into mongodb?


问:
My player is going through walls(Even tho they are rigid bodies) and the script below doesn't work(C#)
Ok, so i wanna make a flappy birds-like game and i'm a noob, i have almost no experience in unity and i started learning c# and programming at all 1 week ago....
so don't expect much from me pls
So, my rigid body is going through walls even tho i have the component rigid body 2D on my walls
And i wanna make a script that changes your scene to main menu if you collide with a wall and it looks like this:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
 public class SceneSwitch : MonoBehaviour {
   void OnTriggerEnter(Collider other){
     SceneManager.LoadScene(0);
    }

 }

    i don't have any error but it just doesn't work.
</code>```

(Srry about the spacing, i'm new to the platform and i don't really know how to use it)

答:
You said you are using a

rigid body 2D

Make sure all your colliders are XYCollider2D and then you would also rather want to use the 2D version OnTriggerEnter2D!

```<code>public class SceneSwitch : MonoBehaviour
{
    private void OnTriggerEnter2D(Collider2D other)
    {
        SceneManager.LoadScene(0);
    }
}
</code>```

In Unity the 3D and 2D Physics are completely separated engines and do not interact in any way. So the Physics2D know nothing about the 3D message OnTriggerEnter but only the 2D message OnTriggerEnter2D.

Body:
Ok, so i wanna make a flappy birds-like game and i'm a noob, i have almost no experience in unity and i started learning c# and programming at all 1 week ago....
so don't expect much from me pls
So, my rigid body is going through walls even tho i have the component rigid body 2D on my walls
And i wanna make a script that changes your scene to main menu if you collide with a wall and it looks like this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
 public class SceneSwitch : MonoBehaviour {
   void OnTriggerEnter(Collider other){
     SceneManager.LoadScene(0);
    }

 }

    i don't have any error but it just doesn't work.

(Srry about the spacing, i'm new to the platform and i don't really know how to use it)

Body:
You said you are using a

rigid body 2D

Make sure all your colliders are XYCollider2D and then you would also rather want to use the 2D version OnTriggerEnter2D!

public class SceneSwitch : MonoBehaviour
{
    private void OnTriggerEnter2D(Collider2D other)
    {
        SceneManager.LoadScene(0);
    }
}

In Unity the 3D and 2D Physics are completely separated engines and do not interact in any way. So the Physics2D know nothing about the 3D message OnTriggerEnter but only the 2D message OnTriggerEnter2D.


问:
Not able to Switch Layout to RTL when arabic text is sent over Push Notification in Android
So i'm trying to send Arabic Text over push notification, i have an image and a textview in a remoteview, when i send the text in english it works perfectly, but if i send it as arabic, then i'm able to receive the text but i'm not able to show it in RTL form, i've enabled RTL in manifest and also used

```<code>android:autoMirrored="true"
</code>```

but for some reason, the text aligns itself onto the right but the image remains on the left itself, which shouldnt be the case

this is my layout, any help would be deeply appreciated

```<code>    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="4dp">

   <ImageView
     android:id="@+id/big_icon"
     android:layout_width="40dp"
     android:layout_height="40dp"
     android:paddingBottom="1dp"
     android:autoMirrored="true"
     android:layout_gravity="center_vertical"
     android:paddingLeft="2dp"
     android:paddingRight="2dp"
     android:src="@mipmap/icon"/>

   <TextView
     android:id="@+id/content_title"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:maxLines="2"
     android:layout_toRightOf="@+id/big_icon"
     android:layout_gravity="center_vertical"
     android:ellipsize="end"
     android:text="Notification Sample App"
     android:textAppearance="@style/TextAppearance.Compat.Notification.Title"/>

</RelativeLayout>
</code>```

This is what i'm getting

答: use this inside textview android:textAlignment="start"</p>

Body:
So i'm trying to send Arabic Text over push notification, i have an image and a textview in a remoteview, when i send the text in english it works perfectly, but if i send it as arabic, then i'm able to receive the text but i'm not able to show it in RTL form, i've enabled RTL in manifest and also used

android:autoMirrored="true"

but for some reason, the text aligns itself onto the right but the image remains on the left itself, which shouldnt be the case

this is my layout, any help would be deeply appreciated

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="4dp">

   <ImageView
     android:id="@+id/big_icon"
     android:layout_width="40dp"
     android:layout_height="40dp"
     android:paddingBottom="1dp"
     android:autoMirrored="true"
     android:layout_gravity="center_vertical"
     android:paddingLeft="2dp"
     android:paddingRight="2dp"
     android:src="@mipmap/icon"/>

   <TextView
     android:id="@+id/content_title"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:maxLines="2"
     android:layout_toRightOf="@+id/big_icon"
     android:layout_gravity="center_vertical"
     android:ellipsize="end"
     android:text="Notification Sample App"
     android:textAppearance="@style/TextAppearance.Compat.Notification.Title"/>

</RelativeLayout>

This is what i'm getting


问:
Type Not Found In Class When Inside Switch
I'm using a class like an enum because my entries need a custom string representation:

```<code>using System.Collections.Generic;

namespace MyProject
{
    internal class Food
    {
        private string _value = "";

        private Food(string value)
        {
            _value = value;
        }

        public override string ToString()
        {
            return _value;
        }

        internal static Food RedApple = new Food("red_apple");
        internal static Food YellowBanana = new Food("yellow_banana");
        internal static Food GreenMango = new Food("green_mango");
    }
}
</code>```

I can use the static fields like Food.RedApple just fine:

```<code>if (str == Food.RedApple.ToString())
    Console.WriteLine("apple");
else if (str == Food.YellowBanana.ToString())
    Console.WriteLine("banana");
else if (str == Food.GreenMango.ToString())
    Console.WriteLine("mango");
else
    Console.WriteLine("unknown");
</code>```

However, when I use them inside switch statements like so:

```<code>using System;

namespace MyProject
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "red_apple";

            switch (str)
            {
                case Food.RedApple.ToString():
                    Console.WriteLine("apple");
                    break;
                case Food.YellowBanana.ToString():
                    Console.WriteLine("banana");
                    break;
                case Food.GreenMango.ToString():
                    Console.WriteLine("mango");
                    break;
                default:
                    Console.WriteLine("unknown");
                    break;
            }
        }
    }
}
</code>```

I get the following error:

The type name RedApple does not exist in the type Food [MyProject]

What exactly is going on here, and does this mean that I can't use my class inside switch statements?

答:
Started from c# 7.0 switch statement has become more powerful and covers a lot of scenarios.

But to answer your question in shortest way you need to put a constant value in your case field. You can try putting a variable or another string property from Food inside switch statement, but it won't work either because switch is looking for a constant value.

You can look at the microsoft docs on switch statement.

Body:
I'm using a class like an enum because my entries need a custom string representation:

using System.Collections.Generic;

namespace MyProject
{
    internal class Food
    {
        private string _value = "";

        private Food(string value)
        {
            _value = value;
        }

        public override string ToString()
        {
            return _value;
        }

        internal static Food RedApple = new Food("red_apple");
        internal static Food YellowBanana = new Food("yellow_banana");
        internal static Food GreenMango = new Food("green_mango");
    }
}

I can use the static fields like Food.RedApple just fine:

if (str == Food.RedApple.ToString())
    Console.WriteLine("apple");
else if (str == Food.YellowBanana.ToString())
    Console.WriteLine("banana");
else if (str == Food.GreenMango.ToString())
    Console.WriteLine("mango");
else
    Console.WriteLine("unknown");

However, when I use them inside switch statements like so:

using System;

namespace MyProject
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "red_apple";

            switch (str)
            {
                case Food.RedApple.ToString():
                    Console.WriteLine("apple");
                    break;
                case Food.YellowBanana.ToString():
                    Console.WriteLine("banana");
                    break;
                case Food.GreenMango.ToString():
                    Console.WriteLine("mango");
                    break;
                default:
                    Console.WriteLine("unknown");
                    break;
            }
        }
    }
}

I get the following error:

The type name RedApple does not exist in the type Food [MyProject]

What exactly is going on here, and does this mean that I can't use my class inside switch statements?


问:
Cron job not running python
I tried to get cron to run a python file but it doesn't seem to run. The command in cron is:

```<code>24 21 * * * python /mnt/c/Users/saifl/git/StaffTrainingLog/automate.py
</code>```

And the following appeared in the log:

```<code>Feb 16 21:24:01 MSI CRON[3839]: (slatifi) CMD (python /mnt/c/Users/saifl/git/StaffTrainingLog/automate.py)
</code>```

However, it doesn't actually run the code. When I run the command in backets above it works with no issues. Please advise.

Update (after Romeo's responce):

I have now move the command to a script (automate_script):

```<code>#!/bin/bash
source ~/.bashrc
cd /mnt/c/Users/saifl/git/StaffTrainingLog
/usr/bin/python3 automate.py
</code>```

And I now have the following in Crontab:

```<code>50 14 * * * /mnt/c/Users/saifl/git/StaffTrainingLog/automate_script
</code>```

And when running /mnt/c/Users/saifl/git/StaffTrainingLog/automate_script in the command line it works, however, it does run with cron as it appears in the log but nothing happens.

答:
There are few things to do when you execute such script. And its better to create dedicated script for this purpose.

```<code>#!/bin/bash
source ~/.bashrc
cd /mnt/c/Users/saifl/git/StaffTrainingLog
/path/to/python  automate.py
</code>```

Source the .bashrc to get your environment settings

cd to directory where the script is located

run it with absolute path to python

and run the above script in cron

```<code>24 21 * * * /path/to/the/script
</code>```

Do not forget to make the script executable

Title: Cron job not running python

Body:
I tried to get cron to run a python file but it doesn't seem to run. The command in cron is:

24 21 * * * python /mnt/c/Users/saifl/git/StaffTrainingLog/automate.py

And the following appeared in the log:

Feb 16 21:24:01 MSI CRON[3839]: (slatifi) CMD (python /mnt/c/Users/saifl/git/StaffTrainingLog/automate.py)

However, it doesn't actually run the code. When I run the command in backets above it works with no issues. Please advise.

Update (after Romeo's responce):

I have now move the command to a script (automate_script):

#!/bin/bash
source ~/.bashrc
cd /mnt/c/Users/saifl/git/StaffTrainingLog
/usr/bin/python3 automate.py

And I now have the following in Crontab:

50 14 * * * /mnt/c/Users/saifl/git/StaffTrainingLog/automate_script

And when running /mnt/c/Users/saifl/git/StaffTrainingLog/automate_script in the command line it works, however, it does run with cron as it appears in the log but nothing happens.

Body:
There are few things to do when you execute such script. And its better to create dedicated script for this purpose.

#!/bin/bash
source ~/.bashrc
cd /mnt/c/Users/saifl/git/StaffTrainingLog
/path/to/python  automate.py

Source the .bashrc to get your environment settings

cd to directory where the script is located

run it with absolute path to python

and run the above script in cron

24 21 * * * /path/to/the/script

Do not forget to make the script executable


答:
You need to check if there is an existing Set already present.

```<code>categorizedResult.put(1, new TreeSet<String>() {{
  addAll(categorizedResult.getOrDefault(1, new TreeSet<>()));
  add("some value");
}});
</code>```

Or more at a time

```<code>categorizedResult.put(1, new TreeSet<String>() {{
  addAll(categorizedResult.getOrDefault(1, new TreeSet<>()));
  add("some value 1");
  add("some value 2");
}});
</code>```

My initial response which is NOT working as a one liner:

```<code>categorizedResult.put(1, categorizedResult.getOrDefault(1, new TreeSet<>()).add("some value"))
</code>```

But I recommend @Eran's solution:

```<code>categorizedResult.computeIfAbsent(1, x -> new TreeSet<String>()).add("Some String in Set one");
</code>```

Title: add a SortedSet directly to a Map

Body:
You need to check if there is an existing Set already present.

categorizedResult.put(1, new TreeSet<String>() {{
  addAll(categorizedResult.getOrDefault(1, new TreeSet<>()));
  add("some value");
}});

Or more at a time

categorizedResult.put(1, new TreeSet<String>() {{
  addAll(categorizedResult.getOrDefault(1, new TreeSet<>()));
  add("some value 1");
  add("some value 2");
}});

My initial response which is NOT working as a one liner:

categorizedResult.put(1, categorizedResult.getOrDefault(1, new TreeSet<>()).add("some value"))

But I recommend @Eran's solution:

categorizedResult.computeIfAbsent(1, x -> new TreeSet<String>()).add("Some String in Set one");


问:
Returning multiple sites' HTTP status code
This component below is meant to return the HTTP status code for different sites based on the data.json file. It currently shows all sites as "Live" even though the second one is non-existent and therefore should show "404", "503" or "523". HTTP status code 200 is the status for the "Live" sites. I am trying to achieve a different message for each status code in the response.

ExampleComponent.vue

<template>

          URL
          Status

          {{ site.url }}
          Live
          404
          503
          523

</template>

```

<p><em>data.json</em></p>

```[
  {
    "name": "",
    "url": "www.google.com",
    "port": 80
  },
  {
    "name": "",
    "url": "www.foo.com",
    "port": 443
  }
]
```

答:
The problem is likely in the conditions of v-if and v-else-if, which is incorrectly using an assignment operator (=) instead of an equality operator.

It's currently setting site.status to a non-zero value and then evaluating the result. Since the result of the first expression is 200, the first condition is always truthy, causing the template to render Live.

Live
404
503
523
```

<p>The correct equality operator is <code>==</code> or <code>===</code>:</p>

<pre class="lang-html prettyprint-override"><code><td v-if="site.status == 200"><span class="label label-success">Live</span>
<td v-else-if="site.status == 404"><span class="label label-success">404</span></td>
<td v-else-if="site.status == 503"><span class="label label-success">503</span></td>
<td v-else-if="site.status == 523"><span class="label label-success">523</span></td>
</code>```

Body:
This component below is meant to return the HTTP status code for different sites based on the data.json file. It currently shows all sites as "Live" even though the second one is non-existent and therefore should show "404", "503" or "523". HTTP status code 200 is the status for the "Live" sites. I am trying to achieve a different message for each status code in the response.

ExampleComponent.vue

<template>

          URL
          Status

          {{ site.url }}
          Live
          404
          503
          523

</template>

data.json

[
  {
    "name": "",
    "url": "www.google.com",
    "port": 80
  },
  {
    "name": "",
    "url": "www.foo.com",
    "port": 443
  }
]

Body:
The problem is likely in the conditions of v-if and v-else-if, which is incorrectly using an assignment operator (=) instead of an equality operator.

It's currently setting site.status to a non-zero value and then evaluating the result. Since the result of the first expression is 200, the first condition is always truthy, causing the template to render Live.

<td v-if="site.status = 200"><span class="label label-success">Live</span>
<td v-else-if="site.status = 404"><span class="label label-success">404</span></td>
<td v-else-if="site.status = 503"><span class="label label-success">503</span></td>
<td v-else-if="site.status = 523"><span class="label label-success">523</span></td>

The correct equality operator is == or ===:

<td v-if="site.status == 200"><span class="label label-success">Live</span>
<td v-else-if="site.status == 404"><span class="label label-success">404</span></td>
<td v-else-if="site.status == 503"><span class="label label-success">503</span></td>
<td v-else-if="site.status == 523"><span class="label label-success">523</span></td>


问:
How to save last components changes?
There is component that is activated by condition ngif.

Use can perform activity, for example open menu, set active element or just write text inside textarea.

After that user leaves this component to another ngif.

After time user returns to previous component.

How to restore last activity, components changes to continue work?

I know, it might be solved using service, but mu component has it's own logic too.

答:
with ngIf the component is destroyed and created based on the value. I think you should save the data in the host component in OnDestroy hook of the component in question, using @output and handling this event in host component, and use @input to pass in data to the component when you need to.

ParentComponent HTML

```<code><app-child-component *ngIf="showThisComponent == 'comp1' " (saveData)="onSaveData($event)" [showData]="showThisData[comp1]"
/>
</code>```

ParentComponent .ts

```<code>onSomeAction() {
    this.showThisComponent = 'comp1';
}

onSaveData(data) {
    this.showThisData[comp1] = data;
}
</code>```

ChildComponent .ts

```<code>@Input() showData: any;
@Output() saveData: new EventEmitter<any>();

ngOnDestroy() {
    this.saveData.emit(data);
}
</code>```

You could do something on these lines I hope you get the idea.

Title: How to save last components changes?

Body:
with ngIf the component is destroyed and created based on the value. I think you should save the data in the host component in OnDestroy hook of the component in question, using @output and handling this event in host component, and use @input to pass in data to the component when you need to.

ParentComponent HTML

<app-child-component *ngIf="showThisComponent == 'comp1' " (saveData)="onSaveData($event)" [showData]="showThisData[comp1]"
/>

ParentComponent .ts

onSomeAction() {
    this.showThisComponent = 'comp1';
}

onSaveData(data) {
    this.showThisData[comp1] = data;
}

ChildComponent .ts

@Input() showData: any;
@Output() saveData: new EventEmitter<any>();

ngOnDestroy() {
    this.saveData.emit(data);
}

You could do something on these lines I hope you get the idea.


问:
How do you call a JSON web service, that requires basic authentication, using jQuery?
I am somewhat novice at javascript, but I am trying to call a JSON web service that require basic authentication using jQuery (or anything that would work really). </p>

<p>I've not been able to come up with any real answers on Google. Is what I am trying to do possible? </p>

答:
Simple.

In asp.net create a reference to the service. Create a web page (with no UI) and make multiple methods in the code behind that are "wrappers" for that service (in C#/VB.NET). Decorate the methods with [WebMethod] and set the WebMethod's Serialization to JSON.

Alternatively you can do the same with any other language (pearl, php, whatever) by making a wrapper for the json web service.

The reason you need that wrapper is because that way you avoid the cross-site scripting... limitations in JS. Also if your page is served over HTTPS, than your JS calls to your wrapper will also be over HTTPS thus not having to worry about security.

Your JS wrapper will be taking care of negotiating the connection, authentication, etc...

The javascript within your other pages can post to the methods in this page as:

```<code>$.post('pagename/method_name', {data:value}, callback(){

});
</code>```

or $.post, $.get, $.ajax... will all work.

Body:
I am somewhat novice at javascript, but I am trying to call a JSON web service that require basic authentication using jQuery (or anything that would work really).

I've not been able to come up with any real answers on Google. Is what I am trying to do possible?

Body:
Simple.

In asp.net create a reference to the service. Create a web page (with no UI) and make multiple methods in the code behind that are "wrappers" for that service (in C#/VB.NET). Decorate the methods with [WebMethod] and set the WebMethod's Serialization to JSON.

Alternatively you can do the same with any other language (pearl, php, whatever) by making a wrapper for the json web service.

The reason you need that wrapper is because that way you avoid the cross-site scripting... limitations in JS. Also if your page is served over HTTPS, than your JS calls to your wrapper will also be over HTTPS thus not having to worry about security.

Your JS wrapper will be taking care of negotiating the connection, authentication, etc...

The javascript within your other pages can post to the methods in this page as:

$.post('pagename/method_name', {data:value}, callback(){

});

or $.post, $.get, $.ajax... will all work.


问:
How can we have Flash of Unstyled Content if CSS is render blocking?
I have heard these two statements:

CSS is render-blocking

We can have Flash of Unstyled Content

now the second statement needs rendering and if CSS blocks rendering how can we have such unstyled content?

PS: tag javascript added to increase the reach of the question to the web community

答:
You can control CSS Block Render-Blocking

Let's do the merge all the css code in one css file.

Always put your stylessheets in the doucment Head using the link tag

Below Example


答:
When some special symbols are in the jquery selector, you need to add 『\\』

console.log($("#img_123\\.000\\.00\\.01"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Title of the document</title>
</head>

<body>
  <img class="img-qrcode" id="img_123.000.00.01" src="http://localhost:7777/data/code_img\123.000.00.01.png" alt="./data/code_img\123.000.00.01.png" style="display:none">
</body>

</html></code>```

Title: jQuery does not find IMG component by its ID

Body:
I have a webpage which contains such code:

I want to locate it with jQuery. For some reason jQuery does not find it by ID, with the code:

$("#img_123.000.00.01")

The added screenshot shows that it returns an empty array.

Why does it not find the element with ID ?

Body:
When some special symbols are in the jquery selector, you need to add 『\\』

console.log($("#img_123\\.000\\.00\\.01"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Title of the document</title>
</head>

<body>
  <img class="img-qrcode" id="img_123.000.00.01" src="http://localhost:7777/data/code_img\123.000.00.01.png" alt="./data/code_img\123.000.00.01.png" style="display:none">
</body>

</html>


问:
What's the pythonic way to set class variables?
perhaps I'm asking the wrong question.  I have code like this:

```<code>class ExpressionGrammar(Grammar):
  def __init__(self, nonterminals, terminals, macros, rules, precedence, nonterminal_name = '_expr'):
    self.nonterminals = nonterminals
    self.terminals = terminals
    self.rules = rules
    self.macros = macros
    self.precedence = precedence
    self.nonterminal = nonterminal
</code>```

and I find it redundant to always have to to self.x = x.  I know python tries to avoid repetition, so what would be the correct way to do something like this?

答:
You could always do:</p>

```<code>self.__dict__.update(locals())
</code>```

Body:
perhaps I'm asking the wrong question.  I have code like this:

class ExpressionGrammar(Grammar):
  def __init__(self, nonterminals, terminals, macros, rules, precedence, nonterminal_name = '_expr'):
    self.nonterminals = nonterminals
    self.terminals = terminals
    self.rules = rules
    self.macros = macros
    self.precedence = precedence
    self.nonterminal = nonterminal

and I find it redundant to always have to to self.x = x.  I know python tries to avoid repetition, so what would be the correct way to do something like this?

Body:
You could always do:

self.__dict__.update(locals())


问:
Overlap raw pointer into unique_ptr and again assign it to unique_ptr
Please let me know which constructor of unique_ptr is invoked below and why?..
I am assuming that 'move constructor' is called here but I am a bit confused as in how it can be called, as the argument to move constructor requires 'r value reference' but her I am not using any r-values.</p>

```<code>int* func1()
{
   int* p = new int();
   *p = 20;
   return p;
}

int main()
{
   std::unique_ptr<int> p = std::unique_ptr<int>(func1());
   return 0;
}
</code>```

答:
This code does not call the move constructor of std::unique_ptr. It calls a specific version of the constructor in which a unique_ptr<T> is constructed from T*.

In the documentation of std::unique_ptr's constructor, this is case number (2) ( pointer is an alias for T*, so in our case int*)

The move constructor can only be called with a r-value reference to an instance of the same class.
This means std::unique_ptr<int> can only be move-constructed by passing it a  std::unique_ptr<int>&&.

Here's an example of a code that calls the move constructor, using the return value from a function.

```<code>std::unique_ptr<int> func() {
    return std::unique_ptr<int>(new int);
}

int main() {
   std::unique_ptr<int> my_ptr(func()); // Move-constructor called here
   return 0
}
</code>```

Another example would use std::move

```<code>int main() {
   std::unique_ptr<int> ptr1 = std::make_unique<int>(20);
   std::unique_ptr<int> ptr2 (std::move(ptr1)); // Move constructor called here

   // At this point ptr1 has been moved from and is now nullptr
   std::cout << ptr1.get() << " " <<ptr2.get()<< " " << *ptr2 <<std::endl;
   return 0
}
</code>```

You can see it run live here. It will print 0, the address of p2 and 20.

Body:
Please let me know which constructor of unique_ptr is invoked below and why?..
I am assuming that 'move constructor' is called here but I am a bit confused as in how it can be called, as the argument to move constructor requires 'r value reference' but her I am not using any r-values.

int* func1()
{
   int* p = new int();
   *p = 20;
   return p;
}

int main()
{
   std::unique_ptr<int> p = std::unique_ptr<int>(func1());
   return 0;
}

Body:
This code does not call the move constructor of std::unique_ptr. It calls a specific version of the constructor in which a unique_ptr<T> is constructed from T*.

In the documentation of std::unique_ptr's constructor, this is case number (2) ( pointer is an alias for T*, so in our case int*)

The move constructor can only be called with a r-value reference to an instance of the same class.
This means std::unique_ptr<int> can only be move-constructed by passing it a  std::unique_ptr<int>&&.

Here's an example of a code that calls the move constructor, using the return value from a function.

std::unique_ptr<int> func() {
    return std::unique_ptr<int>(new int);
}

int main() {
   std::unique_ptr<int> my_ptr(func()); // Move-constructor called here
   return 0
}

Another example would use std::move

int main() {
   std::unique_ptr<int> ptr1 = std::make_unique<int>(20);
   std::unique_ptr<int> ptr2 (std::move(ptr1)); // Move constructor called here

   // At this point ptr1 has been moved from and is now nullptr
   std::cout << ptr1.get() << " " <<ptr2.get()<< " " << *ptr2 <<std::endl;
   return 0
}

You can see it run live here. It will print 0, the address of p2 and 20.


问:
Is data safety guaranteed while using `ThreadPoolExecutor` from python's `future` module?
I'm looking for a conceptual answer on this question.

I'm wondering whether using ThreadPool in python to perform concurrent tasks, guarantees that data is not corrupted; I mean multiple threads don't access the critical data at the same time.

If so, how does this ThreadPoolExecutor internally works to ensure that critical data is accessed by only one thread at a time?

答:
Thread pools do not guarantee that shared data is not corrupted. Threads can swap at any byte code execution boundary and corruption is always a risk. Shared data should be protected by synchronization resources such as locks, condition variables and events. See the threading module docs

concurrent.futures.ThreadPoolExecutor is a thread pool specialized to the concurrent.futures async task model. But all of the risks of traditional threading are still there.

If you are using the python async model, things that fiddle with shared data should be dispatched on the main thread. The thread pool should be used for autonomous events, especially those that wait on blocking I/O.