问:
error C2011: 'SelectorBox' : 'class' type redefinition
I have a problem with a following code:

```<code> #ifndef HEADER_H_

    class SelectorBox{
    public:
        string selectorName;
        map < string, string > attributeMap;
        void setSelectorName(string name);
        void setAttribute(string key, string value);
    };
    string trimTheString(string str); //trimming a string
    #endif

//include libraries
#include "Header.h"
using namespace std;
int main()
{
    vector <SelectorBox> vectorSelectBox;
    SelectorBox *selectorBox;

//code
return 0;
}

#include "Header.h"
#include "main.cpp"

void SelectorBox::setSelectorName(string name)   //setter
{
    name = trimTheString(name);
    selectorName = name;
}

void SelectorBox::setAttribute(string key, string value)  //setter
{
    key = trimTheString(key);
    value = trimTheString(value);
    attributeMap[key] = value;
}
</code>```

When I compile a program, it shows many errors (specifically errors 4430 and 2061), but I believe that the main error is:
error C2011: 'SelectorBox' : 'class' type redefinition.

答:
You are including the same header twice, first before main second after main, this causes a problem if you don't use proper include guards.

Your include guard is incomplete, so multiple includes of the same header will cause this error. The trick is to check if a header-specific preprocessor name is defined: If not, then define it, else skip the whole header.

The pattern to use is like this

```<code>#ifndef GUARD
#define GUARD
/// the actual header contents
#endif
</code>```

but simply copying it into every header will cause another problem, because its lack of header specificity. The simplest way to find a good name is to derive it from the file name itself. In your case I'd name the header after the class SelectorBox defined in it, so SelectorBox.h would be a good name, and the include guards would look like this:

```<code>#ifndef SELECTORBOX_H
#define SELECTORBOX_H

class SelectorBox {
/// etc.
};

#endif
</code>```

Using multiple headers with the same include guard is much worse than using no include guards at all.

Body:
I have a problem with a following code:

 #ifndef HEADER_H_

    class SelectorBox{
    public:
        string selectorName;
        map < string, string > attributeMap;
        void setSelectorName(string name);
        void setAttribute(string key, string value);
    };
    string trimTheString(string str); //trimming a string
    #endif

//include libraries
#include "Header.h"
using namespace std;
int main()
{
    vector <SelectorBox> vectorSelectBox;
    SelectorBox *selectorBox;

//code
return 0;
}

#include "Header.h"
#include "main.cpp"

void SelectorBox::setSelectorName(string name)   //setter
{
    name = trimTheString(name);
    selectorName = name;
}

void SelectorBox::setAttribute(string key, string value)  //setter
{
    key = trimTheString(key);
    value = trimTheString(value);
    attributeMap[key] = value;
}

When I compile a program, it shows many errors (specifically errors 4430 and 2061), but I believe that the main error is:
error C2011: 'SelectorBox' : 'class' type redefinition.

Body:
You are including the same header twice, first before main second after main, this causes a problem if you don't use proper include guards.

Your include guard is incomplete, so multiple includes of the same header will cause this error. The trick is to check if a header-specific preprocessor name is defined: If not, then define it, else skip the whole header.

The pattern to use is like this

#ifndef GUARD
#define GUARD
/// the actual header contents
#endif

but simply copying it into every header will cause another problem, because its lack of header specificity. The simplest way to find a good name is to derive it from the file name itself. In your case I'd name the header after the class SelectorBox defined in it, so SelectorBox.h would be a good name, and the include guards would look like this:

#ifndef SELECTORBOX_H
#define SELECTORBOX_H

class SelectorBox {
/// etc.
};

#endif

Using multiple headers with the same include guard is much worse than using no include guards at all.


来源: stackexchange

问:
How to calculate the total number of passengers
I want to code to calculate the total number of adult, child and baby passengers. I tried with jquery but did not count the total number of all the passengers.

Thanks in advance

https://jsfiddle.net/devefrontend/21036h5c/12/

$("select").on('change', function() {
    var str = "";
    $(".passenger option:selected").each(function() {
        str += $(this).text() + " ";
    });
     $("#count").text(str);
}).change();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div class="form-group">
    <label>Dewasa <span id="count">0</span></label>
    <select name="adult" class="form-control passenger">
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
        <option>6</option>
    </select>
    <select name="child" class="form-control passenger">
        <option>0</option>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
        <option>6</option>
    </select>
    <select name="infant" class="form-control passenger">
        <option>0</option>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
        <option>6</option>
    </select>
</div></code>```

答:
You should convert the text of the selected option to an int value, and to do that use parseInt() function:

$("select").on('change', function() {
        var str = 0;
        $(".passenger option:selected").each(function() {
            str += parseInt($(this).text()) ;
        });
        $("#count").text(str);
    }).change();
    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div class="form-group">
                  <label>Dewasa <span id="count">0</span></label>
                  <select name="adult" class="form-control passenger">
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>5</option>
                    <option>6</option>
                  </select>
                  <select name="child" class="form-control passenger">
                    <option>0</option>
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>5</option>
                    <option>6</option>
                  </select>
                  <select name="infant" class="form-control passenger">
                    <option>0</option>
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>5</option>
                    <option>6</option>
                  </select>
                </div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to code to calculate the total number of adult, child and baby passengers. I tried with jquery but did not count the total number of all the passengers.

Thanks in advance

https://jsfiddle.net/devefrontend/21036h5c/12/

$("select").on('change', function() {
    var str = "";
    $(".passenger option:selected").each(function() {
        str += $(this).text() + " ";
    });
     $("#count").text(str);
}).change();

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    Dewasa 0
    <select name="adult" class="form-control passenger">
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
        <option>6</option>
    </select>
    <select name="child" class="form-control passenger">
        <option>0</option>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
        <option>6</option>
    </select>
    <select name="infant" class="form-control passenger">
        <option>0</option>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
        <option>6</option>
    </select>

Body:
You should convert the text of the selected option to an int value, and to do that use parseInt() function:

$("select").on('change', function() {
        var str = 0;
        $(".passenger option:selected").each(function() {
            str += parseInt($(this).text()) ;
        });
        $("#count").text(str);
    }).change();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div class="form-group">
                  <label>Dewasa <span id="count">0</span></label>
                  <select name="adult" class="form-control passenger">
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>5</option>
                    <option>6</option>
                  </select>
                  <select name="child" class="form-control passenger">
                    <option>0</option>
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>5</option>
                    <option>6</option>
                  </select>
                  <select name="infant" class="form-control passenger">
                    <option>0</option>
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>5</option>
                    <option>6</option>
                  </select>
                </div>


答:
You should convert the values to integer if you want to get the total. Update your Code as shown below.</p>

```<code>$("select").on('change', function() {
    var total = 0;
    $(".passenger option:selected").each(function() {
        total += parseInt($(this).val());
    });
    $("#count").text(total);
}).change();
</code>```

Title: How to calculate the total number of passengers

Body:
You should convert the values to integer if you want to get the total. Update your Code as shown below.

$("select").on('change', function() {
    var total = 0;
    $(".passenger option:selected").each(function() {
        total += parseInt($(this).val());
    });
    $("#count").text(total);
}).change();


答:
You were trying to add strings as numbers. The following code takes the textual values of the options and converts them to numbers.

$("select").on('change', function() {
        var count = 0;
        $(".passenger option:selected").each(function() {
            count += parseInt($(this).text());
        });
        $("#count").text(count);
    }).change();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>label {
  display:block;
  background:skyblue;
  color:#fff;
  padding:20px;
}</code>```

                  Dewasa 0
                  <select name="adult" class="form-control passenger">
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>5</option>
                    <option>6</option>
                  </select>
                  <select name="child" class="form-control passenger">
                    <option>0</option>
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>5</option>
                    <option>6</option>
                  </select>
                  <select name="infant" class="form-control passenger">
                    <option>0</option>
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>5</option>
                    <option>6</option>
                  </select>

```

https://jsfiddle.net/wn1phe51/

Body:
You were trying to add strings as numbers. The following code takes the textual values of the options and converts them to numbers.

$("select").on('change', function() {
        var count = 0;
        $(".passenger option:selected").each(function() {
            count += parseInt($(this).text());
        });
        $("#count").text(count);
    }).change();

label {
  display:block;
  background:skyblue;
  color:#fff;
  padding:20px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
                  <label>Dewasa <span id="count">0</span></label>
                  <select name="adult" class="form-control passenger">
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>5</option>
                    <option>6</option>
                  </select>
                  <select name="child" class="form-control passenger">
                    <option>0</option>
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>5</option>
                    <option>6</option>
                  </select>
                  <select name="infant" class="form-control passenger">
                    <option>0</option>
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>5</option>
                    <option>6</option>
                  </select>
                </div>

https://jsfiddle.net/wn1phe51/


问:
parsing a cv file
I want to write a code either in Java or PHP (Codeigniter) to extract information such as email and phone number of a user uploading hbis resume or cv to the site. Basically I want to build a cv parser.

Need help for this.

thanks

EDIT
The cv format will be in doc.

答:
Since there is no standard CV format, parsing will be next to impossible.

Instead, consider collecting contact information in an HTML form when they upload.

ContentLicense: CC BY-SA 2.5

Title: parsing a cv file


答:
You must define HEADER_H_. You missed second line from below code.

```<code>#ifndef HEADER_H_
#define HEADER_H_
...
#endif
</code>```

Title: error C2011: 'SelectorBox' : 'class' type redefinition

Body:
You must define HEADER_H_. You missed second line from below code.

#ifndef HEADER_H_
#define HEADER_H_
...
#endif


问:
python json.dumps()’s data is contain \, how to clean it
```<code>def getJson(filmList):
film_json = FilmJson()
for video in filmList:
    videoName = video.videoName
    videoUrl = video.videoUrl
    videoTime = video.videoTime
    dic = {}
    if videoName is None:
        break

    if videoUrl is None:
        dic['videourl'] = ""
    else:
        dic['videourl'] = videoUrl

    if videoTime is None:
        dic['videotime'] = ""
    else:
        dic['videotime'] = videoTime
    dic['videoname'] = videoName

    film_json.videolist.append(dic)

