问:
UICollectionView state restoration: customizing scroll position
I am trying to find the best way to handle state restoration for a UICollectionView whose elements may move around. My goal is to make sure that the last viewed item in the collection view is still visible when restarting the app, even if the items have moved around. For example, item A is in cell at index 3 when the app was killed, and when the app restarts if the model says that item A should be displayed at index 4, I want the collection view to initialize offset to the cell at index 4.

I thought that implementing the UIDataSourceModelAssociation protocol in my UICollectionViewDataSource class would take care of this for me, as the documentation states:

[UITableView and UICollectionView] classes use the methods of this protocol to ensure that the same data objects (and not just the same row indexes) are scrolled into view and selected.

However, what I have observed is that implementing this protocol does properly affect the indexPath of the selected cells during restoration (which isn't important to my app), but it does not affect the scroll position. The scroll position (contentOffset of the collection view) is always restored to exactly where it was when the app was killed, and not affected by the UICollectionViewDataSource.

I do have a workaround that looks like this. It's basically the same pattern as the model assocation protocol, but I have to do it manually:

```<code>override func encodeRestorableStateWithCoder(coder: NSCoder) {
    let identifier = determineIdOfCurrentlyVisibleCell()
    coder.encodeObject(identifier, forKey: "visibleCellIdentifier")
}

override func decodeRestorableStateWithCoder(coder: NSCoder) {
    if let identifier = coder.decodeObjectForKey("visibleCellIdentifier") as? String {
        if let indexPath = model.indexPathForIdentifier(identifier) {
            collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .CenteredVertically, animated: false)
        }
    }
}
</code>```

Did I misunderstand the usage of UIDataSourceModelAssociation? Is there a bug? Is there a more elegant or correct way to get this to work?

答:
Update based on @stepane's suggestion using CGPoint.  </p>

```<code>  override func encodeRestorableState(with coder: NSCoder) {
        super.encodeRestorableState(with: coder)
        coder.encode(collectionView.contentOffset, forKey: "CollectionViewContentOffset")
    }

    override func decodeRestorableState(with coder: NSCoder) {
        super.decodeRestorableState(with: coder)
        let offsetValue = coder.decodeObject(forKey: "CollectionViewOffset") as! CGPoint
        collectionView?.setContentOffset(offsetValue, animated: false)
    }
</code>```

Body:
I am trying to find the best way to handle state restoration for a UICollectionView whose elements may move around. My goal is to make sure that the last viewed item in the collection view is still visible when restarting the app, even if the items have moved around. For example, item A is in cell at index 3 when the app was killed, and when the app restarts if the model says that item A should be displayed at index 4, I want the collection view to initialize offset to the cell at index 4.

I thought that implementing the UIDataSourceModelAssociation protocol in my UICollectionViewDataSource class would take care of this for me, as the documentation states:

[UITableView and UICollectionView] classes use the methods of this protocol to ensure that the same data objects (and not just the same row indexes) are scrolled into view and selected.

However, what I have observed is that implementing this protocol does properly affect the indexPath of the selected cells during restoration (which isn't important to my app), but it does not affect the scroll position. The scroll position (contentOffset of the collection view) is always restored to exactly where it was when the app was killed, and not affected by the UICollectionViewDataSource.

I do have a workaround that looks like this. It's basically the same pattern as the model assocation protocol, but I have to do it manually:

override func encodeRestorableStateWithCoder(coder: NSCoder) {
    let identifier = determineIdOfCurrentlyVisibleCell()
    coder.encodeObject(identifier, forKey: "visibleCellIdentifier")
}

override func decodeRestorableStateWithCoder(coder: NSCoder) {
    if let identifier = coder.decodeObjectForKey("visibleCellIdentifier") as? String {
        if let indexPath = model.indexPathForIdentifier(identifier) {
            collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .CenteredVertically, animated: false)
        }
    }
}

Did I misunderstand the usage of UIDataSourceModelAssociation? Is there a bug? Is there a more elegant or correct way to get this to work?

Body:
Update based on @stepane's suggestion using CGPoint.

  override func encodeRestorableState(with coder: NSCoder) {
        super.encodeRestorableState(with: coder)
        coder.encode(collectionView.contentOffset, forKey: "CollectionViewContentOffset")
    }

    override func decodeRestorableState(with coder: NSCoder) {
        super.decodeRestorableState(with: coder)
        let offsetValue = coder.decodeObject(forKey: "CollectionViewOffset") as! CGPoint
        collectionView?.setContentOffset(offsetValue, animated: false)
    }


来源: stackexchange

问:
Why static_assert error: "expression must have a constant value" even if I do pass constants?
This piece of code is compiled with no issues:

```<code>const int tmp1 = 1, tmp2 = 1;
const bool cmp = (tmp1 == tmp2);
static_assert(cmp, "OK");
</code>```

This one is fine, too:

```<code>const bool cmp = (HUGE_VALF == HUGE_VALF);
static_assert(cmp, "OK");
</code>```

This one is not:

```<code>const auto tmp = HUGE_VALF;
const bool cmp = (tmp == tmp);
static_assert(cmp, "OK");   // <-- error
</code>```

Error: expression must have a constant value.

  The value of variable "cmp" cannot be used as a constant

Same behaviour with static const.

What is wrong? HUGE_VALF is a preprocessor macro, i.e. constant, and cmp is with no doubt a compile time constant...

Environment:

Microsoft Windows 10

Microsoft Visual C++ 2013 & 2019

答:
With this test program I got to the problem:

```<code>#include <cmath>

constexpr auto val1 = 1.23f;
constexpr auto val2 = HUGE_VALF;

static_assert(val1 == val1, "OK");
static_assert(val2 == val2, "OK");

int main()
{
}
</code>```

Result:

Visual C++ 2019 32 bits: OK

Visual C++ 2019 64 bits: OK

Visual C++ 2013 32 bits: OK

Visual C++ 2013 64 bits: Failed

Output:

```<code>1>  TestConstexpr.cpp(5): error C2144: syntax error : 'auto' should be preceded by ';'
1>  TestConstexpr.cpp(5): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>  TestConstexpr.cpp(6): error C2144: syntax error : 'auto' should be preceded by ';'
1>  TestConstexpr.cpp(6): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>  TestConstexpr.cpp(6): error C2086: 'int constexpr' : redefinition
1>          TestConstexpr.cpp(5) : see declaration of 'constexpr'
1>  TestConstexpr.cpp(8): error C2057: expected constant expression
1>  TestConstexpr.cpp(9): error C2057: expected constant expression
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This piece of code is compiled with no issues:

const int tmp1 = 1, tmp2 = 1;
const bool cmp = (tmp1 == tmp2);
static_assert(cmp, "OK");

This one is fine, too:

const bool cmp = (HUGE_VALF == HUGE_VALF);
static_assert(cmp, "OK");

This one is not:

const auto tmp = HUGE_VALF;
const bool cmp = (tmp == tmp);
static_assert(cmp, "OK");   // <-- error

Error: expression must have a constant value.

  The value of variable "cmp" cannot be used as a constant

Same behaviour with static const.

What is wrong? HUGE_VALF is a preprocessor macro, i.e. constant, and cmp is with no doubt a compile time constant...

Environment:

Microsoft Windows 10

Microsoft Visual C++ 2013 & 2019

Body:
With this test program I got to the problem:

#include <cmath>

constexpr auto val1 = 1.23f;
constexpr auto val2 = HUGE_VALF;

static_assert(val1 == val1, "OK");
static_assert(val2 == val2, "OK");

int main()
{
}

Result:

Visual C++ 2019 32 bits: OK

Visual C++ 2019 64 bits: OK

Visual C++ 2013 32 bits: OK

Visual C++ 2013 64 bits: Failed

Output:

1>  TestConstexpr.cpp(5): error C2144: syntax error : 'auto' should be preceded by ';'
1>  TestConstexpr.cpp(5): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>  TestConstexpr.cpp(6): error C2144: syntax error : 'auto' should be preceded by ';'
1>  TestConstexpr.cpp(6): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>  TestConstexpr.cpp(6): error C2086: 'int constexpr' : redefinition
1>          TestConstexpr.cpp(5) : see declaration of 'constexpr'
1>  TestConstexpr.cpp(8): error C2057: expected constant expression
1>  TestConstexpr.cpp(9): error C2057: expected constant expression


问:
RecyclerView: No adapter attached skipping layout (TabbedActivity + Firestore)
I am trying to retrieve data from firestore and display it as a RecyclerView within a TabbedActivity. The data is displaying in each tab/fragment, but sometimes if i swipe forwards through the tabs and then back the data disappears and the error "No adapter attached skipping layout" appears.

Fragment.java

```<code>public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.sligo_fragment, container, false);

    recyclerView = (RecyclerView) v.findViewById(R.id.sligo_recycler);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    return v;
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    db.collection("sligo")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        placeNames.add(document.getData().get("Name").toString());
                    }
                    MyAdapter adapter = new MyAdapter(placeNames);
                    recyclerView.setAdapter(adapter);
                }
            });
}
</code>```

MyAdapter.java

```<code>public static class MyViewHolder extends RecyclerView.ViewHolder{
    public TextView textView;
    public MyViewHolder(View itemView) {
        super(itemView);
        textView = itemView.findViewById(R.id.info_text);
    }
}

