问:
Filtering an array to remove items and returning back an array
I have an array and I need to exclude some items from it I use this code but this doesn't always work. or should this work at all times. then I am doing something else wrong</p>

```<code>let ar = this.comments.filter(vc => {
   return vc !== this.id
});
this.myarr = ar ..
</code>```

答:
problem of code for use "this" inside of filter loop.</p>

```<code>let that = this
let ar = this.comments.filter(vc => {
      return vc !== that.id
    })
this.myarr = ar ..
</code>```

Body:
I have an array and I need to exclude some items from it I use this code but this doesn't always work. or should this work at all times. then I am doing something else wrong

let ar = this.comments.filter(vc => {
   return vc !== this.id
});
this.myarr = ar ..

Body:
problem of code for use "this" inside of filter loop.

let that = this
let ar = this.comments.filter(vc => {
      return vc !== that.id
    })
this.myarr = ar ..


来源: stackexchange

问:
Uncaught ReferenceError: _ is not defined at <anonymous>:1:1 (Not jQuery)
.js file including an array of Strings which suppose to generate random words when one of the buttons click on the HTML page but for some reason it has a problem of scoping variables (as much as I've understood in other threads) but I don't know how to set it straight..
enter image description here

var interval;
var randomNum;

function newSubject(str) {

 clearInterval(interval);
 randomNum = Math.floor(Math.random()*(str.length));
 interval = setInterval(document.getElementById('generator').innerHTML = str[randomNum],1000);

}

**var adjectives** = [
'מסוגל',
'מקסים',
'הרפתקני',
'חומצי',
'פעיל',
'מפחד',
'מזדקן',
'אגרסיבי',
'נעים',
'ערמומי',
'מדאיג',
'ערני',
'חי',
'מדהים',
'משועשע',
'עתיק',
'מתבייש',
'מושך',
'ממוצע',
'נורא',
];

var food = [
'אוכל',
'קובנה',
'קוסקוס',
'המבורגר',
'לחם',
'גבינה',
'טבעוני',
'צמחוני',
];

var nature = [
'עץ',
'שדה',
'דשא',
'רוח',
'אדמה',
'מים',
'אש',
];

var space = [
'כדור הארץ',
'אטמוספרה',
'ירח',
'כוכבים',
'חללית',
'חלל חיצון',
'חייזר',
'ונוס',
'שמש',
];

var tech = [
'מכונה',
'בינארי',
'אפס',
'אחד',
'מחשב',
'כוח עיבוד',
];
When buttons ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en-US">
 <head>
    <meta charset="utf-8">
    <title>Connection Freestyler</title>
    <meta name="description" content="Hebrew Freestyle Generator" />
    <meta name="author" content="Connection">

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

 <link rel="stylesheet" type="text/css" href="style.css">
 <script type="text/javascript" src="words.js"></script>

    </head>

<body>
 <div class="main">
  <div class="refresh" onclick="">
  Refresh Every 5 Secs
  </div>

  <div class="generator" id="generator">
  Generator "Select Subject"
  </div>

  <div class="subjects">

   **<button class="adjectives" id="adjectives" onclick="newSubject(adjectives)">**
   Adjectives
   </button>

   <button class="food" id="food" onclick="newSubject(food)">
   Food
   </button>

   <button class="nature" id="nature" onclick="newSubject(nature)">
   Nature
   </button>

   <button class="space" id="space" onclick="newSubject(space)">
   Space
   </button>

   <button class="tech" onclick="newSubject(tech)">
   Tech
   </button>
  </div>
 </div>
 </body>
</html></code>```

I've also tried to put every variable in any scope combination possible but it stick to the same error everytime.

答:
setInterval accept function as parameter. use

```<code>interval = setInterval(() => document.getElementById('generator').innerHTML = str[randomNum],1000);
</code>```

and assuming you mean to make a new random every second, use

```<code>document.getElementById('generator').innerHTML = str[randomNum];
interval = setInterval(() => newSubject(str),1000);
</code>```

snipped:

var interval;
var randomNum;

function newSubject(str) {

 clearInterval(interval);
 randomNum = Math.floor(Math.random()*(str.length));
  document.getElementById('generator').innerHTML = str[randomNum];
 interval = setInterval(() => newSubject(str),1000);

}

var adjectives = [
'מסוגל',
'מקסים',
'הרפתקני',
'חומצי',
'פעיל',
'מפחד',
'מזדקן',
'אגרסיבי',
'נעים',
'ערמומי',
'מדאיג',
'ערני',
'חי',
'מדהים',
'משועשע',
'עתיק',
'מתבייש',
'מושך',
'ממוצע',
'נורא',
];

var food = [
'אוכל',
'קובנה',
'קוסקוס',
'המבורגר',
'לחם',
'גבינה',
'טבעוני',
'צמחוני',
];

var nature = [
'עץ',
'שדה',
'דשא',
'רוח',
'אדמה',
'מים',
'אש',
];

var space = [
'כדור הארץ',
'אטמוספרה',
'ירח',
'כוכבים',
'חללית',
'חלל חיצון',
'חייזר',
'ונוס',
'שמש',
];

var tech = [
'מכונה',
'בינארי',
'אפס',
'אחד',
'מחשב',
'כוח עיבוד',
];```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
 <div class="main">
  <div class="refresh" onclick="">
  Refresh Every 5 Secs
  </div>

  <div class="generator" id="generator">
  Generator "Select Subject"
  </div>

  <div class="subjects">

   **<button class="adjectives" id="adjectives" onclick="newSubject(adjectives)">**
   Adjectives
   </button>

   <button class="food" id="food" onclick="newSubject(food)">
   Food
   </button>

   <button class="nature" id="nature" onclick="newSubject(nature)">
   Nature
   </button>

   <button class="space" id="space" onclick="newSubject(space)">
   Space
   </button>

   <button class="tech" onclick="newSubject(tech)">
   Tech
   </button>
  </div>
 </div></code>```

ContentLicense: CC BY-SA 4.0

Body:
.js file including an array of Strings which suppose to generate random words when one of the buttons click on the HTML page but for some reason it has a problem of scoping variables (as much as I've understood in other threads) but I don't know how to set it straight..
enter image description here

var interval;
var randomNum;

function newSubject(str) {

 clearInterval(interval);
 randomNum = Math.floor(Math.random()*(str.length));
 interval = setInterval(document.getElementById('generator').innerHTML = str[randomNum],1000);

}

**var adjectives** = [
'מסוגל',
'מקסים',
'הרפתקני',
'חומצי',
'פעיל',
'מפחד',
'מזדקן',
'אגרסיבי',
'נעים',
'ערמומי',
'מדאיג',
'ערני',
'חי',
'מדהים',
'משועשע',
'עתיק',
'מתבייש',
'מושך',
'ממוצע',
'נורא',
];

var food = [
'אוכל',
'קובנה',
'קוסקוס',
'המבורגר',
'לחם',
'גבינה',
'טבעוני',
'צמחוני',
];

var nature = [
'עץ',
'שדה',
'דשא',
'רוח',
'אדמה',
'מים',
'אש',
];

var space = [
'כדור הארץ',
'אטמוספרה',
'ירח',
'כוכבים',
'חללית',
'חלל חיצון',
'חייזר',
'ונוס',
'שמש',
];

var tech = [
'מכונה',
'בינארי',
'אפס',
'אחד',
'מחשב',
'כוח עיבוד',
];
When buttons

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Connection Freestyler</title>
    <meta name="description" content="Hebrew Freestyle Generator" />
    <meta name="author" content="Connection">

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

 <link rel="stylesheet" type="text/css" href="style.css">

  Refresh Every 5 Secs

  Generator "Select Subject"

   **<button class="adjectives" id="adjectives" onclick="newSubject(adjectives)">**
   Adjectives
   </button>

   <button class="food" id="food" onclick="newSubject(food)">
   Food
   </button>

   <button class="nature" id="nature" onclick="newSubject(nature)">
   Nature
   </button>

   <button class="space" id="space" onclick="newSubject(space)">
   Space
   </button>

   <button class="tech" onclick="newSubject(tech)">
   Tech
   </button>

I've also tried to put every variable in any scope combination possible but it stick to the same error everytime.

Body:
setInterval accept function as parameter. use

interval = setInterval(() => document.getElementById('generator').innerHTML = str[randomNum],1000);

and assuming you mean to make a new random every second, use

document.getElementById('generator').innerHTML = str[randomNum];
interval = setInterval(() => newSubject(str),1000);

snipped:

var interval;
var randomNum;

function newSubject(str) {

 clearInterval(interval);
 randomNum = Math.floor(Math.random()*(str.length));
  document.getElementById('generator').innerHTML = str[randomNum];
 interval = setInterval(() => newSubject(str),1000);

}

var adjectives = [
'מסוגל',
'מקסים',
'הרפתקני',
'חומצי',
'פעיל',
'מפחד',
'מזדקן',
'אגרסיבי',
'נעים',
'ערמומי',
'מדאיג',
'ערני',
'חי',
'מדהים',
'משועשע',
'עתיק',
'מתבייש',
'מושך',
'ממוצע',
'נורא',
];

var food = [
'אוכל',
'קובנה',
'קוסקוס',
'המבורגר',
'לחם',
'גבינה',
'טבעוני',
'צמחוני',
];

var nature = [
'עץ',
'שדה',
'דשא',
'רוח',
'אדמה',
'מים',
'אש',
];

var space = [
'כדור הארץ',
'אטמוספרה',
'ירח',
'כוכבים',
'חללית',
'חלל חיצון',
'חייזר',
'ונוס',
'שמש',
];

var tech = [
'מכונה',
'בינארי',
'אפס',
'אחד',
'מחשב',
'כוח עיבוד',
];

<body>
 <div class="main">
  <div class="refresh" onclick="">
  Refresh Every 5 Secs
  </div>

  <div class="generator" id="generator">
  Generator "Select Subject"
  </div>

  <div class="subjects">

   **<button class="adjectives" id="adjectives" onclick="newSubject(adjectives)">**
   Adjectives
   </button>

   <button class="food" id="food" onclick="newSubject(food)">
   Food
   </button>

   <button class="nature" id="nature" onclick="newSubject(nature)">
   Nature
   </button>

   <button class="space" id="space" onclick="newSubject(space)">
   Space
   </button>

   <button class="tech" onclick="newSubject(tech)">
   Tech
   </button>
  </div>
 </div>


问:
perror() give seg. fault
After an error occurs, I call perror(), naturally. But I'm getting a segmentation fault when I do this or   printf("error: %s\n", strerror(errno)); I have no idea what is happing.

```<code>  int fd;
  if((fd = open(FILENAME, O_RDONLY)) == -1) {
    perror("fbi");
    exit(1);
  }

  for(;;) {

    readed = read(fd, buffer, BUFSIZE);

    if(readed == 0)
      break;

    if(readed == -1) {
      perror("fbi"); // <- here's the error
      exit(1);
    }
</code>```

How to fix this?

Update:

```<code>printf("%d\n", errno); // given 9
</code>```

UPDATE2:

Looks like there is a relation with the buffer size passed in the recv() function. if BUFSIZE is 1, give the above error. But if BUFSIZE is e.g, 128 no error. Can someone explain this behavior?

答:
Be certain to #include <string.h>, etc. .

I was using #include <errno.h>[...]printf("%s\n",strerror(errno));[...] without problems for days inside a macro.  Then one day I add another call to strerror(errno), the results included bizarre behavior, segmentation faults, incorrect return types, unexpected program termination (with exit status 0), all depending on how I called this second strerror call.

Something as simple as strerror(errno)==NULL would result in warning: comparison between pointer and integer.

Turns out it was because I used strerror without #include <string.h>.  Since the function is being correctly linked as part of the standard c library, the compiler creates a (standards mandated) "implicit declaration" of the function which assumes a definition of int strerror(int).  The incompatible return types cause the issues, since on my system char* is 64 bits but int is 32 bits.  So depending on how the compiler arranges the memory space sometimes pointers will fit in 32 bits, sometimes they won't, sometimes the incorrect addresses happen to match other allocated pages of memory(undefined/blank output), sometimes they don't(segmentation fault).  I happened to get in a situation where it didn't fit in 32 bits and the compiler "cast" the return value to a 32 bit int and then cast it back (for printf) to a 64 bit char* (without the missing upper half of the 64 bits which are now zero), and undefined behavior ensues as the processor attempts to read from unallocated memory pages.

Diagnosing your particular case will require a short, self contained, compilable, example (SSCCE), for example you make reference to a recv function call (I assume you meant read?).

You will need to also include the command you used to compile your code, as the order of linking commands, for example, can, potentially, significatly change the behavior of the resulting code.

ContentLicense: CC BY-SA 3.0

Title: perror() give seg. fault

Body:
After an error occurs, I call perror(), naturally. But I'm getting a segmentation fault when I do this or   printf("error: %s\n", strerror(errno)); I have no idea what is happing.

  int fd;
  if((fd = open(FILENAME, O_RDONLY)) == -1) {
    perror("fbi");
    exit(1);
  }

  for(;;) {

    readed = read(fd, buffer, BUFSIZE);

    if(readed == 0)
      break;

    if(readed == -1) {
      perror("fbi"); // <- here's the error
      exit(1);
    }

How to fix this?

Update:

printf("%d\n", errno); // given 9

UPDATE2:

Looks like there is a relation with the buffer size passed in the recv() function. if BUFSIZE is 1, give the above error. But if BUFSIZE is e.g, 128 no error. Can someone explain this behavior?


问:
SQL - Need help filtering results based on rows
I have a table that looks like this:

```<code>p_id | comp_id
-----+--------
 100 | 1
 100 | 2
 101 | 1
 102 | 1
</code>```

Basically, the p_id can be entered multiple times into the table for as many comp_id as needed.

What I need is to select all the p_ids that have been on comp_id 1 and 2. In the above table, that would mean only p_id == 100 would be returned.

Is there an efficient way to do this?

答:
How about this:</p>

```<code>SELECT t1.p_id
FROM table AS t1
INNER JOIN table AS t2 ON t1.p_id = t2.p_id
WHERE t1.comp_id=1
AND t2.comp_id=2
</code>```

Body:
I have a table that looks like this:

p_id | comp_id
-----+--------
 100 | 1
 100 | 2
 101 | 1
 102 | 1

Basically, the p_id can be entered multiple times into the table for as many comp_id as needed.

What I need is to select all the p_ids that have been on comp_id 1 and 2. In the above table, that would mean only p_id == 100 would be returned.

Is there an efficient way to do this?

Body:
How about this:

SELECT t1.p_id
FROM table AS t1
INNER JOIN table AS t2 ON t1.p_id = t2.p_id
WHERE t1.comp_id=1
AND t2.comp_id=2


问:
Incorrect cell information being pushed to next view controller
So currently I have a table view:

When I click on a cell, occasionally, it will give incorrect info about the event. For example, here is when I add an extra event

When I click on this new event, it gives the wrong info, and instead gives the info for the "testing" event. Each name in the cell represents one event, which has info such as registered . users, time of event, ect. When I click on asfe, the info given is the one corresponding with testing. This bug happens everyonce in a while and i dont know what is causing it.

```<code>import UIKit
import Firebase
class AdminEvents{
    var eventName:String?
    var eventDesc:String?
    var eventStartDate:String?
    var eventEndDate:String?
    var numPeople:Int?
    var numRegister:Int?

    init(evName:String, evDesc:String, evStartDate:String, evEndDate:String, evNumPeople:Int, evNumRegistered:Int){
        self.eventName = evName
        self.eventDesc = evDesc
        self.eventStartDate = evStartDate
        self.eventEndDate = evEndDate
        self.numPeople = evNumPeople
        self.numRegister = evNumRegistered
    }
}

class AdminsEventsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    var eventsArray = [String]()
    var actualEvents:[AdminEvents] = []

    @IBOutlet weak var tblEvents: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        let id = Auth.auth().currentUser?.uid
         Database.database().reference().child("users").child(id!).child("createdEvents").observe(.value) { snapshot in
                 //self.eventsArray.removeAll()
               print("start")
               print(snapshot.childrenCount)
               let enumerator = snapshot.children
               while let rest = enumerator.nextObject() as? DataSnapshot {
                   self.eventsArray.append(rest.key as! String)
               }
                      Database.database().reference().child("Events").observe(.value) { (data) in
                           let events = data.value as! [String:[String:Any]]
                           for(_,value) in events{
                               print(self.eventsArray)
                               if(self.eventsArray.contains(value["EventName"]! as! String)){
                                   self.actualEvents.append(AdminEvents(evName: value["EventName"]! as! String, evDesc: value["EventDescription"]! as! String, evStartDate: value["start time"]! as! String, evEndDate: value["end time"] as! String, evNumPeople: value["NumberOfPeople"]! as! Int, evNumRegistered: value["currentPeople"] as! Int))
                                  }
                               }
                               print("Actual events array " + "\(self.actualEvents)")
                         }
                       self.tblEvents.reloadData()
                   }
                  self.tblEvents.dataSource = self
                  self.tblEvents.delegate = self

    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print("count: "  + "\(eventsArray.count)")
          return eventsArray.count
      }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          let cell = tableView.dequeueReusableCell(withIdentifier: "productstable", for: indexPath)
          cell.textLabel?.text = self.eventsArray[indexPath.row]
          return cell
      }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
           if let destination = segue.destination as? RegisteredUsersViewController {
               destination.events = actualEvents[(tblEvents.indexPathForSelectedRow?.row)!]
               tblEvents.deselectRow(at: tblEvents.indexPathForSelectedRow!, animated: true)

           }
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
</code>```

You can see that in the prepare method, I am pushing the event name to the next view controller.

This the firebase structure

Edit: Someone was asking what is being pushed in the segue, and I forgot to add the class that has this.

```<code>class AdminEvents{
var eventName:String?
var eventDesc:String?
var eventStartDate:String?
var eventEndDate:String?
var numPeople:Int?
var numRegister:Int?

init(evName:String, evDesc:String, evStartDate:String, evEndDate:String, evNumPeople:Int, evNumRegistered:Int){
    self.eventName = evName
    self.eventDesc = evDesc
    self.eventStartDate = evStartDate
    self.eventEndDate = evEndDate
    self.numPeople = evNumPeople
    self.numRegister = evNumRegistered
}
</code>```

}

答:
In your prepare(for:sender:) function you are assuming that the table row selection value is the cell that triggered the segue, but this is not guaranteed.

It is safer to use the sender parameter to identify the row that was tapped:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? RegisteredUsersViewController,
       let cell = sender as? UITableViewCell,
       let indexPath = tblEvents.indexPath(for:cell) {
               destination.events = actualEvents[indexPath.row]
               tblEvents.deselectRow(at: indexPath, animated: true)
           }
    }
}
</code>```

Body:
So currently I have a table view:

When I click on a cell, occasionally, it will give incorrect info about the event. For example, here is when I add an extra event

When I click on this new event, it gives the wrong info, and instead gives the info for the "testing" event. Each name in the cell represents one event, which has info such as registered . users, time of event, ect. When I click on asfe, the info given is the one corresponding with testing. This bug happens everyonce in a while and i dont know what is causing it.

import UIKit
import Firebase
class AdminEvents{
    var eventName:String?
    var eventDesc:String?
    var eventStartDate:String?
    var eventEndDate:String?
    var numPeople:Int?
    var numRegister:Int?

    init(evName:String, evDesc:String, evStartDate:String, evEndDate:String, evNumPeople:Int, evNumRegistered:Int){
        self.eventName = evName
        self.eventDesc = evDesc
        self.eventStartDate = evStartDate
        self.eventEndDate = evEndDate
        self.numPeople = evNumPeople
        self.numRegister = evNumRegistered
    }
}

class AdminsEventsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    var eventsArray = [String]()
    var actualEvents:[AdminEvents] = []

    @IBOutlet weak var tblEvents: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        let id = Auth.auth().currentUser?.uid
         Database.database().reference().child("users").child(id!).child("createdEvents").observe(.value) { snapshot in
                 //self.eventsArray.removeAll()
               print("start")
               print(snapshot.childrenCount)
               let enumerator = snapshot.children
               while let rest = enumerator.nextObject() as? DataSnapshot {
                   self.eventsArray.append(rest.key as! String)
               }
                      Database.database().reference().child("Events").observe(.value) { (data) in
                           let events = data.value as! [String:[String:Any]]
                           for(_,value) in events{
                               print(self.eventsArray)
                               if(self.eventsArray.contains(value["EventName"]! as! String)){
                                   self.actualEvents.append(AdminEvents(evName: value["EventName"]! as! String, evDesc: value["EventDescription"]! as! String, evStartDate: value["start time"]! as! String, evEndDate: value["end time"] as! String, evNumPeople: value["NumberOfPeople"]! as! Int, evNumRegistered: value["currentPeople"] as! Int))
                                  }
                               }
                               print("Actual events array " + "\(self.actualEvents)")
                         }
                       self.tblEvents.reloadData()
                   }
                  self.tblEvents.dataSource = self
                  self.tblEvents.delegate = self

    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print("count: "  + "\(eventsArray.count)")
          return eventsArray.count
      }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          let cell = tableView.dequeueReusableCell(withIdentifier: "productstable", for: indexPath)
          cell.textLabel?.text = self.eventsArray[indexPath.row]
          return cell
      }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
           if let destination = segue.destination as? RegisteredUsersViewController {
               destination.events = actualEvents[(tblEvents.indexPathForSelectedRow?.row)!]
               tblEvents.deselectRow(at: tblEvents.indexPathForSelectedRow!, animated: true)

           }
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

