问:
AJAX form submit to PHP not returning correct data
I have a form that I would like to send data from to a php script using AJAX. However I am running into an issue with actually passing the data across. The $_POST array is empty for some reason.

Currently the HTML is:

```<code><form>
    <label>Email Address:</label>
    <input type='text' name='email' value='jackc@test.com'/>
    <input type='submit' name='submit' value='Check subscription status'/>
</form>
</code>```

The JQuery is:

```<code> $(document).ready(function() {
        $('form').submit(function(e){
            e.preventDefault();
            var url = 'request.php';
            $.ajax({
                type: 'POST',
                url: url,
                contentType: "json",
                data: $('form').serialize(),
                success: function(data){
                    console.log(data);
                    $('#results').html(data);
                }
            });

        });
    });
</code>```

The PHP is:

```<code>        $emailAddress = $_POST['email'];
        echo "EMAIL: " . $emailAddress;
</code>```

However it's not returning anything. It's blank each time. When I do a console log for $('form').serialize() I see email=jackc%40@test.com which I would expect to see returned from my PHP.

I'd appreciate some help on this. Many thanks.

答:
add dataType as json instead of contentType and also return json encoded data from server.

```<code><script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>
<form id="test">
    <label>Email Address:</label>
    <input type='text' name='email' value='jackc@test.com'/>
    <input type='submit' name='submit' value='Check subscription status'/>
</form>

<div id="results"></div>

<script type="text/javascript">
    $(document).ready(function() {
        $('#test').submit(function(e){
            e.preventDefault();
            var formdata = $('#test').serialize();
            var url = 'request.php';

            alert(formdata);
            $.ajax({
                type: 'POST',
                url: url,
                data: formdata,
                dataType: "json",
                encode :true,
                success: function(data){
                    console.log(data);
                    $('#results').html(data);
                }
            });

        });
    });
</script>
</code>```

request.php

```<code><?php
$emailAddress = $_POST['email'];
echo json_encode("EMAIL: " . $emailAddress);

?>
</code>```

Body:
I have a form that I would like to send data from to a php script using AJAX. However I am running into an issue with actually passing the data across. The $_POST array is empty for some reason.

Currently the HTML is:

<form>
    Email Address:
    <input type='text' name='email' value='jackc@test.com'/>
    <input type='submit' name='submit' value='Check subscription status'/>
</form>

The JQuery is:

 $(document).ready(function() {
        $('form').submit(function(e){
            e.preventDefault();
            var url = 'request.php';
            $.ajax({
                type: 'POST',
                url: url,
                contentType: "json",
                data: $('form').serialize(),
                success: function(data){
                    console.log(data);
                    $('#results').html(data);
                }
            });

        });
    });

The PHP is:

        $emailAddress = $_POST['email'];
        echo "EMAIL: " . $emailAddress;

However it's not returning anything. It's blank each time. When I do a console log for $('form').serialize() I see email=jackc%40@test.com which I would expect to see returned from my PHP.

I'd appreciate some help on this. Many thanks.

Body:
add dataType as json instead of contentType and also return json encoded data from server.

<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>
<form id="test">
    <label>Email Address:</label>
    <input type='text' name='email' value='jackc@test.com'/>
    <input type='submit' name='submit' value='Check subscription status'/>
</form>

<div id="results"></div>

<script type="text/javascript">
    $(document).ready(function() {
        $('#test').submit(function(e){
            e.preventDefault();
            var formdata = $('#test').serialize();
            var url = 'request.php';

            alert(formdata);
            $.ajax({
                type: 'POST',
                url: url,
                data: formdata,
                dataType: "json",
                encode :true,
                success: function(data){
                    console.log(data);
                    $('#results').html(data);
                }
            });

        });
    });
</script>

request.php

<?php
$emailAddress = $_POST['email'];
echo json_encode("EMAIL: " . $emailAddress);

?>


来源: stackexchange

问:
How to run multiple batch programs in one batch file at the same time?
We are making a simple adventure game with my friends as a challenge to only use batch and python and my question is that how could we have our bot running in the same exact window while player moves around?</p>

答:
Threading might be a solution for you. I've not encoutered threading in Python before, but a search brought this thread up with a few examples on implementing threading, or something similar within Python.

How to use threading in Python.

ContentLicense: CC BY-SA 3.0


问:
Alternate signals for test bench without manually typing out all times in iverilog
I am writing a test bench that I want to be able to have signals go high and low in a certain pattern (something like this):
Currently I manually type out what I want each time to be like this:

```<code>module TestExample;
reg a, b, c;

initial begin
    $dumpfile("test.vcd");
    $dumpvars(0, TestExample);

    # 0 a=0; b=0; c=0;
    # 10 a=1; b=0; c=0;
    # 20 a=0; b=1; c=0;
    # 30 a=1; b=1; c=0;
    # 40 a=0; b=0; c=1;
    # 50 a=1; b=0; c=1;
    # 60 a=0; b=1; c=1;
    # 70 a=1; b=1; c=1;
    # 80 a=0; b=0; c=0;

    # 90 $stop;
end
endmodule
</code>```

The problem with this is when I get more signals (lets say a-z instead of a-b) it will take a really long time to manually type out each time and the associated value.  Because of this I am wondering if there is a way I can automate the signals.  For example if I could say switch your state every 10 u-seconds for a, every 20 u-seconds for b, and every 30 u-seconds for c?

答:
for generic patterns, you can use multiple initial blocks, say one per variable:</p>

```<code>initial begin
   a = 0;
   forever begin
      #10 a = 1;
      #10 a = 0;
   end
end
initial
   b = 1;
   forever begin
      #30 b = 0;
      #30 b = 1;
   end
end
...
initial begin
    $dumpfile("test.vcd");
    $dumpvars(0, TestExample);

    #1000 $finish;
end
</code>```

Body:
I am writing a test bench that I want to be able to have signals go high and low in a certain pattern (something like this):
Currently I manually type out what I want each time to be like this:

module TestExample;
reg a, b, c;

initial begin
    $dumpfile("test.vcd");
    $dumpvars(0, TestExample);

    # 0 a=0; b=0; c=0;
    # 10 a=1; b=0; c=0;
    # 20 a=0; b=1; c=0;
    # 30 a=1; b=1; c=0;
    # 40 a=0; b=0; c=1;
    # 50 a=1; b=0; c=1;
    # 60 a=0; b=1; c=1;
    # 70 a=1; b=1; c=1;
    # 80 a=0; b=0; c=0;

    # 90 $stop;
end
endmodule

The problem with this is when I get more signals (lets say a-z instead of a-b) it will take a really long time to manually type out each time and the associated value.  Because of this I am wondering if there is a way I can automate the signals.  For example if I could say switch your state every 10 u-seconds for a, every 20 u-seconds for b, and every 30 u-seconds for c?

Body:
for generic patterns, you can use multiple initial blocks, say one per variable:

initial begin
   a = 0;
   forever begin
      #10 a = 1;
      #10 a = 0;
   end
end
initial
   b = 1;
   forever begin
      #30 b = 0;
      #30 b = 1;
   end
end
...
initial begin
    $dumpfile("test.vcd");
    $dumpvars(0, TestExample);

    #1000 $finish;
end


问:
What are the pre-requisites/standards of integrating a chatbot application inside an angularjs web application?
I ran into things on searching the internet :

https://www.ibm.com/watson/services/conversation/
https://conversation-demo.mybluemix.net/ (Demo)

I was really interested in below one:
http://angularjs.chat/tutorials/angularjs-basic-chat-module/

but it needs

```<code>You need PubNub API Keys. This gives you the Doherty Threshold speed chat communication on a data stream network.
</code>```

Can we build a chatbot application which i can configure and handle as API and responds to the configured messages?

Like,

```<code>(user) Hi
(bot)> Hello

(user)ID : 12345
(bot)> Name: Gopal Kumar
  ID : 12345
  Address: Bengaluru
  Link : https://stackoverflow.com/gok
</code>```

Or it is we need to take this chats via key generation. Please suggest

答: You can check Recast.Ai they have some good examples how to build and host chatbots using their API also I think it's free to use without much rate limitations.</p>

Body:
I ran into things on searching the internet :

https://www.ibm.com/watson/services/conversation/
https://conversation-demo.mybluemix.net/ (Demo)

I was really interested in below one:
http://angularjs.chat/tutorials/angularjs-basic-chat-module/

but it needs

You need PubNub API Keys. This gives you the Doherty Threshold speed chat communication on a data stream network.

Can we build a chatbot application which i can configure and handle as API and responds to the configured messages?

Like,

(user) Hi
(bot)> Hello

(user)ID : 12345
(bot)> Name: Gopal Kumar
  ID : 12345
  Address: Bengaluru
  Link : https://stackoverflow.com/gok

Or it is we need to take this chats via key generation. Please suggest


问:
How can I return a class from an async method
Is it possible to return a class from an async method? I get an error message that there is an GetAwaiter missing? Don't know what this means.

```<code>StatusButton.Click += async (sender, e) =>
        {
            ...
            byte[] TheResponse = new byte[1024];
            await TheResponse = client.Read(); // <---- GetAwaiter ?
        };

public class Client
{
    ...

    public async Task<byte[]> Read()
    {
        var ns = tcpClient.GetStream();
        byte[] Result = new byte[1024];
        await ns.ReadAsync(Result, 0, Result.Length);
        return Result;
    }
}
</code>```

答:
```<code>StatusButton.Click += async (sender, e) =>
{
    ...
    byte[] TheResponse = new byte[1024];
    TheResponse = await client.Read();          // <---- place await in the correct place
};
</code>```

Body:
Is it possible to return a class from an async method? I get an error message that there is an GetAwaiter missing? Don't know what this means.

StatusButton.Click += async (sender, e) =>
        {
            ...
            byte[] TheResponse = new byte[1024];
            await TheResponse = client.Read(); // <---- GetAwaiter ?
        };

public class Client
{
    ...

    public async Task<byte[]> Read()
    {
        var ns = tcpClient.GetStream();
        byte[] Result = new byte[1024];
        await ns.ReadAsync(Result, 0, Result.Length);
        return Result;
    }
}


问:
Logging Framework for the ASP.NET application
My application needs to log informations about user actions (inserts, updates, deletes, etc) and exceptions and i want to store de log on Oracle10, so i'am searching some log framework to use.
I read a little bit about:

1 -Log4Net

2 - Logging Application Block

3 - Elmah

Whats your opinion about these log tools?
Whats a good framework (or way to implement) log on my application?

*After a discussion with the project manager, Logging Application Block
 will be our choice, but, lets comment about this =)

答:
I personally like BitFactory.Logging because it's lightweight and uses the right amount of abstractions to make the calling code easily testable.

That said, the things you want to log (inserts, updates, deletes) could be logged using only triggers, a solution that might perform better depending on your setup.

