问:
Component getting re-rendered when props aren't changing
I'm showing a map that is memoized using React.memo(). I want the map to only re-render when the props change, but it re-renders even when they don't. How can I prevent the re-renders when props don't change?

The Map:

```<code>const MapContainer = React.memo((props) => {
  const [map, setMap] = useState();
  var bounds = new props.google.maps.LatLngBounds();

  const setMapObj = (mapProps, map) => {
    setMap(map);
  };

  useDeepCompareEffect(() => {
    if (props.markers.length === 1) {
      bounds.extend(
        new props.google.maps.LatLng(props.markers[0].lat, props.markers[0].lng)
      );
      bounds.extend(
        new props.google.maps.LatLng(
          props.markers[0].lat - 1,
          props.markers[0].lng - 1
        )
      );
      map && map.fitBounds(bounds);
      return;
    }
    for (var i = 0; i < props.markers.length; i++) {
      bounds.extend(
        new props.google.maps.LatLng(props.markers[i].lat, props.markers[i].lng)
      );
    }
    if (map) {
      map.fitBounds(bounds);
    }
  }, [props.markers, map]);

  return (
    <div className={props.className}>
      <Map
        google={props.google}
        style={{ borderRadius: "10px" }}
        // center={{ lat: 59.913, lng: 10.75 }}
        initialCenter={{ lat: 59.913, lng: 10.75 }}
        onReady={setMapObj}
        zoom={8}
      >
        {console.log("rendered")}
        {props.markers.map((item, index) => {
          if (item.lat && item.lng)
            return (
              <Marker key={index} position={{ lat: item.lat, lng: item.lng }} />
            );
        })}
      </Map>
    </div>
  );
});

export default GoogleApiWrapper({
  apiKey: "API_KEY",
})(MapContainer);

</code>```

Since the parent component is pretty big, I've only added in the parts I think are relevant.
The parent of Map:

```<code>function Home() {
  const [plants, setPlants] = useState([
    {
      name: "Plant 1",
      id: uuidv4(),
      location: "",
      coords: {},
      country: "",
      isOffshore: false
    },
  ]);

  const isObjectEmpty = (obj) => {
    for (var i in obj) return false;
    return true;
  };

  const getMarkers = () => {
    var temp = [];
    for (var i = 0; i < plants.length; i++)
      if (!isObjectEmpty(plants[i].coords)) temp.push(plants[i].coords);
    return temp;
  };

  return (
    <section/>
    <CustomMap className="map" markers={getMarkers()} />
    <section/>
  )
}
</code>```

答:
Memo does not make a deep comparison.

Each time home is re-render, the map will be re-render too. Because
you are passing markers as the result of executing a function that
each time generates a new array, a new reference, to a different
object. Which of course is perceived by memo as a trigger for a
re-render. In addition to the new array, keep in mind that the
getMarkers function is also new each time and refers to a different
object. For functions, useCallback is usually used.

I propose to use the useMemo hook to fix and exclude the creation of
a new array, and, accordingly, a reference to a new object. And
accordingly there will be no re-rendering when it is not needed.

Don't forget to include dependencies in useMemo. In your case it is
plants.

Example

```<code>const markers = useMemo(() => {
  var temp = [];
  for (var i = 0; i < plants.length; i++)
    if (!isObjectEmpty(plants[i].coords)) temp.push(plants[i].coords);
  return temp;
}, [plants]);
</code>```

Body:
I'm showing a map that is memoized using React.memo(). I want the map to only re-render when the props change, but it re-renders even when they don't. How can I prevent the re-renders when props don't change?

The Map:

const MapContainer = React.memo((props) => {
  const [map, setMap] = useState();
  var bounds = new props.google.maps.LatLngBounds();

  const setMapObj = (mapProps, map) => {
    setMap(map);
  };

  useDeepCompareEffect(() => {
    if (props.markers.length === 1) {
      bounds.extend(
        new props.google.maps.LatLng(props.markers[0].lat, props.markers[0].lng)
      );
      bounds.extend(
        new props.google.maps.LatLng(
          props.markers[0].lat - 1,
          props.markers[0].lng - 1
        )
      );
      map && map.fitBounds(bounds);
      return;
    }
    for (var i = 0; i < props.markers.length; i++) {
      bounds.extend(
        new props.google.maps.LatLng(props.markers[i].lat, props.markers[i].lng)
      );
    }
    if (map) {
      map.fitBounds(bounds);
    }
  }, [props.markers, map]);

  return (

      <Map
        google={props.google}
        style={{ borderRadius: "10px" }}
        // center={{ lat: 59.913, lng: 10.75 }}
        initialCenter={{ lat: 59.913, lng: 10.75 }}
        onReady={setMapObj}
        zoom={8}
      >
        {console.log("rendered")}
        {props.markers.map((item, index) => {
          if (item.lat && item.lng)
            return (
              <Marker key={index} position={{ lat: item.lat, lng: item.lng }} />
            );
        })}
      </Map>

  );
});

export default GoogleApiWrapper({
  apiKey: "API_KEY",
})(MapContainer);

Since the parent component is pretty big, I've only added in the parts I think are relevant.
The parent of Map:

function Home() {
  const [plants, setPlants] = useState([
    {
      name: "Plant 1",
      id: uuidv4(),
      location: "",
      coords: {},
      country: "",
      isOffshore: false
    },
  ]);

  const isObjectEmpty = (obj) => {
    for (var i in obj) return false;
    return true;
  };

  const getMarkers = () => {
    var temp = [];
    for (var i = 0; i < plants.length; i++)
      if (!isObjectEmpty(plants[i].coords)) temp.push(plants[i].coords);
    return temp;
  };

  return (

    <CustomMap className="map" markers={getMarkers()} />

  )
}

Body:
Memo does not make a deep comparison.

Each time home is re-render, the map will be re-render too. Because
you are passing markers as the result of executing a function that
each time generates a new array, a new reference, to a different
object. Which of course is perceived by memo as a trigger for a
re-render. In addition to the new array, keep in mind that the
getMarkers function is also new each time and refers to a different
object. For functions, useCallback is usually used.

I propose to use the useMemo hook to fix and exclude the creation of
a new array, and, accordingly, a reference to a new object. And
accordingly there will be no re-rendering when it is not needed.

Don't forget to include dependencies in useMemo. In your case it is
plants.

Example

const markers = useMemo(() => {
  var temp = [];
  for (var i = 0; i < plants.length; i++)
    if (!isObjectEmpty(plants[i].coords)) temp.push(plants[i].coords);
  return temp;
}, [plants]);


来源: stackexchange

问:
How to delete AWS Cognito Unconfirmed users from CLI
We have a huge number of Unconfirmed users in AWS congnito, so my requirement is to delete all of them from CLI instead of AWS console.</p>

答:
You didn't specify how you were using the AWS CLI (Windows, Linux, etc.), but here's a script that will accomplish what you are trying to do. Note that your AWS CLI should be configured to output JSON for this to work. Also note that this takes a while to run. I deleted around 80 unconfirmed Cognito users with it and it took 5-6 minutes to complete.

PowerShell

# Update these to your AWS configuration
$AWS_REGION = 'your-aws-region'
$AWS_USER_POOL_ID = 'your-aws-userpool'

$userList = aws cognito-idp list-users --region $AWS_REGION --user-pool-id $AWS_USER_POOL_ID | ConvertFrom-Json
$userList.Users | ForEach-Object {
    if ($_.UserStatus -like 'UNCONFIRMED'){
        aws cognito-idp admin-delete-user --region $AWS_REGION --user-pool-id $AWS_USER_POOL_ID --username $_.Username
    }
}
```

ContentLicense: CC BY-SA 4.0


问:
Does a Silverlight share the HTTP connection of its host
Does a Silverlight video player share the HTTP connection with its host?

Here is the scenario: a web site is password protected. The web page contains a Silverlight control with a video player. The video player plays a video from the same web site. Will the credentials from the web browser be used by the video player? I use MediaElement.Source to specify where the video is coming from.

If not, how can I fix this?

答:
That depends on the way it communicates with the server... for example the webrequest class can be set to use BrowserHTTP or ClientHTTP...

BrowserHTTP uses the browser's HTTP implementation including Referer, Cookies etc.

ClientHTTP allows you to manage HTTP setting like Cookies manually...

Using MediaElement.SetSource you can leverage whatever connection you please (BrowserHTTP / ClientHTPP) with you specific settings (including Authorization header / Cookies etc.) as log as that connection provides a Stream interface for the content...

Further details see

http://msdn.microsoft.com/en-us/library/system.net.browser.webrequestcreator.browserhttp%28v=vs.95%29.aspx

http://msdn.microsoft.com/en-us/library/system.net.browser.webrequestcreator.clienthttp%28v=vs.95%29.aspx

http://msdn.microsoft.com/en-us/library/cc838250%28v=vs.95%29.aspx

http://msdn.microsoft.com/en-us/library/cc190669%28v=vs.95%29.aspx

ContentLicense: CC BY-SA 3.0


问:
How to get rid of border and add background color to MUI TextField variant outlined
I want to customize outlined variant of TextField in Material UI and to below field I want to remove border or give color to white and give different background color.
I'm using styled components in my app, but also tried tried makeStyles and it didn't work, although when I make changes in chrome dev tools I'm able to do so.
I have tried this class from documentation  .MuiTextField-root and it didn't work.
I chrome dev tools it works for this class but when I add this class to styled component ( without this .css-wacwkt-) it doesn't work. With element.style it's the same situation.

To interact with border I need to use in chromedev tools fieldset selector and it works for element.style and this marked class. You can see on the left with border-color:blue which TextFields it's about

This is how it's implemented in the code

```<code> <StyledInputSection>
                        <StyledDataHeader>
                            {contactDataTxt}
                        </StyledDataHeader>
                        <InputForm
                            name={'phoneNumber'}
                            id={'phoneNumber'}
                            label={phoneNumberLabelTxt}
                            disabled={isDisabledInputs}
                        />
                        <InputForm
                            name={'email'}
                            id={'email'}
                            label={emailLabelTxt}
                            disabled={isDisabledInputs}
                        />
                        {/* Show checkbox only for create new user by Admin */}
                        {!isDetailsView && !idUser && (
                            <CheckboxForm
                                label={emailAsLoginTxt}
                                name={'isEmailAsLogin'}
                                disabled={isDisabledInputs}
                            />
                        )}

                        <InputForm
                            name={'userName'}
                            id={'userName'}
                            label={loginLabelTxt}
                            disabled={
                                isDisabledLoginInput || isDisabledInputs
                            }
                        />
                    </StyledInputSection>