You can see that in the prepare method, I am pushing the event name to the next view controller.

This the firebase structure

Edit: Someone was asking what is being pushed in the segue, and I forgot to add the class that has this.

class AdminEvents{
var eventName:String?
var eventDesc:String?
var eventStartDate:String?
var eventEndDate:String?
var numPeople:Int?
var numRegister:Int?

init(evName:String, evDesc:String, evStartDate:String, evEndDate:String, evNumPeople:Int, evNumRegistered:Int){
    self.eventName = evName
    self.eventDesc = evDesc
    self.eventStartDate = evStartDate
    self.eventEndDate = evEndDate
    self.numPeople = evNumPeople
    self.numRegister = evNumRegistered
}

}

Body:
In your prepare(for:sender:) function you are assuming that the table row selection value is the cell that triggered the segue, but this is not guaranteed.

It is safer to use the sender parameter to identify the row that was tapped:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? RegisteredUsersViewController,
       let cell = sender as? UITableViewCell,
       let indexPath = tblEvents.indexPath(for:cell) {
               destination.events = actualEvents[indexPath.row]
               tblEvents.deselectRow(at: indexPath, animated: true)
           }
    }
}


问:
Rcpp and C++ dependencies to gdal, sqlite3 and boost
I am trying to make an hybrid C++/python/R project more easily available for non-programmers.