dict__ = film_json.__dict__
print(dict__)

return dict__
</code>```

The browser send get request

the backend print

```<code>{'filmid': '', 'videolist': [{'videourl': '', 'videotime': '', 'videoname': 'Lifeline'}, {'videourl': '', 'videotime': '', 'videoname': 'Ex Static'}, {'videourl': '', 'videotime': '', 'videoname': 'test'}]}
</code>```

.

```<code>@api_view(http_method_names=['GET'])
@permission_classes((permissions.AllowAny,))
def sendFilm(request):
   ....
    myjson = jsonbean.getJson(filmList)

    return Response(json.dumps(myjson,ensure_ascii=False))
</code>```

The postman test get result

```<code>"{\"filmid\": \"\", \"videolist\": [{\"videourl\": \"\", \"videotime\": \"\", \"videoname\": \"Lifeline\"}, {\"videourl\": \"\", \"videotime\": \"\", \"videoname\": \"Ex Static\"}, {\"videourl\": \"\", \"videotime\": \"\", \"videoname\": \"test\"}]}"
</code>```

how to resolve the  problem

答:
You have double dumped.

You just need to json.dumps() once. This error happens because you've json.dumps() on an object that is already a JSON.

return Response( myjson ) should return a regular object without the \".

Since myjson is already a JSON string and not a dictionary object.

Body:
def getJson(filmList):
film_json = FilmJson()
for video in filmList:
    videoName = video.videoName
    videoUrl = video.videoUrl
    videoTime = video.videoTime
    dic = {}
    if videoName is None:
        break

    if videoUrl is None:
        dic['videourl'] = ""
    else:
        dic['videourl'] = videoUrl

    if videoTime is None:
        dic['videotime'] = ""
    else:
        dic['videotime'] = videoTime
    dic['videoname'] = videoName

    film_json.videolist.append(dic)

dict__ = film_json.__dict__
print(dict__)

return dict__

The browser send get request

the backend print

{'filmid': '', 'videolist': [{'videourl': '', 'videotime': '', 'videoname': 'Lifeline'}, {'videourl': '', 'videotime': '', 'videoname': 'Ex Static'}, {'videourl': '', 'videotime': '', 'videoname': 'test'}]}

.

@api_view(http_method_names=['GET'])
@permission_classes((permissions.AllowAny,))
def sendFilm(request):
   ....
    myjson = jsonbean.getJson(filmList)

    return Response(json.dumps(myjson,ensure_ascii=False))

The postman test get result

"{\"filmid\": \"\", \"videolist\": [{\"videourl\": \"\", \"videotime\": \"\", \"videoname\": \"Lifeline\"}, {\"videourl\": \"\", \"videotime\": \"\", \"videoname\": \"Ex Static\"}, {\"videourl\": \"\", \"videotime\": \"\", \"videoname\": \"test\"}]}"

how to resolve the  problem


问:
Prolog facts of lists and a recursion predicate to accept permutations of lists
I have facts that accept certain lists. These lists are sorted.

```<code>acceptedList([1,2,3]).
acceptedList([4,5,6]).
acceptedList([7,8,9]).
</code>```

Now, I would like to accept any permutation of the accepted lists as well.
To do this, I would like to sort the input list and match it against the above facts.

I can solve this problem using a predicate whose name is not acceptedList, but I was wondering if this could be done in a recursive way.

Here is what I thought:

```<code>acceptedList(List) :-
    sort(List,SortedList),    % Sort the list to match against the facts.
    acceptedList(SortedList). % Match against the facts.
</code>```

My idea is that this predicate should accept input lists such as [3,2,1].
However, this seems to go in an infinite loop, and with my lackluster prolog knowledge, I need some help understanding why and whether it's possible to solve this problem using acceptedList facts and a predicate whose name is the same.

答:
Prolog has a library lists with a predicate permutation/2 that generates all permutations for a given list.

So wen can write:

```<code>acceptedList(Lb) :-
    acceptedList(La),
    permutation(La,Lb).
</code>```

But now we have a problem: this predicate will keep generating lists. Since after it has enumerated the facts it will fire the predicate defined above, and this will again enumerate permutations, so we will then yield permutations of permutations, permutations of permutations of permutations, etc. This is probably not what we want.

The solution to this, is to split the facts from the predicate. So we can rewrite acceptedList/1 to acceptedListFact/1:

```<code>acceptedList<b>Fact</b>([1,2,3]).
acceptedList<b>Fact</b>([4,5,6]).
acceptedList<b>Fact</b>([7,8,9]).

acceptedList(Lb) :-
    acceptedList<b>Fact</b>(La),
    permutation(La,Lb).</code>```

and we thus unify La with a list that is stated as a fact.

Now we obtain the following acceptedList/2s:

```<code>?- acceptedList(L).
L = [1, 2, 3] ;
L = [1, 3, 2] ;
L = [2, 1, 3] ;
L = [2, 3, 1] ;
L = [3, 1, 2] ;
L = [3, 2, 1] ;
L = [4, 5, 6] ;
L = [4, 6, 5] ;
L = [5, 4, 6] ;
L = [5, 6, 4] ;
L = [6, 4, 5] ;
L = [6, 5, 4] ;
L = [7, 8, 9] ;
L = [7, 9, 8] ;
L = [8, 7, 9] ;
L = [8, 9, 7] ;
L = [9, 7, 8] ;
L = [9, 8, 7] ;
false.
</code>```

Body:
I have facts that accept certain lists. These lists are sorted.

acceptedList([1,2,3]).
acceptedList([4,5,6]).
acceptedList([7,8,9]).

Now, I would like to accept any permutation of the accepted lists as well.
To do this, I would like to sort the input list and match it against the above facts.

I can solve this problem using a predicate whose name is not acceptedList, but I was wondering if this could be done in a recursive way.

Here is what I thought:

acceptedList(List) :-
    sort(List,SortedList),    % Sort the list to match against the facts.
    acceptedList(SortedList). % Match against the facts.

My idea is that this predicate should accept input lists such as [3,2,1].
However, this seems to go in an infinite loop, and with my lackluster prolog knowledge, I need some help understanding why and whether it's possible to solve this problem using acceptedList facts and a predicate whose name is the same.

Body:
Prolog has a library lists with a predicate permutation/2 that generates all permutations for a given list.

So wen can write:

acceptedList(Lb) :-
    acceptedList(La),
    permutation(La,Lb).

But now we have a problem: this predicate will keep generating lists. Since after it has enumerated the facts it will fire the predicate defined above, and this will again enumerate permutations, so we will then yield permutations of permutations, permutations of permutations of permutations, etc. This is probably not what we want.

The solution to this, is to split the facts from the predicate. So we can rewrite acceptedList/1 to acceptedListFact/1:

acceptedListFact([1,2,3]).
acceptedListFact([4,5,6]).
acceptedListFact([7,8,9]).

acceptedList(Lb) :-
    acceptedListFact(La),
    permutation(La,Lb).

and we thus unify La with a list that is stated as a fact.

Now we obtain the following acceptedList/2s:

?- acceptedList(L).
L = [1, 2, 3] ;
L = [1, 3, 2] ;
L = [2, 1, 3] ;
L = [2, 3, 1] ;
L = [3, 1, 2] ;
L = [3, 2, 1] ;
L = [4, 5, 6] ;
L = [4, 6, 5] ;
L = [5, 4, 6] ;
L = [5, 6, 4] ;
L = [6, 4, 5] ;
L = [6, 5, 4] ;
L = [7, 8, 9] ;
L = [7, 9, 8] ;
L = [8, 7, 9] ;
L = [8, 9, 7] ;
L = [9, 7, 8] ;
L = [9, 8, 7] ;
false.


问:
COMException (0x80040154): Class not registered when using AxAcroPDFLib
I am getting following error when using AxAcroPDF

System.Runtime.InteropServices.COMException (0x80040154): Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

The line which throws error is

```<code>((System.ComponentModel.ISupportInitialize)(this.axAcroPDF1)).EndInit();
</code>```

If anyone knows the solution please help

答: I have the similar error they are gone after I am install Adobe Reader on my PC.</p>

Body:
I am getting following error when using AxAcroPDF

System.Runtime.InteropServices.COMException (0x80040154): Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

The line which throws error is

((System.ComponentModel.ISupportInitialize)(this.axAcroPDF1)).EndInit();

If anyone knows the solution please help


问:
Can't extract data from Json
I can't extract data from json that I got from an api.
I tried for hours, tried all kinds of formats. Read Stackoverflow threads like How do I extract data from JSON with PHP?, but I can't see what I am doing wrong.

This is the code so far:

```<code>$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';

$results = json_decode($api_results, true);