ContentLicense: CC BY-SA 2.5


问:
hive - how to drop external hive table along with data
I am using

```<code>drop table <table_name>
</code>```

If I recreate the table with the same schema and name, I am getting the old data back.
Should I remove the table directory from hdfs file system to completely get rid of the data?

答:
First get path of the table using following command :

hive> describe formatted database_name.table_name;

Then copy entire location which appear in description, for example :
/user/hive/warehouse/database_name.db/table_name

After this use following command to truncate all the data from given table :

```<code>***hive> dfs -rmr /user/hive/warehouse/database_name.db/table_name;***
</code>```

OR

```<code>***hive> dfs -rm -r /user/hive/warehouse/database_name.db/table_name;***
</code>```

Then you can wipe it completely using DROP TABLE command.

Body:
I am using

drop table <table_name>

If I recreate the table with the same schema and name, I am getting the old data back.
Should I remove the table directory from hdfs file system to completely get rid of the data?

Body:
First get path of the table using following command :

hive> describe formatted database_name.table_name;

Then copy entire location which appear in description, for example :
/user/hive/warehouse/database_name.db/table_name

After this use following command to truncate all the data from given table :

***hive> dfs -rmr /user/hive/warehouse/database_name.db/table_name;***

OR

***hive> dfs -rm -r /user/hive/warehouse/database_name.db/table_name;***

Then you can wipe it completely using DROP TABLE command.


问:
Multiple drop down questions selection in angular js

<!DOCTYPE html>

                Consumer's Choices

            <select ng-model="selectedName" ng-options="x for x in questions" class="form-control">
                    </select>

                    <input type="text" class="form-control" placeholder="Answer">

            <select ng-model="selectedName" ng-options="x for x in questions" class="form-control">
                    </select>

                    <input type="text" class="form-control" placeholder="Answer">

            <select ng-model="selectedName" ng-options="x for x in questions" class="form-control">
                    </select>

                    <input type="text" class="form-control" placeholder="Answer">

```

I'm developing multiple security questions in the dropdown and its answers using angular js. The problem is that these questions come from an array inside the controller and on clicking on drop down, all the other dropdowns are also changing and first selected option should not be displayed in the other drop downs.I need to avoid it.I don't know where I'm making the mistake.

答:
ng-model should be different for each select:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.questions = ["Select a question from the following options.", "What is your favorite color?", "What is your favorite sport?", "What is your favorite car?", "What is your first pet name?", "What is your first car color?"];
  $scope.model = {};

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<body>

  <div ng-app="myApp" ng-controller="myCtrl">
    <div class="form-group">
      <label for="firstname" class="col-sm-3 control-label" id="consumerChoice">Consumer's Choices</label>

      <div class="col-sm-9">
        <div class="row">
          <div class="col-sm-9">
            <select ng-model="selectedName1" class="form-control">
            <option value="{{x}}" ng-repeat="x in questions track by $index">{{x}} </option>
                    </select>
          </div>
          <div class="col-sm-3">
            <input type="text" class="form-control" placeholder="Answer">
          </div>
        </div>
        <div class="row">
          <div class="col-sm-9">
            <select ng-model="selectedName2" class="form-control">
              <option ng-if="selectedName1 != x" value="{{x}}" ng-repeat="x in questions track by $index">{{x}}  </option>
            </select>
          </div>
          <div class="col-sm-3">
            <input type="text" class="form-control" placeholder="Answer">
          </div>
        </div>
        <div class="row">
          <div class="col-sm-9">
            <select ng-model="selectedName3" class="form-control">
              <option value="{{x}}" ng-if="selectedName1 != x && selectedName2 != x" ng-repeat="x in questions track by $index">{{x}} </option>
            </select>
          </div>
          <div class="col-sm-3">
            <input type="text" class="form-control" placeholder="Answer">
          </div>
        </div>
      </div>
    </div>

</body>

</html></code>```

Body:
<!DOCTYPE html>

                Consumer's Choices

            <select ng-model="selectedName" ng-options="x for x in questions" class="form-control">
                    </select>

                    <input type="text" class="form-control" placeholder="Answer">

            <select ng-model="selectedName" ng-options="x for x in questions" class="form-control">
                    </select>

                    <input type="text" class="form-control" placeholder="Answer">

            <select ng-model="selectedName" ng-options="x for x in questions" class="form-control">
                    </select>

                    <input type="text" class="form-control" placeholder="Answer">

I'm developing multiple security questions in the dropdown and its answers using angular js. The problem is that these questions come from an array inside the controller and on clicking on drop down, all the other dropdowns are also changing and first selected option should not be displayed in the other drop downs.I need to avoid it.I don't know where I'm making the mistake.

Body:
ng-model should be different for each select:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.questions = ["Select a question from the following options.", "What is your favorite color?", "What is your favorite sport?", "What is your favorite car?", "What is your first pet name?", "What is your first car color?"];
  $scope.model = {};

});

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<body>

  <div ng-app="myApp" ng-controller="myCtrl">
    <div class="form-group">
      <label for="firstname" class="col-sm-3 control-label" id="consumerChoice">Consumer's Choices</label>

      <div class="col-sm-9">
        <div class="row">
          <div class="col-sm-9">
            <select ng-model="selectedName1" class="form-control">
            <option value="{{x}}" ng-repeat="x in questions track by $index">{{x}} </option>
                    </select>
          </div>
          <div class="col-sm-3">
            <input type="text" class="form-control" placeholder="Answer">
          </div>
        </div>
        <div class="row">
          <div class="col-sm-9">
            <select ng-model="selectedName2" class="form-control">
              <option ng-if="selectedName1 != x" value="{{x}}" ng-repeat="x in questions track by $index">{{x}}  </option>
            </select>
          </div>
          <div class="col-sm-3">
            <input type="text" class="form-control" placeholder="Answer">
          </div>
        </div>
        <div class="row">
          <div class="col-sm-9">
            <select ng-model="selectedName3" class="form-control">
              <option value="{{x}}" ng-if="selectedName1 != x && selectedName2 != x" ng-repeat="x in questions track by $index">{{x}} </option>
            </select>
          </div>
          <div class="col-sm-3">
            <input type="text" class="form-control" placeholder="Answer">
          </div>
        </div>
      </div>
    </div>

</body>

</html>


问:
The different constructor ways
I have write little class, now i see different ways to call constructors. Which way is the correct way? (Or the better way)

SharedKeys.h

```<code>#ifndef SHAREDKEYS_H
    #define SHAREDKEYS_H

    class SharedKeys
    {
    private:
        char keyCode;

    public:
        SharedKeys(char keycode)
        {
            keyCode = keycode;
        }
        ~SharedKeys() {}

        char getKeyCode() { return keyCode; };

    };

    #endif
</code>```

Main.cpp

My constructor call way:

```<code>SharedKeys* SK;
SK = new SharedKeys(*cstr); //Call contructor
</code>```

Other constructor call way:

```<code>// SharedKeys constructor
SharedKeys::SharedKeys(*cstr)
{
    keyCode = keycode;
}
</code>```

I am open to any suggestions for improvement. Thank you.

Main.cpp

SK must be a pointer here or? (this code works)

```<code>SharedKeys* SK;

    vector<SharedKeys> StoreSharedKeys;

string str = x;
char *cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());

SK = new SharedKeys(*cstr);
StoreSharedKeys.push_back(*SK);
delete[] cstr;
</code>```

Did I understand you correctly?

```<code>cout << "Key: " <<  x << " loaded." << endl;
string str = x;
char *cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());

SharedKeys SK(*cstr);
StoreSharedKeys.push_back(SK);
delete[] cstr;
</code>```

if im see that correct then this contructor call is the right way. So i dont must delete the objects. Correct?

答:
The second "call" isn't a call at all.

It's an out-of-class definition. The methods of a class (including constructors and destructors) may be defined inside the body of the class, or outside. If the methods are defined outside the class, you only declare them inside the class.

One important reason to use out-of-class definitions is that you can then put the class definition in a header file, and the method definitions in a .cpp file.

Title: The different constructor ways

Body:
I have write little class, now i see different ways to call constructors. Which way is the correct way? (Or the better way)

SharedKeys.h

#ifndef SHAREDKEYS_H
    #define SHAREDKEYS_H

    class SharedKeys
    {
    private:
        char keyCode;

    public:
        SharedKeys(char keycode)
        {
            keyCode = keycode;
        }
        ~SharedKeys() {}

        char getKeyCode() { return keyCode; };

    };

    #endif

Main.cpp

My constructor call way:

SharedKeys* SK;
SK = new SharedKeys(*cstr); //Call contructor

Other constructor call way:

// SharedKeys constructor
SharedKeys::SharedKeys(*cstr)
{
    keyCode = keycode;
}

I am open to any suggestions for improvement. Thank you.

Main.cpp

SK must be a pointer here or? (this code works)

SharedKeys* SK;

    vector<SharedKeys> StoreSharedKeys;

string str = x;
char *cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());

SK = new SharedKeys(*cstr);
StoreSharedKeys.push_back(*SK);
delete[] cstr;

Did I understand you correctly?

cout << "Key: " <<  x << " loaded." << endl;
string str = x;
char *cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());

SharedKeys SK(*cstr);
StoreSharedKeys.push_back(SK);
delete[] cstr;

if im see that correct then this contructor call is the right way. So i dont must delete the objects. Correct?


问:
Add column to another table and return as a List C#
I have the tabels: main_data and user_data

The table main_data has a foreign key user_id for the table user_data

I want to return a list, which contains all columns form the main_data table and the column full_name from the table user_data.

I already tried to do so, but unfortunately my code doesn't work.

```<code>public override IList<main_data> GetAllDetached()
{
    return this.context.main_data.Join(this.context.user_data,
    o => o.user_id, i => i.user_data_id, (ud, fullName) => new {
    ud.user_id, fullName.full_name }).ToList();
}
</code>```

The following error occurs:

Cannot imlicitly convert type 'System.Collections.Generic.List
  anonymous type: decimal user_id, string full_name' to
  'System.Collections.Generic.IList ProjectName.Model.main_data'. An
  explicit convirsion exists (are you missing a cast?)

答:
Make a DTO Class  which is containing those properties from both the tables which are to be returned into the result:

```<code> Class FinalResult
{
 public int user_id {get; set;}
 public string full_name {get; set;}
 }
</code>```

Then in you code:

```<code> public override List<FinalResult> GetAllDetached()
{

    var result = this.context.main_data.Join(this.context.user_data,
    o => o.user_id, i => i.user_data_id, (ud, fullName) => new {
    ud.user_id, fullName.full_name }).ToList();

 var finalResult = result.Select(x => new FinalResult()
        {
            user_id = x.user_id ,
            full_name = x.full_name

        }).ToList();
        return finalResult ;
}
</code>```

