问:
Is there a way to connect an Azure firewall to a Front Door Premium Policy with Bicep?
I am trying to implement Azure Front Door Premium with a Web Application Firewall connection. I am able to create the Front Door both manually and through Bicep. However, when I try to connect to a WAF through Bicep, I'm not sure if it completely works.

The Bicep resource for my WAF looks like:

```<code>resource profiles_gbt_nprod_sandbox_FrontDoorTest_name_AzureFDTest_ac196269 'Microsoft.Cdn/profiles/securitypolicies@2020-09-01' = {
  parent: profiles_gbt_nprod_sandbox_FrontDoorTest_name_resource
  name: 'AzureFDTest-ac196269'
  properties: {
    parameters: {
      wafPolicy: {
        id: frontdoorwebapplicationfirewallpolicies_AzureFDTest_externalid
      }
      associations: [
        {
          domains: [
            {
              id: profiles_gbt_nprod_sandbox_FrontDoorTest_name_TestFDEndpoint.id
            }
          ]
          patternsToMatch: [
            '/*'
          ]
        }
      ]
      type: 'WebApplicationFirewall'
    }
  }
}
</code>```

To get: AzureFDTest-ac196269 I created the Front Door through Bicep, then manually connected the AzureFDTest policy and it generated this name.

When this is run, it looks like it connects to my Front Door in the Endpoint Manager:

But when I click on the AzureFDTest WAF policy it looks like:

And AzureFDTest is not listed. If I was to manually connect the WAF, this drop down menu would say AzureFDTest. Is this still working as expected or is there an issue with the way I have the resource written?

答:
You can connect an Azure Front Door Premium to a WAF in Bicep via a security policy as follows:

```<code>var frontdoorName = 'frontDoor'
var frontDoorSkuName = 'Premium_AzureFrontDoor'
var endpointName = 'endpoint'
var wafPolicyName = 'wafPolicy'
var securityPolicyName = 'securityPolicy'
param tags object

// Front Door CDN profile
resource profile 'Microsoft.Cdn/profiles@2020-09-01' = {
  name: frontdoorName
  location: 'global'
  sku: {
    name: frontDoorSkuName
  }
  tags: tags
}

// Azure Front Door endpoint
resource endpoint 'Microsoft.Cdn/profiles/afdEndpoints@2020-09-01' = {
  parent: profile
  name: endpointName
  location: 'Global'
  tags: tags
  properties: {
    originResponseTimeoutSeconds: 60
    enabledState: 'Enabled'
  }
}

// WAF policy using Azure managed rule sets
resource wafPolicy 'Microsoft.Network/FrontDoorWebApplicationFirewallPolicies@2020-11-01' = {
  name: wafPolicyName
  location: 'global'
  tags: tags
  sku: {
    name: frontDoorSkuName
  }
  properties: {
    policySettings: {
      enabledState: 'Enabled'
      mode: 'Prevention'
    }
    managedRules: {
      managedRuleSets: [
        {
          ruleSetType: 'Microsoft_DefaultRuleSet'
          ruleSetVersion: '1.1'
        }
        {
          ruleSetType: 'Microsoft_BotManagerRuleSet'
          ruleSetVersion: '1.0'
        }
      ]
    }
  }
}

// Security policy for Front Door which defines the WAF policy linking
resource securityPolicy 'Microsoft.Cdn/profiles/securityPolicies@2020-09-01' = {
  parent: profile
  name: securityPolicyName
  properties: {
    parameters: {
      type: 'WebApplicationFirewall'
      wafPolicy: {
        id: wafPolicy.id
      }
      associations: [
        {
          domains: [
            {
              id: endpoint.id
            }
          ]
          patternsToMatch: [
            '/*'
          ]
        }
      ]
    }
  }
}
</code>```

There is also an azure-quickstart-template available for this scenario:

Front Door Premium with Web Application Firewall and Microsoft-managed rule sets

Body:
I am trying to implement Azure Front Door Premium with a Web Application Firewall connection. I am able to create the Front Door both manually and through Bicep. However, when I try to connect to a WAF through Bicep, I'm not sure if it completely works.

The Bicep resource for my WAF looks like:

resource profiles_gbt_nprod_sandbox_FrontDoorTest_name_AzureFDTest_ac196269 'Microsoft.Cdn/profiles/securitypolicies@2020-09-01' = {
  parent: profiles_gbt_nprod_sandbox_FrontDoorTest_name_resource
  name: 'AzureFDTest-ac196269'
  properties: {
    parameters: {
      wafPolicy: {
        id: frontdoorwebapplicationfirewallpolicies_AzureFDTest_externalid
      }
      associations: [
        {
          domains: [
            {
              id: profiles_gbt_nprod_sandbox_FrontDoorTest_name_TestFDEndpoint.id
            }
          ]
          patternsToMatch: [
            '/*'
          ]
        }
      ]
      type: 'WebApplicationFirewall'
    }
  }
}

To get: AzureFDTest-ac196269 I created the Front Door through Bicep, then manually connected the AzureFDTest policy and it generated this name.

When this is run, it looks like it connects to my Front Door in the Endpoint Manager:

But when I click on the AzureFDTest WAF policy it looks like:

And AzureFDTest is not listed. If I was to manually connect the WAF, this drop down menu would say AzureFDTest. Is this still working as expected or is there an issue with the way I have the resource written?

Body:
You can connect an Azure Front Door Premium to a WAF in Bicep via a security policy as follows:

var frontdoorName = 'frontDoor'
var frontDoorSkuName = 'Premium_AzureFrontDoor'
var endpointName = 'endpoint'
var wafPolicyName = 'wafPolicy'
var securityPolicyName = 'securityPolicy'
param tags object

// Front Door CDN profile
resource profile 'Microsoft.Cdn/profiles@2020-09-01' = {
  name: frontdoorName
  location: 'global'
  sku: {
    name: frontDoorSkuName
  }
  tags: tags
}

// Azure Front Door endpoint
resource endpoint 'Microsoft.Cdn/profiles/afdEndpoints@2020-09-01' = {
  parent: profile
  name: endpointName
  location: 'Global'
  tags: tags
  properties: {
    originResponseTimeoutSeconds: 60
    enabledState: 'Enabled'
  }
}

// WAF policy using Azure managed rule sets
resource wafPolicy 'Microsoft.Network/FrontDoorWebApplicationFirewallPolicies@2020-11-01' = {
  name: wafPolicyName
  location: 'global'
  tags: tags
  sku: {
    name: frontDoorSkuName
  }
  properties: {
    policySettings: {
      enabledState: 'Enabled'
      mode: 'Prevention'
    }
    managedRules: {
      managedRuleSets: [
        {
          ruleSetType: 'Microsoft_DefaultRuleSet'
          ruleSetVersion: '1.1'
        }
        {
          ruleSetType: 'Microsoft_BotManagerRuleSet'
          ruleSetVersion: '1.0'
        }
      ]
    }
  }
}

// Security policy for Front Door which defines the WAF policy linking
resource securityPolicy 'Microsoft.Cdn/profiles/securityPolicies@2020-09-01' = {
  parent: profile
  name: securityPolicyName
  properties: {
    parameters: {
      type: 'WebApplicationFirewall'
      wafPolicy: {
        id: wafPolicy.id
      }
      associations: [
        {
          domains: [
            {
              id: endpoint.id
            }
          ]
          patternsToMatch: [
            '/*'
          ]
        }
      ]
    }
  }
}

There is also an azure-quickstart-template available for this scenario:

Front Door Premium with Web Application Firewall and Microsoft-managed rule sets


来源: stackexchange

问:
Docker not starting on Windows 11 with WSL 2
I'm trying to setup docker with WSL 2 to run a Dockerfile. I downloaded Docker Desktop, and when I tried to follow the quick start guide, I got the following error:

```<code>docker: error during connect: This error may indicate that the docker daemon is not running.: Post "http://%2F%2F.%2Fpipe%d2Fdocker_engine/v1.24/containers/create?name=repo": open //./pipe/docker_enginer: The system cannot find the file specified.
</code>```

I set com.docker.service to run in the Task Manager, and have run:

```<code>“c:\Program Files\Docker\Docker\DockerCli.exe” -SwitchDaemon
</code>```

I have also quit Docker Desktop and reopened it in admin mode, and I still get the message that Docker Desktop has stopped.

Please let me know if there's any other options, thanks!

答:
latest version 4.5.0 It won't work for me too, for me downgrade to 4.4.4 it worked. It may be problem with the latest version

for released note and older version Here

Note: You can install an older version and update to latest version 4.5.0

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to setup docker with WSL 2 to run a Dockerfile. I downloaded Docker Desktop, and when I tried to follow the quick start guide, I got the following error:

docker: error during connect: This error may indicate that the docker daemon is not running.: Post "http://%2F%2F.%2Fpipe%d2Fdocker_engine/v1.24/containers/create?name=repo": open //./pipe/docker_enginer: The system cannot find the file specified.

I set com.docker.service to run in the Task Manager, and have run:

“c:\Program Files\Docker\Docker\DockerCli.exe” -SwitchDaemon

I have also quit Docker Desktop and reopened it in admin mode, and I still get the message that Docker Desktop has stopped.

Please let me know if there's any other options, thanks!


问:
Get convex hull indices
I would like to calculate the convex hull of a set of points. Most algorithms I've found online return a list of points but I need a list of indices to the points.

To do this I've taken some existing code that calculates the points and tried changing it to instead return the points indices.

Original function to return a vector of convex hull points

```<code>#include <iostream>
#include <vector>
#include <tuple>

using namespace std;

typedef std::tuple<int, int> point;

// returns true if the three points make a counter-clockwise turn
bool ccw(const point &a, const point &b, const point &c) {
    return ((std::get<0>(b) - std::get<0>(a)) * (std::get<1>(c) - std::get<1>(a)))
           > ((std::get<1>(b) - std::get<1>(a)) * (std::get<0>(c) - std::get<0>(a)));
}

std::vector<point> convexHull(std::vector<point> p) {
    if (p.size() == 0) return std::vector<point>();
    std::sort(p.begin(), p.end(), [](point &a, point &b) {
        if (std::get<0>(a) < std::get<0>(b)) return true;
        return false;
    });

    std::vector<point> h;

    // lower hull
    for (const auto &pt: p) {
        while (h.size() >= 2 && !ccw(h.at(h.size() - 2), h.at(h.size() - 1), pt)) {
            h.pop_back();
        }
        h.push_back(pt);
    }

    // upper hull
    auto t = h.size() + 1;
    for (auto it = p.crbegin(); it != p.crend(); it = std::next(it)) {
        auto pt = *it;
        while (h.size() >= t && !ccw(h.at(h.size() - 2), h.at(h.size() - 1), pt)) {
            h.pop_back();
        }
        h.push_back(pt);
    }

    h.pop_back();
    return h;
}

int main() {
    using namespace std;

    vector<point> points = {
            make_pair(16, 3), make_pair(12, 17), make_pair(0, 6), make_pair(-4, -6), make_pair(16, 6),
            make_pair(16, -7), make_pair(16, -3), make_pair(17, -4), make_pair(5, 19), make_pair(19, -8),
            make_pair(3, 16), make_pair(12, 13), make_pair(3, -4), make_pair(17, 5), make_pair(-3, 15),
            make_pair(-3, -9), make_pair(0, 11), make_pair(-9, -3), make_pair(-4, -2), make_pair(12, 10)
    };

    auto hull = convexHull(points);

    for (const auto &point: hull) {
        std::cout << get<0>(point) << ", " << get<1>(point) << std::endl;
    }

    return 0;
}
</code>```

