问:
If O2 value is updated, then I need to send email to address in C2 with a template. The email should send only to C2 if the cell O2 is updated
I am using google spreadsheet.

I have Email addresses of participants in C column, and their corresponding Status in O column.( The status will be either, DONE or OPEN or ONGOING or empty).

If O2 value is updated, then I need to send email to address in C2 with a template. The email should send only to C2 if the cell O2 is updated.

I hope you can help me with this.

I tried this script but it sends to all email everytime.

Hope you can help me.

Thanks,

```<code>function StatusChange() {

  SpreadsheetApp.getActiveSpreadsheet().getSheetByName("R & A").activate();

  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var lr = ss.getLastRow();

  var templateText = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template for Email").getRange(1,1).getValue();

  var quotaLeft = MailApp.getRemainingDailyQuota();

  if((lr-1) > quotaLeft){
    Browser.msgBox("You have " + quotaLeft + " left and you're trying to send " + (lr-1) + " emails. Emails were not sent.");
  } else {

    for (var i = 2;i<=lr;i++){

      var currentEmail = ss.getRange(i, 3).getValue();
      var currentSheetTitle = ss.getRange(i, 11).getValue();
      var currentName = ss.getRange(i, 4).getValue();

      var messageBody = templateText.replace("{name}",currentName).replace("{title}",currentSheetTitle);
      var subjectLine = "Reminder: " + currentSheetTitle + " Status Change";

    MailApp.sendEmail(currentEmail, subjectLine, messageBody);

    } // close for loop

  } //close else statement

}
</code>```

If O2 value is updated, then I need to send email to address in C2 with a template. The email should send only to C2 if the cell O2 is updated.

答:
This can be achieved using an onEdit installable trigger, you'll need to set this up by either going to your triggers or running the below code supplied by Google once.

```<code>function createSpreadsheetEditTrigger() {
  var ss = SpreadsheetApp.getActive();
  ScriptApp.newTrigger('statusChange')
      .forSpreadsheet(ss)
      .onEdit()
      .create();
}
</code>```

By doing this you can check if column O is being updated, then run your if else statements based on that result. I've also cleaned up some of the variables so that you're not doing multiple SpreadsheetApp.getActiveSpreadsheet() calls unnecessarily.

Note: you won't be able to run the below script manually, it'll run automatically when the sheet is edited.

```<code>function statusChange(e){

  var sp = SpreadsheetApp.getActiveSpreadsheet();
  var ss = sp.getSheetByName('R & A');
  var row = e.range.getRow(); //get row # for edited range
  var col = e.range.getColumn(); //get column # for edited range

  if(col === 15){ //check if column O was updated

    var templateText = sp.getSheetByName("Template for Email").getRange(1,1).getValue();

    var quotaLeft = MailApp.getRemainingDailyQuota();

    if(quotaLeft < 1){
      Browser.msgBox("You have " + quotaLeft + " left and you're trying to send 1 email. Email was not sent.");
    } else{

      var currentEmail = ss.getRange(row, 3).getValue();
      var currentSheetTitle = ss.getRange(row, 11).getValue();
      var currentName = ss.getRange(row, 4).getValue();

      var messageBody = templateText.replace("{name}",currentName).replace("{title}",currentSheetTitle);
      var subjectLine = "Reminder: " + currentSheetTitle + " Status Change";

      MailApp.sendEmail(currentEmail, subjectLine, messageBody);
    } //close else statement
  } //close if statement
}
</code>```

Since all you're trying to do is send an email for the row you've edited, you don't need the for statement you had in the script. You can get the row and column for the range that has been edited and base the rest of the script off of that instead.

Body:
I am using google spreadsheet.

I have Email addresses of participants in C column, and their corresponding Status in O column.( The status will be either, DONE or OPEN or ONGOING or empty).

If O2 value is updated, then I need to send email to address in C2 with a template. The email should send only to C2 if the cell O2 is updated.

I hope you can help me with this.

I tried this script but it sends to all email everytime.

Hope you can help me.

Thanks,

function StatusChange() {

  SpreadsheetApp.getActiveSpreadsheet().getSheetByName("R & A").activate();

  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var lr = ss.getLastRow();

  var templateText = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template for Email").getRange(1,1).getValue();

  var quotaLeft = MailApp.getRemainingDailyQuota();

  if((lr-1) > quotaLeft){
    Browser.msgBox("You have " + quotaLeft + " left and you're trying to send " + (lr-1) + " emails. Emails were not sent.");
  } else {

    for (var i = 2;i<=lr;i++){

      var currentEmail = ss.getRange(i, 3).getValue();
      var currentSheetTitle = ss.getRange(i, 11).getValue();
      var currentName = ss.getRange(i, 4).getValue();

      var messageBody = templateText.replace("{name}",currentName).replace("{title}",currentSheetTitle);
      var subjectLine = "Reminder: " + currentSheetTitle + " Status Change";

    MailApp.sendEmail(currentEmail, subjectLine, messageBody);

    } // close for loop

  } //close else statement

}

If O2 value is updated, then I need to send email to address in C2 with a template. The email should send only to C2 if the cell O2 is updated.

Body:
This can be achieved using an onEdit installable trigger, you'll need to set this up by either going to your triggers or running the below code supplied by Google once.

function createSpreadsheetEditTrigger() {
  var ss = SpreadsheetApp.getActive();
  ScriptApp.newTrigger('statusChange')
      .forSpreadsheet(ss)
      .onEdit()
      .create();
}

By doing this you can check if column O is being updated, then run your if else statements based on that result. I've also cleaned up some of the variables so that you're not doing multiple SpreadsheetApp.getActiveSpreadsheet() calls unnecessarily.

Note: you won't be able to run the below script manually, it'll run automatically when the sheet is edited.

function statusChange(e){

  var sp = SpreadsheetApp.getActiveSpreadsheet();
  var ss = sp.getSheetByName('R & A');
  var row = e.range.getRow(); //get row # for edited range
  var col = e.range.getColumn(); //get column # for edited range

  if(col === 15){ //check if column O was updated

    var templateText = sp.getSheetByName("Template for Email").getRange(1,1).getValue();

    var quotaLeft = MailApp.getRemainingDailyQuota();

    if(quotaLeft < 1){
      Browser.msgBox("You have " + quotaLeft + " left and you're trying to send 1 email. Email was not sent.");
    } else{

      var currentEmail = ss.getRange(row, 3).getValue();
      var currentSheetTitle = ss.getRange(row, 11).getValue();
      var currentName = ss.getRange(row, 4).getValue();

      var messageBody = templateText.replace("{name}",currentName).replace("{title}",currentSheetTitle);
      var subjectLine = "Reminder: " + currentSheetTitle + " Status Change";

      MailApp.sendEmail(currentEmail, subjectLine, messageBody);
    } //close else statement
  } //close if statement
}

Since all you're trying to do is send an email for the row you've edited, you don't need the for statement you had in the script. You can get the row and column for the range that has been edited and base the rest of the script off of that instead.


来源: stackexchange

问:
How do I make Tkinter drawing lines from an x interval and a y NumPy array?
I have two sources of data to be plotted as X and Y coordinates on a continuous Tkinter line. The x data is generated from a constant like say 1.3. So each x value has to be + 1.3 greater than the last - for example 3.9, 5.2, 6.5 and so on. The y values are held in a numpy array. I need to create a line on a canvas according to these two sets of data.

I have a feeling that this is so, so easy and I am missing something really stupid. So, apologies if this is the case.

At the moment I generate the line array using a for loop but it is too slow (I need to do loads of these per second).

```<code>x_start = 3
x_stop = 5
step = 1.3

for n in range(x_start, x_stop):
    x = n * step
    line_array[n * 2] = x
    line_array[n * 2 + 1] = array[n]
</code>```

答:
You can simply call Canvas.create_line(...) with the array of points created from your two sources of data as below:

```<code>from tkinter import *
import numpy.random

root = Tk()

canvas = Canvas(root, bg='white', width=1600, height=800)
canvas.pack(fill=BOTH, expand=1)

y_array = numpy.random.randint(100, 700, 5000) # generate 5000 y values

x_start = 3
x_stop = 5000
step = 1.3

# create the array of points and draw them
line_array = [(n*step, y_array[n]) for n in range(x_start, x_stop)]
canvas.create_line(line_array)

root.mainloop()
</code>```

It takes less than a second to draw the lines in my i7 notebook.

ContentLicense: CC BY-SA 4.0

Body:
I have two sources of data to be plotted as X and Y coordinates on a continuous Tkinter line. The x data is generated from a constant like say 1.3. So each x value has to be + 1.3 greater than the last - for example 3.9, 5.2, 6.5 and so on. The y values are held in a numpy array. I need to create a line on a canvas according to these two sets of data.

I have a feeling that this is so, so easy and I am missing something really stupid. So, apologies if this is the case.

At the moment I generate the line array using a for loop but it is too slow (I need to do loads of these per second).

x_start = 3
x_stop = 5
step = 1.3

for n in range(x_start, x_stop):
    x = n * step
    line_array[n * 2] = x
    line_array[n * 2 + 1] = array[n]

Body:
You can simply call Canvas.create_line(...) with the array of points created from your two sources of data as below:

from tkinter import *
import numpy.random

root = Tk()

canvas = Canvas(root, bg='white', width=1600, height=800)
canvas.pack(fill=BOTH, expand=1)

y_array = numpy.random.randint(100, 700, 5000) # generate 5000 y values

x_start = 3
x_stop = 5000
step = 1.3

# create the array of points and draw them
line_array = [(n*step, y_array[n]) for n in range(x_start, x_stop)]
canvas.create_line(line_array)

root.mainloop()

It takes less than a second to draw the lines in my i7 notebook.


问:
two objects have the same value
Both object is the same when i edit.
show the solution to seprate objects.
i have an object and with v-model i bind it to inputs to update it but when i edit it but don't save changes the object is changed. for not occurring this situation i use a second object(temporary) when editing i use that object but again it changes the first object.</p>

```<code>data(){
   return{
      user:{
        id:'',
        firstname:'',
        lastname: ''
      },
    tuser:{}
     }
  },
 mounted(){
     axios.get('/user')
         .then((response) => {
              this.user = response.data
             })
         .catch(error)
    },
 methods:{
      edit(){
      this.tuser = this.user
      },
 update(){
      axios.patch(`/user/${this.tuser.id}`,this.tuser)
         .then((response)=>{
                 this.user = this.tuser
          })
       .error()
      }
 }
</code>```

答:
```<code>methods:{
  edit(){
  this.tuser = this.user
  },
</code>```

I think you just need to pass a cloned copy of this.user, you can achieve that using lodash/underscore.js methods like clone or cloneDeep. If you don't copy your object they are referencing the same object

