问:
How to merge before build in a multi-branch pipeline?
For simple pipeline jobs I have the "merge before build" under Additional Behaviours. But how do I do that in a multi-branch pipeline? Can't find that option.

Thanks in advance.

答:
I will just post here what I did through code:</p>

```<code>def mergeBeforeBuild() {

  // Pull the source and test a merge
  try {
    def sourceScmCheck = checkout changelog: true, poll: true, scm: [
      $class: 'GitSCM',
      branches: [[name: "origin/$sourceBranch" ]],
      doGenerateSubmoduleConfigurations: false,
      extensions: [[
        $class: 'PreBuildMerge',
        options: [
          fastForwardMode: 'FF',
          mergeRemote: 'origin',
          mergeStrategy: 'default',
          mergeTarget: "${env.target_branch}"]],
        [$class: 'UserIdentity',
          email: 'jenkins@jenkins.com',
          name: 'jenkins'
      ]],
      submoduleCfg: [],
      userRemoteConfigs: [[
        credentialsId: 'githubCredentials',
        name: 'origin',
        url: "$repoUrl"
      ]]
    ]
  } catch (error) {
    currentBuild.result = 'FAILURE'
    echo "ERROR: ${error}"
    sh 'false'
  }
}
</code>```

Body:
I will just post here what I did through code:

def mergeBeforeBuild() {

  // Pull the source and test a merge
  try {
    def sourceScmCheck = checkout changelog: true, poll: true, scm: [
      $class: 'GitSCM',
      branches: [[name: "origin/$sourceBranch" ]],
      doGenerateSubmoduleConfigurations: false,
      extensions: [[
        $class: 'PreBuildMerge',
        options: [
          fastForwardMode: 'FF',
          mergeRemote: 'origin',
          mergeStrategy: 'default',
          mergeTarget: "${env.target_branch}"]],
        [$class: 'UserIdentity',
          email: 'jenkins@jenkins.com',
          name: 'jenkins'
      ]],
      submoduleCfg: [],
      userRemoteConfigs: [[
        credentialsId: 'githubCredentials',
        name: 'origin',
        url: "$repoUrl"
      ]]
    ]
  } catch (error) {
    currentBuild.result = 'FAILURE'
    echo "ERROR: ${error}"
    sh 'false'
  }
}


来源: stackexchange

问:
R - How to replicate and alter a dataframe based on a list of matching names using a loop
I have a data frame which consists of various species, and a column showing their presence (detection column). I want to end up with a list of data frames, one for each species. Within each species new data frame I want the matching species detection values be turned to a '1', while keeping all other species detection values as 0.  Here is an example data frame with two species:

```<code>structure(list(Camera.Trap.Name = c("CT-Tst-1-1", "CT-Tst-2-1",
"CT-Tst-2-1", "CT-Tst-2-1", "CT-Tst-2-1", "CT-Tst-2-1", "CT-Tst-2-1",
"CT-Tst-2-1", "CT-Tst-3-1", "CT-Tst-3-1", "CT-Tst-3-1", "CT-Tst-3-1",
"CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-5-1",
"CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-5-1",
"CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-5-1",
"CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-5-1",
"CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-8-1", "CT-Tst-8-1", "CT-Tst-8-1",
"CT-Tst-8-1", "CT-Tst-8-1", "CT-Tst-8-1", "CT-Tst-8-1", "CT-Tst-8-1",
"CT-Tst-8-1", "CT-Tst-9-1", "CT-Tst-9-1", "CT-Tst-9-1"), Sampling.Event = c("Olney 1",
"Olney 2", "Olney 2", "Olney 2", "Olney 2", "Olney 2", "Olney 2",
"Olney 2", "Olney 3", "Olney 3", "Olney 3", "Olney 3", "Olney 5",
"Olney 5", "Olney 5", "Olney 5", "Olney 5", "Olney 5", "Olney 5",
"Olney 5", "Olney 5", "Olney 5", "Olney 5", "Olney 5", "Olney 5",
"Olney 5", "Olney 5", "Olney 5", "Olney 5", "Olney 5", "Olney 5",
"Olney 7", "Olney 7", "Olney 7", "Olney 7", "Olney 7", "Olney 7",
"Olney 7", "Olney 7", "Olney 7", "Olney 7", "Olney 7", "Olney 7",
"Olney 5", "Olney 5", "Olney 5"), Photo.Date = c("2018-03-28",
"2018-04-20", "2018-05-02", "2018-05-07", "2018-05-09", "2018-05-10",
"2018-05-11", "2018-05-15", "2019-11-13", "2019-11-14", "2019-11-15",
"2019-11-16", "2020-03-24", "2020-03-25", "2020-03-26", "2020-03-31",
"2020-04-01", "2020-04-02", "2020-04-03", "2020-04-04", "2020-04-04",
"2020-04-05", "2020-04-06", "2020-04-06", "2020-04-07", "2020-04-07",
"2020-04-08", "2020-04-09", "2020-04-10", "2020-04-11", "2020-04-11",
"2020-04-23", "2020-04-24", "2020-05-02", "2020-04-28", "2020-04-29",
"2020-04-30", "2020-05-01", "2020-05-02", "2020-05-03", "2020-05-04",
"2020-05-05", "2020-05-06", "2020-04-01", "2020-04-05", "2020-04-06"
), Species_name = c("Vulpes vulpes", "Vulpes vulpes", "Vulpes vulpes",
"Vulpes vulpes", "Vulpes vulpes", "Vulpes vulpes", "Vulpes vulpes",
"Vulpes vulpes", "Vulpes vulpes", "Vulpes vulpes", "Vulpes vulpes",
"Vulpes vulpes", "Vulpes vulpes", "Lutra lutra", "Vulpes vulpes",
"Vulpes vulpes", "Vulpes vulpes", "Vulpes vulpes", "Vulpes vulpes",
"Lutra lutra", "Vulpes vulpes", "Vulpes vulpes", "Lutra lutra",
"Vulpes vulpes", "Lutra lutra", "Vulpes vulpes", "Vulpes vulpes",
"Vulpes vulpes", "Vulpes vulpes", "Lutra lutra", "Vulpes vulpes",
"Vulpes vulpes", "Vulpes vulpes", "Vulpes vulpes", "Lutra lutra",
"Lutra lutra", "Lutra lutra", "Lutra lutra", "Lutra lutra", "Lutra lutra",
"Lutra lutra", "Lutra lutra", "Lutra lutra", "Vulpes vulpes",
"Vulpes vulpes", "Vulpes vulpes"), Detection = c(0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
), Elevation = c(207, 213, 213, 213, 213, 213, 213, 213, 189,
189, 189, 189, 169, 169, 169, 169, 169, 169, 169, 169, 169, 169,
169, 169, 169, 169, 169, 169, 169, 169, 169, 169, 169, 169, 186,
186, 186, 186, 186, 186, 186, 186, 186, 222, 222, 222)), row.names = c(NA,
-46L), class = "data.frame")
</code>```

I would like to have something that looks like the following, if it was the new data frame for Vulpes vulpes:

```<code>Camera.Trap.Name Sampling.Event Photo.Date  Species_name Detection Elevation
CT-Tst-5-1        Olney 7       2020-05-02  Vulpes vulpes      1       169
CT-Tst-8-1        Olney 7       2020-04-28   Lutra lutra       0       186
CT-Tst-8-1        Olney 7       2020-04-29   Lutra lutra       0       186
</code>```

I have attempted to create list of unique species names, and create a loop that goes through the data frame, that changes the detection value to 1 if the names match, and finally create a new, updated data frame for that species. These were very unsuccessful so all help would be appreciated.
Thanks

答:
The approach you described is correct. However, you need to copy the data first before you modify the Detection value, so that you do not change the original data and the subsequent copies of it.

```<code>s = unique(df$Species_name)   # list of unique species names

m = list()   # empty list (to fill with copies of the data)

for (i in s) {
  temp = df  # make a copy of the data frame

   # change Detection to 1 where species name match
  temp$Detection[temp$Species_name==i] = 1

  m[[i]] = temp # place the new data in the array
}
</code>```

(the temp variable is just to make the code more readable. You can copy directly to m[[i]])

now you will have m as a list containing 2 dataframes:

```<code>> m[["Vulpes vulpes"]]
....
12       CT-Tst-3-1        Olney 3 2019-11-16 Vulpes vulpes         1       189
13       CT-Tst-5-1        Olney 5 2020-03-24 Vulpes vulpes         1       169
14       CT-Tst-5-1        Olney 5 2020-03-25   Lutra lutra         0       169
15       CT-Tst-5-1        Olney 5 2020-03-26 Vulpes vulpes         1       169
</code>```

and