Result

```<code>-9, -3
-3, -9
19, -8
17, 5
12, 17
5, 19
-3, 15
</code>```

Ive taken this code and also added an indices vector. I've then tried adding the current index in each loop to this vector to return the indices based on the points passed into the function.

New function changed to return indices of points

```<code>#include <iostream>
#include <vector>
#include <tuple>

using namespace std;

typedef std::tuple<int, int> point;

// returns true if the three points make a counter-clockwise turn
bool ccw(const point &a, const point &b, const point &c) {
    return ((std::get<0>(b) - std::get<0>(a)) * (std::get<1>(c) - std::get<1>(a)))
           > ((std::get<1>(b) - std::get<1>(a)) * (std::get<0>(c) - std::get<0>(a)));
}

std::vector<int> convexHull(std::vector<point> p) {

    if (p.size() == 0) return {};
    std::sort(p.begin(), p.end(), [](point &a, point &b) {
        if (std::get<0>(a) < std::get<0>(b)) return true;
        return false;
    });

    std::vector<point> h;
    std::vector<int> indices;

    // lower hull
    for (int i = 0; i < p.size(); i++) {

        auto pt = p[i];
        while (h.size() >= 2 && !ccw(h.at(h.size() - 2), h.at(h.size() - 1), pt)) {
            h.pop_back();
            indices.pop_back();
        }
        h.push_back(pt);
        indices.push_back(i);
    }

    // upper hull
    auto t = h.size() + 1;

    for (int i = p.size() - 1; i >= 0; i--) {
        auto pt = p[i];
        while (h.size() >= t && !ccw(h.at(h.size() - 2), h.at(h.size() - 1), pt)) {
            h.pop_back();
            indices.pop_back();
        }
        h.push_back(pt);
        indices.push_back(i);
    }

    h.pop_back();
    indices.pop_back();
    return indices;
}

int main() {
    using namespace std;

    vector<point> points = {
            make_pair(16, 3), make_pair(12, 17), make_pair(0, 6), make_pair(-4, -6), make_pair(16, 6),
            make_pair(16, -7), make_pair(16, -3), make_pair(17, -4), make_pair(5, 19), make_pair(19, -8),
            make_pair(3, 16), make_pair(12, 13), make_pair(3, -4), make_pair(17, 5), make_pair(-3, 15),
            make_pair(-3, -9), make_pair(0, 11), make_pair(-9, -3), make_pair(-4, -2), make_pair(12, 10)
    };

    auto hull = convexHull(points);

    for (const auto &index: hull) {
        std::cout << get<0>(points[index]) << ", " << get<1>(points[index]) << std::endl;
    }

    return 0;
}
</code>```

Result

```<code>16, 3
-4, -6
12, 10
-9, -3
3, -4
19, -8
16, 6
</code>```

I expected to see the same results.

What am I missing?

答:
In your program/function you are sorting the points, then you calculate the indices along with the hull. And you return the indices (based on the sorted vector). You then apply the indices to the vector, which is not sorted.

Remember, C++ can pass by reference or value/copy (I am a bit vague maybe but I hope you get the idea; if you have no idea what I am talking about then that is a topic you have to learn about).

What you can do in the second program is: sort the vector before you print it. Maybe that will give you the expected result.

A better solution takes a bit more effort: Pass by reference

Title: Get convex hull indices

Body:
I would like to calculate the convex hull of a set of points. Most algorithms I've found online return a list of points but I need a list of indices to the points.

To do this I've taken some existing code that calculates the points and tried changing it to instead return the points indices.

Original function to return a vector of convex hull points

#include <iostream>
#include <vector>
#include <tuple>

using namespace std;

typedef std::tuple<int, int> point;

// returns true if the three points make a counter-clockwise turn
bool ccw(const point &a, const point &b, const point &c) {
    return ((std::get<0>(b) - std::get<0>(a)) * (std::get<1>(c) - std::get<1>(a)))
           > ((std::get<1>(b) - std::get<1>(a)) * (std::get<0>(c) - std::get<0>(a)));
}

std::vector<point> convexHull(std::vector<point> p) {
    if (p.size() == 0) return std::vector<point>();
    std::sort(p.begin(), p.end(), [](point &a, point &b) {
        if (std::get<0>(a) < std::get<0>(b)) return true;
        return false;
    });

    std::vector<point> h;

    // lower hull
    for (const auto &pt: p) {
        while (h.size() >= 2 && !ccw(h.at(h.size() - 2), h.at(h.size() - 1), pt)) {
            h.pop_back();
        }
        h.push_back(pt);
    }

    // upper hull
    auto t = h.size() + 1;
    for (auto it = p.crbegin(); it != p.crend(); it = std::next(it)) {
        auto pt = *it;
        while (h.size() >= t && !ccw(h.at(h.size() - 2), h.at(h.size() - 1), pt)) {
            h.pop_back();
        }
        h.push_back(pt);
    }

    h.pop_back();
    return h;
}

int main() {
    using namespace std;

    vector<point> points = {
            make_pair(16, 3), make_pair(12, 17), make_pair(0, 6), make_pair(-4, -6), make_pair(16, 6),
            make_pair(16, -7), make_pair(16, -3), make_pair(17, -4), make_pair(5, 19), make_pair(19, -8),
            make_pair(3, 16), make_pair(12, 13), make_pair(3, -4), make_pair(17, 5), make_pair(-3, 15),
            make_pair(-3, -9), make_pair(0, 11), make_pair(-9, -3), make_pair(-4, -2), make_pair(12, 10)
    };

    auto hull = convexHull(points);

    for (const auto &point: hull) {
        std::cout << get<0>(point) << ", " << get<1>(point) << std::endl;
    }

    return 0;
}

Result

-9, -3
-3, -9
19, -8
17, 5
12, 17
5, 19
-3, 15

Ive taken this code and also added an indices vector. I've then tried adding the current index in each loop to this vector to return the indices based on the points passed into the function.

New function changed to return indices of points

#include <iostream>
#include <vector>
#include <tuple>

using namespace std;

typedef std::tuple<int, int> point;

// returns true if the three points make a counter-clockwise turn
bool ccw(const point &a, const point &b, const point &c) {
    return ((std::get<0>(b) - std::get<0>(a)) * (std::get<1>(c) - std::get<1>(a)))
           > ((std::get<1>(b) - std::get<1>(a)) * (std::get<0>(c) - std::get<0>(a)));
}

std::vector<int> convexHull(std::vector<point> p) {

    if (p.size() == 0) return {};
    std::sort(p.begin(), p.end(), [](point &a, point &b) {
        if (std::get<0>(a) < std::get<0>(b)) return true;
        return false;
    });

    std::vector<point> h;
    std::vector<int> indices;

    // lower hull
    for (int i = 0; i
= 2 && !ccw(h.at(h.size() - 2), h.at(h.size() - 1), pt)) {
            h.pop_back();
            indices.pop_back();
        }
        h.push_back(pt);
        indices.push_back(i);
    }

    // upper hull
    auto t = h.size() + 1;

    for (int i = p.size() - 1; i >= 0; i--) {
        auto pt = p[i];
        while (h.size() >= t && !ccw(h.at(h.size() - 2), h.at(h.size() - 1), pt)) {
            h.pop_back();
            indices.pop_back();
        }
        h.push_back(pt);
        indices.push_back(i);
    }

    h.pop_back();
    indices.pop_back();
    return indices;
}

int main() {
    using namespace std;

    vector<point> points = {
            make_pair(16, 3), make_pair(12, 17), make_pair(0, 6), make_pair(-4, -6), make_pair(16, 6),
            make_pair(16, -7), make_pair(16, -3), make_pair(17, -4), make_pair(5, 19), make_pair(19, -8),
            make_pair(3, 16), make_pair(12, 13), make_pair(3, -4), make_pair(17, 5), make_pair(-3, 15),
            make_pair(-3, -9), make_pair(0, 11), make_pair(-9, -3), make_pair(-4, -2), make_pair(12, 10)
    };

    auto hull = convexHull(points);

    for (const auto &index: hull) {
        std::cout << get<0>(points[index]) << ", " << get<1>(points[index]) << std::endl;
    }

    return 0;
}

Result

16, 3
-4, -6
12, 10
-9, -3
3, -4
19, -8
16, 6

I expected to see the same results.

What am I missing?


问:
Checking a parent container for children javascript
Just wondering how you can check an element (i.e. a div container) for elements (i.e. buttons) and if they exist, remove them?

If I append a child to a div, how can I on the next look check for that child or those type of children? i.e. adding;

example = document.getElementById('div');
example.appendChild(aButton);

//loop to look for aButton / button type in example div
```

Cheers

答:
You could use children and then loop through the children. For example if you have a div with the following set up:

```<code><div id='div'>
    <input type='button'>
    <p>here</p>
    <a href="#"></a>
</div>
</code>```

You could then get the children an loop through them like this:

```<code>var example = document.getElementById("div");
var children = example.children;
alert(children.length);
for(var i = 0; i < children.length; i++)
{
    alert(children[i].tagName);
}
</code>```

And as to remove them it would be as simple as

```<code>example.removeChild( children[i] );
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Just wondering how you can check an element (i.e. a div container) for elements (i.e. buttons) and if they exist, remove them?

If I append a child to a div, how can I on the next look check for that child or those type of children? i.e. adding;

example = document.getElementById('div');
example.appendChild(aButton);

//loop to look for aButton / button type in example div

Cheers

Body:
You could use children and then loop through the children. For example if you have a div with the following set up:

<div id='div'>
    <input type='button'>
    <p>here</p>
    <a href="#"></a>
</div>

You could then get the children an loop through them like this:

var example = document.getElementById("div");
var children = example.children;
alert(children.length);
for(var i = 0; i < children.length; i++)
{
    alert(children[i].tagName);
}

And as to remove them it would be as simple as

example.removeChild( children[i] );


问:
SSIS OData Source - Not all columns visible
I am using OData Source from SSIS Toolbox to load data out from Dynamics AX but not all columns are visible.

E.g. my entity 'ProductionInformationDVL' is available via OData and it contains the Columns 'ProductId','ProductName' and 'ProdStatus'.
But the preview of SSIS does not show the column 'ProdStatus'. I'd like to get all available columns.

Any ideas? Thank you!

答:
We are having the same issue using SSIS 2019 and querying Azure DevOps with the odata source component. When we query using the web browsers (or fetching the $metadata) the enum columns are returned but not using the odata source in SSIS.

We ended writing source script components using C# and HttpClient for such odata queries in order to return the Azure DevOps entities containing enums.


问:
How to add RTL support for Material UI React
I'm building an LTR application and I want to add RTL support.
The application is based on top of Material UI React.
I'm able to rotate the application to RTL since I'm using CSS Flex Box, just by adding dir="rtl" to the body. I also added direction="rtl" to the theme as mentioned here.

However not everything was changed.

Let's take this as an example :

As you can see here I have padding left to the text element.
In the RTL version, since everything was reversed the padding left has no effect in the UI, I mean it must be padding right to show the small space between the two element :