public MyAdapter(ArrayList<String> myDataset) {

    mDataset = myDataset;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    // create a new view
    View v =  LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item, parent, false);
    MyViewHolder vh = new MyViewHolder(v);
    return vh;

}
</code>```

答:
According Fragment LifeCycle onCreate is called before onCreateView. Beside this you are setting adapter inside asynchronous operation which takes time to complete. Try to move the code to onCreateView like below:

```<code>public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.sligo_fragment, container, false);

    recyclerView = (RecyclerView) v.findViewById(R.id.sligo_recycler);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    MyAdapter adapter = new MyAdapter(placeNames);
    recyclerView.setAdapter(adapter);

    db.collection("sligo")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        placeNames.add(document.getData().get("Name").toString());
                    }

                    adapter.notifyDataSetChanged();
                }
            });

    return v;
}
</code>```

Body:
I am trying to retrieve data from firestore and display it as a RecyclerView within a TabbedActivity. The data is displaying in each tab/fragment, but sometimes if i swipe forwards through the tabs and then back the data disappears and the error "No adapter attached skipping layout" appears.

Fragment.java

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.sligo_fragment, container, false);

    recyclerView = (RecyclerView) v.findViewById(R.id.sligo_recycler);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    return v;
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    db.collection("sligo")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        placeNames.add(document.getData().get("Name").toString());
                    }
                    MyAdapter adapter = new MyAdapter(placeNames);
                    recyclerView.setAdapter(adapter);
                }
            });
}

MyAdapter.java

public static class MyViewHolder extends RecyclerView.ViewHolder{
    public TextView textView;
    public MyViewHolder(View itemView) {
        super(itemView);
        textView = itemView.findViewById(R.id.info_text);
    }
}

public MyAdapter(ArrayList<String> myDataset) {

    mDataset = myDataset;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    // create a new view
    View v =  LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item, parent, false);
    MyViewHolder vh = new MyViewHolder(v);
    return vh;

}

Body:
According Fragment LifeCycle onCreate is called before onCreateView. Beside this you are setting adapter inside asynchronous operation which takes time to complete. Try to move the code to onCreateView like below:

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.sligo_fragment, container, false);

    recyclerView = (RecyclerView) v.findViewById(R.id.sligo_recycler);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    MyAdapter adapter = new MyAdapter(placeNames);
    recyclerView.setAdapter(adapter);

    db.collection("sligo")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        placeNames.add(document.getData().get("Name").toString());
                    }

                    adapter.notifyDataSetChanged();
                }
            });

    return v;
}


问:
How do I add a legend for a secondary y-axis?
I am using the ggplot2 and wesanderson packages for plotting a graph which contains a line and bars. A sample of my data is presented as follows:

```<code>        Year  PIB     Variation
        1971  13032.36  0.0629264087
        1972  13686.28  0.0501766372
        1973  15595.61  0.1395068638
        1974  17343.64  0.1120847469
        1975  19246.61  0.1097214887
        1976  20670.32  0.0739719878
        1977  21002.05  0.0160486146
        1978  22200.60  0.0570682386
        1979  23029.58  0.0373404322
        1980  23883.67  0.0370866512
        1981  25224.23  0.0561287273
        1982  25379.32  0.0061484533
        1983  25293.82 -0.0033688846
        1984  25957.86  0.0262530531
        1985  26979.30  0.0393499310
        1986  27914.07  0.0346476743
        1987  27841.75 -0.0025908081
        1988  29481.76  0.0589047025
        1989  29778.28  0.0100577442
        1990  30874.09  0.0367989689
        1991  32199.01  0.0429136535

</code>```

I want to describe the evolution and the GDP growth rate using a secondary axis. so, my code is the following:

```<code>#For constructing the secondary axis
gdp_off_pib <- as.numeric(solve(
a=matrix(c(1,max(annual$Variation),1,min(annual$Variation)),
           nr=2,nc=2,byrow=TRUE),
b=matrix(c(max(annual$PIB),min(annual$PIB)),nc=1)))

graph_pib <- ggplot(annual, aes(x = Year)) +
geom_col(aes(y = PIB, fill = "PIB")) +
scale_fill_manual(values = wes_palette("Zissou1", 3, type = "discrete"))+
geom_line(aes(y=(Variation*gdp_off_pib[2])+gdp_off_pib[1]), color="#F21A00"
           , size =0.8) +
scale_color_manual(values = wes_palette("Zissou1", 2, type = "continuous") )+
xlab("Year") +
ylab("Real GDP") + labs(color="Variables") +scale_y_continuous(
   sec.axis = sec_axis(~(.- gdp_off_pib[1])/gdp_off_pib[2],
                      name = "GDP growth rate"))

graph_pib
</code>```

The code above plots the following graph:

My problem is the right side, as you can see the graph does not explain that the red line is the growth rate and also the word fill appears.

Thanks for your help.

答:
To add the line to the legend, you need to give it a colour via an aesthetic, rather than hard-coding it:

```<code>geom_line(aes(y = (Variation * gdp_off_pib[2L]) + gdp_off_pib[1L], color = 'GDP'))
</code>```

… and possibly apply a suitable palette, which your code tries — the problem is that you explicitly need to select the second colour in it, otherwise your line’s the same blue as the colums:

```<code>wes_palette("Zissou1", 2L, type = "continuous")[2L]
</code>```

To remove the legend titles, set them to NULL or "":

```<code>labs(color = NULL, fill = NULL)
</code>```

The final code is:

```<code>palette = wes_palette("Zissou1", 2L, type = "continuous")

ggplot(annual, aes(x = Year)) +
    geom_col(aes(y = PIB, fill = "PIB")) +
    scale_fill_manual(values = palette[1L]) +
    geom_line(
        aes(y = (Variation * gdp_off_pib[2L]) + gdp_off_pib[1L], color = 'Growth'),
        size = 0.8
    ) +
    scale_color_manual(values = palette[2L]) +
    scale_y_continuous(
        sec.axis = sec_axis(
            ~ (. - gdp_off_pib[1L]) / gdp_off_pib[2L],
            name = "GDP growth rate"
        )
    ) +
    labs(y = 'Real GDP', color = NULL, fill = NULL)
</code>```

But for a publication I would remove the legend entirely, and instead add the information about the axes into the axis title — either by giving them the appropriate colour, or by simply adding the words “bars” and “line” to the axis titles. For instance, the Economist, which (too) liberally uses secondary axes, colours both the axis title and the axis labels in the colour of the corresponding plot element:

Code:

```<code>ggplot(annual, aes(x = Year)) +
    geom_col(aes(y = PIB, fill = "PIB")) +
    scale_fill_manual(values = palette[1L], guide = FALSE) +
    geom_line(
        aes(y = (Variation * gdp_off_pib[2L]) + gdp_off_pib[1L], color = 'Growth'),
        size = 0.8
    ) +
    scale_color_manual(values = palette[2L], guide = FALSE) +
    scale_y_continuous(
        sec.axis = sec_axis(
            ~ (. - gdp_off_pib[1L]) / gdp_off_pib[2L],
            name = "GDP growth rate"
        )
    ) +
    ylab('Real GDP') +
    theme(
        axis.title.y = element_text(color = palette[1L]),
        axis.text.y = element_text(color = palette[1L]),
        axis.title.y.right = element_text(color = palette[2L]),
        axis.text.y.right = element_text(color = palette[2L])
    )