Title: two objects have the same value

Body:
Both object is the same when i edit.
show the solution to seprate objects.
i have an object and with v-model i bind it to inputs to update it but when i edit it but don't save changes the object is changed. for not occurring this situation i use a second object(temporary) when editing i use that object but again it changes the first object.

data(){
   return{
      user:{
        id:'',
        firstname:'',
        lastname: ''
      },
    tuser:{}
     }
  },
 mounted(){
     axios.get('/user')
         .then((response) => {
              this.user = response.data
             })
         .catch(error)
    },
 methods:{
      edit(){
      this.tuser = this.user
      },
 update(){
      axios.patch(`/user/${this.tuser.id}`,this.tuser)
         .then((response)=>{
                 this.user = this.tuser
          })
       .error()
      }
 }

Body:
methods:{
  edit(){
  this.tuser = this.user
  },

I think you just need to pass a cloned copy of this.user, you can achieve that using lodash/underscore.js methods like clone or cloneDeep. If you don't copy your object they are referencing the same object


问:
Calling web service using VBA code in Excel 2010
I am trying to write some VBA code in Excel 2010 that would consume a web service. I am unable to find any related resources on the internet. Can someone please tell me how to do this.</p>

答: I don't think the post marked as the answer is right - it links to the Excel 2003 solution, which was based on the MS Office Web Services Toolkit. That solution is no longer valid as the Toolkit is not supported any more. See: MSDN - Consuming Web Services in Excel 2007. The link provides a solution for Excel 2007 which can be transposed to Excel 2010. You will need Visual Studio 2010 with Microsoft Office Developers Tools though. It also means utilising .Net Framework and coding in C# or VB.NET. </p>

ContentLicense: CC BY-SA 3.0


问:
How to do a mean and a max in the same time doing a groupby?
I have the same list of destinations (Italy, Greece, Spain,etc.) included in a list of airline companies (Easyjet, Panam, Ryan Air, etc.).
Each of these destinations has a length.
Depending of the company, the same destination can have a different length so:
1. I want to find the mean of the destinations' length
2. I want to find the 5 longest destinations

As a beginner in pandas, I'm wondering if there is a way to calculate this with a one and only groupby?

Thanks for your help!

答:
df.groupby('Destination')
  .mean()
  .sort_values('Destination Length', ascending=False)
  .head(5)
```


问:
Cakephp 2.0 $this->Auth->login() not working
I'm trying to use the cakephp built in Auth for a user login. I've managed to validate a user registration (which is located on the same view as the login) but not get the login working.

All i get when trying to login is my 'Invalid username or password, try again' error.  I've gone through the blog tutorial but I'm new to cake/php and have only worked on messy projects in 1.3 that sue their own crude authentication.

MarshallsController.php

```<code>class MarshalsController extends AppController {
public $helpers     = array('Html', 'Form');
public $uses        = array("Marshal", "User");
public $components  = array("RequestHandler","Session", "Auth");

public function beforeFilter() {
    parent::beforeFilter();
    $this->Auth->allow('register', 'login');
}

public function index() {
    $this->set('users', $this->User->find('all',
            array(
                'conditions'=>array(
                    'User.marshall_id'=>$Marshall['Marshall']['id']
                )
            )));
}

//Run when Marshal attempts to register for login page
public function register(){
    if ($this->request->is('post')) {
        $this->Marshal->create();
        if ($this->Marshal->save($this->request->data)) {
            //if new marshall has been saved fetch all their data
            $marshal = $this->Marshal->find('first',
                array(
                    'conditions'=>array(
                        "Marshal.email"     => $this->data['Marshal']['email'],
                    )
                )
            );
            if(!empty($marshal)){
                //set marshal session data to track logged in users and their data
                $this->Session->write("Marshal",$marshal);
            }
            $this->Session->setFlash(__('The Marshal has been saved'));
            //redirect user to logged in page
            $this->redirect(array('controller' => 'pages', 'action' => 'home'));
        } else {
            $this->Session->setFlash(__('The Marshal could not be saved. Please, try again.'));
            echo $this->render('login');
            exit();
        }
    }
    else{
        //if Marshal has not attempted to login redirect the back to the login/register page
        echo $this->render('login');
        exit();
    }
}

public function login() {

    //if user has atempted a login
    if ($this->request->is('post')) {
        if ($this->Auth->login()) {
            //If login detials are correct get user data
            $marshal = $this->Marshal->find('first',
                array(
                    'conditions'=>array(
                        "Marshal.email"     => $this->data['Marshal']['email'],
                    )
                )
            );
            if(!empty($marshal)){
                //set marshal session data to track logged in users and their data
                $this->Session->write("Marshal",$marshal);
            }
            //redirect user to the logged in page
            $this->redirect($this->Auth->redirect());
        } else {
            $this->Session->setFlash(__('Invalid username or password, try again'));
            debug($this->Auth->request->data);
        }
</code>```

Marshal model

```<code>class Marshal extends AppModel {

public function beforeSave($options = array()) {
    if (isset($this->data[$this->alias]['password'])) {
        $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
    }
    return true;
}

public $hasMany = array(
    'User' => array(
        'className'     => 'User',
        'foreignKey'    => 'marshal_id',
        'conditions'    => array('User.status' => '1'),
    )
);

public $validate = array(
    'first_name' => array(
        'required' => array(
            'rule' => array('notEmpty'),
            'message' => 'A first name is required'
        )
    ),
    'last_name' => array(
        'required' => array(
            'rule' => array('notempty'),
            'message' => 'A last name is required'
        )
    ),
    'password' => array(
        'required' => array(
            'rule'    => array('minLength', '8'),
            'message' => 'Minimum 8 characters long'
        )
    ),
    'email' => 'email'
);
</code>```

}

login.ctp

```<code><div class="row">
<?php echo $this->Session->flash('auth'); ?>
<div class="sixcol">
    <?php
    echo $this->Form->create('Marshal', array('action' => 'login'));
    echo $this->Form->inputs(array(
        'legend' => __('Login'),
        'email',
        'password'
    ));
    echo $this->Form->end('Login');
    ?>
</div>
<div class="sixcol last">
    <?php
    echo $this->Form->create('Marshal', array('action' => 'register'));
    echo $this->Form->inputs(array(
        'legend' => __('register'),
        'first_name',
        'last_name',
        'email',
        'password'
    ));
    echo $this->Form->end('Register');
    ?>
</div>
</code>```

答:
function login() {

```<code>//if already logged-in, redirect
// if($this->Session->check('email')){
//     $this->redirect(array('action' => ''));
// }

// if we get the post information, try to authenticate
if ($this->request->is('post')) {
    $data = $this->request->data;

    print_r($data); die;
    if ($this->Auth->login()) {
        return $this->redirect($this->Auth->redirectUrl());
    }
    $this->Session->setFlash(__('Your username or password was incorrect.'));
}
}
</code>```

only else codition is true

Body:
I'm trying to use the cakephp built in Auth for a user login. I've managed to validate a user registration (which is located on the same view as the login) but not get the login working.

All i get when trying to login is my 'Invalid username or password, try again' error.  I've gone through the blog tutorial but I'm new to cake/php and have only worked on messy projects in 1.3 that sue their own crude authentication.

MarshallsController.php

class MarshalsController extends AppController {
public $helpers     = array('Html', 'Form');
public $uses        = array("Marshal", "User");
public $components  = array("RequestHandler","Session", "Auth");

public function beforeFilter() {
    parent::beforeFilter();
    $this->Auth->allow('register', 'login');
}

public function index() {
    $this->set('users', $this->User->find('all',
            array(
                'conditions'=>array(
                    'User.marshall_id'=>$Marshall['Marshall']['id']
                )
            )));
}

//Run when Marshal attempts to register for login page
public function register(){
    if ($this->request->is('post')) {
        $this->Marshal->create();
        if ($this->Marshal->save($this->request->data)) {
            //if new marshall has been saved fetch all their data
            $marshal = $this->Marshal->find('first',
                array(
                    'conditions'=>array(
                        "Marshal.email"     => $this->data['Marshal']['email'],
                    )
                )
            );
            if(!empty($marshal)){
                //set marshal session data to track logged in users and their data
                $this->Session->write("Marshal",$marshal);
            }
            $this->Session->setFlash(__('The Marshal has been saved'));
            //redirect user to logged in page
            $this->redirect(array('controller' => 'pages', 'action' => 'home'));
        } else {
            $this->Session->setFlash(__('The Marshal could not be saved. Please, try again.'));
            echo $this->render('login');
            exit();
        }
    }
    else{
        //if Marshal has not attempted to login redirect the back to the login/register page
        echo $this->render('login');
        exit();
    }
}

public function login() {

    //if user has atempted a login
    if ($this->request->is('post')) {
        if ($this->Auth->login()) {
            //If login detials are correct get user data
            $marshal = $this->Marshal->find('first',
                array(
                    'conditions'=>array(
                        "Marshal.email"     => $this->data['Marshal']['email'],
                    )
                )
            );
            if(!empty($marshal)){
                //set marshal session data to track logged in users and their data
                $this->Session->write("Marshal",$marshal);
            }
            //redirect user to the logged in page
            $this->redirect($this->Auth->redirect());
        } else {
            $this->Session->setFlash(__('Invalid username or password, try again'));
            debug($this->Auth->request->data);
        }

Marshal model

class Marshal extends AppModel {

public function beforeSave($options = array()) {
    if (isset($this->data[$this->alias]['password'])) {
        $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
    }
    return true;
}

public $hasMany = array(
    'User' => array(
        'className'     => 'User',
        'foreignKey'    => 'marshal_id',
        'conditions'    => array('User.status' => '1'),
    )
);

public $validate = array(
    'first_name' => array(
        'required' => array(
            'rule' => array('notEmpty'),
            'message' => 'A first name is required'
        )
    ),
    'last_name' => array(
        'required' => array(
            'rule' => array('notempty'),
            'message' => 'A last name is required'
        )
    ),
    'password' => array(
        'required' => array(
            'rule'    => array('minLength', '8'),
            'message' => 'Minimum 8 characters long'
        )
    ),
    'email' => 'email'
);

}

login.ctp

<?php echo $this->Session->flash('auth'); ?>

    <?php
    echo $this->Form->create('Marshal', array('action' => 'login'));
    echo $this->Form->inputs(array(
        'legend' => __('Login'),
        'email',
        'password'
    ));
    echo $this->Form->end('Login');
    ?>

    <?php
    echo $this->Form->create('Marshal', array('action' => 'register'));
    echo $this->Form->inputs(array(
        'legend' => __('register'),
        'first_name',
        'last_name',
        'email',
        'password'
    ));
    echo $this->Form->end('Register');
    ?>

Body:
function login() {

//if already logged-in, redirect
// if($this->Session->check('email')){
//     $this->redirect(array('action' => ''));
// }

// if we get the post information, try to authenticate
if ($this->request->is('post')) {
    $data = $this->request->data;

    print_r($data); die;
    if ($this->Auth->login()) {
        return $this->redirect($this->Auth->redirectUrl());
    }
    $this->Session->setFlash(__('Your username or password was incorrect.'));
}
}

only else codition is true


答:
You are mutating a reference value, it doesn't matter which one you change - they both get updated as they share the same address in memory heap.

So Use ES6 spread to make clone when you are trying to have copy of any reference value.

```<code>this.user = { ...this.tuser }
</code>```

or

```<code>this.tuser = { ...this.user }
</code>```

References : spread_es6

Title: two objects have the same value

Body:
You are mutating a reference value, it doesn't matter which one you change - they both get updated as they share the same address in memory heap.

So Use ES6 spread to make clone when you are trying to have copy of any reference value.

this.user = { ...this.tuser }

or

this.tuser = { ...this.user }

References : spread_es6


问:
Contact form shows confirmation on new page instead in div (ajax)
I'm trying to get that Contact Form to Work:
https://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form
but the confirmation Text opens in a new site instead of the div "messages".

contact.php

```<code>    <form id="contact-form" method="post" action="contactaction.php" role="form" data-toggle="validator">
        <div class="messages"></div>

    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.9/validator.min.js"></script>
    <script src="contact.js"></script>
</code>```

contact.js

```<code>$(function () {

    // init the validator

    $('#contact-form').validator();

    // when the form is submitted
    $('#contact-form').on('submit', function (e) {

        // if the validator does not prevent form submit
        if (!e.isDefaultPrevented()) {
            var url = "contact.php";

            // POST values in the background the the script URL
            $.ajax({
                type: "POST",
                url: url,
                data: $(this).serialize(),
                success: function (data)
                {
                    // data = JSON object that contact.php returns

                    // we recieve the type of the message: success x danger and apply it to the
                    var messageAlert = 'alert-' + data.type;
                    var messageText = data.message;

                    // let's compose Bootstrap alert box HTML
                    var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';

                    // If we have messageAlert and messageText
                    if (messageAlert && messageText) {
                        // inject the alert to .messages div in our form
                        $('#contact-form').find('.messages').html(alertBox);
                        // empty the form
                        $('#contact-form')[0].reset();
                    }
                }
            });
            return false;
        }
    })
});
</code>```

答:
Just use e.preventDefault(); as the first step of the onsubmit function:</p>

```<code>     // when the form is submitted
     $(function () {

        // init the validator
        $('#contact-form').validator();

        // when the form is submitted
        $('#contact-form').on('submit', function (e) {
            e.preventDefault();
            // if the validator does not prevent form submit
            var url = "contact.php";

            // POST values in the background the the script URL
            $.ajax({
                type: "POST",
                url: url,
                data: $(this).serialize(),
                success: function (data)
                {
                    // data = JSON object that contact.php returns

                    // we recieve the type of the message: success x danger and apply it to the
                    var messageAlert = 'alert-' + data.type;
                    var messageText = data.message;

                    // let's compose Bootstrap alert box HTML
                    var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';

                    // If we have messageAlert and messageText
                    if (messageAlert && messageText) {
                        // inject the alert to .messages div in our form
                        $('#contact-form').find('.messages').html(alertBox);
                        // empty the form
                        $('#contact-form')[0].reset();
                    }
                }
            });
            return false;
        })
    });
</code>```

Body:
I'm trying to get that Contact Form to Work:
https://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form
but the confirmation Text opens in a new site instead of the div "messages".

contact.php

    <form id="contact-form" method="post" action="contactaction.php" role="form" data-toggle="validator">

contact.js

$(function () {

    // init the validator

    $('#contact-form').validator();

    // when the form is submitted
    $('#contact-form').on('submit', function (e) {

        // if the validator does not prevent form submit
        if (!e.isDefaultPrevented()) {
            var url = "contact.php";

            // POST values in the background the the script URL
            $.ajax({
                type: "POST",
                url: url,
                data: $(this).serialize(),
                success: function (data)
                {
                    // data = JSON object that contact.php returns

                    // we recieve the type of the message: success x danger and apply it to the
                    var messageAlert = 'alert-' + data.type;
                    var messageText = data.message;

                    // let's compose Bootstrap alert box HTML
                    var alertBox = '
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '
';

                    // If we have messageAlert and messageText
                    if (messageAlert && messageText) {
                        // inject the alert to .messages div in our form
                        $('#contact-form').find('.messages').html(alertBox);
                        // empty the form
                        $('#contact-form')[0].reset();
                    }
                }
            });
            return false;
        }
    })
});

Body:
Just use e.preventDefault(); as the first step of the onsubmit function:

     // when the form is submitted
     $(function () {

        // init the validator
        $('#contact-form').validator();

        // when the form is submitted
        $('#contact-form').on('submit', function (e) {
            e.preventDefault();
            // if the validator does not prevent form submit
            var url = "contact.php";

            // POST values in the background the the script URL
            $.ajax({
                type: "POST",
                url: url,
                data: $(this).serialize(),
                success: function (data)
                {
                    // data = JSON object that contact.php returns

                    // we recieve the type of the message: success x danger and apply it to the
                    var messageAlert = 'alert-' + data.type;
                    var messageText = data.message;

                    // let's compose Bootstrap alert box HTML
                    var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';

                    // If we have messageAlert and messageText
                    if (messageAlert && messageText) {
                        // inject the alert to .messages div in our form
                        $('#contact-form').find('.messages').html(alertBox);
                        // empty the form
                        $('#contact-form')[0].reset();
                    }
                }
            });
            return false;
        })
    });


问:
Typescript: Partial interface with keys supplied by array
I'm programming against a web api that, for some of the fields, only returns them if you specify them in the query.

```<code>{a:"hello", b:"world", c:"of goo", d:"i am always present"}
</code>```

and I called

```<code>api.getResponse(["a","b"])
</code>```

I would get

```<code>{a:"hello", b:"world", d:"i am always present"}
</code>```

in response.

How do i express that in the type language of typescript?

答:
In Advanced typesscript we can use Partial, Pick, Readonly.

As in your case, keyof , Partial can be used. The same can be implemented in using Pick too: docs

```<code>interface IResponse {
  a: string;
  b: string;
  c: string;
  d: string;
}

const getResponse = (responseKeys: Array<keyof IResponse>): Partial<IResponse> => {
  const responseWithFilteredKeys: Partial<IResponse> = {};
  const response: IResponse = {
    a: 'a',
    b: 'a',
    c: 'a',
    d: 'a',
  };
  responseKeys.forEach((key: keyof IResponse) => {
    responseWithFilteredKeys[key] = response[key];
  });
  return responseWithFilteredKeys;
};

const filterdUserResponse: Partial<IResponse> = getResponse(['a', 'b']);
</code>```

Body:
I'm programming against a web api that, for some of the fields, only returns them if you specify them in the query.

{a:"hello", b:"world", c:"of goo", d:"i am always present"}

and I called

api.getResponse(["a","b"])

I would get

{a:"hello", b:"world", d:"i am always present"}

in response.

How do i express that in the type language of typescript?

Body:
In Advanced typesscript we can use Partial, Pick, Readonly.

As in your case, keyof , Partial can be used. The same can be implemented in using Pick too: docs

interface IResponse {
  a: string;
  b: string;
  c: string;
  d: string;
}

const getResponse = (responseKeys: Array<keyof IResponse>): Partial<IResponse> => {
  const responseWithFilteredKeys: Partial<IResponse> = {};
  const response: IResponse = {
    a: 'a',
    b: 'a',
    c: 'a',
    d: 'a',
  };
  responseKeys.forEach((key: keyof IResponse) => {
    responseWithFilteredKeys[key] = response[key];
  });
  return responseWithFilteredKeys;
};

const filterdUserResponse: Partial<IResponse> = getResponse(['a', 'b']);


问:
Regex - Every spaces without back on line
I would like to accept any spaces with [\s] between to words, but not returns on the line -> [^\n].

I'm using

```<code>([\w\-]+)([\s[^\n]])([\w\-]+)
</code>```

but i doesn't work.

How can I do that?

答:
A character class within another character class will not work. It would be better to specify what you want to match. So [ \t]+ which means one or more spaces or tabs.

Two more points:

1. - does not need to be escaped in a character class if it is the first or the last character, so [\w-] or [-\w] will work fine.

2. Unless you want to use the white space characters between the words you do not need to use brackets.

In summary, the following should work fine:

([-\w]+)[ \t]+([-\w]+)

Body:
I would like to accept any spaces with [\s] between to words, but not returns on the line -> [^\n].

I'm using

([\w\-]+)([\s[^\n]])([\w\-]+)

but i doesn't work.

How can I do that?


问:
How to pass async data retrieved in splashscreen to App.js?
This article explains how to use splash screen to load data before initial screen. Basically it defines:

```<code>const InitialNavigator = createSwitchNavigator({
  Splash: SplashScreen,
  App: AppNavigator
});

export default createAppContainer(InitialNavigator);
</code>```

Here is the AppNavigator:

```<code>const AppNavigator = createBottomTabNavigator(
  {
    Home: {
      screen: HomeNavigator
    },
    HighScores: {
      screen: HighScoresScreen
    },
    {
     initialRouteName: initialScreen,
   }
  }
);
</code>```

The initialScreen will be based on the data loaded during initialization.

Here is component SplashScreen which call 2 async functions to load variable result and user:

```<code>class SplashScreen extends React.Component {
  performTimeConsumingTask = async() => {
    var result, user;
    try {
    result = await helper.getJwtToken();
    console.log("App.js token result is : ", result);
    if (result) {
      console.log("App.js result is true. Retrieve user");
      user = await helper._getUser(result.password, result.username);
      console.log("User is : ", user.name);

    } else {
      console.log("App.js result is false");

    };
    console.log("I am out of App.js async without error");
  } catch (err) {
    console.log("Error in retrieving token : ", err);
    return "";

  };
  }

  async componentDidMount() {
    // Preload data from an external API
    // Preload data using AsyncStorage
    const data = await this.performTimeConsumingTask();

    if (data !== null) {
      this.props.navigation.navigate('App');
    }
  }
.......
</code>```

But how can I pass the value of result and user to App?

答:
Try to pass params:

```<code>class SplashScreen extends React.Component {
  performTimeConsumingTask = async() => {
    var result, user;
    try {
    result = await helper.getJwtToken();
    console.log("App.js token result is : ", result);
    if (result) {
      console.log("App.js result is true. Retrieve user");
      user = await helper._getUser(result.password, result.username);
      console.log("User is : ", user.name);
      return {result, user};
    } else {
      console.log("App.js result is false");

    };
    console.log("I am out of App.js async without error");
  } catch (err) {
    console.log("Error in retrieving token : ", err);
    return {result: null, user: null};

  };
  }

  async componentDidMount() {
    // Preload data from an external API
    // Preload data using AsyncStorage
    const data = await this.performTimeConsumingTask();

    if (data !== null) {
      this.props.navigation.navigate('App', {result, user});
    }
  }
</code>```

and inside App you can use it in this way:

```<code>const { result, user } = this.props.navigation.state.params;
</code>```

Body:
This article explains how to use splash screen to load data before initial screen. Basically it defines:

const InitialNavigator = createSwitchNavigator({
  Splash: SplashScreen,
  App: AppNavigator
});

export default createAppContainer(InitialNavigator);

Here is the AppNavigator:

const AppNavigator = createBottomTabNavigator(
  {
    Home: {
      screen: HomeNavigator
    },
    HighScores: {
      screen: HighScoresScreen
    },
    {
     initialRouteName: initialScreen,
   }
  }
);

The initialScreen will be based on the data loaded during initialization.

Here is component SplashScreen which call 2 async functions to load variable result and user:

class SplashScreen extends React.Component {
  performTimeConsumingTask = async() => {
    var result, user;
    try {
    result = await helper.getJwtToken();
    console.log("App.js token result is : ", result);
    if (result) {
      console.log("App.js result is true. Retrieve user");
      user = await helper._getUser(result.password, result.username);
      console.log("User is : ", user.name);

    } else {
      console.log("App.js result is false");

    };
    console.log("I am out of App.js async without error");
  } catch (err) {
    console.log("Error in retrieving token : ", err);
    return "";

  };
  }

  async componentDidMount() {
    // Preload data from an external API
    // Preload data using AsyncStorage
    const data = await this.performTimeConsumingTask();

    if (data !== null) {
      this.props.navigation.navigate('App');
    }
  }
.......

But how can I pass the value of result and user to App?

Body:
Try to pass params:

class SplashScreen extends React.Component {
  performTimeConsumingTask = async() => {
    var result, user;
    try {
    result = await helper.getJwtToken();
    console.log("App.js token result is : ", result);
    if (result) {
      console.log("App.js result is true. Retrieve user");
      user = await helper._getUser(result.password, result.username);
      console.log("User is : ", user.name);
      return {result, user};
    } else {
      console.log("App.js result is false");

    };
    console.log("I am out of App.js async without error");
  } catch (err) {
    console.log("Error in retrieving token : ", err);
    return {result: null, user: null};

  };
  }

  async componentDidMount() {
    // Preload data from an external API
    // Preload data using AsyncStorage
    const data = await this.performTimeConsumingTask();

    if (data !== null) {
      this.props.navigation.navigate('App', {result, user});
    }
  }

and inside App you can use it in this way:

const { result, user } = this.props.navigation.state.params;


问:
Overflowing data values when input
I am facing problem as the error message show that data limit is exceeding. </p>

<p>i have tried changing the format of the datatime into many such and finally i landed onto this. </p>

```<code><div class="form-group-inner">
   <div class="row">
       <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12">
          <label class="login2 pull-right pull-right-pro">Start Time</label>
       </div>
          <div class="col-lg-9 col-md-9 col-sm-9 col-xs-12">
             <input type="time" id="Timefrom" name="Timefrom"
              min="6:00" max="20:00">
          </div>
   </div>
</div>

<div class="form-group-inner">
   <div class="row">
     <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12">
         <label class="login2 pull-right pull-right-pro">Startdate</label>
     </div>
     <div class="col-lg-9 col-md-9 col-sm-9 col-xs-12">
         <input type="date" id="Startdate" name="Startdate"
          value="2019-06-29" min="2019-01-01" max="2019-12-31">
     </div>
     </div>
   </div>
</div>

</code>```

```<code>if (!String.IsNullOrEmpty(fc["Timefrom"]) && !String.IsNullOrEmpty(fc["Startdate"]))
   {
     string[] rdate = fc["Startdate"].Split('-');
     model.Timefrom = Convert.ToDateTime(rdate[2] + "-" + rdate[1] + "-" + rdate[0] +  " " + fc["Timefrom"])
   }
</code>```

答:
C# does not support datetime format "dd-mm-yy hh:mm". Please rewrite your code as follow</p>

```<code>if (!String.IsNullOrEmpty(fc["Timefrom"]) && !String.IsNullOrEmpty(fc["Startdate"]))
   {
     string[] rdate = fc["Startdate"].Split('-');
     model.Timefrom = Convert.ToDateTime(rdate[0] + "-" + rdate[1] + "-" + rdate[2] +  " " + fc["Timefrom"])
   }
</code>```

Title: Overflowing data values when input

Body:
I am facing problem as the error message show that data limit is exceeding.

i have tried changing the format of the datatime into many such and finally i landed onto this.

          Start Time

             <input type="time" id="Timefrom" name="Timefrom"
              min="6:00" max="20:00">

         Startdate

         <input type="date" id="Startdate" name="Startdate"
          value="2019-06-29" min="2019-01-01" max="2019-12-31">

if (!String.IsNullOrEmpty(fc["Timefrom"]) && !String.IsNullOrEmpty(fc["Startdate"]))
   {
     string[] rdate = fc["Startdate"].Split('-');
     model.Timefrom = Convert.ToDateTime(rdate[2] + "-" + rdate[1] + "-" + rdate[0] +  " " + fc["Timefrom"])
   }

Body:
C# does not support datetime format "dd-mm-yy hh:mm". Please rewrite your code as follow

if (!String.IsNullOrEmpty(fc["Timefrom"]) && !String.IsNullOrEmpty(fc["Startdate"]))
   {
     string[] rdate = fc["Startdate"].Split('-');
     model.Timefrom = Convert.ToDateTime(rdate[0] + "-" + rdate[1] + "-" + rdate[2] +  " " + fc["Timefrom"])
   }


问:
How to fix FAB inside activity?
I'm trying to add a BottomAppBar to my activity but there's a error : " java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mathmech.cards/com.mathmech.cards.activity.MainActivity}: android.view.InflateException: Binary XML file line #24: Binary XML file line #24: Error inflating class com.google.android.material.bottomappbar.BottomAppBar"

I tried to follow guides on web but nothing helped

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".activity.MainActivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/listView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </ListView>

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.google.android.material.bottomappbar.BottomAppBar
            android:id="@+id/bottom_app_bar"
            app:fabAlignmentMode="center"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:backgroundTint="@color/colorPrimary"
            android:gravity="bottom" />

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/fab"
            app:layout_anchor="@id/bottom_app_bar"
            android:layout_width="wrap_content"
            android:src="@drawable/ic_add_black_24dp"
            android:layout_height="wrap_content" />

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

```

<p>EDIT: added styles.xml</p>

<pre class="lang-xml prettyprint-override"><code><resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>
</code>```

答:
Try with this style in your Bottom App Bar XML.</p>

```<code>style=”@style/Widget.MaterialComponents.BottomAppBar”
</code>```

Title: How to fix FAB inside activity?

Body:
I'm trying to add a BottomAppBar to my activity but there's a error : " java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mathmech.cards/com.mathmech.cards.activity.MainActivity}: android.view.InflateException: Binary XML file line #24: Binary XML file line #24: Error inflating class com.google.android.material.bottomappbar.BottomAppBar"

I tried to follow guides on web but nothing helped

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".activity.MainActivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/listView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </ListView>

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.google.android.material.bottomappbar.BottomAppBar
            android:id="@+id/bottom_app_bar"
            app:fabAlignmentMode="center"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:backgroundTint="@color/colorPrimary"
            android:gravity="bottom" />

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/fab"
            app:layout_anchor="@id/bottom_app_bar"
            android:layout_width="wrap_content"
            android:src="@drawable/ic_add_black_24dp"
            android:layout_height="wrap_content" />

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

EDIT: added styles.xml

<resources>

</resources>

Body:
Try with this style in your Bottom App Bar XML.

style=”@style/Widget.MaterialComponents.BottomAppBar”


问:
Way to use bisect module for sets in python
I was looking for something similar to lower_bound() function for sets in
python, as we have in C++.

Task is to have a ds, which inserts element in sorted manner, storing only single instance of each distinct value, and returns the left neighbor of a given value, both operations in O(logn) worst time in python.

python: something similar to bisect module for lists, with efficient insertion may work.

答:
sets are unordered, and the standard lib does not offer tree structures.

Maybe you could look at sorted containers (3rd party lib): http://www.grantjenks.com/docs/sortedcontainers/ it might offer a good approach to your problem.


问:
What are the differences between LDAP and Active Directory authentication?
I have tried to search without success.
(I do know difference between LDAP and Active Directory. Also read this What are the differences between LDAP and Active Directory?)

According to my understanding, LDAP authenticates (binds) with DN (distinguish name) and password.
E.g. CN=bob, OU=Users,DC=test,DC=com

Active Directory authenticates with a short user name or full domain user name and password.
E.g. bob or bob@test.com

Therefore, LDAP does not allow to users with the same CN in the same tree (OU) but it allows the same CN in a different OU.
Active Directory does not allow the same user name in the same domain, even the user object located in different tree of Active Directory.
Active Directory allows the same user name in different domains.

Other differences?

答:
I had to deal with a situation that was like "AD vs LDAP", my clients have MS active directory servers but also others which were called ldap- or corporate directory-servers, which turned out to be NetIQ eDirectory servers (previously from Novell).
My task was to implement authentication first with 'CD', than later AD.

Both groups of servers do speak the LDAP-protocol, but need to be talked to differently, e.g. as mentioned in the question username is either bob@domain (AD) or DN (CD).
Also, when searching users, in AD you look for the field "sAMAccountName" and searchBase derived from your domain, e.g. "DC=test,DC=com" while the other one wants field "uid" and as searchBase the empty-string = "".

Here's a nice page summarizing how to find out which LDAP-implementation is on the other side:
https://ldapwiki.com/wiki/Determine LDAP Server Vendor


问:
How to calculate difference between two dates in months in MySQL
I have two columns in a MySQL table:

DateOfService (datetime)

BirthDate (date)

I want to run a MySQL query that will provide date difference between these two fields in months.

How can I do this in a MySQL select query?

Thanks.

答:
This could work:</p>

```<code>SELECT 12 * (YEAR(DateOfService)
              - YEAR(BirthDate))
       + (MONTH(DateOfService)
           - MONTH(BirthDate)) AS months
FROM table
</code>```

Body:
This could work:

SELECT 12 * (YEAR(DateOfService)
              - YEAR(BirthDate))
       + (MONTH(DateOfService)
           - MONTH(BirthDate)) AS months
FROM table


问:
acquire a semaphore for the esp32 antenna (bluetooth/wifi dualmode)
I am trying to build a esp32 application, where I have bluetooth and wifi enabled at the same time.

Bluetooth is used with the a2dp profile, where the esp is a sink. After receiving the data, it should be published over a UDP socket as a broadcast to the network.

The problem is the antenna. Both bt and wifi are sharing it. The a2dp stream seems to permanently acquiring the antenna and releasing it very rarely (~2 packages/min, I have ~3000 packages/min).

So my question: Is there some kind of semaphore, which can be acquired to have the full control over the antenna? So my socket would be able to send the data to the network?

I am using my esp32 with freeRTOS. The freeRTOS lib is written in C, but I am trying to wrap everything in C++. Still I think this problem is related to a C lib so I tag it with C.

I am open for any suggestions how to build that. Thanks in advance.

UPDATE:

I am using release/v3.3 from the official esp-idf repo.

I have: CONFIG_SW_COEXIST_ENABLE=y and CONFIG_SW_COEXIST_PREFERENCE_WIFI=y

I can't find CONFIG_ESP32_WIFI_SW_COEXIST_ENABLE in my config.

The mentioned configuration doesn't work.

I tried reading the post, but can't find any "scan_window" or "scan_interval" in my lib. It was written that it is somewhere in the gap_api but can't find it.

Here is my code + config: https://github.com/Dimfred/esp32_bt_streamer

The socket client task, which should broadcast the a2dp_msg, is started here:
https://github.com/Dimfred/esp32_bt_streamer/blob/master/main/app/event_handler.cpp#L22

All events popped from station/access point/bluetooth/a2dp are all caught in event_handler.hpp/cpp

答:
As you saw, Bluetooth has higher priority on WIFI.

Have a look at CONFIG_SW_COEXIST_ENABLE and make sure it is enabled. You also need to configure CONFIG_SW_COEXIST_PREFERENCE to WIFI. Please see the page for additional flags that you could update depending on your application.

If you want to leave the hardware responsible for handling the co-existing devices (BL and WIFI), you can disable CONFIG_SW_COEXIST_ENABLE and reduce the scan window and increase the scan interval of the BL to leave time for WIFI to get access to the antenna. See this post for more details.

To answer your original question about a possible semaphore/mutex. I doubt there is one accessible for you to use and I would leave the API (software) handling the co-existing modules accessing the antenna. But you can always checkout what the code is doing once CONFIG_SW_COEXIST_ENABLE is set (the flag is renamed to CONFIG_ESP32_WIFI_SW_COEXIST_ENABLE). See https://github.com/espressif/esp-idf/blob/81ca1c01395f604972fbf141cfbe49764a746023/components/esp_wifi/src/phy_init.c


问:
How to convert Xmla file to Xml format
I am working on ER diagram for a tabular model(SSAS), so converted my model to XMLA file, but my ER diagram tool is accepting only xml format files. So, I need info how to convert my xmla file to xml.</p>

答:
XMLA files will be of the format JSON. You can easily convert XMLA files into XML files using python.

```<code>import json
from json2xml import json2xml
with open('XMLA.xmla') as xmlafile:
    data = json.load(xmlafile)
print(json2xml.Json2xml(data).to_xml())
</code>```

Title: How to convert Xmla file to Xml format

Body:
XMLA files will be of the format JSON. You can easily convert XMLA files into XML files using python.

import json
from json2xml import json2xml
with open('XMLA.xmla') as xmlafile:
    data = json.load(xmlafile)
print(json2xml.Json2xml(data).to_xml())


问:
Up and down arrow inserting unwanted character in tkinter.Entry widget
The following code produces an app with a single Entry widget. When run on MacOS using Python 3.7.3 from Homebrew, pressing the up or down arrow while inside the entry box causes a character 0xF701 to be inserted:

```<code>import tkinter as tk

root = tk.Tk()
app = tk.Frame(master=root)
app.pack()

entry = tk.Entry(app)
entry.pack()

app.mainloop()
</code>```

This doesn't happen with Anaconda Python and I haven't been able to find anyone else having this issue.

By binding print to the up and down events I've been able to see that the character associated with these events is indeed 0xF700 and 0xF701.

```<code>entry.bind('<Down>', print)
entry.bind('<Up>', print)
</code>```

Output after pressing up and down:

```<code><KeyPress event state=Mod3|Mod4 keysym=Up keycode=8320768 char='\uf700' delta=8320768 x=-5 y=-50>
<KeyPress event state=Mod3|Mod4 keysym=Down keycode=8255233 char='\uf701' delta=8255233 x=-5 y=-50>
</code>```

With the Anaconda Python version the output is slightly different:

```<code><KeyPress event state=Mod3|Mod4 keysym=Up keycode=8320768 char='\uf700' x=-5 y=-50>
<KeyPress event state=Mod3|Mod4 keysym=Down keycode=8255233 char='\uf701' x=-5 y=-50>
</code>```

Does anyone know of a simple solution to this problem?

答:
The release why you are getting those unknown characters in an Entry widget is because for some reason char codes of "Up" (\uf700) and "Down" (\uf701) arrows prints  when run from homebrew python but not with anaconda python not sure why is that.

You can try and see yourself by running this code with either of them.

```<code>root = Tk()
E = Entry(root)
E.bind('<Key>', lambda e: print(e.char))
E.pack()
root.mainloop()
</code>```

The solution I come up with is to overwrite the main <Key> bind of Entry widget to ignore  "Up" and "Down" arrows.

```<code>import tkinter as tk

class Entry(tk.Entry):
    def __init__(self, master=None, cnf={}, **kw):
        super(Entry, self).__init__(master=master, cnf=cnf, **kw)
        self.bind_class('Entry', '<Key>', self.add_char)

    def add_char(self, evt):
        if evt.char != '\uf701' and evt.char != '\uf700':
            self.insert('insert', evt.char)
            self.xview_moveto(1)

if __name__ == "__main__":
    root = tk.Tk()

    E = Entry(root)
    E.pack()

    root.mainloop()
</code>```

Body:
The following code produces an app with a single Entry widget. When run on MacOS using Python 3.7.3 from Homebrew, pressing the up or down arrow while inside the entry box causes a character 0xF701 to be inserted:

import tkinter as tk

root = tk.Tk()
app = tk.Frame(master=root)
app.pack()

entry = tk.Entry(app)
entry.pack()

app.mainloop()

This doesn't happen with Anaconda Python and I haven't been able to find anyone else having this issue.

By binding print to the up and down events I've been able to see that the character associated with these events is indeed 0xF700 and 0xF701.

entry.bind('<Down>', print)
entry.bind('<Up>', print)

Output after pressing up and down:

<KeyPress event state=Mod3|Mod4 keysym=Up keycode=8320768 char='\uf700' delta=8320768 x=-5 y=-50>
<KeyPress event state=Mod3|Mod4 keysym=Down keycode=8255233 char='\uf701' delta=8255233 x=-5 y=-50>

With the Anaconda Python version the output is slightly different:

<KeyPress event state=Mod3|Mod4 keysym=Up keycode=8320768 char='\uf700' x=-5 y=-50>
<KeyPress event state=Mod3|Mod4 keysym=Down keycode=8255233 char='\uf701' x=-5 y=-50>

Does anyone know of a simple solution to this problem?

Body:
The release why you are getting those unknown characters in an Entry widget is because for some reason char codes of "Up" (\uf700) and "Down" (\uf701) arrows prints  when run from homebrew python but not with anaconda python not sure why is that.

You can try and see yourself by running this code with either of them.

root = Tk()
E = Entry(root)
E.bind('<Key>', lambda e: print(e.char))
E.pack()
root.mainloop()

The solution I come up with is to overwrite the main <Key> bind of Entry widget to ignore  "Up" and "Down" arrows.

import tkinter as tk

class Entry(tk.Entry):
    def __init__(self, master=None, cnf={}, **kw):
        super(Entry, self).__init__(master=master, cnf=cnf, **kw)
        self.bind_class('Entry', '<Key>', self.add_char)

    def add_char(self, evt):
        if evt.char != '\uf701' and evt.char != '\uf700':
            self.insert('insert', evt.char)
            self.xview_moveto(1)

if __name__ == "__main__":
    root = tk.Tk()

    E = Entry(root)
    E.pack()

    root.mainloop()


问:
Powershell Script that takes username and checks security groups
I want to create a powershell script that checks a users profile which security groups the user belongs to inside the active directory. Then I want to write it to a file.
I'm having trouble solving this problem.

Example of the expected output.

User1

Security Groups

Domain users
Domain admins...

User2

Security Groups

Domain users
Enterprise admins

```<code>New-Item "$home\Desktop\GroupsMembers-list $(get-date -f dd-MM-yyyy).txt"

$users = @("User1", "User2", "User3", "User4")

foreach ($user in $users){
Get-ADPrincipalGroupMembership $user | sort name | select name | Out-File "$home\Desktop\GroupsMembers-list $(get-date -f dd-MM-yyyy).txt"
}
</code>```

答:
I imagine you could get a bit more creative with it but this could definitely work for you:

```<code>$users = @("user1","user2")

foreach ($user in $users){

    $groups = Get-ADPrincipalGroupMembership $user | Where-Object {$_.GroupCategory -eq "Security"} | Sort-Object Name | Select-Object -ExpandProperty Name

    Add-Content -Path C:\path\to\file.txt -Value @"

$user
Security Groups
----------------------------
"@

    foreach ($group in $groups){
        Add-Content -Path C:\path\to\file.txt -Value $group
    }
}
</code>```

This is what the output looks like:

```<code>user1
Security Groups
----------------------------
Administrators
Domain Admins

user2
Security Groups
----------------------------
Administrators
Domain Admins
</code>```

Body:
I want to create a powershell script that checks a users profile which security groups the user belongs to inside the active directory. Then I want to write it to a file.
I'm having trouble solving this problem.

Example of the expected output.

User1

Security Groups

Domain users
Domain admins...

User2

Security Groups

Domain users
Enterprise admins

New-Item "$home\Desktop\GroupsMembers-list $(get-date -f dd-MM-yyyy).txt"

$users = @("User1", "User2", "User3", "User4")

foreach ($user in $users){
Get-ADPrincipalGroupMembership $user | sort name | select name | Out-File "$home\Desktop\GroupsMembers-list $(get-date -f dd-MM-yyyy).txt"
}

Body:
I imagine you could get a bit more creative with it but this could definitely work for you:

$users = @("user1","user2")

foreach ($user in $users){

    $groups = Get-ADPrincipalGroupMembership $user | Where-Object {$_.GroupCategory -eq "Security"} | Sort-Object Name | Select-Object -ExpandProperty Name

    Add-Content -Path C:\path\to\file.txt -Value @"

$user
Security Groups
----------------------------
"@

    foreach ($group in $groups){
        Add-Content -Path C:\path\to\file.txt -Value $group
    }
}

This is what the output looks like:

user1
Security Groups
----------------------------
Administrators
Domain Admins

user2
Security Groups
----------------------------
Administrators
Domain Admins


问:
Embedded dll resources
Is there a clean way of accessing embedded resources (css/js/images etc) inside a dll.

For example, from an aspx page, can something similar to the below be used?

答:
Create a Resource Provider Aspx Page witch will check for a resource name in query string. then retrieves resource from dll and binary writes the resource in output.

then call it like this :

```<code><script type="text/javascript"
    src="ResourceProvider.aspx?name=My.Dll.Namespace.File.js"></script>
</code>```

Title: Embedded dll resources

Body:
Create a Resource Provider Aspx Page witch will check for a resource name in query string. then retrieves resource from dll and binary writes the resource in output.

then call it like this :

<script type="text/javascript"
    src="ResourceProvider.aspx?name=My.Dll.Namespace.File.js"></script>


问:
Kendo listview with many edit template
I use a kendo list view to show my records.

According to a field value, I would like use a different edit template on a field:

if my field value type is a image, i would like show a kendo upload

if my field value type is a text, i would like show a kendo editor

Is it possible ?
Do you have a sample ? a idea ?

Thanks for your help

答:
As you can see in the template documentation, templates can have JavaScript code in them, including if/else blocks:

```<code><script type="text/x-kendo-template" id="myTemplate">
    #if(isAdmin){#
        <li>#: name # is Admin</li>
    #}else{#
        <li>#: name # is User</li>
    #}#
</script>
</code>```

Just check your type in an if block and use whatever controls you need for that type.

Title: Kendo listview with many edit template

Body:
As you can see in the template documentation, templates can have JavaScript code in them, including if/else blocks:

<script type="text/x-kendo-template" id="myTemplate">
    #if(isAdmin){#
        <li>#: name # is Admin</li>
    #}else{#
        <li>#: name # is User</li>
    #}#
</script>

Just check your type in an if block and use whatever controls you need for that type.


问:
Match text in another dataframe and fill missing columns with recognized entity
I want to fill missing Nan in a dataframe with recognized keywords from another dataframe.

```<code>    import pandas as pd
import numpy as np
df1 = pd.DataFrame({'models': ['A3', '520', 'clio3', 'C3']})
df2 = pd.DataFrame({'description': ['I am selling a Citroen C3', 'I sell my Audi A3'], 'model': [np.nan, np.nan]})
</code>```

Update:
this case

```<code>df2 = pd.DataFrame({'description': ['I am selling a BMW 520 with good condition', 'I sell my Audi very good', 'clio3 for sale'], 'model': [np.nan,'A3', np.nan]})
</code>```

should not replace 'A3'.

Expected result

答:
Solution if need avoid extract values in substrings with word boundaries:

Use Series.str.extract with regex and words boundaries with joined values by | for regex OR:

```<code>pat = '|'.join(r"\b{}\b".format(x) for x in df1['models'])
df2['model'] = df2['description'].str.extract('('+ pat + ')', expand=False)
print (df2)

                 description model
0  I am selling a Citroen C3    C3
1          I sell my Audi A3    A3
</code>```

Difference:

```<code>df2 = pd.DataFrame({'description': ['I am selling a Citroen C3',
                                    'I sell my Audi A3',
                                    'I sell my Audi A31']})

pat = '|'.join(r"\b{}\b".format(x) for x in df1['models'])
df2['model1'] = df2['description'].str.extract('('+ pat + ')', expand=False)
</code>```

Solution with no word bounaries should return wrong matched values:

```<code>pat = '|'.join(df1['models'])
df2['model2'] = df2['description'].str.extract('('+ pat + ')', expand=False)
print (df2)

                 description model1 model2
0  I am selling a Citroen C3     C3     C3
1          I sell my Audi A3     A3     A3
2         I sell my Audi A31    NaN     A3
</code>```

Body:
I want to fill missing Nan in a dataframe with recognized keywords from another dataframe.

    import pandas as pd
import numpy as np
df1 = pd.DataFrame({'models': ['A3', '520', 'clio3', 'C3']})
df2 = pd.DataFrame({'description': ['I am selling a Citroen C3', 'I sell my Audi A3'], 'model': [np.nan, np.nan]})

Update:
this case

df2 = pd.DataFrame({'description': ['I am selling a BMW 520 with good condition', 'I sell my Audi very good', 'clio3 for sale'], 'model': [np.nan,'A3', np.nan]})

should not replace 'A3'.

Expected result

Body:
Solution if need avoid extract values in substrings with word boundaries:

Use Series.str.extract with regex and words boundaries with joined values by | for regex OR:

pat = '|'.join(r"\b{}\b".format(x) for x in df1['models'])
df2['model'] = df2['description'].str.extract('('+ pat + ')', expand=False)
print (df2)

                 description model
0  I am selling a Citroen C3    C3
1          I sell my Audi A3    A3

Difference:

df2 = pd.DataFrame({'description': ['I am selling a Citroen C3',
                                    'I sell my Audi A3',
                                    'I sell my Audi A31']})

pat = '|'.join(r"\b{}\b".format(x) for x in df1['models'])
df2['model1'] = df2['description'].str.extract('('+ pat + ')', expand=False)

Solution with no word bounaries should return wrong matched values:

pat = '|'.join(df1['models'])
df2['model2'] = df2['description'].str.extract('('+ pat + ')', expand=False)
print (df2)

                 description model1 model2
0  I am selling a Citroen C3     C3     C3
1          I sell my Audi A3     A3     A3
2         I sell my Audi A31    NaN     A3


问:
Deprecated methods in rxjs v6
I try to use combineLatest:

```<code>import { combineLatest } from 'rxjs/Observable';
</code>```

but I get the warning

```<code>combineLatest is deprecated: Deprecated in favor of static combineLatest.
</code>```

If I follow the solution provided in the RxJS v5.x to v6 Update Guide as it is stated here and I write

```<code>import { combineLatest } from 'rxjs';
</code>```

then I get the tslint message:

```<code>This import is blacklisted, import a submodule instead
</code>```

which seems a bit a snake biting its own tail...

If I use

```<code>import { combineLatest } from 'rxjs/internal/observable/combineLatest';
</code>```

then it works without warning messages, but as far as I know, it's not recommended to import internal packages (correct me if I'm wrong).

Disabling tslint messages doesn't seem acceptable to me.

Example:

```<code>this.Subscription = combineLatest([a,b])
    .pipe(
      map( (...) )
    ).subscribe( (...) );
</code>```

Which is the appropriate solution? Thanks.

答:
Try using import { combineLatest } from 'rxjs/index'; to avoid deprecated library or  blacklisted lint.

See this: https://rxjs-dev.firebaseapp.com/api/index/function/combineLatest

Title: Deprecated methods in rxjs v6

Body:
I try to use combineLatest:

import { combineLatest } from 'rxjs/Observable';

but I get the warning

combineLatest is deprecated: Deprecated in favor of static combineLatest.

If I follow the solution provided in the RxJS v5.x to v6 Update Guide as it is stated here and I write

import { combineLatest } from 'rxjs';

then I get the tslint message:

This import is blacklisted, import a submodule instead

which seems a bit a snake biting its own tail...

If I use

import { combineLatest } from 'rxjs/internal/observable/combineLatest';

then it works without warning messages, but as far as I know, it's not recommended to import internal packages (correct me if I'm wrong).

Disabling tslint messages doesn't seem acceptable to me.

Example:

this.Subscription = combineLatest([a,b])
    .pipe(
      map( (...) )
    ).subscribe( (...) );

Which is the appropriate solution? Thanks.


问:
newline from user input without pressing enter
First of all, I should mention that I found several closely related questions. Eg here and here. However, neither do I want to use printf nor do I want to use \n (because I know already that it does not work).

Is it possible for the user to enter a newline, probably an escape sequence, without hitting enter?

As an example:

```<code>#include <iostream>
#include <string>

int main () {
    std::string a,b;
    std::cin >> a;
    std::cin >> b;
    std::cout << a << "\n" << b;
}
</code>```

Is it possible for a user to provide a single line of input

```<code>hello ??? world
</code>```

such that the above prints

```<code>hello
world
</code>```

?

答:
(I assume that you do not want spaces to delimit strings. For example,

```<code>Foo bar ??? baz qux
</code>```

should be two lines.)

It is not possible that you configure the streams so that ??? is automatically converted to a newline character. For the user to input a newline character, they have to input a newline character, not anything else.

You have to parse it yourself.
Here's an example parser that treats ??? as delimiter:

```<code>void read_string(std::istream& is, std::string& dest)
{
  std::string str = "";
  for (char c; is.get(c);) {
    switch (c) {
    case '?':
      if (is.get(c) && c == '?') {
        if (is.get(c) && c == '?') {
          dest = str;
          return;
        } else {
          str += "??";
        }
      } else {
        str += "?";
      }
    default:
      str += c;
    }
  }
}
</code>```

For example, the input

```<code>? is still one question mark????? is still two question marks???
</code>```

is parsed as two lines:

```<code>? is still one question mark
?? is still two question marks
</code>```

live demo

Body:
First of all, I should mention that I found several closely related questions. Eg here and here. However, neither do I want to use printf nor do I want to use \n (because I know already that it does not work).

Is it possible for the user to enter a newline, probably an escape sequence, without hitting enter?

As an example:

#include <iostream>
#include <string>

int main () {
    std::string a,b;
    std::cin >> a;
    std::cin >> b;
    std::cout << a << "\n" << b;
}

Is it possible for a user to provide a single line of input

hello ??? world

such that the above prints

hello
world

?

Body:
(I assume that you do not want spaces to delimit strings. For example,

Foo bar ??? baz qux

should be two lines.)

It is not possible that you configure the streams so that ??? is automatically converted to a newline character. For the user to input a newline character, they have to input a newline character, not anything else.

You have to parse it yourself.
Here's an example parser that treats ??? as delimiter:

void read_string(std::istream& is, std::string& dest)
{
  std::string str = "";
  for (char c; is.get(c);) {
    switch (c) {
    case '?':
      if (is.get(c) && c == '?') {
        if (is.get(c) && c == '?') {
          dest = str;
          return;
        } else {
          str += "??";
        }
      } else {
        str += "?";
      }
    default:
      str += c;
    }
  }
}

For example, the input

? is still one question mark????? is still two question marks???

is parsed as two lines:

? is still one question mark
?? is still two question marks

live demo


答:
Yes, changing Theme.AppCompact.Light.DarkActionBar to Theme.MaterialComponents will help your see the xml in layout editor.

Also, you can follow this article
Implementing BottomAppBar I: Material Components for Android

Title: How to fix FAB inside activity?


问:
Finding the true anomaly from state vectors
I'm attempting to convert from state vectors (position and speed) into Kepler elements, however I'm running into problems where a negative velocity or position will give me wrong results when trying to calculate true anomaly.

Here are the different ways I'm trying to calculate the True Anomaly:

```<code>/// <summary>
/// https://en.wikipedia.org/wiki/True_anomaly#From_state_vectors
/// </summary>
public static double TrueAnomaly(Vector4 eccentVector, Vector4 position, Vector4 velocity)
{
    var dotEccPos = Vector4.Dot(eccentVector, position);
    var talen = eccentVector.Length() * position.Length();
    talen = dotEccPos / talen;
    talen = GMath.Clamp(talen, -1, 1);
    var trueAnomoly = Math.Acos(talen);

    if (Vector4.Dot(position, velocity) < 0)
        trueAnomoly = Math.PI * 2 - trueAnomoly;

    return trueAnomoly;
}
</code>```

```<code>//sgp = standard gravitational parameter
public static double TrueAnomaly(double sgp, Vector4 position, Vector4 velocity)
{
    var H = Vector4.Cross(position, velocity).Length();
    var R = position.Length();
    var q = Vector4.Dot(position, velocity);  // dot product of r*v
    var TAx = H * H / (R * sgp) - 1;
    var TAy = H * q / (R * sgp);
    var TA = Math.Atan2(TAy, TAx);
    return TA;
}
</code>```

```<code>public static double TrueAnomalyFromEccentricAnomaly(double eccentricity, double eccentricAnomaly)
{
    var x = Math.Sqrt(1 - Math.Pow(eccentricity, 2)) * Math.Sin(eccentricAnomaly);
    var y = Math.Cos(eccentricAnomaly) - eccentricity;
    return Math.Atan2(x, y);
}
</code>```

```<code>public static double TrueAnomalyFromEccentricAnomaly2(double eccentricity, double eccentricAnomaly)
{
    var x = Math.Cos(eccentricAnomaly) - eccentricity;
    var y = 1 - eccentricity * Math.Cos(eccentricAnomaly);
    return Math.Acos(x / y);
}
</code>```

Edit: another way of doing it which Spectre pointed out:

```<code>public static double TrueAnomaly(Vector4 position, double loP)
{
    return Math.Atan2(position.Y, position.X) - loP;
}
</code>```

Positions are all relative to the parent body.

These functions all agree if position.x, position.y and velocity.y are all positive.
How do I fix these so that I get a consistent results when position and velocity are negitive?

Just to clarify: My angles appear to be sort of correct, just pointing in the wrong quadrant depending on the position and or velocity vectors.

Yeah so I was wrong, the above all do return the correct values after all.

So I found an edge case where most of the above calculations fail.
Given position and velocity:

```<code>pos = new Vector4() { X = -0.208994076275941, Y = 0.955838328099748 };
vel = new Vector4() { X = -2.1678187689294E-07, Y = -7.93096769486992E-08 };
</code>```

I get some odd results, ie ~ -31.1 degrees, when I think it should return ` 31.1 (non negative). one of them returns ~ 328.8.

However testing with this position and velocity the results apear to be ok:

```<code>pos = new Vector4() { X = -0.25, Y = 0.25 };
vel = new Vector4() { X = Distance.KmToAU(-25), Y = Distance.KmToAU(-25) };
</code>```

See my answer for extra code on how I'm testing and the math I'm using for some of the other variables.

I'm going around in circles on this one. this is a result of a bug in my existing code that shows up under some conditions but not others.
I guess the real question now is WHY am I getting different results with position/velocity above that don't match to my expectations or each other?

答:
Ok so on further testing it appears my original calcs do all return the correct values, however when I was looking at the outputs I was not taking the LoP into account and basically not recognizing that 180 is essentially the same angle as -180.
(I was also looking at the output in radians and just didn't see what should have been obvious)
Long story short, I have a bug I thought was in this area of the code and got lost in the weeds.

Seems I was wrong above. see OP for edge case.

Here's some code I used to test these,

I used variations of the following inputs:

```<code>pos = new Vector4() { X = 0.25, Y = 0.25 };
vel = new Vector4() { X = Distance.KmToAU(-25), Y = Distance.KmToAU(25) };
</code>```

And tested them with the following

```<code>double parentMass = 1.989e30;
double objMass = 2.2e+15;
double sgp = GameConstants.Science.GravitationalConstant * (parentMass + objMass) / 3.347928976e33;

Vector4 ev = OrbitMath.EccentricityVector(sgp, pos, vel);
double e = ev.Length();
double specificOrbitalEnergy = Math.Pow(vel.Length(), 2) * 0.5 - sgp / pos.Length();
double a = -sgp / (2 * specificOrbitalEnergy);
double ae = e * a;
double aop = Math.Atan2(ev.Y, ev.X);
double eccentricAnomaly = OrbitMath.GetEccentricAnomalyFromStateVectors(pos, a, ae, aop);
double aopD = Angle.ToDegrees(aop);
double directAngle = Math.Atan2(pos.Y, pos.X);

var θ1 = OrbitMath.TrueAnomaly(sgp, pos, vel);
var θ2 = OrbitMath.TrueAnomaly(ev, pos, vel);
var θ3 = OrbitMath.TrueAnomalyFromEccentricAnomaly(e, eccentricAnomaly);
var θ4 = OrbitMath.TrueAnomalyFromEccentricAnomaly2(e, eccentricAnomaly);
var θ5 = OrbitMath.TrueAnomaly(pos, aop);
double angleΔ = 0.0000001; //this is the "acceptable" amount of error, really only the TrueAnomalyFromEccentricAnomaly() calcs needed this.
Assert.AreEqual(0, Angle.DifferenceBetweenRadians(directAngle, aop - θ1), angleΔ);
Assert.AreEqual(0, Angle.DifferenceBetweenRadians(directAngle, aop - θ2), angleΔ);
Assert.AreEqual(0, Angle.DifferenceBetweenRadians(directAngle, aop - θ3), angleΔ);
Assert.AreEqual(0, Angle.DifferenceBetweenRadians(directAngle, aop - θ4), angleΔ);
Assert.AreEqual(0, Angle.DifferenceBetweenRadians(directAngle, aop - θ5), angleΔ);
</code>```

and the following to compare the angles:

```<code>public static double DifferenceBetweenRadians(double a1, double a2)
{
    return Math.PI - Math.Abs(Math.Abs(a1 - a2) - Math.PI);
}
</code>```

And eccentricity Vector found thus:

```<code>public static Vector4 EccentricityVector(double sgp, Vector4 position, Vector4 velocity)
{
    Vector4 angularMomentum = Vector4.Cross(position, velocity);
    Vector4 foo1 = Vector4.Cross(velocity, angularMomentum) / sgp;
    var foo2 = position / position.Length();
    return foo1 - foo2;
}
</code>```

And EccentricAnomaly:

```<code>public static double GetEccentricAnomalyFromStateVectors(Vector4 position, double a, double linierEccentricity, double aop)
{
    var x = (position.X * Math.Cos(-aop)) - (position.Y * Math.Sin(-aop));
    x = linierEccentricity + x;
    double foo = GMath.Clamp(x / a, -1, 1); //because sometimes we were getting a floating point error that resulted in numbers infinatly smaller than -1
    return Math.Acos(foo);
}
</code>```

Thanks to Futurogogist and Spektre for their help.

Body:
I'm attempting to convert from state vectors (position and speed) into Kepler elements, however I'm running into problems where a negative velocity or position will give me wrong results when trying to calculate true anomaly.

Here are the different ways I'm trying to calculate the True Anomaly:

///
/// https://en.wikipedia.org/wiki/True_anomaly#From_state_vectors
///
public static double TrueAnomaly(Vector4 eccentVector, Vector4 position, Vector4 velocity)
{
    var dotEccPos = Vector4.Dot(eccentVector, position);
    var talen = eccentVector.Length() * position.Length();
    talen = dotEccPos / talen;
    talen = GMath.Clamp(talen, -1, 1);
    var trueAnomoly = Math.Acos(talen);

    if (Vector4.Dot(position, velocity) < 0)
        trueAnomoly = Math.PI * 2 - trueAnomoly;

    return trueAnomoly;
}

//sgp = standard gravitational parameter
public static double TrueAnomaly(double sgp, Vector4 position, Vector4 velocity)
{
    var H = Vector4.Cross(position, velocity).Length();
    var R = position.Length();
    var q = Vector4.Dot(position, velocity);  // dot product of r*v
    var TAx = H * H / (R * sgp) - 1;
    var TAy = H * q / (R * sgp);
    var TA = Math.Atan2(TAy, TAx);
    return TA;
}

public static double TrueAnomalyFromEccentricAnomaly(double eccentricity, double eccentricAnomaly)
{
    var x = Math.Sqrt(1 - Math.Pow(eccentricity, 2)) * Math.Sin(eccentricAnomaly);
    var y = Math.Cos(eccentricAnomaly) - eccentricity;
    return Math.Atan2(x, y);
}

public static double TrueAnomalyFromEccentricAnomaly2(double eccentricity, double eccentricAnomaly)
{
    var x = Math.Cos(eccentricAnomaly) - eccentricity;
    var y = 1 - eccentricity * Math.Cos(eccentricAnomaly);
    return Math.Acos(x / y);
}

Edit: another way of doing it which Spectre pointed out:

public static double TrueAnomaly(Vector4 position, double loP)
{
    return Math.Atan2(position.Y, position.X) - loP;
}

Positions are all relative to the parent body.

These functions all agree if position.x, position.y and velocity.y are all positive.
How do I fix these so that I get a consistent results when position and velocity are negitive?

Just to clarify: My angles appear to be sort of correct, just pointing in the wrong quadrant depending on the position and or velocity vectors.

Yeah so I was wrong, the above all do return the correct values after all.

So I found an edge case where most of the above calculations fail.
Given position and velocity:

pos = new Vector4() { X = -0.208994076275941, Y = 0.955838328099748 };
vel = new Vector4() { X = -2.1678187689294E-07, Y = -7.93096769486992E-08 };

I get some odd results, ie ~ -31.1 degrees, when I think it should return ` 31.1 (non negative). one of them returns ~ 328.8.

However testing with this position and velocity the results apear to be ok:

pos = new Vector4() { X = -0.25, Y = 0.25 };
vel = new Vector4() { X = Distance.KmToAU(-25), Y = Distance.KmToAU(-25) };

See my answer for extra code on how I'm testing and the math I'm using for some of the other variables.

I'm going around in circles on this one. this is a result of a bug in my existing code that shows up under some conditions but not others.
I guess the real question now is WHY am I getting different results with position/velocity above that don't match to my expectations or each other?

Body:
Ok so on further testing it appears my original calcs do all return the correct values, however when I was looking at the outputs I was not taking the LoP into account and basically not recognizing that 180 is essentially the same angle as -180.
(I was also looking at the output in radians and just didn't see what should have been obvious)
Long story short, I have a bug I thought was in this area of the code and got lost in the weeds.

Seems I was wrong above. see OP for edge case.

Here's some code I used to test these,

I used variations of the following inputs:

pos = new Vector4() { X = 0.25, Y = 0.25 };
vel = new Vector4() { X = Distance.KmToAU(-25), Y = Distance.KmToAU(25) };

And tested them with the following

double parentMass = 1.989e30;
double objMass = 2.2e+15;
double sgp = GameConstants.Science.GravitationalConstant * (parentMass + objMass) / 3.347928976e33;

Vector4 ev = OrbitMath.EccentricityVector(sgp, pos, vel);
double e = ev.Length();
double specificOrbitalEnergy = Math.Pow(vel.Length(), 2) * 0.5 - sgp / pos.Length();
double a = -sgp / (2 * specificOrbitalEnergy);
double ae = e * a;
double aop = Math.Atan2(ev.Y, ev.X);
double eccentricAnomaly = OrbitMath.GetEccentricAnomalyFromStateVectors(pos, a, ae, aop);
double aopD = Angle.ToDegrees(aop);
double directAngle = Math.Atan2(pos.Y, pos.X);

var θ1 = OrbitMath.TrueAnomaly(sgp, pos, vel);
var θ2 = OrbitMath.TrueAnomaly(ev, pos, vel);
var θ3 = OrbitMath.TrueAnomalyFromEccentricAnomaly(e, eccentricAnomaly);
var θ4 = OrbitMath.TrueAnomalyFromEccentricAnomaly2(e, eccentricAnomaly);
var θ5 = OrbitMath.TrueAnomaly(pos, aop);
double angleΔ = 0.0000001; //this is the "acceptable" amount of error, really only the TrueAnomalyFromEccentricAnomaly() calcs needed this.
Assert.AreEqual(0, Angle.DifferenceBetweenRadians(directAngle, aop - θ1), angleΔ);
Assert.AreEqual(0, Angle.DifferenceBetweenRadians(directAngle, aop - θ2), angleΔ);
Assert.AreEqual(0, Angle.DifferenceBetweenRadians(directAngle, aop - θ3), angleΔ);
Assert.AreEqual(0, Angle.DifferenceBetweenRadians(directAngle, aop - θ4), angleΔ);
Assert.AreEqual(0, Angle.DifferenceBetweenRadians(directAngle, aop - θ5), angleΔ);

and the following to compare the angles:

public static double DifferenceBetweenRadians(double a1, double a2)
{
    return Math.PI - Math.Abs(Math.Abs(a1 - a2) - Math.PI);
}

And eccentricity Vector found thus:

public static Vector4 EccentricityVector(double sgp, Vector4 position, Vector4 velocity)
{
    Vector4 angularMomentum = Vector4.Cross(position, velocity);
    Vector4 foo1 = Vector4.Cross(velocity, angularMomentum) / sgp;
    var foo2 = position / position.Length();
    return foo1 - foo2;
}

And EccentricAnomaly:

public static double GetEccentricAnomalyFromStateVectors(Vector4 position, double a, double linierEccentricity, double aop)
{
    var x = (position.X * Math.Cos(-aop)) - (position.Y * Math.Sin(-aop));
    x = linierEccentricity + x;
    double foo = GMath.Clamp(x / a, -1, 1); //because sometimes we were getting a floating point error that resulted in numbers infinatly smaller than -1
    return Math.Acos(foo);
}

Thanks to Futurogogist and Spektre for their help.


问:
ImportError [E048] Can't import language en from spacy.lang
I am trying to run 'en' for Spacy library, which took a lot of debugging to install and finally got it to import in the python library. Next step to load 'en', I spent lot of time debugging why I can't load the files and unable to load in any type of scenarios.

```<code># in Python: These libraries are getting loaded.
import spacy
import ujson
import en_core_web_sm
</code>```

In Command Line/ linux: I used command below to download 'en' for spacy.

```<code>python -m spacy download en
</code>```

I got this successful message

```<code>"You can now load the model via spacy.load('en')."
</code>```

Then I tried to run this and got this error in Python.

```<code>nlp = spacy.load('en')
</code>```

doc = nlp(u'This is a sentence.')

Error: ImportError: [E048] Can't import language en from spacy.lang.

What I have tried?:

1) Download the jar file insert into this path: spacy.util.get_data_path()

2) Loading the files like this spacy.load('C:/path_to/Anaconda3/lib/site-packages/spacy/data/en') including jar file name passed in the spaces.

3) Running java -jar en_core_web_sm-2.0.0a7.tar and java -jar en-1.1.0.tar before running the script. It fails.

Any idea how to solve this? Greatly appreciated!

答:
I had the same error, try using

```<code>python -m spacy download en_core_web_sm
</code>```

instead of

```<code>python -m spacy download en
</code>```

In fact, the 'en' package is just a shortcut for the statistical model 'en_core_web_sm'.

Body:
I am trying to run 'en' for Spacy library, which took a lot of debugging to install and finally got it to import in the python library. Next step to load 'en', I spent lot of time debugging why I can't load the files and unable to load in any type of scenarios.

# in Python: These libraries are getting loaded.
import spacy
import ujson
import en_core_web_sm

In Command Line/ linux: I used command below to download 'en' for spacy.

python -m spacy download en

I got this successful message

"You can now load the model via spacy.load('en')."

Then I tried to run this and got this error in Python.

nlp = spacy.load('en')

doc = nlp(u'This is a sentence.')

Error: ImportError: [E048] Can't import language en from spacy.lang.

What I have tried?:

1) Download the jar file insert into this path: spacy.util.get_data_path()

2) Loading the files like this spacy.load('C:/path_to/Anaconda3/lib/site-packages/spacy/data/en') including jar file name passed in the spaces.

3) Running java -jar en_core_web_sm-2.0.0a7.tar and java -jar en-1.1.0.tar before running the script. It fails.

Any idea how to solve this? Greatly appreciated!

Body:
I had the same error, try using

python -m spacy download en_core_web_sm

instead of

python -m spacy download en

In fact, the 'en' package is just a shortcut for the statistical model 'en_core_web_sm'.


问:
Globalization of HTML controls
How can i implement globalization in html control

like for ex:

for asp.net control i can do

```<code>  <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" meta:resourcekey="Button1" />
        <!-- Explicit Localization -->
        <asp:Button ID="Button2" runat="server" onclick="Button1_Click" Text = "<%$ Resources:Sample_aspx, Button1Caption %>"/>
</code>```

how do i achieve this in a html control like a label or html anchor tag

答:
You could probably do it a number of ways...The first one would be to add the runat="server" control which turns any regular control into a server control

or perhaps use the localization control. Here's a sample from the MSDN article on localization:

```<code><h1>
   <asp:localize runat="server"
       Text="<%$ Resources:WebResources, WelcomeMessage %>" />
</h1>
</code>```

This would grab the value from your resource file and put in in a h1 tag which is just regular html

That link also has some other pretty useful information to your problem...

Title: Globalization of HTML controls

Body:
How can i implement globalization in html control

like for ex:

for asp.net control i can do

  <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" meta:resourcekey="Button1" />

        <asp:Button ID="Button2" runat="server" onclick="Button1_Click" Text = "<%$ Resources:Sample_aspx, Button1Caption %>"/>

how do i achieve this in a html control like a label or html anchor tag

Body:
You could probably do it a number of ways...The first one would be to add the runat="server" control which turns any regular control into a server control

or perhaps use the localization control. Here's a sample from the MSDN article on localization:

<h1>
   <asp:localize runat="server"
       Text="<%$ Resources:WebResources, WelcomeMessage %>" />
</h1>

This would grab the value from your resource file and put in in a h1 tag which is just regular html

That link also has some other pretty useful information to your problem...


问:
I need to skip three rows from the dataframe while loading from a CSV file in scala
I am loading my CSV file to a data frame and I can do that but I need to skip the starting three lines from the file.

I tried .option() command by giving header as true but it is ignoring the only first line.

```<code>val df = spark.sqlContext.read
    .schema(Myschema)
    .option("header",true)
    .option("delimiter", "|")
    .csv(path)
</code>```

I thought of giving header as 3 lines but I couldn't find the way to do that.

alternative thought: skip those 3 lines from the data frame

Please help me with this. Thanks in Advance.

答:
You may try changing wrt to your schema.</p>

```<code> import org.apache.spark.sql.Row
  val sqlContext = new org.apache.spark.sql.SQLContext(sc)

  //Read CSV
  val file = sc.textFile("csvfilelocation")

  //Remove first 3 lines
  val data = file.mapPartitionsWithIndex{ (idx, iter) => if (idx == 0) iter.drop(3) else iter }

  //Create RowRDD by mapping each line to the required fields
  val rowRdd = data.map(x=>Row(x(0), x(1)))

  //create dataframe by calling sqlcontext.createDataframe with rowRdd and your schema
  val df = sqlContext.createDataFrame(rowRdd, schema)
</code>```

Body:
I am loading my CSV file to a data frame and I can do that but I need to skip the starting three lines from the file.

I tried .option() command by giving header as true but it is ignoring the only first line.

val df = spark.sqlContext.read
    .schema(Myschema)
    .option("header",true)
    .option("delimiter", "|")
    .csv(path)

I thought of giving header as 3 lines but I couldn't find the way to do that.

alternative thought: skip those 3 lines from the data frame

Please help me with this. Thanks in Advance.

Body:
You may try changing wrt to your schema.

 import org.apache.spark.sql.Row
  val sqlContext = new org.apache.spark.sql.SQLContext(sc)

  //Read CSV
  val file = sc.textFile("csvfilelocation")

  //Remove first 3 lines
  val data = file.mapPartitionsWithIndex{ (idx, iter) => if (idx == 0) iter.drop(3) else iter }

  //Create RowRDD by mapping each line to the required fields
  val rowRdd = data.map(x=>Row(x(0), x(1)))

  //create dataframe by calling sqlcontext.createDataframe with rowRdd and your schema
  val df = sqlContext.createDataFrame(rowRdd, schema)