答:
Instead of the sum, you can use np.any with axis=0 such as:

```<code>import numpy as np
# mostly all your code except this line df2 = df1[~sum(vdfs)] that you replace by
df2 = df1[~np.any(vdfs, axis=0)]
</code>```

In your example, the result for df2 is then

```<code>         date  amount  void?    status
0  2019-01-01    10.0  False  CAPTURED
1  2019-01-04    10.0  False  CAPTURED
</code>```

Title: How can I combine n-number of boolean indexes to filter Pandas DataFrame?

Body:
Instead of the sum, you can use np.any with axis=0 such as:

import numpy as np
# mostly all your code except this line df2 = df1[~sum(vdfs)] that you replace by
df2 = df1[~np.any(vdfs, axis=0)]

In your example, the result for df2 is then

         date  amount  void?    status
0  2019-01-01    10.0  False  CAPTURED
1  2019-01-04    10.0  False  CAPTURED


来源: stackexchange

问:
Is there any way to avoid missing bytes on a Python socket data transmission?
I have two different python clients communicating with each other (Client A and Client B) through an external node server on the internet. Client A should send many identified messages in a short period of time to client B, where the node server is responsible to forward all received messages from A to B.

What is happening is that client A is overwriting some message.

I have detected the problem on client B, which is where I analyze the messages. However, the problem occurs in the transmission of messages between client A and Node server, because I am already able to see the broken message on node server logs.

I will show some pseudo-code along with some logs regarding the error (Client A and Server only) :

Client A

Code
    ...
    import socket

```<code>server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.connect((HOST, PORT))

...

while not END:
    #Prepare message_to_clinet

    #If I uncomment this timer, the error will not appear (or appear later)
    #time.sleep(0.2)

    # I have tried either sendall and send. But it seems that is not effective
    server_socket.sendall(message_to_client)
    print '(Sent):' + message_to_client
</code>```

Logs when the error occurs
Imagine that I want to send 100 times the message: 'Where is the bug?'

```<code>...
(Sent): Where is the bug?
(Sent): Where is the bug?
(Sent): Where is the bug?
(Sent): Where is the bug?
(Sent): Where is the bug?
...
</code>```

Node

Code

```<code>const net = require('net');
const tcpServer = net.createServer(connection.requestHandler);
tcpServer.listen(connection.port, (err) => {
    if (err) {
        return console.log('tcp socket error', err);
    }

    console.log(`tcp socket listening on ${connection.port}`);
});

...

const requestHandler = (sock) => {
    sock.on('data', (data) => {
        const protocol_message = new Buffer(data).toString('ascii');

        //Send this message to remote client
        currentConnection.sendMessagesToClient(protocol_message)
        console.log('Received: ' + protocol_message)
    }
}
</code>```

Logs when the error occurs.
I receive more messages for each socket.send maybe because socket.send it is called several times in a short time on client A (which is not a problem because on the real code I have a 4 byte-length prefix to prevent errors when reading on clinet B)

```<code>...
Received: Where is the bug? Where is the bug? Where is the bug?  Where is the bug?Where is the bug?
Received: Where is the bug? Where is the bug? Where is the bug?  Where is the bug?Where is the bug?
Received: Where is thWhere is the bug? Where is the bug?Where is the bug?
...
</code>```

Here I can see that one of the 100 messages I repeatedly sent is broken. However, on client A, everything is apparently well.

Does anyone know what is a possible cause of this error?

I know if put a time.sleep(0.1) between each message on client A, the error takes more time and transmitted bytes to happen. But when it works, it is just too slow.
I also know that if I use the developer local server, I cannot reproduce the error. My guess is that this is related to socket buffer and delay on transmission.

EDIT: I am using Python 2.7

答:
I found the answer to my problem. Basically, everything was correct with python clients. However, with TCP sockets, messages can be split in chunks on an upper layer, which leads to a stupid bug on the server side because I was looking for the first character to decide to which socket I'll redirect the message. Of course, this is not a good approach at all, and now it is solved and working.

Although it was a bug on the server side, I only found it because I did some research and conclude that TCP guarantees the same order but it can split in chunks the data.

Thank you anyway!

ContentLicense: CC BY-SA 4.0

Body:
I have two different python clients communicating with each other (Client A and Client B) through an external node server on the internet. Client A should send many identified messages in a short period of time to client B, where the node server is responsible to forward all received messages from A to B.

What is happening is that client A is overwriting some message.

I have detected the problem on client B, which is where I analyze the messages. However, the problem occurs in the transmission of messages between client A and Node server, because I am already able to see the broken message on node server logs.

I will show some pseudo-code along with some logs regarding the error (Client A and Server only) :

Client A

Code
    ...
    import socket

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.connect((HOST, PORT))

...

while not END:
    #Prepare message_to_clinet

    #If I uncomment this timer, the error will not appear (or appear later)
    #time.sleep(0.2)

    # I have tried either sendall and send. But it seems that is not effective
    server_socket.sendall(message_to_client)
    print '(Sent):' + message_to_client

Logs when the error occurs
Imagine that I want to send 100 times the message: 'Where is the bug?'

...
(Sent): Where is the bug?
(Sent): Where is the bug?
(Sent): Where is the bug?
(Sent): Where is the bug?
(Sent): Where is the bug?
...

Node

Code

const net = require('net');
const tcpServer = net.createServer(connection.requestHandler);
tcpServer.listen(connection.port, (err) => {
    if (err) {
        return console.log('tcp socket error', err);
    }

    console.log(`tcp socket listening on ${connection.port}`);
});

...