```<code>> m[['Lutra lutra']]
....
12       CT-Tst-3-1        Olney 3 2019-11-16 Vulpes vulpes         0       189
13       CT-Tst-5-1        Olney 5 2020-03-24 Vulpes vulpes         0       169
14       CT-Tst-5-1        Olney 5 2020-03-25   Lutra lutra         1       169
15       CT-Tst-5-1        Olney 5 2020-03-26 Vulpes vulpes         0       169
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a data frame which consists of various species, and a column showing their presence (detection column). I want to end up with a list of data frames, one for each species. Within each species new data frame I want the matching species detection values be turned to a '1', while keeping all other species detection values as 0.  Here is an example data frame with two species:

structure(list(Camera.Trap.Name = c("CT-Tst-1-1", "CT-Tst-2-1",
"CT-Tst-2-1", "CT-Tst-2-1", "CT-Tst-2-1", "CT-Tst-2-1", "CT-Tst-2-1",
"CT-Tst-2-1", "CT-Tst-3-1", "CT-Tst-3-1", "CT-Tst-3-1", "CT-Tst-3-1",
"CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-5-1",
"CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-5-1",
"CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-5-1",
"CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-5-1",
"CT-Tst-5-1", "CT-Tst-5-1", "CT-Tst-8-1", "CT-Tst-8-1", "CT-Tst-8-1",
"CT-Tst-8-1", "CT-Tst-8-1", "CT-Tst-8-1", "CT-Tst-8-1", "CT-Tst-8-1",
"CT-Tst-8-1", "CT-Tst-9-1", "CT-Tst-9-1", "CT-Tst-9-1"), Sampling.Event = c("Olney 1",
"Olney 2", "Olney 2", "Olney 2", "Olney 2", "Olney 2", "Olney 2",
"Olney 2", "Olney 3", "Olney 3", "Olney 3", "Olney 3", "Olney 5",
"Olney 5", "Olney 5", "Olney 5", "Olney 5", "Olney 5", "Olney 5",
"Olney 5", "Olney 5", "Olney 5", "Olney 5", "Olney 5", "Olney 5",
"Olney 5", "Olney 5", "Olney 5", "Olney 5", "Olney 5", "Olney 5",
"Olney 7", "Olney 7", "Olney 7", "Olney 7", "Olney 7", "Olney 7",
"Olney 7", "Olney 7", "Olney 7", "Olney 7", "Olney 7", "Olney 7",
"Olney 5", "Olney 5", "Olney 5"), Photo.Date = c("2018-03-28",
"2018-04-20", "2018-05-02", "2018-05-07", "2018-05-09", "2018-05-10",
"2018-05-11", "2018-05-15", "2019-11-13", "2019-11-14", "2019-11-15",
"2019-11-16", "2020-03-24", "2020-03-25", "2020-03-26", "2020-03-31",
"2020-04-01", "2020-04-02", "2020-04-03", "2020-04-04", "2020-04-04",
"2020-04-05", "2020-04-06", "2020-04-06", "2020-04-07", "2020-04-07",
"2020-04-08", "2020-04-09", "2020-04-10", "2020-04-11", "2020-04-11",
"2020-04-23", "2020-04-24", "2020-05-02", "2020-04-28", "2020-04-29",
"2020-04-30", "2020-05-01", "2020-05-02", "2020-05-03", "2020-05-04",
"2020-05-05", "2020-05-06", "2020-04-01", "2020-04-05", "2020-04-06"
), Species_name = c("Vulpes vulpes", "Vulpes vulpes", "Vulpes vulpes",
"Vulpes vulpes", "Vulpes vulpes", "Vulpes vulpes", "Vulpes vulpes",
"Vulpes vulpes", "Vulpes vulpes", "Vulpes vulpes", "Vulpes vulpes",
"Vulpes vulpes", "Vulpes vulpes", "Lutra lutra", "Vulpes vulpes",
"Vulpes vulpes", "Vulpes vulpes", "Vulpes vulpes", "Vulpes vulpes",
"Lutra lutra", "Vulpes vulpes", "Vulpes vulpes", "Lutra lutra",
"Vulpes vulpes", "Lutra lutra", "Vulpes vulpes", "Vulpes vulpes",
"Vulpes vulpes", "Vulpes vulpes", "Lutra lutra", "Vulpes vulpes",
"Vulpes vulpes", "Vulpes vulpes", "Vulpes vulpes", "Lutra lutra",
"Lutra lutra", "Lutra lutra", "Lutra lutra", "Lutra lutra", "Lutra lutra",
"Lutra lutra", "Lutra lutra", "Lutra lutra", "Vulpes vulpes",
"Vulpes vulpes", "Vulpes vulpes"), Detection = c(0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
), Elevation = c(207, 213, 213, 213, 213, 213, 213, 213, 189,
189, 189, 189, 169, 169, 169, 169, 169, 169, 169, 169, 169, 169,
169, 169, 169, 169, 169, 169, 169, 169, 169, 169, 169, 169, 186,
186, 186, 186, 186, 186, 186, 186, 186, 222, 222, 222)), row.names = c(NA,
-46L), class = "data.frame")

I would like to have something that looks like the following, if it was the new data frame for Vulpes vulpes:

Camera.Trap.Name Sampling.Event Photo.Date  Species_name Detection Elevation
CT-Tst-5-1        Olney 7       2020-05-02  Vulpes vulpes      1       169
CT-Tst-8-1        Olney 7       2020-04-28   Lutra lutra       0       186
CT-Tst-8-1        Olney 7       2020-04-29   Lutra lutra       0       186

I have attempted to create list of unique species names, and create a loop that goes through the data frame, that changes the detection value to 1 if the names match, and finally create a new, updated data frame for that species. These were very unsuccessful so all help would be appreciated.
Thanks

Body:
The approach you described is correct. However, you need to copy the data first before you modify the Detection value, so that you do not change the original data and the subsequent copies of it.

s = unique(df$Species_name)   # list of unique species names

m = list()   # empty list (to fill with copies of the data)

for (i in s) {
  temp = df  # make a copy of the data frame

   # change Detection to 1 where species name match
  temp$Detection[temp$Species_name==i] = 1

  m[[i]] = temp # place the new data in the array
}

(the temp variable is just to make the code more readable. You can copy directly to m[[i]])

now you will have m as a list containing 2 dataframes:

> m[["Vulpes vulpes"]]
....
12       CT-Tst-3-1        Olney 3 2019-11-16 Vulpes vulpes         1       189
13       CT-Tst-5-1        Olney 5 2020-03-24 Vulpes vulpes         1       169
14       CT-Tst-5-1        Olney 5 2020-03-25   Lutra lutra         0       169
15       CT-Tst-5-1        Olney 5 2020-03-26 Vulpes vulpes         1       169

and

> m[['Lutra lutra']]
....
12       CT-Tst-3-1        Olney 3 2019-11-16 Vulpes vulpes         0       189
13       CT-Tst-5-1        Olney 5 2020-03-24 Vulpes vulpes         0       169
14       CT-Tst-5-1        Olney 5 2020-03-25   Lutra lutra         1       169
15       CT-Tst-5-1        Olney 5 2020-03-26 Vulpes vulpes         0       169


问:
Generic Type Linked List in TypeScript?
I'm making a linked list in TypeScript and want to type guard the value type of the link node to be the same as all link nodes in the list. Is this behavior possible?

Generic Single Link Node

```<code>class SingleLink<T> {
  next: SingleLink<T> | null;

  constructor(public value: T) {
    this.next = null;
  }
}
</code>```

Linked List

```<code>class LinkedList<T> {
  private len: number;
  private hd: SingleLink<T> | null;
  private tl: SingleLink<T> | null;

  constructor() {
    this.len = 0;
    this.hd = null;
    this.tl = null;
  }

  // properties getters
  // ...
  // ...

  push(input: T) {
    const link = new SingleLink(input);

    if(this.tl) {
      this.tl.next = link;
      this.tl = link;
    } else {
      this.hd = link;
      this.hd.next = link;
      this.tl = link;
    }

    return ++this.len;
  }

  // methods ...
  // ...
}
</code>```

Desired Behavior

```<code>const li1 = new LinkedList();

li1.push(10) // li1 should only accept number

li1.push("a") // type error

const li2 = new LinkedList();

li2.push("A") // li2 should only accept string
li2.push(15) // type error
</code>```

Current Behavior

currently the Linked List accepts any type

```<code>const li = new LinkedList();

li.push(15);
li.push("a"); // No type error occur
</code>```

答:
```<code>const li1 = new LinkedList<number>();

li1.push(10)