Body:
I have the tabels: main_data and user_data

The table main_data has a foreign key user_id for the table user_data

I want to return a list, which contains all columns form the main_data table and the column full_name from the table user_data.

I already tried to do so, but unfortunately my code doesn't work.

public override IList<main_data> GetAllDetached()
{
    return this.context.main_data.Join(this.context.user_data,
    o => o.user_id, i => i.user_data_id, (ud, fullName) => new {
    ud.user_id, fullName.full_name }).ToList();
}

The following error occurs:

Cannot imlicitly convert type 'System.Collections.Generic.List
  anonymous type: decimal user_id, string full_name' to
  'System.Collections.Generic.IList ProjectName.Model.main_data'. An
  explicit convirsion exists (are you missing a cast?)

Body:
Make a DTO Class  which is containing those properties from both the tables which are to be returned into the result:

 Class FinalResult
{
 public int user_id {get; set;}
 public string full_name {get; set;}
 }

Then in you code:

 public override List<FinalResult> GetAllDetached()
{

    var result = this.context.main_data.Join(this.context.user_data,
    o => o.user_id, i => i.user_data_id, (ud, fullName) => new {
    ud.user_id, fullName.full_name }).ToList();

 var finalResult = result.Select(x => new FinalResult()
        {
            user_id = x.user_id ,
            full_name = x.full_name

        }).ToList();
        return finalResult ;
}


问:
Is it safe to grant "auth | User | Can change user" permissions without the "is staff" flag?
I need certain users to edit django.contrib.auth.models.User objects.

My first thought was to grant them the auth | User | Can change user permission and flag them as is staff, so they can log into the Django Admin site. The problem is though, that they can use that to make themselves super admins.

Since I want them to only be able to edit certain fields, I created a very limited view for that. What's left for me to do, is to actually grant permission on that view to that subset of users. The only solution I found was to still grant them the auth | User | Can change user permission (without making them staff).

My question is this:

If I use the @permission_required decorator on that view in cooperation with the auth | User | Can change user permission, is there any other way for the users to hack their way into granting themselves the super admin role (even assuming the user is a advanced Django programmer)? I am talking about things like e. g. API calls I am unaware of, or similar.

I want to take possible mistakes in my code out of the scope here.

答:
It might be better to create a custom permission e.g. 'can_change_user_restricted', and check for that permission in your custom view.

Then you don't need to worry that in future another view/api might be added, or the is_staff flag might be set, and suddenly the user can make themselves a superuser.


问:
highcharts- chart
Could someone guide me on how to get the no of bubbles in highcharts</p>

答:
You can use pointFormatter to calculate the content of the tooltip dynamically. In the callback you can check if the hovered bubble overlaps with other bubbles.

```<code>function areOverlapping(bubble1, bubble2) {
  const {translateX: tx, translateY: ty } = bubble1.series.group

  const x1 = tx + bubble1.plotX
  const y1 = ty + bubble1.plotY
  const r1 = bubble1.marker.radius

  const x2 = tx + bubble2.plotX
  const y2 = ty + bubble2.plotY
  const r2 = bubble2.marker.radius

  const x = x1 - x2
  const y = y1 - y2
  const r = r1 + r2

  return x * x + y * y <= r * r
}
</code>```

Tooltip.pointFormatter:

```<code>series: [{
  tooltip: {
    pointFormatter: function () {
      const overlapCount = this.series.data.reduce((sum, point) => {
        return sum + (point !== this && areOverlapping(this, point))
      }, 0)

      return 'Overlapping bubbles: ' + overlapCount
    }
  },
</code>```

example: https://jsfiddle.net/0yzkfdjr/

Title: highcharts- chart

Body:
You can use pointFormatter to calculate the content of the tooltip dynamically. In the callback you can check if the hovered bubble overlaps with other bubbles.

function areOverlapping(bubble1, bubble2) {
  const {translateX: tx, translateY: ty } = bubble1.series.group

  const x1 = tx + bubble1.plotX
  const y1 = ty + bubble1.plotY
  const r1 = bubble1.marker.radius

  const x2 = tx + bubble2.plotX
  const y2 = ty + bubble2.plotY
  const r2 = bubble2.marker.radius

  const x = x1 - x2
  const y = y1 - y2
  const r = r1 + r2

  return x * x + y * y <= r * r
}

Tooltip.pointFormatter:

series: [{
  tooltip: {
    pointFormatter: function () {
      const overlapCount = this.series.data.reduce((sum, point) => {
        return sum + (point !== this && areOverlapping(this, point))
      }, 0)

      return 'Overlapping bubbles: ' + overlapCount
    }
  },

example: https://jsfiddle.net/0yzkfdjr/


问:
-su: ./start-all.sh: No such file or directory in Ubuntu
-su: ./start-all.sh: No such file or directory
getting this error while ruining /start-all.sh command  in Ubuntu.   </p>

答:
Go to parent dir (the path in which hadoop is installed, typically stored as $HADOOP_HOME) and run:

```<code>./bin/start-all.sh
</code>```

With this much info you provide, that's all I can suggest.

Body:
Go to parent dir (the path in which hadoop is installed, typically stored as $HADOOP_HOME) and run:

./bin/start-all.sh

With this much info you provide, that's all I can suggest.


问:
Conditional @HostBinding depending on @Input()
I'm trying to bind the CSS class foo to my host component, using @HostBinding depending on a test I do on a dynamic variable.
But can't manage to make it work properly.

Here's what I already tried:

```<code>export class MyComponent {
    @Input()
    public input: string;

    @HostBinding('class.foo')
    public isFoo: Boolean = this.inputIsCorrect();

    constructor() {
    }

    private inputIsCorrect(){
        return (this.input != 'not correct');
    }
}
</code>```

How I could make it work ? I was maybe thinking of way to listen to input changes ?

答:
Try this way. Make @Input property getter/setter and set the isFoo from the setter.

```<code>export class MyComponent {
     @Input()
        public get input (): string {
          return this._input;
        }
        public set input (val: string) {
          this._input = val;
          // when the input is set check it and set isFoo;
          this.isFoo = (val != 'not correct');
        }

        @HostBinding('class.foo')
        public isFoo: Boolean = false; // false is init value

        constructor() {
        }
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to bind the CSS class foo to my host component, using @HostBinding depending on a test I do on a dynamic variable.
But can't manage to make it work properly.

Here's what I already tried:

export class MyComponent {
    @Input()
    public input: string;

    @HostBinding('class.foo')
    public isFoo: Boolean = this.inputIsCorrect();

    constructor() {
    }

    private inputIsCorrect(){
        return (this.input != 'not correct');
    }
}

How I could make it work ? I was maybe thinking of way to listen to input changes ?

Body:
Try this way. Make @Input property getter/setter and set the isFoo from the setter.

export class MyComponent {
     @Input()
        public get input (): string {
          return this._input;
        }
        public set input (val: string) {
          this._input = val;
          // when the input is set check it and set isFoo;
          this.isFoo = (val != 'not correct');
        }

        @HostBinding('class.foo')
        public isFoo: Boolean = false; // false is init value

        constructor() {
        }
    }


问:
Possible to InvalidateVisual() on a given region instead of entire WPF control?
I have a complex WPF control that draws a lot of primitives in its OnRender (it's sort of like a map). When a small portion of it changes, I'd only like to re-issue render commands for the affected elements, instead of running the entire OnRender over. While I'm fine with my OnRender function's performance on a resize or whatever, it's not fast enough for mouse hover-based highlighting of primitives.

Currently the only way I know how to force a screen update is to call InvalidateVisual(). No way to send in a dirty rect region to invalidate.

Is the lowest granularity of WPF screen composition the UI element? Will I need to do my renders of primitives into an intermediate target and then have that use InvalidateVisual() to update to the screen?

答:
When you want to write WPF custom/composite controls, you should try to avoid overriding OnRender as possible especially if you plan to invalidate portions of it. It's much easier to use AddVisualChild + override VisualChildrenCount + override GetVisualChild + override Measure & Arrange like this (pseudo code with 2 children):

```<code>private void BuildMyControls()
{
  AddVisualChild(subControl1);
  AddVisualChild(subControl2);
}

protected override int VisualChildrenCount
{
  get
  {
    return 2;
  }
}

protected override Visual GetVisualChild(int index)
{
  if (index == 0) return subControl1;
  if (index == 1) return subControl2;
  return null; // should never be called in fact...
}

protected override Size MeasureCore(Size availableSize)
{
  base.Measure...
  BuildMyControls();
  .. measure them, probably call subControlX.Measure(...);
}

protected override void ArrangeCore(Rect finalRect)
{
  base.ArrangeCore(finalRect);
  ... arrange them, probably call subControlX.Arrange
}
</code>```

With this kind of code, you can invalidate just one portion, with something like subControlX.InvalidateXXX();

Body:
When you want to write WPF custom/composite controls, you should try to avoid overriding OnRender as possible especially if you plan to invalidate portions of it. It's much easier to use AddVisualChild + override VisualChildrenCount + override GetVisualChild + override Measure & Arrange like this (pseudo code with 2 children):

private void BuildMyControls()
{
  AddVisualChild(subControl1);
  AddVisualChild(subControl2);
}

protected override int VisualChildrenCount
{
  get
  {
    return 2;
  }
}

protected override Visual GetVisualChild(int index)
{
  if (index == 0) return subControl1;
  if (index == 1) return subControl2;
  return null; // should never be called in fact...
}

protected override Size MeasureCore(Size availableSize)
{
  base.Measure...
  BuildMyControls();
  .. measure them, probably call subControlX.Measure(...);
}

protected override void ArrangeCore(Rect finalRect)
{
  base.ArrangeCore(finalRect);
  ... arrange them, probably call subControlX.Arrange
}

With this kind of code, you can invalidate just one portion, with something like subControlX.InvalidateXXX();


问:
Using dbus-send to call GetAll
I tried my luck with:

```<code>  dbus-send --system --print-reply  \
     --dest=org.freedesktop.UDisks \
      /org/freedesktop/UIDisks/devices/md0 \
      org.freedesktop.DBus.Properties.GetAll \
      string:""
</code>```

If I'm using d-free and send ""
as parameter to GetAll I get a long list of output

Trying the code above just gives an error:

```<code>Error org.freedesktop.DBus.Error.UnknownMethod: Method "GetAll" with signature "s" on
interface "org.freedesktop.DBus.Properties" doesn't exist
</code>```

So I'm doing something wrong, but I've no idea what's wrong. I searched for a solution but did not come up with a decent solution. Maybe it's to trivial, but I have no idea....

答:
I tried my luck with:

```<code>dbus-send --system --print-reply  \
   --dest=org.freedesktop.UDisks \
    /org/freedesktop/UIDisks/devices/md0 \
    org.freedesktop.DBus.Properties.GetAll \
    string:""
</code>```

You have a typo in the object path: you put UIDisks instead of UDisks. Fixing that should fix your error.

Addressing your comment on this answer about getting all properties at once, the D-Bus specification doesn’t specify that GetAll should accept an empty string for its interface_name argument, so it’s a bug if any services do accept this. Instead, you must call GetAll once for each of the interfaces on the object.

The easiest way of doing this is to use a higher-level D-Bus utility, like gdbus or D-Feet (as you were trying). dbus-send is designed for simple, low-level interaction with D-Bus services.

```<code>$ gdbus introspect --system --dest org.freedesktop.UDisks2 --object-path /org/freedesktop/UDisks2/block_devices/sda1 --only-properties
node /org/freedesktop/UDisks2/block_devices/sda1 {
  interface org.freedesktop.UDisks2.Partition {
    properties:
      readonly u Number = 1;
      …
  };
  interface org.freedesktop.UDisks2.Filesystem {
    properties:
      readonly aay MountPoints = [b'/boot/efi'];
  };
  …
}
</code>```

Title: Using dbus-send to call GetAll

Body:
I tried my luck with:

  dbus-send --system --print-reply  \
     --dest=org.freedesktop.UDisks \
      /org/freedesktop/UIDisks/devices/md0 \
      org.freedesktop.DBus.Properties.GetAll \
      string:""

If I'm using d-free and send ""
as parameter to GetAll I get a long list of output

Trying the code above just gives an error:

Error org.freedesktop.DBus.Error.UnknownMethod: Method "GetAll" with signature "s" on
interface "org.freedesktop.DBus.Properties" doesn't exist

So I'm doing something wrong, but I've no idea what's wrong. I searched for a solution but did not come up with a decent solution. Maybe it's to trivial, but I have no idea....

Body:
I tried my luck with:

dbus-send --system --print-reply  \
   --dest=org.freedesktop.UDisks \
    /org/freedesktop/UIDisks/devices/md0 \
    org.freedesktop.DBus.Properties.GetAll \
    string:""

You have a typo in the object path: you put UIDisks instead of UDisks. Fixing that should fix your error.

Addressing your comment on this answer about getting all properties at once, the D-Bus specification doesn’t specify that GetAll should accept an empty string for its interface_name argument, so it’s a bug if any services do accept this. Instead, you must call GetAll once for each of the interfaces on the object.

The easiest way of doing this is to use a higher-level D-Bus utility, like gdbus or D-Feet (as you were trying). dbus-send is designed for simple, low-level interaction with D-Bus services.

$ gdbus introspect --system --dest org.freedesktop.UDisks2 --object-path /org/freedesktop/UDisks2/block_devices/sda1 --only-properties
node /org/freedesktop/UDisks2/block_devices/sda1 {
  interface org.freedesktop.UDisks2.Partition {
    properties:
      readonly u Number = 1;
      …
  };
  interface org.freedesktop.UDisks2.Filesystem {
    properties:
      readonly aay MountPoints = [b'/boot/efi'];
  };
  …
}


问:
jQuery sidebar two clicks doesnt load script again
I'm busy with a sidebar and the menu is looks like this

#warmtepomplijst

Brand 1

Brand 2

#Soorten

Type 1

Type 2

Now I made with jQuery.load that a part of the website refresh

```<code>$(document).ready(function(){
    $( ".filter_merklink" ).click(function(e) {
        var link = $(this).attr('href');
        e.preventDefault();
        $( "#warmtepomplijst" ).load( link + " #warmtepomplijst", function(e) {
            console.log( "Nieuwe producten zijn opgehaald. Link= " + link );
        });
        $( "#sidebar" ).load( link + " #sidebar", function(e) {
            console.log( "Sidebar opgehaald!" );
        });
    });

    $('#merken a').click(function(e){
        $("#merken a").removeClass('active');
        $(this).addClass('active');
    });

    $('#soorten a').click(function(e){
        $("#soorten a").removeClass('active');
        $(this).addClass('active');
    });

});
</code>```

The first click works fine! So you click on #warmtepomplijst > a and the div#warmtepomplijst refresh with the new products.

The second click if you click on #Soorten > type 1 than the page refresh

And if you first click is #Soorten > type 1 it works, and else second step #warmtepomplijst > Brand 1 it refresh.

Please help me out!

答:
change all .click methods to .on method. like this :

```<code>$('#soorten a').click(function(e){...
</code>```

//changed

$(document).on('click','#soorten a',function(e){...

Body:
I'm busy with a sidebar and the menu is looks like this

#warmtepomplijst

Brand 1

Brand 2

#Soorten

Type 1

Type 2

Now I made with jQuery.load that a part of the website refresh

$(document).ready(function(){
    $( ".filter_merklink" ).click(function(e) {
        var link = $(this).attr('href');
        e.preventDefault();
        $( "#warmtepomplijst" ).load( link + " #warmtepomplijst", function(e) {
            console.log( "Nieuwe producten zijn opgehaald. Link= " + link );
        });
        $( "#sidebar" ).load( link + " #sidebar", function(e) {
            console.log( "Sidebar opgehaald!" );
        });
    });

    $('#merken a').click(function(e){
        $("#merken a").removeClass('active');
        $(this).addClass('active');
    });

    $('#soorten a').click(function(e){
        $("#soorten a").removeClass('active');
        $(this).addClass('active');
    });

});

The first click works fine! So you click on #warmtepomplijst > a and the div#warmtepomplijst refresh with the new products.

The second click if you click on #Soorten > type 1 than the page refresh

And if you first click is #Soorten > type 1 it works, and else second step #warmtepomplijst > Brand 1 it refresh.

Please help me out!

Body:
change all .click methods to .on method. like this :

$('#soorten a').click(function(e){...

//changed

$(document).on('click','#soorten a',function(e){...


问:
ag-grid: pre-setting a (default) filter for the grid
I have a react app and everything seems to work fine.
I want to add an additional piece of functionality with filtering although I'm currently stuck.

Can anyone provide some advice on how to preset the filter

using the example filtering method I've seen in this article I've tried to implement a basic example although it doesn't work

```<code>this.state = {
   gridOptions: {
  .
  .
  .
      onGridReady: this.initialFilter
},

initialFilter(){
    tmp = {Currency: {type: 'contains', filter: 'usd'}};
    this.state.gridOptions.api.setFilterModel(tmp);
    this.state.gridOptions.api.onFilterChanged();

}
</code>```

What I expected from running this is the Currency column would be filtered for condition containing filter text usd

=================================================
edit:
after trying

```<code>initialFilter(){
    let hi=this.state.gridOptions.api.getFilterInstance('Currency');
    hi.setType('contains');
    hi.setFilter('usd');
    hi.onFilterChanged();
}
</code>```

Nothing happens + no error

but when i add the code in an existing method for changing filters (when i manually add a filter):

```<code>onAfterFilterChanged() {
    let hi=this.state.gridOptions.api.getFilterInstance('Currency');
    hi.setType('contains');
    hi.setFilter('usd');
    hi.onFilterChanged();

    this.setState({
        rowsToDisplay: this.state.gridOptions.api.filterManager.rowModel.rowsToDisplay.length,
        filtering: this.props.report.views.filters
    });
    this.props.filterme(this.state.filtering);
}
</code>```

then i get the below error

```<code>Full error: Uncaught RangeError: Maximum call stack size exceeded
at RowRenderer.workOutFirstAndLastRowsToRender (dme-ui-buidle.js:13181)
at RowRenderer.drawVirtualRows (dme-ui-buidle.js:13178)
at RowRenderer.refreshAllVirtualRows (dme-ui-buidle.js:13138)
at RowRenderer.refreshView (dme-ui-buidle.js:13034)
at RowRenderer.onModelUpdated (dme-ui-buidle.js:12979)
at RowRenderer.onPageLoaded (dme-ui-buidle.js:12931)
at dme-ui-buidle.js:2684
at Array.forEach (<anonymous>)
at EventService.dispatchEvent (dme-ui-buidle.js:2683)
at PaginationProxy.onModelUpdated (dme-ui-buidle.js:27264)
</code>```

答:
According to the documentation here:

https://www.ag-grid.com/javascript-grid-filtering/

and this plunker:

https://plnkr.co/edit/0NoAA9cEZa1Zr9brMZ2I?p=info

something like this should do the trick:

```<code>var yourFilterComponent = gridOptions.api.getFilterInstance('youfieldname');
yourFilterComponent.setType('contains');
yourFilterComponent.setFilter('usd');
yourFilterComponent.onFilterChanged();
</code>```

Body:
I have a react app and everything seems to work fine.
I want to add an additional piece of functionality with filtering although I'm currently stuck.

Can anyone provide some advice on how to preset the filter

using the example filtering method I've seen in this article I've tried to implement a basic example although it doesn't work

this.state = {
   gridOptions: {
  .
  .
  .
      onGridReady: this.initialFilter
},

initialFilter(){
    tmp = {Currency: {type: 'contains', filter: 'usd'}};
    this.state.gridOptions.api.setFilterModel(tmp);
    this.state.gridOptions.api.onFilterChanged();

}

What I expected from running this is the Currency column would be filtered for condition containing filter text usd

=================================================
edit:
after trying

initialFilter(){
    let hi=this.state.gridOptions.api.getFilterInstance('Currency');
    hi.setType('contains');
    hi.setFilter('usd');
    hi.onFilterChanged();
}

Nothing happens + no error

but when i add the code in an existing method for changing filters (when i manually add a filter):

onAfterFilterChanged() {
    let hi=this.state.gridOptions.api.getFilterInstance('Currency');
    hi.setType('contains');
    hi.setFilter('usd');
    hi.onFilterChanged();

    this.setState({
        rowsToDisplay: this.state.gridOptions.api.filterManager.rowModel.rowsToDisplay.length,
        filtering: this.props.report.views.filters
    });
    this.props.filterme(this.state.filtering);
}

then i get the below error

Full error: Uncaught RangeError: Maximum call stack size exceeded
at RowRenderer.workOutFirstAndLastRowsToRender (dme-ui-buidle.js:13181)
at RowRenderer.drawVirtualRows (dme-ui-buidle.js:13178)
at RowRenderer.refreshAllVirtualRows (dme-ui-buidle.js:13138)
at RowRenderer.refreshView (dme-ui-buidle.js:13034)
at RowRenderer.onModelUpdated (dme-ui-buidle.js:12979)
at RowRenderer.onPageLoaded (dme-ui-buidle.js:12931)
at dme-ui-buidle.js:2684
at Array.forEach (<anonymous>)
at EventService.dispatchEvent (dme-ui-buidle.js:2683)
at PaginationProxy.onModelUpdated (dme-ui-buidle.js:27264)

Body:
According to the documentation here:

https://www.ag-grid.com/javascript-grid-filtering/

and this plunker:

https://plnkr.co/edit/0NoAA9cEZa1Zr9brMZ2I?p=info

something like this should do the trick:

var yourFilterComponent = gridOptions.api.getFilterInstance('youfieldname');
yourFilterComponent.setType('contains');
yourFilterComponent.setFilter('usd');
yourFilterComponent.onFilterChanged();


问:
Random Variable not being updated in VBA Excel
While running this code to randomize some values I find that the all the cells have the same number. I believe I'm missing a standard concept but I can't seem to wrap my head around the issue.</p>

```<code>Randomize
LWeekDay = Int((400 - 150 + 1) * Rnd + 200)
LWeekEnd = Int((600 - 200 + 1) * Rnd + 200)

For Y = 3 To 10

   For X = 2 To 8
       Cells(Y, X) = LWeekDay
   Next X
Next Y
</code>```

答:
You are currently only calculating LWeekDay once, and then using that value for every cell.

I assume you want to assign a new value every time through the loop:

```<code>Randomize
For Y = 3 To 10
   For X = 2 To 8
       LWeekDay = Int((400 - 150 + 1) * Rnd + 200)
       LWeekEnd = Int((600 - 200 + 1) * Rnd + 200)
       Cells(Y, X) = LWeekDay
   Next X
Next Y
</code>```

Body:
While running this code to randomize some values I find that the all the cells have the same number. I believe I'm missing a standard concept but I can't seem to wrap my head around the issue.

Randomize
LWeekDay = Int((400 - 150 + 1) * Rnd + 200)
LWeekEnd = Int((600 - 200 + 1) * Rnd + 200)

For Y = 3 To 10

   For X = 2 To 8
       Cells(Y, X) = LWeekDay
   Next X
Next Y

Body:
You are currently only calculating LWeekDay once, and then using that value for every cell.

I assume you want to assign a new value every time through the loop:

Randomize
For Y = 3 To 10
   For X = 2 To 8
       LWeekDay = Int((400 - 150 + 1) * Rnd + 200)
       LWeekEnd = Int((600 - 200 + 1) * Rnd + 200)
       Cells(Y, X) = LWeekDay
   Next X
Next Y


问:
Drupal 6: Anonymously created nodes result in 404
Nodes of this certain types can be created by anonymous or registered users. If a registered user creates it, everything works fine. If an anon creates it, going to that node's page results in a 404 error.

The node clearly exists, however. If I edit its entry in the node table and set its uid to be something other than 0, everything works fine.

Why is this?

This rule holds throughout all node types, CCK generated and otherwise. If I set uid = 0, it breaks. If I set uid = 2 (or any other number not 0), it works fine.

debug_print_backtrace() results in this:

```<code>#0 drupal_not_found() called at [/home/sitename/public_html/sitename2/index.php:24]
</code>```

答:
It also appears that if user 0 (anonymous) had previously created a node of a certain content type, and later the permissions for that content type were limited to a logged-in user, then Drupal may not recognize the node.  This will also cause a 404 error.

Upon first glance, it seemed that Drupal simply wasn't picking up or indexing the nodes... that they were simply gone.  However, when looking at the database, the nodes were indeed there.

In my case, user 0 existed in the user table, but the offending nodes had an user id of 0.  Using phpMyAdmin, I manually changed the uid to a valid user (other than 0), and Drupal recognized the nodes once again.

Body:
Nodes of this certain types can be created by anonymous or registered users. If a registered user creates it, everything works fine. If an anon creates it, going to that node's page results in a 404 error.

The node clearly exists, however. If I edit its entry in the node table and set its uid to be something other than 0, everything works fine.

Why is this?

This rule holds throughout all node types, CCK generated and otherwise. If I set uid = 0, it breaks. If I set uid = 2 (or any other number not 0), it works fine.

debug_print_backtrace() results in this:

#0 drupal_not_found() called at [/home/sitename/public_html/sitename2/index.php:24]


问:
Resizing Auto Layout Constraint
I'm developing an iOS application in Xcode 8. I'm having trouble getting my head around the auto-layout constraints even after reading various tutorials. I am trying to find what combination of constraints allows me to have an adjustable spacing between the top layout guide and the top of my image view.

Below is the preview of the view on iPhone 7 Plus:

iPhone 7 Plus Demo

The top constraint of the UIImageView is currently set to =50, which is the perfect size for larger screens. However, I am trying to have this spacing shrink on smaller screens, as seen below:

iPhone 4s Demo

I have tried what feels like all possible combinations of various constraints with different sizes and priorities but the spacing is either small on all screens or large on all screens. Is there something I am missing?

答:
After some playing around with the above ideas, I found a solution to my problem that lets me see the changes in the storyboard. I position my UIImageView in the preferred location (on iPhone 7+) and set an vertical alignment constraint at the current canvas value - I then set this constraint to have a priority of 750.

I then add a top constraint to the top layout guide which is greater than or equal to 10, this has a priority of 1000.

When seen on a larger screen, the UIImageView positions towards the vertical alignment. When seen on the smaller screens, the vertical alignment pushes the image to the top but the higher priority top constraint of 10 keeps it on the screen.

Title: Resizing Auto Layout Constraint


问:
Displaying a custom div inline with a h5
I know it sounds simple, but this is really annoying me. I have researched online and not found a perfect answer for me yet.

I have this html code:

```<code><h5 class="start-online"><div id="online_ajax">0</div> Clients online </h5>
</code>```

I want the online_ajax div to display inline before the Client online text.

My current css is:

```<code>h5.start-online {
    text-align: center;
    font-size: 11px;
}

.online_ajax {
    position: relative;
    display: inline-block;
}
</code>```

答:
As mentioned before: You should use  instead of
. Then you don't need display: inline-block; anymore in your css.

Body:
I know it sounds simple, but this is really annoying me. I have researched online and not found a perfect answer for me yet.

I have this html code:

0
 Clients online

I want the online_ajax div to display inline before the Client online text.

My current css is:

h5.start-online {
    text-align: center;
    font-size: 11px;
}

.online_ajax {
    position: relative;
    display: inline-block;
}

Body: As mentioned before: You should use <span> instead of <div>. Then you don't need display: inline-block; anymore in your css.


问:
How to upgrade pip3?
I want to use python3.5 for development, but many times when I install the module for python 3.5, it always fails. The terminal tells me that a higher version is available, but it doesn't work when I upgrade it.

答:
To upgrade your pip3, try running:

```<code>sudo -H pip3 install --upgrade pip
</code>```

Your pip may move from /bin to /usr/local/bin

To upgrade pip as well, you can follow it by:

```<code>sudo -H pip2 install --upgrade pip
</code>```

Title: How to upgrade pip3?

Body:
To upgrade your pip3, try running:

sudo -H pip3 install --upgrade pip

Your pip may move from /bin to /usr/local/bin

To upgrade pip as well, you can follow it by:

sudo -H pip2 install --upgrade pip


问:
does try catch clause affect performance?
does try/catch affects performance if no exception thrown in try block?

how about try/catch/finally?

答:
try/catch will only effect performance if an Exception is thrown (but that still isn't because of try/catch, it is because an Exception is being created).

try/catch/finally does not add any additional overhead over try/catch.


问:
Node.js app reading cached json value
I have recently started making a node.js app and have gotten to a point at which I need to read a value of a JSON that has just been updated, but not successfully, I have tried using the 'sleep' module to stop threads for a small delay but still no luck.

I haven't been using node.js for very long either, for only about 5 months.

```<code>var obj;

let sData = ('./session-data/data.json');
var contents = fs.readFile(sData, 'utf8', function(err, data){
  if (err) throw err;
  obj = JSON.parse(data);
});

// Below is getting input text from an inquirer question & logging it to the json but when console.log 'ed it outputs the last value from the key in the json
fs.writeFile('./session-data/data.json', `{\n "video": "` + answers.input + `"\n}`, function(err){
  if(err){
    return console.log(err);
  }
  console.log('Video: ' + obj.video)
});
</code>```

答:
With no code, no error and no expected result it's very hard to answer with any specific solution. All I can say after reading the question is that whatever your problem is, you shouldn't use the sleep module for that. From the documentation: "These calls will block execution of all JavaScript by halting Node.js' event loop!" You never want to do that with things that you describe.

Presumably your "JSON" (by which you probably mean an object, not JSON, but I'm guessing here) is updated by some operation, inside of some callback or event handler or as a result of a promise resolution etc. Instead of introducing specific delays you should listen for a relevant event, add a promise resolution handler, add a callback etc. where you could know when the value is changed and needs to be acted upon.

Introducing random delays will never help you with that, and introducing delays that block the entire event loop will only cause trouble.

Title: Node.js app reading cached json value

Body:
I have recently started making a node.js app and have gotten to a point at which I need to read a value of a JSON that has just been updated, but not successfully, I have tried using the 'sleep' module to stop threads for a small delay but still no luck.

I haven't been using node.js for very long either, for only about 5 months.

var obj;

let sData = ('./session-data/data.json');
var contents = fs.readFile(sData, 'utf8', function(err, data){
  if (err) throw err;
  obj = JSON.parse(data);
});

// Below is getting input text from an inquirer question & logging it to the json but when console.log 'ed it outputs the last value from the key in the json
fs.writeFile('./session-data/data.json', `{\n "video": "` + answers.input + `"\n}`, function(err){
  if(err){
    return console.log(err);
  }
  console.log('Video: ' + obj.video)
});


问:
Show/remove classes while scrolling down
I just need to show div while scrolling down and remove another div at same time.
I try with this code and this is working as I expected. The problem is, If I scroll to top I need to show the removed class and hide current class. (opposite side of this)

This is my code.

```<code>    $(window).scroll(function() {
     var scroll = $(window).scrollTop();
     if (scroll >= 0) {
     $(".left-nav").removeClass("white-nav");
    }
  });
</code>```

What is the best solution?

答:
just use addClass() to add class when scrollTop is 0, since you are already check for scroll >= 0, you just need to add an else like this:

```<code> $(window).scroll(function() {
     var scroll = $(window).scrollTop();
     if (scroll > 0) {
        $(".left-nav").removeClass("white-nav");
     } else {
        $(".left-nav").addClass("white-nav");
     }
 });
</code>```

Body:
I just need to show div while scrolling down and remove another div at same time.
I try with this code and this is working as I expected. The problem is, If I scroll to top I need to show the removed class and hide current class. (opposite side of this)

This is my code.

    $(window).scroll(function() {
     var scroll = $(window).scrollTop();
     if (scroll >= 0) {
     $(".left-nav").removeClass("white-nav");
    }
  });

What is the best solution?

Body:
just use addClass() to add class when scrollTop is 0, since you are already check for scroll >= 0, you just need to add an else like this:

 $(window).scroll(function() {
     var scroll = $(window).scrollTop();
     if (scroll > 0) {
        $(".left-nav").removeClass("white-nav");
     } else {
        $(".left-nav").addClass("white-nav");
     }
 });


问:
Get all columns of a table from a different database
s there a syntax wherein I can get the columns of a table from a different database? I have tried using select column_name from information_schema.columns
where table_name = 'Database_Name.DBO.Table_Name' But it's not working. Please do help me, been doing this for days.

答:
This is what I found out. Each database has its own information_schema view so it won't show the information from the other databases. So if you want to get the column names for a table in another database, you have to use the information_schema view of that database.

{database name}.information_schema

Example:

```<code>SET @Sql = CONCAT('INSERT INTO ', @DBName, '.dbo.colname_table (column_name)
    SELECT COLUMN_NAME FROM ', @DBName, '.INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = ''table_name'' AND TABLE_SCHEMA = ''dbo''
    ORDER BY ORDINAL_POSITION');

EXECUTE sp_executesql @Sql;
</code>```

where @DBName is the name of the database.

Body:
This is what I found out. Each database has its own information_schema view so it won't show the information from the other databases. So if you want to get the column names for a table in another database, you have to use the information_schema view of that database.

{database name}.information_schema

Example:

SET @Sql = CONCAT('INSERT INTO ', @DBName, '.dbo.colname_table (column_name)
    SELECT COLUMN_NAME FROM ', @DBName, '.INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = ''table_name'' AND TABLE_SCHEMA = ''dbo''
    ORDER BY ORDINAL_POSITION');

EXECUTE sp_executesql @Sql;

where @DBName is the name of the database.


问:
how to read file line by line and change characters if line contain specific value
I have a FASTA file (testfile.fa), which contains title lines (contain > in the beginning) and lines with characters meaning some types of nucleotides (A, C, G, T, a, g, c, t, N).

```<code>>chr1
cccccccccttttttttaaaa
AAAACCCCTTCCCCCCCCGGG
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTT
>chr1_alt
TCTCTCTCTCTCTCTCTCTCT
gggtttccccccccccccccc
CGCGCGCGCGCGCGCGCGCGC
CCCCCAAAAAAAAAAAAAAAA
>chr2
CCCCCCCCCCCCCCCCCCCCC
TTTTTTTTTTTTATTTTTTTT
>chr3
AAAAAAAAAAAAAAAAAAAAA
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTT
</code>```

I need to read this file line by line and change small characters (a, c, t, g) to N in every sequence except titles, which contain >. So I use the following code:

```<code>#!/bin/bash
while read line
do
    if [[ $line =~ ">" ]]
    then
        echo $line
    else
        tr 'c' 'N'
        echo $line
    fi
done < testfile.fa
</code>```

But the results are confusing:

```<code>>chr1
# the first line was missed
AAAACCCCTTCCCCCCCCGGG
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTT
>Nhr1_alt #the character was changed but the line contains >
TCTCTCTCTCTCTCTCTCTCT
gggtttNNNNNNNNNNNNNNN
CGCGCGCGCGCGCGCGCGCGC
CCCCCAAAAAAAAAAAAAAAA
>Nhr2 #the character was changed but the line contains >
CCCCCCCCCCCCCCCCCCCCC
TTTTTTTTTTTTATTTTTTTT
>Nhr3 #the character was changed but the line contains >
AAAAAAAAAAAAAAAAAAAAA
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTTcccccccccttttttttaaaa #the first line from the first sequence comes here
</code>```

What can be the probable reason of these problems and how can I solve them? Thank you in advance!

答:
You use tr in wrong way.

Here is my script:

```<code>#!/bin/sh

while read line
do
    if [[ $line =~ ">" ]]
    then
        echo $line
    else
        echo $line | tr 'c' 'N'
    fi
done < t.file
</code>```

Body:
I have a FASTA file (testfile.fa), which contains title lines (contain > in the beginning) and lines with characters meaning some types of nucleotides (A, C, G, T, a, g, c, t, N).

>chr1
cccccccccttttttttaaaa
AAAACCCCTTCCCCCCCCGGG
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTT
>chr1_alt
TCTCTCTCTCTCTCTCTCTCT
gggtttccccccccccccccc
CGCGCGCGCGCGCGCGCGCGC
CCCCCAAAAAAAAAAAAAAAA
>chr2
CCCCCCCCCCCCCCCCCCCCC
TTTTTTTTTTTTATTTTTTTT
>chr3
AAAAAAAAAAAAAAAAAAAAA
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTT

I need to read this file line by line and change small characters (a, c, t, g) to N in every sequence except titles, which contain >. So I use the following code:

#!/bin/bash
while read line
do
    if [[ $line =~ ">" ]]
    then
        echo $line
    else
        tr 'c' 'N'
        echo $line
    fi
done < testfile.fa

But the results are confusing:

>chr1
# the first line was missed
AAAACCCCTTCCCCCCCCGGG
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTT
>Nhr1_alt #the character was changed but the line contains >
TCTCTCTCTCTCTCTCTCTCT
gggtttNNNNNNNNNNNNNNN
CGCGCGCGCGCGCGCGCGCGC
CCCCCAAAAAAAAAAAAAAAA
>Nhr2 #the character was changed but the line contains >
CCCCCCCCCCCCCCCCCCCCC
TTTTTTTTTTTTATTTTTTTT
>Nhr3 #the character was changed but the line contains >
AAAAAAAAAAAAAAAAAAAAA
GGGGGGGGGGGGGGGGGGGGG
TTTTTTTTTTTTTTTTTTTTTcccccccccttttttttaaaa #the first line from the first sequence comes here

What can be the probable reason of these problems and how can I solve them? Thank you in advance!

Body:
You use tr in wrong way.

Here is my script:

#!/bin/sh

while read line
do
    if [[ $line =~ ">" ]]
    then
        echo $line
    else
        echo $line | tr 'c' 'N'
    fi
done < t.file


问:
How I can upload files to Amazon S3 without listing bucket
I am uploading files to S3 using Angular front-end with S3 Bucket policy as:

```<code>{
  "Id": "Policy1499245520254",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1499245493674",
      "Action": [
        "s3:*"
      ],
      "Effect": "Allow",
      "Resource": ["arn:aws:s3:::test-dev/*",
                "arn:aws:s3:::test-dev"],
      "Principal": "*"
    }
  ]
}
</code>```

But if I change the above policy to

```<code>{
  "Id": "Policy1499245520254",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1499245493674",
      "Action": [
        "s3:*"
      ],
      "Effect": "Allow",
      "Resource": ["arn:aws:s3:::test-dev/*",
                "arn:aws:s3:::test-dev"],
      "Principal": "*"
    },
    {
      "Sid": "Stmt1499245517941",
      "Action": [
        "s3:ListBucket"
      ],
      "Effect": "Deny",
      "Resource": "arn:aws:s3:::test-dev",
      "Principal": "*"
    }
  ]
}
</code>```

Where I added:

```<code>{
      "Sid": "Stmt1499245517944",
      "Action": [
        "s3:ListBucket"
      ],
      "Effect": "Deny",
      "Resource": "arn:aws:s3:::test-dev",
      "Principal": "*"
 }
</code>```

adding bucket list deny, the upload fails. Any way how I can upload files without listing bucket.

答: That's because the s3:ListBucket actions covers the GET Bucket (List Objects) and HEAD Bucket operations. The HEAD Bucket operation determines if the bucket exists and you have permission to access it, which seems to be called before any action on objects (such as the s3:PutObject action). See Specifying Permissions in a Policy.

Body:
I am uploading files to S3 using Angular front-end with S3 Bucket policy as:

{
  "Id": "Policy1499245520254",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1499245493674",
      "Action": [
        "s3:*"
      ],
      "Effect": "Allow",
      "Resource": ["arn:aws:s3:::test-dev/*",
                "arn:aws:s3:::test-dev"],
      "Principal": "*"
    }
  ]
}

But if I change the above policy to

{
  "Id": "Policy1499245520254",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1499245493674",
      "Action": [
        "s3:*"
      ],
      "Effect": "Allow",
      "Resource": ["arn:aws:s3:::test-dev/*",
                "arn:aws:s3:::test-dev"],
      "Principal": "*"
    },
    {
      "Sid": "Stmt1499245517941",
      "Action": [
        "s3:ListBucket"
      ],
      "Effect": "Deny",
      "Resource": "arn:aws:s3:::test-dev",
      "Principal": "*"
    }
  ]
}

Where I added:

{
      "Sid": "Stmt1499245517944",
      "Action": [
        "s3:ListBucket"
      ],
      "Effect": "Deny",
      "Resource": "arn:aws:s3:::test-dev",
      "Principal": "*"
 }

adding bucket list deny, the upload fails. Any way how I can upload files without listing bucket.


问:
jQuery Get Value of Input Field in the next Div Nest
I am trying to get value of the input field nested in the next div with class 'fullaccountcode' but it keeps on returning empty when I alert the result.

HTML:

```<code><div class="row">
                    <div class="col-lg-1 col-md-1 col-sm-2 col-xs-2 fullaccountcode">
                        <input type=text name=mcode[] id=mcode placeholder="34" class="form-control">
          </div>
                    <div class="col-xs-1 show-slash">
                        <span>/</span>
                    </div>
                    <div class="col-lg-1 col-md-1 col-sm-2 col-xs-2 fullaccountcode">
                        <input type=text name=ccode[] id=ccode placeholder="01" class="form-control" value="yello">
                    </div>
                    <div class="col-xs-1 show-slash">
                        <span>/</span>
                    </div>
                    <div class="col-lg-1 col-md-1 col-sm-2 col-xs-2 fullaccountcode">
                        <input type=text name=sacode[] id=sacode placeholder="0016" class="form-control">
                    </div>
                </div>
</code>```

JS:

```<code>$(document).on("keyup","#mcode",function() {
  alert($(this).closest('div').nextAll('.fullaccountcode').eq(0).val());
});
</code>```

JSFiddle Demo

答:
There are 2 issues in your code:

1) you are targeting div and not the input element in it. Use .find('input') after getting the target div element.

2 ) Also eq selector targets the element based on zero index. You should use :eq(0) or .first() to target first element in matched set:

```<code>$(document).on("keyup","#mcode",function() {
  alert($(this).closest('div').nextAll(".fullaccountcode").eq(0).find('input').val());
});
</code>```

Working Demo

Body:
I am trying to get value of the input field nested in the next div with class 'fullaccountcode' but it keeps on returning empty when I alert the result.

HTML:

                        <input type=text name=mcode[] id=mcode placeholder="34" class="form-control">

                        /

                        <input type=text name=ccode[] id=ccode placeholder="01" class="form-control" value="yello">

                        /

                        <input type=text name=sacode[] id=sacode placeholder="0016" class="form-control">

JS:

$(document).on("keyup","#mcode",function() {
  alert($(this).closest('div').nextAll('.fullaccountcode').eq(0).val());
});

JSFiddle Demo

Body:
There are 2 issues in your code:

1) you are targeting div and not the input element in it. Use .find('input') after getting the target div element.

2 ) Also eq selector targets the element based on zero index. You should use :eq(0) or .first() to target first element in matched set:

$(document).on("keyup","#mcode",function() {
  alert($(this).closest('div').nextAll(".fullaccountcode").eq(0).find('input').val());
});

Working Demo


问:
DataGridRowStyle Overridden by RowHighlightBrush
I have a DataGridStyle that modifies the Foreground property of its TextBlock based on a value called ApprovalLevel. It looks like this:

```<code><Style TargetType="{x:Type DataGridRow}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding ApprovalLevel}" Value="-1">
            <Setter Property="Foreground" Value="Red"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding ApprovalLevel}" Value="0">
            <Setter Property="Foreground" Value="Black"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding ApprovalLevel}" Value="1">
            <Setter Property="Foreground" Value="Green"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding ApprovalLevel}" Value="2">
            <Setter Property="Foreground" Value="Blue"/>
        </DataTrigger>
    </Style.Triggers>