// Some variations I tried:
var_dump($results->status[1]);
var_dump($results->data[1]->opening_price);
var_dump($results["data"][1]["opening_price"]);
</code>```

End result: NULL NULL NULL

What am I doing wrong?

Thanks for the answers! I will upvote the working ones. Seems I got confused in the formating!

答:
You have set the second parameter of json_decode() to true. that means the json will be converted to an array so you are not able to access the data using pointer -> (because it is not an object).

You may access the data like this:

```<code>var_dump($results['status'][0]);
var_dump($results['data'][0]['opening_price']);
</code>```

P.S: Try var_dump($results) to see the exact data, so you know how to access each attribute.

Title: Can't extract data from Json

Body:
I can't extract data from json that I got from an api.
I tried for hours, tried all kinds of formats. Read Stackoverflow threads like How do I extract data from JSON with PHP?, but I can't see what I am doing wrong.

This is the code so far:

$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';

$results = json_decode($api_results, true);

// Some variations I tried:
var_dump($results->status[1]);
var_dump($results->data[1]->opening_price);
var_dump($results["data"][1]["opening_price"]);

End result: NULL NULL NULL

What am I doing wrong?

Thanks for the answers! I will upvote the working ones. Seems I got confused in the formating!

Body:
You have set the second parameter of json_decode() to true. that means the json will be converted to an array so you are not able to access the data using pointer -> (because it is not an object).

You may access the data like this:

var_dump($results['status'][0]);
var_dump($results['data'][0]['opening_price']);

P.S: Try var_dump($results) to see the exact data, so you know how to access each attribute.


问:
How do i read image using PILLOW image?
I wanted read a image using PIL.Image.open().But I've image in different path.
The following is the path I've the python script

```<code>"D:\YY_Aadhi\holy-edge-master\hed\test.py"
</code>```

The following is the path I've the image file.

```<code>"D:\YY_Aadhi\HED-BSDS\test\2018.jpg"

from PIL import Image
'''some code here'''
image = Image.open(????)
</code>```

How should I fill the question mark to access the image file.

答:
you can simply do

```<code>from PIL import Image
image = Image.open("D:\\YY_Aadhi\\HED-BSDS\\test\\2018.jpg")
</code>```

or

```<code>from PIL import Image
directory = "D:\\YY_Aadhi\\HED-BSDS\\test\\2018.jpg"
image = Image.open(directory)
</code>```

like this.

you have to write escape sequence twice in windows, when you want to define as directory. and It will be great if you try some stupid code. It helps you a lot.

Title: How do i read image using PILLOW image?

Body:
I wanted read a image using PIL.Image.open().But I've image in different path.
The following is the path I've the python script

"D:\YY_Aadhi\holy-edge-master\hed\test.py"

The following is the path I've the image file.

"D:\YY_Aadhi\HED-BSDS\test\2018.jpg"

from PIL import Image
'''some code here'''
image = Image.open(????)

How should I fill the question mark to access the image file.

Body:
you can simply do

from PIL import Image
image = Image.open("D:\\YY_Aadhi\\HED-BSDS\\test\\2018.jpg")

or

from PIL import Image
directory = "D:\\YY_Aadhi\\HED-BSDS\\test\\2018.jpg"
image = Image.open(directory)

like this.

you have to write escape sequence twice in windows, when you want to define as directory. and It will be great if you try some stupid code. It helps you a lot.


问:
Rendering optimization using nested state in React
I have a React app where I believe -though not certain- that "nested state" causes me delays.

Here's the thing:

I keep my state in a variable called dataset.

dataset is an array of objects like this:

```<code>(5) [{…}, {…}, {…}, {…}, {…}]
</code>```

and each object has the following structure:

```<code>{id: '5', name: 'Bob', url: 'http://example.com', paid: 'yes'}
</code>```

Finally my render method displays the data in a table:

...
{dataset.map((entry) => (
    ...

{entry.name} has paid: {entry.paid}

    ...
))}
```

<p>It all seems to be working fine but then whenever I need to update the state because presumably user number 5 didn't pay this month I do this:</p>

<pre class="lang-js prettyprint-override"><code>// copy current state
let new_dataset = this.state.dataset.slice();

// modify the copy
new_dataset[5].paid = !this.state.dataset[5].paid;

// replace old state with the modified copy
this.setState({
    dataset: new_dataset
});
</code>```

However here's the problem:

Will React update all 5 rows or just the row holding the object I modified?

Wouldn't it be a waste to have react update 10000 rows just for a small change in one row? What's the best practice for such scenarios?

Thanks in advance.

P.S. I have already looked at how to Avoid Reconciliation but I'm not sure how to apply in this case.

答:
Will React update all 5 rows or just the row holding the object I modified?

It will only update the DOM with what's been changed, however it will still iterate through all your items in your dataset array. The iteration as well as the reconciliation process itself would take time if there are that many items in your array.

So the problem here isn't really the implementation per se - it's a very common approach for small to medium sized arrays. However, if you indeed have large entries in your array, you may notice performance hits, in which case you might want to find a different implementation.

That said, I did find a minor error in your code:

You correctly create a copy of your array with this.state.dataset.slice(); however you are not creating a copy of the object that you are mutating. So essenatially you are mutating the state directly. So instead do:

```<code>// copy current state
let new_dataset = this.state.dataset.slice();

// copy the object
let obj = Object.assign({}, new_dataset[5]);

// modify the copy
obj.paid = !obj.paid;

// replace the array item with the new object
new_dataset[5] = obj;
</code>```

Body:
I have a React app where I believe -though not certain- that "nested state" causes me delays.

Here's the thing:

I keep my state in a variable called dataset.

dataset is an array of objects like this:

(5) [{…}, {…}, {…}, {…}, {…}]

and each object has the following structure:

{id: '5', name: 'Bob', url: 'http://example.com', paid: 'yes'}

Finally my render method displays the data in a table:

...
{dataset.map((entry) => (
    ...

{entry.name} has paid: {entry.paid}

    ...
))}

It all seems to be working fine but then whenever I need to update the state because presumably user number 5 didn't pay this month I do this:

// copy current state
let new_dataset = this.state.dataset.slice();

// modify the copy
new_dataset[5].paid = !this.state.dataset[5].paid;

// replace old state with the modified copy
this.setState({
    dataset: new_dataset
});

However here's the problem:

Will React update all 5 rows or just the row holding the object I modified?

Wouldn't it be a waste to have react update 10000 rows just for a small change in one row? What's the best practice for such scenarios?

Thanks in advance.

P.S. I have already looked at how to Avoid Reconciliation but I'm not sure how to apply in this case.

Body:
Will React update all 5 rows or just the row holding the object I modified?

It will only update the DOM with what's been changed, however it will still iterate through all your items in your dataset array. The iteration as well as the reconciliation process itself would take time if there are that many items in your array.

So the problem here isn't really the implementation per se - it's a very common approach for small to medium sized arrays. However, if you indeed have large entries in your array, you may notice performance hits, in which case you might want to find a different implementation.

That said, I did find a minor error in your code:

You correctly create a copy of your array with this.state.dataset.slice(); however you are not creating a copy of the object that you are mutating. So essenatially you are mutating the state directly. So instead do:

// copy current state
let new_dataset = this.state.dataset.slice();

// copy the object
let obj = Object.assign({}, new_dataset[5]);

// modify the copy
obj.paid = !obj.paid;

// replace the array item with the new object
new_dataset[5] = obj;


问:
Simplest server to server authentication
I have microservice on a new server/vps that will only ever be called via REST by monolith app to perform some heavy lifting and then post the operation results back to the monolith in few minutes.

How should I protect these two endpoints? I think my main goal, for now, is just preventing someone that found servers address to be able to do anything.

Almost every solution I google seems like overkill/premature optimization.

Is it sufficient that I generate random long token once on each machine and then just pass it to headers and check it's presence on the other end?

Do I even need to SSL this? As far as I understand we need SSL encryption for clients that are trying to send sensitive data via wireless or unsafe shared networks.

What are the chances(is it even possible?) that somebody is gonna eavesdrop between two digitalocean vps's sending data via http? Did it ever happen before ?

答:
There's a few simple solutions you could use to authenticate both servers back and forth. The one I would recommend if you want to keep it simple, as you say, is Basic Auth. As long as you're utilizing that over an SSL/HTTPS connection, it suffices as a super simple way to authenticate each end.

You state it is your main goal to protect these endpoints, but then ask if SSL/HTTP is even needed. If these servers are vulnerable to the web in any way, then I would say yes, your endpoints need to be protected, and if you're transmitting sensitive data, then you need to be sending it through a secure stream.

If you believe the data you're sending is not very sensitive, and is likely that no one that knows these two endpoints will even know how to properly manipulate your data by sending fake requests, then sure, you don't need any of this, but then you assume the risk and responsibility for if and when it ever is exposed. Basic Auth is super easy, and with LetsEncrypt it's incredibly easy to obtain an SSL certificate for free. It's good experience, so may as well try it out and protect these endpoints and ensure that they're safe.


问:
Php header location redirect not working
No idea why this is not working. Here is the code:

```<code>if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
    header('Location: page1.php');
    echo $_POST['cancel'];
}
</code>```

Instead of redirecting the page, this output's cancel to the webpage. It skipped over the redirect. Why? How can I fix this? page1.php is a real page located in the same folder as the current page. The above code is the very first lines of the php file. Nothing before it. Nothing. Not even whitespace.

答: Make Sure that you don't leave a space before <?php when you start <?php tag at the top of the page.

Body:
No idea why this is not working. Here is the code:

if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
    header('Location: page1.php');
    echo $_POST['cancel'];
}

Instead of redirecting the page, this output's cancel to the webpage. It skipped over the redirect. Why? How can I fix this? page1.php is a real page located in the same folder as the current page. The above code is the very first lines of the php file. Nothing before it. Nothing. Not even whitespace.


问:
Javascript adding zeros to the beginning of a string (max length 4 chars)
```<code>var number = 1310;
</code>```

should be left alone.

```<code>var number = 120;
</code>```

should be changed to "0120";

```<code>var number = 10;
</code>```

should be changed to "0010";

```<code>var number = 7;
</code>```

should be changed to "0007";

答:
```<code>function pad(n, len) {
  return (new Array(len + 1).join('0') + n).slice(-len);
}
</code>```

might not work in old IE versions.

Body:
var number = 1310;

should be left alone.

var number = 120;

should be changed to "0120";

var number = 10;

should be changed to "0010";

var number = 7;

should be changed to "0007";

Body:
function pad(n, len) {
  return (new Array(len + 1).join('0') + n).slice(-len);
}

might not work in old IE versions.


问:
applescript keystroke: right command and right control keys?
In Applescript, how can I send the keystroke for the right control key on the keyboard? How about right command key? Ultimately, I want to right-click in WINE (winehq's FAQ explains that's not currently possible with ctrl+click). But, it works great via KeyRemap4MacBook, although I need to send the right key. </p>

```<code>tell application "System Events" to key code ???????
</code>```

答:
For the right control it is:</p>

```<code>tell application "system events"
key code 62
end tell
</code>```

Body:
In Applescript, how can I send the keystroke for the right control key on the keyboard? How about right command key? Ultimately, I want to right-click in WINE (winehq's FAQ explains that's not currently possible with ctrl+click). But, it works great via KeyRemap4MacBook, although I need to send the right key.

tell application "System Events" to key code ???????

Body:
For the right control it is:

tell application "system events"
key code 62
end tell


问:
React:Do I make one line html as component or not?
Suppose I have one p tag which is used(with different class) so many times in web pages. So should I make it component or not?

If I make it component, then in future if I have to wrapped it inside suppose div tag then I only have to make changes as one place, otherwise I have to change it at every place.

Suppose I have 50 p tag in my parent component and if I make p tag component and use at wherever needed, then for all 50 time it will call that component(p tag component) which can be avoid if directly use p tag(which is I guess good for performance compare to former one).

答:
It really depends on the project and your uses. In general, there is no reason to wrap native elements into a component.

What do you want to achieve by having a paragraph component? If it's different classes on every P tag, why not pass down a prop from the parent component into the wrapper of the P tag, and in the P tag you can do something like:

```<code><p className={this.props.className + "-specialParagraph"}>Foo</p>
</code>```

That way, you can have a special class for every P tag without making an actual component out of it.

But as I said, it really depends on what you want to achieve.

Body:
It really depends on the project and your uses. In general, there is no reason to wrap native elements into a component.

What do you want to achieve by having a paragraph component? If it's different classes on every P tag, why not pass down a prop from the parent component into the wrapper of the P tag, and in the P tag you can do something like:

<p className={this.props.className + "-specialParagraph"}>Foo</p>

That way, you can have a special class for every P tag without making an actual component out of it.

But as I said, it really depends on what you want to achieve.


问:
MySQL Daemon failed to start on CentOS 6 Server
Whenever I try to start the SQLD service I get MySQL Daemon Failed to Start. I infact tried to "start" the service by doing the following:

```<code>[root@www1 ~]# service mysqld restart
mysqld stopped:                                            [  OK  ]
MySQL Daemon failed to start.
mysqld started:                                            [FAILED]
[root@www1 ~]#
</code>```

In my MySQL error log isnt any information the last entry is:

```<code>170314  3:24:59 [Note] /usr/libexec/mysqld: Normal shutdown

