问:
Get text from mixed element xml tags with ElementTree
I'm using ElementTree to parse an XML document that I have. I am getting the text from the u tags. Some of them have mixed content that I need to filter out or keep as text. Two examples that I have are:

```<code><u>
   <vocal type="filler">
     <desc>eh</desc>
   </vocal>¿Sí?
</u>

<u>Pues...
   <vocal type="non-ling">
     <desc>laugh</desc>
   </vocal>A mí no me suena.
</u>
</code>```

I want to get the text within the vocal tag if it's type is filler but not if it's type is non-ling.

If I iterate through the children of u, somehow the last text bit is always lost. The only way that I can reach it is by using itertext(). But then the chance to check the type of the vocal tag is lost.

How can I parse it so that I get a result like this:

```<code>eh ¿Sí?
Pues... A mí no me suena.
</code>```

答:
The lost text bits, "¿Sí?" and "A mí no me suena.", are available as the tail property of each <vocal> element (the text following the element's end tag).

Here is a way to get the wanted output (tested with Python 2.7).

Assume that vocal.xml looks like this:

```<code><root>
  <u>
    <vocal type="filler">
      <desc>eh</desc>
    </vocal>¿Sí?
  </u>

  <u>Pues...
     <vocal type="non-ling">
       <desc>laugh</desc>
     </vocal>A mí no me suena.
  </u>
</root>
</code>```

Code:

```<code>from xml.etree import ElementTree as ET

root = ET.parse("vocal.xml")

for u in root.findall(".//u"):
    v = u.find("vocal")

    if v.get("type") == "filler":
        frags = [u.text, v.findtext("desc"), v.tail]
    else:
        frags = [u.text, v.tail]

    print " ".join(t.encode("utf-8").strip() for t in frags).strip()
</code>```

Output:

```<code>eh ¿Sí?
Pues... A mí no me suena.
</code>```

Body:
I'm using ElementTree to parse an XML document that I have. I am getting the text from the u tags. Some of them have mixed content that I need to filter out or keep as text. Two examples that I have are:

   <vocal type="filler">
     <desc>eh</desc>
   </vocal>¿Sí?

Pues...
   <vocal type="non-ling">
     <desc>laugh</desc>
   </vocal>A mí no me suena.

I want to get the text within the vocal tag if it's type is filler but not if it's type is non-ling.

If I iterate through the children of u, somehow the last text bit is always lost. The only way that I can reach it is by using itertext(). But then the chance to check the type of the vocal tag is lost.

How can I parse it so that I get a result like this:

eh ¿Sí?
Pues... A mí no me suena.

Body:
The lost text bits, "¿Sí?" and "A mí no me suena.", are available as the tail property of each <vocal> element (the text following the element's end tag).

Here is a way to get the wanted output (tested with Python 2.7).

Assume that vocal.xml looks like this:

<root>
  <u>
    <vocal type="filler">
      <desc>eh</desc>
    </vocal>¿Sí?
  </u>

  <u>Pues...
     <vocal type="non-ling">
       <desc>laugh</desc>
     </vocal>A mí no me suena.
  </u>
</root>

Code:

from xml.etree import ElementTree as ET

root = ET.parse("vocal.xml")

for u in root.findall(".//u"):
    v = u.find("vocal")

    if v.get("type") == "filler":
        frags = [u.text, v.findtext("desc"), v.tail]
    else:
        frags = [u.text, v.tail]

    print " ".join(t.encode("utf-8").strip() for t in frags).strip()

Output:

eh ¿Sí?
Pues... A mí no me suena.

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Can a pointer ever point to itself?
My question is: If a pointer variable has the same address as its value, is it really pointing to itself?

For example -  in the following piece of code, is a a pointer to itself?

```<code>#include<stdio.h>

int main(){
   int* a;
   int b = (int)&a;
   a = b;
   printf("address of a = %d\n", &a);
   printf("  value of a = %d\n", a);
}
</code>```

If a is not a pointer to itself, then the same question poses again: Can a pointer point to itself?

Also, how is a self pointing pointer useful?

答:
Yes, a pointer can point to itself as mentioned in the answers.

A possible use case is we can use this trick in lieu of NULL pointers. You can initialize int * p = (int *)&p, and check this later to see if the pointer is valid or not. This could have been used if say in a system where we wanted 0x0 and the entire address range to be valid addresses.

You can also use this trick in special C programs which would not crash on NULL pointer usage because you would avoid them altogether and on dereference system will not crash. It will lead to erroneous behavior but it may help debugging in certain situations.

Title: Can a pointer ever point to itself?

Body:
My question is: If a pointer variable has the same address as its value, is it really pointing to itself?

For example -  in the following piece of code, is a a pointer to itself?

#include<stdio.h>

int main(){
   int* a;
   int b = (int)&a;
   a = b;
   printf("address of a = %d\n", &a);
   printf("  value of a = %d\n", a);
}

If a is not a pointer to itself, then the same question poses again: Can a pointer point to itself?

Also, how is a self pointing pointer useful?

ContentLicense: CC BY-SA 3.0


问:
(ubuntu) nginx: [emerg] bind() to 0.0.0.0:80 failed (13: permission denied)
I need help figuring out the root cause of this permission denied error. What permissions does nginx need? Why is it so complicated?</p>

答:
nginx needs root access. Just use

sudo nginx

next step along with your password


问:
Convert struct with pointer to char array
I am currently trying to find the simplest way to convert a struct which contains a char * to a char array for transmitting a serial data frame.

The struct stores the frame headers, checksum, msg size etc along with the data to be transmit. eg

```<code>struct {
    unsigned char header;
    unsigned char msgSizeL;
    unsigned char msgSizeH;
    unsigned char *data;
    unsigned char checksum;
    ....
    ....
    ....
    ....
    unsinged char endFrame;
} Frame;
</code>```

The data is a pointer as the amount of data can change with each frame transmit in the range from 1 to 16 bytes.

I am trying to find the simplest way to convert the struct to an array of unsigned chars without copying out each entry in the struct to the array but don't seem to be able to find a way.

Alternately I don't have to use a struct, as i am generating the frame contents excluding the data contents from scratch, I just want to avoid a case of -

```<code>unsigned char frame[1000];
frame[0] = 0x01; // header
frame[1] = msgSizeL; // msg size low byte
frame[2] = msgSizeH; // msg size high byte
frame[3] = data[0]; // data contents 0    Over simplification
frame[4] = data[1]; // data contents 1    for data copying -
frame[5] = data[2]; // data contents 2    data length is variable.
frame[6] = data[3]; // data contents 3
frame[7] = data[4]; // data contents 4
frame[8] = data[5]; // data contents 5
frame[9] = data[6]; // data contents 6
frame[10] = data[7]; // data contents 7
frame[3 + msgSize]; = getChecksum(data);
....
....
....
....
frame [3 + msgSize + 20] = 0xFF; // end frame
</code>```

where i write data to what reads as a random array index rather than something meaningful like frame.checksum = getChecksum(data);.

Open to suggestions and a little bit of flaming for asking a general question rather than a specific one :-)

答:
I am trying to find the simplest way to convert the struct to an array of unsigned chars without copying out each entry in the struct to the array but don't seem to be able to find a way.

If data would contain up to 16 bytes, I would just declare it as 16-char array, like so:

```<code>#define MAX_DATA_LEN 16
struct {
    unsigned char header;
    unsigned char msgSizeL;
    unsigned char msgSizeH;
    unsigned char data[MAX_DATA_LEN]; // 16-char array instead of pointer
    unsigned char checksum;
    ....
    ....
    ....
    ....
    unsinged char endFrame;
} Frame;
</code>```

If this is done, then all your data inside this struct has a pre-defined size (i.e. number of unsigned char * sizeof(unsigned char), and so on with other data types...) and you can use simple memcpy to copy the struct to an array:

```<code>size_t struct_len = /* computing the length of the data */ 100;
memcpy(frame, struct Frame, struct_len);
</code>```

Body:
I am currently trying to find the simplest way to convert a struct which contains a char * to a char array for transmitting a serial data frame.

The struct stores the frame headers, checksum, msg size etc along with the data to be transmit. eg

struct {
    unsigned char header;
    unsigned char msgSizeL;
    unsigned char msgSizeH;
    unsigned char *data;
    unsigned char checksum;
    ....
    ....
    ....
    ....
    unsinged char endFrame;
} Frame;

The data is a pointer as the amount of data can change with each frame transmit in the range from 1 to 16 bytes.

I am trying to find the simplest way to convert the struct to an array of unsigned chars without copying out each entry in the struct to the array but don't seem to be able to find a way.

Alternately I don't have to use a struct, as i am generating the frame contents excluding the data contents from scratch, I just want to avoid a case of -

unsigned char frame[1000];
frame[0] = 0x01; // header
frame[1] = msgSizeL; // msg size low byte
frame[2] = msgSizeH; // msg size high byte
frame[3] = data[0]; // data contents 0    Over simplification
frame[4] = data[1]; // data contents 1    for data copying -
frame[5] = data[2]; // data contents 2    data length is variable.
frame[6] = data[3]; // data contents 3
frame[7] = data[4]; // data contents 4
frame[8] = data[5]; // data contents 5
frame[9] = data[6]; // data contents 6
frame[10] = data[7]; // data contents 7
frame[3 + msgSize]; = getChecksum(data);
....
....
....
....
frame [3 + msgSize + 20] = 0xFF; // end frame

where i write data to what reads as a random array index rather than something meaningful like frame.checksum = getChecksum(data);.

Open to suggestions and a little bit of flaming for asking a general question rather than a specific one :-)

Body:
I am trying to find the simplest way to convert the struct to an array of unsigned chars without copying out each entry in the struct to the array but don't seem to be able to find a way.

If data would contain up to 16 bytes, I would just declare it as 16-char array, like so:

#define MAX_DATA_LEN 16
struct {
    unsigned char header;
    unsigned char msgSizeL;
    unsigned char msgSizeH;
    unsigned char data[MAX_DATA_LEN]; // 16-char array instead of pointer
    unsigned char checksum;
    ....
    ....
    ....
    ....
    unsinged char endFrame;
} Frame;

If this is done, then all your data inside this struct has a pre-defined size (i.e. number of unsigned char * sizeof(unsigned char), and so on with other data types...) and you can use simple memcpy to copy the struct to an array:

size_t struct_len = /* computing the length of the data */ 100;
memcpy(frame, struct Frame, struct_len);


问:
How to build a JPA jhipster application where entities are populated from another jhipster application?
Here's a simple example of two microservices:
a) provide information about a person from a database
b) provide information about an order and a person from a database where the order is stored and it only has a reference to a person by an id