It seems that I'm doing something wrong because in Material UI documentation here this feature must be out of the box after adding this snippet and wrap the component around it.

This is my Parent component App :

```<code>import React, { PureComponent } from "react";
import { theme } from "./styling/theme";
import Routes from "./Routes";
// Redux
import { Provider } from "react-redux";
import store from "./app/store";

import LoadingBar from "react-redux-loading-bar";
// CSS
import { MuiThemeProvider } from "@material-ui/core/styles";
// import { ThemeProvider } from "@material-ui/styles";
import { create } from "jss";
import rtl from "jss-rtl";
import JssProvider from "react-jss/lib/JssProvider";
// import { StylesProvider, jssPreset } from "@material-ui/styles";
import { createGenerateClassName, jssPreset } from "@material-ui/core/styles";
import { themeObject, colors } from "./styling/theme";
// Helpers
import get from "lodash/get";

// Configure JSS
const jss = create({ plugins: [...jssPreset().plugins, rtl()] });
const generateClassName = createGenerateClassName();

function RTL(props) {
  return (
    <JssProvider jss={jss} generateClassName={generateClassName}>
      {
        props.children
      }
    </JssProvider>
  );
}

class App extends PureComponent {
  render() {
    const isRtl = get(store, "classified.language.rtl", false);
    return (
      <Provider store={store}>
        <RTL>
          <MuiThemeProvider
            theme={
              isRtl
                ? { ...theme, direction: "rtl" }
                : { ...theme, direction: "ltr" }
            }
          >
            <LoadingBar
              style={{
                backgroundColor: colors.primary[500],
                height: themeObject.spacing.unit,
                zIndex: 9999
              }}
            />
            <Routes />
          </MuiThemeProvider>
        </RTL>
      </Provider>
    );
  }
}

export default App;
</code>```

And this is an example of my components (The one in the pictures above : CLList) :

```<code>import React, { Component } from "react";
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";
// Helpers
import isFunction from "lodash/isFunction";
import cloneDeep from "lodash/cloneDeep";

import styles from "./CLList.styles";

const defaultImg = "IMAGE_URL_HERE";
class CLList extends Component {
  static propTypes = {
    classes: PropTypes.object.isRequired,
    items: PropTypes.arrayOf(
      PropTypes.shape({
        img: PropTypes.string,
        name: PropTypes.string
      })
    ).isRequired,
    onClick: PropTypes.func
  };
  render() {
    const { classes, items, onClick } = this.props;
    return (
      <ul className={classes.list}>
        {items.map((item, key) => (
          <li
            className={classes.item}
            onClick={() => isFunction(onClick) && onClick(cloneDeep(item))}
            key={key}
          >
            <img
              className={classes.image}
              src={item.img || defaultImg}
              alt={item.name}
              title={item.name}
            />
            <span className={classes.label}>{item.name}</span>
          </li>
        ))}
      </ul>
    );
  }
}

export default withStyles(styles)(CLList);
</code>```

And the last file is the CSS for CLList :

```<code>import { colors } from "../..";
const styles = theme => ({
  list: {
    display: "flex",
    flexDirection: "column",
    listStyle: "none",
    padding: 5,
    margin: 0,
    "& > li:not(:last-child)": {
      marginBottom: 10
    }
  },
  item: {
    flex: 1,
    display: "flex",
    cursor: "pointer",
    "&:hover": {
      backgroundColor: colors.primary[50]
    }
  },
  image: {
    flex: "0 0 15%",
    maxWidth: "40px",
    maxHeight: "40px"
  },
  label: {
    flex: "1",
    alignSelf: "center",
    paddingLeft: 20
  }
});

export default styles;
</code>```

I'm expecting that paddingLeft of label to be => paddingRight. Is this possible ? Is it a feature out of the box ? Or should I just use RTL-CSS-JS and wrap all my styles object when the body contains dir="RTL" to change automatically the style ?

I'm also so confused between these two libraries :

@material-ui/core/styles

@material-ui/styles

Should I use the first or the second one ? What is the difference ?

Thanks for you time.

EDIT 1 :

I used rtlCSSJS on my CSS Object and I get the expected result. But I'm not sure if this is the best way to do it.
The CSS of CLList now look like this :

```<code>import rtlCSSJS from "rtl-css-js";
import { colors } from "../..";
const defaultDir = document.body.getAttribute("dir");
const styles = theme =>
  defaultDir === 'rtl' ? rtlCSSJS({...CSS_HERE....}) : {...CSS_HERE....};
export default styles;
</code>```

答:
```<code>import React, { useState, createContext, useMemo, useEffect } from 'react';
import PropTypes from 'prop-types';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import { SnackbarProvider } from 'notistack';
import { Box } from '@mui/material';
import languageList from 'shared/languageList';
import { useTranslation } from 'react-i18next';
import rtlPlugin from 'stylis-plugin-rtl';
import { CacheProvider } from '@emotion/react';
import createCache from '@emotion/cache';
import { prefixer } from 'stylis';

export const AppThemeContext = createContext({});

const AppTheme = ({ children }) => {
  const { i18n } = useTranslation();
  const [dir, setDir] = useState(i18n.language === 'ar' ? 'rtl' : 'ltr');
  const [language, setLanguage] = useState(i18n.language);

  const toggleLanguage = async (language) => {
    setLanguage(language.value);
    switch (language.value) {
      case 'ar':
        document.body.setAttribute('dir', 'rtl');
        setDir('rtl');
        await i18n.changeLanguage('ar');
        break;
      case 'en':
        document.body.setAttribute('dir', 'ltr');
        setDir('ltr');
        await i18n.changeLanguage('en');
        break;
    }
  };

  const theme = useMemo(() => {
    const arabicFont = '""serif", "Arial", "sans-serif"';
    const englishFont = '"Roboto","Helvetica","Arial",sans-serif';

    const typography = {
      button: {
        textTransform: 'capitalize',
      },
      fontSize: dir === 'rtl' ? 15 : 14,
      fontFamily: dir === 'rtl' ? arabicFont : englishFont,
    };

    return createTheme({
      direction: dir,
      typography,
    });
  }, [dir, colorMode]);

  const direction = useMemo(() => {
    return dir === 'ltr' ? 'left' : 'right';
  }, [dir]);
  // this is the most important part
  const cacheRtl = useMemo(() => {
    if (dir === 'rtl') {
      return createCache({
        key: 'muirtl',
        stylisPlugins: [prefixer, rtlPlugin],
      });
    } else {
      return createCache({ key: 'css' });
    }
  }, [dir]);

  useEffect(async () => {
    await toggleLanguage({ value: language });
  }, []);

  const toggleColorMode = () =>
    setColorMode((prevMode) => (prevMode === 'light' ? 'dark' : 'light'));

  return (
    <AppThemeContext.Provider
      value={{
        language,
        toggleLanguage,
        languageList,
        direction,
        colorMode,
        toggleColorMode,
      }}>
      <Box component="main">
        <CacheProvider value={cacheRtl}>
          <ThemeProvider theme={theme}>
            <SnackbarProvider maxSnack={3}>{children}</SnackbarProvider>
          </ThemeProvider>
        </CacheProvider>
      </Box>
    </AppThemeContext.Provider>
  );
};

AppTheme.propTypes = {
  children: PropTypes.any,
};

export default AppTheme;
</code>```

Important notes

I use MUI version 5

MUI version 5 uses emotion css as default styling engine

CacheProvider is used to configure the RTL or LTR

ThemeProvider must be wrapped inside CacheProvider

make sure to use useMemo when passing the value to CacheProvider or if you're going to use other Providers when changing default styling engine like ( StylesProvider for JSS & StyleSheetManager for styled-components )

Body:
I'm building an LTR application and I want to add RTL support.
The application is based on top of Material UI React.
I'm able to rotate the application to RTL since I'm using CSS Flex Box, just by adding dir="rtl" to the body. I also added direction="rtl" to the theme as mentioned here.

However not everything was changed.

Let's take this as an example :

As you can see here I have padding left to the text element.
In the RTL version, since everything was reversed the padding left has no effect in the UI, I mean it must be padding right to show the small space between the two element :

It seems that I'm doing something wrong because in Material UI documentation here this feature must be out of the box after adding this snippet and wrap the component around it.

This is my Parent component App :

import React, { PureComponent } from "react";
import { theme } from "./styling/theme";
import Routes from "./Routes";
// Redux
import { Provider } from "react-redux";
import store from "./app/store";

import LoadingBar from "react-redux-loading-bar";
// CSS
import { MuiThemeProvider } from "@material-ui/core/styles";
// import { ThemeProvider } from "@material-ui/styles";
import { create } from "jss";
import rtl from "jss-rtl";
import JssProvider from "react-jss/lib/JssProvider";
// import { StylesProvider, jssPreset } from "@material-ui/styles";
import { createGenerateClassName, jssPreset } from "@material-ui/core/styles";
import { themeObject, colors } from "./styling/theme";
// Helpers
import get from "lodash/get";

// Configure JSS
const jss = create({ plugins: [...jssPreset().plugins, rtl()] });
const generateClassName = createGenerateClassName();

function RTL(props) {
  return (
    <JssProvider jss={jss} generateClassName={generateClassName}>
      {
        props.children
      }
    </JssProvider>
  );
}

class App extends PureComponent {
  render() {
    const isRtl = get(store, "classified.language.rtl", false);
    return (
      <Provider store={store}>
        <RTL>
          <MuiThemeProvider
            theme={
              isRtl
                ? { ...theme, direction: "rtl" }
                : { ...theme, direction: "ltr" }
            }
          >
            <LoadingBar
              style={{
                backgroundColor: colors.primary[500],
                height: themeObject.spacing.unit,
                zIndex: 9999
              }}
            />
            <Routes />
          </MuiThemeProvider>
        </RTL>
      </Provider>
    );
  }
}

export default App;

And this is an example of my components (The one in the pictures above : CLList) :

import React, { Component } from "react";
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";
// Helpers
import isFunction from "lodash/isFunction";
import cloneDeep from "lodash/cloneDeep";

import styles from "./CLList.styles";

const defaultImg = "IMAGE_URL_HERE";
class CLList extends Component {
  static propTypes = {
    classes: PropTypes.object.isRequired,
    items: PropTypes.arrayOf(
      PropTypes.shape({
        img: PropTypes.string,
        name: PropTypes.string
      })
    ).isRequired,
    onClick: PropTypes.func
  };
  render() {
    const { classes, items, onClick } = this.props;
    return (

        {items.map((item, key) => (

 isFunction(onClick) && onClick(cloneDeep(item))}
            key={key}
          >

            {item.name}

        ))}

    );
  }
}

export default withStyles(styles)(CLList);

And the last file is the CSS for CLList :

import { colors } from "../..";
const styles = theme => ({
  list: {
    display: "flex",
    flexDirection: "column",
    listStyle: "none",
    padding: 5,
    margin: 0,
    "& > li:not(:last-child)": {
      marginBottom: 10
    }
  },
  item: {
    flex: 1,
    display: "flex",
    cursor: "pointer",
    "&:hover": {
      backgroundColor: colors.primary[50]
    }
  },
  image: {
    flex: "0 0 15%",
    maxWidth: "40px",
    maxHeight: "40px"
  },
  label: {
    flex: "1",
    alignSelf: "center",
    paddingLeft: 20
  }
});