170314  3:24:59 [Note] Event Scheduler: Purging the queue. 0 events
170314  3:25:01 [Warning] /usr/libexec/mysqld: Forcing close of thread 1605619  user: 'admin'

170314  3:25:01 [Warning] /usr/libexec/mysqld: Forcing close of thread 1605617  user: 'admin'
170314  3:25:01 [Warning] /usr/libexec/mysqld: Forcing close of thread 13  user: 'admin'

170314  3:25:06  InnoDB: Starting shutdown...
170314  3:25:08  InnoDB: Waiting for 35 pages to be flushed
170314  3:25:46  InnoDB: Shutdown completed; log sequence number 26624434202
170314  3:25:47 [Note] /usr/libexec/mysqld: Shutdown complete

170314 03:25:50 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended
</code>```

I've tried to start mysql in safemode

```<code>[root@www1 log]# mysqld_safe
170314 09:36:39 mysqld_safe Logging to '/var/log/mysqld.log'.
170314 09:36:39 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
170314 09:36:39 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended
[root@www1 log]#
</code>```

SELinux is disabled on my centos maschine. Can anyone help me?
EDIT: There is no update last night.

答:
This command worked for me. Run this command.</p>

```<code>sudo service httpd restart
</code>```

Body:
Whenever I try to start the SQLD service I get MySQL Daemon Failed to Start. I infact tried to "start" the service by doing the following:

[root@www1 ~]# service mysqld restart
mysqld stopped:                                            [  OK  ]
MySQL Daemon failed to start.
mysqld started:                                            [FAILED]
[root@www1 ~]#

In my MySQL error log isnt any information the last entry is:

170314  3:24:59 [Note] /usr/libexec/mysqld: Normal shutdown

170314  3:24:59 [Note] Event Scheduler: Purging the queue. 0 events
170314  3:25:01 [Warning] /usr/libexec/mysqld: Forcing close of thread 1605619  user: 'admin'

170314  3:25:01 [Warning] /usr/libexec/mysqld: Forcing close of thread 1605617  user: 'admin'
170314  3:25:01 [Warning] /usr/libexec/mysqld: Forcing close of thread 13  user: 'admin'

170314  3:25:06  InnoDB: Starting shutdown...
170314  3:25:08  InnoDB: Waiting for 35 pages to be flushed
170314  3:25:46  InnoDB: Shutdown completed; log sequence number 26624434202
170314  3:25:47 [Note] /usr/libexec/mysqld: Shutdown complete

170314 03:25:50 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended

I've tried to start mysql in safemode

[root@www1 log]# mysqld_safe
170314 09:36:39 mysqld_safe Logging to '/var/log/mysqld.log'.
170314 09:36:39 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
170314 09:36:39 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended
[root@www1 log]#

SELinux is disabled on my centos maschine. Can anyone help me?
EDIT: There is no update last night.

Body:
This command worked for me. Run this command.

sudo service httpd restart


问:
Prevent new line in VS code after formatting
I want the a tag to be in the same line of the li tag here. what setting do i need to change in VS code to fix it.

答:
You need to install the Beautify plugin and create/edit the .jsbeautifyrc file with the settings you require.

The VSCodeBeautify file settings are here which include HTML options, see:

Setting = unformatted, Formatter = HTML, "a" for a link.

So install the plugin, then create the .jsbeautifyrc file and put it in the root of your working directory:

```<code>{
    "html": {
        "unformatted": ["a"] // List of tags that should not be reformatted
    }
}
</code>```

Body:
You need to install the Beautify plugin and create/edit the .jsbeautifyrc file with the settings you require.

The VSCodeBeautify file settings are here which include HTML options, see:

Setting = unformatted, Formatter = HTML, "a" for a link.

So install the plugin, then create the .jsbeautifyrc file and put it in the root of your working directory:

{
    "html": {
        "unformatted": ["a"] // List of tags that should not be reformatted
    }
}


答:
Here if you multilpy by 1, then it implicility convert string(which is number) to number : tot = $(this).text() * 1;

     $("select").on('change', function () {
        var str = 0;
        var tot = 0;
        $(".passenger option:selected").each(function () {
            tot = $(this).text() * 1;
            str = str + tot;
        });
        $("#count").text(str);
    }).change();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div class="form-group">
                  <label>Dewasa <span id="count">0</span></label>
                  <select name="adult" class="form-control passenger">
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>5</option>
                    <option>6</option>
                  </select>
                  <select name="child" class="form-control passenger">
                    <option>0</option>
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>5</option>
                    <option>6</option>
                  </select>
                  <select name="infant" class="form-control passenger">
                    <option>0</option>
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>5</option>
                    <option>6</option>
                  </select>
                </div></code>```

Body:
I want to code to calculate the total number of adult, child and baby passengers. I tried with jquery but did not count the total number of all the passengers.

Thanks in advance

https://jsfiddle.net/devefrontend/21036h5c/12/

$("select").on('change', function() {
    var str = "";
    $(".passenger option:selected").each(function() {
        str += $(this).text() + " ";
    });
     $("#count").text(str);
}).change();

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    Dewasa 0
    <select name="adult" class="form-control passenger">
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
        <option>6</option>
    </select>
    <select name="child" class="form-control passenger">
        <option>0</option>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
        <option>6</option>
    </select>
    <select name="infant" class="form-control passenger">
        <option>0</option>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
        <option>6</option>
    </select>

Body:
Here if you multilpy by 1, then it implicility convert string(which is number) to number : tot = $(this).text() * 1;

     $("select").on('change', function () {
        var str = 0;
        var tot = 0;
        $(".passenger option:selected").each(function () {
            tot = $(this).text() * 1;
            str = str + tot;
        });
        $("#count").text(str);
    }).change();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div class="form-group">
                  <label>Dewasa <span id="count">0</span></label>
                  <select name="adult" class="form-control passenger">
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>5</option>
                    <option>6</option>
                  </select>
                  <select name="child" class="form-control passenger">
                    <option>0</option>
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>5</option>
                    <option>6</option>
                  </select>
                  <select name="infant" class="form-control passenger">
                    <option>0</option>
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>5</option>
                    <option>6</option>
                  </select>
                </div>


问:
C#/ASP.NET Oledb - MS Excel read "Unspecified error"
We have a C#/ASP.NET (2.0) application running on IIS 6 on Windows Server 2003 Enterprise Edition. This application reads Excel files using OleDb, but there are instances when we get an "Unspecified Error" exception thrown from within the application.