The correct SOA way is not to replicate the person in the second service because we don't want data replication. So my question is, how to implement in service b) a model for order and person. But the full person information is populated from service a)?

Please provide an exmaple. Thanks so much.

答: Not a complete answer nor an example, just a hint. I would go with a DTO of the person to decouple the implementation of service a from its interface. This person DTO could be located in a service a interface artifact (e.g. maven module), which would then be a dependency of service b. Or if you want to be more flexible, just put the person DTO into service b as the java representation of the rest api.</p>


问:
how to create custom list with sonata admin
I can't find (understand) how to add items and cathegories to Left Side Admin Menu.
There is no detailed tutorial how to do this.
I can add items to sonata.admin.block.admin_list but to aside Admin Menu
enter image description here</p>

答:
Yes you can do sth like that:</p>

```<code>sonata_admin:
title:      Supplier Portal
title_logo: bundles/supplierportalbackend/img/logo.png
show_mosaic_button: false
security:
    handler: sonata.admin.security.handler.role
templates:
    layout:              SonataAdminBundle::layout.html.twig
    search:              SonataAdminBundle:Core:search.html.twig
    search_result_block: SonataAdminBundle:Block:block_search_result.html.twig
    base_list_field:     SonataAdminBundle:CRUD:base_list_field.html.twig

dashboard:
    blocks:
        - { position: left, type: sonata.admin.block.admin_list }
    # Customize user portal menu by setting links
    groups:
        sonata.admin.group.purchase_order_item.open:
            on_top:          true
            label:           Open Items
            label_catalogue: messages
            icon:            '<i class="fa fa-square-o"></i>'
            items:
                - supplier_portal_backend.admin.purchase_open_order_item

        sonata.admin.group.purchase_order_item.confirmed:
            on_top:          true
            label:           Confirmed Items
            label_catalogue: messages
            icon:            '<i class="fa fa-check-square-o"></i>'
            items:
                - supplier_portal_backend.admin.purchase_confirmed_order_item

        sonata.admin.group.purchase_order_item.shipped:
            on_top:          true
            label:           Shipped Items
            label_catalogue: messages
            icon:            '<i class="fa fa-truck"></i>'
            items:
                - supplier_portal_backend.admin.purchase_shipped_order_item

        sonata.admin.group.purchase_order_item.all:
            on_top:          true
            label:           All Items
            label_catalogue: messages
            icon:            '<i class="fa fa-th-list"></i>'
            items:
                - supplier_portal_backend.admin.purchase_order_item

        sonata.admin.group.administration:
            on_top:          true
            label:           Users
            label_catalogue: messages
            icon:            '<i class="fa fa-users"></i>'
            items:
                - supplier_portal_backend.admin.user
            roles: [ ROLE_SUPER_ADMIN ]
</code>```

Body:
Yes you can do sth like that:

sonata_admin:
title:      Supplier Portal
title_logo: bundles/supplierportalbackend/img/logo.png
show_mosaic_button: false
security:
    handler: sonata.admin.security.handler.role
templates:
    layout:              SonataAdminBundle::layout.html.twig
    search:              SonataAdminBundle:Core:search.html.twig
    search_result_block: SonataAdminBundle:Block:block_search_result.html.twig
    base_list_field:     SonataAdminBundle:CRUD:base_list_field.html.twig

dashboard:
    blocks:
        - { position: left, type: sonata.admin.block.admin_list }
    # Customize user portal menu by setting links
    groups:
        sonata.admin.group.purchase_order_item.open:
            on_top:          true
            label:           Open Items
            label_catalogue: messages
            icon:            '<i class="fa fa-square-o"></i>'
            items:
                - supplier_portal_backend.admin.purchase_open_order_item

        sonata.admin.group.purchase_order_item.confirmed:
            on_top:          true
            label:           Confirmed Items
            label_catalogue: messages
            icon:            '<i class="fa fa-check-square-o"></i>'
            items:
                - supplier_portal_backend.admin.purchase_confirmed_order_item

        sonata.admin.group.purchase_order_item.shipped:
            on_top:          true
            label:           Shipped Items
            label_catalogue: messages
            icon:            '<i class="fa fa-truck"></i>'
            items:
                - supplier_portal_backend.admin.purchase_shipped_order_item

        sonata.admin.group.purchase_order_item.all:
            on_top:          true
            label:           All Items
            label_catalogue: messages
            icon:            '<i class="fa fa-th-list"></i>'
            items:
                - supplier_portal_backend.admin.purchase_order_item

        sonata.admin.group.administration:
            on_top:          true
            label:           Users
            label_catalogue: messages
            icon:            '<i class="fa fa-users"></i>'
            items:
                - supplier_portal_backend.admin.user
            roles: [ ROLE_SUPER_ADMIN ]


问:
WebRequest not returning HTML
I want to load this http://www.yellowpages.ae/categories-by-alphabet/h.html url, but it returns null

In some question I have heard about adding Cookie container but it is already there in my code.

```<code>var MainUrl = "http://www.yellowpages.ae/categories-by-alphabet/h.html";
HtmlWeb web = new HtmlWeb();
web.PreRequest += request =>
{
    request.CookieContainer = new System.Net.CookieContainer();
    return true;
};
web.CacheOnly = false;
var doc = web.Load(MainUrl);
</code>```

the website opens perfectly fine in browser.

答:
You need CookieCollection to get cookies and set UseCookie to true in HtmlWeb.

```<code>CookieCollection cookieCollection = null;
var web = new HtmlWeb
{
    //AutoDetectEncoding = true,
    UseCookies = true,
    CacheOnly = false,
    PreRequest = request =>
    {
        if (cookieCollection != null && cookieCollection.Count > 0)
            request.CookieContainer.Add(cookieCollection);

        return true;
    },
    PostResponse = (request, response) => { cookieCollection = response.Cookies; }
};

var doc = web.Load("https://www.google.com");
</code>```

Title: WebRequest not returning HTML

Body:
I want to load this http://www.yellowpages.ae/categories-by-alphabet/h.html url, but it returns null

In some question I have heard about adding Cookie container but it is already there in my code.

var MainUrl = "http://www.yellowpages.ae/categories-by-alphabet/h.html";
HtmlWeb web = new HtmlWeb();
web.PreRequest += request =>
{
    request.CookieContainer = new System.Net.CookieContainer();
    return true;
};
web.CacheOnly = false;
var doc = web.Load(MainUrl);

the website opens perfectly fine in browser.

Body:
You need CookieCollection to get cookies and set UseCookie to true in HtmlWeb.

CookieCollection cookieCollection = null;
var web = new HtmlWeb
{
    //AutoDetectEncoding = true,
    UseCookies = true,
    CacheOnly = false,
    PreRequest = request =>
    {
        if (cookieCollection != null && cookieCollection.Count > 0)
            request.CookieContainer.Add(cookieCollection);

        return true;
    },
    PostResponse = (request, response) => { cookieCollection = response.Cookies; }
};

var doc = web.Load("https://www.google.com");


问:
how to identify if a number is of float or double type in java
How 19.5 is a double value. Why we need to append F to it to make it float? Just want to know how we identify a number whether it is float or double.

答:
19.5 is a floating-point literal in java. Quote from Java Language Specification #3.10.2:

A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise, its type is double and it can optionally be suffixed with an ASCII letter D or d.

Now when we know that 19.5 is of type double, let's look at your example in the comments:

```<code>float value = 19.5;
</code>```

Conversion from double to float in java is a narrowing primitive conversion. This type of conversion should be explicit. That's why you need to use floating-point literal of type float to get rid of the conversion

```<code>float value = 19.5f;
</code>```

or to make this conversion explicit

```<code>float value = (float) 19.5;
</code>```

Body:
19.5 is a floating-point literal in java. Quote from Java Language Specification #3.10.2:

A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise, its type is double and it can optionally be suffixed with an ASCII letter D or d.

Now when we know that 19.5 is of type double, let's look at your example in the comments:

float value = 19.5;

Conversion from double to float in java is a narrowing primitive conversion. This type of conversion should be explicit. That's why you need to use floating-point literal of type float to get rid of the conversion

float value = 19.5f;

or to make this conversion explicit

float value = (float) 19.5;


问:
Android displaying Multiple markers on Map Fragment
Im having trouble zooming the start point (green marker) and end point (red marker), My code zoom in just on the end point. see the picture below

enter image description here

im getting my first and last data by using this:

```<code>   public void createMarker(int index, Double latitude, Double longitude, String location, String remarks) {

    double latitudeStart, longitudeStart;
    double latitudeEnd, longitudeEnd;

    index = index + 1;
    String text = String.valueOf(index);

    BitmapDescriptor image = BitmapDescriptorFactory.fromResource(index);

    IconGenerator tc = new IconGenerator(getContext());

    if (index == 1) {
        image = BitmapDescriptorFactory.fromResource(R.drawable.pin_green);
        latitudeStart =latitude;
        longitudeStart = longitude;
        mMapSnailTrail.addMarker(new MarkerOptions()
                .position(new LatLng(latitude, longitude))
                .anchor(0.5f, 0.5f)
                .title(location)
                .snippet(remarks)
                .icon(image));

    } else if (index == response_last.body().getAsJsonArray().size()) {
        image = BitmapDescriptorFactory.fromResource(R.drawable.pin_red);
        latitudeEnd =latitude;
        longitudeEnd = longitude;
        mMapSnailTrail.addMarker(new MarkerOptions()
                .position(new LatLng(latitude, longitude))
                .anchor(0.5f, 0.5f)
                .title(location)
                .snippet(remarks)
                .icon(image));
    } else {

    }

    LatLngBounds.Builder builder = new LatLngBounds.Builder();
    builder.include(new LatLng(latitudeStart,longitudeStart));
    builder.include(new LatLng(latitudeEnd,longitudeEnd));
    LatLngBounds bounds = builder.build();
    mMapSnailTrail.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 10));

    mMapSnailTrail.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {
            marker.hideInfoWindow();
        }
    });
}
</code>```

the data latitude and longitude is coming from API which im getting them by this code:

```<code>String lati = jo.get("lat").toString();
                    String latiString = lati;
                    latiString = latiString.replace("\"", "");
                    String lat = String.valueOf(latiString);

                    String longi = jo.get("lng").toString();
                    String longiString = longi;
                    longiString = longiString.replace("\"", "");
                    String lng = String.valueOf(longiString);
</code>```

and lastly this is the create marker that I've been using:

```<code> LatLngBounds.Builder builder = new LatLngBounds.Builder();
    //starting point
    builder.include(new LatLng(latitude,longitude));
        //end point
    builder.include(new LatLng(latitude,longitude));

    LatLngBounds bounds = builder.build();
    mMapSnailTrail.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50));
</code>```