</Style>
</code>```

This applies the style to the row without issue, however when the user highlights the row the style is overridden and the foreground colour is lost. I have tried applying styles such as:

```<code><DataGrid.Resources>
    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/>
</DataGrid.Resources>
</code>```

however all this does is override the entire row to be transparent. MY question is how can I make it clear to the user that they have selected a row whilst preserving the foreground style that I want to apply?

答:
Style the TextBlock using an ElementStyle instead of using a DataGridRow style:

```<code><DataGrid x:Name="dg">
    <DataGrid.Resources>
        <Style x:Key="style" TargetType="{x:Type TextBlock}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ApprovalLevel}" Value="-1">
                    <Setter Property="Foreground" Value="Red"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding ApprovalLevel}" Value="0">
                    <Setter Property="Foreground" Value="Black"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding ApprovalLevel}" Value="1">
                    <Setter Property="Foreground" Value="Green"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding ApprovalLevel}" Value="2">
                    <Setter Property="Foreground" Value="Blue"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding YourProperty}" ElementStyle="{StaticResource style}" />
        <!-- ... -->
    </DataGrid.Columns>
</DataGrid>
</code>```

Body:
I have a DataGridStyle that modifies the Foreground property of its TextBlock based on a value called ApprovalLevel. It looks like this:

</Style>

This applies the style to the row without issue, however when the user highlights the row the style is overridden and the foreground colour is lost. I have tried applying styles such as:

<DataGrid.Resources>
    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/>
</DataGrid.Resources>

however all this does is override the entire row to be transparent. MY question is how can I make it clear to the user that they have selected a row whilst preserving the foreground style that I want to apply?

Body:
Style the TextBlock using an ElementStyle instead of using a DataGridRow style:

<DataGrid x:Name="dg">
    <DataGrid.Resources>
        <Style x:Key="style" TargetType="{x:Type TextBlock}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ApprovalLevel}" Value="-1">
                    <Setter Property="Foreground" Value="Red"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding ApprovalLevel}" Value="0">
                    <Setter Property="Foreground" Value="Black"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding ApprovalLevel}" Value="1">
                    <Setter Property="Foreground" Value="Green"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding ApprovalLevel}" Value="2">
                    <Setter Property="Foreground" Value="Blue"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding YourProperty}" ElementStyle="{StaticResource style}" />
        <!-- ... -->
    </DataGrid.Columns>
</DataGrid>


问:
How to get information, if plant species occur at specific coordinates by using shapefiles in R
I want to create a tables using R that contain the information, if plant species occur at specific points (coordinates). Therefore, I want to use shapefiles, containing the distribution of several specific plant species. My output has to be a table, that for every point/coordinate indicate the presence of every plant species as 1 and the absence as 0.

First, I read in my first shapefile and the CVS table, containing the coordinates I need:

```<code>plant <- shapefile ('plant.shp')
birds<-read.csv2("bird_Coordinates.csv")
</code>```

Next, I extract the coordinates, save them in a dataframe and project the points over the distribution shapefile:

```<code>lats <- birds$lat
lons <- birds$lon
pts <- data.frame(x=lons,y=lats)
coordinates(pts) <- ~x+y
proj4string(pts) <- proj4string(plant)
</code>```

When I now plot the shapefile and the coordinates, I see the shape of the plant distribution and two red points, which indicate that two of my about 60 points are within this distribution:

```<code>plot(plant)
points(pts, pch=20, col='red')
</code>```

Next, I try to use over, to associate the points to the distribution. Here I used two different ways:

1.

```<code>over(pts, plant)$admin
cbind.data.frame(pts, plant=over(pts, plant)$admin)
</code>```

Resulting in the warning message: Error in data.frame(..., check.names = FALSE) : Arguments imply differing numbers of rows: 64, 0

2.

```<code>plantsp <- !is.na(over(pts, as(plant, "SpatialPolygons")))
pts$plant <- over(pts, plant)$Unit_Name
</code>```

Resulting the the warning message: Error in validObject(.Object) : invalid class “SpatialPointsDataFrame”: number of rows in data.frame and SpatialPoints don't match

So, both possibilities fail and I do not know what I did wrong. I know, that for this distribution range, only two points are inside the range, is the the source of the trouble? And how may I fix this? I would be so thankful, if anyone could tell me, how to get this cvs Table, containing the presence/absense information for the distribution ranges for every point!

答:
I think this problem will be easier to solve with rgdal or sf (I recommend learning sf, as it's newer, but for now I'm more familiar with rgdal which is why I've used it here).

Load rgdal (which also loads sp, which we'll need):

```<code>library("rgdal")