The file is stored in the temporary directory by our file upload code before opening. Since we have anonymous access enabled in IIS and since we also use impersonation in web.config, the folder C:\Windows\Temp\ has the proper permissions for the Internet Guest User Account (IUSR_[MachineName]) to be able to create, modify and delete files there.

OleDb connection string:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Windows\Temp\tmp123.tmp.xls;

Extended Properties="Excel 8.0;HDR=Yes;IMEX=1;"

[The "Data Source" attribute above would change for every file.]

```
The stack trace of the exception is:
    System.Exception: FileParsingFailed ---> System.Data.OleDb.OleDbException:
    Unspecified error at
    System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr,
    OleDbConnection connection) at
    System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options,
    Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject) at
    System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection
    owningConnection, DbConnectionPoolGroup poolGroup) at
    System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection
    owningConnection) at
    System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection
    outerConnection, DbConnectionFactory connectionFactory) at
    System.Data.OleDb.OleDbConnection.Open()

```

Workaround:

So far, the only workaround we could come up with was to do an iisreset (we also have application pool recycling configured to happen once everyday in IIS, but it doesn't seem to help since the issue sometimes persists over several consecutive days). While this is not a good thing to do, what makes it worse is that we have other applications on the same web site that would get impacted whenever we reset IIS.

The questions:

1. How do we resolve this error since it happens occasionally and we don't see a pattern?

2. Are there any better (and free) ways of processing Excel files from C#/ASP.NET apart from OleDb? (We prefer not to install MS Office on the servers since it's not recommended by Microsoft)

Our limitations:

1. We're stuck with the MS Office 2003 (.xls) format and cannot move to the MS Office 2007 (OOXML) format.

2. The reasons we don't use CSV are because we may have commas within our data (this is a pain to deal with even if we use quoting) and we also use multiple worksheets in our spreadsheet (this cannot be done with CSV).

Thanks! :)

Update:

Thanks, Keith. It does seem like an issue with the Jet engine, but we use it because of the lack of (free and easy to use) alternatives.

Thanks, Joe. But we're on a limited budget - so we're mainly looking for free tools/libraries.

答:
I suspect the error is something to do with the venerable Jet OLEDB engine. It's fairly creaky - fine for most desktop things but not much use for enterprise data interchange.

If you can upgrade to a recent C# 3/.Net 3.5 you can use the System.IO.Packaging library to open Office 2007 files (.xlsx or .xlsm files).

These files are actually zips - rename them to .zip and you can just view the XML files inside.

The XML files' formats are fairly horrible (for instance cell comments are VML, ugh!) but readable.

Alternatively get your users to save the Excel tables as CSVs. I'd avoid the Microsoft text driver DB provider though - it's rubbish and can't handle unicode. CSVs are easy to read anyway.

OwnerDisplayName: MM

LastEditorDisplayName: MM

Body:
We have a C#/ASP.NET (2.0) application running on IIS 6 on Windows Server 2003 Enterprise Edition. This application reads Excel files using OleDb, but there are instances when we get an "Unspecified Error" exception thrown from within the application.

The file is stored in the temporary directory by our file upload code before opening. Since we have anonymous access enabled in IIS and since we also use impersonation in web.config, the folder C:\Windows\Temp\ has the proper permissions for the Internet Guest User Account (IUSR_[MachineName]) to be able to create, modify and delete files there.

OleDb connection string:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Windows\Temp\tmp123.tmp.xls;

Extended Properties="Excel 8.0;HDR=Yes;IMEX=1;"

[The "Data Source" attribute above would change for every file.]

The stack trace of the exception is:
    System.Exception: FileParsingFailed ---> System.Data.OleDb.OleDbException:
    Unspecified error at
    System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr,
    OleDbConnection connection) at
    System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options,
    Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject) at
    System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection
    owningConnection, DbConnectionPoolGroup poolGroup) at
    System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection
    owningConnection) at
    System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection
    outerConnection, DbConnectionFactory connectionFactory) at
    System.Data.OleDb.OleDbConnection.Open()

Workaround:

So far, the only workaround we could come up with was to do an iisreset (we also have application pool recycling configured to happen once everyday in IIS, but it doesn't seem to help since the issue sometimes persists over several consecutive days). While this is not a good thing to do, what makes it worse is that we have other applications on the same web site that would get impacted whenever we reset IIS.

The questions:

1. How do we resolve this error since it happens occasionally and we don't see a pattern?

2. Are there any better (and free) ways of processing Excel files from C#/ASP.NET apart from OleDb? (We prefer not to install MS Office on the servers since it's not recommended by Microsoft)

Our limitations:

1. We're stuck with the MS Office 2003 (.xls) format and cannot move to the MS Office 2007 (OOXML) format.

2. The reasons we don't use CSV are because we may have commas within our data (this is a pain to deal with even if we use quoting) and we also use multiple worksheets in our spreadsheet (this cannot be done with CSV).

Thanks! :)

Update:

Thanks, Keith. It does seem like an issue with the Jet engine, but we use it because of the lack of (free and easy to use) alternatives.

Thanks, Joe. But we're on a limited budget - so we're mainly looking for free tools/libraries.

OwnerDisplayName: Keith


问:
IIS/ASP.NET responds with cache-control: private for all requests
Why does all responses from ASP.NET contain Cache-Control: private? Even a 404 response? Is there something in IIS that sets this default value, and is there a way to configure it? Or is there something in ASP.NET that sets this?

For dynamic content (that is, all MVC results) I would not like it to be cached by the browser, since it is dynamic and can change at any time. Static content is hosted on a CDN, so is not served by IIS.

Edit:

To clarify, I understand very well what Cache-Control: private is, the difference between private, public, no-store, etc and how/when to use them. The question I have is why Cache-Control: private is added by default by IIS/ASP.NET and how to prevent it from being added by default. I understand that it can be useful to cache dynamic pages, but in my application I don't want to cache dynamic pages/responses. For example, I don't want XHR JSON responses to be cached, since they contain dynamic content. Unfortunately the server adds Cache-Control: private to all responses automatically, so I have to manually override it everywhere.

How to reproduce: Open visual studio and create a new ASP.NET Framework (yes, framework, no not Core. We are not able to migrate our system to core yet) solution with an MVC project. Now start the project in IIS Express (just press the play button), and use F12 devtools in the browser to look at the http response. You will see that it contains Cache-Control: private. My question is, what adds this header, and how can I prevent it from being added by default?

答:
TL; DR

Caching is not used by default for dynamic ASP.NET pages. You need to make an efforts to enable caching in ASP.NET.

Presence of 'Cache-Control: private' header does not mean at all that cached version of the page will be used on repeated requests.

--

There is a very simple test to validate above statements. Create an action that returns current time:

```<code>public ActionResult Index()
{
    ViewBag.CurrTime = DateTime.Now.ToString("T");
    return View();
}
</code>```

View:

```<code>@{
    ViewBag.Title = "Home Page";
}

<h1>@ViewBag.CurrTime</h1>
</code>```

If you refresh such page in abrowser, you'll see fresh time on every request:

There is a possibility to use caching with ASP.NET MVC but you should make some efforts to enable it. See this article for details.

If in spite of this you still for some reason want to exclude any possibility of the caching, you could do it by setting specific HTTP headers. There is a great SO answer that lists which headers should be set:

```<code>Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0
</code>```

You could use action filter to set those headers in every ASP.NET response:

```<code>public class CachingHeadersFilterAttribute : ActionFilterAttribute
{
    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        var response = filterContext.HttpContext.Response;

        response.Cache.SetCacheability(HttpCacheability.NoCache);
        response.Cache.AppendCacheExtension("no-store, must-revalidate");
        response.AppendHeader("Pragma", "no-cache");
        response.AppendHeader("Expires", "0");

        base.OnResultExecuted(filterContext);
    }
}
</code>```

In FilterConfig.cs (crated automatically in ASP.NET MVC template):

```<code>public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new CachingHeadersFilterAttribute());
    }
}
</code>```

Here are result headers from the response:

```<code>HTTP/1.1 200 OK
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Content-Type: text/html; charset=utf-8
Expires: -1
Vary: Accept-Encoding
Server: Microsoft-IIS/10.0
X-AspNetMvc-Version: 5.2
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RDpcRHJvcGJveFxwcm9nXFN0YWNrT3ZlcmZsb3dcUTQ3MjI0NTYxQ2FjaGVcUTQ3MjI0NTYxQ2FjaGU=?=
X-Powered-By: ASP.NET
Date: Mon, 13 Nov 2017 17:44:33 GMT
Content-Length: 837
</code>```

As you see there is no 'Cache-Control: private' header.

But again, I don't see a reason why you should add such filter to your application.

Body:
TL; DR

Caching is not used by default for dynamic ASP.NET pages. You need to make an efforts to enable caching in ASP.NET.

Presence of 'Cache-Control: private' header does not mean at all that cached version of the page will be used on repeated requests.

--

There is a very simple test to validate above statements. Create an action that returns current time:

public ActionResult Index()
{
    ViewBag.CurrTime = DateTime.Now.ToString("T");
    return View();
}

View:

@{
    ViewBag.Title = "Home Page";
}

<h1>@ViewBag.CurrTime</h1>

If you refresh such page in abrowser, you'll see fresh time on every request:

There is a possibility to use caching with ASP.NET MVC but you should make some efforts to enable it. See this article for details.

If in spite of this you still for some reason want to exclude any possibility of the caching, you could do it by setting specific HTTP headers. There is a great SO answer that lists which headers should be set:

Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0

You could use action filter to set those headers in every ASP.NET response:

public class CachingHeadersFilterAttribute : ActionFilterAttribute
{
    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        var response = filterContext.HttpContext.Response;