I am considering the possibility to wrap the C++ code with Rcpp to make it available within an R package and hopefully hide some of the complexity to the end-user.

This question aims to understand to which extend it would be actually easier.

For example, when trying to source my project.cpp, I get  the following error:

```<code>fatal error: gdal_priv.h: No such file or directory #include <gdal_priv.h>
</code>```

Is it possible to write something cross-platform similar to LinkingTo: BH, GDAL, sqlite3 ?

How to know what C++ libraries have been made compatible with Rcpp (like BH for Boost)?

The C++ sub-project works fine using cmake: can I somehow take advantage of these cmake files to help Rcpp finding the external dependencies ?

答:
That's really three questions.

For 1) I do not know if/how gdal and or sqlite3 export themselves as header-only libraries. I kinda doubt it; gdal is well-known, and also somewhat well-know as a source of "trouble" when building.  GeoSpatial foks may know and can possibly help you.

For 2), the question is ill-defined. What is "compatible with Rcpp" supposed to mean?  There are currently over 1800 packages on CRAN using Rcpp; maybe take those as an "existence proof" and search among them?

For 3), R and CRAN use autoconf / configure a lot more than cmake. You can of course use cmake, but you then need to declare that dependency in SystemRequirements.

In short, packaging external libraries is still difficult, chiefly because you now have to look after their installation on up to three different operating systems.  This has nothing to do with Rcpp, and Rcpp cannot really help. :-/

Body:
I am trying to make an hybrid C++/python/R project more easily available for non-programmers.

I am considering the possibility to wrap the C++ code with Rcpp to make it available within an R package and hopefully hide some of the complexity to the end-user.

This question aims to understand to which extend it would be actually easier.

For example, when trying to source my project.cpp, I get  the following error:

fatal error: gdal_priv.h: No such file or directory #include <gdal_priv.h>

Is it possible to write something cross-platform similar to LinkingTo: BH, GDAL, sqlite3 ?

How to know what C++ libraries have been made compatible with Rcpp (like BH for Boost)?

The C++ sub-project works fine using cmake: can I somehow take advantage of these cmake files to help Rcpp finding the external dependencies ?


问:
trying to install bcrypt into node project + node set up issues
I have seen some very similar questions but none that I have found seem to work. I am trying to npm install bcrypt but i keep getting the error below.

bycrypt is the command that I use to install bcrypt modules. I do have Xcode and installing node-gyp does not seem to make a difference

```<code>regan@the-Voyagur buddha-bar (feature/styles) $ npm install --save bcrypt
npm WARN package.json mongo@0.1.0 No repository field.
npm WARN package.json mongo@0.1.0 No README data
-
> bcrypt@0.8.0 install /Users/regan/lighthouse/buddha-bar/node_modules/bcrypt
> node-gyp rebuild

xcode-select: error: tool 'xcodebuild' requires Xcode, but active developer directory '/Library/Developer/CommandLineTools' is a command line tools instance

xcode-select: error: tool 'xcodebuild' requires Xcode, but active developer directory '/Library/Developer/CommandLineTools' is a command line tools instance

No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.

No receipt for 'com.apple.pkg.DeveloperToolsCLILeo' found at '/'.

No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'.

gyp: No Xcode or CLT version detected!
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:343:16)
gyp ERR! stack     at ChildProcess.emit (events.js:98:17)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (child_process.js:810:12)
gyp ERR! System Darwin 14.0.0
gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/regan/lighthouse/buddha-bar/node_modules/bcrypt
gyp ERR! node -v v0.10.33
gyp ERR! node-gyp -v v1.0.1
gyp ERR! not ok

npm ERR! bcrypt@0.8.0 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the bcrypt@0.8.0 install script.
npm ERR! This is most likely a problem with the bcrypt package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get their info via:
npm ERR!     npm owner ls bcrypt
npm ERR! There is likely additional logging output above.
npm ERR! System Darwin 14.0.0
npm ERR! command "node" "/usr/local/bin/npm" "install" "--save" "bcrypt"
npm ERR! cwd /Users/regan/lighthouse/buddha-bar
npm ERR! node -v v0.10.33
npm ERR! npm -v 1.4.28
npm ERR! code ELIFECYCLE
npm ERR! not ok code 0
regan@the-Voyagur buddha-bar (feature/styles) $ xcode-select --print-path
/Library/Developer/CommandLineTools
</code>```

答:
Following these steps helped me to resolve this issue on MacOS

sudo rm -rf $(xcode-select -print-path)

xcode-select --install

/usr/sbin/pkgutil --packages | grep CL

sudo npm install -g node-gyp

Body:
I have seen some very similar questions but none that I have found seem to work. I am trying to npm install bcrypt but i keep getting the error below.

bycrypt is the command that I use to install bcrypt modules. I do have Xcode and installing node-gyp does not seem to make a difference

regan@the-Voyagur buddha-bar (feature/styles) $ npm install --save bcrypt
npm WARN package.json mongo@0.1.0 No repository field.
npm WARN package.json mongo@0.1.0 No README data
-
> bcrypt@0.8.0 install /Users/regan/lighthouse/buddha-bar/node_modules/bcrypt
> node-gyp rebuild

xcode-select: error: tool 'xcodebuild' requires Xcode, but active developer directory '/Library/Developer/CommandLineTools' is a command line tools instance

xcode-select: error: tool 'xcodebuild' requires Xcode, but active developer directory '/Library/Developer/CommandLineTools' is a command line tools instance

No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.

No receipt for 'com.apple.pkg.DeveloperToolsCLILeo' found at '/'.

No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'.

gyp: No Xcode or CLT version detected!
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:343:16)
gyp ERR! stack     at ChildProcess.emit (events.js:98:17)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (child_process.js:810:12)
gyp ERR! System Darwin 14.0.0
gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/regan/lighthouse/buddha-bar/node_modules/bcrypt
gyp ERR! node -v v0.10.33
gyp ERR! node-gyp -v v1.0.1
gyp ERR! not ok

npm ERR! bcrypt@0.8.0 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the bcrypt@0.8.0 install script.
npm ERR! This is most likely a problem with the bcrypt package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get their info via:
npm ERR!     npm owner ls bcrypt
npm ERR! There is likely additional logging output above.
npm ERR! System Darwin 14.0.0
npm ERR! command "node" "/usr/local/bin/npm" "install" "--save" "bcrypt"
npm ERR! cwd /Users/regan/lighthouse/buddha-bar
npm ERR! node -v v0.10.33
npm ERR! npm -v 1.4.28
npm ERR! code ELIFECYCLE
npm ERR! not ok code 0
regan@the-Voyagur buddha-bar (feature/styles) $ xcode-select --print-path
/Library/Developer/CommandLineTools


问:
ParserError: Error tokenizing data. C error: Expected 4 fields in line 6, saw 5
I am new to Python and Pandas library. I am trying to read a csv file using pandas in windows 10 and I am getting the above mentioned error. What's strange is that the same code is running without any error, in some other PCs.
without sep=";"
1)I have tried including sep=";" and the output is not what I am expecting(data read into a series instead of a dataframe).
using sep=";"
2)I am getting a partial output when used attribute nrows="5" but getting same parser error when used nrows="6"(It is clear that the program is facing some difficulty at line 6).

I am including the snapshot of the 1st few lines of the data set for reference.
1st 30 rows of dataset

答:
Explanation

The problem is that when you read the CSV using pd.read_csv, it uses the first line of the file as headers. Your file has 4 such values:

```<code>citrus-fruit, semi-finished fruit, margarine, ready soup
</code>```

It now assumes that every row has at most 4 comma-separated values, but if it has less, it treats the missing values as blank.
When it tries to parse line 6, i.e.

```<code>whole milk, butter, yogurt, rice, abrasive cleaner
</code>```

It sees one extra value (abrasive cleaner) and throws an error.

When you use ; as a separator, it reads the entire line without encountering a ; and so the entire dataframe has a single column, which is the line as a string.

Solution

It depends on what you're trying to achieve. If you really do want to read this in as a CSV, you can:

Add a header row in your CSV file, like so (assuming you have 11 columns):

```<code>item1, item2, item3, item4 ........ item11
</code>```

Use the names argument to read_csv, (again assuming you have 11 columns) like so:

```<code>pd.read_csv(filename, names=['item' + str(i) for i in range(11)])
</code>```

Body:
Explanation

The problem is that when you read the CSV using pd.read_csv, it uses the first line of the file as headers. Your file has 4 such values:

citrus-fruit, semi-finished fruit, margarine, ready soup

It now assumes that every row has at most 4 comma-separated values, but if it has less, it treats the missing values as blank.
When it tries to parse line 6, i.e.

whole milk, butter, yogurt, rice, abrasive cleaner

It sees one extra value (abrasive cleaner) and throws an error.

When you use ; as a separator, it reads the entire line without encountering a ; and so the entire dataframe has a single column, which is the line as a string.

Solution

It depends on what you're trying to achieve. If you really do want to read this in as a CSV, you can:

Add a header row in your CSV file, like so (assuming you have 11 columns):

item1, item2, item3, item4 ........ item11