li1.push("a") // Errors out
</code>```

If you don't mention the type to LinkedList, by default it assumes it to be unknown and hence it accepts values of all types

Title: Generic Type Linked List in TypeScript?

Body:
I'm making a linked list in TypeScript and want to type guard the value type of the link node to be the same as all link nodes in the list. Is this behavior possible?

Generic Single Link Node

class SingleLink<T> {
  next: SingleLink<T> | null;

  constructor(public value: T) {
    this.next = null;
  }
}

Linked List

class LinkedList<T> {
  private len: number;
  private hd: SingleLink<T> | null;
  private tl: SingleLink<T> | null;

  constructor() {
    this.len = 0;
    this.hd = null;
    this.tl = null;
  }

  // properties getters
  // ...
  // ...

  push(input: T) {
    const link = new SingleLink(input);

    if(this.tl) {
      this.tl.next = link;
      this.tl = link;
    } else {
      this.hd = link;
      this.hd.next = link;
      this.tl = link;
    }

    return ++this.len;
  }

  // methods ...
  // ...
}

Desired Behavior

const li1 = new LinkedList();

li1.push(10) // li1 should only accept number

li1.push("a") // type error

const li2 = new LinkedList();

li2.push("A") // li2 should only accept string
li2.push(15) // type error

Current Behavior

currently the Linked List accepts any type

const li = new LinkedList();

li.push(15);
li.push("a"); // No type error occur

Body:
const li1 = new LinkedList<number>();

li1.push(10)

li1.push("a") // Errors out

If you don't mention the type to LinkedList, by default it assumes it to be unknown and hence it accepts values of all types


问:
LDAP authentication using ldapjs in nodejs
Am a newbie to node.js, have somewhat figured out the LDAP authentication. Here am trying to retrieve employee ID from the search but none of the search entries are fetched though the passed credentials are bounded successfully , not sure where i'm mislead. If someone could help me out in it would be of a great help!

Below are the result sets of the code snippet:

Reader bind succeeded
Search results length: 0
Search
retval:{"messageID":2,"protocolOp":"LDAPResult","status":0,"matchedDN":"","errorMessage":"","referrals":[],"controls":[]}
No unique user to bind

ldapRoute.route('/ldap').post((req, res, next) => {

 var result = "";

 var email =req.body.email;

 var client = ldap.createClient({
        url: 'ldap://******'
 });

 var opts = {
  filter: '(sAMAccountName='+ email + ')',
  attributes: ['sAMAccountName']
  };

var username = 'ii' + "\\" + email;

client.bind(username, req.body.password, function(err) {
    if (err){
  result += "Reader bind failed " + err;
    res.send(result);
    return;

 }
 else{

    result += "Reader bind succeeded\n";
 }

 client.search('OU=emp,dc=i,dc=ac,dc=com', opts, function(err, searchRes) {

 var searchList = []

 if (err) {
    result += "Search failed " + err;
    res.send(result);
    return;
 }

searchRes.on("searchEntry", (entry) => {
    result += "Found entry: " + entry + "\n";
    searchList.push(entry);

 });

searchRes.on("error", (err) => {
    result += "Search failed with " + err;
    res.send(result);

 });

searchRes.on("end", (retVal) => {
    result += "Search results length: " + searchList.length + "\n";
    for(var i=0; i<searchList.length; i++)
    result += "DN:" + searchList[i].employeeID + "\n";
    result += "Search retval:" + retVal + "\n";

  if (searchList.length == 1)   {
    client.bind(searchList[0].employeeID, req.body.password, function(err) {
      if (err)
         result += "Bind with real credential error: " + err;
      else
        result += "Bind with real credential is a success";

     res.send(result);
  });  // client.bind (real credential)

  } else {
                        result += "No unique user to bind";
                        res.send(result);
                    }

         });

  });

 });

});```

答:
The issue was in the filters and for some strange reasons the 'end' got fired before hitting the 'searchEntry', debugging it helped me to resolve the issue.</p>

```<code>//Filter
var opts = {
 filter: '(sAMAccountName=' + email+')',
 scope: 'sub',
 attributes: ['employeeID']
 };

//Search
client.search('OU=empl,dc=ii,dc=ac,dc=in', opts, function(err, searchRes)
{
   if (err)
 {
   result += "Search failed " + err;
   res.send(result);
   return;
 }else{
searchRes.on("searchEntry", (entry) =>
 {
   result += "Found entry: " + entry.object.employeeID;
   res.send(result);
 }
 / ........../
} });
</code>```

Body:
The issue was in the filters and for some strange reasons the 'end' got fired before hitting the 'searchEntry', debugging it helped me to resolve the issue.

//Filter
var opts = {
 filter: '(sAMAccountName=' + email+')',
 scope: 'sub',
 attributes: ['employeeID']
 };

//Search
client.search('OU=empl,dc=ii,dc=ac,dc=in', opts, function(err, searchRes)
{
   if (err)
 {
   result += "Search failed " + err;
   res.send(result);
   return;
 }else{
searchRes.on("searchEntry", (entry) =>
 {
   result += "Found entry: " + entry.object.employeeID;
   res.send(result);
 }
 / ........../
} });


问:
Undefined symbol: _OBJC_CLASS_$_FIRAnalytics
I am trying to Call Firebase Analytics in my iOS app ,i am getting error while compiling project .

I have created one framework and from that framework calling firebase analytics but I don’t understand getting below error.

```<code>Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_FIRAnalytics", referenced from:
      objc-class-ref in ViewController.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Showing Recent Errors Only
:-1: Undefined symbol: _OBJC_CLASS_$_FIRAnalytics
</code>```

Below is my app structure

iOS App

MyCustom Framework

Viewcontroller

答: Please make sure you import the PromisesObjc.framework after deleting your old Firebase libraries. I tried all the other steps but this one was also required.

Body:
I am trying to Call Firebase Analytics in my iOS app ,i am getting error while compiling project .

I have created one framework and from that framework calling firebase analytics but I don’t understand getting below error.

Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_FIRAnalytics", referenced from:
      objc-class-ref in ViewController.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Showing Recent Errors Only
:-1: Undefined symbol: _OBJC_CLASS_$_FIRAnalytics

Below is my app structure

iOS App

MyCustom Framework

Viewcontroller


问:
UICollectionViewCell zero spacing not working
I did create a custom calendar based on UICollectionView.

One UICollectionViewCell - one date in the calendar. I want to delete spacing between cells.
CollectionView layout settings -

```<code>func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: (collectionView.frame.width / 7), height: collectionView.frame.width / 7)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0.0
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 0.0
}
</code>```

In different screen sizes, unless iPhone X, we will see the spacing between cells.

How to fix it?

答:
You probably have a rounding error. You are saying

```<code>collectionView.frame.width / 7
</code>```

An iPhone 11 is 414 points wide. 414 / 7 is 59.14285714. There is no way to portray a fractional point on the screen, so now what? We round down, and now there is an extra pixel space between cells.

Body:
I did create a custom calendar based on UICollectionView.

One UICollectionViewCell - one date in the calendar. I want to delete spacing between cells.
CollectionView layout settings -

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: (collectionView.frame.width / 7), height: collectionView.frame.width / 7)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0.0
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 0.0
}

In different screen sizes, unless iPhone X, we will see the spacing between cells.

How to fix it?

Body:
You probably have a rounding error. You are saying

collectionView.frame.width / 7

An iPhone 11 is 414 points wide. 414 / 7 is 59.14285714. There is no way to portray a fractional point on the screen, so now what? We round down, and now there is an extra pixel space between cells.


问:
Nodejs Mysql connection best practice
What is the best practice when we want to create MySql connection in nodejs.

Create a global connection and use it for all queries

Open a new connection for each query and close it after the query is done.

答:
Connection pooling will handle your requests automatically.

This article covers the topic and might be helpful - https://medium.com/@mhagemann/create-a-mysql-database-middleware-with-node-js-8-and-async-await-6984a09d49f4

Title: Nodejs Mysql connection best practice


问:
How to read complex numbers from a file using class and problem with access to private variable in C++?
I get a task. I must read complex numbers from a file and write them into another file. In class, I must create two private variables for the real number and imaginary number. A little bigger function I must create outside class as inline functions.

This is my code:

```<code>#include <iostream>
#include <fstream>
#include <cstdlib>
#include <assert.h>

using namespace std;

class Complex_num {
    double real, imag;
public:
    Complex_num(){
    real=0;
    imag=0;
    }

    friend std::ostream& operator<<(std::ostream&, const Complex_num&);
    friend std::istream& operator>>(std::istream&, Complex_num&);
};

inline void readC(FILE *wp, double *real, double *imag) {
    char c;
    assert(fscanf(wp,"%c%lg%c%lg%c%c",&c,real,&c,real,&c,&c));
}
inline int writeC(FILE *wp, double real, double imag)
{
    fprintf(wp, "%.2f, %.2f\n", real, imag);

    return 1;
}

int main(int argc, char* argv[])
{
    FILE *wz, *wc;

    char c;
    ifstream read(argv[1]);
    if (!read)
        { cerr << "Open error: " << argv[1] << endl; exit(1);}
    ofstream write(argv[2]);
    if(!write) { cerr << "Open error: " << argv[2] << endl; exit(2);}
    while(read.get(c))
        write.put(c);

    Complex_num x1;
    readC(wz, x1.real, x1.imag);
    write(wc, x1.real, x1.imag);

    return 0;
}
</code>```

I have some errors

```<code>czyt_pisanie.cpp: In function ‘int main(int, char**)’:
czyt_pisanie.cpp:48:18: error: ‘double Complex_num::real’ is private within this context
     readC(wz, x1.real, x1.imag);
                  ^~~~
czyt_pisanie.cpp:9:12: note: declared private here
     double real, imag;
            ^~~~
czyt_pisanie.cpp:48:27: error: ‘double Complex_num::imag’ is private within this context
     readC(wz, x1.real, x1.imag);
                           ^~~~
czyt_pisanie.cpp:9:18: note: declared private here
     double real, imag;
                  ^~~~
czyt_pisanie.cpp:48:31: error: cannot convert ‘double’ to ‘double*’ for argument ‘2’ to ‘void readC(FILE*, double*, double*)’
     readC(wz, x1.real, x1.imag);
                               ^
czyt_pisanie.cpp:49:18: error: ‘double Complex_num::real’ is private within this context
     write(wc, x1.real, x1.imag);
                  ^~~~
czyt_pisanie.cpp:9:12: note: declared private here
     double real, imag;
            ^~~~
czyt_pisanie.cpp:49:27: error: ‘double Complex_num::imag’ is private within this context
     write(wc, x1.real, x1.imag);
                           ^~~~
czyt_pisanie.cpp:9:18: note: declared private here
     double real, imag;
                  ^~~~
czyt_pisanie.cpp:49:31: error: no match for call to ‘(std::ofstream {aka std::basic_ofstream<char>}) (FILE*&, double&, double&)’
     write(wc, x1.real, x1.imag);

</code>```