i really need your help to accomplish this task. I'm searching on the internet but i can't find a solution. thanks guys!

答:
Try to add this line of code</p>

```<code>map.getUiSettings().setZoomControlsEnabled(true);
</code>```

Body:
Im having trouble zooming the start point (green marker) and end point (red marker), My code zoom in just on the end point. see the picture below

enter image description here

im getting my first and last data by using this:

   public void createMarker(int index, Double latitude, Double longitude, String location, String remarks) {

    double latitudeStart, longitudeStart;
    double latitudeEnd, longitudeEnd;

    index = index + 1;
    String text = String.valueOf(index);

    BitmapDescriptor image = BitmapDescriptorFactory.fromResource(index);

    IconGenerator tc = new IconGenerator(getContext());

    if (index == 1) {
        image = BitmapDescriptorFactory.fromResource(R.drawable.pin_green);
        latitudeStart =latitude;
        longitudeStart = longitude;
        mMapSnailTrail.addMarker(new MarkerOptions()
                .position(new LatLng(latitude, longitude))
                .anchor(0.5f, 0.5f)
                .title(location)
                .snippet(remarks)
                .icon(image));

    } else if (index == response_last.body().getAsJsonArray().size()) {
        image = BitmapDescriptorFactory.fromResource(R.drawable.pin_red);
        latitudeEnd =latitude;
        longitudeEnd = longitude;
        mMapSnailTrail.addMarker(new MarkerOptions()
                .position(new LatLng(latitude, longitude))
                .anchor(0.5f, 0.5f)
                .title(location)
                .snippet(remarks)
                .icon(image));
    } else {

    }

    LatLngBounds.Builder builder = new LatLngBounds.Builder();
    builder.include(new LatLng(latitudeStart,longitudeStart));
    builder.include(new LatLng(latitudeEnd,longitudeEnd));
    LatLngBounds bounds = builder.build();
    mMapSnailTrail.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 10));

    mMapSnailTrail.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {
            marker.hideInfoWindow();
        }
    });
}

the data latitude and longitude is coming from API which im getting them by this code:

String lati = jo.get("lat").toString();
                    String latiString = lati;
                    latiString = latiString.replace("\"", "");
                    String lat = String.valueOf(latiString);

                    String longi = jo.get("lng").toString();
                    String longiString = longi;
                    longiString = longiString.replace("\"", "");
                    String lng = String.valueOf(longiString);

and lastly this is the create marker that I've been using:

 LatLngBounds.Builder builder = new LatLngBounds.Builder();
    //starting point
    builder.include(new LatLng(latitude,longitude));
        //end point
    builder.include(new LatLng(latitude,longitude));

    LatLngBounds bounds = builder.build();
    mMapSnailTrail.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50));

i really need your help to accomplish this task. I'm searching on the internet but i can't find a solution. thanks guys!

Body:
Try to add this line of code

map.getUiSettings().setZoomControlsEnabled(true);


问:
Obtaining mean of certain columns with specific names
I'm trying to find the mean of values in certain columns, and append that into a new column.

I have a variable containing a list of character elements, and these elements correspond to certain column names. For example,

```<code>qcs <- list.files(qcDirectory)
str(qcs)
chr [1:5] "201701" "201702" "201703" "201704"
</code>```

Here's an example data table:

```<code>        201701  201702  201703  201704
row1    12      20      50      54
row2    15      23      45      35
row3    16      20      52      58
row4    17      13      47      48
</code>```

For example, I'd like to get the average of the values contained in the columns named "201701" and "201702", so the expected output would be:

```<code>        201701  201702  201703  201704  mean
row1    12      20      50      54      16
row2    15      23      45      35      19
row3    16      20      52      58      18
row4    17      13      47      48      15
</code>```

I can't just apply it to the first x number of columns, because they could appear anywhere in the table. I'm thinking lapply might be the way to go, but I'm not sure how I would get this to work. In plain English, I basically want the function to be, "for all column names that are contained in this variable [qcs], find the mean of those values." Not sure whether I need some sort of a loop, or what. I'm sure the answer is already out there, but I'm a noob and having trouble trying to apply similar posts like this and this. I'm thinking something vaguely like what I have below, which can successfully identify the right columns to operate on, but that's just averaging the values in each column and outputting a list, rather than averaging the values across the rows of the relevant columns and putting them into a new column. Any ideas are appreciated.

```<code>sapply(colnames(datamatrix), function(c) {
  if (c %in% qcs) datamatrix$mean = mean(test1[, c])
})
</code>```

答:
This should be a strategy that will fit well in your situation, since (as I understand) you might want to compute this for several different combinations of columns.