# Open the shapefile and copy the projection,
# which we'll need for the bird data

plant <- readOGR(".", "N_columbiana")
wgs84 <- proj4string(plant)

# open the bird data and make a copy for when we change to
# spatialPointsDataFrame

birds <- read.csv2("bird_Coordinates.csv")
birds_data <- birds

# Correct the order of long/lat so the coordinates are correct
birds <- birds[, c("lon", "lat")]
birds <- sp::SpatialPointsDataFrame(birds, birds_data,
                                    proj4string = CRS(wgs84))

# plot to make sure it's worked
plot(plant)
plot(birds, add = TRUE)

# the @data slot is now a data frame for the shapefile
# make all in_plant 0 by default before we subset
birds@data$in_plant <- 0

# Get the specimenID of those birds within the plant boundary
# the birds[plant, ] does the subsetting
# the @data$SpecimenID returns just the specimenID
in_plant <- birds[plant, ]@data$SpecimenID
birds@data$in_plant[in_plant] <- 1

# check it's all worked
plot(plant)
plot(birds[birds@data$in_plant == 1, ], add = TRUE)
</code>```

If you want to extract just the data you can assign it to another object:

```<code>new_data <- birds@data
new_data
#     SpecimenID      lat         lon in_plant
#  1           1 46.06667    7.600000        0
#  2           2 46.60134    9.965973        0
#  3           3 46.02360    7.748607        0
#  4           4 46.60134    9.965973        0
#  5           5 46.91833   13.873611        0
#  ...
#  48         48 40.01861 -105.278056        1
#  49         49 40.02977 -105.581228        1
#  50         50 47.05917   13.615556        0
</code>```

Body:
I want to create a tables using R that contain the information, if plant species occur at specific points (coordinates). Therefore, I want to use shapefiles, containing the distribution of several specific plant species. My output has to be a table, that for every point/coordinate indicate the presence of every plant species as 1 and the absence as 0.

First, I read in my first shapefile and the CVS table, containing the coordinates I need:

plant <- shapefile ('plant.shp')
birds<-read.csv2("bird_Coordinates.csv")

Next, I extract the coordinates, save them in a dataframe and project the points over the distribution shapefile:

lats <- birds$lat
lons <- birds$lon
pts <- data.frame(x=lons,y=lats)
coordinates(pts) <- ~x+y
proj4string(pts) <- proj4string(plant)

When I now plot the shapefile and the coordinates, I see the shape of the plant distribution and two red points, which indicate that two of my about 60 points are within this distribution:

plot(plant)
points(pts, pch=20, col='red')

Next, I try to use over, to associate the points to the distribution. Here I used two different ways:

1.

over(pts, plant)$admin
cbind.data.frame(pts, plant=over(pts, plant)$admin)

Resulting in the warning message: Error in data.frame(..., check.names = FALSE) : Arguments imply differing numbers of rows: 64, 0

2.

plantsp <- !is.na(over(pts, as(plant, "SpatialPolygons")))
pts$plant <- over(pts, plant)$Unit_Name

Resulting the the warning message: Error in validObject(.Object) : invalid class “SpatialPointsDataFrame”: number of rows in data.frame and SpatialPoints don't match

So, both possibilities fail and I do not know what I did wrong. I know, that for this distribution range, only two points are inside the range, is the the source of the trouble? And how may I fix this? I would be so thankful, if anyone could tell me, how to get this cvs Table, containing the presence/absense information for the distribution ranges for every point!

Body:
I think this problem will be easier to solve with rgdal or sf (I recommend learning sf, as it's newer, but for now I'm more familiar with rgdal which is why I've used it here).

Load rgdal (which also loads sp, which we'll need):

library("rgdal")

# Open the shapefile and copy the projection,
# which we'll need for the bird data

plant <- readOGR(".", "N_columbiana")
wgs84 <- proj4string(plant)

# open the bird data and make a copy for when we change to
# spatialPointsDataFrame

birds <- read.csv2("bird_Coordinates.csv")
birds_data <- birds

# Correct the order of long/lat so the coordinates are correct
birds <- birds[, c("lon", "lat")]
birds <- sp::SpatialPointsDataFrame(birds, birds_data,
                                    proj4string = CRS(wgs84))

# plot to make sure it's worked
plot(plant)
plot(birds, add = TRUE)

# the @data slot is now a data frame for the shapefile
# make all in_plant 0 by default before we subset
birds@data$in_plant <- 0

# Get the specimenID of those birds within the plant boundary
# the birds[plant, ] does the subsetting
# the @data$SpecimenID returns just the specimenID
in_plant <- birds[plant, ]@data$SpecimenID
birds@data$in_plant[in_plant] <- 1

# check it's all worked
plot(plant)
plot(birds[birds@data$in_plant == 1, ], add = TRUE)

If you want to extract just the data you can assign it to another object:

new_data <- birds@data
new_data
#     SpecimenID      lat         lon in_plant
#  1           1 46.06667    7.600000        0
#  2           2 46.60134    9.965973        0
#  3           3 46.02360    7.748607        0
#  4           4 46.60134    9.965973        0
#  5           5 46.91833   13.873611        0
#  ...
#  48         48 40.01861 -105.278056        1
#  49         49 40.02977 -105.581228        1
#  50         50 47.05917   13.615556        0


问:
Regex to extract attribute from html element
Text from stream:

```<code><option value=\"1999\">1999</option>\r\n    \r\n \r\n\r\n  \r\n\r\
    n