        response.Cache.SetCacheability(HttpCacheability.NoCache);
        response.Cache.AppendCacheExtension("no-store, must-revalidate");
        response.AppendHeader("Pragma", "no-cache");
        response.AppendHeader("Expires", "0");

        base.OnResultExecuted(filterContext);
    }
}

In FilterConfig.cs (crated automatically in ASP.NET MVC template):

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new CachingHeadersFilterAttribute());
    }
}

Here are result headers from the response:

HTTP/1.1 200 OK
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Content-Type: text/html; charset=utf-8
Expires: -1
Vary: Accept-Encoding
Server: Microsoft-IIS/10.0
X-AspNetMvc-Version: 5.2
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RDpcRHJvcGJveFxwcm9nXFN0YWNrT3ZlcmZsb3dcUTQ3MjI0NTYxQ2FjaGVcUTQ3MjI0NTYxQ2FjaGU=?=
X-Powered-By: ASP.NET
Date: Mon, 13 Nov 2017 17:44:33 GMT
Content-Length: 837

As you see there is no 'Cache-Control: private' header.

But again, I don't see a reason why you should add such filter to your application.


问:
Assigning a number to a name without enumerating and printing a name based on that number
What I am trying to do is using n as the number of characters in list "Roles", print out the number n and the role next to it. Is there a way I can later, depending on the number I ask for, get a character that is "assigned"  to that number. I tried using enumerate, but I wasn't able to call the enumerated roles later with if/while/for or if I wanted to print them. I also tried using dictionary but you can't use append for dictionary. If it's possible to call the enumerated Roles, I would like to know how I can do that, if not I go back to my original question. Here's the code I'm using:

```<code>import random
Roles = ["One", "Two", "Three", "Four"]
SheriffList = []
Alive = []
for n in range(0, len(Roles)):
    random.shuffle(Roles)
    Role = random.choice(Roles)
    Alive.append(Roles.pop(Roles.index(Role)))
    Role2 = n,Role
    print(Role2)
    SheriffList.append(Role2)
    n += 1
    if n == len(Roles):
        random.shuffle(Alive)
        random.choice(Alive)

print(SheriffList)
   [(0, 'One'), (1, 'Four'), (2, 'Three'), (3, 'Two')]
k = int(input("Choose a number:"))
</code>```

Now I want k (The number I choose), to be able to print me back the role that was assigned to it For example if I assign 1 to "k", it will send me 'Four'. I'm sorry if the question was already asked before, I just wasn't able to find what I needed.

答:
you better use a dictionnary:</p>

```<code>import random
Roles = ["One", "Two", "Three", "Four"]
SheriffList = {}
Alive = []
for n in range(0, len(Roles)):
    random.shuffle(Roles)
    Role = random.choice(Roles)
    Alive.append(Roles.pop(Roles.index(Role)))
    #Role2 = (n, Role)
    SheriffList[str(n)]=Role
    #SheriffList.append(Role2)
    n += 1
    if n == len(Roles):
        random.shuffle(Alive)
        random.choice(Alive)

print(SheriffList)
 #  [(0, 'One'), (1, 'Four'), (2, 'Three'), (3, 'Two')]
k = int(input("Choose a number:"))
print(SheriffList[str(k)])
</code>```

Body:
What I am trying to do is using n as the number of characters in list "Roles", print out the number n and the role next to it. Is there a way I can later, depending on the number I ask for, get a character that is "assigned"  to that number. I tried using enumerate, but I wasn't able to call the enumerated roles later with if/while/for or if I wanted to print them. I also tried using dictionary but you can't use append for dictionary. If it's possible to call the enumerated Roles, I would like to know how I can do that, if not I go back to my original question. Here's the code I'm using:

import random
Roles = ["One", "Two", "Three", "Four"]
SheriffList = []
Alive = []
for n in range(0, len(Roles)):
    random.shuffle(Roles)
    Role = random.choice(Roles)
    Alive.append(Roles.pop(Roles.index(Role)))
    Role2 = n,Role
    print(Role2)
    SheriffList.append(Role2)
    n += 1
    if n == len(Roles):
        random.shuffle(Alive)
        random.choice(Alive)

print(SheriffList)
   [(0, 'One'), (1, 'Four'), (2, 'Three'), (3, 'Two')]
k = int(input("Choose a number:"))

Now I want k (The number I choose), to be able to print me back the role that was assigned to it For example if I assign 1 to "k", it will send me 'Four'. I'm sorry if the question was already asked before, I just wasn't able to find what I needed.

Body:
you better use a dictionnary:

import random
Roles = ["One", "Two", "Three", "Four"]
SheriffList = {}
Alive = []
for n in range(0, len(Roles)):
    random.shuffle(Roles)
    Role = random.choice(Roles)
    Alive.append(Roles.pop(Roles.index(Role)))
    #Role2 = (n, Role)
    SheriffList[str(n)]=Role
    #SheriffList.append(Role2)
    n += 1
    if n == len(Roles):
        random.shuffle(Alive)
        random.choice(Alive)

print(SheriffList)
 #  [(0, 'One'), (1, 'Four'), (2, 'Three'), (3, 'Two')]
k = int(input("Choose a number:"))
print(SheriffList[str(k)])


问:
i want the link style like in the picture
html code:

```<code> <ul class="info-link">
   <li><a href="#"><i class="fa fa-map-marker"></i>  3588 N Stelling road, Brooklyn, NYC, United State.</a> </li>
   <li><a href="#"><i class="fa fa-phone"></i>  1900-167-168-99 EXT: 001</a></li>
   <li><a href="#"><i class="fa fa-mobile"></i>  (05) 132-564-3333</a></li>
   <li><a href="#"><i class="fa fa-envelope"></i>  logohere@support.com</a></li>
 </ul>
</code>```

css code :

```<code>ul li {
  list-style: none;
}
</code>```

result picture:
code-result

desire result picture:
desire-result

答:
Try This:

* {
    box-sizing: border-box;
}

li {
    margin-bottom: 10px;
}

ul {
    width: 300px;
    background-color: #DDD;
    list-style: none;
    padding: 0;
}

a {
    color: #000;
    text-decoration: none;
}

i {
    width: 6%;
    margin-left: 1%;
    vertical-align: top;
}

span {
    width: 93%;
    display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<ul class="info-link">
    <li><i class="fa fa-map-marker"></i><span>3588 N Stelling road, Brooklyn, NYC, United State.</span></li>
    <li><i class="fa fa-phone"></i><span>1900-167-168-99 EXT: 001</span></li>
    <li><i class="fa fa-mobile"></i><span>(05) 132-564-3333</span></li>
    <li><i class="fa fa-envelope"></i><span>logohere@support.com</span></li>
</ul></code>```

Body:
html code:

  3588 N Stelling road, Brooklyn, NYC, United State.

  1900-167-168-99 EXT: 001

  (05) 132-564-3333

  logohere@support.com

css code :

ul li {
  list-style: none;
}

result picture:
code-result

desire result picture:
desire-result

Body:
Try This:

* {
    box-sizing: border-box;
}

li {
    margin-bottom: 10px;
}

ul {
    width: 300px;
    background-color: #DDD;
    list-style: none;
    padding: 0;
}

a {
    color: #000;
    text-decoration: none;
}

i {
    width: 6%;
    margin-left: 1%;
    vertical-align: top;
}

span {
    width: 93%;
    display: inline-block;
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<ul class="info-link">
    <li><a href="#"><i class="fa fa-map-marker"></i><span>3588 N Stelling road, Brooklyn, NYC, United State.</span></a></li>
    <li><a href="#"><i class="fa fa-phone"></i><span>1900-167-168-99 EXT: 001</span></a></li>
    <li><a href="#"><i class="fa fa-mobile"></i><span>(05) 132-564-3333</span></a></li>
    <li><a href="#"><i class="fa fa-envelope"></i><span>logohere@support.com</span></a></li>
</ul>


问:
python json.dumps()’s data is contain \, how to clean it
```<code>def getJson(filmList):
film_json = FilmJson()
for video in filmList:
    videoName = video.videoName
    videoUrl = video.videoUrl
    videoTime = video.videoTime
    dic = {}
    if videoName is None:
        break

    if videoUrl is None:
        dic['videourl'] = ""
    else:
        dic['videourl'] = videoUrl

    if videoTime is None:
        dic['videotime'] = ""
    else:
        dic['videotime'] = videoTime
    dic['videoname'] = videoName

    film_json.videolist.append(dic)

dict__ = film_json.__dict__
print(dict__)

return dict__
</code>```

The browser send get request

the backend print

```<code>{'filmid': '', 'videolist': [{'videourl': '', 'videotime': '', 'videoname': 'Lifeline'}, {'videourl': '', 'videotime': '', 'videoname': 'Ex Static'}, {'videourl': '', 'videotime': '', 'videoname': 'test'}]}
</code>```

.

```<code>@api_view(http_method_names=['GET'])
@permission_classes((permissions.AllowAny,))
def sendFilm(request):
   ....
    myjson = jsonbean.getJson(filmList)

    return Response(json.dumps(myjson,ensure_ascii=False))
</code>```

The postman test get result

```<code>"{\"filmid\": \"\", \"videolist\": [{\"videourl\": \"\", \"videotime\": \"\", \"videoname\": \"Lifeline\"}, {\"videourl\": \"\", \"videotime\": \"\", \"videoname\": \"Ex Static\"}, {\"videourl\": \"\", \"videotime\": \"\", \"videoname\": \"test\"}]}"
</code>```

how to resolve the  problem

答: Don't do json.dumps when passing the data to Response.

Body:
def getJson(filmList):
film_json = FilmJson()
for video in filmList:
    videoName = video.videoName
    videoUrl = video.videoUrl
    videoTime = video.videoTime
    dic = {}
    if videoName is None:
        break

    if videoUrl is None:
        dic['videourl'] = ""
    else:
        dic['videourl'] = videoUrl

    if videoTime is None:
        dic['videotime'] = ""
    else:
        dic['videotime'] = videoTime
    dic['videoname'] = videoName

    film_json.videolist.append(dic)

dict__ = film_json.__dict__
print(dict__)

return dict__

The browser send get request

the backend print

{'filmid': '', 'videolist': [{'videourl': '', 'videotime': '', 'videoname': 'Lifeline'}, {'videourl': '', 'videotime': '', 'videoname': 'Ex Static'}, {'videourl': '', 'videotime': '', 'videoname': 'test'}]}

.

@api_view(http_method_names=['GET'])
@permission_classes((permissions.AllowAny,))
def sendFilm(request):
   ....
    myjson = jsonbean.getJson(filmList)

    return Response(json.dumps(myjson,ensure_ascii=False))

The postman test get result

"{\"filmid\": \"\", \"videolist\": [{\"videourl\": \"\", \"videotime\": \"\", \"videoname\": \"Lifeline\"}, {\"videourl\": \"\", \"videotime\": \"\", \"videoname\": \"Ex Static\"}, {\"videourl\": \"\", \"videotime\": \"\", \"videoname\": \"test\"}]}"

how to resolve the  problem


问:
BLE finds a device but does not connect
I'm making an app using Android Studio (java) to scan for a BLE device, and then connect to it, eventually leading to me sending it data.

So far I've created a functioning scanner which can detect the BLE device, and I can call the device name, the MAC address and the RSSI value, but I can't make it connect. Given I have the MAC address, is connecting not a simple small segment of code?

I have tried using createBond(), which gives me a response on the debug section, but fails to do anything.

Now I have the MAC address from the actual scan, is there some way I can connect directly via that address? That would also work for my purpose since I will only be connecting to same BLE module.

Here is my code so you can see what I have, all of which is functioning

```<code>public class BluetoothConnect extends AppCompatActivity {

    BluetoothManager btManager;
    BluetoothAdapter btAdapter;
    BluetoothLeScanner btScanner;
    Button startScanningButton;
    Button stopScanningButton;
    TextView peripheralTextView;
    private final static int REQUEST_ENABLE_BT = 1;
    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
    final Intent startMainActivity = new Intent();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scan_and_connect);

        controlTankScreen();

        //sets us the window for devices to be listed
        peripheralTextView = (TextView) findViewById(R.id.PeripheralTextView);
        peripheralTextView.setMovementMethod(new ScrollingMovementMethod());

        //button id 6 is start scanning
        startScanningButton = findViewById(R.id.button6);
        startScanningButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                startScanning();
            }
        });
        //button id 7 is stop scanning
        stopScanningButton = findViewById(R.id.button7);
        stopScanningButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                stopScanning();
            }
        });

        //enables bluetooth, Adapter refers to the local device, in this case, my smart phone
        btManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
        btAdapter = btManager.getAdapter();
        btScanner = btAdapter.getBluetoothLeScanner();

        if (btAdapter != null && !btAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent,REQUEST_ENABLE_BT);

        }

    // Make sure we have access coarse location enabled, if not, prompt the user to enable it
    if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("This app needs location access");
        builder.setMessage("Please grant location access so this app can detect peripherals.");
        builder.setPositiveButton(android.R.string.ok, null);
        builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
            }
        });
        builder.show();
    }
}

// this will scan for devices, displaying the device name, the mac address, and the RSSI, recieved signal strength indicator
public ScanCallback leScanCallback = new ScanCallback() {
    @Override
    public void onScanResult(int callbackType, ScanResult result) {
        peripheralTextView.append("Device Name: " + result.getDevice().getName() +"Mac Address: "+ result.getDevice().getAddress() +" rssi: " + result.getRssi() + "\n");
        String deviceName = result.getDevice().getName();
        String deviceAddress = result.getDevice().getAddress();
        result.getDevice().createBond();

        // auto scroll for text view
        final int scrollAmount = peripheralTextView.getLayout().getLineTop(peripheralTextView.getLineCount()) - peripheralTextView.getHeight();
        // if there is no need to scroll, scrollAmount will be <=0
        if (scrollAmount > 0)
            peripheralTextView.scrollTo(0, scrollAmount);
    }
};

@Override
//This makes sure that Bluetooth and correct permissions are allowed
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_COARSE_LOCATION: {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                System.out.println("coarse location permission granted");
            } else {
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Functionality limited");
                builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons when in the background.");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {

                    @Override
                    public void onDismiss(DialogInterface dialog) {
                    }

                });
                builder.show();
            }
            return;
        }
    }
}
//ran when button id 6, start scan is pressed
public void startScanning() {
    System.out.println("start scanning");
    peripheralTextView.setText("Started Scanning");
    //startScanningButton.setVisibility(View.INVISIBLE);
    //stopScanningButton.setVisibility(View.VISIBLE);
    AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            btScanner.startScan(leScanCallback);
        }
    });
}
//ran when button id 7, stop scan is pressed
public void stopScanning() {
    System.out.println("stopping scanning");
    peripheralTextView.append("Stopped Scanning");
    //startScanningButton.setVisibility(View.VISIBLE);
    //stopScanningButton.setVisibility(View.INVISIBLE);
    AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            btScanner.stopScan(leScanCallback);
        }
    });
}
//ran from onCreate on app boot up, just sets the app up to control the tank
public void controlTankScreen() {
    startMainActivity.setComponent(new ComponentName("smiths.tankcontroller", "smiths.tankcontroller.MainActivity"));

    final Button button = findViewById(R.id.button5);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startActivity(startMainActivity);
            setContentView(R.layout.activity_main);

            //what to do when the button is pressed
            finish();

        }
    });
}

IntentFilter intent = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);

private final BroadcastReceiver bluetoothParingReciever = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
            final int state        = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
            final int prevState    = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);

            if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
                System.out.println("Paired");
            } else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
                System.out.println("Unpaired");
            }

        }
    }
};

public void pairDevice(BluetoothDevice device) {
    try {
        Method method = device.getClass().getMethod("createBond", (Class[]) null);
        method.invoke(device, (Object[]) null);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}
</code>```

答:
Right way of connecting to BLE peripherals:

```<code>final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);

mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
</code>```

If any of the characteristics require encryption you would need to handle the read/write result "BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION" and retry.

Title: BLE finds a device but does not connect

Body:
I'm making an app using Android Studio (java) to scan for a BLE device, and then connect to it, eventually leading to me sending it data.

So far I've created a functioning scanner which can detect the BLE device, and I can call the device name, the MAC address and the RSSI value, but I can't make it connect. Given I have the MAC address, is connecting not a simple small segment of code?

I have tried using createBond(), which gives me a response on the debug section, but fails to do anything.

Now I have the MAC address from the actual scan, is there some way I can connect directly via that address? That would also work for my purpose since I will only be connecting to same BLE module.

Here is my code so you can see what I have, all of which is functioning

public class BluetoothConnect extends AppCompatActivity {

    BluetoothManager btManager;
    BluetoothAdapter btAdapter;
    BluetoothLeScanner btScanner;
    Button startScanningButton;
    Button stopScanningButton;
    TextView peripheralTextView;
    private final static int REQUEST_ENABLE_BT = 1;
    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
    final Intent startMainActivity = new Intent();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scan_and_connect);

        controlTankScreen();

        //sets us the window for devices to be listed
        peripheralTextView = (TextView) findViewById(R.id.PeripheralTextView);
        peripheralTextView.setMovementMethod(new ScrollingMovementMethod());

        //button id 6 is start scanning
        startScanningButton = findViewById(R.id.button6);
        startScanningButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                startScanning();
            }
        });
        //button id 7 is stop scanning
        stopScanningButton = findViewById(R.id.button7);
        stopScanningButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                stopScanning();
            }
        });

        //enables bluetooth, Adapter refers to the local device, in this case, my smart phone
        btManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
        btAdapter = btManager.getAdapter();
        btScanner = btAdapter.getBluetoothLeScanner();

        if (btAdapter != null && !btAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent,REQUEST_ENABLE_BT);

        }

    // Make sure we have access coarse location enabled, if not, prompt the user to enable it
    if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("This app needs location access");
        builder.setMessage("Please grant location access so this app can detect peripherals.");
        builder.setPositiveButton(android.R.string.ok, null);
        builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
            }
        });
        builder.show();
    }
}

// this will scan for devices, displaying the device name, the mac address, and the RSSI, recieved signal strength indicator
public ScanCallback leScanCallback = new ScanCallback() {
    @Override
    public void onScanResult(int callbackType, ScanResult result) {
        peripheralTextView.append("Device Name: " + result.getDevice().getName() +"Mac Address: "+ result.getDevice().getAddress() +" rssi: " + result.getRssi() + "\n");
        String deviceName = result.getDevice().getName();
        String deviceAddress = result.getDevice().getAddress();
        result.getDevice().createBond();

        // auto scroll for text view
        final int scrollAmount = peripheralTextView.getLayout().getLineTop(peripheralTextView.getLineCount()) - peripheralTextView.getHeight();
        // if there is no need to scroll, scrollAmount will be <=0
        if (scrollAmount > 0)
            peripheralTextView.scrollTo(0, scrollAmount);
    }
};

@Override
//This makes sure that Bluetooth and correct permissions are allowed
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_COARSE_LOCATION: {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                System.out.println("coarse location permission granted");
            } else {
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Functionality limited");
                builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons when in the background.");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {

                    @Override
                    public void onDismiss(DialogInterface dialog) {
                    }

                });
                builder.show();
            }
            return;
        }
    }
}
//ran when button id 6, start scan is pressed
public void startScanning() {
    System.out.println("start scanning");
    peripheralTextView.setText("Started Scanning");
    //startScanningButton.setVisibility(View.INVISIBLE);
    //stopScanningButton.setVisibility(View.VISIBLE);
    AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            btScanner.startScan(leScanCallback);
        }
    });
}
//ran when button id 7, stop scan is pressed
public void stopScanning() {
    System.out.println("stopping scanning");
    peripheralTextView.append("Stopped Scanning");
    //startScanningButton.setVisibility(View.VISIBLE);
    //stopScanningButton.setVisibility(View.INVISIBLE);
    AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            btScanner.stopScan(leScanCallback);
        }
    });
}
//ran from onCreate on app boot up, just sets the app up to control the tank
public void controlTankScreen() {
    startMainActivity.setComponent(new ComponentName("smiths.tankcontroller", "smiths.tankcontroller.MainActivity"));

    final Button button = findViewById(R.id.button5);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startActivity(startMainActivity);
            setContentView(R.layout.activity_main);

            //what to do when the button is pressed
            finish();

        }
    });
}

IntentFilter intent = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);

private final BroadcastReceiver bluetoothParingReciever = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
            final int state        = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
            final int prevState    = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);

            if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
                System.out.println("Paired");
            } else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
                System.out.println("Unpaired");
            }

        }
    }
};

public void pairDevice(BluetoothDevice device) {
    try {
        Method method = device.getClass().getMethod("createBond", (Class[]) null);
        method.invoke(device, (Object[]) null);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

Body:
Right way of connecting to BLE peripherals:

final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);

mBluetoothGatt = device.connectGatt(this, false, mGattCallback);

If any of the characteristics require encryption you would need to handle the read/write result "BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION" and retry.


问:
How to Label Source upon successful build on Visual Studio Team Services
I was trying to use new Build on Visual Studio Team Services (not XAML) but couldn't figure out how to label the source upon successful build.  Any idea?

Below is the screenshot that shows how to do in XAML one.

I already have a feature request at https://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/9613014-allow-label-source-upon-succesful-build-on-visual I'm actually asking for a workaround until Microsoft implements it.

答:
The XAML build did label sources at the start of the build, while vNext build seems to label at the end of the build.
I noticed that, because I modify/checkin/label files during the build.
If I let vNext label the build, it moves the label that I have applied to the files after checkin to the previous version (the version that was used in GetSources).

But I did not see the labeling of vNext in any logfile. Did I miss it?
I will have to disable labeling in vnext and do it in my msbuild script...

edit:
Disabled labeling in vnext build definition and created an msbuild inline task to label the sources of the workspace. Now I can label all sources at the start of the build and move the label for files that were modified during the build :)

If someone wants to do something similiar, here is my inline task:

```<code><!--
    TaskName="LabelWorkspaceSources"
    - input: TfexeFullPath is the path to tf.exe
    - input: BaseDirectory is the mapped folder of the software to build
    - input: Label to apply
    - input: Version is the changeset to apply the label to
-->
<UsingTask TaskName="LabelWorkspaceSources" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll">
    <ParameterGroup>
        <TfexeFullPath Required="true" />
        <BaseDirectory Required="true" />
        <Label Required="true" />
        <Version Required="true" />
    </ParameterGroup>
    <Task>
        <Code Type="Fragment" Language="cs">
        <![CDATA[

        //--- get the workspace mapping ---

        System.Diagnostics.Process tfProcess = new System.Diagnostics.Process();
        tfProcess.StartInfo.FileName = TfexeFullPath;
        tfProcess.StartInfo.Arguments = "workfold";
        tfProcess.StartInfo.UseShellExecute = false;
        tfProcess.StartInfo.CreateNoWindow = true;
        tfProcess.StartInfo.RedirectStandardOutput = true;
        tfProcess.StartInfo.WorkingDirectory = BaseDirectory;
        tfProcess.Start();

        string output = tfProcess.StandardOutput.ReadToEnd();

        tfProcess.WaitForExit();

        string workfoldOutput = output.Trim();
        Log.LogMessage(workfoldOutput, MessageImportance.High);

        string[] linesWorkfoldOutput = workfoldOutput.Split(new string[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
        List<string> mappedFolders = new List<string>();

        Log.LogMessage("Trying to parse mapped folders.", MessageImportance.High);
        foreach (string line in linesWorkfoldOutput)
        {
            //e.g. $/TPA: C:\TFS_Source\TPA
            if (line.Contains("$/"))
            {
                string[] lineSplit = line.Split(new string[] { ": " }, StringSplitOptions.RemoveEmptyEntries);

                //entry lineSplit[0] now contains the server path, lineSplit[1] contains the local folder
                mappedFolders.Add(lineSplit[1]);
                Log.LogMessage("Found mapped folder: " + lineSplit[1], MessageImportance.High);
            }
        }

        //--- label all the mapped folders ---

        foreach (string mappedFolder in mappedFolders)
        {
            tfProcess = new System.Diagnostics.Process();
            tfProcess.StartInfo.FileName = TfexeFullPath;
            tfProcess.StartInfo.Arguments = "label " + Label + " \"" + mappedFolder + "\" /child:replace /recursive /comment:\"Label created by task LabelWorkspaceSources\" /version:" + Version;
            tfProcess.StartInfo.UseShellExecute = false;
            tfProcess.StartInfo.CreateNoWindow = true;
            tfProcess.StartInfo.RedirectStandardOutput = true;
            tfProcess.StartInfo.WorkingDirectory = mappedFolder;
            tfProcess.Start();

            output = tfProcess.StandardOutput.ReadToEnd();

            tfProcess.WaitForExit();

            Log.LogMessage(tfProcess.StartInfo.Arguments, MessageImportance.High);
            Log.LogMessage(output, MessageImportance.High);
        }
        ]]>
        </Code>
    </Task>
</UsingTask>
</code>```

Body:
The XAML build did label sources at the start of the build, while vNext build seems to label at the end of the build.
I noticed that, because I modify/checkin/label files during the build.
If I let vNext label the build, it moves the label that I have applied to the files after checkin to the previous version (the version that was used in GetSources).

But I did not see the labeling of vNext in any logfile. Did I miss it?
I will have to disable labeling in vnext and do it in my msbuild script...

edit:
Disabled labeling in vnext build definition and created an msbuild inline task to label the sources of the workspace. Now I can label all sources at the start of the build and move the label for files that were modified during the build :)

If someone wants to do something similiar, here is my inline task:

<!--
    TaskName="LabelWorkspaceSources"
    - input: TfexeFullPath is the path to tf.exe
    - input: BaseDirectory is the mapped folder of the software to build
    - input: Label to apply
    - input: Version is the changeset to apply the label to
-->
<UsingTask TaskName="LabelWorkspaceSources" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll">
    <ParameterGroup>
        <TfexeFullPath Required="true" />
        <BaseDirectory Required="true" />
        <Label Required="true" />
        <Version Required="true" />
    </ParameterGroup>
    <Task>
        <Code Type="Fragment" Language="cs">
        <![CDATA[

        //--- get the workspace mapping ---

        System.Diagnostics.Process tfProcess = new System.Diagnostics.Process();
        tfProcess.StartInfo.FileName = TfexeFullPath;
        tfProcess.StartInfo.Arguments = "workfold";
        tfProcess.StartInfo.UseShellExecute = false;
        tfProcess.StartInfo.CreateNoWindow = true;
        tfProcess.StartInfo.RedirectStandardOutput = true;
        tfProcess.StartInfo.WorkingDirectory = BaseDirectory;
        tfProcess.Start();

        string output = tfProcess.StandardOutput.ReadToEnd();

        tfProcess.WaitForExit();

        string workfoldOutput = output.Trim();
        Log.LogMessage(workfoldOutput, MessageImportance.High);

        string[] linesWorkfoldOutput = workfoldOutput.Split(new string[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
        List<string> mappedFolders = new List<string>();

        Log.LogMessage("Trying to parse mapped folders.", MessageImportance.High);
        foreach (string line in linesWorkfoldOutput)
        {
            //e.g. $/TPA: C:\TFS_Source\TPA
            if (line.Contains("$/"))
            {
                string[] lineSplit = line.Split(new string[] { ": " }, StringSplitOptions.RemoveEmptyEntries);

                //entry lineSplit[0] now contains the server path, lineSplit[1] contains the local folder
                mappedFolders.Add(lineSplit[1]);
                Log.LogMessage("Found mapped folder: " + lineSplit[1], MessageImportance.High);
            }
        }

        //--- label all the mapped folders ---

        foreach (string mappedFolder in mappedFolders)
        {
            tfProcess = new System.Diagnostics.Process();
            tfProcess.StartInfo.FileName = TfexeFullPath;
            tfProcess.StartInfo.Arguments = "label " + Label + " \"" + mappedFolder + "\" /child:replace /recursive /comment:\"Label created by task LabelWorkspaceSources\" /version:" + Version;
            tfProcess.StartInfo.UseShellExecute = false;
            tfProcess.StartInfo.CreateNoWindow = true;
            tfProcess.StartInfo.RedirectStandardOutput = true;
            tfProcess.StartInfo.WorkingDirectory = mappedFolder;
            tfProcess.Start();

            output = tfProcess.StandardOutput.ReadToEnd();

            tfProcess.WaitForExit();

            Log.LogMessage(tfProcess.StartInfo.Arguments, MessageImportance.High);
            Log.LogMessage(output, MessageImportance.High);
        }
        ]]>
        </Code>
    </Task>
</UsingTask>