export default styles;

I'm expecting that paddingLeft of label to be => paddingRight. Is this possible ? Is it a feature out of the box ? Or should I just use RTL-CSS-JS and wrap all my styles object when the body contains dir="RTL" to change automatically the style ?

I'm also so confused between these two libraries :

@material-ui/core/styles

@material-ui/styles

Should I use the first or the second one ? What is the difference ?

Thanks for you time.

EDIT 1 :

I used rtlCSSJS on my CSS Object and I get the expected result. But I'm not sure if this is the best way to do it.
The CSS of CLList now look like this :

import rtlCSSJS from "rtl-css-js";
import { colors } from "../..";
const defaultDir = document.body.getAttribute("dir");
const styles = theme =>
  defaultDir === 'rtl' ? rtlCSSJS({...CSS_HERE....}) : {...CSS_HERE....};
export default styles;

Body:
import React, { useState, createContext, useMemo, useEffect } from 'react';
import PropTypes from 'prop-types';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import { SnackbarProvider } from 'notistack';
import { Box } from '@mui/material';
import languageList from 'shared/languageList';
import { useTranslation } from 'react-i18next';
import rtlPlugin from 'stylis-plugin-rtl';
import { CacheProvider } from '@emotion/react';
import createCache from '@emotion/cache';
import { prefixer } from 'stylis';

export const AppThemeContext = createContext({});

const AppTheme = ({ children }) => {
  const { i18n } = useTranslation();
  const [dir, setDir] = useState(i18n.language === 'ar' ? 'rtl' : 'ltr');
  const [language, setLanguage] = useState(i18n.language);

  const toggleLanguage = async (language) => {
    setLanguage(language.value);
    switch (language.value) {
      case 'ar':
        document.body.setAttribute('dir', 'rtl');
        setDir('rtl');
        await i18n.changeLanguage('ar');
        break;
      case 'en':
        document.body.setAttribute('dir', 'ltr');
        setDir('ltr');
        await i18n.changeLanguage('en');
        break;
    }
  };

  const theme = useMemo(() => {
    const arabicFont = '""serif", "Arial", "sans-serif"';
    const englishFont = '"Roboto","Helvetica","Arial",sans-serif';

    const typography = {
      button: {
        textTransform: 'capitalize',
      },
      fontSize: dir === 'rtl' ? 15 : 14,
      fontFamily: dir === 'rtl' ? arabicFont : englishFont,
    };

    return createTheme({
      direction: dir,
      typography,
    });
  }, [dir, colorMode]);

  const direction = useMemo(() => {
    return dir === 'ltr' ? 'left' : 'right';
  }, [dir]);
  // this is the most important part
  const cacheRtl = useMemo(() => {
    if (dir === 'rtl') {
      return createCache({
        key: 'muirtl',
        stylisPlugins: [prefixer, rtlPlugin],
      });
    } else {
      return createCache({ key: 'css' });
    }
  }, [dir]);

  useEffect(async () => {
    await toggleLanguage({ value: language });
  }, []);

  const toggleColorMode = () =>
    setColorMode((prevMode) => (prevMode === 'light' ? 'dark' : 'light'));

  return (
    <AppThemeContext.Provider
      value={{
        language,
        toggleLanguage,
        languageList,
        direction,
        colorMode,
        toggleColorMode,
      }}>
      <Box component="main">
        <CacheProvider value={cacheRtl}>
          <ThemeProvider theme={theme}>
            <SnackbarProvider maxSnack={3}>{children}</SnackbarProvider>
          </ThemeProvider>
        </CacheProvider>
      </Box>
    </AppThemeContext.Provider>
  );
};

AppTheme.propTypes = {
  children: PropTypes.any,
};

export default AppTheme;

Important notes

I use MUI version 5

MUI version 5 uses emotion css as default styling engine

CacheProvider is used to configure the RTL or LTR

ThemeProvider must be wrapped inside CacheProvider

make sure to use useMemo when passing the value to CacheProvider or if you're going to use other Providers when changing default styling engine like ( StylesProvider for JSS & StyleSheetManager for styled-components )


问:
.Net System.Text.Json: how to deserialize to a class constructor where parameters nullability doesn't match class properties nullability
I have a bunch of Json files that I want to deserialize to immutable classes.

E.g. a Json file like this :

{
  "Prop1": 5,
  "Prop3": {
    "NestedProp1": "something",
    "NestedProp3": 42
  }
}
```
<p>Should be deserialized to classes like that:</p>
<pre class="lang-cs prettyprint-override"><code>public class Outer
{
  public int Prop1 { get; }
  public int Prop2 { get; }
  public Inner Prop3 { get; }
  public string Prop4 { get; }
  public Outer(int prop1, int? prop2, Inner prop3, string? prop4)
  {
    Prop1 = prop1;
    Prop2 = prop2 ?? GetSensibleRuntimeProp2Default();
    Prop3 = prop3;
    Prop4 = prop4 ?? GetSensibleRuntimeProp4Default();
  }
...
}

public class Inner
{
  public string NestedProp1 { get; }
  public int NestedProp2 { get; }
  public int NestedProp3 { get; }
  public Inner(string nestedProp1, int? nestedProp2, int nestedProp3)
  {
    NestedProp1 = nestedProp1;
    NestedProp2 = nestedProp2 ?? GetSensibleRuntimeNestedProp2Default();
    NestedProp3 = nestedProp3;
  }
...
}
</code>```

As one can see, some constructor parameters are nullable (ref or value types), so that some default value can be injected in case the value is not specified in the Json file. However the matching properties in the classes are not nullable.

The problem is System.Text.Json deserialization requires that constructor parameters and properties have the exact same type so if I try this I get an exception stating this requirement which is indeed documented.

How would I be able to work around this limitation? Could I somehow inject code in the deserilization process to insert my own policy for deserializing objects (while letting the default process handle values and arrays)?

I am dealing with existing classes and Json and I am not allowed to make changes like adding a nullable property to the classes in order to match the constructor parameter.
The thing actually worked using Newtonsoft.Json and I am asked to convert it to using System.Text.Json.

I wrote come code that uses reflection to deserialize the first level object in the Json file using the target class constructor that best matches the Json object properties. It looks like that:

public static object CreateInstance(Type targetType, JsonObject prototype, JsonSerializerOptions serializerOptions)
{
    var constructors = GetEligibleConstructors(targetType);
    var prototypePropertySet = prototype.Select(kvp => kvp.Key)
          .ToImmutableHashSet(StringComparer.CurrentCultureIgnoreCase);
    var bestMatch = FindBestConstructorMatch(prototypePropertySet, constructors);
    if (bestMatch is null)
        throw new NoSuitableConstructorFoundException($"COuld not find a suitable constructor to instanciate {targetType.FullName} from \"{prototype.ToJsonString()}\"");
    var valuedParams = GetParameterValues(bestMatch, prototype, serializerOptions);
    return bestMatch.Constructor.Invoke(bestMatch.Parameters.Select(p => valuedParams[p.Name]).ToArray());
}
```

(I'm deserializing from a JsonObject and not from text but I don't think it's relevant to the issue)

So basically:

get all public constructors of the target type,

find the one that has the most parameters in common with the Json object properties

get the parameters values from the Json using standard System.Text.Json deserialization

Invoke the constructor

Obviously this method limits me to the first level object since all the child properties will be handled by standard deserialization.

I would like to be able to do that recursively by using a similar code in a JsonConverter that would be called on deserializing Json objects while the deserialization of Json arrays or primitive values would be left to the standard converters.

答:
Following @dbc advice, I used the JsonConverterFactory pattern to address my issue.

Here are the two classes I wrote.
The converter itself:

public class CustomObjectConverter<T> : JsonConverter<T> where T : class
{
    private record struct UnmatchedParameterInfo(string Name, Type Type, bool AcceptsNullValue);
    private record struct MatchedParameterInfo(string Name, Type Type, object Value);

    // ConstructorMatcher is a helper class that will keep track of
    // Json properties that can be matched with the parameters of
    // a specific constructor as they are read from the reader
    private class ConstructorMatcher
    {
        public ConstructorInfo ConstructorInfo { get; }
        private Dictionary<string, UnmatchedParameterInfo> UnmatchedParameters { get; }
        private Dictionary<string, MatchedParameterInfo> MatchedParameters { get; } = new();

        private ImmutableList<string> ParameterList { get; }

        public ConstructorMatcher(ConstructorInfo constructorInfo)
        {
            ConstructorInfo = constructorInfo ?? throw new ArgumentNullException(nameof(constructorInfo));
            var parameters = constructorInfo.GetParameters();
            if (parameters.Any(p => p.Name is null))
                throw new Exception("<useful exception message>");
            ParameterList = parameters.Select(p => p.Name!).ToImmutableList();
            UnmatchedParameters =
                 parameters.ToDictionary(
                              p => p.Name!,
                              p => new UnmatchedParameterInfo(
                                           p.Name!,
                                           p.ParameterType,
                                           AcceptsNullValue(p.ParameterType)),
                              StringComparer.CurrentCultureIgnoreCase);
        }

        // Checks is null can be assigned to a certain type
        private bool AcceptsNullValue(Type type)
        {
            // This is improvable as it doesn't use reference types
            // nullability information
            return type.IsClass || Nullable.GetUnderlyingType(type) is not null;
        }

        public int MatchCount => MatchedParameters.Count;

        public int UnmatchedCount => UnmatchedParameters.Count;

        // Checks if the constructor still has a yet unmatched parameter
        // named "name"
        public bool HasParameter(string name) => UnmatchedParameters.ContainsKey(name);

        // Returns the type that the constructor expects for parameter "name".
        // The converter needs this because it has to know beforehand the type
        // of the property it is about to deserialize.
        public Type GetTypeForParameter(string name)
        {
            return UnmatchedParameters.TryGetValue(name, out var info)
                       ? info.Type
                       : throw new Exception("<useful exception message>");
        }

        // Binds a value to a constructor parameter
        public void AddParameterValue(string name, Type type, object? value)
        {
            if (!UnmatchedParameters.Remove(name, out var unmatchedParameterInfo))
                throw new Exception("<useful exception message>");
            if (unmatchedParameterInfo.Type != type)
                throw new Exception("<useful exception message>");
            MatchedParameters.Add(unmatchedParameterInfo.Name,
                                  new MatchedParameterInfo(
                                         unmatchedParameterInfo.Name,
                                         unmatchedParameterInfo.Type,
                                         value));
        }

        // Checks if the constructor has some unbound parameters
        // that won't accept null values
        public bool HasNonNullableUnmatchedParameters => UnmatchedParameters.Values.Any(upi => !upi.AcceptsNullValue);

        // Gets parameter values in the righ order for constructor invocation
        public object?[] GetInvocationParameters()
        {
            return ParameterList.Select(parameterName => MatchedParameters.TryGetValue(parameterName, out var mpi)
                                                             ? mpi.Value
                                                             : null)
                                .ToArray();
        }
    }

    // For each Json property:
    // - read the Json property name,
    // - eliminate constructors that don't have a parameter with
    //   a compatible name
    // - get the expected type for this property (end throw if all
    //   constructors don't expect the same type for the same property)
    // - deserialize the property value to the expected type
    // - bind the deserialized value to the matching parameter of each
    //   candidate constructor
    // When all properties are read, invoke the constructor that has the
    // most parameters bound to values, with the less unbound parameters
    // (with the condition that all unbound parameters can be bound to null)
    public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType != JsonTokenType.StartObject)
        {
            throw new JsonException();
        }

        var candidates = typeToConvert.GetConstructors().Select(ci => new ConstructorMatcher(ci)).ToImmutableList();

        while (reader.Read())
        {
            if (reader.TokenType == JsonTokenType.EndObject)
            {
                var bestCandidate = candidates
                                    .Where(c => !c.HasNonNullableUnmatchedParameters)
                                    .OrderByDescending(c => c.MatchCount)
                                              .ThenBy(c => c.UnmatchedCount)
                                              .FirstOrDefault() ??
                                    throw new NoSuitableConstructorFoundException("<useful exception message>");
                return (T?)bestCandidate.ConstructorInfo.Invoke(bestCandidate.GetInvocationParameters());
            }

            if (reader.TokenType != JsonTokenType.PropertyName)
            {
                throw new JsonException();
            }

            var propertyName = reader.GetString() ?? throw new Exception("<useful exception message>");

            candidates = candidates.Where(c => c.HasParameter(propertyName)).ToImmutableList();
            var possibleTypes = candidates.Select(c => c.GetTypeForParameter(propertyName))
                                          .Distinct()
                                          .ToArray();
            if (possibleTypes.Length > 1)
                throw new AmbiguousConfigurationException("<useful exception message>");

            var propertyType = possibleTypes[0];

            var value = JsonSerializer.Deserialize(ref reader, propertyType, options);

            foreach (var constructorMatcher in candidates)
            {
                constructorMatcher.AddParameterValue(propertyName, propertyType, value);
            }
        }

        throw new JsonException();
    }

    public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
    {
        writer.WriteStartObject();
        foreach (var property in typeof(T).GetProperties())
        {
            writer.WritePropertyName(options.PropertyNamingPolicy?.ConvertName(property.Name) ?? property.Name);
            JsonSerializer.Serialize(value, options);
        }
        writer.WriteEndObject();
    }
}
```
<p>Now for the converter factory the problem we have to address is "to which target types exactly our converter should be applied?"</p>
<p>We'd want to handle all Json objects but there is nothing that clearly ties
Json objects with a certain class of CLR types specifically.
Json objects can be deserialized to POCO classes but also dictionaries
and structs. Conversely collection classes will typically be deserialized from Json arrays.
Some Json objects can also be handled by custom converters from the serialization options.
I'm quite sure our strategy can be improved as we limited ourselves to what was sufficient in our specific situation.</p>
<p>We chose to apply our converter to all classes that don't implement IEnumerable (the main limitation being we dont handle structs, I guess).</p>
<p>Furthermore, if we find a more specific converter in the serialization options that can convert the target type, we will apply it instead of our converter.</p>
<pre class="lang-cs prettyprint-override"><code>public class CustomObjectConverterFactory: JsonConverterFactory
{
    public override bool CanConvert(Type typeToConvert)
    {
        return typeToConvert.IsClass && !typeof(IEnumerable).IsAssignableFrom(typeToConvert);
    }

    public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options)
    {
        var moreSpecificConverter = options.Converters.FirstOrDefault(c => c != this && c.CanConvert(typeToConvert));
        if (moreSpecificConverter is not null)
            return moreSpecificConverter is JsonConverterFactory moreSpecificFactory
                       ? moreSpecificFactory.CreateConverter(typeToConvert, options)
                       : moreSpecificConverter;
        return (JsonConverter?)Activator.CreateInstance(typeof(CustomObjectConverter<>).MakeGenericType(typeToConvert));
    }
}
</code>```

Body:
I have a bunch of Json files that I want to deserialize to immutable classes.

E.g. a Json file like this :

{
  "Prop1": 5,
  "Prop3": {
    "NestedProp1": "something",
    "NestedProp3": 42
  }
}

Should be deserialized to classes like that:

public class Outer
{
  public int Prop1 { get; }
  public int Prop2 { get; }
  public Inner Prop3 { get; }
  public string Prop4 { get; }
  public Outer(int prop1, int? prop2, Inner prop3, string? prop4)
  {
    Prop1 = prop1;
    Prop2 = prop2 ?? GetSensibleRuntimeProp2Default();
    Prop3 = prop3;
    Prop4 = prop4 ?? GetSensibleRuntimeProp4Default();
  }
...
}

public class Inner
{
  public string NestedProp1 { get; }
  public int NestedProp2 { get; }
  public int NestedProp3 { get; }
  public Inner(string nestedProp1, int? nestedProp2, int nestedProp3)
  {
    NestedProp1 = nestedProp1;
    NestedProp2 = nestedProp2 ?? GetSensibleRuntimeNestedProp2Default();
    NestedProp3 = nestedProp3;
  }
...
}

As one can see, some constructor parameters are nullable (ref or value types), so that some default value can be injected in case the value is not specified in the Json file. However the matching properties in the classes are not nullable.

The problem is System.Text.Json deserialization requires that constructor parameters and properties have the exact same type so if I try this I get an exception stating this requirement which is indeed documented.

How would I be able to work around this limitation? Could I somehow inject code in the deserilization process to insert my own policy for deserializing objects (while letting the default process handle values and arrays)?

I am dealing with existing classes and Json and I am not allowed to make changes like adding a nullable property to the classes in order to match the constructor parameter.
The thing actually worked using Newtonsoft.Json and I am asked to convert it to using System.Text.Json.

I wrote come code that uses reflection to deserialize the first level object in the Json file using the target class constructor that best matches the Json object properties. It looks like that:

public static object CreateInstance(Type targetType, JsonObject prototype, JsonSerializerOptions serializerOptions)
{
    var constructors = GetEligibleConstructors(targetType);
    var prototypePropertySet = prototype.Select(kvp => kvp.Key)
          .ToImmutableHashSet(StringComparer.CurrentCultureIgnoreCase);
    var bestMatch = FindBestConstructorMatch(prototypePropertySet, constructors);
    if (bestMatch is null)
        throw new NoSuitableConstructorFoundException($"COuld not find a suitable constructor to instanciate {targetType.FullName} from \"{prototype.ToJsonString()}\"");
    var valuedParams = GetParameterValues(bestMatch, prototype, serializerOptions);
    return bestMatch.Constructor.Invoke(bestMatch.Parameters.Select(p => valuedParams[p.Name]).ToArray());
}

(I'm deserializing from a JsonObject and not from text but I don't think it's relevant to the issue)

So basically:

get all public constructors of the target type,

find the one that has the most parameters in common with the Json object properties

get the parameters values from the Json using standard System.Text.Json deserialization

Invoke the constructor

Obviously this method limits me to the first level object since all the child properties will be handled by standard deserialization.

I would like to be able to do that recursively by using a similar code in a JsonConverter that would be called on deserializing Json objects while the deserialization of Json arrays or primitive values would be left to the standard converters.

Body:
Following @dbc advice, I used the JsonConverterFactory pattern to address my issue.

Here are the two classes I wrote.
The converter itself:

public class CustomObjectConverter<T> : JsonConverter<T> where T : class
{
    private record struct UnmatchedParameterInfo(string Name, Type Type, bool AcceptsNullValue);
    private record struct MatchedParameterInfo(string Name, Type Type, object Value);

    // ConstructorMatcher is a helper class that will keep track of
    // Json properties that can be matched with the parameters of
    // a specific constructor as they are read from the reader
    private class ConstructorMatcher
    {
        public ConstructorInfo ConstructorInfo { get; }
        private Dictionary<string, UnmatchedParameterInfo> UnmatchedParameters { get; }
        private Dictionary<string, MatchedParameterInfo> MatchedParameters { get; } = new();

        private ImmutableList<string> ParameterList { get; }

        public ConstructorMatcher(ConstructorInfo constructorInfo)
        {
            ConstructorInfo = constructorInfo ?? throw new ArgumentNullException(nameof(constructorInfo));
            var parameters = constructorInfo.GetParameters();
            if (parameters.Any(p => p.Name is null))
                throw new Exception("<useful exception message>");
            ParameterList = parameters.Select(p => p.Name!).ToImmutableList();
            UnmatchedParameters =
                 parameters.ToDictionary(
                              p => p.Name!,
                              p => new UnmatchedParameterInfo(
                                           p.Name!,
                                           p.ParameterType,
                                           AcceptsNullValue(p.ParameterType)),
                              StringComparer.CurrentCultureIgnoreCase);
        }

        // Checks is null can be assigned to a certain type
        private bool AcceptsNullValue(Type type)
        {
            // This is improvable as it doesn't use reference types
            // nullability information
            return type.IsClass || Nullable.GetUnderlyingType(type) is not null;
        }

        public int MatchCount => MatchedParameters.Count;

        public int UnmatchedCount => UnmatchedParameters.Count;

        // Checks if the constructor still has a yet unmatched parameter
        // named "name"
        public bool HasParameter(string name) => UnmatchedParameters.ContainsKey(name);

        // Returns the type that the constructor expects for parameter "name".
        // The converter needs this because it has to know beforehand the type
        // of the property it is about to deserialize.
        public Type GetTypeForParameter(string name)
        {
            return UnmatchedParameters.TryGetValue(name, out var info)
                       ? info.Type
                       : throw new Exception("<useful exception message>");
        }

        // Binds a value to a constructor parameter
        public void AddParameterValue(string name, Type type, object? value)
        {
            if (!UnmatchedParameters.Remove(name, out var unmatchedParameterInfo))
                throw new Exception("<useful exception message>");
            if (unmatchedParameterInfo.Type != type)
                throw new Exception("<useful exception message>");
            MatchedParameters.Add(unmatchedParameterInfo.Name,
                                  new MatchedParameterInfo(
                                         unmatchedParameterInfo.Name,
                                         unmatchedParameterInfo.Type,
                                         value));
        }

        // Checks if the constructor has some unbound parameters
        // that won't accept null values
        public bool HasNonNullableUnmatchedParameters => UnmatchedParameters.Values.Any(upi => !upi.AcceptsNullValue);

        // Gets parameter values in the righ order for constructor invocation
        public object?[] GetInvocationParameters()
        {
            return ParameterList.Select(parameterName => MatchedParameters.TryGetValue(parameterName, out var mpi)
                                                             ? mpi.Value
                                                             : null)
                                .ToArray();
        }
    }

    // For each Json property:
    // - read the Json property name,
    // - eliminate constructors that don't have a parameter with
    //   a compatible name
    // - get the expected type for this property (end throw if all
    //   constructors don't expect the same type for the same property)
    // - deserialize the property value to the expected type
    // - bind the deserialized value to the matching parameter of each
    //   candidate constructor
    // When all properties are read, invoke the constructor that has the
    // most parameters bound to values, with the less unbound parameters
    // (with the condition that all unbound parameters can be bound to null)
    public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType != JsonTokenType.StartObject)
        {
            throw new JsonException();
        }

        var candidates = typeToConvert.GetConstructors().Select(ci => new ConstructorMatcher(ci)).ToImmutableList();

        while (reader.Read())
        {
            if (reader.TokenType == JsonTokenType.EndObject)
            {
                var bestCandidate = candidates
                                    .Where(c => !c.HasNonNullableUnmatchedParameters)
                                    .OrderByDescending(c => c.MatchCount)
                                              .ThenBy(c => c.UnmatchedCount)
                                              .FirstOrDefault() ??
                                    throw new NoSuitableConstructorFoundException("<useful exception message>");
                return (T?)bestCandidate.ConstructorInfo.Invoke(bestCandidate.GetInvocationParameters());
            }

            if (reader.TokenType != JsonTokenType.PropertyName)
            {
                throw new JsonException();
            }

            var propertyName = reader.GetString() ?? throw new Exception("<useful exception message>");

            candidates = candidates.Where(c => c.HasParameter(propertyName)).ToImmutableList();
            var possibleTypes = candidates.Select(c => c.GetTypeForParameter(propertyName))
                                          .Distinct()
                                          .ToArray();
            if (possibleTypes.Length > 1)
                throw new AmbiguousConfigurationException("<useful exception message>");

            var propertyType = possibleTypes[0];

            var value = JsonSerializer.Deserialize(ref reader, propertyType, options);

            foreach (var constructorMatcher in candidates)
            {
                constructorMatcher.AddParameterValue(propertyName, propertyType, value);
            }
        }

        throw new JsonException();
    }

    public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
    {
        writer.WriteStartObject();
        foreach (var property in typeof(T).GetProperties())
        {
            writer.WritePropertyName(options.PropertyNamingPolicy?.ConvertName(property.Name) ?? property.Name);
            JsonSerializer.Serialize(value, options);
        }
        writer.WriteEndObject();
    }
}

Now for the converter factory the problem we have to address is "to which target types exactly our converter should be applied?"

We'd want to handle all Json objects but there is nothing that clearly ties
Json objects with a certain class of CLR types specifically.
Json objects can be deserialized to POCO classes but also dictionaries
and structs. Conversely collection classes will typically be deserialized from Json arrays.
Some Json objects can also be handled by custom converters from the serialization options.
I'm quite sure our strategy can be improved as we limited ourselves to what was sufficient in our specific situation.

We chose to apply our converter to all classes that don't implement IEnumerable (the main limitation being we dont handle structs, I guess).

Furthermore, if we find a more specific converter in the serialization options that can convert the target type, we will apply it instead of our converter.

public class CustomObjectConverterFactory: JsonConverterFactory
{
    public override bool CanConvert(Type typeToConvert)
    {
        return typeToConvert.IsClass && !typeof(IEnumerable).IsAssignableFrom(typeToConvert);
    }

    public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options)
    {
        var moreSpecificConverter = options.Converters.FirstOrDefault(c => c != this && c.CanConvert(typeToConvert));
        if (moreSpecificConverter is not null)
            return moreSpecificConverter is JsonConverterFactory moreSpecificFactory
                       ? moreSpecificFactory.CreateConverter(typeToConvert, options)
                       : moreSpecificConverter;
        return (JsonConverter?)Activator.CreateInstance(typeof(CustomObjectConverter<>).MakeGenericType(typeToConvert));
    }
}


问:
Array.indexOf() return confusing results JavaScript
So I am trying to return a number for what week day it is given a string like 'tue'.
So i figured I would get the index of the string 'tue' in an array that contains the week days

week_days = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];

var date = new Date();

var first_month_day = String(new Date(date.getFullYear(), date.getMonth(), 1).toString().slice(0, 4).toLowerCase());

var indexOf = week_days.indexOf(first_month_day)
return indexOf;
```
<p><code>first_month_day</code> = <code>'tue'</code> as of today when I evaluate that code.
therfore I would assume that running</p>
<pre class="lang-js prettyprint-override"><code>week_day.indexOf(first_month_day)
</code>```

would return 2 but instead i get -1. So if instead of running the above if i do

week_days.indexOf('tue')
```