</code>```

InputForm is TextFiled component prepared as re-usable.

appreciate Your support.

regards

答:
Updated Component Example:

You can override the default styling as a styled component by hooking into the existing classes:

```<code>const ExampleTextField = styled(TextField)({
  backgroundColor: "#eee",
  "& .MuiOutlinedInput-notchedOutline": {
    border: "none"
  },
  "&.Mui-focused": {
    "& .MuiOutlinedInput-notchedOutline": {
      border: "none"
    }
  }
});
</code>```

Working component code example: https://codesandbox.io/s/customizedinputs-material-demo-forked-lpxwb?file=/demo.js:166-403

Original Themed Example:

If you're ok adding it to the theme, something as simple as this may work for you:

(You can also do something similar in InputForm with styled components if you don't want this to affect every outlined variant.)

```<code>const theme = createTheme({
  components: {
    // Inputs
    MuiOutlinedInput: {
      styleOverrides: {
        root: {
          backgroundColor: "#eee", // As an example color
          "& .MuiOutlinedInput-notchedOutline": {
            border: "none"
          },
          "&.Mui-focused": {
            "& .MuiOutlinedInput-notchedOutline": {
              border: "none"
            }
          }
        }
      }
    }
  }
});
</code>```

Working theme code example: https://codesandbox.io/s/customstyles-material-demo-forked-u644m?file=/theme.js

Body:
I want to customize outlined variant of TextField in Material UI and to below field I want to remove border or give color to white and give different background color.
I'm using styled components in my app, but also tried tried makeStyles and it didn't work, although when I make changes in chrome dev tools I'm able to do so.
I have tried this class from documentation  .MuiTextField-root and it didn't work.
I chrome dev tools it works for this class but when I add this class to styled component ( without this .css-wacwkt-) it doesn't work. With element.style it's the same situation.

To interact with border I need to use in chromedev tools fieldset selector and it works for element.style and this marked class. You can see on the left with border-color:blue which TextFields it's about

This is how it's implemented in the code

                        <InputForm
                            name={'phoneNumber'}
                            id={'phoneNumber'}
                            label={phoneNumberLabelTxt}
                            disabled={isDisabledInputs}
                        />
                        <InputForm
                            name={'email'}
                            id={'email'}
                            label={emailLabelTxt}
                            disabled={isDisabledInputs}
                        />
                        {/* Show checkbox only for create new user by Admin */}
                        {!isDetailsView && !idUser && (
                            <CheckboxForm
                                label={emailAsLoginTxt}
                                name={'isEmailAsLogin'}
                                disabled={isDisabledInputs}
                            />
                        )}

                        <InputForm
                            name={'userName'}
                            id={'userName'}
                            label={loginLabelTxt}
                            disabled={
                                isDisabledLoginInput || isDisabledInputs
                            }
                        />
                    </StyledInputSection>

InputForm is TextFiled component prepared as re-usable.

appreciate Your support.

regards

Body:
Updated Component Example:

You can override the default styling as a styled component by hooking into the existing classes:

const ExampleTextField = styled(TextField)({
  backgroundColor: "#eee",
  "& .MuiOutlinedInput-notchedOutline": {
    border: "none"
  },
  "&.Mui-focused": {
    "& .MuiOutlinedInput-notchedOutline": {
      border: "none"
    }
  }
});

Working component code example: https://codesandbox.io/s/customizedinputs-material-demo-forked-lpxwb?file=/demo.js:166-403

Original Themed Example:

If you're ok adding it to the theme, something as simple as this may work for you:

(You can also do something similar in InputForm with styled components if you don't want this to affect every outlined variant.)

const theme = createTheme({
  components: {
    // Inputs
    MuiOutlinedInput: {
      styleOverrides: {
        root: {
          backgroundColor: "#eee", // As an example color
          "& .MuiOutlinedInput-notchedOutline": {
            border: "none"
          },
          "&.Mui-focused": {
            "& .MuiOutlinedInput-notchedOutline": {
              border: "none"
            }
          }
        }
      }
    }
  }
});

Working theme code example: https://codesandbox.io/s/customstyles-material-demo-forked-u644m?file=/theme.js


问:
S3 boto3 list directories only
I have below hierarchy in S3 and would like to retrieve only subfolders type information excluding files that ends in .txt (basically exclude filenames and retrieve only prefixes/folders).

```<code>--folder1/subfolder1/item1.txt
--folder1/subfolder1/item11.txt
--folder1/subfolder2/item2.txt
--folder1/subfolder2/item21.txt
--folder1/subfolder3/item3.txt
--folder1/subfolder3/subfolder31/item311.txt
</code>```

Desired Output:

```<code>--folder1/subfolder1
--folder1/subfolder2
--folder1/subfolder3/subfolder31
</code>```

I understand that there is no folders/subfolders in S3 but all are keys.

I tried below code but it is displaying all information including filenames like item1.txt

```<code>s3 = boto3.resource('s3')
client = boto3.client('s3')
bucket = s3.Bucket('s3-bucketname')
paginator = client.get_paginator('list_objects')

objs = list(bucket.objects.filter(Prefix='folder1/'))
for i in range(0, len(objs)):
    print(objs[i].key)
</code>```

Any recommendation to get below output?

```<code>--folder1/subfolder1
--folder1/subfolder2
--folder1/subfolder3/subfolder31
</code>```

答:
As you say, S3 doesn't really have a concept of folders, so to get what you want, in a sense, you need to recreate it.

One option is to list all of the objects in the bucket, and construct the folder, or prefix, of each object, and operate on new names as you run across them:

```<code>import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('s3-bucketname')
shown = set()
for obj in bucket.objects.filter(Prefix='folder1/'):
    prefix = "/".join(obj.key.split("/")[:-1])
    if len(prefix) and prefix not in shown:
        shown.add(prefix)
        print(prefix + "/")
</code>```

Title: S3 boto3 list directories only

Body:
I have below hierarchy in S3 and would like to retrieve only subfolders type information excluding files that ends in .txt (basically exclude filenames and retrieve only prefixes/folders).

--folder1/subfolder1/item1.txt
--folder1/subfolder1/item11.txt
--folder1/subfolder2/item2.txt
--folder1/subfolder2/item21.txt
--folder1/subfolder3/item3.txt
--folder1/subfolder3/subfolder31/item311.txt

Desired Output:

--folder1/subfolder1
--folder1/subfolder2
--folder1/subfolder3/subfolder31

I understand that there is no folders/subfolders in S3 but all are keys.

I tried below code but it is displaying all information including filenames like item1.txt

s3 = boto3.resource('s3')
client = boto3.client('s3')
bucket = s3.Bucket('s3-bucketname')
paginator = client.get_paginator('list_objects')

objs = list(bucket.objects.filter(Prefix='folder1/'))
for i in range(0, len(objs)):
    print(objs[i].key)

Any recommendation to get below output?

--folder1/subfolder1
--folder1/subfolder2
--folder1/subfolder3/subfolder31

Body:
As you say, S3 doesn't really have a concept of folders, so to get what you want, in a sense, you need to recreate it.

One option is to list all of the objects in the bucket, and construct the folder, or prefix, of each object, and operate on new names as you run across them:

import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('s3-bucketname')
shown = set()
for obj in bucket.objects.filter(Prefix='folder1/'):
    prefix = "/".join(obj.key.split("/")[:-1])
    if len(prefix) and prefix not in shown:
        shown.add(prefix)
        print(prefix + "/")


问:
.husky/pre-commit: 2: .: Can't open .husky/_/husky.sh
In a project, we use Husky but when I try to add a commit with git add . and git commit -m "test", I receive below error

.husky/pre-commit: 2: .: Can't open .husky/_/husky.sh

How can i fix this problem ?

My operating system is Windows but I use Ubuntu on this project

I have a pre-commit file and it is as below

Also the codes for husky.sh is below

```<code>if [ -z "$husky_skip_init" ]; then
  debug () {
    if [ "$HUSKY_DEBUG" = "1" ]; then
      echo "husky (debug) - $1"
    fi
  }

  readonly hook_name="$(basename "$0")"
  debug "starting $hook_name..."

  if [ "$HUSKY" = "0" ]; then
    debug "HUSKY env variable is set to 0, skipping hook"
    exit 0
  fi

  if [ -f ~/.huskyrc ]; then
    debug "sourcing ~/.huskyrc"
    . ~/.huskyrc
  fi

  export readonly husky_skip_init=1
  sh -e "$0" "$@"
  exitCode="$?"

  if [ $exitCode != 0 ]; then
    echo "husky - $hook_name hook exited with code $exitCode (error)"
  fi

  exit $exitCode
fi
</code>```

答: for this problem, I have come up with a solution as below. In my IDE, line endings use CRLF by default. So I changed it to LF from the bottom right corner of the IDE and it worked

Body:
In a project, we use Husky but when I try to add a commit with git add . and git commit -m "test", I receive below error

.husky/pre-commit: 2: .: Can't open .husky/_/husky.sh

How can i fix this problem ?

My operating system is Windows but I use Ubuntu on this project

I have a pre-commit file and it is as below

Also the codes for husky.sh is below

if [ -z "$husky_skip_init" ]; then
  debug () {
    if [ "$HUSKY_DEBUG" = "1" ]; then
      echo "husky (debug) - $1"
    fi
  }

  readonly hook_name="$(basename "$0")"
  debug "starting $hook_name..."

  if [ "$HUSKY" = "0" ]; then
    debug "HUSKY env variable is set to 0, skipping hook"
    exit 0
  fi

  if [ -f ~/.huskyrc ]; then
    debug "sourcing ~/.huskyrc"
    . ~/.huskyrc
  fi

  export readonly husky_skip_init=1
  sh -e "$0" "$@"
  exitCode="$?"

  if [ $exitCode != 0 ]; then
    echo "husky - $hook_name hook exited with code $exitCode (error)"
  fi

  exit $exitCode
fi


问:
SQL Server row_number function how to remove dups based on each date within a range
I have a query that will have duplicate entries. It looks for all event messages (text) within the month. The same message can exist from a provider for a patient within a single day and I want to remove those. I do not want to remove any messages that could be identical but happened on a different day. Is that possible?

答:
In the row_number you partition by the text, date(truncated to day level) and provider. If the message text is truly identical within a day the row_number function will count up for that group. If it is identical message but on different day then it will be in next partition. So you just need to filter on row_number = 1 from the result of that cte.

Something like this...

```<code>select * from (
select distinct PtNbr_name
  ,row_number() over(partition by
  event_message,provider,convert(varchar(8),date/time,112) order by PtNbr_name) rn
from table ) x
where x.rn = 1
</code>```

Body:
In the row_number you partition by the text, date(truncated to day level) and provider. If the message text is truly identical within a day the row_number function will count up for that group. If it is identical message but on different day then it will be in next partition. So you just need to filter on row_number = 1 from the result of that cte.

Something like this...

select * from (
select distinct PtNbr_name
  ,row_number() over(partition by
  event_message,provider,convert(varchar(8),date/time,112) order by PtNbr_name) rn
from table ) x
where x.rn = 1


问:
Getting subquery error using string_agg function
I'm using SQL Server Management Studio 2017 and I have a SELECT statement where I use STRING_AGG function in subquery like:

```<code>SELECT
    [p].[test],
    [p].[test],
    ....
    (SELECT [Customers]
     FROM
         (SELECT
              STRING_AGG([C].[Name] , ', ') AS [Customers]
          FROM
              [Project] AS [P]
          RIGHT JOIN
              [ProjectCustomer] AS [PC] ON [P].[ProjectKey] = [PC].[ProjectKey]
          INNER JOIN
              [Customer] AS [C] ON [PC].[CustomerKey] = [C].[CustomerKey]
          GROUP BY
              [P].[Name]) AS [t])