I also have operators, but I don't know what I should do with them

```<code>    friend std::ostream& operator<<(std::ostream&, const Complex_num&);
    friend std::istream& operator>>(std::istream&, Complex_num&);
</code>```

答:
Well, you can't access the private variables on your class, because they are PRIVATE.
You are out of their context on the main function, create a public getter function like this on ComplexNumber class:

```<code>class Complex_num {
    double real, imag;
public:
    Complex_num(){
    real=0;
    imag=0;
    }
    double getReal(){ return real; }
};
</code>```

Alternativelly you can just make the two variables public.
You also should change the readC and writeC to receive a ComplexNumber object as parameter, and then use the getReal() method inside of it.

About the file reading, stop using the C way of writing and reading a file. They provided you a operator override to read ComplexNumber directly from a file, something like this:

```<code>  ofstream outputfile;
  outputfile.open ("example.txt");
  /* Check for opening */
  outputfile << _complexNumber;
  outputfile.close();

  ifstream inputfile;
  inputfile.open ("example.txt");
  /* Check for opening */
  inputfile >> _complexNumber;
  inputfile.close();
</code>```

Having _complexNumber as the function parameter.

Body:
I get a task. I must read complex numbers from a file and write them into another file. In class, I must create two private variables for the real number and imaginary number. A little bigger function I must create outside class as inline functions.

This is my code:

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <assert.h>

using namespace std;

class Complex_num {
    double real, imag;
public:
    Complex_num(){
    real=0;
    imag=0;
    }

    friend std::ostream& operator<<(std::ostream&, const Complex_num&);
    friend std::istream& operator>>(std::istream&, Complex_num&);
};

inline void readC(FILE *wp, double *real, double *imag) {
    char c;
    assert(fscanf(wp,"%c%lg%c%lg%c%c",&c,real,&c,real,&c,&c));
}
inline int writeC(FILE *wp, double real, double imag)
{
    fprintf(wp, "%.2f, %.2f\n", real, imag);

    return 1;
}

int main(int argc, char* argv[])
{
    FILE *wz, *wc;

    char c;
    ifstream read(argv[1]);
    if (!read)
        { cerr << "Open error: " << argv[1] << endl; exit(1);}
    ofstream write(argv[2]);
    if(!write) { cerr << "Open error: " << argv[2] << endl; exit(2);}
    while(read.get(c))
        write.put(c);

    Complex_num x1;
    readC(wz, x1.real, x1.imag);
    write(wc, x1.real, x1.imag);

    return 0;
}

I have some errors

czyt_pisanie.cpp: In function ‘int main(int, char**)’:
czyt_pisanie.cpp:48:18: error: ‘double Complex_num::real’ is private within this context
     readC(wz, x1.real, x1.imag);
                  ^~~~
czyt_pisanie.cpp:9:12: note: declared private here
     double real, imag;
            ^~~~
czyt_pisanie.cpp:48:27: error: ‘double Complex_num::imag’ is private within this context
     readC(wz, x1.real, x1.imag);
                           ^~~~
czyt_pisanie.cpp:9:18: note: declared private here
     double real, imag;
                  ^~~~
czyt_pisanie.cpp:48:31: error: cannot convert ‘double’ to ‘double*’ for argument ‘2’ to ‘void readC(FILE*, double*, double*)’
     readC(wz, x1.real, x1.imag);
                               ^
czyt_pisanie.cpp:49:18: error: ‘double Complex_num::real’ is private within this context
     write(wc, x1.real, x1.imag);
                  ^~~~
czyt_pisanie.cpp:9:12: note: declared private here
     double real, imag;
            ^~~~
czyt_pisanie.cpp:49:27: error: ‘double Complex_num::imag’ is private within this context
     write(wc, x1.real, x1.imag);
                           ^~~~
czyt_pisanie.cpp:9:18: note: declared private here
     double real, imag;
                  ^~~~
czyt_pisanie.cpp:49:31: error: no match for call to ‘(std::ofstream {aka std::basic_ofstream<char>}) (FILE*&, double&, double&)’
     write(wc, x1.real, x1.imag);

I also have operators, but I don't know what I should do with them

    friend std::ostream& operator<<(std::ostream&, const Complex_num&);
    friend std::istream& operator>>(std::istream&, Complex_num&);

Body:
Well, you can't access the private variables on your class, because they are PRIVATE.
You are out of their context on the main function, create a public getter function like this on ComplexNumber class:

class Complex_num {
    double real, imag;
public:
    Complex_num(){
    real=0;
    imag=0;
    }
    double getReal(){ return real; }
};

Alternativelly you can just make the two variables public.
You also should change the readC and writeC to receive a ComplexNumber object as parameter, and then use the getReal() method inside of it.

About the file reading, stop using the C way of writing and reading a file. They provided you a operator override to read ComplexNumber directly from a file, something like this:

  ofstream outputfile;
  outputfile.open ("example.txt");
  /* Check for opening */
  outputfile << _complexNumber;
  outputfile.close();

  ifstream inputfile;
  inputfile.open ("example.txt");
  /* Check for opening */
  inputfile >> _complexNumber;
  inputfile.close();

Having _complexNumber as the function parameter.


问:
I'm trying to create a guessing game but it won't work
I'm trying to create a guessing game where you have to guess a number between 1 and 10, however if you enter 0 then it quits the program. I managed to get it to work (minus the quit part) so I tried adding the next step, the quit feature. I'd assume based off the order of the else if that first if you get the correct number then it says "you won the game", which is what happens, however if the answer is wrong it just quits. I'm trying to get it to only quit if the user types in 0 but it quits no matter what number you type in (as long as it's not the right one) I've spent hours and hours trying different things but nothing seems to work. Here's the code:</p>

```<code>public static void main(String[] args) {
    int secretNumber;
    int guess;
    secretNumber = (int) (Math.random() * 9 + 1);

    Scanner keyboard = new Scanner(System.in);
    System.out.print("Guess a number between 1 and 10: ");

    guess = keyboard.nextInt();

    if (guess == secretNumber)

        System.out.println("You won the game");

    else if (guess == 0)

        System.exit(0);

    else

        System.out.println("Invalid guess!");
}
</code>```

答:
Take a look at this :  </p>

```<code> public static void main(String[] args) {
    int secretNumber;
    int guess;
    secretNumber = (int) (Math.random() * 9 + 1);
    boolean playAgain=true;
    System.out.print("Guess a number between 1 and 10: ");
    do {
       Scanner keyboard = new Scanner(System.in);
       guess = keyboard.nextInt();

       if (guess == secretNumber) {
           System.out.println("You won the game");
           playAgain = false;
       }
       else if (guess == 0)
           System.exit(0);
       else {
           System.out.println("Invalid guess!");
           System.out.print("Try again,Guess a number between 1 and 10:");
       }
   }while(playAgain);
}
</code>```

Body:
I'm trying to create a guessing game where you have to guess a number between 1 and 10, however if you enter 0 then it quits the program. I managed to get it to work (minus the quit part) so I tried adding the next step, the quit feature. I'd assume based off the order of the else if that first if you get the correct number then it says "you won the game", which is what happens, however if the answer is wrong it just quits. I'm trying to get it to only quit if the user types in 0 but it quits no matter what number you type in (as long as it's not the right one) I've spent hours and hours trying different things but nothing seems to work. Here's the code:

public static void main(String[] args) {
    int secretNumber;
    int guess;
    secretNumber = (int) (Math.random() * 9 + 1);

    Scanner keyboard = new Scanner(System.in);
    System.out.print("Guess a number between 1 and 10: ");

    guess = keyboard.nextInt();

    if (guess == secretNumber)

        System.out.println("You won the game");

    else if (guess == 0)

        System.exit(0);

    else

        System.out.println("Invalid guess!");
}

Body:
Take a look at this :

 public static void main(String[] args) {
    int secretNumber;
    int guess;
    secretNumber = (int) (Math.random() * 9 + 1);
    boolean playAgain=true;
    System.out.print("Guess a number between 1 and 10: ");
    do {
       Scanner keyboard = new Scanner(System.in);
       guess = keyboard.nextInt();

       if (guess == secretNumber) {
           System.out.println("You won the game");
           playAgain = false;
       }
       else if (guess == 0)
           System.exit(0);
       else {
           System.out.println("Invalid guess!");
           System.out.print("Try again,Guess a number between 1 and 10:");
       }
   }while(playAgain);
}


问:
tf.data.Dataset: The `batch_size` argument must not be specified for the given input type
I'm using Talos and Google colab TPU to run hyperparameter tuning of a Keras model. Note that I'm using Tensorflow 1.15.0 and Keras 2.2.4-tf.