const requestHandler = (sock) => {
    sock.on('data', (data) => {
        const protocol_message = new Buffer(data).toString('ascii');

        //Send this message to remote client
        currentConnection.sendMessagesToClient(protocol_message)
        console.log('Received: ' + protocol_message)
    }
}

Logs when the error occurs.
I receive more messages for each socket.send maybe because socket.send it is called several times in a short time on client A (which is not a problem because on the real code I have a 4 byte-length prefix to prevent errors when reading on clinet B)

...
Received: Where is the bug? Where is the bug? Where is the bug?  Where is the bug?Where is the bug?
Received: Where is the bug? Where is the bug? Where is the bug?  Where is the bug?Where is the bug?
Received: Where is thWhere is the bug? Where is the bug?Where is the bug?
...

Here I can see that one of the 100 messages I repeatedly sent is broken. However, on client A, everything is apparently well.

Does anyone know what is a possible cause of this error?

I know if put a time.sleep(0.1) between each message on client A, the error takes more time and transmitted bytes to happen. But when it works, it is just too slow.
I also know that if I use the developer local server, I cannot reproduce the error. My guess is that this is related to socket buffer and delay on transmission.

EDIT: I am using Python 2.7


问:
Is it possible to call ansible or ansible-playbook directly on a target host using a script or ansible itself?
I need to know if it's possible to call / execute ansible playbooks from the target machine. I think i saw a vendor do it or at least something similar. they downloaded a script and it did ran the playbook.

if this is possible how would it be done?

my goal is to run ansible as a centralized server in aws to perform tasks in mulitple environments. most are behind firewalls, any reccomendations/thoughts would be appreciated.

答: If you're ok with executing tasks remotely over ssh take a look at Sparrowdo it has out of the box facilities to run bash scripts ( read ansible executable ) remotely from one master host to another. Or you can even use it to install all the ansible dependencies or whatever you need to do for your scope. </p>


问:
prototype javascript calendar with customizable rendering of cells like YUI Calendar
I already make extensive use of prototype and don't want to add an extra framework like YUI.

I need a javascript calendar which enables me to customize rendering of calendar-cells on a cell by cell basis. (For rendering events, prices, etc. on a certain date) .

YUI Calendar makes this possible, but I already make extensive use of prototype and don't want to add an extra framework like YUI.

Does anyone know a good alternative?

Thanks,
Brits

答:
As far as I know, Prototype is a collection of helper functions, but it has no widgets.
YUI is a total different beast (there's a minor overlapping in DOM methods).
We use Prototype for Ajax calls and YUI for widgets (calendar, dialogs, grid).</p>

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Lluís


问:
Angular 7 - Problem with parameters on the Router Link
I have a problem sending a parameter to a URL on child routing. Here are the details:

I have a list of users with an Id and when I click on a user I need to send that Id as a parameter to the Url, Here's the userlist:

```<code><div class="bx--grid" style="height: 100%" style="padding-left: 0%">
          <div class="bx--structured-list bx--col-lg-12">
              <div class="bx--structured-list-tbody">
                      <div class="bx--structured-list-row" *ngFor="let user of users">
                          <div class="bx--structured-list-td">
                          <a class="nav-link"
                          [routerLinkActive]="['active']"
                          [routerLink]="[user.Id, 'userdetailsview']"> {{user.UserName}}
                       </a>
                      </div>
                  </div>
            </div>
      </div>
</code>```

Here's my approuting:

```<code>const routes: Routes = [

    //no parameter, so it's not an edit or a view.
    path: "users-manager", component: UserManagerComponent,
    children: [
      { path: "", redirectTo: "landing", pathMatch: "full" },
      { path: "landing", component: LandingBodyComponent },
      //{ path: "new", component: TO_BE_CREATEDComponent }, //This should open the wizard for new user

      { path: "tracks", component: ArtistTrackListComponent },
      { path: "albums", component: ArtistAlbumListComponent },
      { path: "userdetailsview", component: LandingBodyComponent }
    ]
  },
  {
    //recieves the user id in the url to view or edit his/her profiles.
    path: "users-manager/:userId",
    component: UserManagerComponent,
    children: [
      { path: "", redirectTo: "tracks", pathMatch: "full" },
      { path: "tracks", component: ArtistTrackListComponent },
      { path: "albums", component: ArtistAlbumListComponent },
      { path: "userdetailsview", component: LandingBodyComponent }
    ]
  },
</code>```

My problem is that when I click a user it goes to the right path like:

```<code>http://localhost:4200/#/users-manager/9/userdetailsview
</code>```

but when I click another user it goes to:

```<code>http://localhost:4200/#/users-manager/9/11/userdetailsview
</code>```

I need to replace the new Id 11 in this case with the old one 9

What I'm doing wrong here?

答:
You can use an absolute path from root.</p>

```<code>routerLink="/users-manager/{{user.Id}}/userdetailsview"
</code>```

Body:
I have a problem sending a parameter to a URL on child routing. Here are the details:

I have a list of users with an Id and when I click on a user I need to send that Id as a parameter to the Url, Here's the userlist:

                           {{user.UserName}}

Here's my approuting:

const routes: Routes = [

    //no parameter, so it's not an edit or a view.
    path: "users-manager", component: UserManagerComponent,
    children: [
      { path: "", redirectTo: "landing", pathMatch: "full" },
      { path: "landing", component: LandingBodyComponent },
      //{ path: "new", component: TO_BE_CREATEDComponent }, //This should open the wizard for new user

      { path: "tracks", component: ArtistTrackListComponent },
      { path: "albums", component: ArtistAlbumListComponent },
      { path: "userdetailsview", component: LandingBodyComponent }
    ]
  },
  {
    //recieves the user id in the url to view or edit his/her profiles.
    path: "users-manager/:userId",
    component: UserManagerComponent,
    children: [
      { path: "", redirectTo: "tracks", pathMatch: "full" },
      { path: "tracks", component: ArtistTrackListComponent },
      { path: "albums", component: ArtistAlbumListComponent },
      { path: "userdetailsview", component: LandingBodyComponent }
    ]
  },

My problem is that when I click a user it goes to the right path like:

http://localhost:4200/#/users-manager/9/userdetailsview

but when I click another user it goes to:

http://localhost:4200/#/users-manager/9/11/userdetailsview

I need to replace the new Id 11 in this case with the old one 9

What I'm doing wrong here?

Body:
You can use an absolute path from root.

routerLink="/users-manager/{{user.Id}}/userdetailsview"


问:
How to convert an RDD into a dataframe using a user defined class and toDF
when I try to create the following package by sbt package:

```<code>import org.apache.spark.sql.SparkSession

class Log(val cip: String, val scstatus: Int) {
    var src: String = cip
    var status: Int = scstatus
}

object IISHttpLogs {
  def main(args: Array[String]) {
    val logFiles = "D:/temp/tests/wwwlogs"
    val spark = SparkSession.builder.appName("LogParser").getOrCreate()
    val sc = spark.sparkContext;
    sc.setLogLevel("ERROR")

    val logs = sc.textFile(logFiles)

    import spark.implicits._
    val rowDF = logs.filter(l => !l.startsWith("#"))
        .map(l => l.split(" "))
        .map(c => new Log(c(8), c(11).trim.toInt))
        .toDF();
    println(s"line count: ${rowDF.count()}")
    rowDF.createOrReplaceTempView("rows")
    val maxHit = spark.sql("SELECT top 1 src, count(*) FROM rows group by src order by count(*) desc")
    maxHit.show()

    spark.stop()
  }
}
</code>```

I get the following error:

value toDF is not a member of org.apache.spark.rdd.RDD[Log]

I try several things like:

toDFlog

create a sql context and import imlicits._ from this sqlContext

I just can't compile my code.

Any clue welcome to ovverride this error.

I well read Generate a Spark StructType / Schema from a case class and write:

```<code>val schema =
    StructType(
        StructField("src", StringType, false) ::
        StructField("status", IntegerType, true) :: Nil)

val rowRDD = logs.filter(l => !l.startsWith("#"))
    .map(l => l.split(" "))
    .map(c => Row(c(8), c(11).trim.toInt));

val rowDF = spark.sqlContext.createDataFrame(rowRDD, schema);
</code>```

but doing so I do not use the Log class. I would like to know if there is a way to get the DataFrame by using the defined Log class or if the official/best way is to use the Row class ?

for example I can't write:

```<code>val rowRDD = logs.filter(l => !l.startsWith("#"))
    .map(l => l.split(" "))
    .map(c => new Log(c(8), c(11).trim.toInt));
val rowDF = spark.sqlContext.createDataFrame(
    rowRDD,
    ScalaReflection.schemaFor[Log].dataType.asInstanceOf[StructType]);
</code>```

And I just can't figure out why ?

答:
You have to use a case class. At least that worked for me:

```<code>case class Log(cip: String,  scstatus: Int)
//...
.map(c =>  Log(c(8), c(11).trim.toInt) // ommit 'new'
.toDF()
</code>```

I'm not quite sure whether this is a general rule. However in the announcement of the Dataset API, the usage of case classes is mentioned explicitly:

Spark 1.6 comes with support for automatically generating encoders for a wide variety of types, including primitive types (e.g. String, Integer, Long), Scala case classes, and Java Beans.
  (https://databricks.com/blog/2016/01/04/introducing-apache-spark-datasets.html)

If you can not use a case class, this answer seems to be appropriate.

Body:
when I try to create the following package by sbt package:

import org.apache.spark.sql.SparkSession

class Log(val cip: String, val scstatus: Int) {
    var src: String = cip
    var status: Int = scstatus
}

object IISHttpLogs {
  def main(args: Array[String]) {
    val logFiles = "D:/temp/tests/wwwlogs"
    val spark = SparkSession.builder.appName("LogParser").getOrCreate()
    val sc = spark.sparkContext;
    sc.setLogLevel("ERROR")

    val logs = sc.textFile(logFiles)

    import spark.implicits._
    val rowDF = logs.filter(l => !l.startsWith("#"))
        .map(l => l.split(" "))
        .map(c => new Log(c(8), c(11).trim.toInt))
        .toDF();
    println(s"line count: ${rowDF.count()}")
    rowDF.createOrReplaceTempView("rows")
    val maxHit = spark.sql("SELECT top 1 src, count(*) FROM rows group by src order by count(*) desc")
    maxHit.show()

    spark.stop()
  }
}

I get the following error:

value toDF is not a member of org.apache.spark.rdd.RDD[Log]

I try several things like:

toDFlog

create a sql context and import imlicits._ from this sqlContext

I just can't compile my code.

Any clue welcome to ovverride this error.

I well read Generate a Spark StructType / Schema from a case class and write:

val schema =
    StructType(
        StructField("src", StringType, false) ::
        StructField("status", IntegerType, true) :: Nil)

val rowRDD = logs.filter(l => !l.startsWith("#"))
    .map(l => l.split(" "))
    .map(c => Row(c(8), c(11).trim.toInt));

val rowDF = spark.sqlContext.createDataFrame(rowRDD, schema);

but doing so I do not use the Log class. I would like to know if there is a way to get the DataFrame by using the defined Log class or if the official/best way is to use the Row class ?

for example I can't write:

val rowRDD = logs.filter(l => !l.startsWith("#"))
    .map(l => l.split(" "))
    .map(c => new Log(c(8), c(11).trim.toInt));
val rowDF = spark.sqlContext.createDataFrame(
    rowRDD,
    ScalaReflection.schemaFor[Log].dataType.asInstanceOf[StructType]);

And I just can't figure out why ?

Body:
You have to use a case class. At least that worked for me:

case class Log(cip: String,  scstatus: Int)
//...
.map(c =>  Log(c(8), c(11).trim.toInt) // ommit 'new'
.toDF()

I'm not quite sure whether this is a general rule. However in the announcement of the Dataset API, the usage of case classes is mentioned explicitly:

Spark 1.6 comes with support for automatically generating encoders for a wide variety of types, including primitive types (e.g. String, Integer, Long), Scala case classes, and Java Beans.
  (https://databricks.com/blog/2016/01/04/introducing-apache-spark-datasets.html)

If you can not use a case class, this answer seems to be appropriate.


问:
How to apply bold and italics to an NSMutableAttributedString range?
I've been trying to apply combinations of NSFontAttributes to NSMutableAttributedString's lately and I simply can't find a thorough explanation on how to do it without removing other attributes.

I've searched a bunch, and found this question pertaining to how to do it with HTML, and then this question about how to find where text has been bolded or italicized, but nothing on how to actually do it.

Currently, I try to format stings as follows:

Italics:
[mutableAttributedString addAttribute: NSFontAttributeName value:[fontAttributes valueForKey:CXItalicsFontAttributeName] range:r];

Bold: [mutableAttributedString addAttribute:NSFontAttributeName value:[fontAttributes valueForKey:CXBoldFontAttributeName] range:r];

Where the constants CXItalicsFontAttributeName and CXBoldAttributeName extract the following two values from a dictionary respectfully:

```<code>UIFont *italicsFont = [UIFont fontWithName:@"Avenir-BookOblique" size:14.0f];
UIFont *boldFont = [UIFont fontWithName:@"Avenir-Heavy" size:14.0f];
</code>```

I know this mustn't be the right way to go about formatting, as the NSAttributedString standard attributes don't include a ItalicsFontAttribute or BoldFontAttribute, but I can't find the properly way to do this. Can anyone assist me?

答: Checkout NSAttributedString.Key.obliqueness. Setting the value of this key to values other than 0 make the text italics with different degree.

Body:
I've been trying to apply combinations of NSFontAttributes to NSMutableAttributedString's lately and I simply can't find a thorough explanation on how to do it without removing other attributes.

I've searched a bunch, and found this question pertaining to how to do it with HTML, and then this question about how to find where text has been bolded or italicized, but nothing on how to actually do it.

Currently, I try to format stings as follows:

Italics:
[mutableAttributedString addAttribute: NSFontAttributeName value:[fontAttributes valueForKey:CXItalicsFontAttributeName] range:r];

Bold: [mutableAttributedString addAttribute:NSFontAttributeName value:[fontAttributes valueForKey:CXBoldFontAttributeName] range:r];

Where the constants CXItalicsFontAttributeName and CXBoldAttributeName extract the following two values from a dictionary respectfully:

UIFont *italicsFont = [UIFont fontWithName:@"Avenir-BookOblique" size:14.0f];
UIFont *boldFont = [UIFont fontWithName:@"Avenir-Heavy" size:14.0f];

I know this mustn't be the right way to go about formatting, as the NSAttributedString standard attributes don't include a ItalicsFontAttribute or BoldFontAttribute, but I can't find the properly way to do this. Can anyone assist me?


问:
How remove duplicated Python versions from MacOS Mojave
I'm using Visual Studio Code on MacOS Mojave. However, I've noticed app finds 4(!) versions of Python. I don't know why Python 3.7.x is duplicated and have no idea how can it be deleted.

答: You should be able to search for each version within the computer using the search icon, located within the menu bar on the top right of your screen. Search for the unwanted versions and it will give you an option to delete.</p>


问:
Modifying sphinx_bootstrap_theme method rendering
I have some API Documentation which I'm mostly happy with.

I'm using the sphinx_bootstrap_theme to render my doc style.  However, I want to modify how each API method renders.

Today the docs look like this:

I want to make a small change to the bootstrap theme, such that I get an HR between every method like this:

QUESTION:

Where do I modify sphinx_bootstrap_theme such that I can customize the rendering of these methods?

I looked through the sphinx_bootstrap_theme templates, but I can't seem to find the template I have to monkey with to make this work right.

If you want to see how I've configured my docs, you can find the source tree here

答:
Usually, it is a bit tricky to tweak the original code. What I personally do and so far was happy with is the overwrite the existing style by adding a custom css to implement some minor changes. The way I do it:

Create a folder called css under source/_static

Add a new css (for example: custom.css) file that includes your desired changes.

Add the following code to your conf.py

def setup(app):
    app.add_stylesheet('css/custom.css')
```

Save and build

For more check this

Body:
Usually, it is a bit tricky to tweak the original code. What I personally do and so far was happy with is the overwrite the existing style by adding a custom css to implement some minor changes. The way I do it:

Create a folder called css under source/_static

Add a new css (for example: custom.css) file that includes your desired changes.

Add the following code to your conf.py

def setup(app):
    app.add_stylesheet('css/custom.css')

Save and build

For more check this


问:
How to fix VBA Error "Cannot saving ".xlsm" to ".xlsx""?
I'm dividing a workbook in several stores.

I choose the store I want to see, and the code filters the data of the other stores and deletes that data, only leaving the data of the choosen store.

and after this I want to make a new workbook, saving as my ".xlsm" file to ".xlsx"

But after runing the code i have a pop up message asking if i want "to continue saving as a macro-free workbook"

If i click yes, i have a error saying:

1004 VB Projects and XLM sheets cannot be saved in a macro-free
  workbook

What can i do to fix it?

this is the code to save the new workbook:

```<code>Dim Fname As String

Fname = "02.VIM_REPORT MENSAL - " & Worksheets("aux").Range("V2") & " - " & Worksheets("aux").Range("V3") & ".xlsx"
ActiveWorkbook.SaveAs Filename:=Fname, FileFormat:=xlOpenXMLWorkbook

    ActiveWorkbook.Close False
</code>```

答:
Change that code line to:
ActiveWorkbook.SaveAs Filename:=Fname, FileFormat:=xlWorkbookDefault

Body:
I'm dividing a workbook in several stores.

I choose the store I want to see, and the code filters the data of the other stores and deletes that data, only leaving the data of the choosen store.

and after this I want to make a new workbook, saving as my ".xlsm" file to ".xlsx"

But after runing the code i have a pop up message asking if i want "to continue saving as a macro-free workbook"

If i click yes, i have a error saying:

1004 VB Projects and XLM sheets cannot be saved in a macro-free
  workbook

What can i do to fix it?

this is the code to save the new workbook:

Dim Fname As String

Fname = "02.VIM_REPORT MENSAL - " & Worksheets("aux").Range("V2") & " - " & Worksheets("aux").Range("V3") & ".xlsx"
ActiveWorkbook.SaveAs Filename:=Fname, FileFormat:=xlOpenXMLWorkbook

    ActiveWorkbook.Close False


问:
C++ calling the correct method for derived class
I want to have some nice linear algebra in my code with the help of operator overloading. E.g. a product with a vector and a scalar looks like vec * scalar and returns a vector. The problem is, i have 2D and 3D vectors and at compile time is is not know which one it will be.

My attempt was a empty base class and a derived class for 2D and 3D. However it seems like this is not working as expected because it is not calling the correct methods.

#include <cstdlib>
#include <iostream>

class baseVector {
public:
    baseVector() {}
    ~baseVector() {}
    virtual void print() {
        std::cout << "This is not the vector you are looking for" << std::endl;
    }
    virtual baseVector operator*(const double r) const {}
};

class Vector2 : public baseVector {
public:
    Vector2() {}
    Vector2(double x, double y) {
        data_[0] = x;
        data_[1] = y;
    }

    ~Vector2() {}

    void print() {
        std::cout << data_[0] << ", " << data_[1] << std::endl;
    }

    /** Product: Vector * Scalar */
    baseVector operator*(const double r) const {
        Vector2 result(data_[0]*r,
                       data_[1]*r);
        return result;
    }

private:
    double data_[2];
};

int main(int argc, char** argv) {
    // Construct vector of derived type which is not known at compile time
    baseVector * myVec = new Vector2(1, 2);
    const double val = 5;

    baseVector & tempVec = *myVec;
    tempVec.print();

    // Some nice linear algebra here, can't use datatype Vector 2 because it is know known at compile time
    baseVector resVec = tempVec * val;

    // This should print 5, 10
    resVec.print();
    return 0;
}
```

I expect resVec to be a vector of type Vector2 with the values 5, 10. Instead it calls the print function of the base class. I understand somehow why this is happening but how do I achiev what I want?

Anyway, is this even the right way to go? Thanks in advance for every hint.

Edit: Slicing is not the answer but explains why it doesn't work. I've found a possible solution with the auto keyword. Skip the inheritance and use auto in the main instead of a specific type. Thanks everyone to make me thinking.

答:
To recap why Vector2::print is not called: resVec is not an instance of Vector2. The concrete i.e. most derived type of resVec is baseVector.

A solution is to give up on your attempt at an abstract interface and instead only provide the function in the derived class. You may want to implement it as a non-member function in order to support val * tempVec:

```<code>class Vector2 {
    // ...
    friend Vector2
    operator*(const Vector2& v, double r) {
        return {
            v.data_[0]*r,
            v.data_[1]*r,
        };
    }
    friend Vector2
    operator*(double r, const Vector2& v) {
        return {
            v.data_[0]*r,
            v.data_[1]*r,
        };
    }
};
</code>```

A modifying function virtual baseVector& baseVector::operator*=(double r) would be another possible approach.

Body:
I want to have some nice linear algebra in my code with the help of operator overloading. E.g. a product with a vector and a scalar looks like vec * scalar and returns a vector. The problem is, i have 2D and 3D vectors and at compile time is is not know which one it will be.

My attempt was a empty base class and a derived class for 2D and 3D. However it seems like this is not working as expected because it is not calling the correct methods.

#include <cstdlib>
#include <iostream>

class baseVector {
public:
    baseVector() {}
    ~baseVector() {}
    virtual void print() {
        std::cout << "This is not the vector you are looking for" << std::endl;
    }
    virtual baseVector operator*(const double r) const {}
};

class Vector2 : public baseVector {
public:
    Vector2() {}
    Vector2(double x, double y) {
        data_[0] = x;
        data_[1] = y;
    }

    ~Vector2() {}

    void print() {
        std::cout << data_[0] << ", " << data_[1] << std::endl;
    }

    /** Product: Vector * Scalar */
    baseVector operator*(const double r) const {
        Vector2 result(data_[0]*r,
                       data_[1]*r);
        return result;
    }

private:
    double data_[2];
};

int main(int argc, char** argv) {
    // Construct vector of derived type which is not known at compile time
    baseVector * myVec = new Vector2(1, 2);
    const double val = 5;

    baseVector & tempVec = *myVec;
    tempVec.print();

    // Some nice linear algebra here, can't use datatype Vector 2 because it is know known at compile time
    baseVector resVec = tempVec * val;

    // This should print 5, 10
    resVec.print();
    return 0;
}

I expect resVec to be a vector of type Vector2 with the values 5, 10. Instead it calls the print function of the base class. I understand somehow why this is happening but how do I achiev what I want?

Anyway, is this even the right way to go? Thanks in advance for every hint.

Edit: Slicing is not the answer but explains why it doesn't work. I've found a possible solution with the auto keyword. Skip the inheritance and use auto in the main instead of a specific type. Thanks everyone to make me thinking.

Body:
To recap why Vector2::print is not called: resVec is not an instance of Vector2. The concrete i.e. most derived type of resVec is baseVector.

A solution is to give up on your attempt at an abstract interface and instead only provide the function in the derived class. You may want to implement it as a non-member function in order to support val * tempVec:

class Vector2 {
    // ...
    friend Vector2
    operator*(const Vector2& v, double r) {
        return {
            v.data_[0]*r,
            v.data_[1]*r,
        };
    }
    friend Vector2
    operator*(double r, const Vector2& v) {
        return {
            v.data_[0]*r,
            v.data_[1]*r,
        };
    }
};

A modifying function virtual baseVector& baseVector::operator*=(double r) would be another possible approach.


问:
Update Table with rows from a different Table using Loop in OracleDB
I am new to OracleDB and hoping to help me out. I have two tables, shown on the Image below. I want to insert any number of rows from Table2 to Table1 using a loop (maybe in procedure). This can happen by iterating through IDs from the Table2 and inserting the chosen from me into New Updated Table1
Image:

The second table must remain the same and I must be able to do this with every rows from Table2 that suite my needs. I wrote a pseudo code, but I am not sure how to implement it. Thanks in advance!

答:
This is the original table1:

```<code>SQL> select * from table1;

        ID NAME            PHONE
---------- ---------- ----------
         1 Bob            123456
         2 Jake           654975
         3 Dillan         252487
</code>```

If you want to "copy" any rows you want, then a simple option is a pure SQL INSERT statement, e.g.

```<code>SQL> insert into table1 (id, name, phone)
  2    select id, name, phone
  3    from table2
  4    where id = &par_id;
Enter value for par_id: 4

1 row created.
</code>```

(&par_id is a SQL*Plus substitution variable)

Or, you could specify a few of them as IN list, e.g.

```<code>SQL> insert into table1 (id, name, phone)
  2    select id, name, phone
  3    from table2
  4    where id in (5, 6);

2 rows created.
</code>```

The result is then

```<code>SQL> select * from table1 order by id;

        ID NAME            PHONE
---------- ---------- ----------
         1 Bob            123456
         2 Jake           654975
         3 Dillan         252487
         4 Harley         265687
         5 Jack           244587
         6 Luther         259876

6 rows selected.
</code>```

Or, you could write a procedure to do that (in a loop? Why not, if it does the job), but I presume that the final choice depends on what exactly you want to do. Currently, I don't see a need for PL/SQL.

Body:
This is the original table1:

SQL> select * from table1;

        ID NAME            PHONE
---------- ---------- ----------
         1 Bob            123456
         2 Jake           654975
         3 Dillan         252487

If you want to "copy" any rows you want, then a simple option is a pure SQL INSERT statement, e.g.

SQL> insert into table1 (id, name, phone)
  2    select id, name, phone
  3    from table2
  4    where id = &par_id;
Enter value for par_id: 4

1 row created.

(&par_id is a SQL*Plus substitution variable)

Or, you could specify a few of them as IN list, e.g.

SQL> insert into table1 (id, name, phone)
  2    select id, name, phone
  3    from table2
  4    where id in (5, 6);

2 rows created.

The result is then

SQL> select * from table1 order by id;

        ID NAME            PHONE
---------- ---------- ----------
         1 Bob            123456
         2 Jake           654975
         3 Dillan         252487
         4 Harley         265687
         5 Jack           244587
         6 Luther         259876

6 rows selected.

Or, you could write a procedure to do that (in a loop? Why not, if it does the job), but I presume that the final choice depends on what exactly you want to do. Currently, I don't see a need for PL/SQL.


问:
Laravel Error - Call to undefined method Illuminate\Database\Query\Builder::gets()
I am running a query in Laravel but got this error:

Call to undefined method Illuminate\Database\Query\Builder::gets()

I have written the query

Controller

```<code>            $currentMonth = date('m');
            $currentmonthbilling = DB::table("billings")
                   ->select(DB::raw("SUM(amount) as total"))
                   ->whereRaw('MONTH(created_at) = ?',$currentMonth)
                   ->gets();
</code>```

View

```<code><span class="info-box-number">{{ $currentmonthbilling[0]->total }}</span>
</code>```

I expect it to display total amount for the current month

答:
is ->get(); not ->gets();

```<code>$currentmonthbilling = DB::table("billings")
                   ->select(DB::raw("SUM(amount) as total"))
                   ->whereRaw('MONTH(created_at) = ?',$currentMonth)
                   ->get();`
</code>```

Body:
I am running a query in Laravel but got this error:

Call to undefined method Illuminate\Database\Query\Builder::gets()

I have written the query

Controller

            $currentMonth = date('m');
            $currentmonthbilling = DB::table("billings")
                   ->select(DB::raw("SUM(amount) as total"))
                   ->whereRaw('MONTH(created_at) = ?',$currentMonth)
                   ->gets();

View

{{ $currentmonthbilling[0]->total }}

I expect it to display total amount for the current month

Body:
is ->get(); not ->gets();

$currentmonthbilling = DB::table("billings")
                   ->select(DB::raw("SUM(amount) as total"))
                   ->whereRaw('MONTH(created_at) = ?',$currentMonth)
                   ->get();`


问:
How to distinguish between onClick and onFocus events in JavaScript?
I'm listening to the onFocus and to onClick events on the same input-element. The onFocus should always set a boolean to true and the onClick event handler should toggle this boolean.

But on a click both events are fired with the onFocus at first, so the boolean is being set to true first and then toggled by the onClick. How can I change this behaviour?

I tried to use stopPropagation inside the onClick event handler. Also setting a isClicked flag did not help. (Probably because both events are fired at the same time) (see JSFiddle)

```<code>let input = document.getElementById("input");
let isOpen = false

input.onclick = () => {
    isOpen = !isOpen
}

input.onfocus = () => {
    isOpen = true
}

input.onblur = () => {
    isOpen = false
}
</code>```

JSFiddle: http://jsfiddle.net/coh29gwe/7/

At the first click on the input the isOpen flag should be true but is false.

答:
there are some confuse when you are setting isOpen variable.
I think you should use hasFocus property of this element to indicate the opening state Get focus state of an element

or you can validate the value of isOpen in onClick() before you set it

```<code>if (isOpen == false){
    isOpen = true;
}
</code>```

Because both of onFocus and onClick are fired when you perform a click thus you only need to set isOpen to true when onClick is called without onFocus (via script other some way that we don't know)

Body:
I'm listening to the onFocus and to onClick events on the same input-element. The onFocus should always set a boolean to true and the onClick event handler should toggle this boolean.

But on a click both events are fired with the onFocus at first, so the boolean is being set to true first and then toggled by the onClick. How can I change this behaviour?

I tried to use stopPropagation inside the onClick event handler. Also setting a isClicked flag did not help. (Probably because both events are fired at the same time) (see JSFiddle)

let input = document.getElementById("input");
let isOpen = false

input.onclick = () => {
    isOpen = !isOpen
}

input.onfocus = () => {
    isOpen = true
}

input.onblur = () => {
    isOpen = false
}

JSFiddle: http://jsfiddle.net/coh29gwe/7/

At the first click on the input the isOpen flag should be true but is false.

Body:
there are some confuse when you are setting isOpen variable.
I think you should use hasFocus property of this element to indicate the opening state Get focus state of an element

or you can validate the value of isOpen in onClick() before you set it

if (isOpen == false){
    isOpen = true;
}

Because both of onFocus and onClick are fired when you perform a click thus you only need to set isOpen to true when onClick is called without onFocus (via script other some way that we don't know)


问:
Store dynamically created objects in array C++
I have to create a game. I have Player class that is abstract. I have a GameEngine class that has a dynamic array of pointers to Player. Whenever a player is added I classify it and create a Mage or Hero object (both children of Player) in a "addPlayer()" method in GameEngine. However, after the method finishes the pointer is destroyed and if I try to access that item in the players array it crashes with "segmentation fault". I know why this is happening but I don't know how to work around. I'm not even sure if that's the right way to get this done. Can you give me advice? Thanks :)

EDIT

This is some sample code:

```<code>class GameEngine {
    ...
    Player** players;
    ...
    void addPlayer() {
        Hero h("Frodo");
        players[playerCount] = &h;
        playerCount++;
    }
}

class Player { ... }
class Hero : public Player { ... }
</code>```

答:
Maybe something like this:

```<code>class Player
{
  public:
    virtual std::string& get_name() const = 0;
};

class GameEngine
{
  public:
    std::vector<Player *> m_players;

    void  add_player(Player * p)
    {
      m_players.push_back(p);
    }
};
</code>```

The above is the essence of your question.  The add_player adds a player to your database.

A broader view:

```<code>class Shaman
: public Player
{
  std::string m_name;
  public:
    virtual std::string& get_name() const
    {
       return m_name;
    }
  Shaman()
    : m_name("Bubba")
  { ; }
};
</code>```

The above is an example class derived from Player.

Code fragment to create a dynamic instance and add to the GameEngine:

```<code>Shaman * p_bubba = new Shaman;
GameEngine game;
game.add_player(p_bubba);
</code>```

Remember that GameEngine class only knows about the public functions and members in Player.  C++ has no internal facilities for fetching the type name of the child types in the m_player database.  My recommendation is to provide all the functions that GameEngine needs to know in the Player class and let the descendants implement those functions.

Body:
I have to create a game. I have Player class that is abstract. I have a GameEngine class that has a dynamic array of pointers to Player. Whenever a player is added I classify it and create a Mage or Hero object (both children of Player) in a "addPlayer()" method in GameEngine. However, after the method finishes the pointer is destroyed and if I try to access that item in the players array it crashes with "segmentation fault". I know why this is happening but I don't know how to work around. I'm not even sure if that's the right way to get this done. Can you give me advice? Thanks :)

EDIT

This is some sample code:

class GameEngine {
    ...
    Player** players;
    ...
    void addPlayer() {
        Hero h("Frodo");
        players[playerCount] = &h;
        playerCount++;
    }
}

class Player { ... }
class Hero : public Player { ... }

Body:
Maybe something like this:

class Player
{
  public:
    virtual std::string& get_name() const = 0;
};

class GameEngine
{
  public:
    std::vector<Player *> m_players;

    void  add_player(Player * p)
    {
      m_players.push_back(p);
    }
};

The above is the essence of your question.  The add_player adds a player to your database.

A broader view:

class Shaman
: public Player
{
  std::string m_name;
  public:
    virtual std::string& get_name() const
    {
       return m_name;
    }
  Shaman()
    : m_name("Bubba")
  { ; }
};

The above is an example class derived from Player.

Code fragment to create a dynamic instance and add to the GameEngine:

Shaman * p_bubba = new Shaman;
GameEngine game;
game.add_player(p_bubba);

Remember that GameEngine class only knows about the public functions and members in Player.  C++ has no internal facilities for fetching the type name of the child types in the m_player database.  My recommendation is to provide all the functions that GameEngine needs to know in the Player class and let the descendants implement those functions.


答:
just disable Alerts.

try with

```<code>Application.DisplayAlerts = False

Dim Fname As String

Fname = "02.VIM_REPORT MENSAL - " & Worksheets("aux").Range("V2") & " - " & Worksheets("aux").Range("V3") & ".xlsx"
ActiveWorkbook.SaveAs Filename:=Fname, FileFormat:=xlOpenXMLWorkbook

ActiveWorkbook.Close False

Application.DisplayAlerts = True
</code>```

good luck

Title: How to fix VBA Error "Cannot saving ".xlsm" to ".xlsx""?

Body:
just disable Alerts.

try with

Application.DisplayAlerts = False

Dim Fname As String

Fname = "02.VIM_REPORT MENSAL - " & Worksheets("aux").Range("V2") & " - " & Worksheets("aux").Range("V3") & ".xlsx"
ActiveWorkbook.SaveAs Filename:=Fname, FileFormat:=xlOpenXMLWorkbook

ActiveWorkbook.Close False

Application.DisplayAlerts = True

good luck


问:
Iphone dev : how can I get a result from google currency converter?
Sorry for my english ^^
I would know how I can have a result from the google converter tool for currency, available on http://www.google.com/finance/converter?a=1&from=USD&to=GBP for example.

I have already tried something like that :

```<code>    -(IBAction)getResponse:(id) sender{

     NSString *myURLString = @"http://www.google.com/finance/converter?a=1&from=USD&to=GBP";

     NSURL *myURL =  [NSURL URLWithString: myURLString];

     NSData *data = [NSData alloc];

     data=[NSData dataWithContentsOfURL:myURL];

     if(data!=nil && data != ""){

          NSString *response = [[[NSString alloc] initWithData:data]]

          [label setText: response];

     }

     else [label setText:@"not working"];
}
</code>```

But when I click on my button, the label does not have a text (it is like it is empty).
Am I doing something wrong ?
Is it possible what I want to do ?
Thank you very much for your futures answers !
Olivier.

答:
```<code>NSString *myURLString = @"http://www.google.com/finance/converter?a=1&from=USD&to=GBP";

NSURL *myURL =  [NSURL URLWithString: myURLString];

NSData *data = [NSData alloc];

data=[NSData dataWithContentsOfURL:myURL];

if(data!=nil){

    NSString *response = [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding];

    NSLog(@"%@",response);
}
</code>```

Try this.
This API is giving HTML responce.

ContentLicense: CC BY-SA 3.0

Body:
Sorry for my english ^^
I would know how I can have a result from the google converter tool for currency, available on http://www.google.com/finance/converter?a=1&from=USD&to=GBP for example.

I have already tried something like that :

    -(IBAction)getResponse:(id) sender{

     NSString *myURLString = @"http://www.google.com/finance/converter?a=1&from=USD&to=GBP";

     NSURL *myURL =  [NSURL URLWithString: myURLString];

     NSData *data = [NSData alloc];

     data=[NSData dataWithContentsOfURL:myURL];

     if(data!=nil && data != ""){

          NSString *response = [[[NSString alloc] initWithData:data]]

          [label setText: response];

     }

     else [label setText:@"not working"];
}

But when I click on my button, the label does not have a text (it is like it is empty).
Am I doing something wrong ?
Is it possible what I want to do ?
Thank you very much for your futures answers !
Olivier.

Body:
NSString *myURLString = @"http://www.google.com/finance/converter?a=1&from=USD&to=GBP";

NSURL *myURL =  [NSURL URLWithString: myURLString];

NSData *data = [NSData alloc];

data=[NSData dataWithContentsOfURL:myURL];

if(data!=nil){

    NSString *response = [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding];

    NSLog(@"%@",response);
}

Try this.
This API is giving HTML responce.


问:
How to get jupyter notebook port inside the notebook?
Some applications (e.g. Bokeh) need to know the port of an application in order to work correctly. I can start a jupyter notebook with a default port, but sometimes jupyter takes a different port e.g. when the port is already in use. Therefore, I would like to get the port from inside the notebook and start my code with it, so that it runs independently. I found this snippet that does what I need, but not in every context:

```<code>%%javascript
IPython.OutputArea.prototype._should_scroll = function(lines) {return false;}
var nb = Jupyter.notebook;
var port = window.location.port;
nb.kernel.execute("PORT = '" + port + "'");
</code>```

Together with the jupyter extension AppMode this code does not work anymore. Therefore, I am looking for other, more robust methods of getting the port (and URL) from inside a notebook running a python 3 kernel.

答:
```<code>from notebook import notebookapp
port_list = [note["port"] for note in notebookapp.list_running_servers()]
</code>```

This returns a list containing all the ports of running jupyter servers

Body:
Some applications (e.g. Bokeh) need to know the port of an application in order to work correctly. I can start a jupyter notebook with a default port, but sometimes jupyter takes a different port e.g. when the port is already in use. Therefore, I would like to get the port from inside the notebook and start my code with it, so that it runs independently. I found this snippet that does what I need, but not in every context:

%%javascript
IPython.OutputArea.prototype._should_scroll = function(lines) {return false;}
var nb = Jupyter.notebook;
var port = window.location.port;
nb.kernel.execute("PORT = '" + port + "'");

Together with the jupyter extension AppMode this code does not work anymore. Therefore, I am looking for other, more robust methods of getting the port (and URL) from inside a notebook running a python 3 kernel.

Body:
from notebook import notebookapp
port_list = [note["port"] for note in notebookapp.list_running_servers()]

This returns a list containing all the ports of running jupyter servers


问:
Importing root CA or the intermediate CA instead of the individual public cert
SSL certs never ends to dazzle me. I have an web-app and it makes a rest call to another service from a partner to fetch certain data. They use a self sign'ed or an internal CA generated for the Company. The issue is whenever the other end updates there SSL cert, my app fails. This is because the public cert (.cer) that i downloaded from their website and imported in the java trustore of my app doesn't match with their new site. To fix this, i have to re-download their latest public server cert and import again to my java trust store. </p>

<p>Assuming that they use a consistent ROOT CA or an intermediate CA cert to sign their ever changing SSL certs, can i just import the ROOT CA or the INTERMEDIATE CA once and for in my java trust store all to deal with this? So, as long as they don't change the ROOT CA or the INTERMEDIATE CA, my app will be able to make the call.  </p>

答:
So their self signed CERT is not built from ROOT CA.  Their CERT they generated themselves, so that is why it is considered untrustworthy by default.  So every time they generate a new one, this is what happens:

Your app says hello to their server

Their server sends the newly generated CERT which includes information like: Public key, algorithm, cert valid date range, etc.

Your app gets the new CERT and compares it with the old CERT and realizes, oh, these are not the same.

Your app says, well, this is not trustworthy and throws an error.

This is by design because this would be similar to the same result of a man-in-the-middle attack. Your client only trusts certain CAs for that reason.  The job of a CA is to certify against certs to see if they are good or bad.  If you can add certs on the fly like that without the CA's knowledge, then the CA really has no idea which certs to trust.

So there could be an intermediate Certificate Authority that this company has opened up to you or that they have worked with to provide to you.  You would have to ask them to see if they are using some kind of CA at all that you could connect to.

I doubt this the case because you said they are using "self-signed" certs which implies that they are not working with any CA.

Body:
SSL certs never ends to dazzle me. I have an web-app and it makes a rest call to another service from a partner to fetch certain data. They use a self sign'ed or an internal CA generated for the Company. The issue is whenever the other end updates there SSL cert, my app fails. This is because the public cert (.cer) that i downloaded from their website and imported in the java trustore of my app doesn't match with their new site. To fix this, i have to re-download their latest public server cert and import again to my java trust store.

Assuming that they use a consistent ROOT CA or an intermediate CA cert to sign their ever changing SSL certs, can i just import the ROOT CA or the INTERMEDIATE CA once and for in my java trust store all to deal with this? So, as long as they don't change the ROOT CA or the INTERMEDIATE CA, my app will be able to make the call.


问:
Looking for a quicker way of fuzzy string matching
I am using fuzzywuzzy in python for fuzzy string matching. I have a set of names in a list named HKCP_list which I am matching against a pandas column iteratively to get the best possible match. Given below is the code for it

```<code>import fuzzywuzzy
from fuzzywuzzy import fuzz,process

def search_func(row):
    chk = process.extract(row,HKCP_list,scorer=fuzz_token_sort_ratio)[0]
    return chk

wc_df['match']=wc_df['concat_name'].map(search_func)
</code>```

The wc_df dataframe contains the column 'concat_name' which needs to be matched with every name in the list HKCP_list. The above code took around 2 hours to run with 6K names in the list and 11K names in the column 'concat_name'.

I have to rerun this on another data set where are 89K names in the list and 120K names in the column. In order to speed up the process, I got an idea in the following question on Stackoverflow

Vectorizing or Speeding up Fuzzywuzzy String Matching on PANDAS Column

In one of the comments in the answer in the above, it has been advised to compare names that have the same 1st letter. The 'concat_name' column that I am comparing with is a derived column obtained by concatenating 'first_name' and 'last_name' columns in the dataframe. Hence I am using the following function to match the 1st letter (since this is a token sort score that I am considering, I am comparing the 1st letter of both the first_name and last_name with the elements in the list). Given below is the code:

```<code>wc_df['first_name_1stletter'] = wc_df['first_name'].str[0]
wc_df['last_name_1stletter'] = wc_df['last_name'].str[0]

import time
start_time=time.time()
def match_func(row):
    CP_subset=[x for x in HKCP_list if x[0]==row['first_name_1stletter'] or x[0]==row['last_name_1stletter']]
    return CP_subset
wc_df['list_to_match']=wc_df.apply(match_func,axis=1)
end_time=time.time()
print(end_time-start_time)
</code>```

The above step took 1600 second with 6K X 11K data. The 'list_to_match' column contains the list of names to be compared for each concat_name. Now here I have to again take the list_to_match element and pass individual elements in a list and do the fuzzy string matching using the process.extract method. Is there a more elegant and faster way of doing this in the same step as above?

PS: Editing this to add an example as to how the list and the dataframe column looks like.

```<code>HKCp_list=['jeff bezs','michael blomberg','bill gtes','tim coook','elon musk']
concat_name=['jeff bezos','michael bloomberg','bill gates','tim cook','elon musk','donald trump','kim jong un', 'narendra modi','michael phelps']
first_name=['jeff','michael','bill','tim','elon','donald','kim','narendra','michael']
last_name=['bezos','bloomberg','gates','cook','musk','trump','jong un', 'modi','phelps']
import pandas as pd
df=pd.DataFrame({'first_name':first_name,'last_name':last_name,'concat_name':concat_name})
</code>```

Each row of the 'concat_name' in df has to be compared against the elements of HKcp_list.

PS: editing today to reflect the ":" and the row in the 2nd snippet of code I missed yesterday

Regards,
Nirvik

答:
You can try this function I wrote in another answer, not 100% sure how it holds in terms of speed, you can try for yourself:

```<code>from fuzzywuzzy import fuzz
from fuzzywuzzy import process

# Make dataframe out of list
HKCp = pd.DataFrame({'names':HKCp_list})

# Use fuzzy_merge function
fuzzy_merge(df, HKCp, 'concat_name', 'names')
</code>```

Output

```<code>  first_name  last_name        concat_name           matches
0       jeff      bezos         jeff bezos         jeff bezs
1    michael  bloomberg  michael bloomberg  michael blomberg
2       bill      gates         bill gates         bill gtes
3        tim       cook           tim cook         tim coook
4       elon       musk          elon musk         elon musk
5     donald      trump       donald trump
6        kim    jong un        kim jong un
7   narendra       modi      narendra modi
8    michael     phelps     michael phelps
</code>```

Note you can play with the treshold argument to get less exact matches

Body:
I am using fuzzywuzzy in python for fuzzy string matching. I have a set of names in a list named HKCP_list which I am matching against a pandas column iteratively to get the best possible match. Given below is the code for it

import fuzzywuzzy
from fuzzywuzzy import fuzz,process

def search_func(row):
    chk = process.extract(row,HKCP_list,scorer=fuzz_token_sort_ratio)[0]
    return chk

wc_df['match']=wc_df['concat_name'].map(search_func)

The wc_df dataframe contains the column 'concat_name' which needs to be matched with every name in the list HKCP_list. The above code took around 2 hours to run with 6K names in the list and 11K names in the column 'concat_name'.

I have to rerun this on another data set where are 89K names in the list and 120K names in the column. In order to speed up the process, I got an idea in the following question on Stackoverflow

Vectorizing or Speeding up Fuzzywuzzy String Matching on PANDAS Column

In one of the comments in the answer in the above, it has been advised to compare names that have the same 1st letter. The 'concat_name' column that I am comparing with is a derived column obtained by concatenating 'first_name' and 'last_name' columns in the dataframe. Hence I am using the following function to match the 1st letter (since this is a token sort score that I am considering, I am comparing the 1st letter of both the first_name and last_name with the elements in the list). Given below is the code:

wc_df['first_name_1stletter'] = wc_df['first_name'].str[0]
wc_df['last_name_1stletter'] = wc_df['last_name'].str[0]

import time
start_time=time.time()
def match_func(row):
    CP_subset=[x for x in HKCP_list if x[0]==row['first_name_1stletter'] or x[0]==row['last_name_1stletter']]
    return CP_subset
wc_df['list_to_match']=wc_df.apply(match_func,axis=1)
end_time=time.time()
print(end_time-start_time)

The above step took 1600 second with 6K X 11K data. The 'list_to_match' column contains the list of names to be compared for each concat_name. Now here I have to again take the list_to_match element and pass individual elements in a list and do the fuzzy string matching using the process.extract method. Is there a more elegant and faster way of doing this in the same step as above?

PS: Editing this to add an example as to how the list and the dataframe column looks like.

HKCp_list=['jeff bezs','michael blomberg','bill gtes','tim coook','elon musk']
concat_name=['jeff bezos','michael bloomberg','bill gates','tim cook','elon musk','donald trump','kim jong un', 'narendra modi','michael phelps']
first_name=['jeff','michael','bill','tim','elon','donald','kim','narendra','michael']
last_name=['bezos','bloomberg','gates','cook','musk','trump','jong un', 'modi','phelps']
import pandas as pd
df=pd.DataFrame({'first_name':first_name,'last_name':last_name,'concat_name':concat_name})

Each row of the 'concat_name' in df has to be compared against the elements of HKcp_list.

PS: editing today to reflect the ":" and the row in the 2nd snippet of code I missed yesterday

Regards,
Nirvik

Body:
You can try this function I wrote in another answer, not 100% sure how it holds in terms of speed, you can try for yourself:

from fuzzywuzzy import fuzz
from fuzzywuzzy import process

# Make dataframe out of list
HKCp = pd.DataFrame({'names':HKCp_list})

# Use fuzzy_merge function
fuzzy_merge(df, HKCp, 'concat_name', 'names')

Output

  first_name  last_name        concat_name           matches
0       jeff      bezos         jeff bezos         jeff bezs
1    michael  bloomberg  michael bloomberg  michael blomberg
2       bill      gates         bill gates         bill gtes
3        tim       cook           tim cook         tim coook
4       elon       musk          elon musk         elon musk
5     donald      trump       donald trump
6        kim    jong un        kim jong un
7   narendra       modi      narendra modi
8    michael     phelps     michael phelps

Note you can play with the treshold argument to get less exact matches


问:
C# Writeline that responds with name
I haven't used variables on C# yet so I don't know how I would go about having the next Console.Writeline respond saying, "Hello X, welcome!". Adding the users input to the X.</p>

```<code>Console.WriteLine("What is your name?");
String answer = Console.ReadLine();

if (answer == string)
    Console.WriteLine("Okay , welcome!");
}
</code>```

答:
Use interpolated strings $"Hello {x} , welcome!":

```<code>Console.WriteLine("What is your name?");
string x = Console.ReadLine();// reading the name from the console
Console.WriteLine($"Hello {x} , welcome!");//displaying the name in the console window
</code>```

Also you can put the Console.ReadLine() inside the interpolated string so you don't have to create a string variable:

```<code>Console.WriteLine("What is your name?");
Console.WriteLine($"Hello {Console.ReadLine()} , welcome!");
</code>```

You can find out more about interpolated strings here.

Title: C# Writeline that responds with name

Body:
I haven't used variables on C# yet so I don't know how I would go about having the next Console.Writeline respond saying, "Hello X, welcome!". Adding the users input to the X.

Console.WriteLine("What is your name?");
String answer = Console.ReadLine();

if (answer == string)
    Console.WriteLine("Okay , welcome!");
}

Body:
Use interpolated strings $"Hello {x} , welcome!":

Console.WriteLine("What is your name?");
string x = Console.ReadLine();// reading the name from the console
Console.WriteLine($"Hello {x} , welcome!");//displaying the name in the console window

Also you can put the Console.ReadLine() inside the interpolated string so you don't have to create a string variable:

Console.WriteLine("What is your name?");
Console.WriteLine($"Hello {Console.ReadLine()} , welcome!");

You can find out more about interpolated strings here.


问:
I want to export the array as a CSV file
I want to separate the array (1) and array (2) with commas or tabs
but
It is classified by each letter.

Now

T,h,i,s, ,i,s, ,p,r,o,b,a,b,l,y, ,t,h,e, ,h,i,g,h,e,s,t, ,8,/,1,0, ,I, ,c,o,u,l,d, ,g,i,v,e, ,f,o,r, ,a,n, ,8,/,1,0, ,m,o,v,i,e,.,T,h,e,r,e, ,a,r,e, ,s,o,m,e, ,v,e,r,y, ,g,o,o,d, ,m,o,m,e,n,t,s, ,i,n, ,E,n,d,g,a,m,e, ,a,n,d, ,t,h,a,t,',s, ,c,o,m,i,n,g, ,f,r,o,m, ,a, ,l,o,n,g, ,s,t,a,n,d,i,n,g, ,M,C,U, ,f,a,n, ,g,r,o,w,i,n,g, ,u,p, ,w,i,t,h, ,t,h,e,s,e, ,m,o,v,i,e,s,., ,I,n, ,c,r,e,a,t,i,n,g, ,a,n, ,e,x,t,e,n,s,i,v,e, ,a,n,d, ,e,m,o,t,i,o,n,a,l, ,j,o,u,r,n,e,y, ,f,o,r, ,a, ,l,o,t, ,o,f, ,t,h,e, ,M,C,U, ,c,h,a,r,a,c,t,e,r,s,",", ,i,t, ,a,b,s,o,l,u,t,e,l,y, ,s,u,c,c,e,e,d,s,.,E,n,d,g,a,m,e, ,u,l,t,i,m,a,t,e,l,y, ,i,s, ,a,n, ,e,x,c,e,l,l,e,n,t, ,c,o,n,c,l,u,s,i,o,n, ,t,o, ,o,v,e,r, ,1,0, ,y,e,a,r,s, ,o,f, ,f,i,l,m, ,b,u,t, ,I, ,f,e,e,l, ,t,h,e, ,p,l,o,t,',s, ,p,a,c,i,n,g, ,a,n,d, ,d,i,r,e,c,t,i,o,n, ,i,s, ,r,e,a,l,l,y, ,l,a,c,k,i,n,g, ,t,o, ,I,n,f,i,n,i,t,y, ,W,a,r,",", ,w,h,i,c,h, ,',t,r,i,m,m,e,d, ,t,h,e, ,f,a,t,', ,a,n,d, ,w,a,s, ,m,u,c,h, ,m,o,r,e, ,f,o,c,u,s,e,d, ,a,n,d, ,e,n,e,r,g,e,t,i,c,., ,G,r,a,n,t,e,d,

Want

[sentence A] , [sentence B] , [sentence C]

```<code>html = driver.page_source
soup = BeautifulSoup(html, "html.parser")

for link in soup.find_all('div','text show-more__control'):
    Result.append(link.text.strip())

with open("Filename", 'w', encoding='utf-8')as f:
    writer = csv.writer(f)

    for i in range(len(Result)):
        row = Result[i]
        writer.writerow(row)

#Result is separated into String type.
#Result [1] = "sentence A"
#Result [2] = "sentence B"
</code>```

Thanks!

答:
Say, for example, running this code

```<code>for link in soup.find_all('div','text show-more__control'):
    Result.append(link.text.strip())
</code>```

Gives us this list (Result):

```<code>['foo', 'bar', 'baz']
</code>```

Now let's loop over the list

```<code>for i in range(len(Result)):
    row = Result[i]
</code>```

row is equal to each element in the list as it's iterated over:

in the first iteration it's 'foo'

in the second iteration it's 'bar'

in the third iteration it's 'baz'

each of these values is a string.

In the line

```<code>writer.writerow(row)
</code>```

the writerow method expects an iterable, and assigns each item in the iterable to a separate column in the csv row.  So if it's passed 'foo' then the resulting row will be 'f,o,o'.

If there  is only one column - the element from Result in each row, the code needs to be like this:

```<code>with open("Filename", 'w', encoding='utf-8')as f:
    writer = csv.writer(f)

    for row in Result:
        writer.writerow([row])
</code>```

We make row an element of a length 1 list to make writerow behave as expected.

Body:
I want to separate the array (1) and array (2) with commas or tabs
but
It is classified by each letter.

Now

T,h,i,s, ,i,s, ,p,r,o,b,a,b,l,y, ,t,h,e, ,h,i,g,h,e,s,t, ,8,/,1,0, ,I, ,c,o,u,l,d, ,g,i,v,e, ,f,o,r, ,a,n, ,8,/,1,0, ,m,o,v,i,e,.,T,h,e,r,e, ,a,r,e, ,s,o,m,e, ,v,e,r,y, ,g,o,o,d, ,m,o,m,e,n,t,s, ,i,n, ,E,n,d,g,a,m,e, ,a,n,d, ,t,h,a,t,',s, ,c,o,m,i,n,g, ,f,r,o,m, ,a, ,l,o,n,g, ,s,t,a,n,d,i,n,g, ,M,C,U, ,f,a,n, ,g,r,o,w,i,n,g, ,u,p, ,w,i,t,h, ,t,h,e,s,e, ,m,o,v,i,e,s,., ,I,n, ,c,r,e,a,t,i,n,g, ,a,n, ,e,x,t,e,n,s,i,v,e, ,a,n,d, ,e,m,o,t,i,o,n,a,l, ,j,o,u,r,n,e,y, ,f,o,r, ,a, ,l,o,t, ,o,f, ,t,h,e, ,M,C,U, ,c,h,a,r,a,c,t,e,r,s,",", ,i,t, ,a,b,s,o,l,u,t,e,l,y, ,s,u,c,c,e,e,d,s,.,E,n,d,g,a,m,e, ,u,l,t,i,m,a,t,e,l,y, ,i,s, ,a,n, ,e,x,c,e,l,l,e,n,t, ,c,o,n,c,l,u,s,i,o,n, ,t,o, ,o,v,e,r, ,1,0, ,y,e,a,r,s, ,o,f, ,f,i,l,m, ,b,u,t, ,I, ,f,e,e,l, ,t,h,e, ,p,l,o,t,',s, ,p,a,c,i,n,g, ,a,n,d, ,d,i,r,e,c,t,i,o,n, ,i,s, ,r,e,a,l,l,y, ,l,a,c,k,i,n,g, ,t,o, ,I,n,f,i,n,i,t,y, ,W,a,r,",", ,w,h,i,c,h, ,',t,r,i,m,m,e,d, ,t,h,e, ,f,a,t,', ,a,n,d, ,w,a,s, ,m,u,c,h, ,m,o,r,e, ,f,o,c,u,s,e,d, ,a,n,d, ,e,n,e,r,g,e,t,i,c,., ,G,r,a,n,t,e,d,

Want

[sentence A] , [sentence B] , [sentence C]

html = driver.page_source
soup = BeautifulSoup(html, "html.parser")

for link in soup.find_all('div','text show-more__control'):
    Result.append(link.text.strip())

with open("Filename", 'w', encoding='utf-8')as f:
    writer = csv.writer(f)

    for i in range(len(Result)):
        row = Result[i]
        writer.writerow(row)

#Result is separated into String type.
#Result [1] = "sentence A"
#Result [2] = "sentence B"

Thanks!

Body:
Say, for example, running this code

for link in soup.find_all('div','text show-more__control'):
    Result.append(link.text.strip())

Gives us this list (Result):

['foo', 'bar', 'baz']

Now let's loop over the list

for i in range(len(Result)):
    row = Result[i]

row is equal to each element in the list as it's iterated over:

in the first iteration it's 'foo'

in the second iteration it's 'bar'

in the third iteration it's 'baz'

each of these values is a string.

In the line

writer.writerow(row)

the writerow method expects an iterable, and assigns each item in the iterable to a separate column in the csv row.  So if it's passed 'foo' then the resulting row will be 'f,o,o'.

If there  is only one column - the element from Result in each row, the code needs to be like this:

with open("Filename", 'w', encoding='utf-8')as f:
    writer = csv.writer(f)

    for row in Result:
        writer.writerow([row])

We make row an element of a length 1 list to make writerow behave as expected.


问:
Is it possible to inject shell/python commands from a configuration file?
Say you have a some meta data for a custom file format that your python app reads. Something like a csv with variables that can change as the file is manipulated:

```<code>var1,data1
var2,data2
var3,data3
</code>```

So if the user can manipulate this meta data, do you have to worry about someone crafting a malformed meta data file that will allow some arbitrary code execution? The only thing I can imagine if you you made the poor choice to make var1 be a shell command that you execute with os.sys(data1) in your own code somewhere. Also, if this were C then you would have to worry about buffers being blown, but I don't think you have to worry about that with python. If your reading in that data as a string is it possible to somehow escape the string "\n os.sys('rm -r /'), this SQL like example totally wont work, but is there similar that is possible?

答: Depends entirely on the way the file is processed, but generally this should be safe. In Python, you have to put in some effort if you want to treat text as code and execute it.</p>

Body:
Say you have a some meta data for a custom file format that your python app reads. Something like a csv with variables that can change as the file is manipulated:

var1,data1
var2,data2
var3,data3

So if the user can manipulate this meta data, do you have to worry about someone crafting a malformed meta data file that will allow some arbitrary code execution? The only thing I can imagine if you you made the poor choice to make var1 be a shell command that you execute with os.sys(data1) in your own code somewhere. Also, if this were C then you would have to worry about buffers being blown, but I don't think you have to worry about that with python. If your reading in that data as a string is it possible to somehow escape the string "\n os.sys('rm -r /'), this SQL like example totally wont work, but is there similar that is possible?


问:
IntelliJ IDEA 13 uses Java 1.5 despite setting to 1.7
Despite specifying JDK 1.7 in all project settings (including in File -> Project Structure -> Project :: Project SDK), the following error is produced by IntelliJ 13 when trying to compile some simple Java 7 code which does use the diamond operator:

```<code>java: diamond operator is not supported in -source 1.5
(use -source 7 or higher to enable diamond operator)
</code>```

Is there any other place in the configuration where the expected -source 7 option should be enabled?

答:
One more thing that could cause this is having incorrect version of the <parent> project.

In my case it was pointing to a non-existing project and for some reason IntelliJ downgraded version in settings to 1.5 and later when I fixed it, it was still interpreting target code version as 5 (despite setting it to 11).

Body:
Despite specifying JDK 1.7 in all project settings (including in File -> Project Structure -> Project :: Project SDK), the following error is produced by IntelliJ 13 when trying to compile some simple Java 7 code which does use the diamond operator:

java: diamond operator is not supported in -source 1.5
(use -source 7 or higher to enable diamond operator)

Is there any other place in the configuration where the expected -source 7 option should be enabled?


问:
How do I download a release asset from GitLab via curl
Im trying to create a bash script to download a private release from GitLab using curl but it keeps getting redirected to the signin page.

How can I do this?

I have tried the following with no luck:

```<code>curl --header "PRIVATE-TOKEN: XXXXXXXXX" "https://gitlab.com/mrhid6/test/-/archive/v0.0.5/test-v0.0.5.zip"
</code>```

答:
Gitlab said it is bug =(

https://gitlab.com/gitlab-org/gitlab-ce/issues/62307

I want to download assets too.

Body:
Im trying to create a bash script to download a private release from GitLab using curl but it keeps getting redirected to the signin page.

How can I do this?

I have tried the following with no luck:

curl --header "PRIVATE-TOKEN: XXXXXXXXX" "https://gitlab.com/mrhid6/test/-/archive/v0.0.5/test-v0.0.5.zip"


问:
Fitting a Logistic Curve to Data
I would like to fit a logaritmic function to some data with scipy.

Unfortunatley I get the following error: Covariance of the parameters could not be estimated

How can I prevent this?

import numpy as np
import scipy.optimize as opt
import matplotlib.pyplot as plt

x = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0]
y = [0.073, 2.521, 15.879, 48.365, 72.68, 90.298, 92.111, 93.44, 93.439, 93.389, 93.381, 93.367, 93.94, 93.269, 96.376]

def f(x, a, b, c, d):
    return a / (1. + np.exp(-c * (x - d))) + b

(a_, b_, c_, d_), _ = opt.curve_fit(f, x, y)

y_fit = f(x, a_, b_, c_, d_)
fig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.plot(x, y, 'o')
ax.plot(x, y_fit, '-')
```

答: I tried your code under Python2.7 kernel. I did not get the error you mentioned. The only thing is y_fit=71.50186844 for all values of x. </p>

Title: Fitting a Logistic Curve to Data


问:
Best practices for internationalization/localization with lit-element/lit-html
Thank you for reading.

I am new to polymer/lit-element,lit-html. I have started with the PWA starter kit. And at my surprise it doesn't use polymer elements but lit-elements.

I have tried to apply the default app-localize-behaviour from https://polymer-library.polymer-project.org/3.0/docs/apps/localize .

Without success.

Using mixinBehaviors with PageViewElement seems to break.

```<code>mixinBehaviors([AppLocalizeBehavior], PageViewElement)
</code>```

End up on an error of the type:

```<code>TypeError: this.constructor._classProperties is undefined
</code>```

I saw in the same time there has been several libraries starting to flourish like:

https://github.com/andreasbm/lit-translate

Or:

https://github.com/hamedasemi/lit-element-i18n

So, I must admit I am now lost, in what should I do to do internationalization or localization with lit-element and lit-html.

Is there any recommended library, did I miss a post about what is the official recommended way?

Thank you in advance, and have a lovely day.

答:
I don't think there is an official solution, and lit-element is still to young to have seen a consensus emerge within the users, so there is many solutions, each one trying it thing.

For my part, I have tested (not in production, only on small sides projects) lit-translate that you cite, and https://vaadin.com/directory/component/t2ymi18n-element

Both seems to work pretty good.
The second one is maintained by a team that is serious and follow their components. I have worked with some of theirs before, and never had any important issues. I don't know who is maintaining the first one, but it seems to be answers on issues, and regular updates, so they seems serious too.

I think you can go and try the one that seems easier to use, and don't hesitate to come add feedback on them, it will serve to everyone :)

Body:
Thank you for reading.

I am new to polymer/lit-element,lit-html. I have started with the PWA starter kit. And at my surprise it doesn't use polymer elements but lit-elements.

I have tried to apply the default app-localize-behaviour from https://polymer-library.polymer-project.org/3.0/docs/apps/localize .

Without success.

Using mixinBehaviors with PageViewElement seems to break.

mixinBehaviors([AppLocalizeBehavior], PageViewElement)

End up on an error of the type:

TypeError: this.constructor._classProperties is undefined

I saw in the same time there has been several libraries starting to flourish like:

https://github.com/andreasbm/lit-translate

Or:

https://github.com/hamedasemi/lit-element-i18n

So, I must admit I am now lost, in what should I do to do internationalization or localization with lit-element and lit-html.

Is there any recommended library, did I miss a post about what is the official recommended way?

Thank you in advance, and have a lovely day.


问:
Table cell with image rendered too large in IE
I have the following simple table to reproduce the issue:

```<code><TABLE>
  <TR>
    <TD style="border: black solid 1px; width:24px; height:68px; margin:0px; padding:0px" >
    <IMG
      style="width: 24px; height: 68px; margin:0px; padding:0px; border:none"
      src="Image24x68.png">
    </TD>
  </TR>
</TABLE>
</code>```

The image is actually 24x86 pixels large. The border is just to mark the cell's boundaries. There is no css file assigned to the document.

I want the cell to be exactly as large as the image.

The problem is: the table cell gets always rendered a few pixels too high in any IE version (6, 7, 8) while it works fine in Firefox and other browsers.

Is there any solution / workaround for this?

答:
I tried all the other solutions on this page:

using display:block

removing whitespace in the  tags (i.e. I used
 and  tags without putting any whitespace between them)

using

```<code>padding:0px;
border-spacing:0px;
border-style:none;
border-collapse: collapse;
margin:0;
overflow: hidden;
</code>```

Except for approach (1), these didn't work on IE. After tearing my hair out for three hours, I found this better solution: add a hspace=0 attribute to the image tag. For example:

```<code><img src="http://www.printersrose.com/css/myimages/book1.jpg" alt="Header1"
  class="ImageHeader" hspace="0">
</code>```

I set up an example of this at http://www.PrintersRose.com.

Body:
I have the following simple table to reproduce the issue:

The image is actually 24x86 pixels large. The border is just to mark the cell's boundaries. There is no css file assigned to the document.

I want the cell to be exactly as large as the image.

The problem is: the table cell gets always rendered a few pixels too high in any IE version (6, 7, 8) while it works fine in Firefox and other browsers.

Is there any solution / workaround for this?

Body:
I tried all the other solutions on this page:

using display:block

removing whitespace in the <td> tags (i.e. I used <tr> and <td> tags without putting any whitespace between them)

using

padding:0px;
border-spacing:0px;
border-style:none;
border-collapse: collapse;
margin:0;
overflow: hidden;

Except for approach (1), these didn't work on IE. After tearing my hair out for three hours, I found this better solution: add a hspace=0 attribute to the image tag. For example:

<img src="http://www.printersrose.com/css/myimages/book1.jpg" alt="Header1"
  class="ImageHeader" hspace="0">

I set up an example of this at http://www.PrintersRose.com.


问:
How to change node name in xml with Nokogiri
I need to change

```<code>  <Bureau xmlns="http://www.bbc.com/namespace"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    </Bureau>
</code>```

to

```<code> <Bureau>
   </Bureau>
</code>```

For this I use nokogiri gem. Also, I get this xml from request.

I tried to make it with different methods:xpath,at_xpath.But can't replace it to node name which I need.

```<code>doc = Nokogiri::XML(response)
</code>```

答: Adding doc.remove_namespaces! work for me</p>

Body:
I need to change

  <Bureau xmlns="http://www.bbc.com/namespace"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    </Bureau>

to

 <Bureau>
   </Bureau>

For this I use nokogiri gem. Also, I get this xml from request.

I tried to make it with different methods:xpath,at_xpath.But can't replace it to node name which I need.

doc = Nokogiri::XML(response)


问:
how to make the conversion from barycentric coordinates to Cartesian coordinates?
per wiki, the conversion from barycentric coordinates to Cartesian coordinates is as follow

here is a piece of code come from somewhere else

```<code>import numpy as np
import matplotlib.pyplot as plt
# from barycentric coordinates to Cartesian coordinates
a = np.array([0.  , 0.  , 1.  , 0.25, 0.25, 0.5 ])
b = np.array([0.  , 1.  , 0.  , 0.25, 0.5 , 0.25])
c = np.array([1.  , 0.  , 0.  , 0.5 , 0.25, 0.25])
x = 0.5 * ( 2.*b+c ) / ( a+b+c )
y = 0.5*np.sqrt(3) * c / (a+b+c)
plt.scatter(x,y)
plt.show()
</code>```

it seems that the piece of code is using another formula, if it is, what is the formula?

assume the barycentric coordinates of B is (0,0,1), how to compute its Cartesian coordinates? what lambda_1, lambda_2, lambda_3, x_1, x_2, x_3, y_1, y_2, y_3 are for point B?

答:
Your formula is correct.

Assuming that the three corners of a triangles are encoded as the columns of the matrix t, here is a simple Python implementation:

```<code>import numpy as np

def get_cartesian_from_barycentric(b, t):
    return t.dot(b)

b = np.array([0.25,0.3,0.45]) # Barycentric coordinates
t = np.transpose(np.array([[0,0],[1,0],[0,1]])) # Triangle
c = get_cartesian_from_barycentric(b, t)
</code>```

The formula you found is also calculating Cartesian from barycentric coordinates but uses a predefined regular triangle with the following coordinates:

```<code>(x1,y1) = (0,0)
(x2,y2) = (1,0)
(x3,y3) = (1/2,sqrt(3)/2)
</code>```

In this calculation, the code considers that every column is a point expressed with barycentric coordinates. Thus, it calculates 6 points at once. Furthermore, barycentric coordinates need to be normalized, i.e., lambda1 + lamda2 + lambda3 = 1. This code does not assume normalization, so it needs to divide by the sum of lambdas to ensure this property. Of course, we can see that the sum is always 1 for all 6 points, but the code could be used for lambdas that do not sum to 1.

In the last example you gave, B is a point of the triangle and is not expressed with barycentric coordinates. P is the point that is expressed with barycentric coordinate relative to the point A, B, and C. Let A = (x1,y1), B = (x2,y2), and C = (x3,y3), and that P has barycentric coordinates (l1,l2,l3). Then, the Cartesian coordinates (xp,yp) of P is

```<code>xp = l1*x1 + l2*x2 + l3*x3
yp = l1*y1 + l2*y2 + l3*y3
</code>```

Body:
per wiki, the conversion from barycentric coordinates to Cartesian coordinates is as follow

here is a piece of code come from somewhere else

import numpy as np
import matplotlib.pyplot as plt
# from barycentric coordinates to Cartesian coordinates
a = np.array([0.  , 0.  , 1.  , 0.25, 0.25, 0.5 ])
b = np.array([0.  , 1.  , 0.  , 0.25, 0.5 , 0.25])
c = np.array([1.  , 0.  , 0.  , 0.5 , 0.25, 0.25])
x = 0.5 * ( 2.*b+c ) / ( a+b+c )
y = 0.5*np.sqrt(3) * c / (a+b+c)
plt.scatter(x,y)
plt.show()

it seems that the piece of code is using another formula, if it is, what is the formula?

assume the barycentric coordinates of B is (0,0,1), how to compute its Cartesian coordinates? what lambda_1, lambda_2, lambda_3, x_1, x_2, x_3, y_1, y_2, y_3 are for point B?

Body:
Your formula is correct.

Assuming that the three corners of a triangles are encoded as the columns of the matrix t, here is a simple Python implementation:

import numpy as np

def get_cartesian_from_barycentric(b, t):
    return t.dot(b)

b = np.array([0.25,0.3,0.45]) # Barycentric coordinates
t = np.transpose(np.array([[0,0],[1,0],[0,1]])) # Triangle
c = get_cartesian_from_barycentric(b, t)

The formula you found is also calculating Cartesian from barycentric coordinates but uses a predefined regular triangle with the following coordinates:

(x1,y1) = (0,0)
(x2,y2) = (1,0)
(x3,y3) = (1/2,sqrt(3)/2)

In this calculation, the code considers that every column is a point expressed with barycentric coordinates. Thus, it calculates 6 points at once. Furthermore, barycentric coordinates need to be normalized, i.e., lambda1 + lamda2 + lambda3 = 1. This code does not assume normalization, so it needs to divide by the sum of lambdas to ensure this property. Of course, we can see that the sum is always 1 for all 6 points, but the code could be used for lambdas that do not sum to 1.

In the last example you gave, B is a point of the triangle and is not expressed with barycentric coordinates. P is the point that is expressed with barycentric coordinate relative to the point A, B, and C. Let A = (x1,y1), B = (x2,y2), and C = (x3,y3), and that P has barycentric coordinates (l1,l2,l3). Then, the Cartesian coordinates (xp,yp) of P is

xp = l1*x1 + l2*x2 + l3*x3
yp = l1*y1 + l2*y2 + l3*y3


问:
How to detect intersections of two faces of two bufferGeometryBox?
I am developing a 3d configurator. A cube appears on the scene. If you click on the side of this cube, a rectangle appears. The problem is that if I click on the same side of the cube, another one will be added over the existing rectangle. I would like to block the clicked side. My cubes and rectangles is buffer geometry. I can get raycasting face (a,b,c) and faceIndex. But how to get intersection of two different faces of two different objects? Sorry for my english

This is my project https://alovert.ru

my code

```<code>if (intersect) {
            var index = Math.floor( intersect.faceIndex / 6 );
                if ( intersect.object.name == 'cube' ) {

                    switch ( index ) {
                        case 0: load( intersect.object.position.x + 6.58, intersect.object.position.y, intersect.object.position.z, 'beam', 0, 0, 0 ); break;
                        case 1: load( intersect.object.position.x - 6.58, intersect.object.position.y, intersect.object.position.z, 'beam', 0, 0, 0 ); break;
                        case 2: load( intersect.object.position.x, intersect.object.position.y + 6.58, intersect.object.position.z, 'beam', 0, 0, 90 ); break;
                        case 3: load( intersect.object.position.x, intersect.object.position.y - 6.58, intersect.object.position.z, 'beam', 0, 0, 90 ); break;
                        case 4: load( intersect.object.position.x, intersect.object.position.y, intersect.object.position.z + 6.58, 'beam', 0, 90, 0 ); break;
                        case 5: load( intersect.object.position.x, intersect.object.position.y, intersect.object.position.z - 6.58, 'beam', 0, 90, 0 ); break;
                    }

                }`

</code>```

答:
I suppose that the newly created object that is duplicated will have the same global position (check this) value as the already existing one. So you can simply traverse over the existing objects and compare their positions, if they match or have a minor difference in position values, then block.

To make things faster, you can keep the objects global position values in a list once they are created and iterate over the list instead.

Body:
I am developing a 3d configurator. A cube appears on the scene. If you click on the side of this cube, a rectangle appears. The problem is that if I click on the same side of the cube, another one will be added over the existing rectangle. I would like to block the clicked side. My cubes and rectangles is buffer geometry. I can get raycasting face (a,b,c) and faceIndex. But how to get intersection of two different faces of two different objects? Sorry for my english

This is my project https://alovert.ru

my code

if (intersect) {
            var index = Math.floor( intersect.faceIndex / 6 );
                if ( intersect.object.name == 'cube' ) {

                    switch ( index ) {
                        case 0: load( intersect.object.position.x + 6.58, intersect.object.position.y, intersect.object.position.z, 'beam', 0, 0, 0 ); break;
                        case 1: load( intersect.object.position.x - 6.58, intersect.object.position.y, intersect.object.position.z, 'beam', 0, 0, 0 ); break;
                        case 2: load( intersect.object.position.x, intersect.object.position.y + 6.58, intersect.object.position.z, 'beam', 0, 0, 90 ); break;
                        case 3: load( intersect.object.position.x, intersect.object.position.y - 6.58, intersect.object.position.z, 'beam', 0, 0, 90 ); break;
                        case 4: load( intersect.object.position.x, intersect.object.position.y, intersect.object.position.z + 6.58, 'beam', 0, 90, 0 ); break;
                        case 5: load( intersect.object.position.x, intersect.object.position.y, intersect.object.position.z - 6.58, 'beam', 0, 90, 0 ); break;
                    }

                }`


问:
The "-controller" option does not exist in Laravel
In Laravel5 i am trying to create Model in Model folder with migration,controller and resource by using below command

```<code>$ php artisan make:model "Http/Model/Course" -mcr
</code>```

Or

```<code>$ php artisan make:model "Http/Model/Course" -crm
</code>```

The command works fine if i use simple command i.e.

```<code>$ php artisan make:model Course -mcr
</code>```

but if i change the path of Model folder it gives error

[Symfony\Component\Console\Exception\RuntimeException]     The "-c"
  option does not exist.

Kindly help me in that.

答:
Remove the "" quotes. They are the problem.

This should work:

```<code>php artisan make:model Http/Model/Course -mcr
</code>```

Also if you are not sure how a command works just add --help

```<code>php artisan make:model --help
</code>```

Body:
In Laravel5 i am trying to create Model in Model folder with migration,controller and resource by using below command

$ php artisan make:model "Http/Model/Course" -mcr

Or

$ php artisan make:model "Http/Model/Course" -crm

The command works fine if i use simple command i.e.

$ php artisan make:model Course -mcr

but if i change the path of Model folder it gives error

[Symfony\Component\Console\Exception\RuntimeException]     The "-c"
  option does not exist.

Kindly help me in that.

Body:
Remove the "" quotes. They are the problem.

This should work:

php artisan make:model Http/Model/Course -mcr

Also if you are not sure how a command works just add --help

php artisan make:model --help


问:
Can't read/write file in php
I've read all I could find about this problem on stackoverflow ! This may be a duplicate, but I couldn't fix my issue:
I can't do a thing with files using php.

I've used these commands to have permission:

```<code>sudo chown -R www-data:www-data /var/www/mysite
sudo chmod -R 777 /var/www/mysite
</code>```

This is the code:

```<code><?php

if(isset( $_POST['save_values'])) { // retrieve the form data by using the element's name attributes value as key
    if(!empty($_POST['getURL'])) {
        $URL = $_POST['getURL'];
    }

    if(!empty($_POST['getRefreshRate'])) {
        $RefreshRate = $_POST['getRefreshRate'];
    }

    if(!empty($_POST['getBrightness'])) {
        $Brightness = $_POST['getBrightness'];
    }

}

$filename = "/currentSettings.txt";
chmod($filename,0777);
$cSettings = fopen($filename, "r");

if($cSettings) {
    echo "$cSettings exists";
    while(($line = fgets($cSettings)) !== false) {
         $arr = explode("\n", $line);
         $URL = $arr[0];
         $RefreshRate = $arr[1];
         $Brightness = $arr[2];
    }
    fclose($cSettings);
} else {
    echo "File does not exist";
    fclose($cSettings);
    $cSettings = fopen('/currentSettings.txt', 'w');
    fwrite($cSettings,$URL."\n");
    fwrite($cSettings,$RefreshRate."\n");
    fwrite($cSettings,$Brightness."\n");
    fclose($cSettings);
}

?>
</code>```

It always returns File does not exist. It doesn't write in file and it doesn't read from file.
I've even created the file manually inside www/mysite and it still doesn't read it.

I am very new to PHP and I am certain that my code is broken but I couldn't find a fix for it.

This is how I've fixed it:

```<code><?php

$filename = "./inputs.txt";
$currentSettingsFile = fopen($filename, "c+");
$array = [];

if($currentSettingsFile) {
    echo "Reading from $filename";
    $array = explode(PHP_EOL, fread($currentSettingsFile, filesize($filename)));
    var_dump($array);
    $URL = $array[0];
    $RefreshRate = $array[1];
    $Brightness = $array[2];
    $closeFlag = fclose($currentSettingsFile);
}

if(isset( $_POST['save_values'])) { // retrieve the form data by using the element's name attributes value as key

    if(!empty($_POST['getURL'])) {
        $URL = $_POST['getURL'];
        $array[0] = $URL;
    }

    if(!empty($_POST['getRefreshRate'])) {
        $RefreshRate = $_POST['getRefreshRate'];
        $array[1] = $RefreshRate;
    }

    if(!empty($_POST['getBrightness'])) {
        $Brightness = $_POST['getBrightness'];
        $array[2] = $Brightness;
    }
}

if(!$closeFlag) fclose($currentSettingsFile);

$currentSettingsFile = fopen($filename, "c");
if($currentSettingsFile) {
    echo "Writing in $filename";
    echo fwrite($currentSettingsFile,$array[0].PHP_EOL);
    fwrite($currentSettingsFile,$array[1].PHP_EOL);
    fwrite($currentSettingsFile,$array[2].PHP_EOL);
    fclose($currentSettingsFile);
}

?>
</code>```

答:
The $handle does not seem to be defined.

Here is a version that seems to work while staying as close as possible to your example, but with an important caveat:

$filename = "./currentSettings.txt";

if(is_file($filename)) {
    echo "$filename exists";
        $arr = explode("\n", file_get_contents($filename));
        $URL = $arr[0];
        $RefreshRate = $arr[1];
        $Brightness = $arr[2];

} else {
    echo "File does not exist";
    $URL = ''."\n";
    $RefreshRate = ''."\n";
    $Brightness= ''."\n";
    file_put_contents($filename, $URL.$RefreshRate.$Brightness);
    chmod($filename,0777);
}
```

If the file does not exist, this will create it. But, since $URL, $RefreshRate, $Brightness are not defined, it only adds three empty lines to the file.

I am not sure about the rest of the project's structure but you might want to define some placeholders to fill in the file.

Title: Can't read/write file in php

Body:
I've read all I could find about this problem on stackoverflow ! This may be a duplicate, but I couldn't fix my issue:
I can't do a thing with files using php.

I've used these commands to have permission:

sudo chown -R www-data:www-data /var/www/mysite
sudo chmod -R 777 /var/www/mysite

This is the code:

<?php

if(isset( $_POST['save_values'])) { // retrieve the form data by using the element's name attributes value as key
    if(!empty($_POST['getURL'])) {
        $URL = $_POST['getURL'];
    }

    if(!empty($_POST['getRefreshRate'])) {
        $RefreshRate = $_POST['getRefreshRate'];
    }

    if(!empty($_POST['getBrightness'])) {
        $Brightness = $_POST['getBrightness'];
    }

}

$filename = "/currentSettings.txt";
chmod($filename,0777);
$cSettings = fopen($filename, "r");

if($cSettings) {
    echo "$cSettings exists";
    while(($line = fgets($cSettings)) !== false) {
         $arr = explode("\n", $line);
         $URL = $arr[0];
         $RefreshRate = $arr[1];
         $Brightness = $arr[2];
    }
    fclose($cSettings);
} else {
    echo "File does not exist";
    fclose($cSettings);
    $cSettings = fopen('/currentSettings.txt', 'w');
    fwrite($cSettings,$URL."\n");
    fwrite($cSettings,$RefreshRate."\n");
    fwrite($cSettings,$Brightness."\n");
    fclose($cSettings);
}

?>

It always returns File does not exist. It doesn't write in file and it doesn't read from file.
I've even created the file manually inside www/mysite and it still doesn't read it.

I am very new to PHP and I am certain that my code is broken but I couldn't find a fix for it.

This is how I've fixed it:

<?php

$filename = "./inputs.txt";
$currentSettingsFile = fopen($filename, "c+");
$array = [];

if($currentSettingsFile) {
    echo "Reading from $filename";
    $array = explode(PHP_EOL, fread($currentSettingsFile, filesize($filename)));
    var_dump($array);
    $URL = $array[0];
    $RefreshRate = $array[1];
    $Brightness = $array[2];
    $closeFlag = fclose($currentSettingsFile);
}

if(isset( $_POST['save_values'])) { // retrieve the form data by using the element's name attributes value as key

    if(!empty($_POST['getURL'])) {
        $URL = $_POST['getURL'];
        $array[0] = $URL;
    }

    if(!empty($_POST['getRefreshRate'])) {
        $RefreshRate = $_POST['getRefreshRate'];
        $array[1] = $RefreshRate;
    }

    if(!empty($_POST['getBrightness'])) {
        $Brightness = $_POST['getBrightness'];
        $array[2] = $Brightness;
    }
}

if(!$closeFlag) fclose($currentSettingsFile);

$currentSettingsFile = fopen($filename, "c");
if($currentSettingsFile) {
    echo "Writing in $filename";
    echo fwrite($currentSettingsFile,$array[0].PHP_EOL);
    fwrite($currentSettingsFile,$array[1].PHP_EOL);
    fwrite($currentSettingsFile,$array[2].PHP_EOL);
    fclose($currentSettingsFile);
}

?>

Body:
The $handle does not seem to be defined.

Here is a version that seems to work while staying as close as possible to your example, but with an important caveat:

$filename = "./currentSettings.txt";

if(is_file($filename)) {
    echo "$filename exists";
        $arr = explode("\n", file_get_contents($filename));
        $URL = $arr[0];
        $RefreshRate = $arr[1];
        $Brightness = $arr[2];

} else {
    echo "File does not exist";
    $URL = ''."\n";
    $RefreshRate = ''."\n";
    $Brightness= ''."\n";
    file_put_contents($filename, $URL.$RefreshRate.$Brightness);
    chmod($filename,0777);
}

If the file does not exist, this will create it. But, since $URL, $RefreshRate, $Brightness are not defined, it only adds three empty lines to the file.

I am not sure about the rest of the project's structure but you might want to define some placeholders to fill in the file.