FROM
    ...
</code>```

Problem is when I executed it, I get this exception:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

But if I run subquery as a individual select it runs and it only returns one string value. Can someone explain me what am I doing wrong there? Regards

答:
I ran into the same error message when using a GROUP BY and STRING_AGG in the same subquery. I added another subquery level to do the get mine to work. In your example, I would write this:</p>
```<code>SELECT
  STRING_AGG(distinct_customers.[Name] , ', ') AS [Customers]
FROM
(
    SELECT
      [C].[Name]
    FROM
      [Project] AS [P]
    RIGHT JOIN
      [ProjectCustomer] AS [PC] ON [P].[ProjectKey] = [PC].[ProjectKey]
    INNER JOIN
      [Customer] AS [C] ON [PC].[CustomerKey] = [C].[CustomerKey]
    GROUP BY
      [P].[Name]) AS [t]
) AS distinct_customers
</code>```

Body:
I'm using SQL Server Management Studio 2017 and I have a SELECT statement where I use STRING_AGG function in subquery like:

SELECT
    [p].[test],
    [p].[test],
    ....
    (SELECT [Customers]
     FROM
         (SELECT
              STRING_AGG([C].[Name] , ', ') AS [Customers]
          FROM
              [Project] AS [P]
          RIGHT JOIN
              [ProjectCustomer] AS [PC] ON [P].[ProjectKey] = [PC].[ProjectKey]
          INNER JOIN
              [Customer] AS [C] ON [PC].[CustomerKey] = [C].[CustomerKey]
          GROUP BY
              [P].[Name]) AS [t])
FROM
    ...

Problem is when I executed it, I get this exception:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

But if I run subquery as a individual select it runs and it only returns one string value. Can someone explain me what am I doing wrong there? Regards

Body:
I ran into the same error message when using a GROUP BY and STRING_AGG in the same subquery. I added another subquery level to do the get mine to work. In your example, I would write this:

SELECT
  STRING_AGG(distinct_customers.[Name] , ', ') AS [Customers]
FROM
(
    SELECT
      [C].[Name]
    FROM
      [Project] AS [P]
    RIGHT JOIN
      [ProjectCustomer] AS [PC] ON [P].[ProjectKey] = [PC].[ProjectKey]
    INNER JOIN
      [Customer] AS [C] ON [PC].[CustomerKey] = [C].[CustomerKey]
    GROUP BY
      [P].[Name]) AS [t]
) AS distinct_customers


问:
Accuracy and loss does not change with RMSprop optimizer
The dataset is CIFAR10. I've created a VGG-like network:

```<code>class FirstModel(nn.Module):
    def __init__(self):
        super(FirstModel, self).__init__()
        self.vgg1 = nn.Sequential(
            nn.Conv2d(3, 16, 3, padding=1),
            nn.BatchNorm2d(16),
            nn.ReLU(),
            nn.Conv2d(16, 16, 3, padding=1),
            nn.BatchNorm2d(16),
            nn.ReLU(),
            nn.MaxPool2d(2,2),
            nn.Dropout(0.2)
        )

        self.vgg2 = nn.Sequential(
            nn.Conv2d(16, 32, 3, padding=1),
            nn.BatchNorm2d(32),
            nn.ReLU(),
            nn.Conv2d(32, 32, 3, padding=1),
            nn.BatchNorm2d(32),
            nn.ReLU(),
            nn.MaxPool2d(2,2),
            nn.Dropout(0.2)
        )

        self.vgg3 = nn.Sequential(
            nn.Conv2d(32, 64, 3, padding=1),
            nn.BatchNorm2d(64),
            nn.ReLU(),
            nn.Conv2d(64, 64, 3, padding=1),
            nn.BatchNorm2d(64),
            nn.ReLU(),
            nn.MaxPool2d(2,2),
            nn.Dropout(0.2)
        )

        self.fc1 = nn.Linear(4 * 4 * 64, 4096)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(4096, 4096)
        self.fc3 = nn.Linear(4096, 10)
        self.softmax = nn.Softmax()
        self.dropout = nn.Dropout(0.5)

    def forward(self, x):
        x = self.vgg3(self.vgg2(self.vgg1(x)))
        x = nn.Flatten()(x)
        x = self.relu(self.fc1(x))
        x = self.dropout(x)
        x = self.relu(self.fc2(x))
        x = self.dropout(x)
        x = self.softmax(self.fc3(x))

        return x
</code>```

Then I train it and visualize loss and accuracy:

```<code>import matplotlib.pyplot as plt
from IPython.display import clear_output

def plot_history(train_history, val_history, title='loss'):
    plt.figure()
    plt.title('{}'.format(title))
    plt.plot(train_history, label='train', zorder=1)

    points = np.array(val_history)
    steps = list(range(0, len(train_history) + 1, int(len(train_history) / len(val_history))))[1:]

    plt.scatter(steps, val_history, marker='*', s=180, c='red', label='val', zorder=2)
    plt.xlabel('train steps')

    plt.legend(loc='best')
    plt.grid()

    plt.show()

def train_model(model, optimizer, train_dataloader, test_dataloader):
      criterion = nn.CrossEntropyLoss()

      train_loss_log = []
      train_acc_log = []
      val_loss_log = []
      val_acc_log = []

      for epoch in range(NUM_EPOCH):

        model.train()

        train_loss = 0.
        train_size = 0
        train_acc = 0.

        for inputs, labels in train_dataloader:

          inputs, labels = inputs.to(device), labels.to(device)

          optimizer.zero_grad()
          y_pred = model(inputs)

          loss = criterion(y_pred, labels)
          loss.backward()
          optimizer.step()

          train_loss += loss.item()
          train_size += y_pred.size(0)
          train_loss_log.append(loss.data / y_pred.size(0))

          _, pred_classes = torch.max(y_pred, 1)
          train_acc += (pred_classes == labels).sum().item()
          train_acc_log.append(np.mean((pred_classes == labels).cpu().numpy()))

        # блок validation
        val_loss = 0.
        val_size = 0
        val_acc = 0.

        model.eval()
        with torch.no_grad():
            for inputs, labels in test_dataloader:
                inputs, labels = inputs.to(device), labels.to(device)
                y_pred = model(inputs)
                loss = criterion(y_pred, labels)
                val_loss += loss.item()
                val_size += y_pred.size(0)

                _, pred_classes = torch.max(y_pred, 1)
                val_acc += (pred_classes == labels).sum().item()

        val_loss_log.append(val_loss/val_size)
        val_acc_log.append(val_acc/val_size)

        clear_output()
        plot_history(train_loss_log, val_loss_log, 'loss')
        plot_history(train_acc_log, val_acc_log, 'accuracy')

        print('Train loss:', train_loss / train_size)
        print('Train acc:', train_acc / train_size)
        print('Val loss:', val_loss / val_size)
        print('Val acc:', val_acc / val_size)
</code>```

Then I train the model:

```<code>first_model = FirstModel()
first_model.to(device)

optimizer = optim.RMSprop(first_model.parameters(), lr=0.001, momentum=0.9)

train_model(first_model_rms, optimizer, train_dataloader, test_dataloader)
</code>```

The loss and accuracy do not change (accuracy at level of 0.1). However, if the optimizer is SGD with momentum everything works fine (loss and accuracy change). I've already tried to change momentum and lr, but it does not help.

What should be fixed? Would be grateful for any possible advice!

答:
In my case, I was facing the same error. On my laptop without GPU the training was fine. When I tried on GPU the model didn’t change the accuracy and loss after the first epochs. I was using nn.CrossEntropyLoss() with Adam.
Changing Adam with SGD worked for me.</p>

Body:
The dataset is CIFAR10. I've created a VGG-like network:

class FirstModel(nn.Module):
    def __init__(self):
        super(FirstModel, self).__init__()
        self.vgg1 = nn.Sequential(
            nn.Conv2d(3, 16, 3, padding=1),
            nn.BatchNorm2d(16),
            nn.ReLU(),
            nn.Conv2d(16, 16, 3, padding=1),
            nn.BatchNorm2d(16),
            nn.ReLU(),
            nn.MaxPool2d(2,2),
            nn.Dropout(0.2)
        )

        self.vgg2 = nn.Sequential(
            nn.Conv2d(16, 32, 3, padding=1),
            nn.BatchNorm2d(32),
            nn.ReLU(),
            nn.Conv2d(32, 32, 3, padding=1),
            nn.BatchNorm2d(32),
            nn.ReLU(),
            nn.MaxPool2d(2,2),
            nn.Dropout(0.2)
        )

        self.vgg3 = nn.Sequential(
            nn.Conv2d(32, 64, 3, padding=1),
            nn.BatchNorm2d(64),
            nn.ReLU(),
            nn.Conv2d(64, 64, 3, padding=1),
            nn.BatchNorm2d(64),
            nn.ReLU(),
            nn.MaxPool2d(2,2),
            nn.Dropout(0.2)
        )

        self.fc1 = nn.Linear(4 * 4 * 64, 4096)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(4096, 4096)
        self.fc3 = nn.Linear(4096, 10)
        self.softmax = nn.Softmax()
        self.dropout = nn.Dropout(0.5)

    def forward(self, x):
        x = self.vgg3(self.vgg2(self.vgg1(x)))
        x = nn.Flatten()(x)
        x = self.relu(self.fc1(x))
        x = self.dropout(x)
        x = self.relu(self.fc2(x))
        x = self.dropout(x)
        x = self.softmax(self.fc3(x))

        return x

Then I train it and visualize loss and accuracy:

import matplotlib.pyplot as plt
from IPython.display import clear_output

def plot_history(train_history, val_history, title='loss'):
    plt.figure()
    plt.title('{}'.format(title))
    plt.plot(train_history, label='train', zorder=1)

    points = np.array(val_history)
    steps = list(range(0, len(train_history) + 1, int(len(train_history) / len(val_history))))[1:]

    plt.scatter(steps, val_history, marker='*', s=180, c='red', label='val', zorder=2)
    plt.xlabel('train steps')

    plt.legend(loc='best')
    plt.grid()

    plt.show()

def train_model(model, optimizer, train_dataloader, test_dataloader):
      criterion = nn.CrossEntropyLoss()

      train_loss_log = []
      train_acc_log = []
      val_loss_log = []
      val_acc_log = []

      for epoch in range(NUM_EPOCH):

        model.train()

        train_loss = 0.
        train_size = 0
        train_acc = 0.

        for inputs, labels in train_dataloader:

          inputs, labels = inputs.to(device), labels.to(device)

          optimizer.zero_grad()
          y_pred = model(inputs)

          loss = criterion(y_pred, labels)
          loss.backward()
          optimizer.step()

          train_loss += loss.item()
          train_size += y_pred.size(0)
          train_loss_log.append(loss.data / y_pred.size(0))

          _, pred_classes = torch.max(y_pred, 1)
          train_acc += (pred_classes == labels).sum().item()
          train_acc_log.append(np.mean((pred_classes == labels).cpu().numpy()))

        # блок validation
        val_loss = 0.
        val_size = 0
        val_acc = 0.

        model.eval()
        with torch.no_grad():
            for inputs, labels in test_dataloader:
                inputs, labels = inputs.to(device), labels.to(device)
                y_pred = model(inputs)
                loss = criterion(y_pred, labels)
                val_loss += loss.item()
                val_size += y_pred.size(0)

                _, pred_classes = torch.max(y_pred, 1)
                val_acc += (pred_classes == labels).sum().item()

        val_loss_log.append(val_loss/val_size)
        val_acc_log.append(val_acc/val_size)

        clear_output()
        plot_history(train_loss_log, val_loss_log, 'loss')
        plot_history(train_acc_log, val_acc_log, 'accuracy')

        print('Train loss:', train_loss / train_size)
        print('Train acc:', train_acc / train_size)
        print('Val loss:', val_loss / val_size)
        print('Val acc:', val_acc / val_size)

Then I train the model:

first_model = FirstModel()
first_model.to(device)

optimizer = optim.RMSprop(first_model.parameters(), lr=0.001, momentum=0.9)

train_model(first_model_rms, optimizer, train_dataloader, test_dataloader)

The loss and accuracy do not change (accuracy at level of 0.1). However, if the optimizer is SGD with momentum everything works fine (loss and accuracy change). I've already tried to change momentum and lr, but it does not help.

What should be fixed? Would be grateful for any possible advice!


问:
Reduce time /space complexity of simple loop
So basically if i have an iteration like this in python
Ive editted the question to include my full code

```<code>class Solution:
    def myPow(self, x: float, n: int) -> float:
        temp = [];
        span = range(1,abs(n))
        if n ==0:
            return 1
        if abs(n)==1:
            temp.append(x)
        else:
            for y in span:
                if y == 1:
                    temp = []
                    temp.append(x*x)
                else:
                    temp.append(temp[-1] * x)
        if(n < 0):
            return 1/temp[-1]
        else:
            return temp[-1]