<option value=\"2000\">2000</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2001\">2001</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2002\">2002</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2003\">2003</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2004\">2004</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2005\">2005</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2006\">2006</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2007\">2007</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2008\">2008</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2009\">2009</option>
</code>```

Regex: (?si:<option value=\\\"(?<year>.*?)\\) shouldn't this be the right way to get the year?. meaning for year group, get all characters as long as you don't hit \

Body:
Text from stream:

<option value=\"1999\">1999</option>\r\n    \r\n \r\n\r\n  \r\n\r\
    n
<option value=\"2000\">2000</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2001\">2001</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2002\">2002</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2003\">2003</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2004\">2004</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2005\">2005</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2006\">2006</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2007\">2007</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2008\">2008</option>\r\n    \r\n \r\n\r\n  \r\n\r\n
<option value=\"2009\">2009</option>

Regex: (?si:<option value=\\\"(?<year>.*?)\\) shouldn't this be the right way to get the year?. meaning for year group, get all characters as long as you don't hit \

Body:
It depends exactly what language you're using, but try <option\s+value=(\\\")?(\d+)(\\\")?>.

Here's it working in Python:

>>> re.findall("<option\s+value=(\\\")?(\d+)(\\\")?>", text)
['1999', '2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009']


问:
NSStrikethroughStyleAttributeName , How to strike out the string in iOS 10.3?
I have used this line of code before release of iOS 10.3 ,and worked fine.

```<code>NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",strMRP,strOffer]];