I get the desired 2 I have ensured that first_month_day is a string using typeof and everything I am just at a loss as to why it keeps returning -1 whenever I know it exists inside the array.

答:
As Robin Zigmond said, .slice(0, 4) will give a string with a length of 4, so you were getting "tue " from firstMonthDay  instead of "tue".

const weekDays = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];

const date = new Date();

const firstMonthDay = String(new Date(date.getFullYear(), date.getMonth(), 1).toString().slice(0, 3).toLowerCase());

const index = weekDays.indexOf(firstMonthDay);
console.log(index);```

Body:
So I am trying to return a number for what week day it is given a string like 'tue'.
So i figured I would get the index of the string 'tue' in an array that contains the week days

week_days = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];

var date = new Date();

var first_month_day = String(new Date(date.getFullYear(), date.getMonth(), 1).toString().slice(0, 4).toLowerCase());

var indexOf = week_days.indexOf(first_month_day)
return indexOf;

first_month_day = 'tue' as of today when I evaluate that code.
therfore I would assume that running

week_day.indexOf(first_month_day)

would return 2 but instead i get -1. So if instead of running the above if i do

week_days.indexOf('tue')

I get the desired 2 I have ensured that first_month_day is a string using typeof and everything I am just at a loss as to why it keeps returning -1 whenever I know it exists inside the array.


问:
Python : Dictionary and .format
could someone help me understand why this works and the latter does not?
For instance,

```<code>def main():
    diction = {"DDL":"Defined Data Language","EDW":"Enterprise Data Warehouse","ACID": "Atomicity,Consistency,Isolation,Durability"}
    TEST=diction.get("DDL")

print(" Meaning:{}".format(TEST))
</code>```

The above code works however if I make the variable TEST = diction[0] the code fails. Could anyone explain this to me?

P.S. the error is the following

```<code>Traceback (most recent call last):
  File "C:\Program Files\Sublime Text\Python_Executables\second_mod.py", line 8, in <module>
    main()
  File "C:\Program Files\Sublime Text\Python_Executables\second_mod.py", line 4, in main
    TEST=diction[0]
KeyError: 0
[Finished in 80ms]
</code>```

Thank you ahead of time!

答:
because you are dealing with dictionaries and they are made of set of key,values and you can get the value by given keys and not with indexes.

But if you must get a value using index , you can convert the dictionary to list :

```<code>TEST = list(diction.values())[0]
</code>```

Title: Python : Dictionary and .format

Body:
could someone help me understand why this works and the latter does not?
For instance,

def main():
    diction = {"DDL":"Defined Data Language","EDW":"Enterprise Data Warehouse","ACID": "Atomicity,Consistency,Isolation,Durability"}
    TEST=diction.get("DDL")

print(" Meaning:{}".format(TEST))

The above code works however if I make the variable TEST = diction[0] the code fails. Could anyone explain this to me?

P.S. the error is the following

Traceback (most recent call last):
  File "C:\Program Files\Sublime Text\Python_Executables\second_mod.py", line 8, in <module>
    main()
  File "C:\Program Files\Sublime Text\Python_Executables\second_mod.py", line 4, in main
    TEST=diction[0]
KeyError: 0
[Finished in 80ms]

Thank you ahead of time!

Body:
because you are dealing with dictionaries and they are made of set of key,values and you can get the value by given keys and not with indexes.

But if you must get a value using index , you can convert the dictionary to list :

TEST = list(diction.values())[0]


问:
Bind a JavaScript array to a Vue 3 component's v-for in template to update DOM
I've just started learning Vue 3 and I'm trying to create a Vue Component that is bound to a JavaScript array ** (defined and modified outside Vue)** and uses that array to render a v-for list of child Vue components.

In the code below, I have my "layer-container" Vue component that has a template that renders a list of "layer-item" subcomponents using data from a JavaScript array layersGlobal. If you run it, you can see that the items are rendered properly from the initial data in the array, but when the array is updated (after 1 second, via a push() call in setInterval()) the list is not rerendered, and the DOM is not updated.

    <layer-container />

```

Am I doing something wrong, or misinterpreting how Vue is reactive with arrays? Is it possible to bind a JavaScript array declared outside Vue to a Vue component like this, or can/should I be doing it another way?

I've looked around for a solution and found some example code that works in Vue 2, but not Vue 3.

答:
Reactive data must be updated within the context of the component. You probably want to call setTimeout inside of the component's definition and update the reactive variable this.layers instead of the global array.

app.component("layer-container", {
    /* ... */
    data: function () {
        return {
            layers: layersGlobal
        }
    },
    mounted() {
        setTimeout(() => this.layers.push({ name: "Layer C" }), 1000)
    }
})
```
<p>Alternatively, if you need to update the data from outside the component, you need to explicitly define your global array as a <strong>reactive</strong> object, using the <code>ref()</code> function.</p>
```const layersGlobal = Vue.ref([ /* ... */ ])

setTimeout(() => layersGlobal.value.push({ name: "Layer C" }), 1000)
```

Note the .value property being used to access the actual object.

Body:
I've just started learning Vue 3 and I'm trying to create a Vue Component that is bound to a JavaScript array ** (defined and modified outside Vue)** and uses that array to render a v-for list of child Vue components.

In the code below, I have my "layer-container" Vue component that has a template that renders a list of "layer-item" subcomponents using data from a JavaScript array layersGlobal. If you run it, you can see that the items are rendered properly from the initial data in the array, but when the array is updated (after 1 second, via a push() call in setInterval()) the list is not rerendered, and the DOM is not updated.

    <layer-container />

Am I doing something wrong, or misinterpreting how Vue is reactive with arrays? Is it possible to bind a JavaScript array declared outside Vue to a Vue component like this, or can/should I be doing it another way?

I've looked around for a solution and found some example code that works in Vue 2, but not Vue 3.

Body:
Reactive data must be updated within the context of the component. You probably want to call setTimeout inside of the component's definition and update the reactive variable this.layers instead of the global array.

app.component("layer-container", {
    /* ... */
    data: function () {
        return {
            layers: layersGlobal
        }
    },
    mounted() {
        setTimeout(() => this.layers.push({ name: "Layer C" }), 1000)
    }
})

Alternatively, if you need to update the data from outside the component, you need to explicitly define your global array as a reactive object, using the ref() function.

const layersGlobal = Vue.ref([ /* ... */ ])

setTimeout(() => layersGlobal.value.push({ name: "Layer C" }), 1000)

Note the .value property being used to access the actual object.


问:
Hello I do NOT understand these 'not defined' errors and 'no while
So, I am a noob to coding in C# but I have used unity, which uses C#. Well get all these errors:

```<code>Compilation error (line 8, col 6): } expected
Compilation error (line 13, col 33): Empty character literal
Compilation error (line 21, col 9): Invalid token 'while' in class, record, struct, or interface member declaration
Compilation error (line 21, col 16): Type expected
Compilation error (line 21, col 16): Tuple must contain at least two elements.
Compilation error (line 21, col 16): ) expected
Compilation error (line 21, col 16): Invalid token 'true' in class, record, struct, or interface member declaration
Compilation error (line 23, col 17): Invalid token '=' in class, record, struct, or interface member declaration
Compilation error (line 23, col 17): Invalid token '=' in class, record, struct, or interface member declaration
Compilation error (line 23, col 29): Invalid token '(' in class, record, struct, or interface member declaration
Compilation error (line 23, col 30): Tuple must contain at least two elements.
Compilation error (line 23, col 31): Invalid token ';' in class, record, struct, or interface member declaration
Compilation error (line 25, col 23): Type expected
Compilation error (line 25, col 23): Syntax error, ',' expected
Compilation error (line 26, col 22): Syntax error, '>' expected
Compilation error (line 26, col 22): Tuple must contain at least two elements.
Compilation error (line 26, col 22): ) expected
Compilation error (line 26, col 22): Invalid token ';' in class, record, struct, or interface member declaration
Compilation error (line 27, col 16): Invalid token '=' in class, record, struct, or interface member declaration
Compilation error (line 27, col 16): Invalid token '=' in class, record, struct, or interface member declaration
Compilation error (line 27, col 23): Tuple must contain at least two elements.
Compilation error (line 28, col 26): Invalid token '(' in class, record, struct, or interface member declaration
Compilation error (line 28, col 29): Tuple must contain at least two elements.
Compilation error (line 28, col 30): Invalid token ';' in class, record, struct, or interface member declaration
Compilation error (line 29, col 20): Tuple must contain at least two elements.
Compilation error (line 29, col 20): ) expected
Compilation error (line 29, col 20): Invalid token '!=' in class, record, struct, or interface member declaration
Compilation error (line 31, col 20): Invalid token '=' in class, record, struct, or interface member declaration
Compilation error (line 31, col 20): Invalid token '=' in class, record, struct, or interface member declaration
Compilation error (line 31, col 32): Identifier expected
Compilation error (line 31, col 36): Identifier expected
Compilation error (line 35, col 1): Top-level statements must precede namespace and type declarations.
Compilation error (line 34, col 14): 'else' cannot start a statement.
Compilation error (line 34, col 14): Syntax error, '(' expected
Compilation error (line 34, col 14): Invalid expression term 'else'
Compilation error (line 34, col 14): ) expected
Compilation error (line 34, col 14): Invalid expression term 'else'
Compilation error (line 34, col 14): ; expected
Compilation error (line 67, col 9): Type or namespace definition, or end-of-file expected
Compilation error (line 69, col 5): Type or namespace definition, or end-of-file expected
Compilation error (line 70, col 1): Type or namespace definition, or end-of-file expected
Compilation error (line 31, col 22): Method must have a return type
Compilation error (line 31, col 22): 'Demo.Demo(all, ch)' must declare a body because it is not marked abstract, extern, or partial
Compilation error (line 31, col 29): The type or namespace name 'all' could not be found (are you missing a using directive or an assembly reference?)
Compilation error (line 31, col 34): The type or namespace name 'ch' could not be found (are you missing a using directive or an assembly reference?)
Compilation error (line 27, col 24): The type 'Demo' already contains a definition for 'val'
Compilation error (line 7, col 17): The entry point of the program is global code; ignoring 'Demo.Main()' entry point.
Compilation error (line 37, col 17): The name 'cmd' does not exist in the current context
Compilation error (line 37, col 23): The name 'all' does not exist in the current context
Compilation error (line 38, col 17): The name 'all' does not exist in the current context
Compilation error (line 39, col 17): The name 'all' does not exist in the current context
Compilation error (line 39, col 23): The name 'Concat' does not exist in the current context
Compilation error (line 39, col 30): The name 'all' does not exist in the current context
Compilation error (line 39, col 35): The name 'ch' does not exist in the current context
Compilation error (line 42, col 17): The name 'ch' does not exist in the current context
Compilation error (line 44, col 21): The name 'cmd' does not exist in the current context
Compilation error (line 46, col 38): The name 'path2' does not exist in the current context
Compilation error (line 48, col 67): The name 'path2' does not exist in the current context
Compilation error (line 19, col 14): The field 'Demo.ch' is never used
Compilation error (line 27, col 24): The field 'Demo.val' is never used
Compilation error (line 14, col 24): The field 'Demo.all' is assigned but its value is never used
Compilation error (line 15, col 24): The field 'Demo.cmd' is assigned but its value is never used
Compilation error (line 18, col 13): The field 'Demo.val' is assigned but its value is never used
</code>```

And here is my source code:

```<code>using System;
using System.IO;
using System.Text;

class Demo
{
    static void Main()
    {
        public string path = @"SCRIPT.vis";
        public string path2 = @"header.asm";

        private char previous = '';
        private string all = "";
        private string cmd = "";

        Stream s = new FileStream(@"data.vi", FileMode.Open);
        int val = 0;
        char ch;

        while (true)
        {
            val = s.ReadByte();

            if (val < 0)
                break;
            ch = (char)val;
            Console.Write(ch);
            if (ch != "(")
            {
               all = Concat(all, ch);

            }
            else
            {
                cmd = all;
                all = "";
                all = Concat(all, ch);

            }
            if (ch == ")")
            {
                if (cmd == "os.Start")
                {
                    if (!File.Exists(path2))
                    {
                         using (StreamWriter sw = File.CreateText(path2))
                         {
                             sw.WriteLine("section .multiboot_header");
                             sw.WriteLine("header_start:");
                             sw.WriteLine("     dd 0xe85250d6");
                             sw.WriteLine("     dd 0");
                             sw.WriteLine("     dd header_end - header_start");
                             sw.WriteLine("     dd 0x100000000 - (0xe85250d6 + 0 + (header_end - header_start))");
                             sw.WriteLine("     ");
                             sw.WriteLine("     dw 0");
                             sw.WriteLine("     dw 0");
                             sw.WriteLine("     dd 8");
                             sw.WriteLine("header_end:");

                         }
                    }
                }
            }
        }
        Console.WriteLine();
    }
}
</code>```

So, thanks for the help!
BTW this is for a compiler for stuff. Also, if for some reason you need this I am running (well testing for errors) my code on an online compiler, DOTNETFIDDLE.

答:
this

```<code>    public string path = @"SCRIPT.vis";
    public string path2 = @"header.asm";

    private char previous = '';
    private string all = "";
    private string cmd = "";
</code>```

should be

```<code>    string path = @"SCRIPT.vis";
    string path2 = @"header.asm";

    char previous = '';
    string all = "";
    string cmd = "";
</code>```

also since ch is a char this

```<code>    if (ch != "(")
</code>```

should be

```<code>    if (ch != '(')
</code>```

Body:
So, I am a noob to coding in C# but I have used unity, which uses C#. Well get all these errors:

Compilation error (line 8, col 6): } expected
Compilation error (line 13, col 33): Empty character literal
Compilation error (line 21, col 9): Invalid token 'while' in class, record, struct, or interface member declaration
Compilation error (line 21, col 16): Type expected
Compilation error (line 21, col 16): Tuple must contain at least two elements.
Compilation error (line 21, col 16): ) expected
Compilation error (line 21, col 16): Invalid token 'true' in class, record, struct, or interface member declaration
Compilation error (line 23, col 17): Invalid token '=' in class, record, struct, or interface member declaration
Compilation error (line 23, col 17): Invalid token '=' in class, record, struct, or interface member declaration
Compilation error (line 23, col 29): Invalid token '(' in class, record, struct, or interface member declaration
Compilation error (line 23, col 30): Tuple must contain at least two elements.
Compilation error (line 23, col 31): Invalid token ';' in class, record, struct, or interface member declaration
Compilation error (line 25, col 23): Type expected
Compilation error (line 25, col 23): Syntax error, ',' expected
Compilation error (line 26, col 22): Syntax error, '>' expected
Compilation error (line 26, col 22): Tuple must contain at least two elements.
Compilation error (line 26, col 22): ) expected
Compilation error (line 26, col 22): Invalid token ';' in class, record, struct, or interface member declaration
Compilation error (line 27, col 16): Invalid token '=' in class, record, struct, or interface member declaration
Compilation error (line 27, col 16): Invalid token '=' in class, record, struct, or interface member declaration
Compilation error (line 27, col 23): Tuple must contain at least two elements.
Compilation error (line 28, col 26): Invalid token '(' in class, record, struct, or interface member declaration
Compilation error (line 28, col 29): Tuple must contain at least two elements.
Compilation error (line 28, col 30): Invalid token ';' in class, record, struct, or interface member declaration
Compilation error (line 29, col 20): Tuple must contain at least two elements.
Compilation error (line 29, col 20): ) expected
Compilation error (line 29, col 20): Invalid token '!=' in class, record, struct, or interface member declaration
Compilation error (line 31, col 20): Invalid token '=' in class, record, struct, or interface member declaration
Compilation error (line 31, col 20): Invalid token '=' in class, record, struct, or interface member declaration
Compilation error (line 31, col 32): Identifier expected
Compilation error (line 31, col 36): Identifier expected
Compilation error (line 35, col 1): Top-level statements must precede namespace and type declarations.
Compilation error (line 34, col 14): 'else' cannot start a statement.
Compilation error (line 34, col 14): Syntax error, '(' expected
Compilation error (line 34, col 14): Invalid expression term 'else'
Compilation error (line 34, col 14): ) expected
Compilation error (line 34, col 14): Invalid expression term 'else'
Compilation error (line 34, col 14): ; expected
Compilation error (line 67, col 9): Type or namespace definition, or end-of-file expected
Compilation error (line 69, col 5): Type or namespace definition, or end-of-file expected
Compilation error (line 70, col 1): Type or namespace definition, or end-of-file expected
Compilation error (line 31, col 22): Method must have a return type
Compilation error (line 31, col 22): 'Demo.Demo(all, ch)' must declare a body because it is not marked abstract, extern, or partial
Compilation error (line 31, col 29): The type or namespace name 'all' could not be found (are you missing a using directive or an assembly reference?)
Compilation error (line 31, col 34): The type or namespace name 'ch' could not be found (are you missing a using directive or an assembly reference?)
Compilation error (line 27, col 24): The type 'Demo' already contains a definition for 'val'
Compilation error (line 7, col 17): The entry point of the program is global code; ignoring 'Demo.Main()' entry point.
Compilation error (line 37, col 17): The name 'cmd' does not exist in the current context
Compilation error (line 37, col 23): The name 'all' does not exist in the current context
Compilation error (line 38, col 17): The name 'all' does not exist in the current context
Compilation error (line 39, col 17): The name 'all' does not exist in the current context
Compilation error (line 39, col 23): The name 'Concat' does not exist in the current context
Compilation error (line 39, col 30): The name 'all' does not exist in the current context
Compilation error (line 39, col 35): The name 'ch' does not exist in the current context
Compilation error (line 42, col 17): The name 'ch' does not exist in the current context
Compilation error (line 44, col 21): The name 'cmd' does not exist in the current context
Compilation error (line 46, col 38): The name 'path2' does not exist in the current context
Compilation error (line 48, col 67): The name 'path2' does not exist in the current context
Compilation error (line 19, col 14): The field 'Demo.ch' is never used
Compilation error (line 27, col 24): The field 'Demo.val' is never used
Compilation error (line 14, col 24): The field 'Demo.all' is assigned but its value is never used
Compilation error (line 15, col 24): The field 'Demo.cmd' is assigned but its value is never used
Compilation error (line 18, col 13): The field 'Demo.val' is assigned but its value is never used

And here is my source code:

using System;
using System.IO;
using System.Text;

class Demo
{
    static void Main()
    {
        public string path = @"SCRIPT.vis";
        public string path2 = @"header.asm";

        private char previous = '';
        private string all = "";
        private string cmd = "";

        Stream s = new FileStream(@"data.vi", FileMode.Open);
        int val = 0;
        char ch;

        while (true)
        {
            val = s.ReadByte();

            if (val < 0)
                break;
            ch = (char)val;
            Console.Write(ch);
            if (ch != "(")
            {
               all = Concat(all, ch);

            }
            else
            {
                cmd = all;
                all = "";
                all = Concat(all, ch);

            }
            if (ch == ")")
            {
                if (cmd == "os.Start")
                {
                    if (!File.Exists(path2))
                    {
                         using (StreamWriter sw = File.CreateText(path2))
                         {
                             sw.WriteLine("section .multiboot_header");
                             sw.WriteLine("header_start:");
                             sw.WriteLine("     dd 0xe85250d6");
                             sw.WriteLine("     dd 0");
                             sw.WriteLine("     dd header_end - header_start");
                             sw.WriteLine("     dd 0x100000000 - (0xe85250d6 + 0 + (header_end - header_start))");
                             sw.WriteLine("     ");
                             sw.WriteLine("     dw 0");
                             sw.WriteLine("     dw 0");
                             sw.WriteLine("     dd 8");
                             sw.WriteLine("header_end:");

                         }
                    }
                }
            }
        }
        Console.WriteLine();
    }
}

So, thanks for the help!
BTW this is for a compiler for stuff. Also, if for some reason you need this I am running (well testing for errors) my code on an online compiler, DOTNETFIDDLE.

Body:
this

    public string path = @"SCRIPT.vis";
    public string path2 = @"header.asm";

    private char previous = '';
    private string all = "";
    private string cmd = "";

should be

    string path = @"SCRIPT.vis";
    string path2 = @"header.asm";

    char previous = '';
    string all = "";
    string cmd = "";

also since ch is a char this

    if (ch != "(")

should be

    if (ch != '(')


答: Dictionaries are unordered, you can't get key value by index, you can only get key value by key name, example: TEST = diction["DDL"]

Title: Python : Dictionary and .format


答:
It throws an error because you are trying to get the value of the dictionary identified by the key 0. Yet, you don't have any 0 in your dictionary.

It would work if you included it.

```<code>diction = {"DDL":"Defined Data Language",
           "EDW":"Enterprise Data Warehouse",
           "ACID": "Atomicity,Consistency,Isolation,Durability",
            0: 'something'
        }