Use the names argument to read_csv, (again assuming you have 11 columns) like so:

pd.read_csv(filename, names=['item' + str(i) for i in range(11)])


问:
Select two tables and ignore duplicates
I have two tables, I need to count how many unique rows exist in those two tables

Here's an example.

```<code>Master Table
---------------------------
topicId | category | type
---------------------------
1       |    2     |   1
2       |    2     |   1
3       |    2     |   1
1       |    2     |   2
---------------------------

User Table
---------------------------
topicId | category | type
---------------------------
1       |    2     |   1
5       |    2     |   1
7       |    2     |   2
---------------------------
</code>```

The topicId is not unique but they are unique per type, there may be more categories but it's not relevant for this exemple

I would expect the result to be 6 rows

```<code>Result
---------------------------
topicId | category | type
---------------------------
1       |    2     |   1  <- present on both, only one shows
1       |    2     |   2  <- present on master, same id as above row but diferent type
2       |    2     |   1  <- present on master
3       |    2     |   1  <- present on master
5       |    2     |   1  <- present on user
7       |    2     |   2  <- present on user
----------------------------
</code>```

Right now I query the two tables and run the ids through a function that removes duplicates but I think this is to complex, is there a way to count the rows in a single query?

答:
You can just use union:

```<code>select topicId, category, type from master_table
union
select topicId, category, type from user_table
</code>```

If you want to sort the resultset, then:

```<code>(select topicId, category, type from master_table)
union
(select topicId, category, type from user_table)
order by topicId, category, type
</code>```

Title: Select two tables and ignore duplicates

Body:
I have two tables, I need to count how many unique rows exist in those two tables

Here's an example.

Master Table
---------------------------
topicId | category | type
---------------------------
1       |    2     |   1
2       |    2     |   1
3       |    2     |   1
1       |    2     |   2
---------------------------

User Table
---------------------------
topicId | category | type
---------------------------
1       |    2     |   1
5       |    2     |   1
7       |    2     |   2
---------------------------

The topicId is not unique but they are unique per type, there may be more categories but it's not relevant for this exemple

I would expect the result to be 6 rows

Result
---------------------------
topicId | category | type
---------------------------
1       |    2     |   1  <- present on both, only one shows
1       |    2     |   2  <- present on master, same id as above row but diferent type
2       |    2     |   1  <- present on master
3       |    2     |   1  <- present on master
5       |    2     |   1  <- present on user
7       |    2     |   2  <- present on user
----------------------------

Right now I query the two tables and run the ids through a function that removes duplicates but I think this is to complex, is there a way to count the rows in a single query?

Body:
You can just use union:

select topicId, category, type from master_table
union
select topicId, category, type from user_table

If you want to sort the resultset, then:

(select topicId, category, type from master_table)
union
(select topicId, category, type from user_table)
order by topicId, category, type


问:
How to run a java method on click from html?
I am looking to add a sort button to my data that is displayed on my screen.
At the monet i have my repo set up as shown.

```<code>@Repository
public interface PlayerRepository extends JpaRepository<Player, Long> {

Player findAllById(Long id);
List<Player> findByOrderByPlayerNameAsc();
}
</code>```

And in my controller class i have it as such:

```<code>@GetMapping("/player")
public String displayPlayer(Model model) {

    model.addAttribute("player", service.findAll());

    return "/player";
}
</code>```

I want to be able to create a new method and have it as such so that when i click a button on the html of my application it calls this method and sorts the data. At the moment on loading of the screen it displays all data unfiltered, if i change it to use the "findByOrderByPlayerNameAsc" one it automatically filters upon loading. But i would like this to only happen when a button is clicked.

```<code> public String displayPlayerFilteredByName(Model model) {

    model.addAttribute("player", service.findByOrderByPlayerNameAsc());

    return "/player";
}
</code>```

Is this possible using simply java and html?
Or is there an alternative using JS?

答:
The only way, avoiding JavaScript and dynamic front-end, would be to request from back-end newly generated view or .html of your players.

That requires to set a new mapping eg.

```<code>@GetMapping("/players/asc-names")
public String displayPlayersByPlayerNameAsc(Model model) {
   ...
}
</code>```

where button would'be just a link to new endpoint.

Another way would be giving additional information to you're get /player request and extracting it via @RequestBody on back-end. But that already requeries some JavaScript being set up on the button.

If your application isn't too complex yet. I'd check front-end frameworks such as Angular, which could make it easier to expand in the future.

Body:
I am looking to add a sort button to my data that is displayed on my screen.
At the monet i have my repo set up as shown.

@Repository
public interface PlayerRepository extends JpaRepository<Player, Long> {

Player findAllById(Long id);
List<Player> findByOrderByPlayerNameAsc();
}

And in my controller class i have it as such:

@GetMapping("/player")
public String displayPlayer(Model model) {

    model.addAttribute("player", service.findAll());

    return "/player";
}

I want to be able to create a new method and have it as such so that when i click a button on the html of my application it calls this method and sorts the data. At the moment on loading of the screen it displays all data unfiltered, if i change it to use the "findByOrderByPlayerNameAsc" one it automatically filters upon loading. But i would like this to only happen when a button is clicked.

 public String displayPlayerFilteredByName(Model model) {

    model.addAttribute("player", service.findByOrderByPlayerNameAsc());

    return "/player";
}

Is this possible using simply java and html?
Or is there an alternative using JS?

Body:
The only way, avoiding JavaScript and dynamic front-end, would be to request from back-end newly generated view or .html of your players.

That requires to set a new mapping eg.

@GetMapping("/players/asc-names")
public String displayPlayersByPlayerNameAsc(Model model) {
   ...
}

where button would'be just a link to new endpoint.

Another way would be giving additional information to you're get /player request and extracting it via @RequestBody on back-end. But that already requeries some JavaScript being set up on the button.

If your application isn't too complex yet. I'd check front-end frameworks such as Angular, which could make it easier to expand in the future.


问:
Don't understand iterator, reference and pointer invalidation, an example
I've read a lot of posts abut reference, pointers and iterators invalidation. For instance I've read that insertion invalidates all reference to the elements of a deque, then why in the following code I don't have errors?

```<code>#include <deque>

int main()
{
    std::deque<int> v1 = { 1, 3, 4, 5, 7, 8, 9, 1, 3, 4 };
    int& a = v1[6];
    std::deque<int>::iterator it = v1.insert(v1.begin() + 2, 3);
    int c = a;
    return a;
}
</code>```

When I run this I get 9 as result, so "a" is still referring to the right element.
In general I didn't manage to get invalidation errors. I tried different containers and even with pointers and iterators.

答:
Sometimes, an operation that could invalidate something, doesn't.

I'm not familiar enough with std::deque implementation to comment, but if you did push_back on a std::vector, for example, you might get all your iterators, references and pointers to elements of the vector invalidated, for example, because std::vector needed to allocate more memory to accomodate the new element, and ended up moving all the data to a new location, where that memory was available.

Or, you might get nothing invalidated, because the vector had enough space to just construct a new element in place, or was lucky enough to get enough new memory at the end of its current memory location, and did not have to move anything, while still having changed size.

Usually, the documentation carefully documents what operations can invalidate what. For example, search for "invalidate" in https://en.cppreference.com/w/cpp/container/deque .

Additionally, particular implementations of the standard data structures might be even safer than the standard guarantees - but relying on that will make your code highly non-portable, and potentially introduce hidden bugs when the unspoken safety guarantees change: everything will seem to work just fine until it doesn't.

The only safe thing to do is to read the specification carefully and never rely on something not getting invalidated when it does not guarantee that.

Also, as Enrico pointed out, you might get cases where your references/pointers/iterators get invalidated, but reading from them yields a value that looks fine, so such a simple method for testing if something has been invalidated will not do.

Body:
I've read a lot of posts abut reference, pointers and iterators invalidation. For instance I've read that insertion invalidates all reference to the elements of a deque, then why in the following code I don't have errors?

#include <deque>

int main()
{
    std::deque<int> v1 = { 1, 3, 4, 5, 7, 8, 9, 1, 3, 4 };
    int& a = v1[6];
    std::deque<int>::iterator it = v1.insert(v1.begin() + 2, 3);
    int c = a;
    return a;
}

When I run this I get 9 as result, so "a" is still referring to the right element.
In general I didn't manage to get invalidation errors. I tried different containers and even with pointers and iterators.


问:
Use Open API 3 Codegen for Spring Boot 2 client and server stubs
TL;DR How can I use OpenApi3 Codegen to generate code for spring-web >= 5.x using the rest template?

I have been using the OpenApi 3 code generator for creation of spring-mvc server stubs and spring rest template clients to be used in other applications.

Now I am upgrading my applications to Spring Boot 2 and I was astonished, that I can not find anything on how to configure the maven generator plugin to create code for a spring boot 2 codebase or strictly speaking to use a spring-web dependency >= 5.0.0, without using webflux and webclient, which would obviously be a major breaking change.

For the rest template it seems that only spring-web 4.x can be included.

Ignoring that fact and simply using the generated code in spring projects would most likely work without any issues, as it seems there are no breaking changes in any spring code used in the generated library, but nevertheless, it feels just wrong to depend on that and mix two different major versions of spring.

Is there any way to properly configure that or to run the generator in 'Spring 5 mode' while still using the rest template?

答:
You can make it using the swagger-codegen-maven-plugin, see the example below. The plugin will generate client classes automatically before compiling of the application.

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>ru.ilysenko</groupId>
    <artifactId>openapi-v3-client</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>
        <java.version>11</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.joschi.jackson</groupId>
            <artifactId>jackson-datatype-threetenbp</artifactId>
            <version>2.6.4</version>
        </dependency>
        <dependency>
            <groupId>io.swagger.core.v3</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.threeten</groupId>
            <artifactId>threetenbp</artifactId>
            <version>1.4.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>io.swagger.codegen.v3</groupId>
                <artifactId>swagger-codegen-maven-plugin</artifactId>
                <version>3.0.16</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                        <configuration>
                            <inputSpec>https://somehost.com/openapi/swagger-ui/swagger.yaml</inputSpec>
                            <language>java</language>
                            <library>resttemplate</library>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Generated API classes are the Spring components, so you can inject them in your application, in this case don't forget to scan the generated sources' package.

If it doesn't work, see my working example: https://github.com/0x100/tinka

Body:
You can make it using the swagger-codegen-maven-plugin, see the example below. The plugin will generate client classes automatically before compiling of the application.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>ru.ilysenko</groupId>
    <artifactId>openapi-v3-client</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>
        <java.version>11</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.joschi.jackson</groupId>
            <artifactId>jackson-datatype-threetenbp</artifactId>
            <version>2.6.4</version>
        </dependency>
        <dependency>
            <groupId>io.swagger.core.v3</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.threeten</groupId>
            <artifactId>threetenbp</artifactId>
            <version>1.4.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>io.swagger.codegen.v3</groupId>
                <artifactId>swagger-codegen-maven-plugin</artifactId>
                <version>3.0.16</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                        <configuration>
                            <inputSpec>https://somehost.com/openapi/swagger-ui/swagger.yaml</inputSpec>
                            <language>java</language>
                            <library>resttemplate</library>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

Generated API classes are the Spring components, so you can inject them in your application, in this case don't forget to scan the generated sources' package.

If it doesn't work, see my working example: https://github.com/0x100/tinka


问:
which test card number is used in India by stripe?
I'm using stripe payment integration with my android app, but when I test the card it gives invalid card message means the card is null.
stripe gives these international cards in which India is not mentioned.
how I test card in India.

I tried various cards including 4242 4242 4242 4242
and also others. stripe testing cards

https://stripe.com/docs/testing#international-cards

```<code> final Card cardToSave = mCardMultilineWidget.getCard();

 if (cardToSave == null) {
//     mErrorDialogHandler.showError("Invalid Card Data");

      Toast.makeText(getContext(),"Invalid Card Data",Toast.LENGTH_LONG).show();
      return ;
  }
  else {
            Toast.makeText(getContext(),"valid Card Data",Toast.LENGTH_LONG).show();
                    stripe.createToken(
                            cardToSave,
                            new TokenCallback() {
                                public void onSuccess(Token token) {
                                    //Send token to your own web service
                                    Toast.makeText(getContext(),token +"",Toast.LENGTH_LONG).show();

                                }
                                public void onError(Exception error) {
                                    Toast.makeText(getContext(),
                                            error.getLocalizedMessage(),
                                            Toast.LENGTH_LONG).show();
                                }
                            }
                    );

                }
</code>```

I want that card is valid and token return by stripe.

答:
Short Answer: 4000003560000008

For more numbers or other details check https://stripe.com/docs/testing#international-cards

Note: High chances to oversee the tabs on the section top, limiting to this question, you may want to check for "Asia-Pacific" tab

Body:
I'm using stripe payment integration with my android app, but when I test the card it gives invalid card message means the card is null.
stripe gives these international cards in which India is not mentioned.
how I test card in India.

I tried various cards including 4242 4242 4242 4242
and also others. stripe testing cards

https://stripe.com/docs/testing#international-cards

 final Card cardToSave = mCardMultilineWidget.getCard();

 if (cardToSave == null) {
//     mErrorDialogHandler.showError("Invalid Card Data");

      Toast.makeText(getContext(),"Invalid Card Data",Toast.LENGTH_LONG).show();
      return ;
  }
  else {
            Toast.makeText(getContext(),"valid Card Data",Toast.LENGTH_LONG).show();
                    stripe.createToken(
                            cardToSave,
                            new TokenCallback() {
                                public void onSuccess(Token token) {
                                    //Send token to your own web service
                                    Toast.makeText(getContext(),token +"",Toast.LENGTH_LONG).show();

                                }
                                public void onError(Exception error) {
                                    Toast.makeText(getContext(),
                                            error.getLocalizedMessage(),
                                            Toast.LENGTH_LONG).show();
                                }
                            }
                    );

                }

I want that card is valid and token return by stripe.


问:
collections.Counter, is there any way to avoid adding string values?
For example, I have two dictionaries. </p>

<pre class="lang-py prettyprint-override"><code>>>> dict_a = {'total': 20, 'remaining': 10, 'group': 'group_a'}
>>> dict_b = {'total': 30, 'remaining': 29, 'group': 'group_a'}
</code>```

<p>I am using collections.Counter for counting purposes.</p>

```<code>>>> dict_c = Counter()
>>> dict_c.update(Counter(dict_a))
>>> dict_c.update(Counter(dict_b))
>>> print(dict_c)
{'toal': 50, 'remaining': 39, 'group': 'group_agroup_a'}
</code>```

<p>Is there any way to add only integer type values? i.e when added it adds up integer type values only.</p>

```<code>>>> print(dict_c)
>>> {'toal': 50, 'remaining': 39, 'group': 'group_a'}
</code>```

答:
Is there any way to add only integer type values?

This may not be the most efficient solution, but you can simply iterate through the key-value pairs of dict_c to check if the values are of type int to create a new dictionary that only contains integer values.

from collections import Counter

dict_a = {'total': 20, 'remaining': 10, 'group': 'group_a'}
dict_b = {'total': 30, 'remaining': 29, 'group': 'group_a'}
dict_c = Counter(dict_a) + Counter(dict_b)
dict_result = {key: value for key, value in dict_c.items() if isinstance(value, int)}
print(dict_result)
```

<p>This returns the expected result:</p>

<pre class="lang-py prettyprint-override"><code>{'total': 50, 'remaining': 39}
</code>```

Body:
For example, I have two dictionaries.

>>> dict_a = {'total': 20, 'remaining': 10, 'group': 'group_a'}
>>> dict_b = {'total': 30, 'remaining': 29, 'group': 'group_a'}

I am using collections.Counter for counting purposes.

>>> dict_c = Counter()
>>> dict_c.update(Counter(dict_a))
>>> dict_c.update(Counter(dict_b))
>>> print(dict_c)
{'toal': 50, 'remaining': 39, 'group': 'group_agroup_a'}

Is there any way to add only integer type values? i.e when added it adds up integer type values only.

>>> print(dict_c)
>>> {'toal': 50, 'remaining': 39, 'group': 'group_a'}

Body:
Is there any way to add only integer type values?

This may not be the most efficient solution, but you can simply iterate through the key-value pairs of dict_c to check if the values are of type int to create a new dictionary that only contains integer values.

from collections import Counter

dict_a = {'total': 20, 'remaining': 10, 'group': 'group_a'}
dict_b = {'total': 30, 'remaining': 29, 'group': 'group_a'}
dict_c = Counter(dict_a) + Counter(dict_b)
dict_result = {key: value for key, value in dict_c.items() if isinstance(value, int)}
print(dict_result)

This returns the expected result:

{'total': 50, 'remaining': 39}


问:
Android Studio can't find property XMLConstants.ACCESS_EXTERNAL_DTD
I'm having a very similar issue to this post - Java and Xerces: can't find property XMLConstants.ACCESS_EXTERNAL_DTD - but with working on Android Studio IDE.

I'm also trying to fix the same issue about disabling XML external entity (XXE) processing that gets raised as a vulnerability in our SonarCloud analysis (see: https://sonarcloud.io/project/issues?id=org.digitalcampus.mobile.learning&open=AW3ezGnx-dJmagWAiKPH&resolved=false&types=VULNERABILITY).

As far as I can tell, I have the most recent version of Android Studio installed, along with the all recent updates for Java, my Android Studio about dialog shows this:

```<code>Android Studio 3.5.3
Build #AI-191.8026.42.35.6010548, built on November 15, 2019
JRE: 1.8.0_202-release-1483-b49-5587405 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Linux 4.15.0-76-generic
</code>```

I'd really appreciate any feedback/help on how I can resolve this, so I can remove the vulnerability from my code. Just let me know if there is any other specific information (versions etc) that you may need.

Thanks in advance for you help...

Update (14/2/20)...
Looks like the ACCESS_EXTERNAL_DTD constant is not available in Android - see the Android java reference docs: https://developer.android.com/reference/javax/xml/XMLConstants.html.

So would the FEATURE_SECURE_PROCESSING constant be sufficient?

答:
you can use the below code to solve your issue, check the XML External Entity Prevention Cheat Sheet for more details

```<code> DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    String FEATURE = null;
    try {

        dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
        dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        dbf.setXIncludeAware(false);
        dbf.setExpandEntityReferences(false);

    } catch (ParserConfigurationException e) {
        // This should catch a failed setFeature feature

    } catch (SAXException e) {
        // On Apache, this should be thrown when disallowing DOCTYPE

    } catch (IOException e) {
        // XXE that points to a file that doesn't exist

    }

// Load XML file or stream using a XXE agnostic configured parser...
        DocumentBuilder safebuilder = dbf.newDocumentBuilder();
</code>```

if this was helpful, please mark this as the answer.

Body:
I'm having a very similar issue to this post - Java and Xerces: can't find property XMLConstants.ACCESS_EXTERNAL_DTD - but with working on Android Studio IDE.

I'm also trying to fix the same issue about disabling XML external entity (XXE) processing that gets raised as a vulnerability in our SonarCloud analysis (see: https://sonarcloud.io/project/issues?id=org.digitalcampus.mobile.learning&open=AW3ezGnx-dJmagWAiKPH&resolved=false&types=VULNERABILITY).

As far as I can tell, I have the most recent version of Android Studio installed, along with the all recent updates for Java, my Android Studio about dialog shows this:

Android Studio 3.5.3
Build #AI-191.8026.42.35.6010548, built on November 15, 2019
JRE: 1.8.0_202-release-1483-b49-5587405 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Linux 4.15.0-76-generic

I'd really appreciate any feedback/help on how I can resolve this, so I can remove the vulnerability from my code. Just let me know if there is any other specific information (versions etc) that you may need.

Thanks in advance for you help...

Update (14/2/20)...
Looks like the ACCESS_EXTERNAL_DTD constant is not available in Android - see the Android java reference docs: https://developer.android.com/reference/javax/xml/XMLConstants.html.

So would the FEATURE_SECURE_PROCESSING constant be sufficient?

Body:
you can use the below code to solve your issue, check the XML External Entity Prevention Cheat Sheet for more details

 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    String FEATURE = null;
    try {

        dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
        dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        dbf.setXIncludeAware(false);
        dbf.setExpandEntityReferences(false);

    } catch (ParserConfigurationException e) {
        // This should catch a failed setFeature feature

    } catch (SAXException e) {
        // On Apache, this should be thrown when disallowing DOCTYPE

    } catch (IOException e) {
        // XXE that points to a file that doesn't exist

    }

// Load XML file or stream using a XXE agnostic configured parser...
        DocumentBuilder safebuilder = dbf.newDocumentBuilder();

if this was helpful, please mark this as the answer.


问:
Assembly - How to use a variable pushed into the stack
Having a bit of trouble. I have a function which is called like this:

```<code>;  Calc(&average, &ErrorMargin) Equivalent:
    push    ErrorMargin
    push    average
    call    Calc

;ErrorMargin and average are both declared with "dd"
</code>```

How would I actually change the values of these variables that were pushed onto the stack? Would I use esp and go through the stack? Would I instead pop them into a register? How the heck do I access these variables?

Thanks!

答:
I figured it out with the insight given by W. Chang's comment.

The Error Margin variable is accessed through:

mov rdx, [rbp-8]

And the Average variable is accessed with:

mov rdx, [rbp-16]

This method would only work on the first function call and I realized that it was due to the given template changing the location of rsp, so I accounted for it with an offset in later function calls.

Body:
Having a bit of trouble. I have a function which is called like this:

;  Calc(&average, &ErrorMargin) Equivalent:
    push    ErrorMargin
    push    average
    call    Calc

;ErrorMargin and average are both declared with "dd"

How would I actually change the values of these variables that were pushed onto the stack? Would I use esp and go through the stack? Would I instead pop them into a register? How the heck do I access these variables?

Thanks!


问:
How to best address the adverse impact of SSL encryption on zero-copy optimization
Kafka consumers are unable to take advantage of zero-copy optimization over SSL encryption. This is because SSL requires copying of data for encryption before sending it over the wire. Is there a workaround to this problem?</p>

答:
What you are looking for is a way to have end-to-end encryption so that broker always deals with encrypted messages thereby still taking advantage of zero-copy.
Encrypt while producing and decrypt while consuming - if the kafka producer and consumer apis can do this out of box (with support to get keys per topic/cluster) this can be achieved. This is under discussion at KIP-317

Alternatively you can have side cars that do this transparently for you. Check out this interesting blog which uses side-cars to achieve the same.


问:
Split Wav File in VB6
I need help to fix the attached VB6 code which is supposed to take an audio file and split it into 5 equal parts.

This is the way this code should work:

The first part starts from the beginning of Track.wav file.
The second part starts from where the first split part ended.
The third part starts from where the second split part ended.
The fourth part starts from where the third split part ended.
The fifth part starts from where the fourth split part ended.

Essentially each of the file parts is a continuation of the previous part of file split. After the split I have 1.wav, 2.wav, 3.wav. 4.wav and 5.wav all derived from a Track.wav file. The code attached already splits the file into five equal parts but the problem is that all the audio parts are the same as the first part instead of a continuation.

I need help to get this fixed to work as it should in VB6 (not .NET). I'd be grateful for your assistance with this.

```<code>Dim Wavlength As Integer

Private Sub Command1_Click()

On Error Resume Next

DoFirstWav

Me.SetFocus

End Sub

Private Sub DoFirstWav()

On Error Resume Next

Dim ByteData() As Byte
Dim FirstWav As Integer

FirstWav = Wavlength / 5

ByteData = ReadFile(App.Path & "\Track.wav", 1, FirstWav & "0000")
Call WriteFile(App.Path & "\Segments\1.wav", ByteData)

DoSecondWav

End Sub

Private Sub DoSecondWav()

On Error Resume Next

Dim ByteData() As Byte
Dim SecondWav As Integer

SecondWav = Wavlength / 5

ByteData = ReadFile(App.Path & "\Track.wav", 1, SecondWav & "0000")
Call WriteFile(App.Path & "\Segments\2.wav", ByteData)

DoThirdWav

End Sub

Private Sub DoThirdWav()

On Error Resume Next

Dim ByteData() As Byte
Dim ThirdWav As Integer

ThirdWav = Wavlength / 5

ByteData = ReadFile(App.Path & "\Track.wav", 1, ThirdWav & "0000")
Call WriteFile(App.Path & "\Segments\3.wav", ByteData)

DoFourthWav

End Sub

Private Sub DoFourthWav()

On Error Resume Next

Dim ByteData() As Byte
Dim FourthWav As Integer

FourthWav = Wavlength / 5

ByteData = ReadFile(App.Path & "\Track.wav", 1, FourthWav & "0000")
Call WriteFile(App.Path & "\Segments\4.wav", ByteData)

DoFifthWav

End Sub

Private Sub DoFifthWav()

On Error Resume Next

Dim ByteData() As Byte
Dim FifthWav As Integer

FifthWav = Wavlength / 5

ByteData = ReadFile(App.Path & "\Track.wav", 1, FifthWav & "0000")
Call WriteFile(App.Path & "\Segments\5.wav", ByteData)

MsgBox "Wav Split Successfully", vbInformation

End

End Sub

Private Function ReadFile(ByVal strFileName As String, Optional ByVal lngStartPos As Long = 1, Optional ByVal lngFileSize As Long = -1) As Byte()

On Error Resume Next

Dim FilNum As Integer

FilNum = FreeFile

Open strFileName For Binary As #FilNum
    If lngFileSize = -1 Then
        ReDim ReadFile(LOF(FilNum) - lngStartPos)
        Else
        ReDim ReadFile(lngFileSize - 1)
    End If
    Get #FilNum, lngStartPos, ReadFile
Close #FilNum

End Function

Private Function WriteFile(ByVal strFileName As String, ByteData() As Byte, Optional ByVal lngStartPos As Long = -1, Optional ByVal OverWrite As Boolean = True)

On Error Resume Next

Dim FilNum As Integer

FilNum = FreeFile

If OverWrite = True And Dir(strFileName) <> "" Then
    Kill strFileName
End If

Open strFileName For Binary As #FilNum
    If lngStartPos = -1 Then
        Put #FilNum, LOF(FilNum) + 1, ByteData
        Else
        Put #FilNum, l, ByteData
    End If
Close #FilNum

End Function

Private Sub Form_Load()

On Error Resume Next

Dim MyInt As Integer
Dim MyByte As Byte
Dim MyStr As String * 4
Dim MyLong As Long
Dim SampleRate, BytesPerSample, FileSize As Long

Open App.Path & "\Track.wav" For Binary Access Read Lock Read As #1
    Get #1, , MyStr:    Debug.Print "Riff = "; MyStr
    Get #1, , MyLong:   Debug.Print "File size = "; MyLong
    FileSize = MyLong
    Get #1, , MyStr:    Debug.Print "Wave = "; MyStr
    Get #1, , MyStr:    Debug.Print "Format = "; MyStr
    Get #1, , MyLong:   Debug.Print "Any = "; MyLong
    Get #1, , MyInt:    Debug.Print "formatTag = "; MyInt
    Get #1, , MyInt:    Debug.Print "Channels = "; MyInt
    Get #1, , MyLong:   Debug.Print "Samples per Sec = "; MyLong
    SampleRate = MyLong
    Get #1, , MyInt:    Debug.Print "Bytes per Sec = "; MyInt
    Get #1, , MyInt:    Debug.Print "BlockAlign = "; MyInt
    Get #1, , MyInt:    Debug.Print "Bytes per Sample = "; MyInt
    BytesPerSample = MyInt
Close #1

Wavlength = FileSize / (SampleRate * BytesPerSample)

End Sub
</code>```

答:
This question is quite involved, particularly if each part needs to be playable.  The reason is that each file you create needs to have a valid header record.  To complicate it further, it appears a header record may be 44 bytes, 46 bytes, or even other sizes.

I worked out some basic code based on your post that appears to work for the wav file I tested:

```<code>Option Explicit

Private Const HEADER_SIZE As Long = 46
Private Const CHUNK_COUNT As Long = 5

Private HeaderData(HEADER_SIZE) As Byte
Private ChunkSize As Long

Private Sub Form_Load()
   Dim MyInt As Integer
   Dim MyByte As Byte
   Dim MyStr As String * 4
   Dim MyLong As Long
   Dim FileSize As Long

   Open App.Path & "\Track.wav" For Binary Access Read Lock Read As #1
   Get #1, , MyStr:    Debug.Print "Riff = "; MyStr
   Get #1, , MyLong:   Debug.Print "File size = "; MyLong
   Get #1, , MyStr:    Debug.Print "Wave = "; MyStr
   Get #1, , MyStr:    Debug.Print "Format = "; MyStr
   Get #1, , MyLong:   Debug.Print "Any = "; MyLong
   Get #1, , MyInt:    Debug.Print "formatTag = "; MyInt
   Get #1, , MyInt:    Debug.Print "Channels = "; MyInt
   Get #1, , MyLong:   Debug.Print "Samples per Sec = "; MyLong
   Get #1, , MyInt:    Debug.Print "Bytes per Sec = "; MyInt
   Get #1, , MyInt:    Debug.Print "BlockAlign = "; MyInt
   Get #1, , MyInt:    Debug.Print "Bytes per Sample = "; MyInt
   Get #1, , MyInt:    Debug.Print "Something = "; MyInt  'for my wave file, I needed 2 extra bytes
   Get #1, , MyStr:    Debug.Print "SubchunkID = "; MyStr
   Get #1, , FileSize: Debug.Print "SubchunkSize = "; FileSize
   Get #1, 1, HeaderData  'the size changes depending upon the file
   Close #1

   ChunkSize = CLng(FileSize / CHUNK_COUNT)  'you might loose some data here
End Sub

Private Sub Command1_Click()
   Dim i As Integer
   Dim ByteData() As Byte
   Dim StartPos As Long

   For i = 1 To CHUNK_COUNT
      StartPos = HEADER_SIZE + ((i - 1) * ChunkSize)
      ByteData = ReadFile(App.Path & "\Track.wav", StartPos, ChunkSize)
      Call WriteFile(App.Path & "\Segments\" & i & ".wav", HeaderData, ByteData)
   Next

   MsgBox "Wav Split Successfully", vbInformation
   End
End Sub

Private Function ReadFile(ByVal strFileName As String, ByVal lngStartPos As Long, ByVal lngFileSize As Long) As Byte()
   On Error Resume Next

   Dim FilNum As Integer

   FilNum = FreeFile

   ReDim ReadFile(lngFileSize - 1)

   Open strFileName For Binary As #FilNum

   Get #FilNum, lngStartPos, ReadFile

   Close #FilNum
End Function

Private Function WriteFile(ByVal strFileName As String, HeaderData() As Byte, ByteData() As Byte, Optional ByVal OverWrite As Boolean = True)
   On Error Resume Next

   Dim FilNum As Integer

   FilNum = FreeFile

   If OverWrite = True And Dir(strFileName) <> "" Then
       Kill strFileName
   End If

   Open strFileName For Binary As #FilNum

   Put #FilNum, LOF(FilNum) + 1, HeaderData
   Put #FilNum, HEADER_SIZE, ByteData

   Close #FilNum
End Function
</code>```

I eliminated a lot of duplicate code by implementing a For loop.  In that loop, I calculate the Start position for the Read, and also pass the header record for the Write.

Again, I stress that this is very basic and will not work for all wav files.  You can manually adjust the HEADER_SIZE if it does not work for your file.

Likely the header record needs to be modified to reflect the correct size of the new file, instead of using the header from the original file.

This should get you started.

Title: Split Wav File in VB6

Body:
I need help to fix the attached VB6 code which is supposed to take an audio file and split it into 5 equal parts.

This is the way this code should work:

The first part starts from the beginning of Track.wav file.
The second part starts from where the first split part ended.
The third part starts from where the second split part ended.
The fourth part starts from where the third split part ended.
The fifth part starts from where the fourth split part ended.

Essentially each of the file parts is a continuation of the previous part of file split. After the split I have 1.wav, 2.wav, 3.wav. 4.wav and 5.wav all derived from a Track.wav file. The code attached already splits the file into five equal parts but the problem is that all the audio parts are the same as the first part instead of a continuation.

I need help to get this fixed to work as it should in VB6 (not .NET). I'd be grateful for your assistance with this.

Dim Wavlength As Integer

Private Sub Command1_Click()

On Error Resume Next

DoFirstWav

Me.SetFocus

End Sub

Private Sub DoFirstWav()

On Error Resume Next

Dim ByteData() As Byte
Dim FirstWav As Integer

FirstWav = Wavlength / 5

ByteData = ReadFile(App.Path & "\Track.wav", 1, FirstWav & "0000")
Call WriteFile(App.Path & "\Segments\1.wav", ByteData)

DoSecondWav

End Sub

Private Sub DoSecondWav()

On Error Resume Next

Dim ByteData() As Byte
Dim SecondWav As Integer

SecondWav = Wavlength / 5

ByteData = ReadFile(App.Path & "\Track.wav", 1, SecondWav & "0000")
Call WriteFile(App.Path & "\Segments\2.wav", ByteData)

DoThirdWav

End Sub

Private Sub DoThirdWav()

On Error Resume Next

Dim ByteData() As Byte
Dim ThirdWav As Integer

ThirdWav = Wavlength / 5

ByteData = ReadFile(App.Path & "\Track.wav", 1, ThirdWav & "0000")
Call WriteFile(App.Path & "\Segments\3.wav", ByteData)

DoFourthWav

End Sub

Private Sub DoFourthWav()

On Error Resume Next

Dim ByteData() As Byte
Dim FourthWav As Integer

FourthWav = Wavlength / 5

ByteData = ReadFile(App.Path & "\Track.wav", 1, FourthWav & "0000")
Call WriteFile(App.Path & "\Segments\4.wav", ByteData)

DoFifthWav

End Sub

Private Sub DoFifthWav()

On Error Resume Next

Dim ByteData() As Byte
Dim FifthWav As Integer

FifthWav = Wavlength / 5

ByteData = ReadFile(App.Path & "\Track.wav", 1, FifthWav & "0000")
Call WriteFile(App.Path & "\Segments\5.wav", ByteData)

MsgBox "Wav Split Successfully", vbInformation

End

End Sub

Private Function ReadFile(ByVal strFileName As String, Optional ByVal lngStartPos As Long = 1, Optional ByVal lngFileSize As Long = -1) As Byte()

On Error Resume Next

Dim FilNum As Integer

FilNum = FreeFile

Open strFileName For Binary As #FilNum
    If lngFileSize = -1 Then
        ReDim ReadFile(LOF(FilNum) - lngStartPos)
        Else
        ReDim ReadFile(lngFileSize - 1)
    End If
    Get #FilNum, lngStartPos, ReadFile
Close #FilNum

End Function

Private Function WriteFile(ByVal strFileName As String, ByteData() As Byte, Optional ByVal lngStartPos As Long = -1, Optional ByVal OverWrite As Boolean = True)

On Error Resume Next

Dim FilNum As Integer

FilNum = FreeFile

If OverWrite = True And Dir(strFileName) <> "" Then
    Kill strFileName
End If

Open strFileName For Binary As #FilNum
    If lngStartPos = -1 Then
        Put #FilNum, LOF(FilNum) + 1, ByteData
        Else
        Put #FilNum, l, ByteData
    End If
Close #FilNum

End Function

Private Sub Form_Load()

On Error Resume Next

Dim MyInt As Integer
Dim MyByte As Byte
Dim MyStr As String * 4
Dim MyLong As Long
Dim SampleRate, BytesPerSample, FileSize As Long

Open App.Path & "\Track.wav" For Binary Access Read Lock Read As #1
    Get #1, , MyStr:    Debug.Print "Riff = "; MyStr
    Get #1, , MyLong:   Debug.Print "File size = "; MyLong
    FileSize = MyLong
    Get #1, , MyStr:    Debug.Print "Wave = "; MyStr
    Get #1, , MyStr:    Debug.Print "Format = "; MyStr
    Get #1, , MyLong:   Debug.Print "Any = "; MyLong
    Get #1, , MyInt:    Debug.Print "formatTag = "; MyInt
    Get #1, , MyInt:    Debug.Print "Channels = "; MyInt
    Get #1, , MyLong:   Debug.Print "Samples per Sec = "; MyLong
    SampleRate = MyLong
    Get #1, , MyInt:    Debug.Print "Bytes per Sec = "; MyInt
    Get #1, , MyInt:    Debug.Print "BlockAlign = "; MyInt
    Get #1, , MyInt:    Debug.Print "Bytes per Sample = "; MyInt
    BytesPerSample = MyInt
Close #1

Wavlength = FileSize / (SampleRate * BytesPerSample)

End Sub

Body:
This question is quite involved, particularly if each part needs to be playable.  The reason is that each file you create needs to have a valid header record.  To complicate it further, it appears a header record may be 44 bytes, 46 bytes, or even other sizes.

I worked out some basic code based on your post that appears to work for the wav file I tested:

Option Explicit

Private Const HEADER_SIZE As Long = 46
Private Const CHUNK_COUNT As Long = 5

Private HeaderData(HEADER_SIZE) As Byte
Private ChunkSize As Long

Private Sub Form_Load()
   Dim MyInt As Integer
   Dim MyByte As Byte
   Dim MyStr As String * 4
   Dim MyLong As Long
   Dim FileSize As Long

   Open App.Path & "\Track.wav" For Binary Access Read Lock Read As #1
   Get #1, , MyStr:    Debug.Print "Riff = "; MyStr
   Get #1, , MyLong:   Debug.Print "File size = "; MyLong
   Get #1, , MyStr:    Debug.Print "Wave = "; MyStr
   Get #1, , MyStr:    Debug.Print "Format = "; MyStr
   Get #1, , MyLong:   Debug.Print "Any = "; MyLong
   Get #1, , MyInt:    Debug.Print "formatTag = "; MyInt
   Get #1, , MyInt:    Debug.Print "Channels = "; MyInt
   Get #1, , MyLong:   Debug.Print "Samples per Sec = "; MyLong
   Get #1, , MyInt:    Debug.Print "Bytes per Sec = "; MyInt
   Get #1, , MyInt:    Debug.Print "BlockAlign = "; MyInt
   Get #1, , MyInt:    Debug.Print "Bytes per Sample = "; MyInt
   Get #1, , MyInt:    Debug.Print "Something = "; MyInt  'for my wave file, I needed 2 extra bytes
   Get #1, , MyStr:    Debug.Print "SubchunkID = "; MyStr
   Get #1, , FileSize: Debug.Print "SubchunkSize = "; FileSize
   Get #1, 1, HeaderData  'the size changes depending upon the file
   Close #1

   ChunkSize = CLng(FileSize / CHUNK_COUNT)  'you might loose some data here
End Sub

Private Sub Command1_Click()
   Dim i As Integer
   Dim ByteData() As Byte
   Dim StartPos As Long

   For i = 1 To CHUNK_COUNT
      StartPos = HEADER_SIZE + ((i - 1) * ChunkSize)
      ByteData = ReadFile(App.Path & "\Track.wav", StartPos, ChunkSize)
      Call WriteFile(App.Path & "\Segments\" & i & ".wav", HeaderData, ByteData)
   Next

   MsgBox "Wav Split Successfully", vbInformation
   End
End Sub

Private Function ReadFile(ByVal strFileName As String, ByVal lngStartPos As Long, ByVal lngFileSize As Long) As Byte()
   On Error Resume Next

   Dim FilNum As Integer

   FilNum = FreeFile

   ReDim ReadFile(lngFileSize - 1)

   Open strFileName For Binary As #FilNum

   Get #FilNum, lngStartPos, ReadFile

   Close #FilNum
End Function

Private Function WriteFile(ByVal strFileName As String, HeaderData() As Byte, ByteData() As Byte, Optional ByVal OverWrite As Boolean = True)
   On Error Resume Next

   Dim FilNum As Integer

   FilNum = FreeFile

   If OverWrite = True And Dir(strFileName) <> "" Then
       Kill strFileName
   End If

   Open strFileName For Binary As #FilNum

   Put #FilNum, LOF(FilNum) + 1, HeaderData
   Put #FilNum, HEADER_SIZE, ByteData

   Close #FilNum
End Function

I eliminated a lot of duplicate code by implementing a For loop.  In that loop, I calculate the Start position for the Read, and also pass the header record for the Write.

Again, I stress that this is very basic and will not work for all wav files.  You can manually adjust the HEADER_SIZE if it does not work for your file.

Likely the header record needs to be modified to reflect the correct size of the new file, instead of using the header from the original file.

This should get you started.


问:
assign headers based on existing row in dataframe in R
After transforming a dataframe, I would like to assign heads/names to the columns based on an existing row.
My headers are currently:

```<code>row.names   X2  X3  X4  X5  X6  X7  X8  X9  ...
</code>```

I would like to get rid of that and use the following row as column headers (without having to type them out since I have many).

The only solution I have for this is to export and re-load the data (with header=T).

答:
A new answer that uses dplyr and tidyr:

Extracts the desired column names and converts to a list

```<code>library(tidyverse)

col_names <- raw_dta %>%
  slice(2) %>%
  pivot_longer(
    cols = "X2":"X10", # until last named column
    names_to = "old_names",
    values_to = "new_names") %>%
  pull(new_names)
</code>```

Removes the incorrect rows and adds the correct column names

```<code>dta <- raw_dta %>%
  slice(-1, -2) %>% # Removes the rows containing new and original names
  set_names(., nm = col_names)

</code>```

Body:
After transforming a dataframe, I would like to assign heads/names to the columns based on an existing row.
My headers are currently:

row.names   X2  X3  X4  X5  X6  X7  X8  X9  ...

I would like to get rid of that and use the following row as column headers (without having to type them out since I have many).

The only solution I have for this is to export and re-load the data (with header=T).

Body:
A new answer that uses dplyr and tidyr:

Extracts the desired column names and converts to a list

library(tidyverse)

col_names <- raw_dta %>%
  slice(2) %>%
  pivot_longer(
    cols = "X2":"X10", # until last named column
    names_to = "old_names",
    values_to = "new_names") %>%
  pull(new_names)

Removes the incorrect rows and adds the correct column names

dta <- raw_dta %>%
  slice(-1, -2) %>% # Removes the rows containing new and original names
  set_names(., nm = col_names)


问:
Python: How to convert string entries with only numeric components in a column to integer?
I have a data frame with string type columns that have both character and numeric entries.

Below is an example df:

```<code>A        B
101a5    12222
11111    e2edw2
22222    33333
asxaa    0045
</code>```

I want to turn the entries with only numeric values from string into integer, but keep the rest as string.

What would be the best approach?

Thanks in advance!

答:
You can use the following function:

```<code>def func(x):
    try:
        return int(x)
    except ValueError:
        return x

df = df.applymap(func)

print(df.applymap(type))
</code>```

Output:

```<code>               A              B
0  <class 'str'>  <class 'int'>
1  <class 'int'>  <class 'str'>
2  <class 'int'>  <class 'int'>
3  <class 'str'>  <class 'int'>
</code>```

Body:
I have a data frame with string type columns that have both character and numeric entries.

Below is an example df:

A        B
101a5    12222
11111    e2edw2
22222    33333
asxaa    0045

I want to turn the entries with only numeric values from string into integer, but keep the rest as string.

What would be the best approach?

Thanks in advance!

Body:
You can use the following function:

def func(x):
    try:
        return int(x)
    except ValueError:
        return x

df = df.applymap(func)

print(df.applymap(type))

Output:

               A              B
0  <class 'str'>  <class 'int'>
1  <class 'int'>  <class 'str'>
2  <class 'int'>  <class 'int'>
3  <class 'str'>  <class 'int'>


问:
How can I determine where the Focus is *right now*?

The short version

```<code>public class CustomDataGrid : DataGridControl, IXmlSettingsProvider
{
    public CustomDataGrid()
    {
        if (DesignModeHelper.IsInDesignMode) return;

        Loaded += (e, a) =>
                      {
                          ...
                      };

        LostFocus += (e, a) =>
                         {
                             if(IsBeingEdited /* &&
                                CurrentFocusTarget.GetType() == typeof(TabControl)*/)
                                EndEdit();
                         };
    }
}
</code>```

How can I find UIElement CurrentFocusTarget in the above sample?

The long version - Context

We use the XCeed DataGrid in order to show data in different tabs of a lazy-loaded TabControl. Each tab is lazy-loaded so that the content gets rendered (and, more importantly, the data is fetch) only when the tab is Visible. The whole data flow works great using the MVVM approach.

The problem

Somehow, whenever the user makes changes to a cell and Changes Tab, the databound ViewModel property (that had already been updated) is being set to null.

In order to avoid this, it is possible to call EndEdit() when the focus is lost from the grid.

However, I only want to call it when the focus is lost to a TabItem (or the TabControl).

So, my question is:

What is the easiest way to know where the Focus is right now, from the codebehind. I have inspected the FocusManager but can't seem to find the current Focus bearer (or to whom the focus is lost).

答:
```<code>FocusManager.GetFocusedElement(Application.Current.MainWindow)
</code>```

I might need a special case if the DataGrid is not hosted in the Application.Current.MainWindow.

Here is the complete code:

```<code>public class CustomDataGrid : DataGridControl, IXmlSettingsProvider
{
    public BSIDataGrid()
    {
        if (DesignModeHelper.IsInDesignMode) return;

        CommandBindings.Add(new CommandBinding(ResetDataGridLayout, ResetDataGridLayoutExecute, ResetDataGridLayoutCanExecute));

        Loaded += (e, a) =>
                      {
                          ...
                      };

        LostFocus += (e, a) =>
                         {
                             if(IsBeingEdited && IsTabFocused())
                                EndEdit();
                         };
    }

    private static bool IsTabFocused()
    {
        var dependencyObject = FocusManager.GetFocusedElement(Application.Current.MainWindow);
        return dependencyObject is TabItem;
    }
}
</code>```

Body:
The short version

public class CustomDataGrid : DataGridControl, IXmlSettingsProvider
{
    public CustomDataGrid()
    {
        if (DesignModeHelper.IsInDesignMode) return;

        Loaded += (e, a) =>
                      {
                          ...
                      };

        LostFocus += (e, a) =>
                         {
                             if(IsBeingEdited /* &&
                                CurrentFocusTarget.GetType() == typeof(TabControl)*/)
                                EndEdit();
                         };
    }
}

How can I find UIElement CurrentFocusTarget in the above sample?

The long version - Context

We use the XCeed DataGrid in order to show data in different tabs of a lazy-loaded TabControl. Each tab is lazy-loaded so that the content gets rendered (and, more importantly, the data is fetch) only when the tab is Visible. The whole data flow works great using the MVVM approach.

The problem

Somehow, whenever the user makes changes to a cell and Changes Tab, the databound ViewModel property (that had already been updated) is being set to null.

In order to avoid this, it is possible to call EndEdit() when the focus is lost from the grid.

However, I only want to call it when the focus is lost to a TabItem (or the TabControl).

So, my question is:

What is the easiest way to know where the Focus is right now, from the codebehind. I have inspected the FocusManager but can't seem to find the current Focus bearer (or to whom the focus is lost).

Body:
FocusManager.GetFocusedElement(Application.Current.MainWindow)

I might need a special case if the DataGrid is not hosted in the Application.Current.MainWindow.

Here is the complete code:

public class CustomDataGrid : DataGridControl, IXmlSettingsProvider
{
    public BSIDataGrid()
    {
        if (DesignModeHelper.IsInDesignMode) return;

        CommandBindings.Add(new CommandBinding(ResetDataGridLayout, ResetDataGridLayoutExecute, ResetDataGridLayoutCanExecute));

        Loaded += (e, a) =>
                      {
                          ...
                      };

        LostFocus += (e, a) =>
                         {
                             if(IsBeingEdited && IsTabFocused())
                                EndEdit();
                         };
    }

    private static bool IsTabFocused()
    {
        var dependencyObject = FocusManager.GetFocusedElement(Application.Current.MainWindow);
        return dependencyObject is TabItem;
    }
}


问:
matching row values (text) with column names and return value
I am trying to find the column name with the same name as the text in another column called "region", and return the corresponding value. My data "df" looks like something similar to this

```<code>region  A   B   C   D   E   F
H      796  792 844 812 796 776
J      568  564 508 268 320 396
A      820  804 748 528 560 600
X      292  272 260 324 224 200
M      872  812 792 760 668 656
N      100 992  972 880 872 864
C      940  948 952 916 864 880
L      960  956 952 920 900 920
E      980  968 956 940 944 932
F      236  364 460 524 552 616
P      796  792 844 812 796 776
Q      568  564 508 268 320 396
</code>```

And I want to get something that looks like this:

```<code>region  A   B   C   D   E   F
H       NA  NA  NA  NA  NA  NA
J       NA  NA  NA  NA  NA  NA
A       820 NA  NA  NA  NA  NA
X       NA  NA  NA  NA  NA  NA
M       NA  NA  NA  NA  NA  NA
N       NA  NA  NA  NA  NA  NA
C       NA  NA  952 NA  NA  NA
L       NA  NA  NA  NA  NA  NA
E       NA  NA  NA  NA  944 NA
F       NA  NA  NA  NA  NA  616
P       NA  NA  NA  NA  NA  NA
Q       NA  NA  NA  NA  NA  NA
</code>```

To do this, I tried this piece of code from this other questions (Loop that matches row to column names and computes an average of the 3 preceding columns) but it only returns the position, and I would like to get the value as shown in the example above.

apply (df, MARGIN = 1, FUN = function(x, i){
  position <- (which(x[['region']] == colnames(df)))
})

How can I modify the code to get the real value?
Thanks

答:
Here is another base R code

```<code>df[-1]<-Map(function(v,k) {if(is.na(k)) v<-NA else v[-k]<-NA; v},df[-1],
            match(names(df[-1]),df$region))
</code>```

such that

```<code>> df
   region   A  B   C  D   E   F
1       H  NA NA  NA NA  NA  NA
2       J  NA NA  NA NA  NA  NA
3       A 820 NA  NA NA  NA  NA
4       X  NA NA  NA NA  NA  NA
5       M  NA NA  NA NA  NA  NA
6       N  NA NA  NA NA  NA  NA
7       C  NA NA 952 NA  NA  NA
8       L  NA NA  NA NA  NA  NA
9       E  NA NA  NA NA 944  NA
10      F  NA NA  NA NA  NA 616
11      P  NA NA  NA NA  NA  NA
12      Q  NA NA  NA NA  NA  NA
</code>```

Body:
I am trying to find the column name with the same name as the text in another column called "region", and return the corresponding value. My data "df" looks like something similar to this

region  A   B   C   D   E   F
H      796  792 844 812 796 776
J      568  564 508 268 320 396
A      820  804 748 528 560 600
X      292  272 260 324 224 200
M      872  812 792 760 668 656
N      100 992  972 880 872 864
C      940  948 952 916 864 880
L      960  956 952 920 900 920
E      980  968 956 940 944 932
F      236  364 460 524 552 616
P      796  792 844 812 796 776
Q      568  564 508 268 320 396

And I want to get something that looks like this:

region  A   B   C   D   E   F
H       NA  NA  NA  NA  NA  NA
J       NA  NA  NA  NA  NA  NA
A       820 NA  NA  NA  NA  NA
X       NA  NA  NA  NA  NA  NA
M       NA  NA  NA  NA  NA  NA
N       NA  NA  NA  NA  NA  NA
C       NA  NA  952 NA  NA  NA
L       NA  NA  NA  NA  NA  NA
E       NA  NA  NA  NA  944 NA
F       NA  NA  NA  NA  NA  616
P       NA  NA  NA  NA  NA  NA
Q       NA  NA  NA  NA  NA  NA

To do this, I tried this piece of code from this other questions (Loop that matches row to column names and computes an average of the 3 preceding columns) but it only returns the position, and I would like to get the value as shown in the example above.

apply (df, MARGIN = 1, FUN = function(x, i){
  position <- (which(x[['region']] == colnames(df)))
})

How can I modify the code to get the real value?
Thanks

Body:
Here is another base R code

df[-1]<-Map(function(v,k) {if(is.na(k)) v<-NA else v[-k]<-NA; v},df[-1],
            match(names(df[-1]),df$region))

such that

> df
   region   A  B   C  D   E   F
1       H  NA NA  NA NA  NA  NA
2       J  NA NA  NA NA  NA  NA
3       A 820 NA  NA NA  NA  NA
4       X  NA NA  NA NA  NA  NA
5       M  NA NA  NA NA  NA  NA
6       N  NA NA  NA NA  NA  NA
7       C  NA NA 952 NA  NA  NA
8       L  NA NA  NA NA  NA  NA
9       E  NA NA  NA NA 944  NA
10      F  NA NA  NA NA  NA 616
11      P  NA NA  NA NA  NA  NA
12      Q  NA NA  NA NA  NA  NA