[attributeString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:12] range:NSMakeRange(0, strMRP.length)];

[attributeString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:15] range:NSMakeRange(strMRP.length, strOffer.length+1)];

[attributeString addAttribute:NSStrikethroughStyleAttributeName
                        value:[NSNumber numberWithInteger: NSUnderlineStyleDouble]
                        range:NSMakeRange(0,strMRP.length)];
</code>```

But now it is stopped working ,is there any alternate way to do the strike out ?

答:
***You can pass it to function & Enjoy !!!

```<code>func customString(currentprice:String,oldPrice:String) -> NSMutableAttributedString{
        // 1
        let NewString = currentprice + "  " + oldPrice

        let string = NewString as NSString
        let attributedString = NSMutableAttributedString(string: string as String)

        // 2
        let firstAttributes = [NSForegroundColorAttributeName: UIColor(red: 238/255, green: 140/255, blue: 84/255, alpha: 1),NSBaselineOffsetAttributeName:1]
        let secondAttributes = [NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSStrikethroughStyleAttributeName: 1]

        // 3
        attributedString.addAttributes(firstAttributes, range: string.rangeOfString(currentprice))
        attributedString.addAttributes(secondAttributes, range: string.rangeOfString(oldPrice))

        return attributedString
    }
</code>```

and use like:

```<code>YourUILabel.attributedText   = customString("300", oldPrice: "400")
</code>```

Body:
I have used this line of code before release of iOS 10.3 ,and worked fine.

NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",strMRP,strOffer]];

[attributeString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:12] range:NSMakeRange(0, strMRP.length)];

[attributeString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:15] range:NSMakeRange(strMRP.length, strOffer.length+1)];

[attributeString addAttribute:NSStrikethroughStyleAttributeName
                        value:[NSNumber numberWithInteger: NSUnderlineStyleDouble]
                        range:NSMakeRange(0,strMRP.length)];

But now it is stopped working ,is there any alternate way to do the strike out ?

Body:
***You can pass it to function & Enjoy !!!

func customString(currentprice:String,oldPrice:String) -> NSMutableAttributedString{
        // 1
        let NewString = currentprice + "  " + oldPrice

        let string = NewString as NSString
        let attributedString = NSMutableAttributedString(string: string as String)

        // 2
        let firstAttributes = [NSForegroundColorAttributeName: UIColor(red: 238/255, green: 140/255, blue: 84/255, alpha: 1),NSBaselineOffsetAttributeName:1]
        let secondAttributes = [NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSStrikethroughStyleAttributeName: 1]

        // 3
        attributedString.addAttributes(firstAttributes, range: string.rangeOfString(currentprice))
        attributedString.addAttributes(secondAttributes, range: string.rangeOfString(oldPrice))

        return attributedString
    }

and use like:

YourUILabel.attributedText   = customString("300", oldPrice: "400")


问:
Directory.EnumerateFiles returns 0 files in UWP
In my console application I use

```<code>var allFiles = Directory.EnumerateFiles(directoryPath, "*.*", SearchOption.AllDirectories).ToList();
</code>```

to return the path of each file in a folder (and in all sub-folders).

However in UWP, using the same thing returns 0

```<code>    FolderPicker folderPicker = new FolderPicker();
    folderPicker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
    folderPicker.FileTypeFilter.Add("*");
    StorageFolder pickedFolder = await folderPicker.PickSingleFolderAsync();
    var allFiles = Directory.EnumerateFiles(pickedFolder.Path, "*.*", SearchOption.AllDirectories).ToList();
</code>```

I've made a method that uses the GetFilesAsync() and GetFolderAsync() functions but it is no where near as quick as Directory.EnumerateFiles()

```<code> private async Task GetFilesInFolders(ObservableCollection<string> list, StorageFolder parent)
    {
        foreach (var file in await parent.GetFilesAsync())
        {
            list.Add(file.Path);
        }
        foreach (var folder in await parent.GetFoldersAsync())
        {
            await GetFilesInFolders(list, folder);
        }
    }
</code>```

Why does Directory.EnumerateFiles() returns 0 files?

答:
Unlike the traditional desktop application, UWP runs sandboxed and have very limited access to the file system.

By default the UWP can only access its Local Folder like the LocalFolder/InstallationFolder... or the files and folders in the user's Downloads folder that your app created, if apps need to access others fils, we may need to use capabilities or file picker. For more information, please see File access permissions

Why does Directory.EnumerateFiles() returns 0 files?

UWP app has no direct access to the folder by using the pickedFolder.Path if the pickedFolder is not in the app's local folder. If you pick the folder from the app's local folder, your code will work fine.

Besides, using the path in the UWP may not be a good practice, it does not work for the KnownFolders like the musiclibrary,videolibrary..as well. For more information, please refer to Rob's blog: Skip the path: stick to the StorageFile.

It is recommend to use a FolderPicker to let the user pick the folder and add it to your app's FutureAccessList or MostRecentlyUsedList, in this way the they can be reloaded later without requiring the user to go through the picker.  For more information, please check: How to track recently-used files and folders.

Body:
In my console application I use

var allFiles = Directory.EnumerateFiles(directoryPath, "*.*", SearchOption.AllDirectories).ToList();

to return the path of each file in a folder (and in all sub-folders).

However in UWP, using the same thing returns 0

    FolderPicker folderPicker = new FolderPicker();
    folderPicker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
    folderPicker.FileTypeFilter.Add("*");
    StorageFolder pickedFolder = await folderPicker.PickSingleFolderAsync();
    var allFiles = Directory.EnumerateFiles(pickedFolder.Path, "*.*", SearchOption.AllDirectories).ToList();

I've made a method that uses the GetFilesAsync() and GetFolderAsync() functions but it is no where near as quick as Directory.EnumerateFiles()

 private async Task GetFilesInFolders(ObservableCollection<string> list, StorageFolder parent)
    {
        foreach (var file in await parent.GetFilesAsync())
        {
            list.Add(file.Path);
        }
        foreach (var folder in await parent.GetFoldersAsync())
        {
            await GetFilesInFolders(list, folder);
        }
    }

Why does Directory.EnumerateFiles() returns 0 files?


问:
VS Code - how to document an object using JSDoc
I have a variable storage, that stores all elements of type Person. So basically it is a dictionary with key URL and value PersonInstance:

let storage = {}
storage["localhost.com/person/1"] = new Person("John Wick");
```

<p>Actually I could do it by writing:
</p>

```/**
 * @type {Object.<string, Person>}
 */
```

But VS Code Intellisense does not work in such case. Is there other way to document such object with unlimited number of keys in VS Code?

答:
I found that it is better to use Map instead of object. So basically you can write something like this

```<code>    /**
     * @type {Map<string, Person>}
     */
    let bsStorage = new Map();
</code>```

NOTE: And if you concern about older browsers, that do not support ES6, you can transpile using Babel.

Body:
I have a variable storage, that stores all elements of type Person. So basically it is a dictionary with key URL and value PersonInstance:

let storage = {}
storage["localhost.com/person/1"] = new Person("John Wick");

Actually I could do it by writing:

/**
 * @type {Object.<string, Person>}
 */

But VS Code Intellisense does not work in such case. Is there other way to document such object with unlimited number of keys in VS Code?

Body:
I found that it is better to use Map instead of object. So basically you can write something like this

    /**
     * @type {Map<string, Person>}
     */
    let bsStorage = new Map();

NOTE: And if you concern about older browsers, that do not support ES6, you can transpile using Babel.


问:
Golang strconv.ParseFloat fails to parse the string correctly when using 32 for bitSize parameter
Why the converted float64 variable has 1.590000033378601 as value?
1.59 seems small enough to be fitted into 32 bits:

```<code>package main

import (
    "fmt"
    "strconv"
)

func main() {
    str := `1.59`
    float, err := strconv.ParseFloat(str, 32)
    if err != nil {
        fmt.Println("err: ", err)
    }
    fmt.Printf("%T -> %+v\n", float, float)
}
</code>```

Go playground link

答:
The decimal number 1.59 look short, but that's only because we are using the decimal number system.

When the computer tries to represent the same number in binary scientific notation (a * 2^b) it requires a lot more fractional digits: 1.1001011100001010001111010111000010100011110101110001 * 2^0.

If you round this value to 32 bits, store it in a variable of type float32 and then print as decimal, you get 1.59, but storing the same rounded value in a float64 variable and printing as decimal, you get 1.590000033378601.

Function strconv.ParseFloat returns float64, but since you have specified 32 bits of precision, you are supposed to cast the value to float32 prior to using.

Body:
Why the converted float64 variable has 1.590000033378601 as value?
1.59 seems small enough to be fitted into 32 bits:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    str := `1.59`
    float, err := strconv.ParseFloat(str, 32)
    if err != nil {
        fmt.Println("err: ", err)
    }
    fmt.Printf("%T -> %+v\n", float, float)
}

Go playground link