</code>```

In conclusion, you can only call elements by their key, if you are dealing with dictionaries in Python, not by their index position, as you would do with a list or tuple. Therefore, the possibilities you have are the following; everything else will fail.

```<code>diction['DDL']
diction['EDW']
diction['ACID']
</code>```

Title: Python : Dictionary and .format

Body:
It throws an error because you are trying to get the value of the dictionary identified by the key 0. Yet, you don't have any 0 in your dictionary.

It would work if you included it.

diction = {"DDL":"Defined Data Language",
           "EDW":"Enterprise Data Warehouse",
           "ACID": "Atomicity,Consistency,Isolation,Durability",
            0: 'something'
        }

In conclusion, you can only call elements by their key, if you are dealing with dictionaries in Python, not by their index position, as you would do with a list or tuple. Therefore, the possibilities you have are the following; everything else will fail.

diction['DDL']
diction['EDW']
diction['ACID']


问:
Website not rendering properly on boss's computer / browser, but all others seem to work fine. Help?
I'm a university student, and just built my first website for an internship. We are approaching the launch of the site, however during my debugging process I've found that of all places, it doesn't work on my boss's machine and browser combination. She uses a Vista OS and internet explorer 7 for a browser. I know IE7 is outdated, but according to broswershots.org IE7 will still render the site mostly correct on an XP operating system.

The main page of the site is accessible here

Here are screenshots of what happens with the Vista/IE7 combo:

Please let me know what you think, as any ideas would be extremely helpful. Thanks!

答:
In your boss's browser, go to Tools, Internet Options, Accessiblity.

She may have checkboxes checked that override font settings.


问:
Equivalent of Clean & build in Android Studio?
Today while running an app from Android Studio, it didn't build from my latest code.

I looked for a Clean & build option but I couldn't find one.

So my question is: what is Android Studio's equivalent of Clean & build?

答:
If none of the above works and Build->Make is grayed out. try this:,

First select the project and then

Go to file->Project_structure

Close the window and the Build->Make ; will be available.

This is for


答: Python Dictionary items are accessed using key name, index can't be used. In your example, 0 is considered as a key. Since it is not in the dictionary diction, code throw KeyError</p>

Title: Python : Dictionary and .format


问:
not a valid identifier error with read command
I have looked into reading files from this site, man pages and google but not understanding, I apologize if this has been answered. I am having trouble reading a file into my script. I am using bash shell in linux. I am also new to linux.

I have a script that is supposed to read from a text file, perform tests, calculations, etc on each of the data lines specified.

I am getting the following error: ./hw-script7b: line 8: read: `hw7.list3': not a valid identifier
the hw7.list3 is the input file. it has full rights (read, write, even execute) hw-script7b is my script.

the text file contains an -ls listing of a directory. this is probably a basic issue but I am lost.
thanks for any assistance,

Debbie

here is the script.

```<code>echo "start"
count=0     #counting all files
xcount=0    #counting executeable files
total=0     #counting total space used
temp=0      #holding place for file being checked

exec 9< $1
while read $1 $2 $3 $4 $5 $6 $7 $8 0<&9
do
count='expr $count + 1'
if [ $4 > "$temp" ]
then
lfname="$8"
linode="$1"
lsize="$4"
lrights="$2"
lmonth="$5"
lday="$6"
temp="$4"
else
 if [ $4 < "$temp" ]
 then
 sfname="$8"
 sinode="$1"
 ssize="$4"
 srights="$2"
 smonth="$5"
 sday="$6"
 temp="$4"
 fi
fi

#looking for executeable files
if [ -x "$8" ]
then
xcount='expr $xcount + 1'
fi
done

echo "The largest file is: "$lfile""
echo "      Inode    Size    Rights       Date     "
echo "     $linode  $lsize  $lrights  $lmonth $lday"
echo
echo
echo "The smallest file is: "$sfile""
echo "      Inode    Size    Rights       Date     "
echo "     $sinode  $ssize  $srights  $smonth $sday"
echo
echo
echo "The total number of files is "$count" and they use "$total" bytes."
echo
echo
echo "There are "$xcount" executable files."
exit 0

sample of input file: hw7.list3
934250 -rwxrwxr-x 1 1107 Dec  2 18:48 //home/others/professor/class-share/hw7.howard
7934314 -r-xr-xr-t 1 1232 Dec  2 18:48 //home/others/professor/class-share/Matts_HW6
7934139 -rwxrwxr-x 1 1232 Dec  4 20:08 //home/others/professor/class-share/Matts_HW6_2
7934366 -rwxrw-r-- 1 1537 Dec  9 19:32 //home/others/professor/class-share/bs-hw7
7934364 -rwx------ 1  965 Dec  9 19:48 //home/others/professor/class-share/hw7
7948204 -rwxr-xr-x 1 107 Nov 12 07:47 readtest1
7948209 -rwxr-xr-x 1 107 Nov 12 07:48 readtest1a
7948205 -rwxr-xr-x 1 140 Nov 12 07:48 readtest2
7948206 -rwxr-xr-x 1 160 Nov 12 07:48 readtest3
7948207 -rwxr-xr-x 1 165 Nov 12 07:48 readtest4
7948208 -rwxr-xr-x 1 211 Nov 12 07:48 readtest5
7948210 -rwxr-xr-x 1   8 Nov 12 07:49 namefile1
7948211 -rwxr-xr-x 1  17 Nov 12 07:49 namefile2
7948212 -rwxr-xr-x 1  28 Nov 12 07:49 namefile3
7932451 -rwxr--r-- 1  219 Nov 13 16:53 //home/others/professor/class-share/grades-text
7934113 -rw-r--r-- 1  111 Nov 18 17:27 //home/others/professor/class-share/test2.gz
</code>```

答:
I realise that this is a VERY old post, but I just discovered the answer

The text file should be saved as UNIX Line Feeds instead of Mac OS CR or Windows CRLF

Body:
I have looked into reading files from this site, man pages and google but not understanding, I apologize if this has been answered. I am having trouble reading a file into my script. I am using bash shell in linux. I am also new to linux.

I have a script that is supposed to read from a text file, perform tests, calculations, etc on each of the data lines specified.

I am getting the following error: ./hw-script7b: line 8: read: `hw7.list3': not a valid identifier
the hw7.list3 is the input file. it has full rights (read, write, even execute) hw-script7b is my script.

the text file contains an -ls listing of a directory. this is probably a basic issue but I am lost.
thanks for any assistance,

Debbie

here is the script.

echo "start"
count=0     #counting all files
xcount=0    #counting executeable files
total=0     #counting total space used
temp=0      #holding place for file being checked

exec 9< $1
while read $1 $2 $3 $4 $5 $6 $7 $8 0<&9
do
count='expr $count + 1'
if [ $4 > "$temp" ]
then
lfname="$8"
linode="$1"
lsize="$4"
lrights="$2"
lmonth="$5"
lday="$6"
temp="$4"
else
 if [ $4 < "$temp" ]
 then
 sfname="$8"
 sinode="$1"
 ssize="$4"
 srights="$2"
 smonth="$5"
 sday="$6"
 temp="$4"
 fi
fi

#looking for executeable files
if [ -x "$8" ]
then
xcount='expr $xcount + 1'
fi
done

echo "The largest file is: "$lfile""
echo "      Inode    Size    Rights       Date     "
echo "     $linode  $lsize  $lrights  $lmonth $lday"
echo
echo
echo "The smallest file is: "$sfile""
echo "      Inode    Size    Rights       Date     "
echo "     $sinode  $ssize  $srights  $smonth $sday"
echo
echo
echo "The total number of files is "$count" and they use "$total" bytes."
echo
echo
echo "There are "$xcount" executable files."
exit 0

sample of input file: hw7.list3
934250 -rwxrwxr-x 1 1107 Dec  2 18:48 //home/others/professor/class-share/hw7.howard
7934314 -r-xr-xr-t 1 1232 Dec  2 18:48 //home/others/professor/class-share/Matts_HW6
7934139 -rwxrwxr-x 1 1232 Dec  4 20:08 //home/others/professor/class-share/Matts_HW6_2
7934366 -rwxrw-r-- 1 1537 Dec  9 19:32 //home/others/professor/class-share/bs-hw7
7934364 -rwx------ 1  965 Dec  9 19:48 //home/others/professor/class-share/hw7
7948204 -rwxr-xr-x 1 107 Nov 12 07:47 readtest1
7948209 -rwxr-xr-x 1 107 Nov 12 07:48 readtest1a
7948205 -rwxr-xr-x 1 140 Nov 12 07:48 readtest2
7948206 -rwxr-xr-x 1 160 Nov 12 07:48 readtest3
7948207 -rwxr-xr-x 1 165 Nov 12 07:48 readtest4
7948208 -rwxr-xr-x 1 211 Nov 12 07:48 readtest5
7948210 -rwxr-xr-x 1   8 Nov 12 07:49 namefile1
7948211 -rwxr-xr-x 1  17 Nov 12 07:49 namefile2
7948212 -rwxr-xr-x 1  28 Nov 12 07:49 namefile3
7932451 -rwxr--r-- 1  219 Nov 13 16:53 //home/others/professor/class-share/grades-text
7934113 -rw-r--r-- 1  111 Nov 18 17:27 //home/others/professor/class-share/test2.gz