问:
React Redux fetching data from backend approach
I'm a bit confused and would love an answer that will help me to clear my thoughts.
Let's say I have a backend (nodejs, express etc..) where I store my users and their data, and sometimes I wanna fetch data from the backend, such as the user info after he logs in, or a list of products and save them in the state.

My approach so far and what I've seen, I fetch the data before the component loads and dispatch an action with the data from the response.
But I recently started digging a bit about this and I saw react-thunk library which I knew earlier and started to wonder if what is the best practice of fetching from backend/API?
Has React Hooks change anything about this topic? Is it important to know this?

I feel a bit dumb but couldn't find an article or video that talks exactly about this topic :)

答:
To do this best practice, use the following method:

I used some packages and patterns for best practice:

redux-logger for log actions and states in console of browser.

reselect Selectors can compute derived data, allowing Redux to
store the minimal possible state and etc.

redux-thunk Thunks are the recommended middleware for basic
Redux side effects logic, including complex synchronous logic that
needs access to the store, and simple async logic like AJAX requests
and etc.

axios for work with api (Promise based HTTP client for the
browser and node.js)

create a directory by name redux or any name of you like in src folder and
  then create two files store.js and rootReducer.js in redux directory. We assume fetch products from API.

To do this:

Create a new directory by name product in redux directory and then
  create four files by names product.types.js, product.actions.js,
  product.reducer.js, product.selector.js in redux/product directory

The structure of the project should be as follows

```<code>...
src
  App.js
  redux
    product
      product.types.js
      product.actions.js
      product.reducer.js
    rootReducer.js
    store.js
 Index.js
package.json
...
</code>```

store.js

In this file we do the redux configuration

```<code>// redux/store.js:
import { createStore, applyMiddleware } from "redux";
import logger from "redux-logger";
import thunk from "redux-thunk";

import rootReducer from "./root-reducer";

const middlewares = [logger, thunk];

export const store = createStore(rootReducer, applyMiddleware(...middlewares));
</code>```

rootReducer.js

The combineReducers helper function turns an object whose values are
  different reducing functions into a single reducing function you can
  pass to createStore.

```<code>// redux/rootReducer.js
import { combineReducers } from "redux";

import productReducer from "./product/product.reducer";

const rootReducer = combineReducers({
  shop: productReducer,
});

export default rootReducer;
</code>```

product.types.js
In this file we define constants for manage types of actions.

```<code>export const ShopActionTypes = {
  FETCH_PRODUCTS_START: "FETCH_PRODUCTS_START",
  FETCH_PRODUCTS_SUCCESS: "FETCH_PRODUCTS_SUCCESS",
  FETCH_PRODUCTS_FAILURE: "FETCH_PRODUCTS_FAILURE"
};
</code>```

product.actions.js
In this file we create action creators for handle actions.

```<code>// redux/product/product.actions.js
import { ShopActionTypes } from "./product.types";
import axios from "axios";

export const fetchProductsStart = () => ({
  type: ShopActionTypes.FETCH_PRODUCTS_START
});

export const fetchProductsSuccess = products => ({
  type: ShopActionTypes.FETCH_PRODUCTS_SUCCESS,
  payload: products
});

export const fetchProductsFailure = error => ({
  type: ShopActionTypes.FETCH_PRODUCTS_FAILURE,
  payload: error
});

export const fetchProductsStartAsync = () => {
  return dispatch => {
    dispatch(fetchProductsStart());
    axios
      .get(url)
      .then(response => dispatch(fetchProductsSuccess(response.data.data)))
      .catch(error => dispatch(fetchProductsFailure(error)));
  };
};
</code>```

product.reducer.js
In this file we create productReducer function for handle actions.

```<code>import { ShopActionTypes } from "./product.types";

const INITIAL_STATE = {
  products: [],
  isFetching: false,
  errorMessage: undefined,
};

const productReducer = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case ShopActionTypes.FETCH_PRODUCTS_START:
      return {
        ...state,
        isFetching: true
      };
    case ShopActionTypes.FETCH_PRODUCTS_SUCCESS:
      return {
        ...state,
        products: action.payload,
        isFetching: false
      };
    case ShopActionTypes.FETCH_PRODUCTS_FAILURE:
      return {
        ...state,
        isFetching: false,
        errorMessage: action.payload
      };
    default:
      return state;
  }
};

export default productReducer;
</code>```

product.selector.js
In this file we select products and isFetching from shop state.

```<code>import { createSelector } from "reselect";

const selectShop = state => state.shop;

export const selectProducts = createSelector(
  [selectShop],
  shop => shop.products
);

export const selectIsProductsFetching = createSelector(
  [selectShop],
  shop => shop.isFetching
);
</code>```

Index.js
In this file wrapped whole app and components with Provider for access child components to the store and states.

```<code>// src/Index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

import { Provider } from "react-redux";
import { store } from "./redux/store";

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("root")
);
</code>```

App.js class component
In this file we do connect to the store and states with class component

```<code>// src/App.js
import React, { Component } from "react";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import {
  selectIsProductsFetching,
  selectProducts
} from "./redux/product/product.selectors";

import { fetchProductsStartAsync } from "./redux/product/product.actions";

class App extends Component {
  componentDidMount() {
    const { fetchProductsStartAsync } = this.props;
    fetchProductsStartAsync();
  }

  render() {
    const { products, isProductsFetching } = this.props;
    console.log('products', products);
    console.log('isProductsFetching', isProductsFetching);
    return (
      <div className="App">Please see console in browser</div>
    );
  }
}

const mapStateToProps = createStructuredSelector({
  products: selectProducts,
  isProductsFetching: selectIsProductsFetching,
});

const mapDispatchToProps = dispatch => ({
  fetchProductsStartAsync: () => dispatch(fetchProductsStartAsync())
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App);
</code>```

or App.js with functional component ( useEffect hook )
In this file we do connect to the store and states with functional component

```<code>// src/App.js
import React, { Component, useEffect } from "react";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import {
  selectIsProductsFetching,
  selectProducts
} from "./redux/product/product.selectors";

import { fetchProductsStartAsync } from "./redux/product/product.actions";

const App = ({ fetchProductsStartAsync, products, isProductsFetching}) => {
  useEffect(() => {
    fetchProductsStartAsync();
  },[]);

    console.log('products', products);
    console.log('isProductsFetching', isProductsFetching);

    return (
      <div className="App">Please see console in browser</div>
    );
}

const mapStateToProps = createStructuredSelector({
  products: selectProducts,
  isProductsFetching: selectIsProductsFetching,
});

const mapDispatchToProps = dispatch => ({
  fetchProductsStartAsync: () => dispatch(fetchProductsStartAsync())
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App);
</code>```

Body:
To do this best practice, use the following method:

I used some packages and patterns for best practice:

redux-logger for log actions and states in console of browser.

reselect Selectors can compute derived data, allowing Redux to
store the minimal possible state and etc.

redux-thunk Thunks are the recommended middleware for basic
Redux side effects logic, including complex synchronous logic that
needs access to the store, and simple async logic like AJAX requests
and etc.

axios for work with api (Promise based HTTP client for the
browser and node.js)

create a directory by name redux or any name of you like in src folder and
  then create two files store.js and rootReducer.js in redux directory. We assume fetch products from API.

To do this:

Create a new directory by name product in redux directory and then
  create four files by names product.types.js, product.actions.js,
  product.reducer.js, product.selector.js in redux/product directory

The structure of the project should be as follows

...
src
  App.js
  redux
    product
      product.types.js
      product.actions.js
      product.reducer.js
    rootReducer.js
    store.js
 Index.js
package.json
...

store.js

In this file we do the redux configuration

// redux/store.js:
import { createStore, applyMiddleware } from "redux";
import logger from "redux-logger";
import thunk from "redux-thunk";

import rootReducer from "./root-reducer";

const middlewares = [logger, thunk];

export const store = createStore(rootReducer, applyMiddleware(...middlewares));

rootReducer.js

The combineReducers helper function turns an object whose values are
  different reducing functions into a single reducing function you can
  pass to createStore.

// redux/rootReducer.js
import { combineReducers } from "redux";

import productReducer from "./product/product.reducer";

const rootReducer = combineReducers({
  shop: productReducer,
});

export default rootReducer;

product.types.js
In this file we define constants for manage types of actions.

export const ShopActionTypes = {
  FETCH_PRODUCTS_START: "FETCH_PRODUCTS_START",
  FETCH_PRODUCTS_SUCCESS: "FETCH_PRODUCTS_SUCCESS",
  FETCH_PRODUCTS_FAILURE: "FETCH_PRODUCTS_FAILURE"
};

product.actions.js
In this file we create action creators for handle actions.

// redux/product/product.actions.js
import { ShopActionTypes } from "./product.types";
import axios from "axios";

export const fetchProductsStart = () => ({
  type: ShopActionTypes.FETCH_PRODUCTS_START
});

export const fetchProductsSuccess = products => ({
  type: ShopActionTypes.FETCH_PRODUCTS_SUCCESS,
  payload: products
});

export const fetchProductsFailure = error => ({
  type: ShopActionTypes.FETCH_PRODUCTS_FAILURE,
  payload: error
});

export const fetchProductsStartAsync = () => {
  return dispatch => {
    dispatch(fetchProductsStart());
    axios
      .get(url)
      .then(response => dispatch(fetchProductsSuccess(response.data.data)))
      .catch(error => dispatch(fetchProductsFailure(error)));
  };
};

product.reducer.js
In this file we create productReducer function for handle actions.

import { ShopActionTypes } from "./product.types";

const INITIAL_STATE = {
  products: [],
  isFetching: false,
  errorMessage: undefined,
};

const productReducer = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case ShopActionTypes.FETCH_PRODUCTS_START:
      return {
        ...state,
        isFetching: true
      };
    case ShopActionTypes.FETCH_PRODUCTS_SUCCESS:
      return {
        ...state,
        products: action.payload,
        isFetching: false
      };
    case ShopActionTypes.FETCH_PRODUCTS_FAILURE:
      return {
        ...state,
        isFetching: false,
        errorMessage: action.payload
      };
    default:
      return state;
  }
};

export default productReducer;

product.selector.js
In this file we select products and isFetching from shop state.

import { createSelector } from "reselect";

const selectShop = state => state.shop;

export const selectProducts = createSelector(
  [selectShop],
  shop => shop.products
);

export const selectIsProductsFetching = createSelector(
  [selectShop],
  shop => shop.isFetching
);

Index.js
In this file wrapped whole app and components with Provider for access child components to the store and states.

// src/Index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

import { Provider } from "react-redux";
import { store } from "./redux/store";

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("root")
);

App.js class component
In this file we do connect to the store and states with class component

// src/App.js
import React, { Component } from "react";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import {
  selectIsProductsFetching,
  selectProducts
} from "./redux/product/product.selectors";

import { fetchProductsStartAsync } from "./redux/product/product.actions";

class App extends Component {
  componentDidMount() {
    const { fetchProductsStartAsync } = this.props;
    fetchProductsStartAsync();
  }

  render() {
    const { products, isProductsFetching } = this.props;
    console.log('products', products);
    console.log('isProductsFetching', isProductsFetching);
    return (
      <div className="App">Please see console in browser</div>
    );
  }
}

const mapStateToProps = createStructuredSelector({
  products: selectProducts,
  isProductsFetching: selectIsProductsFetching,
});

const mapDispatchToProps = dispatch => ({
  fetchProductsStartAsync: () => dispatch(fetchProductsStartAsync())
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

or App.js with functional component ( useEffect hook )
In this file we do connect to the store and states with functional component

// src/App.js
import React, { Component, useEffect } from "react";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import {
  selectIsProductsFetching,
  selectProducts
} from "./redux/product/product.selectors";

import { fetchProductsStartAsync } from "./redux/product/product.actions";

const App = ({ fetchProductsStartAsync, products, isProductsFetching}) => {
  useEffect(() => {
    fetchProductsStartAsync();
  },[]);

    console.log('products', products);
    console.log('isProductsFetching', isProductsFetching);

    return (
      <div className="App">Please see console in browser</div>
    );
}

const mapStateToProps = createStructuredSelector({
  products: selectProducts,
  isProductsFetching: selectIsProductsFetching,
});

const mapDispatchToProps = dispatch => ({
  fetchProductsStartAsync: () => dispatch(fetchProductsStartAsync())
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App);


来源: stackexchange

问:
Why call of Google Slides API returns error?
I have essentially been using this code to load an image into Google Drive and then transferring that image over to Google Slides using Python and for some reason it stopped working today.

The code I based mine off of is located here:
http://wescpy.blogspot.com/2016/11/using-google-slides-api-with-python.html

However, today I reran it and am getting an error:

googleapiclient.errors.HttpError: https://slides.googleapis.com/v1/presentations/PRESENTATION_ID returned "Invalid requests[0].createImage: Access to the provided image was forbidden.">

I am wondering if anything have changed in Google API?

答:
I ran into the same issue. You should check out this link, which describes changes to the Drive API: Upcoming changes to the Google Drive API and Google Picker API

The proposed solution here seems feasible, although I have not fully tested it myself: Google script replaceAllShapesWithImage with image from drive doesn"t work any more

ContentLicense: CC BY-SA 4.0


问:
SendGrid handling multiple environments
Couldn't find any info on that: does anyone know if SendGrid supports anyhow multiple environments?

I'm talking specifically about webhooks and seems that you can have only one webhook at a time where it would be nice to have separate for dev, stage and production environment while having one template base.

答: I finally found https://postmarkapp.com/ - so far the only one really supporting multiple environments independently.</p>

Title: SendGrid handling multiple environments


问:
python upload to S3 without credentials
I have S3 bucket which has following policy to allow full access from specific IP

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicWriteFromIP",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::logs-dev",
                "arn:aws:s3:::logs-dev/*"
            ],
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": "#.#.#.#/32"
                }
            }
        }
    ]
}
</code>```

I want to upload file to S3 bucket without any credentials using python. When I tried to use boto/boto3 with empty env AWS_ACCESS_KEY_ID='' & AWS_SECRET_ACCESS_KEY='' I got following error

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/boto3/s3/inject.py", line 209, in bucket_upload_file
    ExtraArgs=ExtraArgs, Callback=Callback, Config=Config)
  File "/usr/local/lib/python2.7/site-packages/boto3/s3/inject.py", line 131, in upload_file
    extra_args=ExtraArgs, callback=Callback)
  File "/usr/local/lib/python2.7/site-packages/boto3/s3/transfer.py", line 279, in upload_file
    future.result()
  File "/usr/local/lib/python2.7/site-packages/s3transfer/futures.py", line 106, in result
    return self._coordinator.result()
  File "/usr/local/lib/python2.7/site-packages/s3transfer/futures.py", line 265, in result
    raise self._exception
botocore.exceptions.NoCredentialsError: Unable to locate credentials
</code>```

How can I upload files to S3 bucket without credentials ? Is it possible to just use urllib2 to upload file to S3 (public) ?

答:
I had to enable Static Web hosting & set Block all public access to off

Then following code worked

```<code>import requests
url = "https://logs-dev.s3-us-east-1.amazonaws.com/"
data = { 'key': '/test.txt' }
files = { 'file': open('/tmp/test.txt', 'rb') }
r = requests.post(url, data=data, files=files)
print "status %s" % r.status_code
</code>```

Title: python upload to S3 without credentials

Body:
I have S3 bucket which has following policy to allow full access from specific IP

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicWriteFromIP",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::logs-dev",
                "arn:aws:s3:::logs-dev/*"
            ],
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": "#.#.#.#/32"
                }
            }
        }
    ]
}

I want to upload file to S3 bucket without any credentials using python. When I tried to use boto/boto3 with empty env AWS_ACCESS_KEY_ID='' & AWS_SECRET_ACCESS_KEY='' I got following error

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/boto3/s3/inject.py", line 209, in bucket_upload_file
    ExtraArgs=ExtraArgs, Callback=Callback, Config=Config)
  File "/usr/local/lib/python2.7/site-packages/boto3/s3/inject.py", line 131, in upload_file
    extra_args=ExtraArgs, callback=Callback)
  File "/usr/local/lib/python2.7/site-packages/boto3/s3/transfer.py", line 279, in upload_file
    future.result()
  File "/usr/local/lib/python2.7/site-packages/s3transfer/futures.py", line 106, in result
    return self._coordinator.result()
  File "/usr/local/lib/python2.7/site-packages/s3transfer/futures.py", line 265, in result
    raise self._exception
botocore.exceptions.NoCredentialsError: Unable to locate credentials

How can I upload files to S3 bucket without credentials ? Is it possible to just use urllib2 to upload file to S3 (public) ?

Body:
I had to enable Static Web hosting & set Block all public access to off

Then following code worked

import requests
url = "https://logs-dev.s3-us-east-1.amazonaws.com/"
data = { 'key': '/test.txt' }
files = { 'file': open('/tmp/test.txt', 'rb') }
r = requests.post(url, data=data, files=files)
print "status %s" % r.status_code


问:
XSLT can't find element in XML
I am trying to find the "source" element in the xml file but the XSLT code can't find the source element in the XML. Any thoughts on why the XSLT is not working and finding the source element?

XSLT:

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt"  exclude-result-prefixes="msxsl">
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

      <xsl:template match="source">

            <xsl:apply-templates select="@* | node()"/>
            <xsl:apply-templates select="Target"/>

    </xsl:template>

</xsl:stylesheet>
</code>```

XML File:

```<code><?xml version="1.0" encoding="utf-8"?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:sap="http://www.sap.com" xmlns:xhtml="http://www.w3.ogr/1999/xhtml" xmlns:w="http://www.sap.com/w">
    <file datatype="x-application/dsl universe" original="file:/C:/Users/Cost%20Center%20Hierarchy.blx" product-name="SAP Businessobjects Enterprise XI 4.0" source-language="en-US" target-language="pl-PL">
        <header>
            <phase-group>
                <phase process-name="devel" phase-name="devel" tool-id="x-sap-translation-management-tool" />
            </phase-group>
            <tool tool-name="Translation Management Tool" tool-id="x-sap-translation-management-tool" tool-version="XI 4.0" tool-company="SAP Business Objects " />
            <sap:localization-properties>
                <formats />
                <sap:locale-attribute visible="0" fallback="0" modified="0" />
            </sap:localization-properties>
        </header>
        <body>
            <group id="Universe:_7lB2dhEaEeSA04VtNpazeQ">
                <trans-unit id="Universe:_7lB2dhEaEeSA04VtNpazeQ?name" datatype="plaintext">
                    <source>XYZ Hierarchy</source>
                </trans-unit>
                <group>
                    <group id="Folder:_7lB2eREaEeSA04VtNpazeQ">
                        <trans-unit id="Folder:_7lB2eREaEeSA04VtNpazeQ?name" datatype="plaintext">
                            <source>Cost Center Hierarchy</source>
                        </trans-unit>
                        <group id="Dimension:_7lB2ehEaEeSA04VtNpazeQ">
                            <trans-unit id="Dimension:_7lB2ehEaEeSA04VtNpazeQ?name" datatype="plaintext">
                                <source>XYZ Area</source>
                            </trans-unit>
                        </group>
                </group>
            </group>
        </body>
    </file>
</xliff>
</code>```

Thank you for the help in advanced.

答:
You don't have an element called source. You do have an element called urn:oasis:names:tc:xliff:document:1.2: source. The namespace of an XML node always matters, and you've specified by the xmlns attribute in the document that any element not otherwise specified is in this namespace.

To fix this problem, include the namespace with a prefix:

xmlns:some prefix="urn:oasis:names:tc:xliff:document:1.2"

and reference the desired element by this prefix:

<xsl:template match="myprefix:source">

Title: XSLT can't find element in XML

Body:
I am trying to find the "source" element in the xml file but the XSLT code can't find the source element in the XML. Any thoughts on why the XSLT is not working and finding the source element?

XSLT:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt"  exclude-result-prefixes="msxsl">
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

      <xsl:template match="source">

            <xsl:apply-templates select="@* | node()"/>
            <xsl:apply-templates select="Target"/>

    </xsl:template>

</xsl:stylesheet>

XML File:

<?xml version="1.0" encoding="utf-8"?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:sap="http://www.sap.com" xmlns:xhtml="http://www.w3.ogr/1999/xhtml" xmlns:w="http://www.sap.com/w">
    <file datatype="x-application/dsl universe" original="file:/C:/Users/Cost%20Center%20Hierarchy.blx" product-name="SAP Businessobjects Enterprise XI 4.0" source-language="en-US" target-language="pl-PL">

            <phase-group>
                <phase process-name="devel" phase-name="devel" tool-id="x-sap-translation-management-tool" />
            </phase-group>
            <tool tool-name="Translation Management Tool" tool-id="x-sap-translation-management-tool" tool-version="XI 4.0" tool-company="SAP Business Objects " />
            <sap:localization-properties>
                <formats />
                <sap:locale-attribute visible="0" fallback="0" modified="0" />
            </sap:localization-properties>

            <group id="Universe:_7lB2dhEaEeSA04VtNpazeQ">
                <trans-unit id="Universe:_7lB2dhEaEeSA04VtNpazeQ?name" datatype="plaintext">
                    <source>XYZ Hierarchy</source>
                </trans-unit>
                <group>
                    <group id="Folder:_7lB2eREaEeSA04VtNpazeQ">
                        <trans-unit id="Folder:_7lB2eREaEeSA04VtNpazeQ?name" datatype="plaintext">
                            <source>Cost Center Hierarchy</source>
                        </trans-unit>
                        <group id="Dimension:_7lB2ehEaEeSA04VtNpazeQ">
                            <trans-unit id="Dimension:_7lB2ehEaEeSA04VtNpazeQ?name" datatype="plaintext">
                                <source>XYZ Area</source>
                            </trans-unit>
                        </group>
                </group>
            </group>

    </file>
</xliff>

Thank you for the help in advanced.


问:
Clustered leaflet markers with sum (not count) totals: how to get consistent round red shape and label format like in unclustered markers
I would like to modify the behavior of leaflet grouping feature to total on grouping and preserve a round red bubble shape dependent on value.

My data contains columns:

lon lat sales_ytd

I would like to cluster data depending on zoom using clusterOptions = markerClusterOptions(iconCreateFunction=JS(sum.formula))

Here is my function. I do not know JS but I tried numerous examples and the function works by summing up the grouped values.

```<code> sum.formula  = JS("function (cluster) {
        var markers = cluster.getAllChildMarkers();
        var sum = 0;
        for (i = 0; i < markers.length; i++) {
          sum += Number(markers[i].options.mag);
    //      sum += 1;
        }
          var size = sum/30000;

        return new L.DivIcon({ html:  sum ,  iconSize: L.point(size, size)});
      }")
</code>```

Evidently L.DivIcon() returns a square... is there a way for it to return round red bubble?

Then I am trying using it in a shiny app (R code).

```<code>renderLeaflet({
  leaflet(df_summary_towns()) %>%
  addTiles() %>%
  addCircleMarkers(
    radius = ~sales_ytd/30000,
    color = 'red',
    stroke = FALSE,
    fillOpacity = 0.5,
    options = markerOptions(mag = ~ sales_ytd),
    clusterOptions = markerClusterOptions(iconCreateFunction=JS(sum.formula))
  ) %>%
    addLabelOnlyMarkers(
      ~lon, ~lat,
      options = markerOptions(mag = ~ sales_ytd),
      label =  ~scales::number(sales_ytd),
      labelOptions = labelOptions(noHide = T, direction = 'center', textOnly = T),
      clusterOptions = markerClusterOptions(iconCreateFunction=JS(sum.formula)))
})
</code>```

The grouping somewhat works, the values are totaled for clustered data and if I click them, leaflet zooms and show individual points (nice red circles with values inside). But the grouped markers are white squares and not round red circles like the individual points. Also I do not know how to achieve consistent formatting for numbers. In R it is easy but the definition of grouped markers is now in JS.
How can it be achieved: consistent shape, color and size dependent on value in both ungrouped and grouped markers and consistent number formats?
One can also see I tried normalizing the size in R, and I divided size/1000 in JS - I did not know how to pass the sum of the data.frame column to JS.

答:
For total number of markers/layers you can use the getLayers() function which will return an array of all the component layers of that cluster.

```<code>var testCluster = L.markerClusterGroup();
L.marker([event.latlng.lat,
event.latlng.lng]).addTo(testCluster);
testCluster.getLayers();
</code>```

It will return array of each marker as layer.

Alternatively You can use this:

```<code>map.eachLayer(function (layer) {
        if (layer.getChildCount){
            console.log(layer._childClusters.length)
            console.log(layer._childCount);
            }
    });
</code>```

Body:
I would like to modify the behavior of leaflet grouping feature to total on grouping and preserve a round red bubble shape dependent on value.

My data contains columns:

lon lat sales_ytd

I would like to cluster data depending on zoom using clusterOptions = markerClusterOptions(iconCreateFunction=JS(sum.formula))

Here is my function. I do not know JS but I tried numerous examples and the function works by summing up the grouped values.

 sum.formula  = JS("function (cluster) {
        var markers = cluster.getAllChildMarkers();
        var sum = 0;
        for (i = 0; i < markers.length; i++) {
          sum += Number(markers[i].options.mag);
    //      sum += 1;
        }
          var size = sum/30000;

        return new L.DivIcon({ html:  sum ,  iconSize: L.point(size, size)});
      }")

Evidently L.DivIcon() returns a square... is there a way for it to return round red bubble?

Then I am trying using it in a shiny app (R code).

renderLeaflet({
  leaflet(df_summary_towns()) %>%
  addTiles() %>%
  addCircleMarkers(
    radius = ~sales_ytd/30000,
    color = 'red',
    stroke = FALSE,
    fillOpacity = 0.5,
    options = markerOptions(mag = ~ sales_ytd),
    clusterOptions = markerClusterOptions(iconCreateFunction=JS(sum.formula))
  ) %>%
    addLabelOnlyMarkers(
      ~lon, ~lat,
      options = markerOptions(mag = ~ sales_ytd),
      label =  ~scales::number(sales_ytd),
      labelOptions = labelOptions(noHide = T, direction = 'center', textOnly = T),
      clusterOptions = markerClusterOptions(iconCreateFunction=JS(sum.formula)))
})

The grouping somewhat works, the values are totaled for clustered data and if I click them, leaflet zooms and show individual points (nice red circles with values inside). But the grouped markers are white squares and not round red circles like the individual points. Also I do not know how to achieve consistent formatting for numbers. In R it is easy but the definition of grouped markers is now in JS.
How can it be achieved: consistent shape, color and size dependent on value in both ungrouped and grouped markers and consistent number formats?
One can also see I tried normalizing the size in R, and I divided size/1000 in JS - I did not know how to pass the sum of the data.frame column to JS.

Body:
For total number of markers/layers you can use the getLayers() function which will return an array of all the component layers of that cluster.

var testCluster = L.markerClusterGroup();
L.marker([event.latlng.lat,
event.latlng.lng]).addTo(testCluster);
testCluster.getLayers();

It will return array of each marker as layer.

Alternatively You can use this:

map.eachLayer(function (layer) {
        if (layer.getChildCount){
            console.log(layer._childClusters.length)
            console.log(layer._childCount);
            }
    });


问:
System.ArgumentOutOfRangeException: 'Specified argument was out of the range of valid values. Parameter name: index' in asp.net
Default.aspx

```<code>        <Columns>
            <asp:TemplateField HeaderText="Type">
                <ItemTemplate>
                    <asp:DropDownList ID="typeHobby" runat="server">
                        <asp:ListItem style="display:none">--Select--</asp:ListItem>
                        <asp:ListItem Value="Sports">Sports</asp:ListItem>
                        <asp:ListItem Value="FineArt">Fine Arts</asp:ListItem>
                        <asp:ListItem Value="Other">Other</asp:ListItem>
                    </asp:DropDownList>
                </ItemTemplate>
            </asp:TemplateField>

            <asp:TemplateField HeaderText="Name">
                <ItemTemplate>
                     <asp:TextBox  ID="nameSport" style="margin:2px" CssClass="cap" pattern="[A-Za-z]{2,15}" runat="server" ></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Details of participation">
                <ItemTemplate>
                     <asp:TextBox ID="detailSport" style="margin:2px" CssClass="cap" pattern="[A-Za-z]{2,15}" runat="server"></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Distinction achieved">
                <ItemTemplate>
                     <asp:TextBox ID="distSport" style="margin:2px" CssClass="cap" pattern="[A-Za-z]{2,15}" runat="server"></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Whether still intrested">
                <ItemTemplate>
                    <asp:DropDownList ID="intrestSport" runat="server">
                        <asp:ListItem style="display:none">--Select--</asp:ListItem>
                        <asp:ListItem Value="yes">Yes</asp:ListItem>
                        <asp:ListItem Value="no">No</asp:ListItem>
                    </asp:DropDownList>
                </ItemTemplate>
                <FooterStyle HorizontalAlign="Right" />
                    <FooterTemplate>
                        <asp:Button ID="addHobby" runat="server" Text="Add" OnClick="ButtonAdd_Click_Hobby" CausesValidation="false" />
                    </FooterTemplate>
            </asp:TemplateField>
        </Columns>

    </asp:GridView>
</code>```

Default.aspx.cs

```<code>protected void ButtonAdd_Click_Hobby(object sender, EventArgs e)
        {
            addHobby();
        }

        protected void addHobby()
        {
         //   MessageBox.Show("add hobby");
            try
            {
                int rowIndex = 0;
                if (ViewState["HoobyTable"] != null)
                {
                    MessageBox.Show("if true");
                    DataTable dtHobbyTable = (DataTable)ViewState["HoobyTable"];
                    DataRow drHobbyRow = null;
                    if (dtHobbyTable.Rows.Count > 0)
                    {
                        MessageBox.Show(dtHobbyTable.Rows.Count.ToString());
                        for (int i = 1; i <= dtHobbyTable.Rows.Count; i++)
                        {
                            //extract the TextBox values
                            MessageBox.Show("loop");
                            DropDownList txh1 = (DropDownList)hobbyGrid.Rows[rowIndex].Cells[1].FindControl("typeHobby");
                            TextBox txh2 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[2].FindControl("nameSport");
                            TextBox txh3 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[3].FindControl("detailSport");
                            TextBox txh4 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[4].FindControl("distSport");
                            DropDownList txh5 = (DropDownList)hobbyGrid.Rows[rowIndex].Cells[5].FindControl("intrestSport");
                            MessageBox.Show("Hello" + txh1.Text);
                            drHobbyRow = dtHobbyTable.NewRow();
                            drHobbyRow["Slno"] = i + 1;

                            dtHobbyTable.Rows[i - 1]["hoType"] = txh1.Text;
                            dtHobbyTable.Rows[i - 1]["Name"] = txh2.Text;
                            dtHobbyTable.Rows[i - 1]["Detail"] = txh3.Text;
                            dtHobbyTable.Rows[i - 1]["Distinction"] = txh4.Text;
                            dtHobbyTable.Rows[i - 1]["Interest"] ="interest";

                            rowIndex++;
                        }
                        dtHobbyTable.Rows.Add(drHobbyRow);
                        ViewState["HoobyTable"] = dtHobbyTable;

                        hobbyGrid.DataSource = dtHobbyTable;
                        hobbyGrid.DataBind();
                    }
                }
                else
                {
                    Response.Write("ViewState is null");
                }
            }
            catch (Exception e)
            {
                // MessageBox.Show(e.ToString());
            }
            //Set Previous Data on Postbacks
          SetPreviousDataHobby();

        }
        private void SetPreviousDataHobby()
        {
            int rowIndex = 0;
            if (ViewState["HoobyTable"] != null)
            {
                DataTable dt = (DataTable)ViewState["HoobyTable"];
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {

                        DropDownList txh1 = (DropDownList)hobbyGrid.Rows[rowIndex].Cells[1].FindControl("typeHobby");
                        TextBox txh2 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[2].FindControl("nameSport");
                        TextBox txh3 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[3].FindControl("detailSport");
                        TextBox txh4 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[4].FindControl("distSport");
                        DropDownList txh5 = (DropDownList)hobbyGrid.Rows[rowIndex].Cells[5].FindControl("intrestSport");
                        MessageBox.Show("type hobby" + dt.Rows[i]["hoType"].ToString());
                        txh1.Text = dt.Rows[i]["hoType"].ToString();
                        txh2.Text = dt.Rows[i]["Name"].ToString();
                        txh3.Text = dt.Rows[i]["Detail"].ToString();
                        txh4.Text = dt.Rows[i]["Distinction"].ToString();
                        txh5.Text = dt.Rows[i]["Interest"].ToString();

                        rowIndex++;
                    }
                }
            }
        }
</code>```

System.ArgumentOutOfRangeException: 'Specified argument was out of the range of valid values.
Parameter name: index'
-> got an error like above in line:
DropDownList txh5 = (DropDownList)hobbyGrid.Rows[rowIndex].Cells[5].FindControl("intrestSport");

(line from SetPreviousDataHobby() function)

答:
Error is because, you are accessing cells from 1 through 5. so at Cells[5] its throwing out of range exception. Please modify your code to start from 0:

```<code>DropDownList txh1 = (DropDownList)hobbyGrid.Rows[rowIndex].Cells[0].FindControl("typeHobby");
TextBox txh2 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[1].FindControl("nameSport");
TextBox txh3 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[2].FindControl("detailSport");
TextBox txh4 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[3].FindControl("distSport");
DropDownList txh5 = (DropDownList)hobbyGrid.Rows[rowIndex].Cells[4].FindControl("intrestSport");
</code>```

Side but related notes:
1) There is another issue that you may encounter after fixing this error:
adding data row outside forloop. So, you are basically overwriting data row in for loop and adding just one row. Ignore me if that is what you expected. Otherwise, move the below line inside for loop.

```<code>dtHobbyTable.Rows.Add(drHobbyRow);
</code>```

2) Another issue is you are running for loop on an item which you are updating. Instead its good to have for loop on hobbyGrid.Rows.Count.

Body:
Default.aspx

        <Columns>
            <asp:TemplateField HeaderText="Type">
                <ItemTemplate>
                    <asp:DropDownList ID="typeHobby" runat="server">
                        <asp:ListItem style="display:none">--Select--</asp:ListItem>
                        <asp:ListItem Value="Sports">Sports</asp:ListItem>
                        <asp:ListItem Value="FineArt">Fine Arts</asp:ListItem>
                        <asp:ListItem Value="Other">Other</asp:ListItem>
                    </asp:DropDownList>
                </ItemTemplate>
            </asp:TemplateField>

            <asp:TemplateField HeaderText="Name">
                <ItemTemplate>
                     <asp:TextBox  ID="nameSport" style="margin:2px" CssClass="cap" pattern="[A-Za-z]{2,15}" runat="server" ></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Details of participation">
                <ItemTemplate>
                     <asp:TextBox ID="detailSport" style="margin:2px" CssClass="cap" pattern="[A-Za-z]{2,15}" runat="server"></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Distinction achieved">
                <ItemTemplate>
                     <asp:TextBox ID="distSport" style="margin:2px" CssClass="cap" pattern="[A-Za-z]{2,15}" runat="server"></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Whether still intrested">
                <ItemTemplate>
                    <asp:DropDownList ID="intrestSport" runat="server">
                        <asp:ListItem style="display:none">--Select--</asp:ListItem>
                        <asp:ListItem Value="yes">Yes</asp:ListItem>
                        <asp:ListItem Value="no">No</asp:ListItem>
                    </asp:DropDownList>
                </ItemTemplate>
                <FooterStyle HorizontalAlign="Right" />
                    <FooterTemplate>
                        <asp:Button ID="addHobby" runat="server" Text="Add" OnClick="ButtonAdd_Click_Hobby" CausesValidation="false" />
                    </FooterTemplate>
            </asp:TemplateField>
        </Columns>

    </asp:GridView>

Default.aspx.cs

protected void ButtonAdd_Click_Hobby(object sender, EventArgs e)
        {
            addHobby();
        }

        protected void addHobby()
        {
         //   MessageBox.Show("add hobby");
            try
            {
                int rowIndex = 0;
                if (ViewState["HoobyTable"] != null)
                {
                    MessageBox.Show("if true");
                    DataTable dtHobbyTable = (DataTable)ViewState["HoobyTable"];
                    DataRow drHobbyRow = null;
                    if (dtHobbyTable.Rows.Count > 0)
                    {
                        MessageBox.Show(dtHobbyTable.Rows.Count.ToString());
                        for (int i = 1; i <= dtHobbyTable.Rows.Count; i++)
                        {
                            //extract the TextBox values
                            MessageBox.Show("loop");
                            DropDownList txh1 = (DropDownList)hobbyGrid.Rows[rowIndex].Cells[1].FindControl("typeHobby");
                            TextBox txh2 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[2].FindControl("nameSport");
                            TextBox txh3 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[3].FindControl("detailSport");
                            TextBox txh4 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[4].FindControl("distSport");
                            DropDownList txh5 = (DropDownList)hobbyGrid.Rows[rowIndex].Cells[5].FindControl("intrestSport");
                            MessageBox.Show("Hello" + txh1.Text);
                            drHobbyRow = dtHobbyTable.NewRow();
                            drHobbyRow["Slno"] = i + 1;

                            dtHobbyTable.Rows[i - 1]["hoType"] = txh1.Text;
                            dtHobbyTable.Rows[i - 1]["Name"] = txh2.Text;
                            dtHobbyTable.Rows[i - 1]["Detail"] = txh3.Text;
                            dtHobbyTable.Rows[i - 1]["Distinction"] = txh4.Text;
                            dtHobbyTable.Rows[i - 1]["Interest"] ="interest";

                            rowIndex++;
                        }
                        dtHobbyTable.Rows.Add(drHobbyRow);
                        ViewState["HoobyTable"] = dtHobbyTable;

                        hobbyGrid.DataSource = dtHobbyTable;
                        hobbyGrid.DataBind();
                    }
                }
                else
                {
                    Response.Write("ViewState is null");
                }
            }
            catch (Exception e)
            {
                // MessageBox.Show(e.ToString());
            }
            //Set Previous Data on Postbacks
          SetPreviousDataHobby();

        }
        private void SetPreviousDataHobby()
        {
            int rowIndex = 0;
            if (ViewState["HoobyTable"] != null)
            {
                DataTable dt = (DataTable)ViewState["HoobyTable"];
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {

                        DropDownList txh1 = (DropDownList)hobbyGrid.Rows[rowIndex].Cells[1].FindControl("typeHobby");
                        TextBox txh2 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[2].FindControl("nameSport");
                        TextBox txh3 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[3].FindControl("detailSport");
                        TextBox txh4 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[4].FindControl("distSport");
                        DropDownList txh5 = (DropDownList)hobbyGrid.Rows[rowIndex].Cells[5].FindControl("intrestSport");
                        MessageBox.Show("type hobby" + dt.Rows[i]["hoType"].ToString());
                        txh1.Text = dt.Rows[i]["hoType"].ToString();
                        txh2.Text = dt.Rows[i]["Name"].ToString();
                        txh3.Text = dt.Rows[i]["Detail"].ToString();
                        txh4.Text = dt.Rows[i]["Distinction"].ToString();
                        txh5.Text = dt.Rows[i]["Interest"].ToString();

                        rowIndex++;
                    }
                }
            }
        }

System.ArgumentOutOfRangeException: 'Specified argument was out of the range of valid values.
Parameter name: index'
-> got an error like above in line:
DropDownList txh5 = (DropDownList)hobbyGrid.Rows[rowIndex].Cells[5].FindControl("intrestSport");

(line from SetPreviousDataHobby() function)

Body:
Error is because, you are accessing cells from 1 through 5. so at Cells[5] its throwing out of range exception. Please modify your code to start from 0:

DropDownList txh1 = (DropDownList)hobbyGrid.Rows[rowIndex].Cells[0].FindControl("typeHobby");
TextBox txh2 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[1].FindControl("nameSport");
TextBox txh3 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[2].FindControl("detailSport");
TextBox txh4 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[3].FindControl("distSport");
DropDownList txh5 = (DropDownList)hobbyGrid.Rows[rowIndex].Cells[4].FindControl("intrestSport");

Side but related notes:
1) There is another issue that you may encounter after fixing this error:
adding data row outside forloop. So, you are basically overwriting data row in for loop and adding just one row. Ignore me if that is what you expected. Otherwise, move the below line inside for loop.

dtHobbyTable.Rows.Add(drHobbyRow);

2) Another issue is you are running for loop on an item which you are updating. Instead its good to have for loop on hobbyGrid.Rows.Count.


问:
What are some reasons for jquery .focus() not working?
Some thoughts are that the ELEMENT_ID.focus() is inside divs that are hidden at certain times.

This should be an easy problem to solve -- but I'm struggling :(

***code works fine -- the text field isn't being focused on upon page loading up.

STEP1 [SOLVED]
JAVASCRIPT:

```<code>$("#goal-input").focus();

$('#goal-input').keypress(function(event){
 var keycode = (event.keyCode ? event.keyCode : event.which);
  if(keycode == '13') {
etc, etc, etc
}
</code>```

HTML

```<code><input type="text" id="goal-input" name="goal" />
</code>```

[STEP2]
JAVASCRIPT:

```<code> if (goal) {
          step1.fadeOut('fast', function() {
          step1.hide();
          step2.fadeIn('fast');

etc, etc
</code>```

HTML:

```<code>  <div id="step-2">
        <div class="notifications">
        </div>
        <input type="text" id="name"   name="name" placeholder="Name" />
               <script type="text/javascript">
              $(function(){
              $("#name").focus();
              });
            </script>
</code>```

Why doesn't step 2 work? :(

答:
The problem is there is a JavaScript .focus and a jQuery .focus function. This call to .focus is ambiguous. So it doesn't always work. What I do is cast my jQuery object to a JavaScript object and use the JavaScript .focus. This works for me:</p>

```<code>$("#goal-input")[0].focus();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Some thoughts are that the ELEMENT_ID.focus() is inside divs that are hidden at certain times.

This should be an easy problem to solve -- but I'm struggling :(

***code works fine -- the text field isn't being focused on upon page loading up.

STEP1 [SOLVED]
JAVASCRIPT:

$("#goal-input").focus();

$('#goal-input').keypress(function(event){
 var keycode = (event.keyCode ? event.keyCode : event.which);
  if(keycode == '13') {
etc, etc, etc
}

HTML

<input type="text" id="goal-input" name="goal" />

[STEP2]
JAVASCRIPT:

 if (goal) {
          step1.fadeOut('fast', function() {
          step1.hide();
          step2.fadeIn('fast');

etc, etc

HTML:

        <input type="text" id="name"   name="name" placeholder="Name" />

Why doesn't step 2 work? :(

Body:
The problem is there is a JavaScript .focus and a jQuery .focus function. This call to .focus is ambiguous. So it doesn't always work. What I do is cast my jQuery object to a JavaScript object and use the JavaScript .focus. This works for me:

$("#goal-input")[0].focus();


问:
how to pass encrypted query string in asp.net
I need to pass values between asp.net pages. How do i encrypt those values in the URL?
Example : Response.Redirect("customerAdd.aspx?customerId=" + custId);</p>

答:
Create a key/value pair string. Encrypt it. Base64 it. Now, just have a query string variable called "x" or something, and the value will be the Base64 string, so like:

domain.com/MyPage?x=hfjhwke878979blahblah

Then, you decrypt and use it and put it back into a key/value data structure.
This is one approach.

OwnerDisplayName: Ksmps

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: BobbyShaftoe


问:
Using the addition function over the natural numbers, give a recursive definition of multiplication of natural numbers?
I have the following exercise but am not sure on how I should begin. The wording doesn't make sense to me:

Using the addition function over the
  natural numbers, give a recursive
  definition of multiplication of
  natural numbers.

答:
Multiplication of i, j is nothing but adding i, j times. this is java code, but you can take the logic from this.</p>

```<code>    public int mul(int i, int j) {
        if(j==1) return i;
        return i + mul(i, j-1);
    }
</code>```

Body:
Multiplication of i, j is nothing but adding i, j times. this is java code, but you can take the logic from this.

    public int mul(int i, int j) {
        if(j==1) return i;
        return i + mul(i, j-1);
    }


问:
Get request body string from ServerHttpRequest / Flux<DataBuffer>
I am using spring boot version - 2.0.6.RELEASE and spring cloud version - Finchley.SR2

and i have created my custom gateway filter to modify the request body.

but while converting the request body to string using Flux i am getting a empty string. i need a method to get the string corresponding to my request  body.

```<code>@Override
public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    ServerHttpRequest request = (ServerHttpRequest) exchange.getRequest();
    String s = resolveBodyFromRequest(request);
     /* s comes out to be "" */
    return chain.filter(newExchange);

}

private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest){
    //Get the request body
    Flux<DataBuffer> body = serverHttpRequest.getBody();
    StringBuilder sb = new StringBuilder();

    body.subscribe(buffer -> {
        byte[] bytes = new byte[buffer.readableByteCount()];
        buffer.read(bytes);
        DataBufferUtils.release(buffer);
        String bodyString = new String(bytes, StandardCharsets.UTF_8);
        sb.append(bodyString);
    });
    return sb.toString();

}
</code>```

答:
You could use the ModifyRequestBodyGatewayFilterFactory which I believe is included in Spring Cloud Gateway 2.0.2 which is part of Finchley. </p>

<p>For Ex: </p>

```<code>@Override
public GatewayFilter apply(Config config) {
   return (exchange, chain) -> {
        ModifyRequestBodyGatewayFilterFactory.Config modifyRequestConfig = new ModifyRequestBodyGatewayFilterFactory.Config()
                .setContentType(ContentType.APPLICATION_JSON.getMimeType())
                .setRewriteFunction(String.class, String.class, (exchange1, originalRequestBody) -> {
                    String modifiedRequestBody = yourMethodToModifyRequestBody(originalRequestBody);
                    return Mono.just(modifiedRequestBody);
                });

        return new ModifyRequestBodyGatewayFilterFactory().apply(modifyRequestConfig).filter(exchange, chain);
    };
}
</code>```

Body:
I am using spring boot version - 2.0.6.RELEASE and spring cloud version - Finchley.SR2

and i have created my custom gateway filter to modify the request body.

but while converting the request body to string using Flux i am getting a empty string. i need a method to get the string corresponding to my request  body.

@Override
public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    ServerHttpRequest request = (ServerHttpRequest) exchange.getRequest();
    String s = resolveBodyFromRequest(request);
     /* s comes out to be "" */
    return chain.filter(newExchange);

}

private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest){
    //Get the request body
    Flux<DataBuffer> body = serverHttpRequest.getBody();
    StringBuilder sb = new StringBuilder();

    body.subscribe(buffer -> {
        byte[] bytes = new byte[buffer.readableByteCount()];
        buffer.read(bytes);
        DataBufferUtils.release(buffer);
        String bodyString = new String(bytes, StandardCharsets.UTF_8);
        sb.append(bodyString);
    });
    return sb.toString();

}

Body:
You could use the ModifyRequestBodyGatewayFilterFactory which I believe is included in Spring Cloud Gateway 2.0.2 which is part of Finchley.

For Ex:

@Override
public GatewayFilter apply(Config config) {
   return (exchange, chain) -> {
        ModifyRequestBodyGatewayFilterFactory.Config modifyRequestConfig = new ModifyRequestBodyGatewayFilterFactory.Config()
                .setContentType(ContentType.APPLICATION_JSON.getMimeType())
                .setRewriteFunction(String.class, String.class, (exchange1, originalRequestBody) -> {
                    String modifiedRequestBody = yourMethodToModifyRequestBody(originalRequestBody);
                    return Mono.just(modifiedRequestBody);
                });

        return new ModifyRequestBodyGatewayFilterFactory().apply(modifyRequestConfig).filter(exchange, chain);
    };
}


问:
Redirect to component in Angular based upon error status code
I am handling errors with four pieces...an http interceptor for server returned errors, a global error handler that builds upon the built-in Angular error handler. an error service that logs the errors to a back end service for support purposes and a Material dialog component to display a friendly message to the end user.

There are some errors where we wish to capture the error status code and redirect to a component for a friendlier end user experience.

One example is a 404. We have a not found component. If the server error status is 404, I want to redirect to the not found component and not display the error dialog.

Here is my interceptor...

```<code>import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
import { MatDialog } from '@angular/material';
import * as StackTrace from 'stacktrace-js';
import { ErrorDialogComponent } from './error-dialog.component';
import { PathLocationStrategy } from '@angular/common';
import { ErrorService } from './error.service';
import { LoggerService } from './logger.service';
import { Router } from '@angular/router';

@Injectable()
/**
 * HttpErrorInterceptor to grab errors during http calls and log them
 *
 * @param (clientId) client id
 */
export class HttpErrorInterceptor implements HttpInterceptor {
  /**
   * constructor to grab errors during http calls and log them
   *
   * @param (dialog) MAT dialog to display to end user
   * @param (errorService) error service to grab error messages
   * @param (logger) logger service to post log errors to api and mantis
   */
  constructor(
    public dialog: MatDialog,
    private errorService: ErrorService,
    private logger: LoggerService,
    private router: Router
  ) {}
  /**
   * Interecept to grab request, deal with it and pass it along
   *
   * @param (request) http request
   * @param (next) send request to next http handler
   */
  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    // return the next statement
    return next.handle(request).pipe(
      // retry the call once
      retry(1),
      // catch the error
      catchError((error: HttpErrorResponse) => {
        if (error.status === 404) {
          console.log('error.status: ', error.status);
          // this.router.navigate(['']);
        } else {
          // Message variable to hold error message
          let errorMessage = '';
          // Variable to hold url location of error
          const url =
            location instanceof PathLocationStrategy ? location.path() : '';
          // server-side error
          errorMessage = this.errorService.getServerMessage(error);
          // get the stack trace, lets grab the last 10 stacks only
          StackTrace.fromError(error).then(stackframes => {
            const stackString = stackframes
              .splice(0, 20)
              .map(function(sf) {
                return sf.toString();
              })
              .join();
            /**
             * Function to log errors to api and mantis
             *
             * @param (errorMessage) error message passed to function
             * @param (url) url passed to function
             * @param (stackString) stackString passed to function
             */
            this.logger
              .createErrorLog(errorMessage, url, stackString)
              .subscribe(
                result => {
                  console.log('log filed: ', result);
                },
                (err: any) => console.log(err)
              );
          });
          // Check if error is undefined and open dialog with appropriate error info
          if (typeof errorMessage !== 'undefined') {
            this.openDialog(errorMessage);
          } else {
            this.openDialog('undefined');
          }
          // throw error
          return throwError(errorMessage);
        }
      })
    );
  }
  /**
   * Function to open dialog to display error
   *
   * @param (data) error data to display
   */
  openDialog(data): void {
    // Constant to hold and call dialog to display error
    const dialogRef = this.dialog.open(ErrorDialogComponent, {
      width: '60%',
      data: data
    });
    // Code to run after the dialog is closed
    dialogRef.afterClosed().subscribe(result => {
      // Redirect back to home (dashboard)?
    });
  }
}
</code>```

As you can see, I have a simple if where I am checking the status code. I then have a navigate method call where I am trying to route to nothing because my router module has the not found component listed as the "nothing" route.

This is redirecting, but also displaying the error dialog message. I do not want that to display. The dialog just displays the error message to the end user and gives them ways to contact us.

Here is my Global Handler...

```<code>import { ErrorHandler, Injectable, Injector } from '@angular/core';
import {
  HttpErrorResponse,
  HttpHeaders,
  HttpClient
} from '@angular/common/http';
import { LocationStrategy, PathLocationStrategy } from '@angular/common';
import { throwError } from 'rxjs';
import * as StackTrace from 'stacktrace-js';
import { LoggerService } from '../core/logger.service';
import { ErrorService } from '../core/error.service';
import { MatDialog } from '@angular/material';
import { ErrorDialogComponent } from './error-dialog.component';
import { ConfigService } from '../app-config.service';

@Injectable({
  providedIn: 'root'
})
/**
 * GlobalErrorHandler to grab errors and log them
 */
export class GlobalErrorHandler implements ErrorHandler {
  /**
   * constructor to inject
   */
  constructor(private injector: Injector, public dialog: MatDialog) {}
  /**
   * Function to handle errors
   *
   * @param (error) error passed to function
   */
  handleError(error: Error) {
    console.log('error (global): ', error);
    const errorService = this.injector.get(ErrorService);
    const logger = this.injector.get(LoggerService);
    const location = this.injector.get(LocationStrategy);
        // Message variable to hold error message
    let errorMessage;
    // Variable to hold url location of error
    const url = location instanceof PathLocationStrategy ? location.path() : '';
    console.log('url: ', url);
    // check if error is a client error
    if (error instanceof Error) {
      // Client error message from error service
      errorMessage = errorService.getClientMessage(error);
      // Open dialog and display error message
      this.openDialog(errorMessage);
    }
    // get the stack trace, lets grab the last 10 stacks only
    StackTrace.fromError(error).then(stackframes => {
      const stackString = stackframes
        .splice(0, 20)
        .map(function(sf) {
          return sf.toString();
        })
        .join();
      /**
       * Function to log errors to api and mantis
       *
       * @param (errorMessage) error message passed to function
       * @param (url) url passed to function
       * @param (stackString) stackString passed to function
       */
      logger.createErrorLog(errorMessage, url, stackString).subscribe(
        result => {
          console.log('log filed');
        },
        (err: any) => console.log(err)
      );
    });
    return throwError(error);
  }
  /**
   * Function to open dialog to display error
   *
   * @param (data) error data to display
   */
  openDialog(data): void {
    const dialogRef = this.dialog.open(ErrorDialogComponent, {
      width: '60%',
      data: data
    });
    // Code to run after the dialog is closed
    dialogRef.afterClosed().subscribe(result => {
      // Redirect back to home (dashboard)?
    });
  }
}
</code>```

So is there a way to capture the 404 code and perform the redirect, but not invoke the global error handler?

答:
I was able to fix it with the help of Z.Bagley and the link he shared. I noticed that I was missing the next.handle() call. </p>

<p>Here is my revised interceptor code... </p>

```<code>if (error.status === 404) {
    const newRequest = request.clone();
    return next.handle(newRequest);
}
</code>```

Body:
I am handling errors with four pieces...an http interceptor for server returned errors, a global error handler that builds upon the built-in Angular error handler. an error service that logs the errors to a back end service for support purposes and a Material dialog component to display a friendly message to the end user.

There are some errors where we wish to capture the error status code and redirect to a component for a friendlier end user experience.

One example is a 404. We have a not found component. If the server error status is 404, I want to redirect to the not found component and not display the error dialog.

Here is my interceptor...

import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
import { MatDialog } from '@angular/material';
import * as StackTrace from 'stacktrace-js';
import { ErrorDialogComponent } from './error-dialog.component';
import { PathLocationStrategy } from '@angular/common';
import { ErrorService } from './error.service';
import { LoggerService } from './logger.service';
import { Router } from '@angular/router';

@Injectable()
/**
 * HttpErrorInterceptor to grab errors during http calls and log them
 *
 * @param (clientId) client id
 */
export class HttpErrorInterceptor implements HttpInterceptor {
  /**
   * constructor to grab errors during http calls and log them
   *
   * @param (dialog) MAT dialog to display to end user
   * @param (errorService) error service to grab error messages
   * @param (logger) logger service to post log errors to api and mantis
   */
  constructor(
    public dialog: MatDialog,
    private errorService: ErrorService,
    private logger: LoggerService,
    private router: Router
  ) {}
  /**
   * Interecept to grab request, deal with it and pass it along
   *
   * @param (request) http request
   * @param (next) send request to next http handler
   */
  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    // return the next statement
    return next.handle(request).pipe(
      // retry the call once
      retry(1),
      // catch the error
      catchError((error: HttpErrorResponse) => {
        if (error.status === 404) {
          console.log('error.status: ', error.status);
          // this.router.navigate(['']);
        } else {
          // Message variable to hold error message
          let errorMessage = '';
          // Variable to hold url location of error
          const url =
            location instanceof PathLocationStrategy ? location.path() : '';
          // server-side error
          errorMessage = this.errorService.getServerMessage(error);
          // get the stack trace, lets grab the last 10 stacks only
          StackTrace.fromError(error).then(stackframes => {
            const stackString = stackframes
              .splice(0, 20)
              .map(function(sf) {
                return sf.toString();
              })
              .join();
            /**
             * Function to log errors to api and mantis
             *
             * @param (errorMessage) error message passed to function
             * @param (url) url passed to function
             * @param (stackString) stackString passed to function
             */
            this.logger
              .createErrorLog(errorMessage, url, stackString)
              .subscribe(
                result => {
                  console.log('log filed: ', result);
                },
                (err: any) => console.log(err)
              );
          });
          // Check if error is undefined and open dialog with appropriate error info
          if (typeof errorMessage !== 'undefined') {
            this.openDialog(errorMessage);
          } else {
            this.openDialog('undefined');
          }
          // throw error
          return throwError(errorMessage);
        }
      })
    );
  }
  /**
   * Function to open dialog to display error
   *
   * @param (data) error data to display
   */
  openDialog(data): void {
    // Constant to hold and call dialog to display error
    const dialogRef = this.dialog.open(ErrorDialogComponent, {
      width: '60%',
      data: data
    });
    // Code to run after the dialog is closed
    dialogRef.afterClosed().subscribe(result => {
      // Redirect back to home (dashboard)?
    });
  }
}

As you can see, I have a simple if where I am checking the status code. I then have a navigate method call where I am trying to route to nothing because my router module has the not found component listed as the "nothing" route.

This is redirecting, but also displaying the error dialog message. I do not want that to display. The dialog just displays the error message to the end user and gives them ways to contact us.

Here is my Global Handler...

import { ErrorHandler, Injectable, Injector } from '@angular/core';
import {
  HttpErrorResponse,
  HttpHeaders,
  HttpClient
} from '@angular/common/http';
import { LocationStrategy, PathLocationStrategy } from '@angular/common';
import { throwError } from 'rxjs';
import * as StackTrace from 'stacktrace-js';
import { LoggerService } from '../core/logger.service';
import { ErrorService } from '../core/error.service';
import { MatDialog } from '@angular/material';
import { ErrorDialogComponent } from './error-dialog.component';
import { ConfigService } from '../app-config.service';

@Injectable({
  providedIn: 'root'
})
/**
 * GlobalErrorHandler to grab errors and log them
 */
export class GlobalErrorHandler implements ErrorHandler {
  /**
   * constructor to inject
   */
  constructor(private injector: Injector, public dialog: MatDialog) {}
  /**
   * Function to handle errors
   *
   * @param (error) error passed to function
   */
  handleError(error: Error) {
    console.log('error (global): ', error);
    const errorService = this.injector.get(ErrorService);
    const logger = this.injector.get(LoggerService);
    const location = this.injector.get(LocationStrategy);
        // Message variable to hold error message
    let errorMessage;
    // Variable to hold url location of error
    const url = location instanceof PathLocationStrategy ? location.path() : '';
    console.log('url: ', url);
    // check if error is a client error
    if (error instanceof Error) {
      // Client error message from error service
      errorMessage = errorService.getClientMessage(error);
      // Open dialog and display error message
      this.openDialog(errorMessage);
    }
    // get the stack trace, lets grab the last 10 stacks only
    StackTrace.fromError(error).then(stackframes => {
      const stackString = stackframes
        .splice(0, 20)
        .map(function(sf) {
          return sf.toString();
        })
        .join();
      /**
       * Function to log errors to api and mantis
       *
       * @param (errorMessage) error message passed to function
       * @param (url) url passed to function
       * @param (stackString) stackString passed to function
       */
      logger.createErrorLog(errorMessage, url, stackString).subscribe(
        result => {
          console.log('log filed');
        },
        (err: any) => console.log(err)
      );
    });
    return throwError(error);
  }
  /**
   * Function to open dialog to display error
   *
   * @param (data) error data to display
   */
  openDialog(data): void {
    const dialogRef = this.dialog.open(ErrorDialogComponent, {
      width: '60%',
      data: data
    });
    // Code to run after the dialog is closed
    dialogRef.afterClosed().subscribe(result => {
      // Redirect back to home (dashboard)?
    });
  }
}

So is there a way to capture the 404 code and perform the redirect, but not invoke the global error handler?

Body:
I was able to fix it with the help of Z.Bagley and the link he shared. I noticed that I was missing the next.handle() call.

Here is my revised interceptor code...

if (error.status === 404) {
    const newRequest = request.clone();
    return next.handle(newRequest);
}


问:
Noisy Signal in Data (FFT) - MATLAB
I am plotting some data I collected at 10000 Hz, I attached a snip of some of the data in the form of an FFT and time. I am getting a repeating frequency around 10Hz that seems to be pretty obviously some sort of noise from the system i am testing. The signal shows up in the time domain and also the frequency domain.

I am looking to use MATLAB to remove these spikes.

Has anyone dealt with a similar issue and can provide any advice.

答:
To filter out specific frequency components of a signal, you would normally use either a notch filter or a comb filter, for which MATLAB already has some commands in the DSP System Toolbox:

https://www.mathworks.com/help/dsp/ref/iirnotch.html

https://www.mathworks.com/help/dsp/ref/fdesign.comb.html

Alternatively, if you have the Signal Processing Toolbox, you can use the band-stop Butterworth filter to remove individual frequency components (ranges) using

https://www.mathworks.com/help/signal/ref/butter.html

Title: Noisy Signal in Data (FFT) - MATLAB


问:
Overriding Dart methods with Generics arguments
I have this case where I am extending from a super class with methods being typed using Generics as the following:

Models

abstract class SuperClass {

   //.....
}

class SubClass extends SuperClass {
  int a;
  int b;
  String c;
  //....
}
```

<h2>Controllers</h2>

<pre class="lang-dart prettyprint-override"><code>abstract class A {
   T getDoc<T extends SuperClass>(T doc);
}

class B extends A {
   T getDoc<T extends SubClass>(T doc) {     //<================ Error
       //....
    }
}

</code>```

Basically class B will only deal with a SubClass model and any class that extends it. Extending SuperClass is not enough. It's a way to enforce the type usage. I could add a helper function that will check the type for each method within class B (doc is SubClass) but seems like a lot repetition.

But the above architecture fails when overriding the method getDoc in class B saying that it isn't a valid override although SubClass is a SuperClass. How can I achieve something like this? Or is there a better way of doing it? Appreciate any pointers :)

答:
I have finally a found a way :)

So I wanted the class B's methods to accept exclusively types that extend SubClass, but class A method's signature expects parameters extending class SuperClass.

To go about this I did the following:

Models

abstract class SuperClass {

   //.....
}

class SubClass extends SuperClass {
  int a;
  int b;
  String c;
  //....
}
```

<h2>Controllers</h2>

<pre class="lang-dart prettyprint-override"><code>abstract class A<K extends SuperClass> {
   T getDoc<T extends K>(T doc);
}

class B extends A<SubClass> {
   T getDoc<T extends SubClass>(T doc) {
          //.......
    }
}

</code>```

Body:
I have this case where I am extending from a super class with methods being typed using Generics as the following:

Models

abstract class SuperClass {

   //.....
}

class SubClass extends SuperClass {
  int a;
  int b;
  String c;
  //....
}

Controllers

abstract class A {
   T getDoc<T extends SuperClass>(T doc);
}

class B extends A {
   T getDoc<T extends SubClass>(T doc) {     //<================ Error
       //....
    }
}

Basically class B will only deal with a SubClass model and any class that extends it. Extending SuperClass is not enough. It's a way to enforce the type usage. I could add a helper function that will check the type for each method within class B (doc is SubClass) but seems like a lot repetition.

But the above architecture fails when overriding the method getDoc in class B saying that it isn't a valid override although SubClass is a SuperClass. How can I achieve something like this? Or is there a better way of doing it? Appreciate any pointers :)

Body:
I have finally a found a way :)

So I wanted the class B's methods to accept exclusively types that extend SubClass, but class A method's signature expects parameters extending class SuperClass.

To go about this I did the following:

Models

abstract class SuperClass {

   //.....
}

class SubClass extends SuperClass {
  int a;
  int b;
  String c;
  //....
}

Controllers

abstract class A<K extends SuperClass> {
   T getDoc<T extends K>(T doc);
}

class B extends A<SubClass> {
   T getDoc<T extends SubClass>(T doc) {
          //.......
    }
}


问:
Hidden friend templates in class template

The original working code

I have a class template with two template parameters and an optimized operator== when the two types are the same and one another condition is satisfied. My original code is as follows (for demonstration purposes I make the generic comparison return false and the one where T1 == T2 return true):

template<typename T1, typename T2>
struct my_class
{
    // A few hundred LOCs
};

template<typename U1, typename U2>
bool operator==(my_class<U1, U2> const& lhs, my_class<U1, U2> const& rhs)
{
    return false;
}

template<typename U>
auto operator==(my_class const& lhs, my_class const& rhs)
    -> std::enable_if_t<some_condition, bool>
{
    return true;
}
```

<p>The idea is that the first overload of <code>operator==</code> is the default, and when both <code>U1</code> and <code>U2</code> are the same type and <code>some_condition</code> is satisfied the second overload is valid and picked as a better match.</p>

<h3>The problem</h3>

<p>I recently started implementing more and more operators in my generic libraries as hidden friends to avoid some unwanted implicit conversions and to reduce the overload set the compiler has to choose from at namespace scope.</p>

<p>I first tried the most obvious approach to friends, which is to move the definitions as is in the class template and to prefix them with <code>friend</code>:</p>

<pre class="lang-cpp prettyprint-override"><code>template<typename T1, typename T2>
struct my_class
{
    // A few hundred LOCs

    template<typename U1, typename U2>
    friend bool operator==(my_class<U1, U2> const& lhs, my_class<U1, U2> const& rhs)
    {
        return false;
    }

    template<typename U>
    friend auto operator==(my_class<U, U> const& lhs, my_class<U, U> const& rhs)
        -> std::enable_if_t<some_condition, bool>
    {
        return true;
    }
};
</code>```

Much not to my surprise this didn't work and I got redefinition errors. The reason why is explained - along with a standard quote - in this answer.

An attempt

We are always comparing my_class with matching template parameters, so I figured that I could get rid of the inner template<typename U1, typename U2> in the first definition, however it is trickier in the second one since the single template parameter was used to create a more specialized overload of operator==. Another solution would be to put that overload in a specialization of my_class<T, T> but since the class is big I didn't feel like duplicating its contents since pretty much everything else is the same. I could probably introduce another layer of indirection for the common code but I already have a hefty amount of indirection.

Failing that I tried to fallback to good old SFINAE to make sure that T1 and T2 are the same:

template<typename T1, typename T2>
struct my_class
{
    // A few hundred LOCs

    friend auto operator==(my_class const& lhs, my_class const& rhs)
        -> bool
    {
        return false;
    }

    friend auto operator==(my_class const& lhs, my_class const& rhs)
        -> std::enable_if_t<std::is_same<T1, T2>::value && some_condition, bool>
    {
        return true;
    }
};
```

<p>For some reason I don't claim to fully understand the second <code>operator==</code> above is actually ill-formed, but we can get around that by adding back some additional defaulted template parameters into the mix:</p>

<pre class="lang-cpp prettyprint-override"><code>template<typename T1, typename T2>
struct my_class
{
    // A few hundred LOCs

    friend auto operator==(my_class const& lhs, my_class const& rhs)
        -> bool
    {
        return false;
    }

    template<typename U1=T1, typename U2=T2>
    friend auto operator==(my_class const& lhs, my_class const& rhs)
        -> std::enable_if_t<std::is_same<U1, U2>::value && some_condition, bool>
    {
        return true;
    }
};
</code>```

This compiles as expected, but comparing two instances of my_class with matching T1 and T2 now returns false because the second overload of operator== is less specialized than the first one. An educated guess tells me that the new template layer is the reason, so I added back template parameters to the first overload of operator== and also an SFINAE condition which is a negation of the other one to make sure that the overload wouldn't be ambiguous with matching T1 and T2:

template<typename T1, typename T2>
struct my_class
{
    // A few hundred LOCs

    template<typename U1=T1, typename U2=T2>
    friend auto operator==(my_class const& lhs, my_class const& rhs)
        -> std::enable_if_t<not(std::is_same<U1, U2>::value && some_condition), bool>
    {
        return false;
    }

    template<typename U1=T1, typename U2=T2>
    friend auto operator==(my_class const& lhs, my_class const& rhs)
        -> std::enable_if_t<std::is_same<U1, U2>::value && some_condition, bool>
    {
        return true;
    }
};
```

This finally gives the intended result while also providing the benefits of hidden friends, but the cost is a bit high in term of readability and maintainability.

Back to the question I originally meant to ask

I tried to explain my problem and rough solution and how I got to it above. My question is: is there a better way to achieve the same result (hidden friends with my code) without having to dive into all the template issues I highlighted above? Can I have such hidden friends while relying on the built-in partial ordering of function templates instead of replacing it with another layer of SFINAE as I did?

答:
Would you accept this?</p>

```<code>template<typename T1, typename T2>
struct my_class
{
    friend bool operator==(my_class const& lhs, my_class const& rhs)
    {
        if constexpr (std::is_same_v<T1, T2>) {
            return condition;
        } else {
            return false;
        }
    }
};
</code>```

Body:
The original working code

I have a class template with two template parameters and an optimized operator== when the two types are the same and one another condition is satisfied. My original code is as follows (for demonstration purposes I make the generic comparison return false and the one where T1 == T2 return true):

template<typename T1, typename T2>
struct my_class
{
    // A few hundred LOCs
};

template<typename U1, typename U2>
bool operator==(my_class<U1, U2> const& lhs, my_class<U1, U2> const& rhs)
{
    return false;
}

template<typename U>
auto operator==(my_class const& lhs, my_class const& rhs)
    -> std::enable_if_t<some_condition, bool>
{
    return true;
}

The idea is that the first overload of operator== is the default, and when both U1 and U2 are the same type and some_condition is satisfied the second overload is valid and picked as a better match.

The problem

I recently started implementing more and more operators in my generic libraries as hidden friends to avoid some unwanted implicit conversions and to reduce the overload set the compiler has to choose from at namespace scope.

I first tried the most obvious approach to friends, which is to move the definitions as is in the class template and to prefix them with friend:

template<typename T1, typename T2>
struct my_class
{
    // A few hundred LOCs

    template<typename U1, typename U2>
    friend bool operator==(my_class<U1, U2> const& lhs, my_class<U1, U2> const& rhs)
    {
        return false;
    }

    template<typename U>
    friend auto operator==(my_class const& lhs, my_class const& rhs)
        -> std::enable_if_t<some_condition, bool>
    {
        return true;
    }
};

Much not to my surprise this didn't work and I got redefinition errors. The reason why is explained - along with a standard quote - in this answer.

An attempt

We are always comparing my_class with matching template parameters, so I figured that I could get rid of the inner template<typename U1, typename U2> in the first definition, however it is trickier in the second one since the single template parameter was used to create a more specialized overload of operator==. Another solution would be to put that overload in a specialization of my_class<T, T> but since the class is big I didn't feel like duplicating its contents since pretty much everything else is the same. I could probably introduce another layer of indirection for the common code but I already have a hefty amount of indirection.

Failing that I tried to fallback to good old SFINAE to make sure that T1 and T2 are the same:

template<typename T1, typename T2>
struct my_class
{
    // A few hundred LOCs

    friend auto operator==(my_class const& lhs, my_class const& rhs)
        -> bool
    {
        return false;
    }

    friend auto operator==(my_class const& lhs, my_class const& rhs)
        -> std::enable_if_t<std::is_same<T1, T2>::value && some_condition, bool>
    {
        return true;
    }
};

For some reason I don't claim to fully understand the second operator== above is actually ill-formed, but we can get around that by adding back some additional defaulted template parameters into the mix:

template<typename T1, typename T2>
struct my_class
{
    // A few hundred LOCs

    friend auto operator==(my_class const& lhs, my_class const& rhs)
        -> bool
    {
        return false;
    }

    template<typename U1=T1, typename U2=T2>
    friend auto operator==(my_class const& lhs, my_class const& rhs)
        -> std::enable_if_t<std::is_same<U1, U2>::value && some_condition, bool>
    {
        return true;
    }
};

This compiles as expected, but comparing two instances of my_class with matching T1 and T2 now returns false because the second overload of operator== is less specialized than the first one. An educated guess tells me that the new template layer is the reason, so I added back template parameters to the first overload of operator== and also an SFINAE condition which is a negation of the other one to make sure that the overload wouldn't be ambiguous with matching T1 and T2:

template<typename T1, typename T2>
struct my_class
{
    // A few hundred LOCs

    template<typename U1=T1, typename U2=T2>
    friend auto operator==(my_class const& lhs, my_class const& rhs)
        -> std::enable_if_t<not(std::is_same<U1, U2>::value && some_condition), bool>
    {
        return false;
    }

    template<typename U1=T1, typename U2=T2>
    friend auto operator==(my_class const& lhs, my_class const& rhs)
        -> std::enable_if_t<std::is_same<U1, U2>::value && some_condition, bool>
    {
        return true;
    }
};

This finally gives the intended result while also providing the benefits of hidden friends, but the cost is a bit high in term of readability and maintainability.

Back to the question I originally meant to ask

I tried to explain my problem and rough solution and how I got to it above. My question is: is there a better way to achieve the same result (hidden friends with my code) without having to dive into all the template issues I highlighted above? Can I have such hidden friends while relying on the built-in partial ordering of function templates instead of replacing it with another layer of SFINAE as I did?

Body:
Would you accept this?

template<typename T1, typename T2>
struct my_class
{
    friend bool operator==(my_class const& lhs, my_class const& rhs)
    {
        if constexpr (std::is_same_v<T1, T2>) {
            return condition;
        } else {
            return false;
        }
    }
};


问:
iterating through the rows of a table using tableadapters in vb.net
i have a problem. I have database with a tableadpater. i want to get the userid with this tableadapter.

```<code> Dim dsGN As New ForumTableAdapters.Message2TableAdapter

    Dim dtBetrieb As Data.DataTable = dsGN.GetUserIdFromThisMessage(ConversationID)

    For Each objRow As dsGN.Message2Row In dtBetrieb.Rows

        mystring = objRow.UserId.ToString
    Next
</code>```

i get the error "dsGN.Message2Row is not defined"

The Name ob my table in the database is "Message"
i hope that somebody can help me.

答:
You have to do this :

```<code>GridView.DataSource = yourAdapter.GetUserID(ID);
GridView.DataBind();
</code>```

Then make a tableadapter named:GetUserID where you select from your tables passing the ID like: @ID;

Hope this helped!
You can read more about this here:

http://msdn.microsoft.com/en-us/library/aa581776.aspx

Body:
i have a problem. I have database with a tableadpater. i want to get the userid with this tableadapter.

 Dim dsGN As New ForumTableAdapters.Message2TableAdapter

    Dim dtBetrieb As Data.DataTable = dsGN.GetUserIdFromThisMessage(ConversationID)

    For Each objRow As dsGN.Message2Row In dtBetrieb.Rows

        mystring = objRow.UserId.ToString
    Next

i get the error "dsGN.Message2Row is not defined"

The Name ob my table in the database is "Message"
i hope that somebody can help me.

Body:
You have to do this :

GridView.DataSource = yourAdapter.GetUserID(ID);
GridView.DataBind();

Then make a tableadapter named:GetUserID where you select from your tables passing the ID like: @ID;

Hope this helped!
You can read more about this here:

http://msdn.microsoft.com/en-us/library/aa581776.aspx


问:
Invalid SQL statement in UpdateCursor using ArcPy
I am trying to determine qualitative distances (Very Close, Close, and Far) of different sized cities (Small, Medium, Large) using an Update Cursor and keep getting this error message:

```<code>Traceback (most recent call last):
  File "<string>", line 34, in <module>
RuntimeError: An invalid SQL statement was used. [SELECT NEAR_DIST, MedCities, OBJECTID_1 FROM popPlaces WHERE EST_POP>500ANDEST_POP<=10000]
</code>```

The code I am using is as follows:

```<code>#Task 7: Provide a qualitative classification of distance to hospitals for different size cities
#Create qualitative fields
arcpy.management.AddFields('popPlaces', [['SmallCities','TEXT'],['MedCities','TEXT'],['LargeCities','TEXT']])
#Assign qualitiative city size variabes to new fields
small=popCol+"<="+"500"
medium=popCol+">"+"500"+ "AND" +popCol+"<="+"10000"
large=popCol+">10000"
print('small', 'medium', 'large')

#Create an Update Cursor separately for the different size cities that assigns a qualitative class to each record based on distance to hospital.
#For SmallCities
with arcpy.da.UpdateCursor(popPlaces,(Dist,"SmallCities"),small) as cursor:
 for i in cursor:
  if i[0] <= 1000:
   i[1] = "Very Close"
  elif i[0] > 1000 and i[0] < 10000:
   i[1] = 'Close'
  else:
   i[1] = 'Far'
  cursor.updateRow(i)

#For LargeCities
with arcpy.da.UpdateCursor(popPlaces,(Dist,"LargeCities"),large) as cursor:
 for i in cursor:
  if i[0] <= 1000:
   i[1] = "Very Close"
  elif i[0] > 1000 and i[0] < 10000:
   i[1] = 'Close'
  else:
   i[1] = 'Far'
  cursor.updateRow(i)

#For MedCities
with arcpy.da.UpdateCursor(popPlaces,(Dist,"MedCities"),medium) as cursor:
 for i in cursor:
  if i[0] <= 1000:
   i[1] = "Very Close"
  elif i[0] > 1000 and i[0] < 10000:
   i[1] = 'Close'
  else:
   i[1] = 'Far'
  cursor.updateRow(i)
</code>```

The Cursor works for Small and Large Cities but not Medium cities and I'm unsure where I've gone wrong. Thank you for your help!

答:
You're missing spaces around AND in

```<code>EST_POP>500ANDEST_POP<=10000
</code>```

Change

```<code>medium=popCol+">"+"500"+ "AND" +popCol+"<="+"10000"
</code>```

to

```<code>medium=popCol+">"+"500"+ " AND " +popCol+"<="+"10000"
</code>```

Body:
I am trying to determine qualitative distances (Very Close, Close, and Far) of different sized cities (Small, Medium, Large) using an Update Cursor and keep getting this error message:

Traceback (most recent call last):
  File "<string>", line 34, in <module>
RuntimeError: An invalid SQL statement was used. [SELECT NEAR_DIST, MedCities, OBJECTID_1 FROM popPlaces WHERE EST_POP>500ANDEST_POP<=10000]

The code I am using is as follows:

#Task 7: Provide a qualitative classification of distance to hospitals for different size cities
#Create qualitative fields
arcpy.management.AddFields('popPlaces', [['SmallCities','TEXT'],['MedCities','TEXT'],['LargeCities','TEXT']])
#Assign qualitiative city size variabes to new fields
small=popCol+"<="+"500"
medium=popCol+">"+"500"+ "AND" +popCol+"<="+"10000"
large=popCol+">10000"
print('small', 'medium', 'large')

#Create an Update Cursor separately for the different size cities that assigns a qualitative class to each record based on distance to hospital.
#For SmallCities
with arcpy.da.UpdateCursor(popPlaces,(Dist,"SmallCities"),small) as cursor:
 for i in cursor:
  if i[0] <= 1000:
   i[1] = "Very Close"
  elif i[0] > 1000 and i[0] < 10000:
   i[1] = 'Close'
  else:
   i[1] = 'Far'
  cursor.updateRow(i)

#For LargeCities
with arcpy.da.UpdateCursor(popPlaces,(Dist,"LargeCities"),large) as cursor:
 for i in cursor:
  if i[0] <= 1000:
   i[1] = "Very Close"
  elif i[0] > 1000 and i[0] < 10000:
   i[1] = 'Close'
  else:
   i[1] = 'Far'
  cursor.updateRow(i)

#For MedCities
with arcpy.da.UpdateCursor(popPlaces,(Dist,"MedCities"),medium) as cursor:
 for i in cursor:
  if i[0] <= 1000:
   i[1] = "Very Close"
  elif i[0] > 1000 and i[0] < 10000:
   i[1] = 'Close'
  else:
   i[1] = 'Far'
  cursor.updateRow(i)

The Cursor works for Small and Large Cities but not Medium cities and I'm unsure where I've gone wrong. Thank you for your help!

Body:
You're missing spaces around AND in

EST_POP>500ANDEST_POP<=10000

Change

medium=popCol+">"+"500"+ "AND" +popCol+"<="+"10000"

to

medium=popCol+">"+"500"+ " AND " +popCol+"<="+"10000"


问:
cypress semantic-ui-react menu tests - not getting content of menu options
I am writing some tests here on a component that uses semantic-react-ui using cypress js to test with.

Here is the div containing the elements I wish to test on:

```<code><div data-testid="images-count" class="customize-row images-count">
   <h3 data-testid="option-name-8" class="option-name">Font Size</h3>
   <div data-testid="font-select" role="listbox" aria-expanded="true" class="ui active visible selection dropdown option-input images-select" tabindex="0">
      <div class="text" role="alert" aria-live="polite">Medium</div>
      <i aria-hidden="true" class="dropdown icon"></i>
      <div class="menu transition visible">
         <div role="option" aria-checked="false" aria-selected="false" class="item" style="pointer-events: all;"><span class="text">Small</span></div>
         <div role="option" aria-checked="true" aria-selected="true" class="active selected item" style="pointer-events: all;"><span class="text">Medium</span></div>
         <div role="option" aria-checked="false" aria-selected="false" class="item" style="pointer-events: all;"><span class="text">Large</span></div>
         <div role="option" aria-checked="false" aria-selected="false" class="item" style="pointer-events: all;"><span class="text">Extra Large</span></div>
      </div>
   </div>
</div>
</code>```

Here is a small test that I have done so far for elements within that div:

```<code>    cy.get("[data-testid=images-count]").within($result => {
       cy.findByRole("alert").should("have.text", "Medium");
       cy.get(".icon").should("be.visible");
       cy.get(".menu").should("not.be.visible");
       cy.get("[data-testid=font-select]").click();
       cy.get(".menu").should("be.visible");
    });
</code>```

I attempted to get the options from the menu into an array, then validate them against another array:

```<code>cy.get('.menu').then(options => {
  const actual = [...options].map(o => o.value)
  expect(actual).to.deep.eq(['Small', 'Medium', 'Large', 'Extra Large'])
})
</code>```

However this returns the list of divs and not the actual test contant I am looking for. Any ideas?

答:
You can't just do options.map without the array and spread op? I think the way you're doing it would just insert an array into another array...

If its an issue with options coming back as undefined or empty, just put in an

```<code>const actual = options && options.length > 0 ? options.map(o => o.value) : []
</code>```

Body:
I am writing some tests here on a component that uses semantic-react-ui using cypress js to test with.

Here is the div containing the elements I wish to test on:

Font Size

Medium

Small

Medium

Large

Extra Large

Here is a small test that I have done so far for elements within that div:

    cy.get("[data-testid=images-count]").within($result => {
       cy.findByRole("alert").should("have.text", "Medium");
       cy.get(".icon").should("be.visible");
       cy.get(".menu").should("not.be.visible");
       cy.get("[data-testid=font-select]").click();
       cy.get(".menu").should("be.visible");
    });

I attempted to get the options from the menu into an array, then validate them against another array:

cy.get('.menu').then(options => {
  const actual = [...options].map(o => o.value)
  expect(actual).to.deep.eq(['Small', 'Medium', 'Large', 'Extra Large'])
})

However this returns the list of divs and not the actual test contant I am looking for. Any ideas?

Body:
You can't just do options.map without the array and spread op? I think the way you're doing it would just insert an array into another array...

If its an issue with options coming back as undefined or empty, just put in an

const actual = options && options.length > 0 ? options.map(o => o.value) : []