import os
import tensorflow as tf
import talos as ta
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam
from sklearn.model_selection import train_test_split

def iris_model(x_train, y_train, x_val, y_val, params):

    # Specify a distributed strategy to use TPU
    resolver = tf.contrib.cluster_resolver.TPUClusterResolver(tpu='grpc://' + os.environ['COLAB_TPU_ADDR'])
    tf.contrib.distribute.initialize_tpu_system(resolver)
    strategy = tf.contrib.distribute.TPUStrategy(resolver)

    # Use the strategy to create and compile a Keras model
    with strategy.scope():
      model = Sequential()
      model.add(Dense(32, input_shape=(4,), activation=tf.nn.relu, name="relu"))
      model.add(Dense(3, activation=tf.nn.softmax, name="softmax"))
      model.compile(optimizer=Adam(learning_rate=0.1), loss=params['losses'])

    # Convert data type to use TPU
    x_train = x_train.astype('float32')
    x_val = x_val.astype('float32')

    dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
    dataset = dataset.cache()
    dataset = dataset.shuffle(1000, reshuffle_each_iteration=True).repeat()
    dataset = dataset.batch(params['batch_size'], drop_remainder=True)

    # Fit the Keras model on the dataset
    out = model.fit(dataset, batch_size=params['batch_size'], epochs=params['epochs'], validation_data=[x_val, y_val], verbose=0, steps_per_epoch=2)

    return out, model

# Load dataset
X, y = ta.templates.datasets.iris()

# Train and test set
x_train, x_val, y_train, y_val = train_test_split(X, y, test_size=0.30, shuffle=False)

# Create a hyperparameter distributions
p = {'losses': ['logcosh'], 'batch_size': [128, 256, 384, 512, 1024], 'epochs': [10, 20]}

# Use Talos to scan the best hyperparameters of the Keras model
scan_object = ta.Scan(x_train, y_train, params=p, model=iris_model, experiment_name='test', x_val=x_val, y_val=y_val, fraction_limit=0.1)
```

<p>After converting the train set to a Dataset using <code>tf.data.Dataset</code>, I get the following error when fitting the model with <code>out = model.fit</code>:</p>

```---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-3-c812209b95d0> in <module>()
      8
      9 # Use Talos to scan the best hyperparameters of the Keras model
---> 10 scan_object = ta.Scan(x_train, y_train, params=p, model=iris_model, experiment_name='test', x_val=x_val, y_val=y_val, fraction_limit=0.1)

8 frames
/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/keras/engine/training.py in _validate_or_infer_batch_size(self, batch_size, steps, x)
   1813             'The `batch_size` argument must not be specified for the given '
   1814             'input type. Received input: {}, batch_size: {}'.format(
-> 1815                 x, batch_size))
   1816       return
   1817

ValueError: The `batch_size` argument must not be specified for the given input type. Received input: <DatasetV1Adapter shapes: ((512, 4), (512, 3)), types: (tf.float32, tf.float32)>, batch_size: 512
```

<p>Then, if I follow those instructions and don't set the batch-size argument to <code>model.fit</code>. I get another error in:</p>

```---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-c812209b95d0> in <module>()
      8
      9 # Use Talos to scan the best hyperparameters of the Keras model
---> 10 scan_object = ta.Scan(x_train, y_train, params=p, model=iris_model, experiment_name='test', x_val=x_val, y_val=y_val, fraction_limit=0.1)

8 frames
/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/keras/engine/training.py in _distribution_standardize_user_data(self, x, y, sample_weight, class_weight, batch_size, validation_split, shuffle, epochs, allow_partial_batch)
   2307             strategy) and not drop_remainder:
   2308           dataset_size = first_x_value.shape[0]
-> 2309           if dataset_size % batch_size == 0:
   2310             drop_remainder = True
   2311

TypeError: unsupported operand type(s) for %: 'int' and 'NoneType'
```

答:
It looks to me that the problem with your code is that the training
and validation data is not in the same format. You are batching the
training data but not the validation examples.

You can ensure that they are in the same format by replacing the
bottom half of your iris_model function with this:

```<code>def fix_data(x, y):
    x = x.astype('float32')
    ds = Dataset.from_tensor_slices((x, y))
    ds = ds.cache()
    ds = ds.shuffle(1000, reshuffle_each_iteration = True)
    ds = ds.repeat()
    ds = ds.batch(params['batch_size'], drop_remainder = True)
    return ds
train = fix_data(x_train, y_train)
val = fix_data(x_val, y_val)

# Fit the Keras model on the dataset
out = model.fit(x = train, epochs = params['epochs'],
                steps_per_epoch = 2,
                validation_data = val,
                validation_steps = 2)
</code>```

At least this works for me and your code runs without error.

Body:
I'm using Talos and Google colab TPU to run hyperparameter tuning of a Keras model. Note that I'm using Tensorflow 1.15.0 and Keras 2.2.4-tf.

import os
import tensorflow as tf
import talos as ta
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam
from sklearn.model_selection import train_test_split

def iris_model(x_train, y_train, x_val, y_val, params):

    # Specify a distributed strategy to use TPU
    resolver = tf.contrib.cluster_resolver.TPUClusterResolver(tpu='grpc://' + os.environ['COLAB_TPU_ADDR'])
    tf.contrib.distribute.initialize_tpu_system(resolver)
    strategy = tf.contrib.distribute.TPUStrategy(resolver)

    # Use the strategy to create and compile a Keras model
    with strategy.scope():
      model = Sequential()
      model.add(Dense(32, input_shape=(4,), activation=tf.nn.relu, name="relu"))
      model.add(Dense(3, activation=tf.nn.softmax, name="softmax"))
      model.compile(optimizer=Adam(learning_rate=0.1), loss=params['losses'])

    # Convert data type to use TPU
    x_train = x_train.astype('float32')
    x_val = x_val.astype('float32')

    dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
    dataset = dataset.cache()
    dataset = dataset.shuffle(1000, reshuffle_each_iteration=True).repeat()
    dataset = dataset.batch(params['batch_size'], drop_remainder=True)

    # Fit the Keras model on the dataset
    out = model.fit(dataset, batch_size=params['batch_size'], epochs=params['epochs'], validation_data=[x_val, y_val], verbose=0, steps_per_epoch=2)

    return out, model

# Load dataset
X, y = ta.templates.datasets.iris()

# Train and test set
x_train, x_val, y_train, y_val = train_test_split(X, y, test_size=0.30, shuffle=False)

# Create a hyperparameter distributions
p = {'losses': ['logcosh'], 'batch_size': [128, 256, 384, 512, 1024], 'epochs': [10, 20]}

# Use Talos to scan the best hyperparameters of the Keras model
scan_object = ta.Scan(x_train, y_train, params=p, model=iris_model, experiment_name='test', x_val=x_val, y_val=y_val, fraction_limit=0.1)

After converting the train set to a Dataset using tf.data.Dataset, I get the following error when fitting the model with out = model.fit:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-3-c812209b95d0> in <module>()
      8
      9 # Use Talos to scan the best hyperparameters of the Keras model
---> 10 scan_object = ta.Scan(x_train, y_train, params=p, model=iris_model, experiment_name='test', x_val=x_val, y_val=y_val, fraction_limit=0.1)

8 frames
/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/keras/engine/training.py in _validate_or_infer_batch_size(self, batch_size, steps, x)
   1813             'The `batch_size` argument must not be specified for the given '
   1814             'input type. Received input: {}, batch_size: {}'.format(
-> 1815                 x, batch_size))
   1816       return
   1817

ValueError: The `batch_size` argument must not be specified for the given input type. Received input: <DatasetV1Adapter shapes: ((512, 4), (512, 3)), types: (tf.float32, tf.float32)>, batch_size: 512

Then, if I follow those instructions and don't set the batch-size argument to model.fit. I get another error in:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-c812209b95d0> in <module>()
      8
      9 # Use Talos to scan the best hyperparameters of the Keras model
---> 10 scan_object = ta.Scan(x_train, y_train, params=p, model=iris_model, experiment_name='test', x_val=x_val, y_val=y_val, fraction_limit=0.1)

8 frames
/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/keras/engine/training.py in _distribution_standardize_user_data(self, x, y, sample_weight, class_weight, batch_size, validation_split, shuffle, epochs, allow_partial_batch)
   2307             strategy) and not drop_remainder:
   2308           dataset_size = first_x_value.shape[0]
-> 2309           if dataset_size % batch_size == 0:
   2310             drop_remainder = True
   2311

TypeError: unsupported operand type(s) for %: 'int' and 'NoneType'

Body:
It looks to me that the problem with your code is that the training
and validation data is not in the same format. You are batching the
training data but not the validation examples.

You can ensure that they are in the same format by replacing the
bottom half of your iris_model function with this:

def fix_data(x, y):
    x = x.astype('float32')
    ds = Dataset.from_tensor_slices((x, y))
    ds = ds.cache()
    ds = ds.shuffle(1000, reshuffle_each_iteration = True)
    ds = ds.repeat()
    ds = ds.batch(params['batch_size'], drop_remainder = True)
    return ds
train = fix_data(x_train, y_train)
val = fix_data(x_val, y_val)

# Fit the Keras model on the dataset
out = model.fit(x = train, epochs = params['epochs'],
                steps_per_epoch = 2,
                validation_data = val,
                validation_steps = 2)

At least this works for me and your code runs without error.


问:
How to set the size attribute of a Material UI Select component with multiple options?
I'm trying to set what would be the size attribute on a native HTML select element. This dictates how many options to show (i.e. the vertical height) in the multi-select. I cannot see a prop for this in the docs.

```<code><Field
  component={Select}
  disabled={props.disabled}
  name={props.name}
  multiple
  native
  size={props.size || 4}