</code>```

Body:
I am using the ggplot2 and wesanderson packages for plotting a graph which contains a line and bars. A sample of my data is presented as follows:

        Year  PIB     Variation
        1971  13032.36  0.0629264087
        1972  13686.28  0.0501766372
        1973  15595.61  0.1395068638
        1974  17343.64  0.1120847469
        1975  19246.61  0.1097214887
        1976  20670.32  0.0739719878
        1977  21002.05  0.0160486146
        1978  22200.60  0.0570682386
        1979  23029.58  0.0373404322
        1980  23883.67  0.0370866512
        1981  25224.23  0.0561287273
        1982  25379.32  0.0061484533
        1983  25293.82 -0.0033688846
        1984  25957.86  0.0262530531
        1985  26979.30  0.0393499310
        1986  27914.07  0.0346476743
        1987  27841.75 -0.0025908081
        1988  29481.76  0.0589047025
        1989  29778.28  0.0100577442
        1990  30874.09  0.0367989689
        1991  32199.01  0.0429136535

I want to describe the evolution and the GDP growth rate using a secondary axis. so, my code is the following:

#For constructing the secondary axis
gdp_off_pib <- as.numeric(solve(
a=matrix(c(1,max(annual$Variation),1,min(annual$Variation)),
           nr=2,nc=2,byrow=TRUE),
b=matrix(c(max(annual$PIB),min(annual$PIB)),nc=1)))

graph_pib <- ggplot(annual, aes(x = Year)) +
geom_col(aes(y = PIB, fill = "PIB")) +
scale_fill_manual(values = wes_palette("Zissou1", 3, type = "discrete"))+
geom_line(aes(y=(Variation*gdp_off_pib[2])+gdp_off_pib[1]), color="#F21A00"
           , size =0.8) +
scale_color_manual(values = wes_palette("Zissou1", 2, type = "continuous") )+
xlab("Year") +
ylab("Real GDP") + labs(color="Variables") +scale_y_continuous(
   sec.axis = sec_axis(~(.- gdp_off_pib[1])/gdp_off_pib[2],
                      name = "GDP growth rate"))

graph_pib

The code above plots the following graph:

My problem is the right side, as you can see the graph does not explain that the red line is the growth rate and also the word fill appears.

Thanks for your help.

Body:
To add the line to the legend, you need to give it a colour via an aesthetic, rather than hard-coding it:

geom_line(aes(y = (Variation * gdp_off_pib[2L]) + gdp_off_pib[1L], color = 'GDP'))

… and possibly apply a suitable palette, which your code tries — the problem is that you explicitly need to select the second colour in it, otherwise your line’s the same blue as the colums:

wes_palette("Zissou1", 2L, type = "continuous")[2L]

To remove the legend titles, set them to NULL or "":

labs(color = NULL, fill = NULL)

The final code is:

palette = wes_palette("Zissou1", 2L, type = "continuous")

ggplot(annual, aes(x = Year)) +
    geom_col(aes(y = PIB, fill = "PIB")) +
    scale_fill_manual(values = palette[1L]) +
    geom_line(
        aes(y = (Variation * gdp_off_pib[2L]) + gdp_off_pib[1L], color = 'Growth'),
        size = 0.8
    ) +
    scale_color_manual(values = palette[2L]) +
    scale_y_continuous(
        sec.axis = sec_axis(
            ~ (. - gdp_off_pib[1L]) / gdp_off_pib[2L],
            name = "GDP growth rate"
        )
    ) +
    labs(y = 'Real GDP', color = NULL, fill = NULL)

But for a publication I would remove the legend entirely, and instead add the information about the axes into the axis title — either by giving them the appropriate colour, or by simply adding the words “bars” and “line” to the axis titles. For instance, the Economist, which (too) liberally uses secondary axes, colours both the axis title and the axis labels in the colour of the corresponding plot element:

Code:

ggplot(annual, aes(x = Year)) +
    geom_col(aes(y = PIB, fill = "PIB")) +
    scale_fill_manual(values = palette[1L], guide = FALSE) +
    geom_line(
        aes(y = (Variation * gdp_off_pib[2L]) + gdp_off_pib[1L], color = 'Growth'),
        size = 0.8
    ) +
    scale_color_manual(values = palette[2L], guide = FALSE) +
    scale_y_continuous(
        sec.axis = sec_axis(
            ~ (. - gdp_off_pib[1L]) / gdp_off_pib[2L],
            name = "GDP growth rate"
        )
    ) +
    ylab('Real GDP') +
    theme(
        axis.title.y = element_text(color = palette[1L]),
        axis.text.y = element_text(color = palette[1L]),
        axis.title.y.right = element_text(color = palette[2L]),
        axis.text.y.right = element_text(color = palette[2L])
    )


问:
Generating GeoJson with javascript
I'm getting a lat/lon array with ajax

```<code>$.ajax({
    type: "POST",
    url: '../m/m_share.php',
    data: 'zone=' + zone,
    dataType: 'json',
    success: function(tab) {
        var i = 0;
        var size = tab.length;
        for (i = 0; i < size; i++) {
            var lat = tab[i]['lat'];
            var lon = tab[i]['lon'];
        }
    }
</code>```

The "tab" param is a jscon_encode(array) sent by php of my lat/lon request from db.
What I would like to do is creating a geojson such as this one but with my lat/lon datas.

```<code>var geojson =
   {"name":"NewFeatureType",
    "type":"FeatureCollection",
    "features":[{"type":"Feature",
                 "geometry":{"type":"LineString",
                             "coordinates":[[169.13693,-44.696476,296],[169.134602,-44.69764,295],[169.129983,-44.701164,299]]},
    "properties":null}]};
</code>```

I tried to save the lat/lon in a var

```<code>  $.ajax({
            type: "POST",
            url: '../m/m_share.php',
            data: 'zone=' + zone,
            dataType: 'json',
            success: function(tab) {
                var i = 0;
                var size = tab.length;
                for (i = 0; i < size; i++) {
                     var lat = tab[i]['lat'];
                     var lon = tab[i]['lon'];
                   if(i===size){
                      coord = coord+'['+lat+','+lon+']';
                       alert(coord);
                    }
                    else{
                      coord = coord+'['+lat+','+lon+']'+',';

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

And then replace the lat/lon in the geoJson with my coord var but it seems that leaflet does not like it "Invalid LatLng object: (NaN, Nan)".

答:
The approach mentioned by Pedro Estrada is correct. But there is a slight correction required.

GeoJson standard requires geographical points with (longitude,latitude) convention.

var gj = {
    "name":"MyFeatureType",
    "type":"FeatureCollection",
    "features":[]
};
```

<p>Push a new feature object</p>

<pre class="lang-js prettyprint-override"><code>gj.features.push({ "type": "Feature","geometry": {"type": "LineString","coordinates": []},"properties": null });
</code>```

Add a coordinate to newly pushed object:

lon=20;
lat=10;
gj.features[0].geometry.coordinates.push([lon,lat]);
```

ContentLicense: CC BY-SA 3.0

Title: Generating GeoJson with javascript

Body:
I'm getting a lat/lon array with ajax

$.ajax({
    type: "POST",
    url: '../m/m_share.php',
    data: 'zone=' + zone,
    dataType: 'json',
    success: function(tab) {
        var i = 0;
        var size = tab.length;
        for (i = 0; i < size; i++) {
            var lat = tab[i]['lat'];
            var lon = tab[i]['lon'];
        }
    }

The "tab" param is a jscon_encode(array) sent by php of my lat/lon request from db.
What I would like to do is creating a geojson such as this one but with my lat/lon datas.

var geojson =
   {"name":"NewFeatureType",
    "type":"FeatureCollection",
    "features":[{"type":"Feature",
                 "geometry":{"type":"LineString",
                             "coordinates":[[169.13693,-44.696476,296],[169.134602,-44.69764,295],[169.129983,-44.701164,299]]},
    "properties":null}]};

I tried to save the lat/lon in a var

  $.ajax({
            type: "POST",
            url: '../m/m_share.php',
            data: 'zone=' + zone,
            dataType: 'json',
            success: function(tab) {
                var i = 0;
                var size = tab.length;
                for (i = 0; i < size; i++) {
                     var lat = tab[i]['lat'];
                     var lon = tab[i]['lon'];
                   if(i===size){
                      coord = coord+'['+lat+','+lon+']';
                       alert(coord);
                    }
                    else{
                      coord = coord+'['+lat+','+lon+']'+',';

                    }
                }
                }
            });

And then replace the lat/lon in the geoJson with my coord var but it seems that leaflet does not like it "Invalid LatLng object: (NaN, Nan)".

Body:
The approach mentioned by Pedro Estrada is correct. But there is a slight correction required.

GeoJson standard requires geographical points with (longitude,latitude) convention.

var gj = {
    "name":"MyFeatureType",
    "type":"FeatureCollection",
    "features":[]
};

Push a new feature object

gj.features.push({ "type": "Feature","geometry": {"type": "LineString","coordinates": []},"properties": null });

Add a coordinate to newly pushed object:

lon=20;
lat=10;
gj.features[0].geometry.coordinates.push([lon,lat]);


问:
Get number of ISO weeks in given year in C#
I'm trying to get the number of ISO weeks in given year/leap year. I saw that .Net Core 3.0 have ISOWeek.GetWeeksInYear class, but we're running .Net Core 2.2.1... and it's not possible to update at the moment...

I've tried this:

```<code>var cultInfo = CultureInfo.CurrentCulture;
var lastDayOfYear = new DateTime(2019, 12, 31);
var numberOfWeeks = cultInfo.Calendar.GetWeekOfYear(
                                    lastDayOfYear,
                                    cultInfo.DateTimeFormat.CalendarWeekRule,
                                    DayOfWeek.Monday);
</code>```

With 2019 it returns 53, it's not correct by the result I wanted (52). And if I change the date to 2020 it is 53, which is correct, but yeah, not by ISO which is what I want.

Thanks in advance.

答:
A year contains 53 ISO weeks if and only if it contains 53 Thursdays; so in order to return 53 a year must either

Start from Thursday

Be a leap year and starts either from Thursday or Wednesday

Code:

```<code>public static int GetWeeksInYear(int year) {
  if (year < DateTime.MinValue.Year || year > DateTime.MaxValue.Year)
    throw new ArgumentOutOfRangeException(nameof(year));

  var dw = new DateTime(year, 1, 1).DayOfWeek;

  return (dw == DayOfWeek.Thursday) ||
         (dw == DayOfWeek.Wednesday) && DateTime.IsLeapYear(year)
    ? 53
    : 52;
}
</code>```

Demo:

```<code>  var report = string.Join(Environment.NewLine, Enumerable
    .Range(1990, 2020 - 1990 + 1)
    .Select(year => $"{year} : {GetWeeksInYear(year)}"));

  Console.Write(report);
</code>```

Outcome:

```<code>1990 : 52
1991 : 52
1992 : 53
1993 : 52
1994 : 52
1995 : 52
1996 : 52
1997 : 52
1998 : 53
1999 : 52
2000 : 52
2001 : 52
2002 : 52
2003 : 52
2004 : 53
2005 : 52
2006 : 52
2007 : 52
2008 : 52
2009 : 53
2010 : 52
2011 : 52
2012 : 52
2013 : 52
2014 : 52
2015 : 53
2016 : 52
2017 : 52
2018 : 52
2019 : 52
2020 : 53
</code>```

Body:
I'm trying to get the number of ISO weeks in given year/leap year. I saw that .Net Core 3.0 have ISOWeek.GetWeeksInYear class, but we're running .Net Core 2.2.1... and it's not possible to update at the moment...

I've tried this:

var cultInfo = CultureInfo.CurrentCulture;
var lastDayOfYear = new DateTime(2019, 12, 31);
var numberOfWeeks = cultInfo.Calendar.GetWeekOfYear(
                                    lastDayOfYear,
                                    cultInfo.DateTimeFormat.CalendarWeekRule,
                                    DayOfWeek.Monday);

With 2019 it returns 53, it's not correct by the result I wanted (52). And if I change the date to 2020 it is 53, which is correct, but yeah, not by ISO which is what I want.

Thanks in advance.

Body:
A year contains 53 ISO weeks if and only if it contains 53 Thursdays; so in order to return 53 a year must either

Start from Thursday

Be a leap year and starts either from Thursday or Wednesday

Code:

public static int GetWeeksInYear(int year) {
  if (year < DateTime.MinValue.Year || year > DateTime.MaxValue.Year)
    throw new ArgumentOutOfRangeException(nameof(year));

  var dw = new DateTime(year, 1, 1).DayOfWeek;

  return (dw == DayOfWeek.Thursday) ||
         (dw == DayOfWeek.Wednesday) && DateTime.IsLeapYear(year)
    ? 53
    : 52;
}

Demo:

  var report = string.Join(Environment.NewLine, Enumerable
    .Range(1990, 2020 - 1990 + 1)
    .Select(year => $"{year} : {GetWeeksInYear(year)}"));

  Console.Write(report);

Outcome:

1990 : 52
1991 : 52
1992 : 53
1993 : 52
1994 : 52
1995 : 52
1996 : 52
1997 : 52
1998 : 53
1999 : 52
2000 : 52
2001 : 52
2002 : 52
2003 : 52
2004 : 53
2005 : 52
2006 : 52
2007 : 52
2008 : 52
2009 : 53
2010 : 52
2011 : 52
2012 : 52
2013 : 52
2014 : 52
2015 : 53
2016 : 52
2017 : 52
2018 : 52
2019 : 52
2020 : 53


问:
Force application to run only in one instance in PCF
I have one scheduler app to be run only in one instance in PCF cloud environment. Is there any way to do it in Cloud environment ?

Few of the things I tried by making instances:1 in manifest.yml , to force it to run only in one instance and not autoscale .

But looking for any better approach in PCF .

答:
This will support cf v7.
Or you might be able to schedule it with the cf task option.

And as shown above, you can create various tasks through cf7.

https://v3-apidocs.cloudfoundry.org/version/3.81.0/index.html#the-process-object

This can be separated into several processes as shown below.

```<code>applications:
name: cf-env
  buildpacks:
  ruby_buildpack
  processes:
  type: web
    instances: 1
    memory: 256M
  routes:
  route: all-new-route.cfapps.io
</code>```

Body:
This will support cf v7.
Or you might be able to schedule it with the cf task option.

And as shown above, you can create various tasks through cf7.

https://v3-apidocs.cloudfoundry.org/version/3.81.0/index.html#the-process-object

This can be separated into several processes as shown below.

applications:
name: cf-env
  buildpacks:
  ruby_buildpack
  processes:
  type: web
    instances: 1
    memory: 256M
  routes:
  route: all-new-route.cfapps.io


问:
How to change label on input focus when input comes after label?
```<code><div id="my-field">
    <label class="my-label">Label</label>
    <input class="my-input" value="input" />
</div>
</code>```

```<code>#my-field{
}
.my-label {
}
.my-input{
}
</code>```

Is there any way I can customize the CSS of .my-label when input is in focus without touching the HTML? There are multiple ways to select successor sibling elements. But any way to select predecessor(s)?

Note: There is a restriction in the project that HTML cannot be modified here. Everything has to be done in CSS only. No jQuery/JS either.

答:
If there is only one input field in #my-field, you can try :focus-within:

```<code>#my-field:focus-within .my-label{ ... }
</code>```

Body:
    Label
    <input class="my-input" value="input" />

#my-field{
}
.my-label {
}
.my-input{
}

Is there any way I can customize the CSS of .my-label when input is in focus without touching the HTML? There are multiple ways to select successor sibling elements. But any way to select predecessor(s)?

Note: There is a restriction in the project that HTML cannot be modified here. Everything has to be done in CSS only. No jQuery/JS either.

Body:
If there is only one input field in #my-field, you can try :focus-within:

#my-field:focus-within .my-label{ ... }


问:
Is it possible to send a friend request through Android Facebook API?
I am trying to create an Android app and I want to send a Facebook friend request through Android Facebook API. I have spent some time but couldn't find an interface for this. Is this possible to do this through Facebook API if I know the person's Facebook id?</p>

答: It is recommended that you use the Friends dialog: see http://developers.facebook.com/docs/reference/dialogs/friends/ for details.</p>


问:
What fields uniquely identify a row in Oracle BRM's Account_Nameinfo_T Table?
I'm trying to determine a set of fields that uniquely identify a row in Account_Nameinfo_T. Oracle BRM uses no constraints so I cannot determine it that way. Does anyone know these fields? Better yet, does anyone know how I can determine this for other tables in BRM?

(Apparently there is no Oracle-Brm tag in SO).

答:
Just to add a bit more information to the (good) answer provided by @Pavel Chernikov.

In general, BRM stores the definition of a class in 3 Data Dictionary tables (namely DD_OBJECTS_T, DD_FIELDS_T and DD_OBJECTS_FIELDS_T) but you should use the Class Browser of the Developer Center to have a convenient, graphical view.

Furthermore, the BRM documentation (under BRM Documentation - Reference - Database reference - Storable class definitions) has extensive information about class definition.

For example we can take a look at the /account class:

in the SQL Mapping section, we can see that it maps to the table ACCOUNT_T

it has an array PIN_FLD_NAMEINFO that is mapped to the table ACCOUNT_NAMEINFO_T

therefore, a record in ACCOUNT_NAMEINFO_T will be uniquely identified by the couple

OBJ_ID0, which can be thought of as a foreign key to the POID_ID0(*) of the corresponding record in ACCOUNT_T

REC_ID, which is called the element ID and is used to differentiate among possible multiple records in ACCOUNT_NAMEINFO_T for the same record in ACCOUNT_T

the documentation also gives us a hint of the functional meaning of the element ID

array PIN_FLD_NAMEINFO: Contact information for account. This array contains any number of contacts with the description for the type of contact. The element-id is not significant except for the billing contact (1) and mailing contact (2). The element-id's 3-100 are reserved.

in case of further nesting, additional elements IDs are used, like REC_ID2: for instance, the array PIN_FLD_PHONES, within the very same array PIN_FLD_NAMEINFO, maps to the table ACCOUNT_PHONES_T where a record would be uniquely identified by the triplet (OBJ_ID0, REC_ID, REC_ID2)

(*) Please note that in general, a POID is composed of 4 elements:

an ID (POID_ID0)

a type (POID_TYPE)

a database number (POID_DB)

a revision number (POID_REV)

However, for a single-DB installation and for the sake of this discussion, we can assume that the ID is sufficient to uniquely identify a record in a given table.


问:
Bootstrapping Binomial Distribution
I am working on a simple problem, I want to write a function that will randomly draw n samples of size q from a binomial distribution (say 60% 1, and 40% 0), and then save the share of 1s from each sample in an array (so that I can analyze that array later). For instance, I would like to simulate, if I drew 1,000 samples each of size 30 from a distribution with 60% 1s and 40% 0s, and I would like as an output an array of length 1,000, where each row represents the share of 1's from that sample.</p>

答:
To get the number of 1s, it will be

```<code>import numpy as np
sim = np.random.binomial(n=30,p=0.6,size=1000)
</code>```

To actually get the draws:

```<code>sim = np.random.binomial(n=1,p=0.6,size=(1000,30))
sim.shape
import matplotlib.pyplot as plt
plt.hist(np.mean(sim,axis=1))
</code>```

Title: Bootstrapping Binomial Distribution

Body:
To get the number of 1s, it will be

import numpy as np
sim = np.random.binomial(n=30,p=0.6,size=1000)

To actually get the draws:

sim = np.random.binomial(n=1,p=0.6,size=(1000,30))
sim.shape
import matplotlib.pyplot as plt
plt.hist(np.mean(sim,axis=1))


问:
Can AWS Lambda be used as the backend for getstream.io?
I didn't find any posts related to this topic. It seems natural to use Lambda as a getstream backend, but I'm not sure if it heavily depends on persistent connections or other architectural choices that would rule it out. Is it a sensible approach? Has anyone made it work? Any advice?</p>

答:
While you can build an entire website only in Lambda, you have to consider the followings:

Lambda behind API Gateway has a timeout limit of 30 seconds and a Payload size limit (both received and sended) of 6MB. While for most of the cases this is fine, if you have some really big operations or you need to send some really big datas (like a high resolution image), you can't do it with this approach, but you need to think about something else (for instance you can send an SNS to another Lambda function with higher timeout that can do all this asynchronously and then send the result to the client when it's done, supposing the client is capable of receiving events)

Lambda has cold starts, which in terms slow down your APIs when a client calls them for the first time in a while. The cold start time depends on the language you are doing your Lambdas, so you might consider this too. If you are using C# or Java for your Lambdas, than this is probably not the best choice. From this point of view, Node.JS and Python seems to be the best choices, with Golang rising. You can find more about it here. And by the way, you can now specify a Provisioned Throughput for your Lambda, which aims to fix the cold start issue, but I haven't used it yet so I can't tell if there is any difference (but I'm sure there is)

If done correctly you'll end up managing hundreds of Lambda functions, while with a standard Docker Container under ECS you'll manage few APIs with multiple endpoints. This point should not be underestimated, as on one side it will make changes easier in the future, since lambda will be small and you'll easily find the bug and fix it, but on the other side you have to move across these functions, which if you don't know exactly which lambda is responsible of what can be a long process

Lambda can't handle sessions as far as I know. Because after some time the Lambda container gets dropped, you can't store any session inside the Lambda itself. You'll always need a structure to store the session so it can be shared across multiple Lambda invocations, such as some records in a DynamoDB table or something else, but this mean that you have to write the code for this, while in a classic API (like a .NET Core one) all of this is handled by the language itself and you only need to store or retrieve items from the session (most of the times)

So... yeah! A backed written entirely in Lambda is possible. The company I work in does it and I must say is a lot better, both in terms of speed and development time. But those benefits comes later, since you need to face all of the reasons I listed above before, and is not as easy as it could seem


问:
Linq list of lists to one list
I have a Linq query that updates the first item in each conditioned group like this

```<code>var results = StudentsList.GroupBy(x => x.GroupID)
    .Where(g => !g.Any(p => p.Student == "Adam") && g.Any(x => x.University == "OPQ"))
    .Select(g =>
            {
                var firstItem = g.First(x => x.University == "OPQ");
                firstItem.IsQualified = true;

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

While preserving original functionality, I want to additionally-

If exists, update IsQualified= true for ALL students in same group with University!= "OPQ" and Course= "HR" (Group 2). If don't exist, just ignore (Group 5)

Output

Donald, Silver, Emity (all Group 2) and White (Group 5).

What I tried

Just below the "firstItem.IsQualified = true;" line, I added-

```<code>var otherItems=g.Any(x=>x.University != "OPQ" && x.Course =="HR");
otherItems.IsQualified= true;
</code>```

My Code

```<code>    List<StudentInfo> StudentsList = new List<StudentInfo>();

    // Group 1
    StudentsList.Add( new StudentInfo { Student="Gungun", University="cdf", Course="GD", GroupID = 1, IsQualified=false});
    StudentsList.Add( new StudentInfo { Student="John", University="abc", Course="ACC", GroupID = 1, IsQualified=false});
    StudentsList.Add( new StudentInfo { Student="Jack", University="def", Course="CS", GroupID = 1, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Peter", University="abc", Course="GD", GroupID = 1, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Lemity", University="abc", Course="CS", GroupID = 1, IsQualified=false} );

    // Group 2
    StudentsList.Add( new StudentInfo { Student="Donald", University="def", Course="HR",GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Olivia", University="ggh", Course="RC",GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Silver", University="tcs", Course="HR",GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Carl", University="yyz", Course="AC",GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Emity", University="OPQ", Course="AC",GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Emma", University="OPQ", Course="GD", GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Alan", University="OPQ", Course="GD", GroupID = 2, IsQualified=false} );

    // Group 3
    StudentsList.Add( new StudentInfo { Student="Adam", University="yub", Course="CS", GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Jacob", University="OPQ", Course="AC",GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Matthew", University="OPQ", Course="HR", GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Saint", University="abc", Course="MNGT",  GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Joshua", University="qer", Course="MNGT",  GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Aubrey", University="fef", Course="MNGT",  GroupID = 3, IsQualified=false} );

    // Group 4
    StudentsList.Add( new StudentInfo { Student="Caleb", University="DEF", Course="HR", GroupID = 4, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Anna", University="ABC", Course="HR", GroupID = 4, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Chill", University="GHI", Course="GD", GroupID = 4, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Alexis", University="JKL", Course="CS", GroupID = 4, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Zoe", University="MNO", Course="MNGT", GroupID = 4, IsQualified=false} );

    // Group 5
    StudentsList.Add( new StudentInfo { Student="Dylan", University="PQR", Course="ACC", GroupID = 5, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="White", University="OPQ", Course="CE", GroupID = 5, IsQualified=false} );

public class StudentInfo
{
  public string Student { get; set; }
  public string University { get; set; }
  public string Course { get; set; }
  public int GroupID { get; set; }
  public bool IsQualified {get; set;}
}
</code>```

答:
Could you try this:</p>

```<code>        var otherItems = StudentsList.Where(x => x.University != "OPQ" && x.Course == "HR");
        foreach (var otherItem in otherItems)
        {
            otherItem.IsQualified = true;
        }
</code>```

Title: Linq list of lists to one list

Body:
I have a Linq query that updates the first item in each conditioned group like this

var results = StudentsList.GroupBy(x => x.GroupID)
    .Where(g => !g.Any(p => p.Student == "Adam") && g.Any(x => x.University == "OPQ"))
    .Select(g =>
            {
                var firstItem = g.First(x => x.University == "OPQ");
                firstItem.IsQualified = true;

                return firstItem;
            }).ToList();

While preserving original functionality, I want to additionally-

If exists, update IsQualified= true for ALL students in same group with University!= "OPQ" and Course= "HR" (Group 2). If don't exist, just ignore (Group 5)

Output

Donald, Silver, Emity (all Group 2) and White (Group 5).

What I tried

Just below the "firstItem.IsQualified = true;" line, I added-

var otherItems=g.Any(x=>x.University != "OPQ" && x.Course =="HR");
otherItems.IsQualified= true;

My Code

    List<StudentInfo> StudentsList = new List<StudentInfo>();

    // Group 1
    StudentsList.Add( new StudentInfo { Student="Gungun", University="cdf", Course="GD", GroupID = 1, IsQualified=false});
    StudentsList.Add( new StudentInfo { Student="John", University="abc", Course="ACC", GroupID = 1, IsQualified=false});
    StudentsList.Add( new StudentInfo { Student="Jack", University="def", Course="CS", GroupID = 1, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Peter", University="abc", Course="GD", GroupID = 1, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Lemity", University="abc", Course="CS", GroupID = 1, IsQualified=false} );

    // Group 2
    StudentsList.Add( new StudentInfo { Student="Donald", University="def", Course="HR",GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Olivia", University="ggh", Course="RC",GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Silver", University="tcs", Course="HR",GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Carl", University="yyz", Course="AC",GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Emity", University="OPQ", Course="AC",GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Emma", University="OPQ", Course="GD", GroupID = 2, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Alan", University="OPQ", Course="GD", GroupID = 2, IsQualified=false} );

    // Group 3
    StudentsList.Add( new StudentInfo { Student="Adam", University="yub", Course="CS", GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Jacob", University="OPQ", Course="AC",GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Matthew", University="OPQ", Course="HR", GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Saint", University="abc", Course="MNGT",  GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Joshua", University="qer", Course="MNGT",  GroupID = 3, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Aubrey", University="fef", Course="MNGT",  GroupID = 3, IsQualified=false} );

    // Group 4
    StudentsList.Add( new StudentInfo { Student="Caleb", University="DEF", Course="HR", GroupID = 4, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Anna", University="ABC", Course="HR", GroupID = 4, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Chill", University="GHI", Course="GD", GroupID = 4, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Alexis", University="JKL", Course="CS", GroupID = 4, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="Zoe", University="MNO", Course="MNGT", GroupID = 4, IsQualified=false} );

    // Group 5
    StudentsList.Add( new StudentInfo { Student="Dylan", University="PQR", Course="ACC", GroupID = 5, IsQualified=false} );
    StudentsList.Add( new StudentInfo { Student="White", University="OPQ", Course="CE", GroupID = 5, IsQualified=false} );

public class StudentInfo
{
  public string Student { get; set; }
  public string University { get; set; }
  public string Course { get; set; }
  public int GroupID { get; set; }
  public bool IsQualified {get; set;}
}

Body:
Could you try this:

        var otherItems = StudentsList.Where(x => x.University != "OPQ" && x.Course == "HR");
        foreach (var otherItem in otherItems)
        {
            otherItem.IsQualified = true;
        }


问:
Using Mac Automator to run Python Find & Replace. Multiline (\n\r) not working
I'm using Mac Automator to run a 'Find & Replace' python script. (Below is a simplified version.) It's working really well, with the exception of line breaks...

I've tried multiple variants of \r \n \r\n but it's not removing the line breaks.

```<code>    replacements = {
    'class="spec-container"':'class="row"',
    '</span>\n\n':'</span>',
    '</div>\n\n\n':'</div>\n'
    }

    with open('/../TEMP/INPUT.txt') as infile,
    open('/../TEMP/OUTPUT.txt', 'w') as outfile:
    for line in infile:
        for find, replace in replacements.iteritems():
            line = line.replace(find, replace)
        outfile.write(line)
</code>```

Really only just find my feet with Python, so apologies in advance. But any help gratefully received.

答: You can use the strip() method for removing whitespace around a string in Python. "hello\n".strip() will return "hello". You can also use lstrip() or rstrip() if you only want it to strip the string on one side.

Body:
I'm using Mac Automator to run a 'Find & Replace' python script. (Below is a simplified version.) It's working really well, with the exception of line breaks...

I've tried multiple variants of \r \n \r\n but it's not removing the line breaks.

    replacements = {
    'class="spec-container"':'class="row"',
    '\n\n':'',
    '
\n\n\n':'
\n'
    }

    with open('/../TEMP/INPUT.txt') as infile,
    open('/../TEMP/OUTPUT.txt', 'w') as outfile:
    for line in infile:
        for find, replace in replacements.iteritems():
            line = line.replace(find, replace)
        outfile.write(line)

Really only just find my feet with Python, so apologies in advance. But any help gratefully received.


问:
sort json array by value jq bash
I want to sort below array based on groupId such that keys with smaller groupId come first in array.

```<code>[
  {
    "groupId": 11,
    "lowerThreshold": 33,
    "target": {
      "alarm_id": 22
    },
    "thresholdPeriod": 3,
    "upperThreshold": 44
  },
  {
    "groupId": 31,
    "lowerThreshold": 33,
    "target": {
      "alarm_id": 122
    },
    "thresholdPeriod": 3,
    "upperThreshold": 44
  },
  {
    "groupId": "0",
    "target": {
      "alarm_id": "69"
    },
    "upperThreshold": "20",
    "lowerThreshold": "10",
    "thresholdPeriod": "5"
  }
]
</code>```

Expectation is

```<code>[
  {
    "groupId": "0",
    "target": {
      "alarm_id": "69"
    },
    "upperThreshold": "20",
    "lowerThreshold": "10",
    "thresholdPeriod": "5"
  },
  {
    "groupId": 11,
    "lowerThreshold": 33,
    "target": {
      "alarm_id": 22
    },
    "thresholdPeriod": 3,
    "upperThreshold": 44
  },
  {
    "groupId": 31,
    "lowerThreshold": 33,
    "target": {
      "alarm_id": 122
    },
    "thresholdPeriod": 3,
    "upperThreshold": 44
  }
]
</code>```

答:
You can use sort_by like following:

```<code>jq 'sort_by(.groupId)'
</code>```

Title: sort json array by value jq bash

Body:
I want to sort below array based on groupId such that keys with smaller groupId come first in array.

[
  {
    "groupId": 11,
    "lowerThreshold": 33,
    "target": {
      "alarm_id": 22
    },
    "thresholdPeriod": 3,
    "upperThreshold": 44
  },
  {
    "groupId": 31,
    "lowerThreshold": 33,
    "target": {
      "alarm_id": 122
    },
    "thresholdPeriod": 3,
    "upperThreshold": 44
  },
  {
    "groupId": "0",
    "target": {
      "alarm_id": "69"
    },
    "upperThreshold": "20",
    "lowerThreshold": "10",
    "thresholdPeriod": "5"
  }
]

Expectation is

[
  {
    "groupId": "0",
    "target": {
      "alarm_id": "69"
    },
    "upperThreshold": "20",
    "lowerThreshold": "10",
    "thresholdPeriod": "5"
  },
  {
    "groupId": 11,
    "lowerThreshold": 33,
    "target": {
      "alarm_id": 22
    },
    "thresholdPeriod": 3,
    "upperThreshold": 44
  },
  {
    "groupId": 31,
    "lowerThreshold": 33,
    "target": {
      "alarm_id": 122
    },
    "thresholdPeriod": 3,
    "upperThreshold": 44
  }
]

Body:
You can use sort_by like following:

jq 'sort_by(.groupId)'


问:
How to redirect specific name only domain with https to another domain
i have NGINX  server which is targeting by two domain https://a.com and https://b.com . i want that if url come from only https://a.com then should redirect to https://b.com . in short my server should serve as https://b.com to all coming https links

答:
Try this</p>

```<code>server {    # traffic from http://a.com will redirect to https://b.com
    listen      80;
    server_name *.a.com;

    return 301 https://b.com$request_uri;
}

server {    # traffic from https://a.com will redirect to https://b.com
    listen      443 ssl;
    server_name *.a.com;

    ssl_certificate     /path/to/your/certs/a.com.crt;
    ssl_certificate_key /path/to/your/certs/a.com.key;

    ...

    return 301 https://b.com$request_uri;
}

server {    # will serve your app
    listen  443 ssl default_server;

    server_name *.b.com;

    ssl_certificate     /path/to/your/certs/b.com.crt;
    ssl_certificate_key /path/to/your/certs/b.com.key;

    ...

    location / {
        root        /path/to/your/app;
        index       index.html;
        try_files   $uri $uri/ /index.html;
    }
}
</code>```

Body:
Try this

server {    # traffic from http://a.com will redirect to https://b.com
    listen      80;
    server_name *.a.com;

    return 301 https://b.com$request_uri;
}

server {    # traffic from https://a.com will redirect to https://b.com
    listen      443 ssl;
    server_name *.a.com;

    ssl_certificate     /path/to/your/certs/a.com.crt;
    ssl_certificate_key /path/to/your/certs/a.com.key;

    ...

    return 301 https://b.com$request_uri;
}

server {    # will serve your app
    listen  443 ssl default_server;

    server_name *.b.com;

    ssl_certificate     /path/to/your/certs/b.com.crt;
    ssl_certificate_key /path/to/your/certs/b.com.key;

    ...

    location / {
        root        /path/to/your/app;
        index       index.html;
        try_files   $uri $uri/ /index.html;
    }
}


问:
How to multithread Flask server and python script?
I have one python script that is used for reading data form COM port and storing the same data in MongoDB. On the other side there is Flask server that is used for displaying data from same database on web page. They are working separately without any problem. Is there any way to merge this two programs, like multithreading in python and how to manage this transformation? If needed, I can provide source code for both programs.</p>

答:
From my understanding, you want to run two python scripts at the same time.

Simply create a bash script with following text, (replace script1 & script 2 with file names)

```<code>python script1.py &
python script2.py &
</code>```

Body:
From my understanding, you want to run two python scripts at the same time.

Simply create a bash script with following text, (replace script1 & script 2 with file names)

python script1.py &
python script2.py &


问:
Wasm with emscripten and SDL - How to clear only part of the renderer
I've created a Wasm animation using emscripten and SDL. I am now trying to create a button where the user can start and stop/pause the animation. The problem I have is that the whole canvas is cleared on every iteration. As I see it, there are 3 options here:

Redraw the button on every frame.

Only clear the part of the canvas that the animation uses on each iteration.

Use a HTML form for the input buttons.

(1) seems inefficient. (3) would require me to start interoperating between JS and Wasm. So far I've been able to build the whole thing without writing a single line of JS, and would prefer to keep it that way. So probably (2) is best.

I know that with JS it is possible to specify the dimensions of a clearRect call. I can't find this functionality in the SDL API however.

Below is the mainLoop function (which gets called about 60 times a second) (This is written in C if it's unclear. Not C++). My question is, how can I adapt the "SDL_RenderClear" so that it only clears one half of the canvas? (The half with the animation. I.e. don't clear the half where I want to make buttons.

main.c

```<code>#include <stdio.h>
#include <SDL2/SDL.h>
#include <emscripten.h>
#include <stdlib.h>
#include <stdbool.h>

<....>

/**
 * The loop handler, will be called repeatedly
 */
void mainLoop(void *arg) {
    struct Context *ctx = arg;
    printf("iteration: %d\n", ctx->iteration);

    SDL_SetRenderDrawColor(ctx->renderer, 255, 0, 100, 255);
    SDL_RenderClear(ctx->renderer);

    bool running = true;

    if (running) {
        for (int j=1; j<8; j++) {
            for (int i=1; i<130; i++) {
                // drawRect is another app function that calls the SDL to draw a rectangles.
                drawRectangle(ctx, i, j);
            }
        }
    }
    SDL_RenderPresent(ctx->renderer);
    ctx->iteration++;
}

<....>
</code>```

答:
You can just paint over parts you don't want with SDL_RenderFillRect. However, unless you do a lot of trickery, it isn't very helpful.

Formal reason - https://wiki.libsdl.org/SDL_RenderPresent says "The backbuffer should be considered invalidated after each present; do not assume that previous contents will exist between frames."

There are many cases when your buffer will be (partially) invalidated, e.g. moving window out of screen bounds. I don't know about webasm, you probably need to check webgl documentation if anything about buffer contents is being promised.

Even if you can rely on contents to be kept, but e.g. you have double buffered setup. You've rendered to first buffer, performed buffer swap - now you have second buffer, which contents isn't initialised yet. After second swap it could be more-or-less similar, but any change will be lagging behind 1 frame.

Some 3d software (e.g. blender) did what you described but even there it wasn't 100% stable and usually there was an option to disable that behabiour. Performing full redraw is much cheaper than you think, and if it becomes too costly - you can always render part of your screen into render texture and use it as single static image, updating it when necessary.

Body:
I've created a Wasm animation using emscripten and SDL. I am now trying to create a button where the user can start and stop/pause the animation. The problem I have is that the whole canvas is cleared on every iteration. As I see it, there are 3 options here:

Redraw the button on every frame.

Only clear the part of the canvas that the animation uses on each iteration.

Use a HTML form for the input buttons.

(1) seems inefficient. (3) would require me to start interoperating between JS and Wasm. So far I've been able to build the whole thing without writing a single line of JS, and would prefer to keep it that way. So probably (2) is best.

I know that with JS it is possible to specify the dimensions of a clearRect call. I can't find this functionality in the SDL API however.

Below is the mainLoop function (which gets called about 60 times a second) (This is written in C if it's unclear. Not C++). My question is, how can I adapt the "SDL_RenderClear" so that it only clears one half of the canvas? (The half with the animation. I.e. don't clear the half where I want to make buttons.

main.c

#include <stdio.h>
#include <SDL2/SDL.h>
#include <emscripten.h>
#include <stdlib.h>
#include <stdbool.h>

<....>

/**
 * The loop handler, will be called repeatedly
 */
void mainLoop(void *arg) {
    struct Context *ctx = arg;
    printf("iteration: %d\n", ctx->iteration);

    SDL_SetRenderDrawColor(ctx->renderer, 255, 0, 100, 255);
    SDL_RenderClear(ctx->renderer);

    bool running = true;

    if (running) {
        for (int j=1; j<8; j++) {
            for (int i=1; i<130; i++) {
                // drawRect is another app function that calls the SDL to draw a rectangles.
                drawRectangle(ctx, i, j);
            }
        }
    }
    SDL_RenderPresent(ctx->renderer);
    ctx->iteration++;
}

<....>


问:
FluentValidation "Error cs0103 the name 'x' does not exist in the current context" .asp.net core 2.1
Issue

I am receiving the following error when using FluentValidation.AspNetCore (ver 8.6.1). this occurs when my edit view is saved. Very basic setup at the moment but i want to expand on the ActionValidator when it works...thanks

Error cs0103 the name 'x' does not exist in the current context

Code

Startup.cs -

```<code>    services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
        .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<ActionValidator>());
</code>```

Validation class -

```<code>public class ActionValidator : AbstractValidator<EditActionVM>
{
    public ActionValidator()
    {
        RuleFor(x => x.ActionCompletionDate).NotEmpty();
    }
}
</code>```

What i have tried

Following the FluentValidation guide at  - https://docs.fluentvalidation.net/en/latest/aspnet.html#getting-started

Changing startup to use the following code -

```<code>    services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
        .AddFluentValidation();

    services.AddTransient<IValidator<EditActionVM>, ActionValidator>();
</code>```

Edit

EditActionVM.cs -

```<code>public class EditActionVM
{
    public int Id { get; set; }

    [Display(Name = "Action Reference")]
    public string ActionRef { get; set; }

    [Display(Name = "Status")]
    public Enums.Enums.Status Status { get; set; }

    [Display(Name = "Created Date")]
    public DateTime? CreatedDate { get; set; }

    [Display(Name = "Action Completion Date")]
    public DateTime? ActionCompletionDate { get; set; }

}
</code>```

答: Reinstalling FluentValidation resolved my issue...potentially something within my environment that was causing the issue </p>

Body:
Issue

I am receiving the following error when using FluentValidation.AspNetCore (ver 8.6.1). this occurs when my edit view is saved. Very basic setup at the moment but i want to expand on the ActionValidator when it works...thanks

Error cs0103 the name 'x' does not exist in the current context

Code

Startup.cs -

    services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
        .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<ActionValidator>());

Validation class -

public class ActionValidator : AbstractValidator<EditActionVM>
{
    public ActionValidator()
    {
        RuleFor(x => x.ActionCompletionDate).NotEmpty();
    }
}

What i have tried

Following the FluentValidation guide at  - https://docs.fluentvalidation.net/en/latest/aspnet.html#getting-started

Changing startup to use the following code -

    services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
        .AddFluentValidation();

    services.AddTransient<IValidator<EditActionVM>, ActionValidator>();

Edit

EditActionVM.cs -

public class EditActionVM
{
    public int Id { get; set; }

    [Display(Name = "Action Reference")]
    public string ActionRef { get; set; }

    [Display(Name = "Status")]
    public Enums.Enums.Status Status { get; set; }

    [Display(Name = "Created Date")]
    public DateTime? CreatedDate { get; set; }

    [Display(Name = "Action Completion Date")]
    public DateTime? ActionCompletionDate { get; set; }

}


问:
How to get elements from XPath in Java
I want to get data from an XPath query:

```<code>Element location = (Element) doc.query("//location[location_name='"+ locationName +"']/*").get(0).getDocument().getRootElement();
System.out.println(location.toXML());

Element loc = location.getFirstChildElement("location");
System.out.println(loc.getFirstChildElement("location_name").getValue());
</code>```

However, no matter what I choose, I always get 1 node (because of .get(0)). I don't know how to select the node which was selected by query.

I found that I should cast the node to Element, (XOM getting attribute from Node?) but the link only shows how to select the first node.

答: It's not clear (at least for me) what actually has to be done. From your query you should get list of nodes matching the given criteria. You will get NodeList and then you can iterate over this NodeList and get content of each node with getNodeValue for example.</p>

Title: How to get elements from XPath in Java

Body:
I want to get data from an XPath query:

Element location = (Element) doc.query("//location[location_name='"+ locationName +"']/*").get(0).getDocument().getRootElement();
System.out.println(location.toXML());

Element loc = location.getFirstChildElement("location");
System.out.println(loc.getFirstChildElement("location_name").getValue());

However, no matter what I choose, I always get 1 node (because of .get(0)). I don't know how to select the node which was selected by query.

I found that I should cast the node to Element, (XOM getting attribute from Node?) but the link only shows how to select the first node.


问:
Get inner JSON content as string without deserializing
I've got a file with JSON content like this:

```<code>{
  "Data": {
    "A": {
      "A1": "S",
      "A2": 0.0
    }
  },
  "NoData": "text"
}
</code>```

What I want to achieve is to get the inner json of "Data" as a string. I do not want it to be deserialized as an object. I already tried to deserialize it with Json.NET JsonConvert.DeserializeObject<TestClass> where Test class is defined as

```<code>class Testclass
{
  public string Data {get; set;}
  public string NoData {get; set;}
}
</code>```

But this results in Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: {. Path 'Data', line 2, position 11.

The data in "Data" is cryptographically signed by a remote server and the signature needs to be checked. But I do not necessarily have the same classes the data was serialized with at the clients side. That's why I want to do as few conversions as possible. So deserializing and serializing again may change the original string in "data". All spaces and linebreaks have to stay intact.

答:
```<code> {
    "A": {
      "A1": "S",
      "A2": 0.0
    }
  }
</code>```

is a JSON Object Use JToken datatype

```<code>class JsonConverterObjectToString : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return (objectType == typeof(JTokenType));
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JToken token = JToken.Load(reader);
            if (token.Type == JTokenType.Object)
            {
                return token.ToString();
            }
            return null;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            //serializer.Serialize(writer, value);

            //serialize as actual JSON and not string data
            var token = JToken.Parse(value.ToString());
            writer.WriteToken(token.CreateReader());

        }
    }
</code>```

Otherwise use JsonConverter like this

```<code>  JsonConvert.DeserializeObject<Testclass>(json,
                new JsonConverterObjectToString());
</code>```

Body:
I've got a file with JSON content like this:

{
  "Data": {
    "A": {
      "A1": "S",
      "A2": 0.0
    }
  },
  "NoData": "text"
}

What I want to achieve is to get the inner json of "Data" as a string. I do not want it to be deserialized as an object. I already tried to deserialize it with Json.NET JsonConvert.DeserializeObject<TestClass> where Test class is defined as

class Testclass
{
  public string Data {get; set;}
  public string NoData {get; set;}
}

But this results in Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: {. Path 'Data', line 2, position 11.

The data in "Data" is cryptographically signed by a remote server and the signature needs to be checked. But I do not necessarily have the same classes the data was serialized with at the clients side. That's why I want to do as few conversions as possible. So deserializing and serializing again may change the original string in "data". All spaces and linebreaks have to stay intact.

Body:
 {
    "A": {
      "A1": "S",
      "A2": 0.0
    }
  }

is a JSON Object Use JToken datatype

class JsonConverterObjectToString : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return (objectType == typeof(JTokenType));
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JToken token = JToken.Load(reader);
            if (token.Type == JTokenType.Object)
            {
                return token.ToString();
            }
            return null;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            //serializer.Serialize(writer, value);

            //serialize as actual JSON and not string data
            var token = JToken.Parse(value.ToString());
            writer.WriteToken(token.CreateReader());

        }
    }

Otherwise use JsonConverter like this

  JsonConvert.DeserializeObject<Testclass>(json,
                new JsonConverterObjectToString());


问:
Type Any don't have member count, two dimensional array
hi I want to make a view like this picture below, so what I try to do is to make a two dimensional array with UITableViewCell and a string. Since it types Any the compiler complain "Type Any don't have a member of count and subscript". is it my approach right? to make this view like the picture below, or should I create one by one?

This is my code

```<code>var tableItems = [
        [ProgressCell.self],
        ["Information", "Address", "Password"],
        ["Help", "Term and Condition", "Privacy"],
        [SignOutCell]
    ] as Any

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return tableItems[section].count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)

    let name                = tableItems[indexPath.section][indexPath.row] as! Int

    cell.textLabel?.text    = name
    cell.textLabel?.font    = UIFont(name: "NunitoSans-Regular", size: 16)
    cell.accessoryType      = .disclosureIndicator

    return cell
}
</code>```

答:
The following code worked for me. Moreover, self was also needed for SignOutCell. Please see the attached link as well.

```<code>var tableItems = [
    [ProgressCell.self],
    ["Information", "Address", "Password"],
    ["Help", "Term and Condition", "Privacy"],
    [SignOutCell.self] as [Any]
  ]
</code>```

https://i.stack.imgur.com/QexjG.png

Body:
hi I want to make a view like this picture below, so what I try to do is to make a two dimensional array with UITableViewCell and a string. Since it types Any the compiler complain "Type Any don't have a member of count and subscript". is it my approach right? to make this view like the picture below, or should I create one by one?

This is my code

var tableItems = [
        [ProgressCell.self],
        ["Information", "Address", "Password"],
        ["Help", "Term and Condition", "Privacy"],
        [SignOutCell]
    ] as Any

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return tableItems[section].count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)

    let name                = tableItems[indexPath.section][indexPath.row] as! Int

    cell.textLabel?.text    = name
    cell.textLabel?.font    = UIFont(name: "NunitoSans-Regular", size: 16)
    cell.accessoryType      = .disclosureIndicator

    return cell
}

Body:
The following code worked for me. Moreover, self was also needed for SignOutCell. Please see the attached link as well.

var tableItems = [
    [ProgressCell.self],
    ["Information", "Address", "Password"],
    ["Help", "Term and Condition", "Privacy"],
    [SignOutCell.self] as [Any]
  ]

https://i.stack.imgur.com/QexjG.png


答:
Here is one way you can do it without changing your HTML structure.

The :focus-within CSS pseudo-class represents an element that has received focus or contains an element that has received focus. In other words, it represents an element that is itself matched by the :focus pseudo-class or has a descendant that is matched by :focus

Note that example uses :focus-within on the entire form and on interior input-wrapping
.

Learn more about :focus-within selector.

#my-field:focus-within .my-label {
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="my-field">
    <label class="my-label">Label</label>
    <input class="my-input" value="input" />
</div></code>```

Please let me know if this helps.

Title: How to change label on input focus when input comes after label?

Body:
    Label
    <input class="my-input" value="input" />

#my-field{
}
.my-label {
}
.my-input{
}

Is there any way I can customize the CSS of .my-label when input is in focus without touching the HTML? There are multiple ways to select successor sibling elements. But any way to select predecessor(s)?

Note: There is a restriction in the project that HTML cannot be modified here. Everything has to be done in CSS only. No jQuery/JS either.

Body:
Here is one way you can do it without changing your HTML structure.

The :focus-within CSS pseudo-class represents an element that has received focus or contains an element that has received focus. In other words, it represents an element that is itself matched by the :focus pseudo-class or has a descendant that is matched by :focus

Note that example uses :focus-within on the entire form and on interior input-wrapping <div>.

Learn more about :focus-within selector.

#my-field:focus-within .my-label {
  background: red;
}

<div id="my-field">
    <label class="my-label">Label</label>
    <input class="my-input" value="input" />
</div>

Please let me know if this helps.


问:
Extracting a specific substring from a column in sql
i wanted to extract month from a column named implemented_date which specifies the date/time as 2018-02-14 15:00:23. I just want 02 from this data and want to view months of all the rows similarly. How can i do it in mysql

答:
Use the MONTH() function like this</p>

```<code>SELECT MONTH(implemented_date), ..... FROM ....
</code>```

Body:
Use the MONTH() function like this

SELECT MONTH(implemented_date), ..... FROM ....


答:
You can make use of Common Table Expressions (CTE)

Assuming your data in "data" table:

```<code>with total_fee as (
    select distinct id_test, fee from data
),
total_price as (
    select distinct id_test, sum(quantity) quantity, sum(price) price
    from data
    group by id_test
)

select sum(b.price*quantity) quantity, sum(a.fee) fee
from total_fee a
left join total_price b
on a.id_test = b.id_test
</code>```

Title: SQL Query SUM with conditions

Body:
I'm having some difficulties finding the good query I need, looking for help.
After multiple JOIN and a lot of WHERE, I have this columns and values :

+---------+----------+--------+-------+
| id_test | quantity | price  |  fee  |
+---------+----------+--------+-------+
| "1-3"   |        1 | 33.52  | 29.00 |
| "1-5"   |        1 | 33.52  | 29.00 |
| "1-6"   |        1 | 33.52  | 29.00 |
| "1-8"   |        1 | 86.49  | 29.00 |
| "19-1"  |        1 | 176.54 | 29.00 |
| "19-4"  |        1 | 176.54 | 29.00 |
| "19-5"  |        4 | 176.54 | 29.00 |
| "19-6"  |        1 | 199.47 | 29.00 |
| "19-6"  |        1 | 176.54 | 29.00 |
| "20-10" |        2 | 72.67  | 29.00 |
| "20-11" |        2 | 18.95  | 29.00 |
| "20-9"  |        1 | 22.13  | 29.00 |
+---------+----------+--------+-------+

Each id_test object as a quantity, a price and a fee. I would like to SUM everything so to have a global price : (quantity*price)+fee
The thing is, and that's where I'm stuck, the fee has to be added only once by id_test. Yet, I have here two id_test "19-6".

If I SUM everything I have 1827.67 (price*quantity) + 348 (fee).

Since I have two "19-6", I need 1827.67 (price*quantity) + 319 (fee).

How would you do in SQL ?

Thanks

Body:
You can make use of Common Table Expressions (CTE)

Assuming your data in "data" table:

with total_fee as (
    select distinct id_test, fee from data
),
total_price as (
    select distinct id_test, sum(quantity) quantity, sum(price) price
    from data
    group by id_test
)

select sum(b.price*quantity) quantity, sum(a.fee) fee
from total_fee a
left join total_price b
on a.id_test = b.id_test


问:
spring sleuth baggage - support in sleuth version #2
Is spring sleuth baggage going to be deprectaed? If yes what is the alternative?

Is it must to have a configuration for the propogated field names starting version #2?

答:
Where did you get this information that baggage is deprecated? In the documentation we've stated that you need to explicitly state what the baggage keys should be, not that the baggage is depreacted. Also in the Sleuth migration guide (https://github.com/spring-cloud/spring-cloud-sleuth/wiki/Spring-Cloud-Sleuth-2.0-Migration-Guide#baggage-needs-to-be-whitelisted) you could see

In Sleuth we used to create headers that had the baggage prefix. You
  can do it via 2 properties:

```<code>spring.sleuth.baggage-keys - those keys will be prefixed with baggage- and baggage_. That way we are backward compatible with
</code>```

previous versions of Sleuth.
      spring.sleuth.propagation-keys - those keys will be whitelisted as they are. No prefix will be set.

Body:
Where did you get this information that baggage is deprecated? In the documentation we've stated that you need to explicitly state what the baggage keys should be, not that the baggage is depreacted. Also in the Sleuth migration guide (https://github.com/spring-cloud/spring-cloud-sleuth/wiki/Spring-Cloud-Sleuth-2.0-Migration-Guide#baggage-needs-to-be-whitelisted) you could see

In Sleuth we used to create headers that had the baggage prefix. You
  can do it via 2 properties:

spring.sleuth.baggage-keys - those keys will be prefixed with baggage- and baggage_. That way we are backward compatible with

previous versions of Sleuth.
      spring.sleuth.propagation-keys - those keys will be whitelisted as they are. No prefix will be set.


问:
Adding mysql data in to HTML table
I have a mysql database called waterparamsdb and a table called waterparams.
The table has 6 columns:

```<code>Temperature
Acidity
Ammonia
Nitrite
Nitrate
Phosphate
</code>```

I use an HTML form to update the table with numbers.  This part works fine.  In PHPMYADMIN I see new rows with the information:

```<code>temperature ¦ acidity ¦ ammonia ¦ nitrite ¦ nitrate ¦ phosphate
25.50 ¦ 7.60 ¦ 0.25 ¦ 0.00 ¦ 0.00 ¦ 1.00
26.00 ¦ 7.80 ¦ 0.50 ¦ 0.25 ¦ 0.25 ¦ 2.00
</code>```

I followed https://www.w3schools.com/php/php_mysql_select.asp example and was able to first get the information using:

```<code><!DOCTYPE html>
<html>

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Untitled 1</title>
</head>

<body>
<?php
$username = "redacted";
$password = "redacted";
$database = "waterparamsdb";
$mysqli = new mysqli("localhost", $username, $password, $database);
$query = "SELECT * FROM waterparams";

echo '<table border="0" cellspacing="2" cellpadding="2">
      <tr>
          <td> <font face="Arial">Temperature</font> </td>
          <td> <font face="Arial">Acidity</font> </td>
          <td> <font face="Arial">Ammonia</font> </td>
          <td> <font face="Arial">Nitrite</font> </td>
          <td> <font face="Arial">Nitrate</font> </td>
          <td> <font face="Arial">Phosphate</font> </td>
      </tr>';

if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_assoc()) {
        $field1name = $row["col1"];
        $field2name = $row["col2"];
        $field3name = $row["col3"];
        $field4name = $row["col4"];
        $field5name = $row["col5"];
        $field5name = $row["col6"];

        echo '<tr>
                  <td>'.$field1name.'</td>
                  <td>'.$field2name.'</td>
                  <td>'.$field3name.'</td>
                  <td>'.$field4name.'</td>
                  <td>'.$field5name.'</td>
                  <td>'.$field6name.'</td>
              </tr>';
    }
    $result->free();
}
?>
</body>
</html>
</code>```

This works fine and displays the two rows of information in a plain format.  What I would like to do though is only output the last row's values in to a HTML table and display the information on the web page like this:

```<code>Temperature ¦ Value
Acidity ¦ Value
Ammonia ¦ Value
Nitrite ¦ Value
Nitrate ¦ Value
Phosphate ¦ Value
</code>```

I've tried the following adapted from the website above, but it returns 0 results.

```<code><!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
    border: 1px solid black;
}
</style>
</head>
<body>

<?php
$servername = "localhost";
$username = "redacted";
$password = "redacted";
$dbname = "waterparamsdb";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, temperature FROM waterparams";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    echo "<table><tr><th>Parameter</th><th>Value</th></tr>";
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<tr><td>" . $row["id"]. "</td><td>" . $row["temperature"]."</td></tr>";
    }
    echo "</table>";
} else {
    echo "0 results";
}

$conn->close();
?>

</body>
</html>
</code>```

I know this is likely just a simple understanding and formatting issue, I'm still learning!  If anyone is able to help, I would appreciate it greatly.  Thanks.

答:
Change your if loop like this

```<code>if ($result->num_rows > 0) {
    echo "<table><tr><th>Temperature</th><th>Acidity</th><th>Ammonia</th><th>Nitrite</th><th>Nitrate</th><th>Phosphate
    </th></tr>";
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<tr><td>" . $row["Temperature"]. "</td><td>" . $row["Acidity"]."</td><td>" . $row["Ammonia"]."</td><td>" . $row["Nitrite"]."</td><td>" . $row["Nitrate"]."</td><td>" . $row["Phosphate"]."</td></tr>";
    }
    echo "</table>";
} else {
    echo "0 results";
}
</code>```

But make sure the value inside these $row["Temperature"] array should be correct column name

And change your sql query to this

```<code>$sql = "SELECT * FROM waterparams";
</code>```

Title: Adding mysql data in to HTML table

Body:
I have a mysql database called waterparamsdb and a table called waterparams.
The table has 6 columns:

Temperature
Acidity
Ammonia
Nitrite
Nitrate
Phosphate

I use an HTML form to update the table with numbers.  This part works fine.  In PHPMYADMIN I see new rows with the information:

temperature ¦ acidity ¦ ammonia ¦ nitrite ¦ nitrate ¦ phosphate
25.50 ¦ 7.60 ¦ 0.25 ¦ 0.00 ¦ 0.00 ¦ 1.00
26.00 ¦ 7.80 ¦ 0.50 ¦ 0.25 ¦ 0.25 ¦ 2.00

I followed https://www.w3schools.com/php/php_mysql_select.asp example and was able to first get the information using:

<!DOCTYPE html>

<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Untitled 1</title>

<?php
$username = "redacted";
$password = "redacted";
$database = "waterparamsdb";
$mysqli = new mysqli("localhost", $username, $password, $database);
$query = "SELECT * FROM waterparams";

echo '

           Temperature
           Acidity
           Ammonia
           Nitrite
           Nitrate
           Phosphate

';

if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_assoc()) {
        $field1name = $row["col1"];
        $field2name = $row["col2"];
        $field3name = $row["col3"];
        $field4name = $row["col4"];
        $field5name = $row["col5"];
        $field5name = $row["col6"];

        echo '

                  '.$field1name.'
                  '.$field2name.'
                  '.$field3name.'
                  '.$field4name.'
                  '.$field5name.'
                  '.$field6name.'

';
    }
    $result->free();
}
?>

This works fine and displays the two rows of information in a plain format.  What I would like to do though is only output the last row's values in to a HTML table and display the information on the web page like this:

Temperature ¦ Value
Acidity ¦ Value
Ammonia ¦ Value
Nitrite ¦ Value
Nitrate ¦ Value
Phosphate ¦ Value

I've tried the following adapted from the website above, but it returns 0 results.

<!DOCTYPE html>

<?php
$servername = "localhost";
$username = "redacted";
$password = "redacted";
$dbname = "waterparamsdb";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, temperature FROM waterparams";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    echo "

Parameter	Value
";
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "
" . $row["id"]. "	" . $row["temperature"]."
";
    }
    echo "
";
} else {
    echo "0 results";
}

$conn->close();
?>

I know this is likely just a simple understanding and formatting issue, I'm still learning!  If anyone is able to help, I would appreciate it greatly.  Thanks.

Body:
Change your if loop like this

if ($result->num_rows > 0) {
    echo "<table><tr><th>Temperature</th><th>Acidity</th><th>Ammonia</th><th>Nitrite</th><th>Nitrate</th><th>Phosphate
    </th></tr>";
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<tr><td>" . $row["Temperature"]. "</td><td>" . $row["Acidity"]."</td><td>" . $row["Ammonia"]."</td><td>" . $row["Nitrite"]."</td><td>" . $row["Nitrate"]."</td><td>" . $row["Phosphate"]."</td></tr>";
    }
    echo "</table>";
} else {
    echo "0 results";
}

But make sure the value inside these $row["Temperature"] array should be correct column name

And change your sql query to this

$sql = "SELECT * FROM waterparams";


问:
How can one tell the version of React running at runtime in the browser?
Is there a way to know the runtime version of React in the browser?</p>

答:
With the React Devtools installed you can run this from the browser console:

```<code>__REACT_DEVTOOLS_GLOBAL_HOOK__.renderers.forEach(r => console.log(`${r.rendererPackageName}: ${r.version}`))
</code>```

Which outputs something like:

```<code>react-dom: 16.12.0
</code>```

Body:
With the React Devtools installed you can run this from the browser console:

__REACT_DEVTOOLS_GLOBAL_HOOK__.renderers.forEach(r => console.log(`${r.rendererPackageName}: ${r.version}`))

Which outputs something like:

react-dom: 16.12.0


问:
resize image in xamarin without wrapping it in stacklayout
I have a lottie animation that is disabled after it is clicked again.

This is what my lottie animation looks like:

Paused:

Played:

As we can see the actual "Image" size is bigger. My row definition size is "Auto", and HeightRequest="180", WidthRequest="180" for the lottie animation.

What I want to happen here is if the lottie animation is disabled, my image that is overlapped with the animation will be (IsVisible) true.

But even if my HeightRequest="10" and WidthRequest="10" the image looks like this:

How can I achieve it to look like the size of the first image without wrapping it with stacklayout? I dont want to wrap it with stacklayout because I want my UI to be responsive.

If I use this code:

```<code>
               <StackLayout Grid.Row="2"
                             Grid.ColumnSpan="2"
                             Padding="0,55,0,0">
                    <Image Source="red_record"
                           HeightRequest="85"
                           WidthRequest="85"
                           x:Name="red_record_lottie"
                           IsVisible="True"
                           />
                </StackLayout>

</code>```

It will look like the desired output (for the UI):

But we know that the code will not make it responsive. How can I make it responsive?

答:
Well... as ironic as it may sound, I have found a solution just now... and I wrapped it with stacklayout

This is the code that worked for me:

```<code>
                <StackLayout Grid.Row="2"
                             Grid.ColumnSpan="2"
                             Padding="0,0,0,0">

                <forms:AnimationView x:Name="blue_record_lottie"
                                     Animation="blue_record.json"
                                     Loop="True"
                                     AutoPlay="False"
                                     HeightRequest="180"
                                     WidthRequest="180"
                                     Margin="0,10,0,10"
                                     OnClick="blue_record_lottie_OnClick"/>

                    <Image Source="dark_red_rec"
                           HeightRequest="85"
                           WidthRequest="85"
                           Margin="0,55,0,60"
                           x:Name="red_record_lottie"
                           IsVisible="False"/>
                </StackLayout>

</code>```

I am also surprised and I have proven this by testing on my emulator (Pixel Pie 2: 1080x1920), and my physical device (samsung galaxy core: 480 x 800).

On my Pixel Pie:

On my Samsung Galaxy Core:

Body:
I have a lottie animation that is disabled after it is clicked again.

This is what my lottie animation looks like:

Paused:

Played:

As we can see the actual "Image" size is bigger. My row definition size is "Auto", and HeightRequest="180", WidthRequest="180" for the lottie animation.

What I want to happen here is if the lottie animation is disabled, my image that is overlapped with the animation will be (IsVisible) true.

But even if my HeightRequest="10" and WidthRequest="10" the image looks like this:

How can I achieve it to look like the size of the first image without wrapping it with stacklayout? I dont want to wrap it with stacklayout because I want my UI to be responsive.

If I use this code:

               <StackLayout Grid.Row="2"
                             Grid.ColumnSpan="2"
                             Padding="0,55,0,0">
                    <Image Source="red_record"
                           HeightRequest="85"
                           WidthRequest="85"
                           x:Name="red_record_lottie"
                           IsVisible="True"
                           />
                </StackLayout>

It will look like the desired output (for the UI):

But we know that the code will not make it responsive. How can I make it responsive?

Body:
Well... as ironic as it may sound, I have found a solution just now... and I wrapped it with stacklayout

This is the code that worked for me:

                <StackLayout Grid.Row="2"
                             Grid.ColumnSpan="2"
                             Padding="0,0,0,0">

                <forms:AnimationView x:Name="blue_record_lottie"
                                     Animation="blue_record.json"
                                     Loop="True"
                                     AutoPlay="False"
                                     HeightRequest="180"
                                     WidthRequest="180"
                                     Margin="0,10,0,10"
                                     OnClick="blue_record_lottie_OnClick"/>

                    <Image Source="dark_red_rec"
                           HeightRequest="85"
                           WidthRequest="85"
                           Margin="0,55,0,60"
                           x:Name="red_record_lottie"
                           IsVisible="False"/>
                </StackLayout>

I am also surprised and I have proven this by testing on my emulator (Pixel Pie 2: 1080x1920), and my physical device (samsung galaxy core: 480 x 800).

On my Pixel Pie:

On my Samsung Galaxy Core: