问:
Anything wrong with the loop - getting Maximum execution time of 30 seconds exceeded?
Just want to check if am doing something wrong here coz for small dataset the function works fine but a little more records and i get max executuion time error;

```<code>function getValue($products, $storeNum, $productKey) {
    foreach($products as $row)
    {
      if((int)$row->name === (int)$storeNum && (int)$row->product_key === (int)$productKey)
      {
        return $row->value;
      }
    }
    return 0;
}
</code>```

Input $products array is like this:

```<code>Array
(
    [0] => stdClass Object
        (
            [value] => 0
            [name] => 3195
            [product_key] => 13
        )

)
</code>```

PS: Function getvalue() is being called in another loop that creates the matrix of 400 (stores as Y-axis) by 50 (product names X-axis)

答:
If the $products array needs to maintain that specific format, here's the most efficient method to retrieve the product value from millions of records:

```<code>function getValue($products, $name, $productKey) {
    return ($search = explode('"name":' . $name . ',"product_key":' . $productKey, json_encode($products))) && (next($search) !== false) ? rtrim(substr($search[0], strrpos($search[0], '":') + 2), ',') : false;
}
</code>```

Example product array:

```<code>$products = array(
    (object) array(
        'value' => 0,
        'name' => 13,
        'product_key' => 3195
    ),
    (object) array(
        'value' => 20,
        'name' => 14,
        'product_key' => 3196
    ),
    (object) array(
        'value' => 40,
        'name' => 15,
        'product_key' => 3197
    )
);
</code>```

Retrieving a value with product name and key (returns false if no value is found):

```<code>$productValue = getValue($products, 14, 3196);
</code>```

Body:
Just want to check if am doing something wrong here coz for small dataset the function works fine but a little more records and i get max executuion time error;

function getValue($products, $storeNum, $productKey) {
    foreach($products as $row)
    {
      if((int)$row->name === (int)$storeNum && (int)$row->product_key === (int)$productKey)
      {
        return $row->value;
      }
    }
    return 0;
}

Input $products array is like this:

Array
(
    [0] => stdClass Object
        (
            [value] => 0
            [name] => 3195
            [product_key] => 13
        )

)

PS: Function getvalue() is being called in another loop that creates the matrix of 400 (stores as Y-axis) by 50 (product names X-axis)

Body:
If the $products array needs to maintain that specific format, here's the most efficient method to retrieve the product value from millions of records:

function getValue($products, $name, $productKey) {
    return ($search = explode('"name":' . $name . ',"product_key":' . $productKey, json_encode($products))) && (next($search) !== false) ? rtrim(substr($search[0], strrpos($search[0], '":') + 2), ',') : false;
}

Example product array:

$products = array(
    (object) array(
        'value' => 0,
        'name' => 13,
        'product_key' => 3195
    ),
    (object) array(
        'value' => 20,
        'name' => 14,
        'product_key' => 3196
    ),
    (object) array(
        'value' => 40,
        'name' => 15,
        'product_key' => 3197
    )
);

Retrieving a value with product name and key (returns false if no value is found):

$productValue = getValue($products, 14, 3196);


来源: stackexchange

问:
material-ui cards dont have CSS on load

I have cards created using material-UI.  The problem is when the page loads or re-loads, the cards look like the ones on the left.  There does not appear to be any css on it.  After a few seconds it looks like it should look.  Is this because of something i am doing on my end or is it just the way just Material-UI works

```<code>import React, { Component } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardActionArea from '@material-ui/core/CardActionArea';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';

class ImgMediaCard extends Component {
  constructor(props){
    super(props)
  }
  render(){

  return (
    <div className="Cards-div">
    <Card className="Cards">
      <CardActionArea>
        <CardMedia
          component="img"
          alt={this.props.imgAlt}
          height="300"
          image={this.props.imgLink}
          title={this.props.imgTitle}
        />
        <CardContent>
          <Typography gutterBottom variant="h5" component="h2">
            {this.props.title}
          </Typography>
          <Typography variant="body2" color="textSecondary" component="p">
            {this.props.text}
            {this.props.technologies}
          </Typography>
        </CardContent>
      </CardActionArea>
      <CardActions>
        <Button size="small" color="primary">
          Visit
        </Button>

      </CardActions>
    </Card>
  </div>
)};
}

export default ImgMediaCard;
</code>```

Github repo: https://github.com/Kohdz/port

答:
Alright after wrestling with this thing for a bit, I finally got it. The key seems to be in /pages/_document.js. There's 2 things that I had to do, bring back _document.js and have it handle the getInitialProps() as well as add the flush from styled-jsx.

import React from 'react';
import Document, { Head, Main, NextScript } from 'next/document';
import { ServerStyleSheets } from '@material-ui/styles';
import flush from 'styled-jsx/server';
import { createMuiTheme } from '@material-ui/core/styles';
import red from '@material-ui/core/colors/red';

const theme = createMuiTheme({
  palette: {
    primary: {
      main: '#556cd6',
    },
    secondary: {
      main: '#19857b',
    },
    error: {
      main: red.A400,
    },
    background: {
      default: '#fff',
    },
  },
});

class MyDocument extends Document {

    render() {
        return (

                    <meta charSet="utf-8" />
                    <meta
                        name="viewport"
                        content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no"
                    />
                    <meta name="theme-color" content={theme.palette.primary.main} />
                    <link
                        rel="stylesheet"
                        href="https://fonts.googleapis.com/css?family=Roboto:300,400,500&display=swap"
                    />

                    <NextScript />

        );
    }
}

MyDocument.getInitialProps = async ctx => {

    const sheets = new ServerStyleSheets();
    const originalRenderPage = ctx.renderPage;

    ctx.renderPage = () =>
        originalRenderPage({
            enhanceApp: App => props => sheets.collect(<App {...props} />),
        });

    const initialProps = await Document.getInitialProps(ctx);

    return {
        ...initialProps,
        styles: (
            <React.Fragment>
                {sheets.getStyleElement()}
                {flush() || null}
            </React.Fragment>
        ),
    };
};

export default MyDocument;```

Material UI has an example here.
This was also an interesting thread

ContentLicense: CC BY-SA 4.0

Title: material-ui cards dont have CSS on load

Body:
I have cards created using material-UI.  The problem is when the page loads or re-loads, the cards look like the ones on the left.  There does not appear to be any css on it.  After a few seconds it looks like it should look.  Is this because of something i am doing on my end or is it just the way just Material-UI works

import React, { Component } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardActionArea from '@material-ui/core/CardActionArea';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';

class ImgMediaCard extends Component {
  constructor(props){
    super(props)
  }
  render(){

  return (

    <Card className="Cards">
      <CardActionArea>
        <CardMedia
          component="img"
          alt={this.props.imgAlt}
          height="300"
          image={this.props.imgLink}
          title={this.props.imgTitle}
        />
        <CardContent>
          <Typography gutterBottom variant="h5" component="h2">
            {this.props.title}
          </Typography>
          <Typography variant="body2" color="textSecondary" component="p">
            {this.props.text}
            {this.props.technologies}
          </Typography>
        </CardContent>
      </CardActionArea>
      <CardActions>
        <Button size="small" color="primary">
          Visit
        </Button>

      </CardActions>
    </Card>

)};
}

export default ImgMediaCard;

Github repo: https://github.com/Kohdz/port

Body:
Alright after wrestling with this thing for a bit, I finally got it. The key seems to be in /pages/_document.js. There's 2 things that I had to do, bring back _document.js and have it handle the getInitialProps() as well as add the flush from styled-jsx.

import React from 'react';
import Document, { Head, Main, NextScript } from 'next/document';
import { ServerStyleSheets } from '@material-ui/styles';
import flush from 'styled-jsx/server';
import { createMuiTheme } from '@material-ui/core/styles';
import red from '@material-ui/core/colors/red';

const theme = createMuiTheme({
  palette: {
    primary: {
      main: '#556cd6',
    },
    secondary: {
      main: '#19857b',
    },
    error: {
      main: red.A400,
    },
    background: {
      default: '#fff',
    },
  },
});

class MyDocument extends Document {

    render() {
        return (
            <html lang="en" dir="ltr">
                <Head>
                    <meta charSet="utf-8" />
                    <meta
                        name="viewport"
                        content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no"
                    />
                    <meta name="theme-color" content={theme.palette.primary.main} />
                    <link
                        rel="stylesheet"
                        href="https://fonts.googleapis.com/css?family=Roboto:300,400,500&display=swap"
                    />
                </Head>
                <body>
                    <Main />
                    <NextScript />
                </body>
            </html>
        );
    }
}

MyDocument.getInitialProps = async ctx => {

    const sheets = new ServerStyleSheets();
    const originalRenderPage = ctx.renderPage;

    ctx.renderPage = () =>
        originalRenderPage({
            enhanceApp: App => props => sheets.collect(<App {...props} />),
        });

    const initialProps = await Document.getInitialProps(ctx);

    return {
        ...initialProps,
        styles: (
            <React.Fragment>
                {sheets.getStyleElement()}
                {flush() || null}
            </React.Fragment>
        ),
    };
};

export default MyDocument;

Material UI has an example here.
This was also an interesting thread


问:
sap.m.PlanningCalendar - How to display hour in 24-hour format?
I am using a planning calendar where I am displaying the appointments. I am showing the calendar from 7AM to 5PM. But I want the Hour format to be in 24-hour format, like after 12PM it should be 13, 14, 15.. likewise.</p>

答:
<s>It seems like hour format for planning calendar depends on browser locale. For example for me (Europe, Poland) hours are in 24hours format.</s>

It is related to Launchpad settings:

You can set it default in transaction SU01 tab defaults for selected user or You could do massive change in SU10. If You need more information You could find it in 2404186 SAP Note launchpad.support.sap.com/#/notes/0002504186


问:
Clear WooCommerce checkout pre-filled shipping fields values
I need to clear shipping fields from a wordpress customer profile after they have placed an order

The shop is set up to sell giftbaskets and many returning customers will want to send a giftbasket to a different shipping address each time they return. They will use the same billing info that is in their profile

```<code>add_filter('woocommerce_checkout_fields','custom_override_checkout_fields' );

function custom_override_checkout_fields( $fields ) {

  $fields['shipping']['shipping_first_name'] = '';
  $fields['shipping']['shipping_last_name'] = '';
  $fields['shipping']['shipping_company'] = '';
  $fields['shipping']['shipping_address_1'] = '';
  $fields['shipping']['shipping_address_2'] = '';
  $fields['shipping']['shipping_city'] = '';
  $fields['shipping']['shipping_postcode'] = '';
  $fields['shipping']['shipping_country'] = '';
  $fields['shipping']['shipping_state'] = '';

  return $fields;
}
</code>```

This clears the fields and it also clears the field labels. Can I edit the existing to to clear just the fields and leave the labels visible above each field.

Thanks alot for looking

答:
You are not using the right filter hook… The following will clear pre-filled shipping fields values:

```<code>add_filter( 'woocommerce_checkout_get_value', 'clear_shipping_fields_values', 5, 2 );
function clear_shipping_fields_values( $value, $input ) {
    $keys = ['first_name','last_name','company','address_1','address_2','city','postcode','country','state'];
    $key  = str_replace('shipping_', '', $input);
    if( in_array($key, $keys) && is_checkout() ) {
        $value = '';
    }
    return $value;
}
</code>```

Code goes in functions.php file of your active child theme (or active theme). Tested and work.

Body:
I need to clear shipping fields from a wordpress customer profile after they have placed an order

The shop is set up to sell giftbaskets and many returning customers will want to send a giftbasket to a different shipping address each time they return. They will use the same billing info that is in their profile

add_filter('woocommerce_checkout_fields','custom_override_checkout_fields' );

function custom_override_checkout_fields( $fields ) {

  $fields['shipping']['shipping_first_name'] = '';
  $fields['shipping']['shipping_last_name'] = '';
  $fields['shipping']['shipping_company'] = '';
  $fields['shipping']['shipping_address_1'] = '';
  $fields['shipping']['shipping_address_2'] = '';
  $fields['shipping']['shipping_city'] = '';
  $fields['shipping']['shipping_postcode'] = '';
  $fields['shipping']['shipping_country'] = '';
  $fields['shipping']['shipping_state'] = '';

  return $fields;
}

This clears the fields and it also clears the field labels. Can I edit the existing to to clear just the fields and leave the labels visible above each field.

Thanks alot for looking

Body:
You are not using the right filter hook… The following will clear pre-filled shipping fields values:

add_filter( 'woocommerce_checkout_get_value', 'clear_shipping_fields_values', 5, 2 );
function clear_shipping_fields_values( $value, $input ) {
    $keys = ['first_name','last_name','company','address_1','address_2','city','postcode','country','state'];
    $key  = str_replace('shipping_', '', $input);
    if( in_array($key, $keys) && is_checkout() ) {
        $value = '';
    }
    return $value;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and work.


问:
MouseOver Flicking
Why is mouse over flickering with these set events?

I have tried the following code

```<code>const headerTags1 = document.querySelector('h1');
headerTags1.addEventListener('mouseenter', function(event){
event.target.style.display = "none";
})
console.log(headerTags1)

const headerTags2 = document.querySelector('h1');
headerTags2.addEventListener('mouseleave', function(event){
event.target.style.display = "initial";
})
console.log(headerTags2)
</code>```

答:
This happens because as soon as you hover over an h1 it hides, and because it's now hidden, you aren't mousing over it anymore and mouseleave fires, so it's then shown, but then you are mousing over it, so it hides, and so on.

const headerTags1 = document.querySelector('h1');
headerTags1.addEventListener('mouseenter', function(event){
event.target.style.display = "none";
})
console.log(headerTags1)

const headerTags2 = document.querySelector('h1');
headerTags2.addEventListener('mouseleave', function(event){
event.target.style.display = "initial";
})
console.log(headerTags2)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Now you see me...</h1></code>```

This, of course, is not a good design decision in the first place. What are you really trying to accomplish?

EDIT:

Just want to have the button disappear and reappear when it's hovered
  over or better yet just change colors when it's hovered over...

Then the better approach would be to just use the CSS :hover pseudo-class to modify the element' style only while it's being hovered.

<!doctype html>

  <title>Page Title Here</title>

Now you see me...

  <button>Hover Over Me</button>

```

Title: MouseOver Flicking

Body:
Why is mouse over flickering with these set events?

I have tried the following code

const headerTags1 = document.querySelector('h1');
headerTags1.addEventListener('mouseenter', function(event){
event.target.style.display = "none";
})
console.log(headerTags1)

const headerTags2 = document.querySelector('h1');
headerTags2.addEventListener('mouseleave', function(event){
event.target.style.display = "initial";
})
console.log(headerTags2)

Body:
This happens because as soon as you hover over an h1 it hides, and because it's now hidden, you aren't mousing over it anymore and mouseleave fires, so it's then shown, but then you are mousing over it, so it hides, and so on.

const headerTags1 = document.querySelector('h1');
headerTags1.addEventListener('mouseenter', function(event){
event.target.style.display = "none";
})
console.log(headerTags1)

const headerTags2 = document.querySelector('h1');
headerTags2.addEventListener('mouseleave', function(event){
event.target.style.display = "initial";
})
console.log(headerTags2)

<h1>Now you see me...</h1>

This, of course, is not a good design decision in the first place. What are you really trying to accomplish?

EDIT:

Just want to have the button disappear and reappear when it's hovered
  over or better yet just change colors when it's hovered over...

Then the better approach would be to just use the CSS :hover pseudo-class to modify the element' style only while it's being hovered.

<!doctype html>
<html>
<head>
  <title>Page Title Here</title>
  <style>
    h1:hover { opacity:0; }
    button:hover { color:red; background-color:#ff0; }
  </style>
</head>
<body>

  <h1>Now you see me...</h1>
  <button>Hover Over Me</button>

</body>
</html>


问:
excel matching two arrays
I have a problem that seems pretty easy, but still cannot find a proper solution, I want to avoid using vba.

I have two tables in one spreadsheet. both have the same columns - Name, City, Province.
My goal is compare both and if three out of three values in a row match, then pull "1", if not, pull 0.

I have used the formulas below , but it does not work for my case .

=IF(AND(A2=P:P,G2=M:M,H2=L:L),1,0)

=INDEX(A:P,MATCH(A2,P:P,FALSE),MATCH(G2,M:M,FALSE),2)

=INDEX(L:P,MATCH(A5,P:P,0),MATCH(G5,M:M,0),MATCH(H5,L:L,0))

=SUMPRODUCT(--(L2:L60=H2),--(M2:M60=G2),--(P2:P60=A2),B2:B60)

It seems that the solution is quiet simple , but I cannot find it,

Thanks in advance!

答:
The key here is to merge the columns together, them Match on that.

Like this

```<code>=IFERROR( IF( MATCH(H3&"_"&I3&"_"&J3, $C$2:$C$60&"_"&$B$2:$B$60&"_"&$A$2:$A$60,0), "Yes"), "No")
</code>```

Choose a seperator character that doesn't otherwise appear in your data (I've chosne _)

Title: excel matching two arrays

Body:
The key here is to merge the columns together, them Match on that.

Like this

=IFERROR( IF( MATCH(H3&"_"&I3&"_"&J3, $C$2:$C$60&"_"&$B$2:$B$60&"_"&$A$2:$A$60,0), "Yes"), "No")

Choose a seperator character that doesn't otherwise appear in your data (I've chosne _)


问:
How can I check if the table behind a synonym exists
I'm trying to create a simple script to dump the results of a complex view out into a table for reporting.  I have used synonyms to simplify tweaking the view and table names.

The idea is that the user of the script can put the name of the view they want to use as the source, and the name of the target reporting table in at the start and away they go.  If the table doesn't exist then the script should create it.  If the table already exists then the script should only copy the records from the view which aren't already in the table over.

The script below covers all those requirements, but I can't find a nice way to check if the table behind the synonym already exists:

```<code>CREATE SYNONYM SourceView FOR my_view
CREATE SYNONYM TargetReportingTable FOR my_table

-- Here's where I'm having trouble, how do I check if the underlying table exists?
IF (SELECT COUNT(*) FROM information_schema.tables WHERE table_name = TargetReportingTable) = 0
  BEGIN
    -- Table does not exists, so insert into.
    SELECT * INTO TargetReportingTable FROM SourceView
  END
ELSE
  BEGIN
    -- Table already exists so work out the last record which was copied over
    -- and insert only the newer records.
    DECLARE @LastReportedRecordId INT;
    SET @LastReportedRecordId = (SELECT MAX(RecordId) FROM TargetReportingTable)
    INSERT INTO TargetReportingTable SELECT * FROM SourceView WHERE RecordId > @LastReportedRecordId
  END

DROP SYNONYM SourceView
DROP SYNONYM TargetReportingTable
</code>```

I know I could just get the user of the script to copy the table name into the 'information_schema' line as well as into the synonym at the top, but that leaves scope for error.

I also know I could do something filthy like put the table name into a variable and blat the SQL out as a string, but that makes me feel a bit sick!

Is there a nice elegant SQL way for me to check if the table behind the synonym exists?  Or a totally different way to solve to problem?

答:
Another simpler solution:

```<code>IF (EXISTS (SELECT * FROM sys.synonyms WHERE NAME ='mySynonymName'))
BEGIN
    UPDATE mySynonymName
    SET [Win] = 1
END
</code>```

In this case, I do database setup first. I drop all Synonyms in my database (database1) first, then run a SPROC to create synonyms for all tables in the destination database(database2).
Some SPROCS in database1 call on tables in DB2. If table doesnt exist in DB2 the SPROC fails. If table doesnt exist in DB2, the synonmy is not automatically created on database setup. So I just use the above to check if the Synonym exist, and skip that part of the SPROC if the Synonym is not present.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create a simple script to dump the results of a complex view out into a table for reporting.  I have used synonyms to simplify tweaking the view and table names.

The idea is that the user of the script can put the name of the view they want to use as the source, and the name of the target reporting table in at the start and away they go.  If the table doesn't exist then the script should create it.  If the table already exists then the script should only copy the records from the view which aren't already in the table over.

The script below covers all those requirements, but I can't find a nice way to check if the table behind the synonym already exists:

CREATE SYNONYM SourceView FOR my_view
CREATE SYNONYM TargetReportingTable FOR my_table

-- Here's where I'm having trouble, how do I check if the underlying table exists?
IF (SELECT COUNT(*) FROM information_schema.tables WHERE table_name = TargetReportingTable) = 0
  BEGIN
    -- Table does not exists, so insert into.
    SELECT * INTO TargetReportingTable FROM SourceView
  END
ELSE
  BEGIN
    -- Table already exists so work out the last record which was copied over
    -- and insert only the newer records.
    DECLARE @LastReportedRecordId INT;
    SET @LastReportedRecordId = (SELECT MAX(RecordId) FROM TargetReportingTable)
    INSERT INTO TargetReportingTable SELECT * FROM SourceView WHERE RecordId > @LastReportedRecordId
  END

DROP SYNONYM SourceView
DROP SYNONYM TargetReportingTable

I know I could just get the user of the script to copy the table name into the 'information_schema' line as well as into the synonym at the top, but that leaves scope for error.

I also know I could do something filthy like put the table name into a variable and blat the SQL out as a string, but that makes me feel a bit sick!

Is there a nice elegant SQL way for me to check if the table behind the synonym exists?  Or a totally different way to solve to problem?

Body:
Another simpler solution:

IF (EXISTS (SELECT * FROM sys.synonyms WHERE NAME ='mySynonymName'))
BEGIN
    UPDATE mySynonymName
    SET [Win] = 1
END

In this case, I do database setup first. I drop all Synonyms in my database (database1) first, then run a SPROC to create synonyms for all tables in the destination database(database2).
Some SPROCS in database1 call on tables in DB2. If table doesnt exist in DB2 the SPROC fails. If table doesnt exist in DB2, the synonmy is not automatically created on database setup. So I just use the above to check if the Synonym exist, and skip that part of the SPROC if the Synonym is not present.


问:
Connect to Power BI XMLA endpoint with Python
Since the announcement about XMLA endpoints, I've been trying to figure out how to connect to a URL of the form powerbi://api.powerbi.com/v1.0/myorg/[workspace name] as an SSAS OLAP cube via Python, but I haven't gotten anything to work.

I have a workspace in a premium capacity and I am able to connect to it using DAX Studio as well as SSMS as explained here, but I haven't figured out how to do it with Python. I've tried installing olap.xmla, but I get the following error when I try to use the Power BI URL as the location using either the powerbi or https as the prefix.

```<code>import olap.xmla.xmla as xmla
p = xmla.XMLAProvider()
c = p.connect(location="powerbi://api.powerbi.com/v1.0/myorg/[My Workspace]")
[...]
TransportError: Server returned HTTP status 404 (no content available)
</code>```

I'm sure there are authentication issues involved, but I'm a bit out of my depth here. Do I need to set up an "app" in ActiveDirectory and use the API somehow? How is authentication handled for this kind of connection?

If anyone knows of any blog posts or other resources that demonstrate how to connect to a Power BI XMLA endpoint specifically using Python, that would be amazing. My searching has failed me, but surely I can't be the only one who is trying to do this.

答:
After @Gigga pointed the connector issue, I went looking for other Python modules that worked with MSOLAP to connect and found one that I got working!

The module is adodbapi (note the pywin32 prerequisite).

Connecting is as simple as this:

import adodbapi

# Connection string
conn = adodbapi.connect("Provider=MSOLAP.8; \
    Data Source='powerbi://api.powerbi.com/v1.0/myorg/My Workspace Name'; \
    Initial Catalog='My Data Model'")

# Example query
print('The tables in your database are:')
for name in conn.get_table_names():
    print(name)
```

It authenticated using my Windows credentials by popping up a window like this:

Body:
Since the announcement about XMLA endpoints, I've been trying to figure out how to connect to a URL of the form powerbi://api.powerbi.com/v1.0/myorg/[workspace name] as an SSAS OLAP cube via Python, but I haven't gotten anything to work.

I have a workspace in a premium capacity and I am able to connect to it using DAX Studio as well as SSMS as explained here, but I haven't figured out how to do it with Python. I've tried installing olap.xmla, but I get the following error when I try to use the Power BI URL as the location using either the powerbi or https as the prefix.

import olap.xmla.xmla as xmla
p = xmla.XMLAProvider()
c = p.connect(location="powerbi://api.powerbi.com/v1.0/myorg/[My Workspace]")
[...]
TransportError: Server returned HTTP status 404 (no content available)

I'm sure there are authentication issues involved, but I'm a bit out of my depth here. Do I need to set up an "app" in ActiveDirectory and use the API somehow? How is authentication handled for this kind of connection?

If anyone knows of any blog posts or other resources that demonstrate how to connect to a Power BI XMLA endpoint specifically using Python, that would be amazing. My searching has failed me, but surely I can't be the only one who is trying to do this.

Body:
After @Gigga pointed the connector issue, I went looking for other Python modules that worked with MSOLAP to connect and found one that I got working!

The module is adodbapi (note the pywin32 prerequisite).

Connecting is as simple as this:

import adodbapi

# Connection string
conn = adodbapi.connect("Provider=MSOLAP.8; \
    Data Source='powerbi://api.powerbi.com/v1.0/myorg/My Workspace Name'; \
    Initial Catalog='My Data Model'")

# Example query
print('The tables in your database are:')
for name in conn.get_table_names():
    print(name)

It authenticated using my Windows credentials by popping up a window like this:


问:
How to change the class of component after period of time?
I am using a component which renders a SVG image but it does not render the fill. I made two classes </p>

```<code>.svg  {
  fill-opacity: 0;

.svg-show {
  fill-opacity: 1;
  transition: fill-opacity 2s;
}
</code>```

<p>} My question would be how could I apply a classname svg-show to the below component after lets say duration of 200</p>

```<code>  <ReactVivus
            className="svg"
            option={{
              file: forever,
              duration: 200,
              animTimingFunction: "oneByOne",
              type: "delayed",
              onReady: console.log
            }}
            callback={console.log}
          />
</code>```

答:
If you want to do with hooks:

import React, {useState, useEffect} from "react";

function Calendar() {
    const [svgShow, setSvgShow] = useState(false);

    useEffect(() => {
        setTimeout(() => {
            setSvgShow(true);
        }, 200);
    }, []);

    return (
        <ReactVivus
            className={svgShow ? "svg-show" : "svg"}
            option={{
                file: forever,
                duration: 200,
                animTimingFunction: "oneByOne",
                type: "delayed",
                onReady: console.log
            }}
            callback={console.log}
        />
    )
}
export default Calendar;
```

Body:
I am using a component which renders a SVG image but it does not render the fill. I made two classes

.svg  {
  fill-opacity: 0;

.svg-show {
  fill-opacity: 1;
  transition: fill-opacity 2s;
}

} My question would be how could I apply a classname svg-show to the below component after lets say duration of 200

  <ReactVivus
            className="svg"
            option={{
              file: forever,
              duration: 200,
              animTimingFunction: "oneByOne",
              type: "delayed",
              onReady: console.log
            }}
            callback={console.log}
          />


问:
The UWP JS app I am making with Visual Studio 2017 will not print numbers generated by JavaScript. Is there a reason or workaround to this?
My UWP JS app in Visual Studio 2017 will accept my JavaScript code that is supposed to generate numbers and print in the html field that is provided, but when I test it nothing happens. Is there a reason why this is happening? If so can someone help me find a workaround?
Here is the HTML and JavaScript code:

function displaySuccess() {
  // console.log('yeah');
  displayTask();
}

function displayFailure() {
  // console.log('nope')
}

function displayTask() {
  var a = Math.random() * 25,
    b = Math.random() * 25;
  var c = parseInt(a) * parseInt(b);

  var inputA = document.getElementById("a");
  inputA.setAttribute("value", parseInt(a));
  var inputB = document.getElementById("b");
  inputB.setAttribute("value", parseInt(b));

  var inputC = document.querySelector("useranswer");
  inputC.setAttribute("value", "");
  inputC.onchange = function(evt) {
    var elem = evt.target;
    try {
      var result = parseInt(elem.value);
      if (result == c) {
        displaySuccess();
      } else {
        displayFailure();
      }
    } catch (e) {}
  };
}
window.onload = function() {
  displayTask();
}
```

<pre class="lang-html prettyprint-override"><code><form method='post'>
  <input type='hidden' name='a' value={{a}} />
  <input type='hidden' name='b' value={{b}} />
  <input type='hidden' name='calcanswer' value={{calcanswer}} />
  <h3>Solve the multiplication:    <input type=text name=a size=3 id="a"> x <input type=text name=b size=3 value={{b}}> = <input type='text' name='useranswer' value='{{useranswer}}' size='2' /></h3>
  <input type='submit' value='Answer' />
</form>
</code>```

答: I figured out the problem. it was my main.js import. apparently since it was in the head rather than inside the body it wouldn't generate.</p>

Body:
My UWP JS app in Visual Studio 2017 will accept my JavaScript code that is supposed to generate numbers and print in the html field that is provided, but when I test it nothing happens. Is there a reason why this is happening? If so can someone help me find a workaround?
Here is the HTML and JavaScript code:

function displaySuccess() {
  // console.log('yeah');
  displayTask();
}

function displayFailure() {
  // console.log('nope')
}

function displayTask() {
  var a = Math.random() * 25,
    b = Math.random() * 25;
  var c = parseInt(a) * parseInt(b);

  var inputA = document.getElementById("a");
  inputA.setAttribute("value", parseInt(a));
  var inputB = document.getElementById("b");
  inputB.setAttribute("value", parseInt(b));

  var inputC = document.querySelector("useranswer");
  inputC.setAttribute("value", "");
  inputC.onchange = function(evt) {
    var elem = evt.target;
    try {
      var result = parseInt(elem.value);
      if (result == c) {
        displaySuccess();
      } else {
        displayFailure();
      }
    } catch (e) {}
  };
}
window.onload = function() {
  displayTask();
}

<form method='post'>
  <input type='hidden' name='a' value={{a}} />
  <input type='hidden' name='b' value={{b}} />
  <input type='hidden' name='calcanswer' value={{calcanswer}} />

Solve the multiplication:    <input type=text name=a size=3 id="a"> x <input type=text name=b size=3 value={{b}}> = <input type='text' name='useranswer' value='{{useranswer}}' size='2' />

  <input type='submit' value='Answer' />
</form>


问:
Remove images from product description
I would like to show product images from the description only on mobile devices.  I don't know how to split the images from the product.description.</p>

```<code>         <div class="product-description rte" itemprop="description">
         // this works how I want it to. shows images and text
         <div class="mobileShow">
          {{ product.description }}

        </div>

         // if not mobile device only show text. strip out images.
           {% if product.description contains "<img" %}
           // ??

          </div>
</code>```

答:
If you're wanting to hide all images within the description on mobile you can use a media query to target them.

The media query is dependent on the theme, though. Here's an example:

```<code>@include media-query($small) {
  .product-description img {
    display: none;
  }
}
</code>```

You'd want to add that to the end of your scss file (most likely theme.scss.liquid.)

The query above is for Simple and a few others - here's the list:

Narrative, Simple, Venture, Debut, Boundless: @include media-query($small) {

Jumpstart, Brooklyn, Supply, Pop, Minimal: @include at-query($max, $small) {

Title: Remove images from product description

Body:
I would like to show product images from the description only on mobile devices.  I don't know how to split the images from the product.description.

         // this works how I want it to. shows images and text

          {{ product.description }}

         // if not mobile device only show text. strip out images.
           {% if product.description contains "<img" %}
           // ??

Body:
If you're wanting to hide all images within the description on mobile you can use a media query to target them.

The media query is dependent on the theme, though. Here's an example:

@include media-query($small) {
  .product-description img {
    display: none;
  }
}

You'd want to add that to the end of your scss file (most likely theme.scss.liquid.)

The query above is for Simple and a few others - here's the list:

Narrative, Simple, Venture, Debut, Boundless: @include media-query($small) {

Jumpstart, Brooklyn, Supply, Pop, Minimal: @include at-query($max, $small) {


问:
How do you balance working for a living and contributing to open source projects?
I have been a working programmer since the turn of the century and I have always been fascinated by the open source world. I have wanted to contribute to these projects but I find it difficult to find the time that I think these projects would require.

I find professional software development to be a huge time sink. Almost every project I have worked on has a familiar litany inflexible deadlines and inevitable round the clock last minute pushes that eat up your nights and weekends and everything else in sight. Even in the project that don't have this - the typical work day is 10 to 12 hours and after that one has errands and chores, reading up on the latest stuff, etc...

Since this happens with a fair amount of regularity - I am hesitant to join projects since I can't promise to devote a regular number of hours every week.

My question is how do you people do it?

Do you work at open source companies? Am I exaggerating the amount of time I need to spend (I am thinking a couple of hours everyday)? Am I way off base and simply not managing my time efficiently? How do you manage your time?

答:
I am currently a student and I am working on an open source project. I donate my free time for it, but it's okay because it is also some kind of hobby for me. How much time you want to spend depends on the work you plan to be doing. There is many different work to do in an open source project, for example except plain coding there is also documentation, user support, ticket classification etc.

Mailing lists can be a good introduction to the project and how it works. Start following the development mailing list and watch how developers interact. Many developers do not work on the project every day, but may limit their contributions to weekends only. Also, most developers understand when real life is more important to you than the work on the project.

Also take a look at their bug trackers. There might be just some feature requests lying around which do not require much work, but nobody had time yet to address them. In this case, feel free to implement it and attach it to the report. That's a good possibility to contribute to the project. Every contribution counts and you do not have to create big plans, small contributions are fine, too.

After all, do not hesitate to get into an open source project just because you fear the amount of time you will spend with it. Looking forward to see some patch of you in any open source software soon ;-)

OwnerDisplayName: Nikhil

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Raim


问:
Parallel.For spins up an unexpected amount of threads
Consider the following code:

```<code>var options = new ParallelOptions();
var urls = GetListOfUrls();

Parallel.ForEach(urls, options, url => {
    try {
        using (HttpClient client = new HttpClient()) {
            client.Timeout = TimeSpan.FromMinutes(30);
            Task task = client.GetAsync(url);
            task.Wait();
        }
    } catch (Exception exception) {
        Console.WriteLine(exception.Message);
    }

});
</code>```

It spins up ~670 threads on a VM with 8 cores.  Is this normal?  My understanding was that the rule of thumb for TPL was 25 threads per core, which would put it into the 200 threads range.

P.S.  In the code below GetListOfUrls() returns a million URLs.

答:
Parallel is overkill here, since the HttpClient methods are async. I would suggest calling them asynchronously instead. Otherwise you will create a high number of threads that are doing nothing but waiting.

Also, use a single instance of the HttpClient. This will increase cache hits and reduce the need for the HttpClient to spin up threads to access proxy or DNS information.

```<code>var client = new HttpClient();
var tasks = urls.Select( url => client.GetAsync(url) ).ToList();
await Task.WhenAll(tasks);
var results = tasks.Select( task => task.Result ).ToList();
</code>```

Body:
Consider the following code:

var options = new ParallelOptions();
var urls = GetListOfUrls();

Parallel.ForEach(urls, options, url => {
    try {
        using (HttpClient client = new HttpClient()) {
            client.Timeout = TimeSpan.FromMinutes(30);
            Task task = client.GetAsync(url);
            task.Wait();
        }
    } catch (Exception exception) {
        Console.WriteLine(exception.Message);
    }

});

It spins up ~670 threads on a VM with 8 cores.  Is this normal?  My understanding was that the rule of thumb for TPL was 25 threads per core, which would put it into the 200 threads range.

P.S.  In the code below GetListOfUrls() returns a million URLs.

Body:
Parallel is overkill here, since the HttpClient methods are async. I would suggest calling them asynchronously instead. Otherwise you will create a high number of threads that are doing nothing but waiting.

Also, use a single instance of the HttpClient. This will increase cache hits and reduce the need for the HttpClient to spin up threads to access proxy or DNS information.

var client = new HttpClient();
var tasks = urls.Select( url => client.GetAsync(url) ).ToList();
await Task.WhenAll(tasks);
var results = tasks.Select( task => task.Result ).ToList();


问:
Stacking column data in excel SQL query
I'm trying to pull data from an access database into an excel table with an SQL query. The problem is that my access database has columns with similar data that I want to combine into one single column. This should give me duplicates of the data in other columns for each entry. I'm not great with SQL but I think I have the basics down.

Database structure that I have:

```<code>Date | Product | Hours 1 | Reason 1 | Hours 2 | Reason 2 |
2019    A          3         "xxx"      5         "yyy"
</code>```

Excel table that I want:

```<code>Date | Product | Hours | Reason |
2019     A         3      "xxx"
2019     A         5      "yyy"
</code>```

Also not sure if it's possible but it would be great to see the source column of each

```<code>Date | Product | Hours | Reason |  Source  |
2019     A         3      "xxx"   "Hours 1"
2019     A         5      "yyy"   "Hours 2"
</code>```

I've tried UNION ALL and got duplicates of the data but not merged into one column. I'm about to try INSERT INTO but sort of lost on how to get each one into the same column

答:
It looks like you have a bad data structure in the table. By that I mean its a "flat" table with multiple hours in one row for a record. This is generally a PITA when it comes doing tasks for reviewing data in many to one situations. Normally there would be a table where records get logged separately for each hour involved. I understand you probably didnt build it, but its worth pointing out for you own information.

Fundamentally, this issue would be easier to appproach once you understood how that less than desirable structure affects what youre task is. This is essentially, in my mind, a pivot problem. PIVOT in SQL is essentially switching rows and columns. There are may ways to pivot data with code - pick your favorite - most people actually use the function PIVOT, where I tend to teeter between CTE's (common table experessions) and PIVOT. IMO CTE's are easier to read once you understand them. Because Acess SQL doesnt support PIVOT or CTE's we just had to treat the body of what a cte wouldve been as a correlated subquery.

```<code>SELECT x.*
FROM
(
    SELECT
        Date,
        Product,
        Hours,
        Reason,
        [Hours 1] AS Source
    FROM yourTableName
    UNION
    SELECT
        Date,
        Product,
        Hours,
        Reason,
        [Hours 2] AS Source
    FROM yourTableName
) x
</code>```

Title: Stacking column data in excel SQL query

Body:
I'm trying to pull data from an access database into an excel table with an SQL query. The problem is that my access database has columns with similar data that I want to combine into one single column. This should give me duplicates of the data in other columns for each entry. I'm not great with SQL but I think I have the basics down.

Database structure that I have:

Date | Product | Hours 1 | Reason 1 | Hours 2 | Reason 2 |
2019    A          3         "xxx"      5         "yyy"

Excel table that I want:

Date | Product | Hours | Reason |
2019     A         3      "xxx"
2019     A         5      "yyy"

Also not sure if it's possible but it would be great to see the source column of each

Date | Product | Hours | Reason |  Source  |
2019     A         3      "xxx"   "Hours 1"
2019     A         5      "yyy"   "Hours 2"

I've tried UNION ALL and got duplicates of the data but not merged into one column. I'm about to try INSERT INTO but sort of lost on how to get each one into the same column

Body:
It looks like you have a bad data structure in the table. By that I mean its a "flat" table with multiple hours in one row for a record. This is generally a PITA when it comes doing tasks for reviewing data in many to one situations. Normally there would be a table where records get logged separately for each hour involved. I understand you probably didnt build it, but its worth pointing out for you own information.

Fundamentally, this issue would be easier to appproach once you understood how that less than desirable structure affects what youre task is. This is essentially, in my mind, a pivot problem. PIVOT in SQL is essentially switching rows and columns. There are may ways to pivot data with code - pick your favorite - most people actually use the function PIVOT, where I tend to teeter between CTE's (common table experessions) and PIVOT. IMO CTE's are easier to read once you understand them. Because Acess SQL doesnt support PIVOT or CTE's we just had to treat the body of what a cte wouldve been as a correlated subquery.

SELECT x.*
FROM
(
    SELECT
        Date,
        Product,
        Hours,
        Reason,
        [Hours 1] AS Source
    FROM yourTableName
    UNION
    SELECT
        Date,
        Product,
        Hours,
        Reason,
        [Hours 2] AS Source
    FROM yourTableName
) x


问:
How can I access methods inside a class from outside of class
I have a couple questions regarding Class files. I have the below Class

```<code>class CouchController {
constructor(couchbase, config) {
    // You may either pass couchbase and config as params, or import directly into the controller
    this.cluster = new couchbase.Cluster(config.cluster);
    this.cluster.authenticate(config.userid, config.password);
    this.bucket = cluster.openBucket(config.bucket);
    this.N1qlQuery = couchbase.N1qlQuery;
  }

        doSomeQuery(queryString, callback) {
              this.bucket.manager().createPrimaryIndex(function() {
              this.bucket.query(
                this.N1qlQuery.fromString("SELECT * FROM bucketname WHERE $1 in interests LIMIT 1"),
                [queryString],
                callback(err, result)
              )
            });
          }
  }
</code>```

my problem is how can I go and access the doSomeQuery function from outside the class file? Inside there is no issue accessing the function but I need to be able to call it from outside.
I tried something like this

```<code>const CouchController = require("../controllers/CouchController")(couchbase, config)
let newTest = new CouchController
</code>```

doing so newTest never exposes the doSomeQuery method.

Also what are the limitations of a method ? Can it only be a simple one or can it be async and use promises etc ?

答:
There are 2 main things that you should consider with the following problem.

Export it properly first. I'm not sure if you meant to leave this out, but it's important to export the class for use outside as a require. Here is the NodeJS exports documentation if you wish for the technical details.

```<code>// common module default export
module.exports = class CouchController {
  constructor(couchbase, config) {
    // You may either pass couchbase and config as params, or import directly into the controller
    this.cluster = new couchbase.Cluster(config.cluster);
    this.cluster.authenticate(config.userid, config.password);
    this.bucket = cluster.openBucket(config.bucket);
    this.N1qlQuery = couchbase.N1qlQuery;
  }

        doSomeQuery(queryString, callback) {
              this.bucket.manager().createPrimaryIndex(function() {
              this.bucket.query(
                this.N1qlQuery.fromString("SELECT * FROM bucketname WHERE $1 in interests LIMIT 1"),
                [queryString],
                callback(err, result)
              )
            });
          }
  }
</code>```

The class initialization is slightly incorrect. You can see the docs on this here. You can change your require and initialization to...

```<code>const CouchController = require('../controllers/CouchController');
const newTest = new CouchController(couchbase, config);

// now you can access the function :)
newTest.doSomeQuery("query it up", () => {
// here is your callback
})
</code>```

If you were using ES6 modules or typescript you could export something like...

```<code>export default class CouchController {
  // ...
}
</code>```

... and import something like...

```<code>import CouchController from '../controllers/CouchController';

const newTest = new CouchController(couchbase, config);
</code>```

Body:
I have a couple questions regarding Class files. I have the below Class

class CouchController {
constructor(couchbase, config) {
    // You may either pass couchbase and config as params, or import directly into the controller
    this.cluster = new couchbase.Cluster(config.cluster);
    this.cluster.authenticate(config.userid, config.password);
    this.bucket = cluster.openBucket(config.bucket);
    this.N1qlQuery = couchbase.N1qlQuery;
  }

        doSomeQuery(queryString, callback) {
              this.bucket.manager().createPrimaryIndex(function() {
              this.bucket.query(
                this.N1qlQuery.fromString("SELECT * FROM bucketname WHERE $1 in interests LIMIT 1"),
                [queryString],
                callback(err, result)
              )
            });
          }
  }

my problem is how can I go and access the doSomeQuery function from outside the class file? Inside there is no issue accessing the function but I need to be able to call it from outside.
I tried something like this

const CouchController = require("../controllers/CouchController")(couchbase, config)
let newTest = new CouchController

doing so newTest never exposes the doSomeQuery method.

Also what are the limitations of a method ? Can it only be a simple one or can it be async and use promises etc ?

Body:
There are 2 main things that you should consider with the following problem.

Export it properly first. I'm not sure if you meant to leave this out, but it's important to export the class for use outside as a require. Here is the NodeJS exports documentation if you wish for the technical details.

// common module default export
module.exports = class CouchController {
  constructor(couchbase, config) {
    // You may either pass couchbase and config as params, or import directly into the controller
    this.cluster = new couchbase.Cluster(config.cluster);
    this.cluster.authenticate(config.userid, config.password);
    this.bucket = cluster.openBucket(config.bucket);
    this.N1qlQuery = couchbase.N1qlQuery;
  }

        doSomeQuery(queryString, callback) {
              this.bucket.manager().createPrimaryIndex(function() {
              this.bucket.query(
                this.N1qlQuery.fromString("SELECT * FROM bucketname WHERE $1 in interests LIMIT 1"),
                [queryString],
                callback(err, result)
              )
            });
          }
  }

The class initialization is slightly incorrect. You can see the docs on this here. You can change your require and initialization to...

const CouchController = require('../controllers/CouchController');
const newTest = new CouchController(couchbase, config);

// now you can access the function :)
newTest.doSomeQuery("query it up", () => {
// here is your callback
})

If you were using ES6 modules or typescript you could export something like...

export default class CouchController {
  // ...
}

... and import something like...

import CouchController from '../controllers/CouchController';

const newTest = new CouchController(couchbase, config);


问:
How to create a workspace
How do we create a workspace in Visual Studio Code?

I see File menu commands to open, add a folder to and save a workspace, but nothing to create one.

The questions How can I create a workspace in Visual Studio Code? and How can I create a Visual Studio Code Python workspace? are specific to Python. I am asking how to create a generic workspace.

The question What is a 'workspace' in Visual Studio Code? provides some explanation of what they are, but it is not clear how to create them.

答:
I had your same question, but the answer is simple, you don't. There is no need to start a blank workspace. To start on a new project use Open Folder from the File menu: navigate to the project, create a folder if needed, and then select the folder. You are now working on any files within that folder as if it were a workspace. If you leave and open another folder or workspace with files still open in editors, those files will be open when you open that folder again. Visual Studio Code making things work effortlessly! Until you do something that specifically requires a workspace you don't have to save it. If you save a workspace with no settings changed to the root folder here's what it looks like: {"folders": [{"path": "."}],"settings": {}}. That's it. The open editors are saved internally regardless of whether you saved as workspace. Starting by saving a blank workspace is like having an empty file cabinet in your office. VSCode will inform you if you ever need that and you can save a workspace then.

I finally had a chance to use VSC on a Mac. The difference on a Mac is
that Open File and Open Folder are under the same general Open
command (apparently because Macs use the same browser to select files and folders). Just use that to Open a folder, and open files in that folder workspace using the VSC explorer. All this still applies. The folder is the workspace.

You only need to save that workspace if you want to Add Folder to Workspace (in which case VSC will prompt you to save your multiroot workspace if you exit, or if you want to save settings specific to your project folder (though you can do that without a workspace using a settings json in a .vscode folder within). Even then VSC will auto save workspace settings for the folder internally when you haven't explicitly made the project folder a workspace.

Do you need a workspace and the extra .code-workspace file involved? If you have multiple root folders it's certainly nice to open the workspace and have those all there in your next session. If it's just for settings for a project with one root it's not needed (maybe if you want a file you can share with others on the project), and if the reason you are changing settings per project is language related then it may make far more sense to add language settings to your main settings file and have them in effect every time you work on that kind of project.

In short every time you use Open Folder workbench.action.files.openFolder you are essentially switching to another workspace.

Title: How to create a workspace


问:
Incorrect binding for DLQ Rabbit using Spring Cloud Stream
I have one simple Spring Cloud Stream application with following configuration

```<code>spring:
    cloud:
        stream:
            rabbit:
                bindings:
                    input:
                        consumer:
                            exchangeType: topic
                            bindingRoutingKey: service.routing
                            autoBindDlq: true
                            deadLetterExchange: service.exchange.error
                            deadLetterQueueName: service.queue.error
                            deadLetterRoutingKey: service.routing.error
                            deadLetterExchangeType: topic
                            queueNameGroupOnly: true
                            republishToDlq: true
            bindings:
                input:
                    destination: service.exchange
                    group: service.queue
                    binder: rabbit
                    consumer:
                        errorChannelEnabled: true
                        maxAttempts: 2
                        concurrency: 3
            binders:
                rabbit:
                    type: rabbit
                    environment:
                        spring:
                            rabbitmq:
                                host: ${RABBITMQ_HOST:localhost}
                                port: ${RABBITMQ_PORT:5672}
                                username: ${RABBITMQ_USERNAME:guest}
                                password: ${RABBITMQ_PASSWORD:guest}
</code>```

Everything looks fine but the binding in DLQ is incorrect as a result DLQ is not getting any message.

Expected result

Exchange (service.exchange.error) -> Routing (service.routing.error) -> Queue (service.queue.error)

Actual result

Exchange (service.exchange.error) -> Routing (service.queue) -> Queue (service.queue.error)

Is there anyway to fix this issue.

答:
When republishToDlq is true, we also bind with the queue name because the republisher knows nothing about partitioned destinations.

```<code>Binding dlqBinding = new Binding(dlq.getName(), DestinationType.QUEUE,
        dlxName, properties.getDlqDeadLetterRoutingKey() == null ? routingKey
                : properties.getDeadLetterRoutingKey(),
        null);
declareBinding(dlqName, dlqBinding);
if (properties instanceof RabbitConsumerProperties
        && ((RabbitConsumerProperties) properties).isRepublishToDlq()) {
    /*
     * Also bind with the base queue name when republishToDlq is used, which
     * does not know about partitioning
     */
    declareBinding(dlqName, new Binding(dlq.getName(), DestinationType.QUEUE,
            dlxName, baseQueueName, null));
}
</code>```

So you should see 2 bindings - yours and the extra one.

Body:
I have one simple Spring Cloud Stream application with following configuration

spring:
    cloud:
        stream:
            rabbit:
                bindings:
                    input:
                        consumer:
                            exchangeType: topic
                            bindingRoutingKey: service.routing
                            autoBindDlq: true
                            deadLetterExchange: service.exchange.error
                            deadLetterQueueName: service.queue.error
                            deadLetterRoutingKey: service.routing.error
                            deadLetterExchangeType: topic
                            queueNameGroupOnly: true
                            republishToDlq: true
            bindings:
                input:
                    destination: service.exchange
                    group: service.queue
                    binder: rabbit
                    consumer:
                        errorChannelEnabled: true
                        maxAttempts: 2
                        concurrency: 3
            binders:
                rabbit:
                    type: rabbit
                    environment:
                        spring:
                            rabbitmq:
                                host: ${RABBITMQ_HOST:localhost}
                                port: ${RABBITMQ_PORT:5672}
                                username: ${RABBITMQ_USERNAME:guest}
                                password: ${RABBITMQ_PASSWORD:guest}

Everything looks fine but the binding in DLQ is incorrect as a result DLQ is not getting any message.

Expected result

Exchange (service.exchange.error) -> Routing (service.routing.error) -> Queue (service.queue.error)

Actual result

Exchange (service.exchange.error) -> Routing (service.queue) -> Queue (service.queue.error)

Is there anyway to fix this issue.

Body:
When republishToDlq is true, we also bind with the queue name because the republisher knows nothing about partitioned destinations.

Binding dlqBinding = new Binding(dlq.getName(), DestinationType.QUEUE,
        dlxName, properties.getDlqDeadLetterRoutingKey() == null ? routingKey
                : properties.getDeadLetterRoutingKey(),
        null);
declareBinding(dlqName, dlqBinding);
if (properties instanceof RabbitConsumerProperties
        && ((RabbitConsumerProperties) properties).isRepublishToDlq()) {
    /*
     * Also bind with the base queue name when republishToDlq is used, which
     * does not know about partitioning
     */
    declareBinding(dlqName, new Binding(dlq.getName(), DestinationType.QUEUE,
            dlxName, baseQueueName, null));
}

So you should see 2 bindings - yours and the extra one.


问:
Precise pixel movement in Canvas
I am doing some sort of drawing software in WPF, and I have certain visual elements in a Canvas like for example Rectangles and Lines. I have implemented dragging of those elements around the Canvas to move them. The motion must be aligned to pixels, I read WPF uses points and not pixels so it has become a concern of mine to know whether my lines or rectangles are aligned to pixels. I tried using SnapsToPixels, but I'm not sure it will do the trick, or if it will do it when I'm moving the visuals around.

Finally, I must implement moving visuals with the keyboard, a single cursor stroke means move the visual exactly one pixel, how can I do this from the code behind? I assume doing something like:

```<code>Canvas.SetLeft(visual) = Canvas.GetLeft(visual) + 1;
</code>```

Will only add one point to its position, and not one pixel, how can I move exactly one pixel in the Canvas?

Thank you very much.

答: It might help to use SnapToDevicePixels for your canvas.</p>

Title: Precise pixel movement in Canvas

Body:
I am doing some sort of drawing software in WPF, and I have certain visual elements in a Canvas like for example Rectangles and Lines. I have implemented dragging of those elements around the Canvas to move them. The motion must be aligned to pixels, I read WPF uses points and not pixels so it has become a concern of mine to know whether my lines or rectangles are aligned to pixels. I tried using SnapsToPixels, but I'm not sure it will do the trick, or if it will do it when I'm moving the visuals around.

Finally, I must implement moving visuals with the keyboard, a single cursor stroke means move the visual exactly one pixel, how can I do this from the code behind? I assume doing something like:

Canvas.SetLeft(visual) = Canvas.GetLeft(visual) + 1;

Will only add one point to its position, and not one pixel, how can I move exactly one pixel in the Canvas?

Thank you very much.


问:
Configure HostnameVerifier with reactor netty for spring-webflux WebClient
I'm trying to configure spring-webflux WebClient (with reactor netty under the hood) with ssl and client hostname verification. I'm provided with javax.net.ssl.SSLContext, HostnameVerifier and a list of trusted hostnames (as string list).

So far I've configured WebClient with my SSLContext, but I can't find a way to configure hostname verification.

To state my problem: I have a set of trusted services hostnames (String list) and a HostnameVerifier. I want to configure my WebClient with it.

Is there a possibility to do it with the javax.net.ssl.HostnameVerifier? Is there an alternative approach in reactor netty?

This is what I've got so far:

```<code>WebClient.builder()
  .clientConnector(
    new ReactorClientHttpConnector(
      opt -> opt.sslContext(new JdkSslContext(mySSLContext,
                      true, ClientAuth.OPTIONAL))))
  .build();
</code>```

答:
I've tried following solution with Netty HttpClient and it worked as well (Disabling the hostname verification by using a custom hostname matcher)

```<code>public HttpClient getHttpClient(HttpClientProperties properties){

            // configure pool resources
            HttpClientProperties.Pool pool = properties.getPool();

            ConnectionProvider connectionProvider;
            if (pool.getType() == DISABLED) {
                connectionProvider = ConnectionProvider.newConnection();
            }
            else if (pool.getType() == FIXED) {
                connectionProvider = ConnectionProvider.fixed(pool.getName(),
                        pool.getMaxConnections(), pool.getAcquireTimeout());
            }
            else {
                connectionProvider = ConnectionProvider.elastic(pool.getName());
            }

            HttpClient httpClient = HttpClient.create(connectionProvider)
                    .tcpConfiguration(tcpClient -> {

                        if (properties.getConnectTimeout() != null) {
                            tcpClient = tcpClient.option(
                                    ChannelOption.CONNECT_TIMEOUT_MILLIS,
                                    properties.getConnectTimeout());
                        }

                        // configure proxy if proxy host is set.
                        HttpClientProperties.Proxy proxy = properties.getProxy();

                        if (StringUtils.hasText(proxy.getHost())) {

                            tcpClient = tcpClient.proxy(proxySpec -> {
                                ProxyProvider.Builder builder = proxySpec
                                        .type(ProxyProvider.Proxy.HTTP)
                                        .host(proxy.getHost());

                                PropertyMapper map = PropertyMapper.get();

                                map.from(proxy::getPort).whenNonNull().to(builder::port);
                                map.from(proxy::getUsername).whenHasText()
                                        .to(builder::username);
                                map.from(proxy::getPassword).whenHasText()
                                        .to(password -> builder.password(s -> password));
                                map.from(proxy::getNonProxyHostsPattern).whenHasText()
                                        .to(builder::nonProxyHosts);
                            });
                        }
                        return tcpClient;
                    });

            HttpClientProperties.Ssl ssl = properties.getSsl();
            if (ssl.getTrustedX509CertificatesForTrustManager().length > 0
                    || ssl.isUseInsecureTrustManager()) {
                httpClient = httpClient.secure(sslContextSpec -> {
                    // configure ssl
                    SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();

                    X509Certificate[] trustedX509Certificates = ssl
                            .getTrustedX509CertificatesForTrustManager();
                    if (trustedX509Certificates.length > 0) {
                        sslContextBuilder.trustManager(trustedX509Certificates);
                    }
                    else if (ssl.isUseInsecureTrustManager()) {
                        sslContextBuilder
                                .trustManager(InsecureTrustManagerFactory.INSTANCE);
                    }

                    sslContextSpec.sslContext(sslContextBuilder)
                            .defaultConfiguration(ssl.getDefaultConfigurationType())
                            .handshakeTimeout(ssl.getHandshakeTimeout())
                            .closeNotifyFlushTimeout(ssl.getCloseNotifyFlushTimeout())
                            .closeNotifyReadTimeout(ssl.getCloseNotifyReadTimeout())
                            .handlerConfigurator(
                                    (handler)->{
                                        SSLEngine engine = handler.engine();
                                        //engine.setNeedClientAuth(true);
                                        SSLParameters params = new SSLParameters();
                                        List<SNIMatcher> matchers = new LinkedList<>();
                                        SNIMatcher matcher = new SNIMatcher(0) {

                                            @Override
                                            public boolean matches(SNIServerName serverName) {
                                                return true;
                                            }
                                        };
                                        matchers.add(matcher);
                                        params.setSNIMatchers(matchers);
                                        engine.setSSLParameters(params);
                                    }
                            )
                    ;
                });
            }

            return httpClient;

        }
</code>```

It uses nettys handlerConfigurator to configure SSLEngine and use it with custom matchers

Body:
I'm trying to configure spring-webflux WebClient (with reactor netty under the hood) with ssl and client hostname verification. I'm provided with javax.net.ssl.SSLContext, HostnameVerifier and a list of trusted hostnames (as string list).

So far I've configured WebClient with my SSLContext, but I can't find a way to configure hostname verification.

To state my problem: I have a set of trusted services hostnames (String list) and a HostnameVerifier. I want to configure my WebClient with it.

Is there a possibility to do it with the javax.net.ssl.HostnameVerifier? Is there an alternative approach in reactor netty?

This is what I've got so far:

WebClient.builder()
  .clientConnector(
    new ReactorClientHttpConnector(
      opt -> opt.sslContext(new JdkSslContext(mySSLContext,
                      true, ClientAuth.OPTIONAL))))
  .build();

Body:
I've tried following solution with Netty HttpClient and it worked as well (Disabling the hostname verification by using a custom hostname matcher)

public HttpClient getHttpClient(HttpClientProperties properties){

            // configure pool resources
            HttpClientProperties.Pool pool = properties.getPool();

            ConnectionProvider connectionProvider;
            if (pool.getType() == DISABLED) {
                connectionProvider = ConnectionProvider.newConnection();
            }
            else if (pool.getType() == FIXED) {
                connectionProvider = ConnectionProvider.fixed(pool.getName(),
                        pool.getMaxConnections(), pool.getAcquireTimeout());
            }
            else {
                connectionProvider = ConnectionProvider.elastic(pool.getName());
            }

            HttpClient httpClient = HttpClient.create(connectionProvider)
                    .tcpConfiguration(tcpClient -> {

                        if (properties.getConnectTimeout() != null) {
                            tcpClient = tcpClient.option(
                                    ChannelOption.CONNECT_TIMEOUT_MILLIS,
                                    properties.getConnectTimeout());
                        }

                        // configure proxy if proxy host is set.
                        HttpClientProperties.Proxy proxy = properties.getProxy();

                        if (StringUtils.hasText(proxy.getHost())) {

                            tcpClient = tcpClient.proxy(proxySpec -> {
                                ProxyProvider.Builder builder = proxySpec
                                        .type(ProxyProvider.Proxy.HTTP)
                                        .host(proxy.getHost());

                                PropertyMapper map = PropertyMapper.get();

                                map.from(proxy::getPort).whenNonNull().to(builder::port);
                                map.from(proxy::getUsername).whenHasText()
                                        .to(builder::username);
                                map.from(proxy::getPassword).whenHasText()
                                        .to(password -> builder.password(s -> password));
                                map.from(proxy::getNonProxyHostsPattern).whenHasText()
                                        .to(builder::nonProxyHosts);
                            });
                        }
                        return tcpClient;
                    });

            HttpClientProperties.Ssl ssl = properties.getSsl();
            if (ssl.getTrustedX509CertificatesForTrustManager().length > 0
                    || ssl.isUseInsecureTrustManager()) {
                httpClient = httpClient.secure(sslContextSpec -> {
                    // configure ssl
                    SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();

                    X509Certificate[] trustedX509Certificates = ssl
                            .getTrustedX509CertificatesForTrustManager();
                    if (trustedX509Certificates.length > 0) {
                        sslContextBuilder.trustManager(trustedX509Certificates);
                    }
                    else if (ssl.isUseInsecureTrustManager()) {
                        sslContextBuilder
                                .trustManager(InsecureTrustManagerFactory.INSTANCE);
                    }

                    sslContextSpec.sslContext(sslContextBuilder)
                            .defaultConfiguration(ssl.getDefaultConfigurationType())
                            .handshakeTimeout(ssl.getHandshakeTimeout())
                            .closeNotifyFlushTimeout(ssl.getCloseNotifyFlushTimeout())
                            .closeNotifyReadTimeout(ssl.getCloseNotifyReadTimeout())
                            .handlerConfigurator(
                                    (handler)->{
                                        SSLEngine engine = handler.engine();
                                        //engine.setNeedClientAuth(true);
                                        SSLParameters params = new SSLParameters();
                                        List<SNIMatcher> matchers = new LinkedList<>();
                                        SNIMatcher matcher = new SNIMatcher(0) {

                                            @Override
                                            public boolean matches(SNIServerName serverName) {
                                                return true;
                                            }
                                        };
                                        matchers.add(matcher);
                                        params.setSNIMatchers(matchers);
                                        engine.setSSLParameters(params);
                                    }
                            )
                    ;
                });
            }

            return httpClient;

        }

It uses nettys handlerConfigurator to configure SSLEngine and use it with custom matchers


问:
Loop through the contents of a specific element in JSON response using PHP
I need to loop through one large element in a JSON object which is a response from an API call.  One version of the API gives a response with information nested into a large element called statuses and the other does not. I can print a specific key/value on the one that is not nested - but I am having trouble with the one that is.

Here are examples of each response:

First, with no nesting:

```<code>    [
      {
        "created_at": "xzy",
        "id": 123abc,
        "id_str": "123abc",
        "text": "Hello world"
        ...
        ...
        ...
      },
      {
        "created_at": "xzy",
        "id": 123abc,
        "id_str": "123abc",
        "text": "Hello world"
        ...
        ...
        ...
      }
    ]
</code>```

This is put into php array with standard

`$string is defined below, I'm using a Twitter API wrapper link here

```<code>    $string = json_decode($twitter->setGetfield($getfield)
    ->buildOauth($url, $requestMethod)
    ->performRequest(),$assoc = TRUE);
</code>```

I can return all of the id values with a simple foreach loop like this:

```<code>    foreach ($string as $items)
    {
      echo "The id from the response is: ".$items['id']."br />";
    }
</code>```

This give me something like this:

The id from the response is: 123abc

The id from the response is: abc123

The id from the response is: xyz321

...

The other version of the API's reponse (the one I need to use) has similar information but stored in a large element statuses

```<code>    {
      "statuses": [
        {
          "created_at": "xzy",
          "id": 123abc,
          "id_str": "123abc",
          "text": "Hello world"
          ...
          ...
          ...
        },
        {
          "created_at": "xzy",
          "id": 123abc,
          "id_str": "123abc",
          "text": "Hello world"
          ...
          ...
          ...
        }
      ],
      "search_metadata": {...}
    }
</code>```

When I try to loop through this json, I never get any output.

The json has been put into $string with json_decode, same as before.

It's obvious that the information is structured the same, just nested in statuses. Here is what I have tried:

```<code>    foreach($string['statuses'] as $items)
    {
      echo "The id's from the response are: ".$items['id']."br />";
    }
</code>```

As well as:

```<code>    foreach($string[0] as $items)
    {
      echo "The id's from the response are: ".$items['id']."br />";
    }
</code>```

And:

```<code>    foreach($string as $items)
        {
          foreach ($items as $statuses => $tweets)
          {
            if (is_array($tweets))
            {
              foreach ($tweets as $t => $v)
              {
                $output[$statuses.'_'.$t] = $v
              }
            }
            else {$output[$statuses] = $tweets;}
          }

        }

     print_r($output);
</code>```

I simply need to loop through the contents of statuses as if it weren't even there like in the first response, but nothing is working.

答:
This code actually does work. I just wasn't seeing any output from the json because the id is a data type that cannot be concatenated, at least not in the way I was doing it. There is an "id" element and a string version "id_str" and the string version showed up on my web page.

```<code>foreach($string['statuses'] as $items)
{
  echo "The id's from the response are: ".$items['id']."br />";
}
</code>```

To be clear, this is the snippet that achieved my goal:

```<code>foreach($string['statuses'] as $items)
{
  echo "The id's from the response are: ".$items['id_str']."br />";
}
</code>```

Body:
I need to loop through one large element in a JSON object which is a response from an API call.  One version of the API gives a response with information nested into a large element called statuses and the other does not. I can print a specific key/value on the one that is not nested - but I am having trouble with the one that is.

Here are examples of each response:

First, with no nesting:

    [
      {
        "created_at": "xzy",
        "id": 123abc,
        "id_str": "123abc",
        "text": "Hello world"
        ...
        ...
        ...
      },
      {
        "created_at": "xzy",
        "id": 123abc,
        "id_str": "123abc",
        "text": "Hello world"
        ...
        ...
        ...
      }
    ]

This is put into php array with standard

`$string is defined below, I'm using a Twitter API wrapper link here

    $string = json_decode($twitter->setGetfield($getfield)
    ->buildOauth($url, $requestMethod)
    ->performRequest(),$assoc = TRUE);

I can return all of the id values with a simple foreach loop like this:

    foreach ($string as $items)
    {
      echo "The id from the response is: ".$items['id']."br />";
    }

This give me something like this:

The id from the response is: 123abc

The id from the response is: abc123

The id from the response is: xyz321

...

The other version of the API's reponse (the one I need to use) has similar information but stored in a large element statuses

    {
      "statuses": [
        {
          "created_at": "xzy",
          "id": 123abc,
          "id_str": "123abc",
          "text": "Hello world"
          ...
          ...
          ...
        },
        {
          "created_at": "xzy",
          "id": 123abc,
          "id_str": "123abc",
          "text": "Hello world"
          ...
          ...
          ...
        }
      ],
      "search_metadata": {...}
    }

When I try to loop through this json, I never get any output.

The json has been put into $string with json_decode, same as before.

It's obvious that the information is structured the same, just nested in statuses. Here is what I have tried:

    foreach($string['statuses'] as $items)
    {
      echo "The id's from the response are: ".$items['id']."br />";
    }

As well as:

    foreach($string[0] as $items)
    {
      echo "The id's from the response are: ".$items['id']."br />";
    }

And:

    foreach($string as $items)
        {
          foreach ($items as $statuses => $tweets)
          {
            if (is_array($tweets))
            {
              foreach ($tweets as $t => $v)
              {
                $output[$statuses.'_'.$t] = $v
              }
            }
            else {$output[$statuses] = $tweets;}
          }

        }

     print_r($output);

I simply need to loop through the contents of statuses as if it weren't even there like in the first response, but nothing is working.

Body:
This code actually does work. I just wasn't seeing any output from the json because the id is a data type that cannot be concatenated, at least not in the way I was doing it. There is an "id" element and a string version "id_str" and the string version showed up on my web page.

foreach($string['statuses'] as $items)
{
  echo "The id's from the response are: ".$items['id']."br />";
}

To be clear, this is the snippet that achieved my goal:

foreach($string['statuses'] as $items)
{
  echo "The id's from the response are: ".$items['id_str']."br />";
}


答:
Your code example is not written with async in mind.  You do not need to Parallel.ForEachat all.  HttpClient.GetAsync is already async there there is no point wrapping it in CPU bound tasks.

```<code>private readonly _httpClient = new HttpClient();

var tasks = new List<Task>();
foreach(var url in urls)
{
    var task = DoWork(url);
    tasks.Add(task);
}
await Task.WhenAll(tasks);

foreach(var task in tasks)
{
  if (task.Exception != null)
    Console.WriteLine(task.Exception.Message);
}

public async Task DoWork(string url)
{
  var json = await _httpClient.GetAsync(url);
  // do something with json
}
</code>```

While Parallel.ForEach() is a more efficient version of looping and using Task.Run() it should really only be used for Cpu Bound work (Task.Run Etiquette and Proper Usage). Calling a URL is not CPU bound work, it's I/O work (or more technically referred to as IO Completion Port work).

YOU'RE USING HTTPCLIENT WRONG AND IT IS DESTABILIZING YOUR SOFTWARE

Thanks for the HttpClient link. Wow. The fix seems like such an anti-pattern.

While it may seem like an anti-pattern, it's because the solution provided actually is an anti-pattern.  The HttpClient is using external resources to do it's job, so it should be disposed (it implements IDisposable) but at the same time it should be used as a singleton.  That poses the problem because there is no clean way to dispose of a singleton used as static property/field on a class.  However, since it was written by mirosoft, we should not be concerned that we always need to dispose of objects we create if the documentation states otherwise.

Since you point out that neither Parallel.ForEach nor Task.Run is suited for HttpClient work because it's I/O bound, what would you recommend?

Async/Await

I've added the million portion to the question

So you need to limit the number of parallel tasks so:

```<code>var maximumNumberofParallelOperations = 1;
foreach(var url in urls)
{
    var task = DoWork(url);
    tasks.Add(task);
    while (allTasks.Count(t => !t.IsCompleted) >= maximumNumberofParallelOperations )
    {
      await Task.WhenAny(allTasks);
    }
}
</code>```

Title: Parallel.For spins up an unexpected amount of threads

Body:
Your code example is not written with async in mind.  You do not need to Parallel.ForEachat all.  HttpClient.GetAsync is already async there there is no point wrapping it in CPU bound tasks.

private readonly _httpClient = new HttpClient();

var tasks = new List<Task>();
foreach(var url in urls)
{
    var task = DoWork(url);
    tasks.Add(task);
}
await Task.WhenAll(tasks);

foreach(var task in tasks)
{
  if (task.Exception != null)
    Console.WriteLine(task.Exception.Message);
}

public async Task DoWork(string url)
{
  var json = await _httpClient.GetAsync(url);
  // do something with json
}

While Parallel.ForEach() is a more efficient version of looping and using Task.Run() it should really only be used for Cpu Bound work (Task.Run Etiquette and Proper Usage). Calling a URL is not CPU bound work, it's I/O work (or more technically referred to as IO Completion Port work).

YOU'RE USING HTTPCLIENT WRONG AND IT IS DESTABILIZING YOUR SOFTWARE

Thanks for the HttpClient link. Wow. The fix seems like such an anti-pattern.

While it may seem like an anti-pattern, it's because the solution provided actually is an anti-pattern.  The HttpClient is using external resources to do it's job, so it should be disposed (it implements IDisposable) but at the same time it should be used as a singleton.  That poses the problem because there is no clean way to dispose of a singleton used as static property/field on a class.  However, since it was written by mirosoft, we should not be concerned that we always need to dispose of objects we create if the documentation states otherwise.

Since you point out that neither Parallel.ForEach nor Task.Run is suited for HttpClient work because it's I/O bound, what would you recommend?

Async/Await

I've added the million portion to the question

So you need to limit the number of parallel tasks so:

var maximumNumberofParallelOperations = 1;
foreach(var url in urls)
{
    var task = DoWork(url);
    tasks.Add(task);
    while (allTasks.Count(t => !t.IsCompleted) >= maximumNumberofParallelOperations )
    {
      await Task.WhenAny(allTasks);
    }
}


问:
Call Kotlin function with Lambda parameters in Java
How do I call Kotlin functions with lambdas in the parameter from a Java class.

Example

```<code>fun getToken(
        tokenUrl: String,
        onSuccess: (String) -> Unit,
        onError: (Error) -> Unit
    ): Provider {
        //Implementation
    }
</code>```

答:
This is for calling it within Kotlin, the question was edited to say "from Java" after I provided my answer. Leaving it here anyway in hope that it is useful.

You can call it like this

fun test() {

    getToken("asdf", { print(it) }, { println(it) })

    getToken("asdf", { print(it) }) { err -> println(err) }

    getToken("asdf", ::println, ::println)

    getToken("asdf", ::println) { println(it) }
}
```

Body:
How do I call Kotlin functions with lambdas in the parameter from a Java class.

Example

fun getToken(
        tokenUrl: String,
        onSuccess: (String) -> Unit,
        onError: (Error) -> Unit
    ): Provider {
        //Implementation
    }


问:
Comparing specific custom-defined attribute of user
For an XACML policy document I had in mind, I have a subject (user) and an object, each attached with a label. Let's call this myLabel = {[a,b,c], [1,2,3]}. I wish to do a comparison of parts of this label.

How can I define a subject and object to contain this label in the access request and policy to formulate a decision to compare this?

I wish to use XML rather than JSON or ALFA to declare the above.

答:
XACML (and ALFA) comes with a set of clearly defined data types and functions. For instance XACML defines the following datatypes:

string

integer

boolean

date...

There are 18 or so datatypes out-of-the-box.

To work on those datatypes, XACML defines hundreds of functions such as:

string-equal

string-greater-than

integer-equal

...

Attributes in XACML (e.g. label or role or department) must have a datatype. Attributes can be multi-valued. In other words, role = ["manager"] or role = ["manager", "employee", "janitor"]. Both are perfectly valid.

In your case, you are referring to a value structured as follows: {[a,b,c],[1,2,3]}. This is not a standard datatype. It's a complex object and as such would require further processing (in a PEP? in a PIP?). How were you thinking of passing it to the PDP?

Let's assume we have simple values e.g. label = '2'. To compare a user's label to a resource's label and grant access if they are equal, you would write the following:

ALFA

    /**
     * Control access based on labels
     */
    policy labelAccessControl{
        apply firstApplicable
        rule allowIfSameLabel{
            permit
            condition user.label == object.label
        }

    }
```

<h2>XACML XML equivalent</h2>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?><!--This file was generated by the
    ALFA Plugin for Eclipse from Axiomatics AB (http://www.axiomatics.com). --><!--Any modification to this file will
    be lost upon recompilation of the source ALFA file -->
<xacml3:Policy
    xmlns:xacml3="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17"
    PolicyId="http://axiomatics.com/alfa/identifier/com.axiomatics.labelAccessControl"
    RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:first-applicable"
    Version="1.0">
    <xacml3:Description>Control access based on labels</xacml3:Description>
    <xacml3:PolicyDefaults>
        <xacml3:XPathVersion>http://www.w3.org/TR/1999/REC-xpath-19991116
        </xacml3:XPathVersion>
    </xacml3:PolicyDefaults>
    <xacml3:Target />
    <xacml3:Rule Effect="Permit"
        RuleId="com.axiomatics.labelAccessControl.allowIfSameLabel">
        <xacml3:Description />
        <xacml3:Target />
        <xacml3:Condition>
            <xacml3:Apply
                FunctionId="urn:oasis:names:tc:xacml:3.0:function:any-of-any">
                <xacml3:Function
                    FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-equal" />
                <xacml3:AttributeDesignator
                    AttributeId="com.axiomatics.user.label"
                    Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"
                    DataType="http://www.w3.org/2001/XMLSchema#string"
                    MustBePresent="false" />
                <xacml3:AttributeDesignator
                    AttributeId="com.axiomatics.object.label"
                    Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource"
                    DataType="http://www.w3.org/2001/XMLSchema#string"
                    MustBePresent="false" />
            </xacml3:Apply>
        </xacml3:Condition>
    </xacml3:Rule>
</xacml3:Policy>
</code>```

Body:
XACML (and ALFA) comes with a set of clearly defined data types and functions. For instance XACML defines the following datatypes:

string

integer

boolean

date...

There are 18 or so datatypes out-of-the-box.

To work on those datatypes, XACML defines hundreds of functions such as:

string-equal

string-greater-than

integer-equal

...

Attributes in XACML (e.g. label or role or department) must have a datatype. Attributes can be multi-valued. In other words, role = ["manager"] or role = ["manager", "employee", "janitor"]. Both are perfectly valid.

In your case, you are referring to a value structured as follows: {[a,b,c],[1,2,3]}. This is not a standard datatype. It's a complex object and as such would require further processing (in a PEP? in a PIP?). How were you thinking of passing it to the PDP?

Let's assume we have simple values e.g. label = '2'. To compare a user's label to a resource's label and grant access if they are equal, you would write the following:

ALFA

    /**
     * Control access based on labels
     */
    policy labelAccessControl{
        apply firstApplicable
        rule allowIfSameLabel{
            permit
            condition user.label == object.label
        }

    }

XACML XML equivalent

<?xml version="1.0" encoding="UTF-8"?><!--This file was generated by the
    ALFA Plugin for Eclipse from Axiomatics AB (http://www.axiomatics.com). --><!--Any modification to this file will
    be lost upon recompilation of the source ALFA file -->
<xacml3:Policy
    xmlns:xacml3="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17"
    PolicyId="http://axiomatics.com/alfa/identifier/com.axiomatics.labelAccessControl"
    RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:first-applicable"
    Version="1.0">
    <xacml3:Description>Control access based on labels</xacml3:Description>
    <xacml3:PolicyDefaults>
        <xacml3:XPathVersion>http://www.w3.org/TR/1999/REC-xpath-19991116
        </xacml3:XPathVersion>
    </xacml3:PolicyDefaults>
    <xacml3:Target />
    <xacml3:Rule Effect="Permit"
        RuleId="com.axiomatics.labelAccessControl.allowIfSameLabel">
        <xacml3:Description />
        <xacml3:Target />
        <xacml3:Condition>
            <xacml3:Apply
                FunctionId="urn:oasis:names:tc:xacml:3.0:function:any-of-any">
                <xacml3:Function
                    FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-equal" />
                <xacml3:AttributeDesignator
                    AttributeId="com.axiomatics.user.label"
                    Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"
                    DataType="http://www.w3.org/2001/XMLSchema#string"
                    MustBePresent="false" />
                <xacml3:AttributeDesignator
                    AttributeId="com.axiomatics.object.label"
                    Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource"
                    DataType="http://www.w3.org/2001/XMLSchema#string"
                    MustBePresent="false" />
            </xacml3:Apply>
        </xacml3:Condition>
    </xacml3:Rule>
</xacml3:Policy>


问:
how to determine maximum route cost in a n high numeric pyramid
I've got a numeric pyramid like this

```<code>       7
      4 8
     1 8 9
    2 4 6 7
   4 6 7 4 9
  4 9 7 3 8 8

routes: 32
</code>```

every number indexed by how powerful in its line.

```<code> 0 ( 9 => 1 ) 1 ( 8 => 5 ) 2 ( 8 => 4 ) 3 ( 7 => 2 ) 4 ( 4 => 0 ) 5 ( 3 => 3 )
 0 ( 9 => 4 ) 1 ( 7 => 2 ) 2 ( 6 => 1 ) 3 ( 4 => 3 ) 4 ( 4 => 0 )
 0 ( 7 => 3 ) 1 ( 6 => 2 ) 2 ( 4 => 1 ) 3 ( 2 => 0 )
 0 ( 9 => 2 ) 1 ( 8 => 1 ) 2 ( 1 => 0 )
 0 ( 8 => 1 ) 1 ( 4 => 0 )
 0 ( 7 => 0 )
</code>```

in this pyramid there are 2^(n-1) routes (you can go 2 way form each number)
If the pyramid high this low, it's easy you can calculate all the routes, and compare to eachother. But if you have an 50 high pyramid with 562949953421312 routes, the problem little bit more difficult.

I thoght I start from the bottom beginning from the most powerful numbers, but soon i realized, the max route cost ain't necesserly start or end up in big numbers.

Then I thought maybe secoundary indexes (where can you go futher from a number) will help, but I didin't even implement that becouse I assumed its still uses much resources and not optimal.

And now i'm confused how to restart thinking about this problem... any advice appreciated

答:
I think that even if you use the Suggested Dijkstra's Algorithm, you still have to test every route. First of all because there is no single starting and end point, but there are 50 starting points for the end point. So the algorithm has to be tested 50 times.

And because every option has 2 paths, there is no way of skipping one. You can never rule out a path untill you are at the very end.

So I dont think there is a quicker way to find the longest path (so not the shortest as in Dijkstra's Algorithm) then to test all routes.

Body:
I've got a numeric pyramid like this

       7
      4 8
     1 8 9
    2 4 6 7
   4 6 7 4 9
  4 9 7 3 8 8

routes: 32

every number indexed by how powerful in its line.

 0 ( 9 => 1 ) 1 ( 8 => 5 ) 2 ( 8 => 4 ) 3 ( 7 => 2 ) 4 ( 4 => 0 ) 5 ( 3 => 3 )
 0 ( 9 => 4 ) 1 ( 7 => 2 ) 2 ( 6 => 1 ) 3 ( 4 => 3 ) 4 ( 4 => 0 )
 0 ( 7 => 3 ) 1 ( 6 => 2 ) 2 ( 4 => 1 ) 3 ( 2 => 0 )
 0 ( 9 => 2 ) 1 ( 8 => 1 ) 2 ( 1 => 0 )
 0 ( 8 => 1 ) 1 ( 4 => 0 )
 0 ( 7 => 0 )

in this pyramid there are 2^(n-1) routes (you can go 2 way form each number)
If the pyramid high this low, it's easy you can calculate all the routes, and compare to eachother. But if you have an 50 high pyramid with 562949953421312 routes, the problem little bit more difficult.

I thoght I start from the bottom beginning from the most powerful numbers, but soon i realized, the max route cost ain't necesserly start or end up in big numbers.

Then I thought maybe secoundary indexes (where can you go futher from a number) will help, but I didin't even implement that becouse I assumed its still uses much resources and not optimal.

And now i'm confused how to restart thinking about this problem... any advice appreciated