Illustrating with the iris dataset: say you want to add a new column which for each row is the mean of the values in the "Sepal.Width" and "Petal.Width" columns at the corresponding row. Here is a vector holding the relevant column names (here they're selected by a pattern in the column name, as in your case as I understand it).

```<code>data(iris)
cname_pattern <- "Width"
target_cols <- grep(cname_pattern, names(iris), value=TRUE)
</code>```

Then you can just say

```<code>iris[[paste0(cname_pattern, "_mean")]] <- rowMeans(iris[, target_cols])
</code>```

And you'll get the mean of the relevant columns at each row in the new column. This should be flexible enough to fit the case at hand. Might want to use na.rm=TRUE in rowMeans() if it's possible there'll be missing values anywhere.

Body:
I'm trying to find the mean of values in certain columns, and append that into a new column.

I have a variable containing a list of character elements, and these elements correspond to certain column names. For example,

qcs <- list.files(qcDirectory)
str(qcs)
chr [1:5] "201701" "201702" "201703" "201704"

Here's an example data table:

        201701  201702  201703  201704
row1    12      20      50      54
row2    15      23      45      35
row3    16      20      52      58
row4    17      13      47      48

For example, I'd like to get the average of the values contained in the columns named "201701" and "201702", so the expected output would be:

        201701  201702  201703  201704  mean
row1    12      20      50      54      16
row2    15      23      45      35      19
row3    16      20      52      58      18
row4    17      13      47      48      15

I can't just apply it to the first x number of columns, because they could appear anywhere in the table. I'm thinking lapply might be the way to go, but I'm not sure how I would get this to work. In plain English, I basically want the function to be, "for all column names that are contained in this variable [qcs], find the mean of those values." Not sure whether I need some sort of a loop, or what. I'm sure the answer is already out there, but I'm a noob and having trouble trying to apply similar posts like this and this. I'm thinking something vaguely like what I have below, which can successfully identify the right columns to operate on, but that's just averaging the values in each column and outputting a list, rather than averaging the values across the rows of the relevant columns and putting them into a new column. Any ideas are appreciated.

sapply(colnames(datamatrix), function(c) {
  if (c %in% qcs) datamatrix$mean = mean(test1[, c])
})

Body:
This should be a strategy that will fit well in your situation, since (as I understand) you might want to compute this for several different combinations of columns.

Illustrating with the iris dataset: say you want to add a new column which for each row is the mean of the values in the "Sepal.Width" and "Petal.Width" columns at the corresponding row. Here is a vector holding the relevant column names (here they're selected by a pattern in the column name, as in your case as I understand it).

data(iris)
cname_pattern <- "Width"
target_cols <- grep(cname_pattern, names(iris), value=TRUE)

Then you can just say

iris[[paste0(cname_pattern, "_mean")]] <- rowMeans(iris[, target_cols])

And you'll get the mean of the relevant columns at each row in the new column. This should be flexible enough to fit the case at hand. Might want to use na.rm=TRUE in rowMeans() if it's possible there'll be missing values anywhere.


问:
Python input validation?
I have a simple input validation code asking the user for either ACT or SAT.

```<code>test=input("Are you taking SAT or ACT?..")
while test!=("SAT" or "ACT"):
    print("error")
    test=input("Are you taking SAT or ACT?..")
</code>```

It seems to work correctly for "SAT" which is in front on line 2, but not ACT! When I type in ACT in the module it will print "error" like it was false. What is my flaw here? Logic? Syntax? Semantic? What can I do to fix it?

Thank you.

答:
The expression ("SAT" or "ACT") evaluates to "SAT" since it basically evaluates the OR operation on two strings. In order to fix the issue, this is what you can do:

```<code>while(1):
    test = input("Are you taking SAT or ACT")
    if test in ("SAT", "ACT"):
        break

    print("Error")
</code>```

Title: Python input validation?

Body:
I have a simple input validation code asking the user for either ACT or SAT.

test=input("Are you taking SAT or ACT?..")
while test!=("SAT" or "ACT"):
    print("error")
    test=input("Are you taking SAT or ACT?..")

It seems to work correctly for "SAT" which is in front on line 2, but not ACT! When I type in ACT in the module it will print "error" like it was false. What is my flaw here? Logic? Syntax? Semantic? What can I do to fix it?

Thank you.

Body:
The expression ("SAT" or "ACT") evaluates to "SAT" since it basically evaluates the OR operation on two strings. In order to fix the issue, this is what you can do:

while(1):
    test = input("Are you taking SAT or ACT")
    if test in ("SAT", "ACT"):
        break

    print("Error")


问:
How to set the selection border of a Textfield a certain color in JavaFX?
I'm trying to create a Textfield in JavaFX. I would like to use a custom color for the selection of the Textfield. I'm not sure what the property is, so I can only explain it this way. When you select it by default, a sky-bluish color shows up on the border. How do I remove that completely, or set it to a custom color? Here is my CSS code:</p>

```<code>.login-info {
-fx-border-style: solid;

-fx-accent: red; }
</code>```

答:
The textfield uses -fx-background-color: property to achive that. So by overriding

```<code>.textfield:focused{
   -fx-background-color : yellow,white;
   -fx-background-insets: 0,3px;
}
</code>```

will make the border color yellow, instead of sky-blue when you click on it.

Body:
I'm trying to create a Textfield in JavaFX. I would like to use a custom color for the selection of the Textfield. I'm not sure what the property is, so I can only explain it this way. When you select it by default, a sky-bluish color shows up on the border. How do I remove that completely, or set it to a custom color? Here is my CSS code:

.login-info {
-fx-border-style: solid;

-fx-accent: red; }

Body:
The textfield uses -fx-background-color: property to achive that. So by overriding

.textfield:focused{
   -fx-background-color : yellow,white;
   -fx-background-insets: 0,3px;
}

will make the border color yellow, instead of sky-blue when you click on it.


问:
Multiple projects for Application Services in ASP.NET Boilerplate
I have an application with two projects that contain IApplicationService classes, but the framework only resolves client proxies (in JavaScript: abp.services.app.xxxx) by default for Application project that comes with base template.

```<code>myProject.Application => default ASP.NET Boilerplate
</code>```

```<code>myProject.ExtraServices => my own (not generating client proxies)
</code>```

Thanks.

答:
ASP.NET Core

Create controllers for your ExtraServices project in MyProjectWebCoreModule:

Configuration.Modules.AbpAspNetCore()
    .CreateControllersForAppServices(
        typeof(ExtraServicesModule).GetAssembly()
    );
```

<h1>ASP.NET MVC 5</h1>

<p>Create controllers for your <code>ExtraServices</code> project in MyProjectWebApiModule:</p>

<pre class="lang-cs prettyprint-override"><code>Configuration.Modules.AbpWebApi().DynamicApiControllerBuilder
    .ForAll<IApplicationService>(typeof(ExtraServicesModule).Assembly, "app")
    .Build();
</code>```

Body:
I have an application with two projects that contain IApplicationService classes, but the framework only resolves client proxies (in JavaScript: abp.services.app.xxxx) by default for Application project that comes with base template.

myProject.Application => default ASP.NET Boilerplate

myProject.ExtraServices => my own (not generating client proxies)

Thanks.

Body:
ASP.NET Core

Create controllers for your ExtraServices project in MyProjectWebCoreModule:

Configuration.Modules.AbpAspNetCore()
    .CreateControllersForAppServices(
        typeof(ExtraServicesModule).GetAssembly()
    );

ASP.NET MVC 5

Create controllers for your ExtraServices project in MyProjectWebApiModule:

Configuration.Modules.AbpWebApi().DynamicApiControllerBuilder
    .ForAll<IApplicationService>(typeof(ExtraServicesModule).Assembly, "app")
    .Build();


问:
Split TypeScript namespaces between files - Intellisense Error
I am new to TypeScript and trying to not get off to a bad start.  Using TypeScript 2.5.3 within Visual Studio 2017 I am getting intellsense errors saying "Duplicate Identifier 'MyCo'".  Am I doing something wrong here and if so how should I be doing this?  The code runs as desired but VS intellisense is calling this an error.

MyCo.TestSuite1.ts

```<code>namespace MyCo {
  export class TestSuite1 {
    run() {
      alert("MyCo.TestSuite1.run");
    }
  }
}
</code>```

MyCo.TestSuite2.ts

```<code>namespace MyCo {
  export class TestSuite2 {
    run() {
      alert("MyCo.TestSuite2.run");
    }
  }
}
</code>```

App.ts

```<code>/// <reference path="MyCo.TestSuite1.ts" />
/// <reference path="MyCo.TestSuite2.ts" />

namespace MyCo {
  export class Main {
    run() {
      var ts1 = new MyCo.TestSuite1();
      ts1.run();
      var ts2 = new MyCo.TestSuite2();
      ts2.run();
    }
  }
}

(function () {
  var main = new MyCo.Main();
  main.run();
})();
</code>```

答:
You Main class is :

```<code> export class Main {
    run() {
      var ts1 = new MyCo.TestSuite1();
      ts1.run();
      var ts2 = new MyCo.TestSuite2();
      ts2.run();
    }
</code>```

but your MyCo.TestSuite1.ts  has export class TestSuite2 not TestSuite1
Check class names in your .ts file

Body:
I am new to TypeScript and trying to not get off to a bad start.  Using TypeScript 2.5.3 within Visual Studio 2017 I am getting intellsense errors saying "Duplicate Identifier 'MyCo'".  Am I doing something wrong here and if so how should I be doing this?  The code runs as desired but VS intellisense is calling this an error.

MyCo.TestSuite1.ts

namespace MyCo {
  export class TestSuite1 {
    run() {
      alert("MyCo.TestSuite1.run");
    }
  }
}

MyCo.TestSuite2.ts

namespace MyCo {
  export class TestSuite2 {
    run() {
      alert("MyCo.TestSuite2.run");
    }
  }
}

App.ts

/// <reference path="MyCo.TestSuite1.ts" />
/// <reference path="MyCo.TestSuite2.ts" />

namespace MyCo {
  export class Main {
    run() {
      var ts1 = new MyCo.TestSuite1();
      ts1.run();
      var ts2 = new MyCo.TestSuite2();
      ts2.run();
    }
  }
}

(function () {
  var main = new MyCo.Main();
  main.run();
})();

Body:
You Main class is :

 export class Main {
    run() {
      var ts1 = new MyCo.TestSuite1();
      ts1.run();
      var ts2 = new MyCo.TestSuite2();
      ts2.run();
    }

but your MyCo.TestSuite1.ts  has export class TestSuite2 not TestSuite1
Check class names in your .ts file


问:
Two controllers for one shared view in Ruby on Rails
I have two controllers for two respective models, by example, photos and categories. index and show methods are very similar in each controller, and the views are identical. What is the best method for share the view by the two models?

I've though two options:

Use a helper. In the helper will put the code for the view, and will call the helper from each view (photos/views and categories/views)

Use a partial in each views. I think it's a more clean solution, but I see huge DRY's in my mind when going to code this solution.

So, I have two controllers from two models, each one at and exposes a @photo object (photos controller with all the photos, and categories controller with just the selected categorie's photos) and I need one view to show both.

I'm looking for an elegant solution for this, complaining REST and DRY principes. Any idea?

Thanks in advance.

答:
I have a similar situation with one of my projects. All the delete views for most controllers are styled the same way, display the same confirmation boxes, and simply renders a predictable display of whatever object is being deleted.

The solution was quite simple and elegant in my opinion. Simply put, what we (the developers) did was create a new directory in app/views called shared and put shared views in there. These could be full template files or just partials.

I would suggest using a shared template (in neither categories nor photos view directories, but rather in the shared directory) and rendering it manually from the view.

e.g. have a method as such in both controllers and a file app/views/shared/photo.html.erb:

```<code>def show
  @photo = Photo.first # ... or whatever here
  render :template => 'shared/photo'
end
</code>```

This should successfully render the shared template. It is the DRYest route and doesn't have the feeling of pollution you get when using a more-or-less empty view in each controller's view directory just to include a shared partial, as I understand your question is suggesting.

OwnerDisplayName: ARemesal

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Beds

Body:
I have a similar situation with one of my projects. All the delete views for most controllers are styled the same way, display the same confirmation boxes, and simply renders a predictable display of whatever object is being deleted.

The solution was quite simple and elegant in my opinion. Simply put, what we (the developers) did was create a new directory in app/views called shared and put shared views in there. These could be full template files or just partials.

I would suggest using a shared template (in neither categories nor photos view directories, but rather in the shared directory) and rendering it manually from the view.

e.g. have a method as such in both controllers and a file app/views/shared/photo.html.erb:

def show
  @photo = Photo.first # ... or whatever here
  render :template => 'shared/photo'
end

This should successfully render the shared template. It is the DRYest route and doesn't have the feeling of pollution you get when using a more-or-less empty view in each controller's view directory just to include a shared partial, as I understand your question is suggesting.

OwnerDisplayName: bjeanes

LastEditorDisplayName: bjeanes


问:
Check Bluetooth status - Swift 4
I have a problem with the Bluetooth in Xcode. I can’t find a great solution on how to check if Bluetooth is on or not. I want just that. I searched around the web some solution, but nothing works for me. Any idea on how to check Bluetooth? I imported the CoreBluetooth class and I made this line of code:</p>

```<code>if CBPeripheralManager.authorizationStatus() == .denied { code }
if CBPeripheralManager.authorizationStatus() == .authorized  { code }
</code>```

答:
Implement CBCentralManagerDelegate delegate for that.

```<code> var manager:CBCentralManager!

 viewDidLoad() {      // Or init()
     manager          = CBCentralManager()
     manager.delegate = self
 }
</code>```

Delegate method :

```<code>func centralManagerDidUpdateState(_ central: CBCentralManager) {
    switch central.state {
    case .poweredOn:
        break
    case .poweredOff:
        print("Bluetooth is Off.")
        break
    case .resetting:
        break
    case .unauthorized:
        break
    case .unsupported:
        break
    case .unknown:
        break
    default:
        break
    }
}
</code>```

Title: Check Bluetooth status - Swift 4

Body:
I have a problem with the Bluetooth in Xcode. I can’t find a great solution on how to check if Bluetooth is on or not. I want just that. I searched around the web some solution, but nothing works for me. Any idea on how to check Bluetooth? I imported the CoreBluetooth class and I made this line of code:

if CBPeripheralManager.authorizationStatus() == .denied { code }
if CBPeripheralManager.authorizationStatus() == .authorized  { code }

Body:
Implement CBCentralManagerDelegate delegate for that.

 var manager:CBCentralManager!

 viewDidLoad() {      // Or init()
     manager          = CBCentralManager()
     manager.delegate = self
 }

Delegate method :

func centralManagerDidUpdateState(_ central: CBCentralManager) {
    switch central.state {
    case .poweredOn:
        break
    case .poweredOff:
        print("Bluetooth is Off.")
        break
    case .resetting:
        break
    case .unauthorized:
        break
    case .unsupported:
        break
    case .unknown:
        break
    default:
        break
    }
}


问:
Subscription API in recurly
I am trying to fetch subscription data using recurly.js api in PHP.Below is my code:

```<code>require_once('lib/recurly.php');
Recurly_Client::$subdomain = 'https://subdomain.recurly.com/v2/subscriptions';
Recurly_Client::$apiKey = 'privatekey';
$subscriptions = Recurly_SubscriptionList::getActive();
print_r($subscriptions);
foreach ($subscriptions as $subscription) {
   print_r($subscription);
}
</code>```

$subscriptions is printing this:

```<code>Recurly_SubscriptionList Object(
  [_position:Recurly_Pager:private] => 0
  [_objects:protected] =>
  [_href:protected] => /subscriptions?state=active
  [_type:protected] =>
  [_client:protected] => Recurly_Client Object
    (
        [_apiKey:Recurly_Client:private] =>
        [_acceptLanguage:Recurly_Client:private] => en-US
    )

  [_links:protected] => Array
    (
    )
)
</code>```

While $subscription is printing nothing.What went wrong that the result is not the list of the subscriptions.

答:
Since print_r(gettype($subscription)); is an object you cannot treat it as an array. In order to get the properties of an object as an array you can use an inbuilt function get_obj_vars.

You may follow this code:

```<code>require_once('lib/recurly.php');
Recurly_Client::$subdomain = 'https://subdomain.recurly.com/v2/subscriptions';
Recurly_Client::$apiKey = 'privatekey';
$subscriptions = Recurly_SubscriptionList::getActive();
foreach(get_obj_vars($subscription) as $key => $value) {
    echo $key . ' => ' . $value;
}
</code>```

This would basically create an array of all public members in the object $subscriptions. But, as your output for print_r($subscriptions); contains only private and protected members, it would practically return you an empty array.

Title: Subscription API in recurly

Body:
I am trying to fetch subscription data using recurly.js api in PHP.Below is my code:

require_once('lib/recurly.php');
Recurly_Client::$subdomain = 'https://subdomain.recurly.com/v2/subscriptions';
Recurly_Client::$apiKey = 'privatekey';
$subscriptions = Recurly_SubscriptionList::getActive();
print_r($subscriptions);
foreach ($subscriptions as $subscription) {
   print_r($subscription);
}

$subscriptions is printing this:

Recurly_SubscriptionList Object(
  [_position:Recurly_Pager:private] => 0
  [_objects:protected] =>
  [_href:protected] => /subscriptions?state=active
  [_type:protected] =>
  [_client:protected] => Recurly_Client Object
    (
        [_apiKey:Recurly_Client:private] =>
        [_acceptLanguage:Recurly_Client:private] => en-US
    )

  [_links:protected] => Array
    (
    )
)

While $subscription is printing nothing.What went wrong that the result is not the list of the subscriptions.

Body:
Since print_r(gettype($subscription)); is an object you cannot treat it as an array. In order to get the properties of an object as an array you can use an inbuilt function get_obj_vars.

You may follow this code:

require_once('lib/recurly.php');
Recurly_Client::$subdomain = 'https://subdomain.recurly.com/v2/subscriptions';
Recurly_Client::$apiKey = 'privatekey';
$subscriptions = Recurly_SubscriptionList::getActive();
foreach(get_obj_vars($subscription) as $key => $value) {
    echo $key . ' => ' . $value;
}

This would basically create an array of all public members in the object $subscriptions. But, as your output for print_r($subscriptions); contains only private and protected members, it would practically return you an empty array.


问:
getCurrentPosition doesn't work on ionic application
I am working on ionic application.

```<code>import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { MenuController, NavController, NavParams } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
import { RoleService } from '../../services/role.service';
import { RoleViewDto } from '../../contracts/role/roleViewDto';
import { RoleType } from '../../contracts/enums/enums';

import { GoogleMapsService } from '../../services/google-maps.service';
import { CommonService } from '../../services/common.service';

declare var google;

@Component({
    selector: 'pwssr-welcome',
    templateUrl: 'welcome.page.html',
})
export class WelcomePage implements OnInit {
@ViewChild('map') mapElement: ElementRef;
map: any;
role: RoleViewDto;
roleType = RoleType;

lat: number;
lng: number;

marker: any;

constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    public geolocation: Geolocation,
    private roleService: RoleService,
    private googleMapsService: GoogleMapsService,
    private commonService: CommonService,
) {
}

ngOnInit() {
    this.commonService.setTitle("Sweet Rides");
    this.roleService.getRole().subscribe((res) => {
        this.role = res;
    });
}

ionViewDidLoad() {
    this.loadMap();
}

loadMap() {

    this.geolocation.getCurrentPosition().then((position) => {

        let latLng = new google.maps.LatLng(-32.3003176, 115.7749078);

        this.map = this.googleMapsService.get(latLng, this.mapElement);

    }, (err) => {
        console.log(err);
        }).catch(error => {
            console.log('[DEBUG] Promise Unfulfilled. ' + JSON.stringify(error));
        });

}
</code>```

this code is working on web browsers but it doesn't work on android devices after building apk. I installed the Cordova and Ionic Native plugins using this tutorial https://ionicframework.com/docs/native/geolocation/

```<code>ionic info

cli packages: (C:\Users\Peda\AppData\Roaming\npm\node_modules)

   @ionic/cli-utils  : 1.18.0
   ionic (Ionic CLI) : 3.18.0

global packages:

   cordova (Cordova CLI) : not installed

local packages:

    @ionic/app-scripts : 1.3.7
    Cordova Platforms  : android 6.2.3
    Ionic Framework    : ionic-angular 3.6.0

System:

    Node : v6.11.2
    npm  : 3.10.10
    OS   : Windows 10

Environment Variables:

    ANDROID_HOME : not set

Misc:

    backend : legacy
</code>```

Looks like this.geolocation.getCurrentPosition doesn't work. Also I don't have any error messages in console

答:
Try this and let me know:</p>

```<code> let element = document.getElementById('map');
 let map: GoogleMap = this.googleMaps.create(element);
 map.getMyLocation((loc: any)=>{
        console.log("--Latitude--" + loc.latLng.lat);
        console.log("--Longitude--" + loc.latLng.lng);
       }).catch((error) => {
          console.log("--Error--");
        });
</code>```

Body:
I am working on ionic application.

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { MenuController, NavController, NavParams } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
import { RoleService } from '../../services/role.service';
import { RoleViewDto } from '../../contracts/role/roleViewDto';
import { RoleType } from '../../contracts/enums/enums';

import { GoogleMapsService } from '../../services/google-maps.service';
import { CommonService } from '../../services/common.service';

declare var google;

@Component({
    selector: 'pwssr-welcome',
    templateUrl: 'welcome.page.html',
})
export class WelcomePage implements OnInit {
@ViewChild('map') mapElement: ElementRef;
map: any;
role: RoleViewDto;
roleType = RoleType;

lat: number;
lng: number;

marker: any;

constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    public geolocation: Geolocation,
    private roleService: RoleService,
    private googleMapsService: GoogleMapsService,
    private commonService: CommonService,
) {
}

ngOnInit() {
    this.commonService.setTitle("Sweet Rides");
    this.roleService.getRole().subscribe((res) => {
        this.role = res;
    });
}

ionViewDidLoad() {
    this.loadMap();
}

loadMap() {

    this.geolocation.getCurrentPosition().then((position) => {

        let latLng = new google.maps.LatLng(-32.3003176, 115.7749078);

        this.map = this.googleMapsService.get(latLng, this.mapElement);

    }, (err) => {
        console.log(err);
        }).catch(error => {
            console.log('[DEBUG] Promise Unfulfilled. ' + JSON.stringify(error));
        });

}

this code is working on web browsers but it doesn't work on android devices after building apk. I installed the Cordova and Ionic Native plugins using this tutorial https://ionicframework.com/docs/native/geolocation/

ionic info

cli packages: (C:\Users\Peda\AppData\Roaming\npm\node_modules)

   @ionic/cli-utils  : 1.18.0
   ionic (Ionic CLI) : 3.18.0

global packages:

   cordova (Cordova CLI) : not installed

local packages:

    @ionic/app-scripts : 1.3.7
    Cordova Platforms  : android 6.2.3
    Ionic Framework    : ionic-angular 3.6.0

System:

    Node : v6.11.2
    npm  : 3.10.10
    OS   : Windows 10

Environment Variables:

    ANDROID_HOME : not set

Misc:

    backend : legacy

Looks like this.geolocation.getCurrentPosition doesn't work. Also I don't have any error messages in console

Body:
Try this and let me know:

 let element = document.getElementById('map');
 let map: GoogleMap = this.googleMaps.create(element);
 map.getMyLocation((loc: any)=>{
        console.log("--Latitude--" + loc.latLng.lat);
        console.log("--Longitude--" + loc.latLng.lng);
       }).catch((error) => {
          console.log("--Error--");
        });


问:
How to iterate over numeric keys from an array in order to make them accessible in a newly created object from the same array?
Consider the below code snippet :

```<code><?php
  $obj = (object) array('1' => 'foo');
  var_dump(isset($obj->{'1'})); // outputs 'bool(false)'
  var_dump(key($obj)); // outputs 'int(1)'
?>
</code>```

The output of above code in a web browser is below :

```<code>bool(false) int(1)
</code>```

You can see from the output that after converting the array $obj into an object I'm not able to access the key of an array(i.e.'1') as an object property and it's corresponding value(i.e.'foo')?

How to make them accessible?

答:
Here is the trick rather using typecasting do it with

```<code>$obj = array('1' => 'foo');
$obj = json_decode(json_encode($obj));
echo $obj->{'1'};
</code>```

// it will output 'foo'

Body:
Consider the below code snippet :

<?php
  $obj = (object) array('1' => 'foo');
  var_dump(isset($obj->{'1'})); // outputs 'bool(false)'
  var_dump(key($obj)); // outputs 'int(1)'
?>

The output of above code in a web browser is below :

bool(false) int(1)

You can see from the output that after converting the array $obj into an object I'm not able to access the key of an array(i.e.'1') as an object property and it's corresponding value(i.e.'foo')?

How to make them accessible?

Body:
Here is the trick rather using typecasting do it with

$obj = array('1' => 'foo');
$obj = json_decode(json_encode($obj));
echo $obj->{'1'};

// it will output 'foo'


问:
how to pass react-intl as argument in react component method while jest testing, throws 'TypeError: intl.formatMessage is not a function'
I am doing unit testing for my react component(using jest). I have few methods that are called from the component.
For Example:

```<code>    export function getText(text, intl) => ((text !== 'NA') ? (intl.formatMessage({ id: value })) : '');

    const ReactComponent = (props) => {
       const text = getText(text, intl);

       return (....);
    }

    export default injectIntl(ReactComponent);
</code>```

in test file i have:

```<code>    import { getText } from 'path';
    import { intl } from 'react-intl';

    it('should render text', () => {
      expect(getText('string', { intl })).toBe('string');
    });
</code>```

When i try to run test, it throws error intl.formatMessage is not a function.

答:
Your getText method requires 2 arguments (text and intl).

```<code>const getText = (text, intl) => ((text !== 'NA') ? (intl.formatMessage({ id: value })) : '')
</code>```

is the same as:

```<code>const getText = (text, intl) => {
  if (text !== 'NA') {
    return intl.formatMessage({ id: value })
  }

  return ''
}
</code>```

You are currently calling your test method with getText('string'). Consequently, text (first argument) is different than NA and getText is going to return intl.formatMessage(...).
Since you didn't provide intl, you method will eventually break. That's why you got it throws another error 'formatMessage is not a function' message.

While testing, make sure you are exporting getText so you can use it.

Instead of

const getText = (...)

Use:

export const getText = (...)

so then you can use it as:

import { getText } from 'path/to/gettext'

Body:
I am doing unit testing for my react component(using jest). I have few methods that are called from the component.
For Example:

    export function getText(text, intl) => ((text !== 'NA') ? (intl.formatMessage({ id: value })) : '');

    const ReactComponent = (props) => {
       const text = getText(text, intl);

       return (....);
    }

    export default injectIntl(ReactComponent);

in test file i have:

    import { getText } from 'path';
    import { intl } from 'react-intl';

    it('should render text', () => {
      expect(getText('string', { intl })).toBe('string');
    });

When i try to run test, it throws error intl.formatMessage is not a function.

Body:
Your getText method requires 2 arguments (text and intl).

const getText = (text, intl) => ((text !== 'NA') ? (intl.formatMessage({ id: value })) : '')

is the same as:

const getText = (text, intl) => {
  if (text !== 'NA') {
    return intl.formatMessage({ id: value })
  }

  return ''
}

You are currently calling your test method with getText('string'). Consequently, text (first argument) is different than NA and getText is going to return intl.formatMessage(...).
Since you didn't provide intl, you method will eventually break. That's why you got it throws another error 'formatMessage is not a function' message.

While testing, make sure you are exporting getText so you can use it.

Instead of

const getText = (...)

Use:

export const getText = (...)

so then you can use it as:

import { getText } from 'path/to/gettext'


问:
sum array from map result dynamically using javascript
I am getting the array from multidimensional array using map. Below is my code

```<code> var data = [{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},
        {"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},
        {"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}]
var result = data.map(function(arr, count) {
  return arr.points;
});
</code>```

Output is [36, 122, 25].
But i need the sum as 183?

答:
Use Array#reduce method to get the sum of the property.

var data = [{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},
        {"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},
        {"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}]

var result = data.reduce(function(tot, arr) {
  // return the sum with previous value
  return tot + arr.points;

  // set initial value as 0
},0);

console.log(result);```

Body:
I am getting the array from multidimensional array using map. Below is my code

 var data = [{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},
        {"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},
        {"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}]
var result = data.map(function(arr, count) {
  return arr.points;
});

Output is [36, 122, 25].
But i need the sum as 183?


答:
you will need to use CBCentralManager and it provide delegate method "centralManagerDidUpdateState" https://developer.apple.com/documentation/corebluetooth/cbcentralmanager</p>

```<code>func centralManagerDidUpdateState(_ central: CBCentralManager)
{
    if central.state == .poweredOn
    {
        print("Searching for BLE Devices")

        // Scan for peripherals if BLE is turned on
    }
    else
    {
        // Can have different conditions for all states if needed - print generic message for now, i.e. Bluetooth isn't On
        print("Bluetooth switched off or not initialized")
    }
}
</code>```

Title: Check Bluetooth status - Swift 4

Body:
you will need to use CBCentralManager and it provide delegate method "centralManagerDidUpdateState" https://developer.apple.com/documentation/corebluetooth/cbcentralmanager

func centralManagerDidUpdateState(_ central: CBCentralManager)
{
    if central.state == .poweredOn
    {
        print("Searching for BLE Devices")

        // Scan for peripherals if BLE is turned on
    }
    else
    {
        // Can have different conditions for all states if needed - print generic message for now, i.e. Bluetooth isn't On
        print("Bluetooth switched off or not initialized")
    }
}


问:
Print entire PHP array in 1 html table cell
so I'm trying to get my PHP array to print an entire array within one td, so I want the table to look like this:

```<code>First  ---  Last  ---  Values
John   --  Smith  --  1,2,4,6
</code>```

$comp_labs holds the values (1,2,4,6 for example)

Here's the code I've got at the moment:

```<code>echo "<tr>";
echo "
<td> ".$firstName."</td>
<td> ".$lastName."</td>
<td> ".$comp_labs."</td>
</tr>\n";
echo "</table>";
</code>```

it's printing the name fine but only the last element of the array. I tried looping through just that td printing array[i] like so:

```<code>echo "<tr>";
echo "
<td> ".$firstName."</td>
<td> ".$lastName."</td>
<td> "for($i=0; $i < count($comp_labs); $i++){.$comp_labs[i].}"</td>
</tr>\n";
echo "</table>";
</code>```

but it didn't like that. However if I just Echo out the $comp_labs array outside of the table it prints the entire array fine, which I find a little confusing. I've had a look online but every forum I've come across has been people trying to loop through and print 1 value per td, not all values in one td.

If anyone is able to help out here I would greatly appreciate it, thanks in advance!

答:
You need implode()

```<code> <td> ".implode(",", $comp_labs )."</td>
</code>```

So it becomes :

```<code>echo "<tr>
              <td> ".$firstName."</td>
              <td> ".$lastName."</td>
              <td> ".implode(",", $comp_labs)."</td>
     </tr>\n";
</code>```

Body:
so I'm trying to get my PHP array to print an entire array within one td, so I want the table to look like this:

First  ---  Last  ---  Values
John   --  Smith  --  1,2,4,6

$comp_labs holds the values (1,2,4,6 for example)

Here's the code I've got at the moment:

echo "
";
echo "
 ".$firstName."
 ".$lastName."
 ".$comp_labs."

\n";
echo "
";

it's printing the name fine but only the last element of the array. I tried looping through just that td printing array[i] like so:

echo "
";
echo "
 ".$firstName."
 ".$lastName."
 "for($i=0; $i < count($comp_labs); $i++){.$comp_labs[i].}"

\n";
echo "
";

but it didn't like that. However if I just Echo out the $comp_labs array outside of the table it prints the entire array fine, which I find a little confusing. I've had a look online but every forum I've come across has been people trying to loop through and print 1 value per td, not all values in one td.

If anyone is able to help out here I would greatly appreciate it, thanks in advance!

Body:
You need implode()

 <td> ".implode(",", $comp_labs )."</td>

So it becomes :

echo "<tr>
              <td> ".$firstName."</td>
              <td> ".$lastName."</td>
              <td> ".implode(",", $comp_labs)."</td>
     </tr>\n";


问:
Stopping supervisord: Shut down
I tired to start supervisor but getting error. Can anyone help? Thanks

/etc/init.d/supervisord file.

```<code>SUPERVISORD=/usr/local/bin/supervisord
SUPERVISORCTL=/usr/local/bin/supervisorctl
case $1 in
start)
        echo -n "Starting supervisord: "
        $SUPERVISORD
        echo
        ;;
stop)
        echo -n "Stopping supervisord: "
        $SUPERVISORCTL shutdown
        echo
        ;;
restart)
        echo -n "Stopping supervisord: "
        $SUPERVISORCTL shutdown
        echo
        echo -n "Starting supervisord: "
        $SUPERVISORD
        echo
        ;;
esac
</code>```

Then run these

```<code>sudo chmod +x /etc/init.d/supervisord
sudo update-rc.d supervisord defaults
sudo /etc/init.d/supervisord start
</code>```

And getting this:

```<code>Stopping supervisord: Shut down

Starting supervisord: /usr/local/lib/python2.7/dist-packages/supervisor/options.py:286: UserWarning: Supervisord is running as root and it is searching for its configuration file in default locations (including its current working directory); you probably want to specify a "-c" argument specifying an absolute path to a configuration file for improved security.
  'Supervisord is running as root and it is searching '
Error: Another program is already listening on a port that one of our HTTP servers is configured to use.  Shut this program down first before starting supervisord.
For help, use /usr/local/bin/supervisord -h
</code>```

Conf file (located at /etc/supervisord.conf):

```<code>[unix_http_server]
file=/tmp/supervisor.sock; (the path to the socket file)

[supervisord]
logfile=/tmp/supervisord.log ; (main log file;default $CWD/supervisord.log)
logfile_maxbytes=50MB       ; (max main logfile bytes b4 rotation;default 50MB)
logfile_backups=10          ; (num of main logfile rotation backups;default 10)
loglevel=info               ; (log level;default info; others: debug,warn,trace)
pidfile=/tmp/supervisord.pid ; (supervisord pidfile;default supervisord.pid)
nodaemon=false              ; (start in foreground if true;default false)
minfds=1024                 ; (min. avail startup file descriptors;default 1024)
minprocs=200                ; (min. avail process descriptors;default 200)

[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

[supervisorctl]
serverurl=unix:///tmp/supervisor.sock; use a unix:// URL  for a unix socket

[program:myproject]
command=/home/richard/envs/myproject_stage/bin/python /home/richard/webapps/myproject/manage.py run_gunicorn -b 127.0.0.1:8002 --log-file=/tmp/myproject_stage_gunicorn.log
directory=/home/richard/webapps/myproject/
user=www-data
autostart=true
autorestart=true
stdout_logfile=/tmp/myproject_stage_supervisord.log
redirect_stderr=true
</code>```

答:
```<code>$ ps aux | grep supervisor
alexamil         54253   0.0  0.0  2506960   6440   ??  Ss   10:09PM   0:00.26 /usr/bin/python /usr/local/bin/supervisord -c supervisord.conf
</code>```

so we can use:

```<code>$ pkill -f supervisord  # kill it
</code>```

Title: Stopping supervisord: Shut down

Body:
I tired to start supervisor but getting error. Can anyone help? Thanks

/etc/init.d/supervisord file.

SUPERVISORD=/usr/local/bin/supervisord
SUPERVISORCTL=/usr/local/bin/supervisorctl
case $1 in
start)
        echo -n "Starting supervisord: "
        $SUPERVISORD
        echo
        ;;
stop)
        echo -n "Stopping supervisord: "
        $SUPERVISORCTL shutdown
        echo
        ;;
restart)
        echo -n "Stopping supervisord: "
        $SUPERVISORCTL shutdown
        echo
        echo -n "Starting supervisord: "
        $SUPERVISORD
        echo
        ;;
esac

Then run these

sudo chmod +x /etc/init.d/supervisord
sudo update-rc.d supervisord defaults
sudo /etc/init.d/supervisord start

And getting this:

Stopping supervisord: Shut down

Starting supervisord: /usr/local/lib/python2.7/dist-packages/supervisor/options.py:286: UserWarning: Supervisord is running as root and it is searching for its configuration file in default locations (including its current working directory); you probably want to specify a "-c" argument specifying an absolute path to a configuration file for improved security.
  'Supervisord is running as root and it is searching '
Error: Another program is already listening on a port that one of our HTTP servers is configured to use.  Shut this program down first before starting supervisord.
For help, use /usr/local/bin/supervisord -h

Conf file (located at /etc/supervisord.conf):

[unix_http_server]
file=/tmp/supervisor.sock; (the path to the socket file)

[supervisord]
logfile=/tmp/supervisord.log ; (main log file;default $CWD/supervisord.log)
logfile_maxbytes=50MB       ; (max main logfile bytes b4 rotation;default 50MB)
logfile_backups=10          ; (num of main logfile rotation backups;default 10)
loglevel=info               ; (log level;default info; others: debug,warn,trace)
pidfile=/tmp/supervisord.pid ; (supervisord pidfile;default supervisord.pid)
nodaemon=false              ; (start in foreground if true;default false)
minfds=1024                 ; (min. avail startup file descriptors;default 1024)
minprocs=200                ; (min. avail process descriptors;default 200)

[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

[supervisorctl]
serverurl=unix:///tmp/supervisor.sock; use a unix:// URL  for a unix socket

[program:myproject]
command=/home/richard/envs/myproject_stage/bin/python /home/richard/webapps/myproject/manage.py run_gunicorn -b 127.0.0.1:8002 --log-file=/tmp/myproject_stage_gunicorn.log
directory=/home/richard/webapps/myproject/
user=www-data
autostart=true
autorestart=true
stdout_logfile=/tmp/myproject_stage_supervisord.log
redirect_stderr=true

Body:
$ ps aux | grep supervisor
alexamil         54253   0.0  0.0  2506960   6440   ??  Ss   10:09PM   0:00.26 /usr/bin/python /usr/local/bin/supervisord -c supervisord.conf

so we can use:

$ pkill -f supervisord  # kill it


问:
Azure Data Factory: does Start Integration Runtime cost me?
I have several SSIS packages that I want to deploy and to run periodically. I am following this MS tutorial.

Somewhere near the end there's a command to start Integration runtime. I got a bit put off because it said it will take 20-30mins to complete. So my main question is: Will I get billed if I complete the start Integration runtime command but do not execute any SSIS package?

I read in Data Factory Pricing that

An inactive pipeline is charged at $0.40 per month

But I have had no experience with it yet and I want to be certain I am not wasting my dev allowance.

And if it really is (almost) free unless I do start executing packages, once I start the runtime, then am I supposed to just leave it running?

Also, I have searched online several times but didn't find any tutorial on how to create an integration runtime via portal. Is that really the case?

Lastly, I am trying to deploy these SSIS packages to a SQL Server that has nothing to do with either the source or destination SQL Server - both servers are owned by someone else. Is that fine?

答:
Yes, you will be billed as the SSIS IR is started, regardless if you are executing the package or not. Currently, in ADF V2, Azure SSIS IR is a dedicated pool model, so that as long as your start the pool, it's dedicated for you to use only and it's running. The pricing for the Azure SSIS IR is listed under the section called "SQL Server Integration Services compute resource through Azure-SSIS Integration Runtime" on the ADF V2 pricing page.

if you do not want to be billed while not running packages, you need to stop the IR explicitly. thanks

jimmy


问:
Addition 2 Matrix Erlang
I have a question
I want to do the addition of 2 matrix by row in erlang, I'm trying to apply the code for Haskell:

```<code>add :: Num a => [[a]] -> [[a]] -> [[a]]
add = zipWith $ zipWith (+)
</code>```

I did something like this:

```<code>add([[]],[[]]) -> []
add = zipWith $ zipWith (+)
</code>```

but it get's an error, with the $, I'm really confused. How can I do this in erlang?

And works in this way:

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

Result:

```<code>[[ 6, 8], [ 10, 12]]
</code>```

Title: Addition 2 Matrix Erlang

Body:
I have a question
I want to do the addition of 2 matrix by row in erlang, I'm trying to apply the code for Haskell:

add :: Num a => [[a]] -> [[a]] -> [[a]]
add = zipWith $ zipWith (+)

I did something like this:

add([[]],[[]]) -> []
add = zipWith $ zipWith (+)

but it get's an error, with the $, I'm really confused. How can I do this in erlang?

And works in this way:

  add([[ 1, 2 ],[ 3 , 4 ]] , [[ 4 , 5 ],[ 6 , 7 ]] ).

Result:

[[ 6, 8], [ 10, 12]]

Body:
1> shell:strings(false).
true
2> AddRow = fun(X, Y) -> lists:zipwith(fun erlang:'+'/2, X, Y) end.
#Fun<erl_eval.12.99386804>
3> Add = fun(X, Y) -> lists:zipwith(AddRow, X, Y) end.
#Fun<erl_eval.12.99386804>
4> Add([[1,2],[3,4]],[[4,5],[6,7]]).
[[5,7],[9,11]]


问:
Yii-2 how to update a record on basis of id
I want to update my table/model. The scenario is, I have a 'status' column, I want to SET this column to a value then update the model based on the id. I want to do something like update statement.

Update 'table' SET status = 'status value' where id = 'myid'

My action controller look like

```<code>$model = $this->findModel($id);
$ogp_id = $model->id;
$status = $model->status;
</code>```

I have searched for it but couldn't find a solution

Any help would be highly appreciated

答:
for retrive the $id related  model
You can use findOne($id)  if id is the primary key

```<code>$model =YourModel::findOne($id);
$model->status = 'Active';
$model->save();
</code>```

or find()->Where()->one() in general cases

```<code>$model =YourModel::find()-where(['id'=>$id])->one();
$model->status = 'Active';
$model->save();
</code>```

if your validation rules fail you can try using $model->save(false);  if in this case e row is updated  thin mean that some of your data don't respect validation rules .. and you should check for this

Body:
I want to update my table/model. The scenario is, I have a 'status' column, I want to SET this column to a value then update the model based on the id. I want to do something like update statement.

Update 'table' SET status = 'status value' where id = 'myid'

My action controller look like

$model = $this->findModel($id);
$ogp_id = $model->id;
$status = $model->status;

I have searched for it but couldn't find a solution

Any help would be highly appreciated

Body:
for retrive the $id related  model
You can use findOne($id)  if id is the primary key

$model =YourModel::findOne($id);
$model->status = 'Active';
$model->save();

or find()->Where()->one() in general cases

$model =YourModel::find()-where(['id'=>$id])->one();
$model->status = 'Active';
$model->save();

if your validation rules fail you can try using $model->save(false);  if in this case e row is updated  thin mean that some of your data don't respect validation rules .. and you should check for this


问:
How to handle a 404 in Koa 2?
I have a 404.jade file that I want to render whenever there is an invalid GET request.

Here is my current code:

app.js

```<code>import Koa from 'koa'
import views from 'koa-views'
import serve from 'koa-static'
import rootRoutes from './routes/index'
import userRoutes from './routes/user'

const app = new Koa()

app.use(views(`${__dirname}/views`, { extension: 'jade' }))
app.use(serve(`${__dirname}/public`))
app.use(rootRoutes.routes())
app.use(userRoutes.routes())

app.listen(3000, () => {
  console.log('Server running at http://localhost:3000')
})

export default app
</code>```

routes/index.js

```<code>import Router from 'koa-router'
const router = new Router()

router.get('/', async ctx => {
  await ctx.render('index')
})

router.get('/about', async ctx => {
  await ctx.render('about')
})

export default router
</code>```

routes/user.js

```<code>import Router from 'koa-router'
const router = new Router({ prefix: '/user' })

router.get('/:name', async ctx => {
  const user = ctx.params.name
  await ctx.render('user', { user })
})

export default router
</code>```

How can I handle any type of invalid GET request and somehow use await ctx.render('404') whenever it happens?

答:
The default value of ctx.response.status is 404

application.js line 125 :

```<code>callback() {
    const fn = compose(this.middleware);

    if (!this.listeners('error').length) this.on('error', this.onerror);

    const handleRequest = (req, res) => {
      res.statusCode = 404;  // defaul
      const ctx = this.createContext(req, res);
      const onerror = err => ctx.onerror(err);
      const handleResponse = () => respond(ctx);
      onFinished(res, onerror);
      return fn(ctx).then(handleResponse).catch(onerror);
    };

    return handleRequest;
}
</code>```

and if you call :

```<code>this.render('index',{});
this.send();
this.body='';
</code>```

the status code will change automatically.

So we can just use this :

```<code>app.use(async (ctx, next) => {
    if(parseInt(ctx.status) === 404){
       ctx.status = 404
       ctx.body = {msg:'emmmmmmm, seems 404'};
    }
})
</code>```

Warning here, if you are using koa-router, make sure the function above is called with app.use( app = new Koa() ), not router.use

Title: How to handle a 404 in Koa 2?

Body:
I have a 404.jade file that I want to render whenever there is an invalid GET request.

Here is my current code:

app.js

import Koa from 'koa'
import views from 'koa-views'
import serve from 'koa-static'
import rootRoutes from './routes/index'
import userRoutes from './routes/user'

const app = new Koa()

app.use(views(`${__dirname}/views`, { extension: 'jade' }))
app.use(serve(`${__dirname}/public`))
app.use(rootRoutes.routes())
app.use(userRoutes.routes())

app.listen(3000, () => {
  console.log('Server running at http://localhost:3000')
})

export default app

routes/index.js

import Router from 'koa-router'
const router = new Router()

router.get('/', async ctx => {
  await ctx.render('index')
})

router.get('/about', async ctx => {
  await ctx.render('about')
})

export default router

routes/user.js

import Router from 'koa-router'
const router = new Router({ prefix: '/user' })

router.get('/:name', async ctx => {
  const user = ctx.params.name
  await ctx.render('user', { user })
})

export default router

How can I handle any type of invalid GET request and somehow use await ctx.render('404') whenever it happens?

Body:
The default value of ctx.response.status is 404

application.js line 125 :

callback() {
    const fn = compose(this.middleware);

    if (!this.listeners('error').length) this.on('error', this.onerror);

    const handleRequest = (req, res) => {
      res.statusCode = 404;  // defaul
      const ctx = this.createContext(req, res);
      const onerror = err => ctx.onerror(err);
      const handleResponse = () => respond(ctx);
      onFinished(res, onerror);
      return fn(ctx).then(handleResponse).catch(onerror);
    };

    return handleRequest;
}

and if you call :

this.render('index',{});
this.send();
this.body='';

the status code will change automatically.

So we can just use this :

app.use(async (ctx, next) => {
    if(parseInt(ctx.status) === 404){
       ctx.status = 404
       ctx.body = {msg:'emmmmmmm, seems 404'};
    }
})

Warning here, if you are using koa-router, make sure the function above is called with app.use( app = new Koa() ), not router.use


问:
Injecting ResourceBundle in Spring Bean
I want to inject a resource bundle into a bean. I need the resourcebundle, I can't get the messages directly. I am using this snippet to load the resource:

```<code> <bean id="reportMessages" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename">
            <value>report.messages</value>
        </property>
</code>```

Then I can inject it into my bean like this:

```<code>@Autowired
@Qualifier("reportMessages")
private ResourceBundleMessageSource reportMessages;
</code>```

But this gives me a ResourceBundleMessageSource, which has a getResourceBundle() method which is protected and thus I can't call it.

I.e. what I want is Spring's built-in functionality to read a Message Bundle depending on locale, and then treat it as a separate bean.

答:
I came across the same situtation as OP did, and M. Deinum 's comment to wrap MessageSource with MessageSourceResourceBundle solved my issue.

```<code>Locale locale = Locale.getDefault();
params.put(JRParameter.REPORT_LOCALE, locale);
    /* wrap the annotated messageSource with MessageSourceResourceBundle */
params.put(JRParameter.REPORT_RESOURCE_BUNDLE, new MessageSourceResourceBundle(messageSource, locale));
</code>```

Title: Injecting ResourceBundle in Spring Bean

Body:
I want to inject a resource bundle into a bean. I need the resourcebundle, I can't get the messages directly. I am using this snippet to load the resource:

 <bean id="reportMessages" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename">
            <value>report.messages</value>
        </property>

Then I can inject it into my bean like this:

@Autowired
@Qualifier("reportMessages")
private ResourceBundleMessageSource reportMessages;

But this gives me a ResourceBundleMessageSource, which has a getResourceBundle() method which is protected and thus I can't call it.

I.e. what I want is Spring's built-in functionality to read a Message Bundle depending on locale, and then treat it as a separate bean.

Body:
I came across the same situtation as OP did, and M. Deinum 's comment to wrap MessageSource with MessageSourceResourceBundle solved my issue.

Locale locale = Locale.getDefault();
params.put(JRParameter.REPORT_LOCALE, locale);
    /* wrap the annotated messageSource with MessageSourceResourceBundle */
params.put(JRParameter.REPORT_RESOURCE_BUNDLE, new MessageSourceResourceBundle(messageSource, locale));


答:
Implode the array turning it into a string.</p>

```<code>$comp  = implode(", ",$comp_labs);
</code>```

Title: Print entire PHP array in 1 html table cell

Body:
Implode the array turning it into a string.

$comp  = implode(", ",$comp_labs);


问:
Get if TFS build agent is busy or not
I would like to solve with TFS 2015 REST API to get if an agent is busy or not.
I tried to get requests from an agent but seems, it's listed only completed ones:

http://tfsserver:8080/tfs/_apis/distributedtask/pools/2/jobrequests?agentId=41

I looked up all possible api call but I couldn't figured out, how can I get if and agent has running build or not.

May somebody can help me out.

Thank you!

答:
Just check the latest Request (top first request) of the response, if there is the item "result" (eg: "result": "succeeded") in the value, then the agent is idle, otherwise it's busy.

In short :

Idle:

"result": "succeeded", or "result": "abandoned", or "result": "succeededWithIssues",

Busy:

No "result" item

You can use below PowerShell script to identify that, if the Result is empty, then the agent is busy:

```<code>$serverurl = "http://tfsserver:8080/tfs"
$poolid = "39"
$agentid = "147"
$baseUrl = "$serverurl/_apis/distributedtask/pools/$poolid/jobrequests?agentId=$agentid"
$response = (Invoke-RestMethod -Uri $baseUrl -Method Get -UseDefaultCredential).value

$requests = @()

foreach($request in $response){

    $customObject = new-object PSObject -property @{
          "RequestId" = $request.requestId
          "Result" = $request.result
          "AgentName" = $request.reservedAgent.name
          "AgentVersion" = $request.reservedAgent.version
          "AgentStatus" = $request.reservedAgent.status
          "BuildDefinitionID" = $request.definition.id
          "BuildDefinitionName" = $request.definition.name
          "BuildID" = $request.owner.id
          "BuildName" = $request.owner.name
        }

    $requests += $customObject
}

$requests | Select-Object -first 1 `
                RequestId,
                Result,
                AgentName,
                AgentVersion,
                AgentStatus,
                BuildDefinitionID,
                BuildDefinitionName,
                BuildID,
                BuildName
</code>```

Actually, the simplest way is checking the agnet status via web portal:

Manage Project (gear icon) --> Agent Pools --> Select the specific Agent pool and Agent --> Check the Requests

Title: Get if TFS build agent is busy or not

Body:
Just check the latest Request (top first request) of the response, if there is the item "result" (eg: "result": "succeeded") in the value, then the agent is idle, otherwise it's busy.

In short :

Idle:

"result": "succeeded", or "result": "abandoned", or "result": "succeededWithIssues",

Busy:

No "result" item

You can use below PowerShell script to identify that, if the Result is empty, then the agent is busy:

$serverurl = "http://tfsserver:8080/tfs"
$poolid = "39"
$agentid = "147"
$baseUrl = "$serverurl/_apis/distributedtask/pools/$poolid/jobrequests?agentId=$agentid"
$response = (Invoke-RestMethod -Uri $baseUrl -Method Get -UseDefaultCredential).value

$requests = @()

foreach($request in $response){

    $customObject = new-object PSObject -property @{
          "RequestId" = $request.requestId
          "Result" = $request.result
          "AgentName" = $request.reservedAgent.name
          "AgentVersion" = $request.reservedAgent.version
          "AgentStatus" = $request.reservedAgent.status
          "BuildDefinitionID" = $request.definition.id
          "BuildDefinitionName" = $request.definition.name
          "BuildID" = $request.owner.id
          "BuildName" = $request.owner.name
        }

    $requests += $customObject
}

$requests | Select-Object -first 1 `
                RequestId,
                Result,
                AgentName,
                AgentVersion,
                AgentStatus,
                BuildDefinitionID,
                BuildDefinitionName,
                BuildID,
                BuildName

Actually, the simplest way is checking the agnet status via web portal:

Manage Project (gear icon) --> Agent Pools --> Select the specific Agent pool and Agent --> Check the Requests


问:
Unbound record field id error
I am trying out Reason-React. I am facing a problem when I try to add a key to one of the components.

I have a TodoApp that takes a list of TodoItem as state. The app works fine when I don't have a key for the TodoItem. When I add it, however I am getting a compilation error. I am adding the files here for reference:

TodoItem.re:

```<code>type item = {
  id: int,
  title: string,
  completed: bool
};

let lastId = ref(0);

let newItem = () => {
  lastId := lastId^ + 1;
  {id: lastId^, title: "Click a button", completed: false}
};

let toString = ReasonReact.stringToElement;

let component = ReasonReact.statelessComponent("TodoItem");

let make = (~item, children) => {
  ...component,
  render: (self) =>
    <div className="item">
      <input _type="checkbox" checked=(Js.Boolean.to_js_boolean(item.completed)) />
      (toString(item.title))
    </div>
};
</code>```

TodoApp.re:

```<code>let toString = ReasonReact.stringToElement;

type state = {items: list(TodoItem.item)};

type action =
  | AddItem;

let component = ReasonReact.reducerComponent("TodoApp");

let currentItems = [TodoItem.{id: 0, title: "ToDo", completed: false}];

let make = (children) => {
  ...component,
  initialState: () => {items: currentItems},
  reducer: (action, {items}) =>
    switch action {
    | AddItem => ReasonReact.Update({items: [TodoItem.newItem(), ...items]})
    },
  render: ({state: {items}, reduce}) => {
    let numOfItems = List.length(items);
    <div className="app">
      <div className="title">
        (toString("What to do"))
        <button onClick=(reduce((_evt) => AddItem))> (toString("Add Something")) </button>
      </div>
      <div className="items">
        (
          ReasonReact.arrayToElement(
            Array.of_list(
              (List.map((item) => <TodoItem key=(string_of_int(item.id)) item />, items))
              /*List.map((item) => <TodoItem item />, items) This works but the above line of code with the key does not*/
            )
          )
        )
      </div>
      <div className="footer"> (toString(string_of_int(numOfItems) ++ " items")) </div>
    </div>
  }
};
</code>```

I've added a comment near the line where the error occurs.

The error reads as Unbound record field id, but I am not able to figure out how it is not bound. What am I missing here?

答:
Type inference is unfortunately a bit limited when it comes to inferring the type of a record from another module based on the usage of record fields, so you need to give it some help. Two options that should work are:

Annotating the type of ìtem:

List.map((item: TodoItem.item) => <TodoItem key=(string_of_int(item.id)) item />)
```
<p>or locally opening the module where the record field is used:</p>
<pre class="lang-jsx prettyprint-override"><code>List.map((item) => <TodoItem key=(string_of_int(item.TodoItem.id)) item />)
</code>```

Title: Unbound record field id error

Body:
I am trying out Reason-React. I am facing a problem when I try to add a key to one of the components.

I have a TodoApp that takes a list of TodoItem as state. The app works fine when I don't have a key for the TodoItem. When I add it, however I am getting a compilation error. I am adding the files here for reference:

TodoItem.re:

type item = {
  id: int,
  title: string,
  completed: bool
};

let lastId = ref(0);

let newItem = () => {
  lastId := lastId^ + 1;
  {id: lastId^, title: "Click a button", completed: false}
};

let toString = ReasonReact.stringToElement;

let component = ReasonReact.statelessComponent("TodoItem");

let make = (~item, children) => {
  ...component,
  render: (self) =>

      <input _type="checkbox" checked=(Js.Boolean.to_js_boolean(item.completed)) />
      (toString(item.title))

};

TodoApp.re:

let toString = ReasonReact.stringToElement;

type state = {items: list(TodoItem.item)};

type action =
  | AddItem;

let component = ReasonReact.reducerComponent("TodoApp");

let currentItems = [TodoItem.{id: 0, title: "ToDo", completed: false}];

let make = (children) => {
  ...component,
  initialState: () => {items: currentItems},
  reducer: (action, {items}) =>
    switch action {
    | AddItem => ReasonReact.Update({items: [TodoItem.newItem(), ...items]})
    },
  render: ({state: {items}, reduce}) => {
    let numOfItems = List.length(items);

        (toString("What to do"))
        <button onClick=(reduce((_evt) => AddItem))> (toString("Add Something")) </button>

        (
          ReasonReact.arrayToElement(
            Array.of_list(
              (List.map((item) => <TodoItem key=(string_of_int(item.id)) item />, items))
              /*List.map((item) => <TodoItem item />, items) This works but the above line of code with the key does not*/
            )
          )
        )

 (toString(string_of_int(numOfItems) ++ " items"))

  }
};

I've added a comment near the line where the error occurs.

The error reads as Unbound record field id, but I am not able to figure out how it is not bound. What am I missing here?

Body:
Type inference is unfortunately a bit limited when it comes to inferring the type of a record from another module based on the usage of record fields, so you need to give it some help. Two options that should work are:

Annotating the type of ìtem:

List.map((item: TodoItem.item) => <TodoItem key=(string_of_int(item.id)) item />)

or locally opening the module where the record field is used:

List.map((item) => <TodoItem key=(string_of_int(item.TodoItem.id)) item />)