>
  {props.children}
</Field>
</code>```

The size attribute is ineffective here and appears to default to four options but I'd like more.

The Field component in the example code is from formik and Select is from formik-material-ui.

答:
You can specify size via inputProps:

```<code><Field component={Select} multiple native inputProps={{ size: 6 }} ...>
  {options}
</Field>
</code>```

Body:
I'm trying to set what would be the size attribute on a native HTML select element. This dictates how many options to show (i.e. the vertical height) in the multi-select. I cannot see a prop for this in the docs.

<Field
  component={Select}
  disabled={props.disabled}
  name={props.name}
  multiple
  native
  size={props.size || 4}
>
  {props.children}
</Field>

The size attribute is ineffective here and appears to default to four options but I'd like more.

The Field component in the example code is from formik and Select is from formik-material-ui.

Body:
You can specify size via inputProps:

<Field component={Select} multiple native inputProps={{ size: 6 }} ...>
  {options}
</Field>


问:
Replacing items in message queue
Our system requirements say that we need to build a slightly unusual producer-consumer processing system. Imagine we have multiple data streams and we take a snapshot each X seconds and put it into the queue for processing. The streams count is not constant. The more clients we have, the more streams we need to process. At the same time, we don't need to process ALL taken snapshots. If we have too many clients and we are not able to process all items in real-time, we would prefer to skip old snapshots and process only the latest ones.

So as I see, the requirements can be met by keeping only one item in a queue for each stream. If there is a new snapshot, while the previous is still there, we need to REPLACE it using stream id as a key.
Is it possible to implement such behavior by Service Bus queue or something similar? Or maybe it makes sense to look into some other solutions like Redis?

答:
So as I see, the requirements can be met by keeping only one item in a
  queue for each stream. If there is a new snapshot, while the previous
  is still there, we need to REPLACE it using stream id as a key. Is it
  possible to implement such behavior by Service Bus queue or something
  similar?

To the best of my knowledge, Azure Service Bus does not support this scenario. Through it's duplicate detection functionality, in fact it supports exact opposite of that. You would need to use some other mechanism (like Redis Cache you mentioned) to accomplish this.

Title: Replacing items in message queue


问:
How to solve this error Error: Could not resolve the package
```<code>Compiler message:
Error: Could not resolve the package 'razorpay_flutter' in
'package:razorpay_flutter/razorpay_flutter.dart'.
lib/Screens/add_amount.dart:5:8: Error: Not found:
'package:razorpay_flutter/razorpay_flutter.dart'
import 'package:razorpay_flutter/razorpay_flutter.dart';
</code>```

I a implementing the flutter_razorpay in my flutter application but i am getting this error. And then i created a new project and again implemented this but same error appear every time when i import the package and hot reload

```<code>name: gamershub
environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^0.1.3
  flutter_spinkit: ^4.1.2+1
  cloud_firestore: ^0.13.6
  google_sign_in: ^4.5.1
  flutter_facebook_login: ^3.0.0
  firebase_auth: ^0.16.0
  fluttertoast: ^4.0.1
  razorpay_flutter:
dev_dependencies:
   flutter_test:
    sdk: flutter
</code>```

答:
i think you have not mentioned the version code :)

```<code>dependencies:
   razorpay_flutter: ^1.2.1
</code>```

make sure the pubspec.yaml file has this, and make sure you follow the required indentations

if you still have not got it fixed...

Run flutter doctor in the command-line make sure there aren't any errors

make sure you do a flutter packages get if flutter did not automatically do that for you

then run flutter pub cache repair which should fix the error for you

Body:
Compiler message:
Error: Could not resolve the package 'razorpay_flutter' in
'package:razorpay_flutter/razorpay_flutter.dart'.
lib/Screens/add_amount.dart:5:8: Error: Not found:
'package:razorpay_flutter/razorpay_flutter.dart'
import 'package:razorpay_flutter/razorpay_flutter.dart';

I a implementing the flutter_razorpay in my flutter application but i am getting this error. And then i created a new project and again implemented this but same error appear every time when i import the package and hot reload

name: gamershub
environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^0.1.3
  flutter_spinkit: ^4.1.2+1
  cloud_firestore: ^0.13.6
  google_sign_in: ^4.5.1
  flutter_facebook_login: ^3.0.0
  firebase_auth: ^0.16.0
  fluttertoast: ^4.0.1
  razorpay_flutter:
dev_dependencies:
   flutter_test:
    sdk: flutter

Body:
i think you have not mentioned the version code :)

dependencies:
   razorpay_flutter: ^1.2.1

make sure the pubspec.yaml file has this, and make sure you follow the required indentations

if you still have not got it fixed...

Run flutter doctor in the command-line make sure there aren't any errors

make sure you do a flutter packages get if flutter did not automatically do that for you

then run flutter pub cache repair which should fix the error for you


问:
Add Bearer token option in swagger for particular version in web api
I am using Swagger in the Web API application. I have multiple versions of API, but I want to apply Bearer token option to version 2 only. There is no authentication for both versions. Here is my code:

```<code>services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
    c.SwaggerDoc("v2", new OpenApiInfo { Title = "My API", Version = "v2" });

    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        In = ParameterLocation.Header,
        Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey,
    });
});
</code>```

答:
Another way of solving this, I assume you have a prefix for controller version v1 as prefix, then what you can do is:

```<code>public class AuthorizationHeaderParameterOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        if (operation.Parameters == null)
            operation.Parameters = new List<OpenApiParameter>();

        if (context.ApiDescription.RelativePath.StartsWith("v2"))
        {
            operation.Parameters.Add(new OpenApiParameter()
            {
                @In = ParameterLocation.Header,
                Description =
                    "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                Name = "Authorization",
            });
        }

    }
}
</code>```

and use it

```<code>services.ConfigureSwaggerGen(options =>
{
    options.OperationFilter<AuthorizationHeaderParameterOperationFilter>();
});
</code>```

This will only add Bearer field to v2 end points.

Body:
I am using Swagger in the Web API application. I have multiple versions of API, but I want to apply Bearer token option to version 2 only. There is no authentication for both versions. Here is my code:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
    c.SwaggerDoc("v2", new OpenApiInfo { Title = "My API", Version = "v2" });

    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        In = ParameterLocation.Header,
        Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey,
    });
});

Body:
Another way of solving this, I assume you have a prefix for controller version v1 as prefix, then what you can do is:

public class AuthorizationHeaderParameterOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        if (operation.Parameters == null)
            operation.Parameters = new List<OpenApiParameter>();

        if (context.ApiDescription.RelativePath.StartsWith("v2"))
        {
            operation.Parameters.Add(new OpenApiParameter()
            {
                @In = ParameterLocation.Header,
                Description =
                    "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                Name = "Authorization",
            });
        }

    }
}

and use it

services.ConfigureSwaggerGen(options =>
{
    options.OperationFilter<AuthorizationHeaderParameterOperationFilter>();
});

This will only add Bearer field to v2 end points.


问:
Slick js make the slick slide to grow to match the parent sibling height
Working on slick js and I need help with the slick slide to match the parent's sibling height. I want it to grow so that it will be dynamic.

Below is my code:

$(".single-item").slick({
 dots: true,
  adaptiveHeight: true
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  display: flex;
  margin: 0 auto;
  padding: 40px;
  width: 100%;
  color: #333;
  background: #419be0;
}

.slick-slide {
  text-align: center;
  color: #419be0;
  background: white;
}

.one {
  width: 20%;
  border: 1px solid #000;
}

.single-item {
  width: 75%;
  border: 1px solid #000;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.5.9/slick.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.5.9/slick-theme.min.css" rel="stylesheet"/>

      Text Loreum ipsum Loreum ipsumLoreum ipsumLoreum ipsumLoreum ipsumLoreum ipsum Loreum ipsum Loreum ipsum Loreum ipsum Loreum ipsum Loreum ipsumLoreum ipsum Loreum ipsum Loreum ipsum Loreum ipsumLoreum ipsum Loreum ipsumLoreum ipsum

Loreum ipsum Loreum ipsum Loreum ipsumLoreum ipsumLoreum ipsumLoreum ipsumLoreum ipsumLoreum ipsumLoreum ipsum

2

3

4

5

6

```

I want the white part to grow the full height to match the parent(.single-item) sibling(.one) height. Not all the slides are having the same content so they are not equal height.

答:
I figured this out.

$('.offers-slick-main').on('afterChange', function(event, slick, currentSlide, nextSlide) {

  var $loginLogoutWideContainer = $('.row.hero-content'),
      $loginLogoutWideContainerHeight = $loginLogoutWideContainer.height(),
      $slideSelection = $(slick.$slides.get(currentSlide)),
      $slideSelectionHeight = $slideSelection.height();

  if ($slideSelectionHeight < $loginLogoutWideContainerHeight) {
    $slideSelection.height(($loginLogoutWideContainerHeight - 60) + 'px'); //60 is the height of the navigation buttons
    $slickOffersWrapperWide.slick('resize');
  }

});```

Body:
Working on slick js and I need help with the slick slide to match the parent's sibling height. I want it to grow so that it will be dynamic.

Below is my code:

$(".single-item").slick({
 dots: true,
  adaptiveHeight: true
});

.container {
  display: flex;
  margin: 0 auto;
  padding: 40px;
  width: 100%;
  color: #333;
  background: #419be0;
}

.slick-slide {
  text-align: center;
  color: #419be0;
  background: white;
}

.one {
  width: 20%;
  border: 1px solid #000;
}

.single-item {
  width: 75%;
  border: 1px solid #000;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.5.9/slick.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.5.9/slick-theme.min.css" rel="stylesheet"/>

      Text Loreum ipsum Loreum ipsumLoreum ipsumLoreum ipsumLoreum ipsumLoreum ipsum Loreum ipsum Loreum ipsum Loreum ipsum Loreum ipsum Loreum ipsumLoreum ipsum Loreum ipsum Loreum ipsum Loreum ipsumLoreum ipsum Loreum ipsumLoreum ipsum

Loreum ipsum Loreum ipsum Loreum ipsumLoreum ipsumLoreum ipsumLoreum ipsumLoreum ipsumLoreum ipsumLoreum ipsum

2

3

4

5

6

I want the white part to grow the full height to match the parent(.single-item) sibling(.one) height. Not all the slides are having the same content so they are not equal height.


问:
Multiple foreach on if statement
I'm trying to rerun task-sequences on multiple computers from a Drop-Down list that contains the task-sequences names,
and a computer list is loaded via a text file.

I tryed 2 diferent functions but the action isn't being triggered, no errors or output from ISE.

How can i achieve this?

```<code>#Removed #foreach ($Computer in $Computers)

#TaskSequences
$W10_PRELOAD_1809 = "W10_PRELOAD_1809"
$W10_UPG_1809 = "W10_UPG_1809"
$W10_UPG_1809_FORCE = "W10_UPG_1809_FORCE"

$Browse_OnClick = {
    $FileName = Select-FileDialog
    $Computers = Get-Content $FileName
    $Install.enabled = $true
}

$TaskSequence = "$W10_PRELOAD_1809", "$W10_UPG_1809", "$W10_UPG_1809_FORCE", "$W7_CHECK_PRELOAD", "$W7_1809_PRELOAD", "$W7_UPG_1809", "$W7_UPG_1809_FORCE"
$TaskSequence | % { $ListApps.Items.Add($_) }

$Install_OnClick= {

    if (!$ListApps.SelectedItem) {[System.Windows.Forms.MessageBox]::Show("Please select a Task-Sequence from the drop down menu")

       }
    else {

        $TaskSequenceItem = $ListApps.SelectedItem.ToString()

      if ($TaskSequenceItem -eq "W10_PRELOAD_1809")
        {
           New-Item -Path \\emeamai-rs08\TEMP\Baseline_FMT\test_PRELOAD_$Computer.txt -Force
        }

        if ($TaskSequenceItem -eq "W10_UPG_1809")
        {
             New-Item -Path \\emeamai-rs08\TEMP\Baseline_FMT\test_UPG_$Computer.txt -Force
        }

        if ($TaskSequenceItem -eq "W10_UPG_1809_FORCE")
        {
          New-Item -Path \\emeamai-rs08\TEMP\Baseline_FMT\test_Force_$Computer.txt -Force
        }

    }
}
</code>```

答:
```<code>$Servers = Get-Content $FileName

ForEach ($Server in $Servers){

    if (!$ListApps.SelectedItem) {[System.Windows.Forms.MessageBox]::Show("Please select a Task-Sequence from the drop down menu")

       }
    else {

        $TaskSequenceItem = $ListApps.SelectedItem.ToString()

      if ($TaskSequenceItem -eq "W10_PRELOAD_1809")
        {
            New-Item -Path \\emeamai-rs08\TEMP\Baseline_FMT\test_PRELOAD_$Server.txt -Force

        }

        if ($TaskSequenceItem -eq "W10_UPG_1809")
        {
             New-Item -Path \\emeamai-rs08\TEMP\Baseline_FMT\test_UPG_$Server.txt -Force
        }

        if ($TaskSequenceItem -eq "W10_UPG_1809_FORCE")
        {
          New-Item -Path \\emeamai-rs08\TEMP\Baseline_FMT\test_Force_$Computer.txt -Force
        }

    }
}
}

</code>```

Title: Multiple foreach on if statement

Body:
I'm trying to rerun task-sequences on multiple computers from a Drop-Down list that contains the task-sequences names,
and a computer list is loaded via a text file.

I tryed 2 diferent functions but the action isn't being triggered, no errors or output from ISE.

How can i achieve this?

#Removed #foreach ($Computer in $Computers)

#TaskSequences
$W10_PRELOAD_1809 = "W10_PRELOAD_1809"
$W10_UPG_1809 = "W10_UPG_1809"
$W10_UPG_1809_FORCE = "W10_UPG_1809_FORCE"

$Browse_OnClick = {
    $FileName = Select-FileDialog
    $Computers = Get-Content $FileName
    $Install.enabled = $true
}

$TaskSequence = "$W10_PRELOAD_1809", "$W10_UPG_1809", "$W10_UPG_1809_FORCE", "$W7_CHECK_PRELOAD", "$W7_1809_PRELOAD", "$W7_UPG_1809", "$W7_UPG_1809_FORCE"
$TaskSequence | % { $ListApps.Items.Add($_) }

$Install_OnClick= {

    if (!$ListApps.SelectedItem) {[System.Windows.Forms.MessageBox]::Show("Please select a Task-Sequence from the drop down menu")

       }
    else {

        $TaskSequenceItem = $ListApps.SelectedItem.ToString()

      if ($TaskSequenceItem -eq "W10_PRELOAD_1809")
        {
           New-Item -Path \\emeamai-rs08\TEMP\Baseline_FMT\test_PRELOAD_$Computer.txt -Force
        }

        if ($TaskSequenceItem -eq "W10_UPG_1809")
        {
             New-Item -Path \\emeamai-rs08\TEMP\Baseline_FMT\test_UPG_$Computer.txt -Force
        }

        if ($TaskSequenceItem -eq "W10_UPG_1809_FORCE")
        {
          New-Item -Path \\emeamai-rs08\TEMP\Baseline_FMT\test_Force_$Computer.txt -Force
        }

    }
}


问:
Adding new column, based on values of another column pandas
Can anyone help, i'm new to Python so bear with me.

My data looks like this but has all the region information available. I'm trying to create a new column 'actual price' that works out the price based on the region. as for every entry I have each price for every region. is this possible.

```<code>data = [[1, 'EDF', 'Eastern', 400, 500, 300], [2, 'EDF', 'Southern', 200, 100, 300], [3, 'NPower',
        'Eastern', 600, 500, 700]]

df = pd.DataFrame(data, columns = ['ID', 'Supplier', 'Region', 'Av Price', 'Eastern Price',
'Southern Price'])

df
</code>```

答:
Use, np.select:

```<code>conditions = [df['Region'].eq(reg) for reg in df['Region'].unique()]
choices = [df[f'{reg} Price'] for reg in df['Region'].unique()]
df['actual_price'] = np.select(conditions, choices)
</code>```

Result:

```<code># print(df)
   ID Supplier    Region  Av Price  Eastern Price  Southern Price  actual_price
0   1      EDF   Eastern       400            500             300           500
1   2      EDF  Southern       200            100             300           300
2   3   NPower   Eastern       600            500             700           500
</code>```

Body:
Can anyone help, i'm new to Python so bear with me.

My data looks like this but has all the region information available. I'm trying to create a new column 'actual price' that works out the price based on the region. as for every entry I have each price for every region. is this possible.

data = [[1, 'EDF', 'Eastern', 400, 500, 300], [2, 'EDF', 'Southern', 200, 100, 300], [3, 'NPower',
        'Eastern', 600, 500, 700]]

df = pd.DataFrame(data, columns = ['ID', 'Supplier', 'Region', 'Av Price', 'Eastern Price',
'Southern Price'])

df

Body:
Use, np.select:

conditions = [df['Region'].eq(reg) for reg in df['Region'].unique()]
choices = [df[f'{reg} Price'] for reg in df['Region'].unique()]
df['actual_price'] = np.select(conditions, choices)

Result:

# print(df)
   ID Supplier    Region  Av Price  Eastern Price  Southern Price  actual_price
0   1      EDF   Eastern       400            500             300           500
1   2      EDF  Southern       200            100             300           300
2   3   NPower   Eastern       600            500             700           500


问:
Get all users with role in Laravel
I'm working in this Laravel project which has this structure

users: id | first_name |...

roles: id | name

assigned_roles: id | user_id | role_id

I think this is quite obvious :p

User model

```<code>class User extends ConfideUser {
use HasRole;

public function Roles(){
    return $this->belongsToMany('Role','assigned_roles');
}
</code>```

Role model

```<code>class Role extends EntrustRole
{
public function Users()
{
    return $this->belongsToMany('User','assigned_roles');
}

}
</code>```

I'm looking for a way to get all users with a specified role in this case 'Teacher'. I've tried this:

```<code>$students = User::with(array('Roles' => function($query) {
        $query->where('name','Teacher');
    }))
    ->get();
    return $students;
</code>```

but this always returns an array of all users.

would anyone know why that's so?
Thanks!

答:
In case you want to get all users with a list of potentials roles:</p>

```<code>$authorizedRoles = ['Teacher', 'Professor', 'Super professor'];

$users = User::whereHas('roles', static function ($query) use ($authorizedRoles) {
                    return $query->whereIn('name', $authorizedRoles);
                })->get();
</code>```

ContentLicense: CC BY-SA 3.0

Title: Get all users with role in Laravel

Body:
I'm working in this Laravel project which has this structure

users: id | first_name |...

roles: id | name

assigned_roles: id | user_id | role_id

I think this is quite obvious :p

User model

class User extends ConfideUser {
use HasRole;

public function Roles(){
    return $this->belongsToMany('Role','assigned_roles');
}

Role model

class Role extends EntrustRole
{
public function Users()
{
    return $this->belongsToMany('User','assigned_roles');
}

}

I'm looking for a way to get all users with a specified role in this case 'Teacher'. I've tried this:

$students = User::with(array('Roles' => function($query) {
        $query->where('name','Teacher');
    }))
    ->get();
    return $students;

but this always returns an array of all users.

would anyone know why that's so?
Thanks!

Body:
In case you want to get all users with a list of potentials roles:

$authorizedRoles = ['Teacher', 'Professor', 'Super professor'];

$users = User::whereHas('roles', static function ($query) use ($authorizedRoles) {
                    return $query->whereIn('name', $authorizedRoles);
                })->get();


问:
Unable to launch firefox browser and run test with RSpec in RubyMine
I am new to Ruby and Rspec. I just did below steps.

Clicked on New Project in RubyMine

Gave title as Selenium2(just some random name)

I am using ruby 2.7.1

Created a new directory 'src' under Selenium2 folder

Added test.rb file

I added below code in test.tb file(already  did gem install for selenium-webdriver and rspec) as shown in below screenshot.

Right clicked on test.rb and selected Run 'test'.

Got the below output as shown in below screenshot. As a newbie I dont see any issue with the code. But its not even launching Firefox browser and not printing puts in the console.

Am I missing something here?

答:
I think you're doing it wrong.

In your project root folder, add Gemfile file, this Gemfile can have something like this:

source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.6.5'

gem 'rspec', '~> 3.9'
gem 'capybara', '~> 3.30'
gem 'selenium-webdriver', '~> 3.142', '>= 3.142.6'
```</li>
<li><p>Create a <code>spec/</code> directory in your project root</p></li>
<li><p>Create a <code>log/</code> directory in your project root for your selinium logs.</p></li>
<li><p>Create a <code>spec/spec_helper.rb</code> file with configuration like this:</p>

<pre class="lang-rb prettyprint-override"><code># frozen-string-literal: true

require 'rspec'
require 'capybara/rspec'
require 'capybara/dsl'
require 'selenium-webdriver'

Selenium::WebDriver.logger.level = :debug
Selenium::WebDriver.logger.output = File.dirname(Dir.pwd) + '/project_dir_name/log/selenium.log'

Capybara.register_driver :firefox do |app|
  Capybara::Selenium::Driver.new(app, browser: :firefox)
end

Capybara.default_driver = :firefox
Capybara.javascript_driver = :firefox
Capybara.app_host = 'http://127.0.0.1:3005'
Capybara.default_max_wait_time = 10

RSpec.configure do |config|
  config.before(:each) do
    config.include Capybara::DSL
  end
end
</code>```

The above code will setup rspec, capybara. You can change the driver, host and other configs if you want.

Now create a new spec/features/test.rb file with something like this:

require 'spec_helper'

describe 'Google homepage test', js: true do
  before(:each) do
    visit('https://google.com')
  end

  describe "First test" do
    it "check title" do
      expect(page.title).to be == "some text"
    end
  end
end
```</li>
<li><p>Then run: <code>bundle exec rspec spec/features/test.rb</code> from your project root.</p></li>
</ol>

<hr>

<p>If you don't want this way, then the problem is that you're running <code>ruby test.rb</code>, actually <code>test.rb</code> this should be runned via <code>rspec</code>:</p>

<pre class="lang-sh prettyprint-override"><code>$ rspec test.rb
</code>```

If you're using bundler, then:

$ bundle exec rspec test.rb
```

Body:
I think you're doing it wrong.

In your project root folder, add Gemfile file, this Gemfile can have something like this:

source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.6.5'

gem 'rspec', '~> 3.9'
gem 'capybara', '~> 3.30'
gem 'selenium-webdriver', '~> 3.142', '>= 3.142.6'

Create a spec/ directory in your project root

Create a log/ directory in your project root for your selinium logs.

Create a spec/spec_helper.rb file with configuration like this:

# frozen-string-literal: true

require 'rspec'
require 'capybara/rspec'
require 'capybara/dsl'
require 'selenium-webdriver'

Selenium::WebDriver.logger.level = :debug
Selenium::WebDriver.logger.output = File.dirname(Dir.pwd) + '/project_dir_name/log/selenium.log'

Capybara.register_driver :firefox do |app|
  Capybara::Selenium::Driver.new(app, browser: :firefox)
end

Capybara.default_driver = :firefox
Capybara.javascript_driver = :firefox
Capybara.app_host = 'http://127.0.0.1:3005'
Capybara.default_max_wait_time = 10

RSpec.configure do |config|
  config.before(:each) do
    config.include Capybara::DSL
  end
end

The above code will setup rspec, capybara. You can change the driver, host and other configs if you want.

Now create a new spec/features/test.rb file with something like this:

require 'spec_helper'

describe 'Google homepage test', js: true do
  before(:each) do
    visit('https://google.com')
  end

  describe "First test" do
    it "check title" do
      expect(page.title).to be == "some text"
    end
  end
end

Then run: bundle exec rspec spec/features/test.rb from your project root.

If you don't want this way, then the problem is that you're running ruby test.rb, actually test.rb this should be runned via rspec:

$ rspec test.rb

If you're using bundler, then:

$ bundle exec rspec test.rb


问:
How can I iterate over overlapping (current, next) pairs of values from a list?
I sometimes need to iterate a list in Python looking at the "current" element and the "next" element. I have, till now, done so with code like:

```<code>for current, next in zip(the_list, the_list[1:]):
    # Do something
</code>```

This works and does what I expect, but is there's a more idiomatic or efficient way to do the same thing?

Some answers to this problem can simplify by addressing the specific case of taking only two elements at a time. For the general case of N elements at a time, see Rolling or sliding window iterator?.

答:
This is now a simple Import As of 16th May 2020

```<code>from more_itertools import pairwise
for current, next in pairwise(your_iterable):
  print(f'Current = {current}, next = {nxt}')
</code>```

Docs for more-itertools
Under the hood this code is the same as that in the other answers, but I much prefer imports when available.

If you don't already have it installed then:
pip install more-itertools

Example

For instance if you had the fibbonnacci sequence, you could calculate the ratios of subsequent pairs as:

```<code>from more_itertools import pairwise
fib= [1,1,2,3,5,8,13]
for current, nxt in pairwise(fib):
    ratio=current/nxt
    print(f'Curent = {current}, next = {nxt}, ratio = {ratio} ')
</code>```

Body:
I sometimes need to iterate a list in Python looking at the "current" element and the "next" element. I have, till now, done so with code like:

for current, next in zip(the_list, the_list[1:]):
    # Do something

This works and does what I expect, but is there's a more idiomatic or efficient way to do the same thing?

Some answers to this problem can simplify by addressing the specific case of taking only two elements at a time. For the general case of N elements at a time, see Rolling or sliding window iterator?.

Body:
This is now a simple Import As of 16th May 2020

from more_itertools import pairwise
for current, next in pairwise(your_iterable):
  print(f'Current = {current}, next = {nxt}')

Docs for more-itertools
Under the hood this code is the same as that in the other answers, but I much prefer imports when available.

If you don't already have it installed then:
pip install more-itertools

Example

For instance if you had the fibbonnacci sequence, you could calculate the ratios of subsequent pairs as:

from more_itertools import pairwise
fib= [1,1,2,3,5,8,13]
for current, nxt in pairwise(fib):
    ratio=current/nxt
    print(f'Curent = {current}, next = {nxt}, ratio = {ratio} ')


问:
Saving Files c# - without overwriting?
I am saving data to a file every 60 secs, I have it saving every 60 secs ok but it deletes the previous data added. Is there a way in which it would add to the file rather than overwrite it. And without using save dialog as it is done in the background.

Any feedback is greatly appreciated

答: Specify FileMode.Append in the FileStream constructor.

Title: Saving Files c# - without overwriting?