</code>```

The problem link is : Pow(x,n)-leetcode
How can I modify this to conserve memory and time. Is there another data structure i can use. Im just learning python....

------------EDIT------------
ive modified the code to use a variable instead of a list for the temp data

```<code>class Solution:
    def myPow(self, x: float, n: int) -> float:
        span = range(1,abs(n))
        if n ==0:
            return 1
        if abs(n)==1:
            temp = x
        else:
            for y in span:
                if y == 1:
                    temp = x*x
                else:
                    temp = temp * x
        if(n < 0):
            return 1/temp
        else:
            return temp
</code>```

I still have a problem with my time complexity.
Its working for many testcases, however when it trys to run with x = 0.00001 and n = 2147483647. The time limit issue arises

答:
To reduce the time complexity you can divide the work each time by taking x to the power of 2 and dividing the exponent by two. This makes a logarithmic time algorithm since the exponent is halved at each step.

Consider the following examples:

```<code>10^8 = 10^(2*4) = (10^2)^4 = (10*10)^4
</code>```

Now, there is one edge case. When the exponent is an odd number you can't integer divide it by 2. So in that case you need to multiply the results by the base one additional time.

The following is a direct recursive implementation of the above idea:

class Solution:
    def myPow(self, x: float, n: int) -> float:
        sign = -1 if n < 0 else 1
        n = abs(n)

        def helper(x, n):
            if n == 1: return x
            if n == 0: return 1

            if n % 2 == 1:
                return helper(x*x, n // 2) * x
            else:
                return helper(x*x, n // 2)

        res = helper(x, n)
        if sign == -1:
            return 1/res
        else:
            return res
```

Note that we have taken abs of the exponent and stored the sign and deal with it at the end.

Body:
So basically if i have an iteration like this in python
Ive editted the question to include my full code

class Solution:
    def myPow(self, x: float, n: int) -> float:
        temp = [];
        span = range(1,abs(n))
        if n ==0:
            return 1
        if abs(n)==1:
            temp.append(x)
        else:
            for y in span:
                if y == 1:
                    temp = []
                    temp.append(x*x)
                else:
                    temp.append(temp[-1] * x)
        if(n < 0):
            return 1/temp[-1]
        else:
            return temp[-1]

The problem link is : Pow(x,n)-leetcode
How can I modify this to conserve memory and time. Is there another data structure i can use. Im just learning python....

------------EDIT------------
ive modified the code to use a variable instead of a list for the temp data

class Solution:
    def myPow(self, x: float, n: int) -> float:
        span = range(1,abs(n))
        if n ==0:
            return 1
        if abs(n)==1:
            temp = x
        else:
            for y in span:
                if y == 1:
                    temp = x*x
                else:
                    temp = temp * x
        if(n < 0):
            return 1/temp
        else:
            return temp

I still have a problem with my time complexity.
Its working for many testcases, however when it trys to run with x = 0.00001 and n = 2147483647. The time limit issue arises

Body:
To reduce the time complexity you can divide the work each time by taking x to the power of 2 and dividing the exponent by two. This makes a logarithmic time algorithm since the exponent is halved at each step.

Consider the following examples:

10^8 = 10^(2*4) = (10^2)^4 = (10*10)^4

Now, there is one edge case. When the exponent is an odd number you can't integer divide it by 2. So in that case you need to multiply the results by the base one additional time.

The following is a direct recursive implementation of the above idea:

class Solution:
    def myPow(self, x: float, n: int) -> float:
        sign = -1 if n < 0 else 1
        n = abs(n)

        def helper(x, n):
            if n == 1: return x
            if n == 0: return 1

            if n % 2 == 1:
                return helper(x*x, n // 2) * x
            else:
                return helper(x*x, n // 2)

        res = helper(x, n)
        if sign == -1:
            return 1/res
        else:
            return res

Note that we have taken abs of the exponent and stored the sign and deal with it at the end.


问:
Is there a way to redefine the bibliography output in biblatex w/ apacite citestyle? The german translation seems to be wrong
I am trying to create a bibliography for my thesis using biblatex with the APA-citestyle. I also use the babel with german option since my thesis is in German.

My bibfile looks like this:

```<code>% literature.bib
@misc{A01,
  author = {Author, A. and Buthor, B. and Cuthor, C.},
  year = {2001},
  title = {This is the title},
  url = {https://www.google.de/},
  urldate = {2020-01-10}
}
</code>```

..and my main.tex like this:

```<code>\documentclass{scrbook}

\usepackage[utf8]{inputenc}
\usepackage{csquotes}
\usepackage[ngerman]{babel}
\usepackage[backend=biber, style=apa]{biblatex}
\addbibresource{literature.bib}

\begin{document}

\cite{A01}

\printbibliography
\end{document}
</code>```

However, on online sources the "accessed" link seems to be translated in a wrong way. It outputs "...Verfügbar + date + unter +url" which translates to "...Available + date + from url". But the date is the date I accessed the url, not the publishing date. If I change the language in the babel package to American, the output is correct.

Since I am new to Latex and Biblatex specifically, I wonder if there is a way to redefine the Output of the urldate field. I am using the Overleaf editor if that is of importance.

答:
Either use a version prior to the commit https://github.com/plk/biblatex-apa/commit/79848cf1e29a2fb0c01b2420ad4753a34b5d2bbd or fix the translation yourself:

```<code>\documentclass{scrbook}

\usepackage[utf8]{inputenc}
\usepackage{csquotes}
\usepackage[ngerman]{babel}
\usepackage[backend=biber, style=apa]{biblatex}

\DefineBibliographyStrings{ngerman}{
  retrieved = {abgerufen am},
  from      = {von},
}

\begin{filecontents}[overwrite]{\jobname.bib}
@misc{A01,
  author = {Author, A. and Buthor, B. and Cuthor, C.},
  year = {2001},
  title = {This is the title},
  url = {https://www.google.de/},
  urldate = {2020-01-10}
}
\end{filecontents}
\addbibresource{\jobname.bib}

\begin{document}
\cite{A01}
\printbibliography
\end{document}
</code>```

Body:
I am trying to create a bibliography for my thesis using biblatex with the APA-citestyle. I also use the babel with german option since my thesis is in German.

My bibfile looks like this:

% literature.bib
@misc{A01,
  author = {Author, A. and Buthor, B. and Cuthor, C.},
  year = {2001},
  title = {This is the title},
  url = {https://www.google.de/},
  urldate = {2020-01-10}
}

..and my main.tex like this:

\documentclass{scrbook}

\usepackage[utf8]{inputenc}
\usepackage{csquotes}
\usepackage[ngerman]{babel}
\usepackage[backend=biber, style=apa]{biblatex}
\addbibresource{literature.bib}

\begin{document}

\cite{A01}

\printbibliography
\end{document}

However, on online sources the "accessed" link seems to be translated in a wrong way. It outputs "...Verfügbar + date + unter +url" which translates to "...Available + date + from url". But the date is the date I accessed the url, not the publishing date. If I change the language in the babel package to American, the output is correct.

Since I am new to Latex and Biblatex specifically, I wonder if there is a way to redefine the Output of the urldate field. I am using the Overleaf editor if that is of importance.

Body:
Either use a version prior to the commit https://github.com/plk/biblatex-apa/commit/79848cf1e29a2fb0c01b2420ad4753a34b5d2bbd or fix the translation yourself:

\documentclass{scrbook}

\usepackage[utf8]{inputenc}
\usepackage{csquotes}
\usepackage[ngerman]{babel}
\usepackage[backend=biber, style=apa]{biblatex}

\DefineBibliographyStrings{ngerman}{
  retrieved = {abgerufen am},
  from      = {von},
}

\begin{filecontents}[overwrite]{\jobname.bib}
@misc{A01,
  author = {Author, A. and Buthor, B. and Cuthor, C.},
  year = {2001},
  title = {This is the title},
  url = {https://www.google.de/},
  urldate = {2020-01-10}
}
\end{filecontents}
\addbibresource{\jobname.bib}

\begin{document}
\cite{A01}
\printbibliography
\end{document}


问:
How do I handle 50 clients to server using multithreading
I am using TCP socket for server and client communication. The clients are multiple raspberry pi and server is on window. My clients only connect to server when they want to sent the message. client act like send receive and disconnect.

But my question is how to I communicate if there are 50 to 100 clients.

Is it possible to connect if all clients wants to connect at a time to server and if not then how many clients it can connect to server and it depends on what.

Can anyone show an python simple example of TCP socket using multithreading handling multiple clients.

答:
It can be done.

TCP is actually handled by your OS, not by userspace code. So the best thing you may do is to kindly ask your OS about it via the (system) calls it exposes.

As such, OS knows and is prepared for parallel calls from many user-space threads. It is protected by an appropriate locking mechanism to ensure serializability.

What you should or should not be concerned about is performance and error handling. What do you do if the Windows server you have does not accept TCP connection? What would you do if it did accept, however TCP retransmission happens over and over again and you can't pass a message? What do you do if the Windows service forcibly terminates the connection? There are many questions to ask in distributed systems.

Performance is another story. You haven't mentioned it, so I won't spend much time on it. Let me know if I should though, I'll update the post.

Now about Python specifics. Due to the "global interpreter lock" in the CPython, multithreading along with its Thread does not make your code truly parallel; at best you get single-treaded multitasking a-ka simplest possible concurrency. That shouldn't be a big problem for you, since TCP is inherently IO-bound.

The simplest you can do is to spawn a dedicated Thread per session. That kinda implies long-living sessions, otherwise, it is a resource waster and performance killer. Again, you did not mention the requirements, so I won't suggest anything.


问:
Get values from ID HTML and save in array
I'm doing a view where once I click I'm displaying

For Loop

I am having a view that captures a QR code and displays it on the screen, what I want to do next is take these values by iterating the elements with a for loop and save it in an array, in this case my ID is id="scanned-result" and I want to iterate each  containing values and saving to an array.

I am doing this but for some reason it is not performing the operation correctly. I would like to know what I should correct?

```<code>      function SubmitCodes() {
             var QRCodeval= document.querySelectorAll('scanned-result');
             var arr = [];
             for (var i in QRCodeval) {
                 alert(QRCodeval[i]);
                 arr.push( QRCodeval[i]);
             }
             alert(arr.val);
         }
</code>```

VIEW

```<code>    <div class="container">
        <div class="row">
            <div class="col-md-12" style="text-align: center;margin-bottom: 20px;">
                <div id="reader" style="display: inline-block;"></div>
                <div class="empty"></div>

                <div id="scanned-result">
                   <div>[1] - https://www.investopedia.com/terms/q/quick-response-qr-code.asp</div>
                   <div>[2] - https://www.dropbox.com/s/705b6p4a2ydvayx/EN-Poster.pdf?dl=0</div></div>
            </div>

        </div>
    </div>
</code>```

答:
There are several issues with your code. To select element by ID using querySelector you need to use # selector, also to select the divs inside you can use element > element selector.

```<code>var QRCodeval = document.querySelectorAll("#scanned-result>div");
</code>```

querySelectorAll returns a nodeList. So you need to iterate through it to get value of individual elements. But you should not use for..in. You can use forEach instead.

function submitCodes() {
  var QRCodeval = document.querySelectorAll("#scanned-result>div");
  var arr = [];
  QRCodeval.forEach((el) => arr.push(el.innerHTML));
  console.log(arr)
}

submitCodes();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="row">
    <div class="col-md-12" style="text-align: center;margin-bottom: 20px;">
      <div id="reader" style="display: inline-block;"></div>
      <div class="empty"></div>

      <div id="scanned-result">
        <div>[1] - https://www.investopedia.com/terms/q/quick-response-qr-code.asp</div>
        <div>[2] - https://www.dropbox.com/s/705b6p4a2ydvayx/EN-Poster.pdf?dl=0</div>
      </div>
    </div>

  </div>
</div></code>```

To get the text inside of the elements you can use innerHTML.

Body:
I'm doing a view where once I click I'm displaying

For Loop

I am having a view that captures a QR code and displays it on the screen, what I want to do next is take these values by iterating the elements with a for loop and save it in an array, in this case my ID is id="scanned-result" and I want to iterate each  containing values and saving to an array.

I am doing this but for some reason it is not performing the operation correctly. I would like to know what I should correct?

      function SubmitCodes() {
             var QRCodeval= document.querySelectorAll('scanned-result');
             var arr = [];
             for (var i in QRCodeval) {
                 alert(QRCodeval[i]);
                 arr.push( QRCodeval[i]);
             }
             alert(arr.val);
         }

VIEW

[1] - https://www.investopedia.com/terms/q/quick-response-qr-code.asp

[2] - https://www.dropbox.com/s/705b6p4a2ydvayx/EN-Poster.pdf?dl=0

Body:
There are several issues with your code. To select element by ID using querySelector you need to use # selector, also to select the divs inside you can use element > element selector.

var QRCodeval = document.querySelectorAll("#scanned-result>div");

querySelectorAll returns a nodeList. So you need to iterate through it to get value of individual elements. But you should not use for..in. You can use forEach instead.

function submitCodes() {
  var QRCodeval = document.querySelectorAll("#scanned-result>div");
  var arr = [];
  QRCodeval.forEach((el) => arr.push(el.innerHTML));
  console.log(arr)
}

submitCodes();

<div class="container">
  <div class="row">
    <div class="col-md-12" style="text-align: center;margin-bottom: 20px;">
      <div id="reader" style="display: inline-block;"></div>
      <div class="empty"></div>

      <div id="scanned-result">
        <div>[1] - https://www.investopedia.com/terms/q/quick-response-qr-code.asp</div>
        <div>[2] - https://www.dropbox.com/s/705b6p4a2ydvayx/EN-Poster.pdf?dl=0</div>
      </div>
    </div>

  </div>
</div>

To get the text inside of the elements you can use innerHTML.


问:
How to show original list in the list view builder once the search is clear -- FLUTTER
I have implemented a search operation on a list view builder but have not been able to show the original contact list once the search bar is clear.

```<code>class ContactsPage extends StatefulWidget {
  @override
  _ContactsPageState createState() => _ContactsPageState();
}

class _ContactsPageState extends State<ContactsPage> {
  List<Contact> _contacts = [];
  List<Contact> _contactsFiltered = [];
  TextEditingController searchController = TextEditingController();

  @override
  void initState() {
    getContacts();
    super.initState();
    searchController.addListener(() {
      filterContacts();
    });
  }

  Future<void> getContacts() async {
    final List<Contact> contacts = await ContactsService.getContacts(
      withThumbnails: false,
      photoHighResolution: false,
    );

    setState(() {
      _contacts = contacts;
    });
  }

  filterContacts() {
    List<Contact> _results = [];
    _results.addAll(_contacts);
    if (searchController.text.isNotEmpty) {
      _contacts.retainWhere((contact) {
        String searchTerm = searchController.text.toLowerCase();

        String contactName = contact.displayName!.toLowerCase();

        return contactName.contains(searchTerm);
      });
      setState(() {
        _contactsFiltered = _contacts;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    bool isSearching = searchController.text.isNotEmpty;

    return Scaffold(
        appBar: AppBar(
          title: (const Text('Contacts')),
        ),
        body: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0),
          child: Column(
            children: [
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 8.0),
                child: TextField(
                  controller: searchController,
                  decoration: const InputDecoration(
                    prefixIcon: Icon(Icons.search),
                    suffixIcon: Icon(
                      Icons.close,
                    ),
                    hintText: 'Search Customer',
                  ),
                ),
              ),
              const SizedBox(
                height: 6.0,
              ),
              Align(
                alignment: Alignment.topLeft,
                child: TextButton(
                  onPressed: () {},
                  child: const Text(
                    "  + Add new Customer",
                    style:
                        TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold),
                  ),
                ),
              ),
              Expanded(
                child: ListView.builder(
                  shrinkWrap: true,
                  itemCount: isSearching == true
                      ? _contactsFiltered.length
                      : _contacts.length,
                  itemBuilder: (BuildContext context, int index) {
                    Contact? contact = isSearching == true
                        ? _contactsFiltered[index]
                        : _contacts[index];
                    return ListTile(
                      leading: CircleAvatar(
                        child: Text(contact.initials()),
                      ),
                      title: Text(contact.displayName ?? ''),
                    );
                  },
                ),
              ),
            ],
          ),
        ));
  }
}
</code>```

I am able to search the contact list based on their name but the searching is not quite perfect. For example if I accidentally type in the wrong name then it will not show me either the original list or the filtered result

答:
You can use onChange attr of textField, check the value and then assign false to the isSearching. please check the below example :

           TextField(
                  controller: searchController,
                  onChanged: (value) {
                    if (value.isEmpty) {
                      setState(() {
                        isSearching = false;
                      });
                    }
                  },
                  decoration: const InputDecoration(
                    prefixIcon: Icon(Icons.search),
                    suffixIcon: Icon(
                      Icons.close,
                    ),
                    hintText: 'Search Customer',
                  ),
                ),
```

Body:
I have implemented a search operation on a list view builder but have not been able to show the original contact list once the search bar is clear.

class ContactsPage extends StatefulWidget {
  @override
  _ContactsPageState createState() => _ContactsPageState();
}

class _ContactsPageState extends State<ContactsPage> {
  List<Contact> _contacts = [];
  List<Contact> _contactsFiltered = [];
  TextEditingController searchController = TextEditingController();

  @override
  void initState() {
    getContacts();
    super.initState();
    searchController.addListener(() {
      filterContacts();
    });
  }

  Future<void> getContacts() async {
    final List<Contact> contacts = await ContactsService.getContacts(
      withThumbnails: false,
      photoHighResolution: false,
    );

    setState(() {
      _contacts = contacts;
    });
  }

  filterContacts() {
    List<Contact> _results = [];
    _results.addAll(_contacts);
    if (searchController.text.isNotEmpty) {
      _contacts.retainWhere((contact) {
        String searchTerm = searchController.text.toLowerCase();

        String contactName = contact.displayName!.toLowerCase();

        return contactName.contains(searchTerm);
      });
      setState(() {
        _contactsFiltered = _contacts;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    bool isSearching = searchController.text.isNotEmpty;

    return Scaffold(
        appBar: AppBar(
          title: (const Text('Contacts')),
        ),
        body: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0),
          child: Column(
            children: [
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 8.0),
                child: TextField(
                  controller: searchController,
                  decoration: const InputDecoration(
                    prefixIcon: Icon(Icons.search),
                    suffixIcon: Icon(
                      Icons.close,
                    ),
                    hintText: 'Search Customer',
                  ),
                ),
              ),
              const SizedBox(
                height: 6.0,
              ),
              Align(
                alignment: Alignment.topLeft,
                child: TextButton(
                  onPressed: () {},
                  child: const Text(
                    "  + Add new Customer",
                    style:
                        TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold),
                  ),
                ),
              ),
              Expanded(
                child: ListView.builder(
                  shrinkWrap: true,
                  itemCount: isSearching == true
                      ? _contactsFiltered.length
                      : _contacts.length,
                  itemBuilder: (BuildContext context, int index) {
                    Contact? contact = isSearching == true
                        ? _contactsFiltered[index]
                        : _contacts[index];
                    return ListTile(
                      leading: CircleAvatar(
                        child: Text(contact.initials()),
                      ),
                      title: Text(contact.displayName ?? ''),
                    );
                  },
                ),
              ),
            ],
          ),
        ));
  }
}

I am able to search the contact list based on their name but the searching is not quite perfect. For example if I accidentally type in the wrong name then it will not show me either the original list or the filtered result


问:
Variable route parameter with different datatypes
I have a controller with the following RouteAttribute:

```<code>[Route("api/[controller]/{customerId}")]
</code>```

Now I have the following action method with the route:

```<code>[HttpGet("CustomerDetails")]
public async Task<ActionResult<GetCustomerDetailsQueryResponse>> GetCustomerDetail(Guid customerId)
</code>```

Now, I would like to re-purpose this endpoint such that when I provide customer number, I should be able to get customer details based on that.

So if I make a postman call to: /api/Customers/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/CustomerDetails, I would get customer details based on the Guid Id.

Now the same endpoint should work if I make the call /api/Customers/01234/CustomerDetails.

What I have tried: I have tried the following:

```<code>[HttpGet("{customerNumber:int?}/CustomerDetails")]
public async Task<ActionResult<GetCustomerDetailsQueryResponse>> GetCustomerDetail(Guid customerId, int customerNumber)
</code>```

But unfortunately, this doesn't work. Any ideas on making this work?

答:
You want three methods:

Accept a guid, no routing attribute

Accept an int, no routing attribute

Accept a string, always route here as a string

The return types of all three method stay the same.

Method #3 will try to parse a guid, and then call method #1 if it succeeds, returning it's result. If it can't parse the guid it will try to parse an int and call method #2 if it succeeds, returning it's result. If that also fails, send a 404.

One additional step you can take is having one of the first two methods only do enough work to transform it's argument to the other method's key type, and then call that method. In this way, you only have one implementation which actually builds the response, or only one query to maintain. However, this does have a performance cost for that route, and so you want to be careful which you choose. It might even matter enough to be worth keeping both sets of code.

```<code>[ApiController]
[Route("[controller]")]
public class CustomersController : ControllerBase
{
    [HttpGet("{customerId:string}/CustomerDetails")]
    public async Task<ActionResult<GetCustomerDetailsQueryResponse>> GetCustomerDetails(string customerId)
    {   // could probably shorten this via pattern matching, but that's not part of my workflow yet
        Guid cIdGuid;
        int cIdInt;

        if (Guid.TryParse(customerId, out cId))
        {
            return CustomerDetailsGuidHelper(cIdGuid);
        }
        else if (int.TryParse(customerId, out cIdInt))
        {
            return CustomerDetailsGuidHelper(cIdInt);
        }
        else
        {
            return My404Result();
        }
    }

    private async Task<ActionResult<GetCustomerDetailsQueryResponse>> CustomerDetailsGuidHelper(Guid customerId)
    {
        int customerIntId = await DB.GetIntIdViaGuid(customerID);
        return CustomerDetailsIntHelper(customerIntId);
    }

    private async Task<ActionResult<GetCustomerDetailsQueryResponse>> CustomerDetailsIntHelper(int customerId)
    {
        // build your CustomerDetails json here
    }

}
</code>```

Body:
I have a controller with the following RouteAttribute:

[Route("api/[controller]/{customerId}")]

Now I have the following action method with the route:

[HttpGet("CustomerDetails")]
public async Task<ActionResult<GetCustomerDetailsQueryResponse>> GetCustomerDetail(Guid customerId)

Now, I would like to re-purpose this endpoint such that when I provide customer number, I should be able to get customer details based on that.

So if I make a postman call to: /api/Customers/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/CustomerDetails, I would get customer details based on the Guid Id.

Now the same endpoint should work if I make the call /api/Customers/01234/CustomerDetails.

What I have tried: I have tried the following:

[HttpGet("{customerNumber:int?}/CustomerDetails")]
public async Task<ActionResult<GetCustomerDetailsQueryResponse>> GetCustomerDetail(Guid customerId, int customerNumber)

But unfortunately, this doesn't work. Any ideas on making this work?

Body:
You want three methods:

Accept a guid, no routing attribute

Accept an int, no routing attribute

Accept a string, always route here as a string

The return types of all three method stay the same.

Method #3 will try to parse a guid, and then call method #1 if it succeeds, returning it's result. If it can't parse the guid it will try to parse an int and call method #2 if it succeeds, returning it's result. If that also fails, send a 404.

One additional step you can take is having one of the first two methods only do enough work to transform it's argument to the other method's key type, and then call that method. In this way, you only have one implementation which actually builds the response, or only one query to maintain. However, this does have a performance cost for that route, and so you want to be careful which you choose. It might even matter enough to be worth keeping both sets of code.

[ApiController]
[Route("[controller]")]
public class CustomersController : ControllerBase
{
    [HttpGet("{customerId:string}/CustomerDetails")]
    public async Task<ActionResult<GetCustomerDetailsQueryResponse>> GetCustomerDetails(string customerId)
    {   // could probably shorten this via pattern matching, but that's not part of my workflow yet
        Guid cIdGuid;
        int cIdInt;

        if (Guid.TryParse(customerId, out cId))
        {
            return CustomerDetailsGuidHelper(cIdGuid);
        }
        else if (int.TryParse(customerId, out cIdInt))
        {
            return CustomerDetailsGuidHelper(cIdInt);
        }
        else
        {
            return My404Result();
        }
    }

    private async Task<ActionResult<GetCustomerDetailsQueryResponse>> CustomerDetailsGuidHelper(Guid customerId)
    {
        int customerIntId = await DB.GetIntIdViaGuid(customerID);
        return CustomerDetailsIntHelper(customerIntId);
    }

    private async Task<ActionResult<GetCustomerDetailsQueryResponse>> CustomerDetailsIntHelper(int customerId)
    {
        // build your CustomerDetails json here
    }

}


问:
Python Plotly Dash : responsive/ autosize indicator text
How to resize text and numbers in indicator automatically when changed browser window size.

For example:

```<code>import plotly.graph_objects as go
import dash_bootstrap_components as dbc
import dash
import dash_core_components as dcc
import dash_html_components as html

indicator_style ={"height": 100, 'border-radius': '13px',
                                                       'background': '#FFFFFF 0% 0% no-repeat padding-box',
                                                       'border': '1px solid  #CECECE',
                                                       'box-shadow': '3px 3px 6px #00000029', 'padding': '6px',
                                                       }

fig_1 = go.Figure(go.Indicator(mode="number",
                                         title='<b>'+'Indicator 1'+'<b>',
                                         value=477526,
                                         number={'valueformat': '$,.0f'},
                                         domain={'x': [0, 1], 'y': [0, 1]}))
fig_1.update_traces(number_font_size=33, title_font_size=16, title_font_family='Roboto',
                                          title_font_color="#211C51")

fig_2 = go.Figure(go.Indicator(mode="number",
                                                     title='<b>'+'Indicator 2'+'<b>',
                                                     value=477526,
                                                     number={'valueformat': '$,.0f'},
                                                     domain={'x': [0, 1], 'y': [0, 1]}))
fig_2.update_traces(number_font_size=33, title_font_size=16, title_font_family='Roboto',
                                                title_font_color="#211C51")

fig_3 = go.Figure(go.Indicator(mode="number",
                                                     title='<b>'+'Indicator 3'+'<b>',
                                                     value=477526,
                                                     number={'valueformat': '$,.0f'},
                                                     domain={'x': [0, 1], 'y': [0, 1]}))
fig_3.update_traces(number_font_size=33, title_font_size=16, title_font_family='Roboto',
                                              title_font_color="#211C51")

fig_4 = go.Figure(go.Indicator(mode="number",
                                                     title='<b>'+'Indicator 4'+'<b>',
                                                     value=477526,
                                                     number={'valueformat': '$,.0f'},
                                                     domain={'x': [0, 1], 'y': [0, 1]}))
fig_4.update_traces(number_font_size=33, title_font_size=16, title_font_family='Roboto',
                                          title_font_color="#211C51")

fig_5 = go.Figure(go.Indicator(mode="number",
                                                       title='<b>'+'Indicator 5'+'<b>',
                                                       value=477526,
                                                       number={'valueformat': '$,.0f'},
                                                       domain={'x': [0, 1], 'y': [0, 1]}))
fig_5.update_traces(number_font_size=33, title_font_size=16, title_font_family='Roboto',
                                            title_font_color="#211C51")
fig_6 = go.Figure(go.Indicator(mode="number",
                                                      title='<b>'+'Indicator 6'+'<b>',
                                                      value=0.25,
                                                      number={'valueformat': '.2%'},
                                                      domain={'x': [0, 1], 'y': [0, 1]}))
fig_6.update_traces(number_font_size=33, title_font_size=16, title_font_family='Roboto',
                                           title_font_color="#211C51")

app = dash.Dash(external_stylesheets=[dbc.themes.SANDSTONE])
app.layout = html.Div([
    dbc.Row([
        dbc.Col([dcc.Graph(figure=fig_1, style=indicator_style)],width=2),
        dbc.Col([dcc.Graph(figure=fig_2, style=indicator_style)],width=2),
        dbc.Col([dcc.Graph(figure=fig_3, style=indicator_style)],width=2),
        dbc.Col([dcc.Graph(figure=fig_4, style=indicator_style)],width=2),
        dbc.Col([dcc.Graph(figure=fig_5, style=indicator_style)],width=2),
        dbc.Col([dcc.Graph(figure=fig_6, style=indicator_style)],width=2)
    ])

])

app.run_server(debug=True, use_reloader=False)  # Turn off reloader if inside Jupyter
</code>```

Normal  and Small browser size:

The indicator window decreases, but the text and numbers remain unchanged so nothing can be seen.

How can numbers and text be scaled down based on browser size?
Is there a way to detect the size of a browser window and place it as a condition within the text size settings?

答:
I don't know if I did understand correctly what's the problem you're facing but anyway I think you're not doing this in the best way.

To make the app responsive you need to add this metadata when you create the instance of your dash app:

```<code>app = dash.Dash(
    external_stylesheets=[dbc.themes.SANDSTONE],
    meta_tags=[
        {
            "name": "viewport",
            "content": "width=device-width, initial-scale=1, maximum-scale=1",
        }
    ],
)
</code>```

Instead of using Plotly figures to it, try to implement this by using html.Div() with callbacks... So you can dynamically feed your app;

I will give you a simple example using your first indicator:

```<code>app.layout = html.Div(
[
    dbc.Row(
        [
            dbc.Col(
                html.Div(
                    [
                        html.Div(f"Indicator {n}", style={"textAlign": "center"}),
                        html.Div(
                            id=f"value-{n}",
                            children=f"R$ {477526:,}",
                            style={"textAlign": "center", "fontSize": "28px"},
                        ),
                    ],
                    style=indicator_style,
                )
            )
            for n in range(6)
        ],
    ),
]
</code>```

)

By using the id in the html.Div you will be able to use a callback to send the data needed to your div and show as you want

Body:
How to resize text and numbers in indicator automatically when changed browser window size.

For example:

import plotly.graph_objects as go
import dash_bootstrap_components as dbc
import dash
import dash_core_components as dcc
import dash_html_components as html

indicator_style ={"height": 100, 'border-radius': '13px',
                                                       'background': '#FFFFFF 0% 0% no-repeat padding-box',
                                                       'border': '1px solid  #CECECE',
                                                       'box-shadow': '3px 3px 6px #00000029', 'padding': '6px',
                                                       }

fig_1 = go.Figure(go.Indicator(mode="number",
                                         title=''+'Indicator 1'+'',
                                         value=477526,
                                         number={'valueformat': '$,.0f'},
                                         domain={'x': [0, 1], 'y': [0, 1]}))
fig_1.update_traces(number_font_size=33, title_font_size=16, title_font_family='Roboto',
                                          title_font_color="#211C51")

fig_2 = go.Figure(go.Indicator(mode="number",
                                                     title=''+'Indicator 2'+'',
                                                     value=477526,
                                                     number={'valueformat': '$,.0f'},
                                                     domain={'x': [0, 1], 'y': [0, 1]}))
fig_2.update_traces(number_font_size=33, title_font_size=16, title_font_family='Roboto',
                                                title_font_color="#211C51")

fig_3 = go.Figure(go.Indicator(mode="number",
                                                     title=''+'Indicator 3'+'',
                                                     value=477526,
                                                     number={'valueformat': '$,.0f'},
                                                     domain={'x': [0, 1], 'y': [0, 1]}))
fig_3.update_traces(number_font_size=33, title_font_size=16, title_font_family='Roboto',
                                              title_font_color="#211C51")

fig_4 = go.Figure(go.Indicator(mode="number",
                                                     title=''+'Indicator 4'+'',
                                                     value=477526,
                                                     number={'valueformat': '$,.0f'},
                                                     domain={'x': [0, 1], 'y': [0, 1]}))
fig_4.update_traces(number_font_size=33, title_font_size=16, title_font_family='Roboto',
                                          title_font_color="#211C51")

fig_5 = go.Figure(go.Indicator(mode="number",
                                                       title=''+'Indicator 5'+'',
                                                       value=477526,
                                                       number={'valueformat': '$,.0f'},
                                                       domain={'x': [0, 1], 'y': [0, 1]}))
fig_5.update_traces(number_font_size=33, title_font_size=16, title_font_family='Roboto',
                                            title_font_color="#211C51")
fig_6 = go.Figure(go.Indicator(mode="number",
                                                      title=''+'Indicator 6'+'',
                                                      value=0.25,
                                                      number={'valueformat': '.2%'},
                                                      domain={'x': [0, 1], 'y': [0, 1]}))
fig_6.update_traces(number_font_size=33, title_font_size=16, title_font_family='Roboto',
                                           title_font_color="#211C51")

app = dash.Dash(external_stylesheets=[dbc.themes.SANDSTONE])
app.layout = html.Div([
    dbc.Row([
        dbc.Col([dcc.Graph(figure=fig_1, style=indicator_style)],width=2),
        dbc.Col([dcc.Graph(figure=fig_2, style=indicator_style)],width=2),
        dbc.Col([dcc.Graph(figure=fig_3, style=indicator_style)],width=2),
        dbc.Col([dcc.Graph(figure=fig_4, style=indicator_style)],width=2),
        dbc.Col([dcc.Graph(figure=fig_5, style=indicator_style)],width=2),
        dbc.Col([dcc.Graph(figure=fig_6, style=indicator_style)],width=2)
    ])

])

app.run_server(debug=True, use_reloader=False)  # Turn off reloader if inside Jupyter

Normal  and Small browser size:

The indicator window decreases, but the text and numbers remain unchanged so nothing can be seen.

How can numbers and text be scaled down based on browser size?
Is there a way to detect the size of a browser window and place it as a condition within the text size settings?

Body:
I don't know if I did understand correctly what's the problem you're facing but anyway I think you're not doing this in the best way.

To make the app responsive you need to add this metadata when you create the instance of your dash app:

app = dash.Dash(
    external_stylesheets=[dbc.themes.SANDSTONE],
    meta_tags=[
        {
            "name": "viewport",
            "content": "width=device-width, initial-scale=1, maximum-scale=1",
        }
    ],
)

Instead of using Plotly figures to it, try to implement this by using html.Div() with callbacks... So you can dynamically feed your app;

I will give you a simple example using your first indicator:

app.layout = html.Div(
[
    dbc.Row(
        [
            dbc.Col(
                html.Div(
                    [
                        html.Div(f"Indicator {n}", style={"textAlign": "center"}),
                        html.Div(
                            id=f"value-{n}",
                            children=f"R$ {477526:,}",
                            style={"textAlign": "center", "fontSize": "28px"},
                        ),
                    ],
                    style=indicator_style,
                )
            )
            for n in range(6)
        ],
    ),
]

)

By using the id in the html.Div you will be able to use a callback to send the data needed to your div and show as you want


问:
What gui library is used by sublime text editor?
I've downloaded an editor of sublimetext and I want to know what GUI library is used in there.

The filenames of files that are in the editor executables directory are:

```<code>bz2.pyd
Microsoft.VC90.CRT.manifest
msvcp90.dll
msvcr90.dll
PackageSetup.py
PackageSetup.pyc
pyexpat.pyd
python26.dll
python26.zip
select.pyd
sublimeplugin.py
sublimeplugin.pyc
sublimetext.exe
unicodedata.pyd
unins000.dat
unins000.exe
_ctypes.pyd
_elementtree.pyd
_hashlib.pyd
_socket.pyd
_ssl.pyd
</code>```

Can I find the information from the file names?

答:
a little Googling suggested it is using the Sublime GUI, which judging by the Debian source package is written in C++.

then again, running strings on the Linux sublime_text binary shows the following shared libraries (equivalent of Windows DLLs) which might suggest gtk:

```<code>/lib/ld-linux.so.2
libgtk-x11-2.0.so.0
libgdk-x11-2.0.so.0
libatk-1.0.so.0
libgio-2.0.so.0
libpangoft2-1.0.so.0
libpangocairo-1.0.so.0
libgdk_pixbuf-2.0.so.0
libcairo.so.2
libpng12.so.0
libpango-1.0.so.0
libfreetype.so.6
libfontconfig.so.1
libgobject-2.0.so.0
libgmodule-2.0.so.0
libgthread-2.0.so.0
librt.so.1
libglib-2.0.so.0
libpthread.so.0
libdl.so.2
libutil.so.1
libm.so.6
libX11.so.6
libstdc++.so.6
libgcc_s.so.1
libc.so.6
libgio-2.0.so
libgio-2.0.so.0
module.so
</code>```

this also suggests gtk.

Body:
I've downloaded an editor of sublimetext and I want to know what GUI library is used in there.

The filenames of files that are in the editor executables directory are:

bz2.pyd
Microsoft.VC90.CRT.manifest
msvcp90.dll
msvcr90.dll
PackageSetup.py
PackageSetup.pyc
pyexpat.pyd
python26.dll
python26.zip
select.pyd
sublimeplugin.py
sublimeplugin.pyc
sublimetext.exe
unicodedata.pyd
unins000.dat
unins000.exe
_ctypes.pyd
_elementtree.pyd
_hashlib.pyd
_socket.pyd
_ssl.pyd

Can I find the information from the file names?

Body:
a little Googling suggested it is using the Sublime GUI, which judging by the Debian source package is written in C++.

then again, running strings on the Linux sublime_text binary shows the following shared libraries (equivalent of Windows DLLs) which might suggest gtk:

/lib/ld-linux.so.2
libgtk-x11-2.0.so.0
libgdk-x11-2.0.so.0
libatk-1.0.so.0
libgio-2.0.so.0
libpangoft2-1.0.so.0
libpangocairo-1.0.so.0
libgdk_pixbuf-2.0.so.0
libcairo.so.2
libpng12.so.0
libpango-1.0.so.0
libfreetype.so.6
libfontconfig.so.1
libgobject-2.0.so.0
libgmodule-2.0.so.0
libgthread-2.0.so.0
librt.so.1
libglib-2.0.so.0
libpthread.so.0
libdl.so.2
libutil.so.1
libm.so.6
libX11.so.6
libstdc++.so.6
libgcc_s.so.1
libc.so.6
libgio-2.0.so
libgio-2.0.so.0
module.so

this also suggests gtk.


问:
How to solve Invalid comparison?
```<code>def show_entry_fields():
    print("Bit Diameter as cms: %s\nWell Name: %s" % (e1.get(), e2.get()))

master = tk.Tk()
tk.Label(master,
         text="Bit Diameter as cms").grid(row=0)
tk.Label(master,
         text="Well Name").grid(row=1)

e1 = tk.Entry(master)
e2 = tk.Entry(master)

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)

tk.Button(master,
          text='Quit',
          command=master.quit).grid(row=3,
                                    column=0,
                                    sticky=tk.W,
                                    pady=4)
tk.Button(master,
          text='Show', command=show_entry_fields).grid(row=3,
                                                       column=1,
                                                       sticky=tk.W,
                                                       pady=4)

tk.mainloop()

import tkinter.filedialog

file = filedialog.askopenfilename()

if file:
        try:
            filename = r"{}".format(file)
            df = pd.read_excel(file)
        except ValueError:
            label.config(text="File could not be opened")
        except FileNotFoundError:
            label.config(text="File Not Found")

data = df.loc[df['WELL'] == 'V131B'][['DEPTH_MD', 'CALIPER', 'GR', 'LITHOLOGY', 'SHALLOW', 'DEEP']]

df.loc[(df.GR < 30.0000) & (df.CALIPER > 'e1') & (df.SHALLOW > 2.60000)  , "LITHOLOGY"] = '1'
df.loc[(df.GR > 100.0000) , "LITHOLOGY"] = '3'
df.LITHOLOGY.fillna('2', inplace=True)

df

app_root.mainloop()
</code>```

I'm trying to create an interface for taking data from user. As you can see, I want user to write a value which I defined as e1. The problem is when I try to connect this with my data frame, It gives TypeError: Invalid comparison between dtype=float64 and str .

How can I solve the problem in this line? df.loc[(df.GR < 30.0000) & (df.CALIPER > 'e1') & (df.SHALLOW > 2.60000)  , "LITHOLOGY"] = '1'

Edit: I changed the type of e1 as print("Bit Diameter as cms: %s\nWell Name: %s" % (float(e1.get()), e2.get())) but still I have problems. I cannot use e1 as I want.

答:
As @cls said you are comparing a float to the string 'e1' in (df.CALIPER > 'e1').  You need to compare df.CALIPER to float( e1.get() ).  I don't have access to your files so I've not shown a second gui just a print statement.  As the first GUI will be destroyed after the quit e1.get() must be executed before destroying the application with the result stored for later access.

```<code>import tkinter as tk

def show_entry_fields():
    print("Bit Diameter as cms: %s\nWell Name: %s" % (e1.get(), e2.get()))

master = tk.Tk()
tk.Label(master,
         text="Bit Diameter as cms").grid(row=0)
tk.Label(master,
         text="Well Name").grid(row=1)

e1 = tk.Entry(master)
e2 = tk.Entry(master)

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)

e1_float = 0.0          # Storage for results on exit
e2_string = ""          # Storage for results on exit

def get_float( entry ):
    """ Converts the characters in an Entry to a float,
        returns 0.0 if not a valid float"""
    try:
        return float( entry.get() )
    except ValueError:
        return 0.0

def save_and_quit():
    global e1_float, e2_string
    e1_float = get_float( e1 )
    e2_string = e2.get()
    print( type( 'e1'),  'e1', type(e1), e1 )   # Prints to see what happens.
    print( type( e1.get()), e1.get(), type(e1_float), e1_float )
    master.destroy()

tk.Button(master,
          text='Save & Quit',
          command=save_and_quit).grid(row=3,
                                      column=0,
                                      sticky=tk.W,
                                      pady=4)
tk.Button(master,
          text='Show', command=show_entry_fields).grid(row=3,
                                                       column=1,
                                                       sticky=tk.W,
                                                       pady=4)

tk.mainloop()

print("Bit Diameter as cms: %s\nWell Name: %s" % (e1_float, e2_string))
</code>```

Title: How to solve Invalid comparison?

Body:
def show_entry_fields():
    print("Bit Diameter as cms: %s\nWell Name: %s" % (e1.get(), e2.get()))

master = tk.Tk()
tk.Label(master,
         text="Bit Diameter as cms").grid(row=0)
tk.Label(master,
         text="Well Name").grid(row=1)

e1 = tk.Entry(master)
e2 = tk.Entry(master)

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)

tk.Button(master,
          text='Quit',
          command=master.quit).grid(row=3,
                                    column=0,
                                    sticky=tk.W,
                                    pady=4)
tk.Button(master,
          text='Show', command=show_entry_fields).grid(row=3,
                                                       column=1,
                                                       sticky=tk.W,
                                                       pady=4)

tk.mainloop()

import tkinter.filedialog

file = filedialog.askopenfilename()

if file:
        try:
            filename = r"{}".format(file)
            df = pd.read_excel(file)
        except ValueError:
            label.config(text="File could not be opened")
        except FileNotFoundError:
            label.config(text="File Not Found")

data = df.loc[df['WELL'] == 'V131B'][['DEPTH_MD', 'CALIPER', 'GR', 'LITHOLOGY', 'SHALLOW', 'DEEP']]

df.loc[(df.GR < 30.0000) & (df.CALIPER > 'e1') & (df.SHALLOW > 2.60000)  , "LITHOLOGY"] = '1'
df.loc[(df.GR > 100.0000) , "LITHOLOGY"] = '3'
df.LITHOLOGY.fillna('2', inplace=True)

df

app_root.mainloop()

I'm trying to create an interface for taking data from user. As you can see, I want user to write a value which I defined as e1. The problem is when I try to connect this with my data frame, It gives TypeError: Invalid comparison between dtype=float64 and str .

How can I solve the problem in this line? df.loc[(df.GR < 30.0000) & (df.CALIPER > 'e1') & (df.SHALLOW > 2.60000)  , "LITHOLOGY"] = '1'

Edit: I changed the type of e1 as print("Bit Diameter as cms: %s\nWell Name: %s" % (float(e1.get()), e2.get())) but still I have problems. I cannot use e1 as I want.

Body:
As @cls said you are comparing a float to the string 'e1' in (df.CALIPER > 'e1').  You need to compare df.CALIPER to float( e1.get() ).  I don't have access to your files so I've not shown a second gui just a print statement.  As the first GUI will be destroyed after the quit e1.get() must be executed before destroying the application with the result stored for later access.

import tkinter as tk

def show_entry_fields():
    print("Bit Diameter as cms: %s\nWell Name: %s" % (e1.get(), e2.get()))

master = tk.Tk()
tk.Label(master,
         text="Bit Diameter as cms").grid(row=0)
tk.Label(master,
         text="Well Name").grid(row=1)

e1 = tk.Entry(master)
e2 = tk.Entry(master)

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)

e1_float = 0.0          # Storage for results on exit
e2_string = ""          # Storage for results on exit

def get_float( entry ):
    """ Converts the characters in an Entry to a float,
        returns 0.0 if not a valid float"""
    try:
        return float( entry.get() )
    except ValueError:
        return 0.0

def save_and_quit():
    global e1_float, e2_string
    e1_float = get_float( e1 )
    e2_string = e2.get()
    print( type( 'e1'),  'e1', type(e1), e1 )   # Prints to see what happens.
    print( type( e1.get()), e1.get(), type(e1_float), e1_float )
    master.destroy()

tk.Button(master,
          text='Save & Quit',
          command=save_and_quit).grid(row=3,
                                      column=0,
                                      sticky=tk.W,
                                      pady=4)
tk.Button(master,
          text='Show', command=show_entry_fields).grid(row=3,
                                                       column=1,
                                                       sticky=tk.W,
                                                       pady=4)

tk.mainloop()

print("Bit Diameter as cms: %s\nWell Name: %s" % (e1_float, e2_string))


问:
Why is my use of exception capturing not good?
```<code>def parse_input(json_str):
    json_dict = {'input': []}
    try:
        json_dict = json.loads(json_str)
        if 'input' in json_dict:
            json_dict['input'] = json.loads(json_dict['input'])
    except JSONDecodeError as e:
        print(f'Invalid json str format: {json_str} {e}')
    except TypeError as e:
        print(f'json_str is not a string: {json_str} {e}')

    return json_dict
</code>```

This function is to parse json string and ALWAYS produce a valid dict object, even if an exception occurs. However, when I process a batch of json strings, it still fails on one of the json strings, and the error is below:

```<code>json_str is not a string: null argument of type 'NoneType' is not iterable
Traceback (most recent call last):
  File "kafka_consumer.py", line 76, in <module>
    fetch_data(sys.argv[1])
  File "kafka_consumer.py", line 55, in fetch_data
    for input in json_dict['input']:
TypeError: 'NoneType' object is not subscriptable
</code>```

The code produced the error above:

```<code>        json_dict = parse_input(data)
        for input in json_dict['input']:
            unix_time = input['time']
            ...
</code>```

So the question is, why doesn't the parse_input() produce a valid dict when the exception occurs? Is my way of using the exception capturing wrong?

答:
This can occur when data is 'null'.

In that case the JSON is valid, but it represents None. And because 'input' in cannot be applied to None, this leads to the first -- handled -- error: the return value remains None.

Now the loop wants to execute, but None is not iterable, and so you get a second -- unhandled -- error.

A similar error can occur when data is '{ "input": null }'

In that case the second call to json.loads will trigger the first -- handled -- exception, and the dictionary that is returned is { "input": None }

Now the loop will bump into the same problem as above.

You should also look at the case where the JSON is valid, but just doesn't have an "input" property. In that case no except block will execute, but the main code will still have an issue to iterate over the non-existing input key.

Solution

Depending on what exactly you want to happen in that case, you could add the following statement in each of the two except blocks, and in an else block for the if:

```<code>return {'input': []}
</code>```

That way it doesn't matter that the first json.loads assigned a value to json_dict... you'll still ignore that when it doesn't pass validation, and just return the default dictionary.

Body:
def parse_input(json_str):
    json_dict = {'input': []}
    try:
        json_dict = json.loads(json_str)
        if 'input' in json_dict:
            json_dict['input'] = json.loads(json_dict['input'])
    except JSONDecodeError as e:
        print(f'Invalid json str format: {json_str} {e}')
    except TypeError as e:
        print(f'json_str is not a string: {json_str} {e}')

    return json_dict

This function is to parse json string and ALWAYS produce a valid dict object, even if an exception occurs. However, when I process a batch of json strings, it still fails on one of the json strings, and the error is below:

json_str is not a string: null argument of type 'NoneType' is not iterable
Traceback (most recent call last):
  File "kafka_consumer.py", line 76, in <module>
    fetch_data(sys.argv[1])
  File "kafka_consumer.py", line 55, in fetch_data
    for input in json_dict['input']:
TypeError: 'NoneType' object is not subscriptable

The code produced the error above:

        json_dict = parse_input(data)
        for input in json_dict['input']:
            unix_time = input['time']
            ...

So the question is, why doesn't the parse_input() produce a valid dict when the exception occurs? Is my way of using the exception capturing wrong?

Body:
This can occur when data is 'null'.

In that case the JSON is valid, but it represents None. And because 'input' in cannot be applied to None, this leads to the first -- handled -- error: the return value remains None.

Now the loop wants to execute, but None is not iterable, and so you get a second -- unhandled -- error.

A similar error can occur when data is '{ "input": null }'

In that case the second call to json.loads will trigger the first -- handled -- exception, and the dictionary that is returned is { "input": None }

Now the loop will bump into the same problem as above.

You should also look at the case where the JSON is valid, but just doesn't have an "input" property. In that case no except block will execute, but the main code will still have an issue to iterate over the non-existing input key.

Solution

Depending on what exactly you want to happen in that case, you could add the following statement in each of the two except blocks, and in an else block for the if:

return {'input': []}

That way it doesn't matter that the first json.loads assigned a value to json_dict... you'll still ignore that when it doesn't pass validation, and just return the default dictionary.


问:
How can I have case insensitive URLS in Spring MVC with annotated mappings
I have annotated mappings working great through my spring mvc web app, however, they are case sensitive. I cannot find a way to make them case insensitive. (I'd love to make this happen within Spring MVC, rather than redirecting traffic somehow)</p>

答:
Spring since version 5.3 does not use PathMatcher anymore by default, it uses PathPatternMatcher instead. To configure PathPatternMatcher, do the following:

```<code>@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        PathPatternParser patternParser = new PathPatternParser();
        patternParser.setCaseSensitive(false);
        configurer.setPatternParser(patternParser);
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Spring since version 5.3 does not use PathMatcher anymore by default, it uses PathPatternMatcher instead. To configure PathPatternMatcher, do the following:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        PathPatternParser patternParser = new PathPatternParser();
        patternParser.setCaseSensitive(false);
        configurer.setPatternParser(patternParser);
    }
}