问:
How to send data from one screen to another
I've got this problem - I can get variables from the props (being sent from MainContainer which contains navigation and those variables. (item.name, item.coordinates.latitude and item.coordinates.longitude work fine on Primary.js, but I can't get them on Map_map.js.

What i'm trying to do is to send the coords (from MainContainer.js through Primary.js which shows names of cities) into  in Map_map.js.
When it gets there, it should place a marker only on the location of the city I clicked on.

Also, I currently have Map_map in the navigation tab and when I remove it from there, I can't navigate to it anymore so I need help with that as well.

Code:
MainContainer.js

```<code>import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons';

// Screens
import Primary from './Screens/Primary';
import Secondary from './Screens/Secondary';
import Map_map from './Screens/Map_map';

// Locations
const mesta = [
  {
    name: 'Praha',
    coordinates: {
      latitude: 50.072829,
      longitude: 14.433817
  }},
  ,
  {
    name: 'České Budějovice',
    coordinates: {
      latitude: 48.975250,
      longitude: 14.479161
}},
,
  {
    name: 'Plzeň',
    coordinates: {
      latitude: 49.739296,
      longitude: 13.372455
  }},

  {
    name: 'Karlovy Vary',
    coordinates: {
      latitude: 50.231656,
      longitude: 12.869226
  }},
  {
    name: 'Ústí nad Labem',
    coordinates: {
      latitude: 50.662592,
      longitude: 14.042824
  }},
  {
    name: 'Liberec',
    coordinates: {
      latitude: 50.764136,
      longitude: 15.047840
  }},
  {
    name: 'Hradec Králové',
    coordinates: {
      latitude: 50.210071,
      longitude: 15.829660
  }},
  {
    name: 'Pardubice',
    coordinates: {
      latitude: 50.032558,
      longitude: 15.773678
  }},
  {
    name: 'Jihlava',
    coordinates: {
      latitude: 49.401642,
      longitude: 15.584001
  }},
  {
    name: 'Brno',
    coordinates: {
      latitude: 49.190254,
      longitude: 16.614144
  }},
  {
    name: 'Olomouc',
    coordinates: {
      latitude: 49.590450,
      longitude: 17.259280
  }},
  {
    name: 'Ostrava',
    coordinates: {
      latitude: 49.820469,
      longitude: 18.269387
  }},
  {
    name: 'Zlín',
    coordinates: {
      latitude: 49.224215,
      longitude: 17.668567
  }},
]

//Screen names
const lokace = "Lokace";
const mapa = "Mapa";
const mapa_det = "Mapa_det";

const Tab = createBottomTabNavigator();

function MainContainer() {
  return (
    <NavigationContainer>
      <Tab.Navigator
        initialRouteName={lokace}
        screenOptions={({ route }) => ({
          tabBarIcon: ({ focused, color, size }) => {
            let iconName;
            let rn = route.name;

            if (rn === lokace) {
              iconName = focused ? 'home' : 'home-outline';

            } else if (rn === mapa) {
              iconName = focused ? 'map' : 'map-outline';
            }
            else if (rn === mapa_det) {
              iconName = focused ? 'locate' : 'locate-outline';
            }
            // You can return any component that you like here!
            return <Ionicons name={iconName} size={size} color={color} />;
          },
        })}
        tabBarOptions={{
          activeTintColor: '#007aff',
          inactiveTintColor: 'grey',
          labelStyle: { paddingBottom: 10, fontSize: 10 },
          style: { padding: 10, height: 70}
        }}>

        <Tab.Screen name={lokace} children={() => <Primary towns={mesta}/>}/>
        <Tab.Screen name={mapa} children={() => <Secondary towns={mesta}/>}/>
        <Tab.Screen name={mapa_det} component={Map_map}/>

      </Tab.Navigator>
    </NavigationContainer>
  );
}

export default MainContainer;
</code>```

(inside "nav" folder): Primary.js, Secondary.js, Map_map.js

Primary.js

```<code>import * as React from 'react';
import { StyleSheet, ScrollView, View, Text, Image } from 'react-native';
import { useNavigation } from '@react-navigation/native';

export default function Primary(props)
{
    const navigation = useNavigation();
    const map_map = "Map_map";
    return(
        <ScrollView style=
            {{
                flex: 1,
            }}>
            <View>
                {props.towns.map(item => (
                    <Text
                    style={styles.card}
                    onPress={() => navigation.navigate('Map_map', item.coordinates)}
                    >
                        {item.name}
                        {item.coordinates.latitude }
                        {item.coordinates.longitude}
                    </Text>
                ))}
            </View>
            </ScrollView>
    );
}

const styles = StyleSheet.create({
    card:{
        backgroundColor: "#007aff",
        borderRadius: 50,
        alignItems: 'center',
        margin: 5,
        padding: 10,
        color: 'white',
        fontWeight: 'bold'
    },
    card2:{
        backgroundColor: "#FF3300",
        borderRadius: 50,
        alignItems: 'center',
        margin: 5,
        padding: 10,
        color: 'white',
        fontWeight: 'bold'
    },
  });
</code>```

Map_map.js

```<code>import * as React from 'react';
import { StyleSheet, View, Text, Image } from 'react-native';
import Primary from './Primary.js';
import MapView, {PROVIDER_GOOGLE, Marker} from 'react-native-maps';

function ProfileScreen({ navigation: { goBack } }) {
    return (
      <View>
        <Button onPress={() => goBack()} title="Go back from ProfileScreen" />
      </View>
    );
  }

export default function Map_map({ navigation }) {
    return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <MapView
                style={styles.map}
                provider={PROVIDER_GOOGLE}
                //specify our coordinates.
                initialRegion=
                {{
                latitude: 49.061880,
                longitude: 17.349916,
                latitudeDelta: 0.002,
                longitudeDelta: 0.002,
                }}
            >
                <Marker
                    //coordinate={navigation.getParam(item.coordinates)}
                        // latitude: 49.061880,
                        // longitude: 17.349916,

                />
            </MapView>
        </View>
    );
}
const styles = StyleSheet.create({
    map: {
      height: '100%',
      width: '100%'
    },
  });
</code>```

答:
As you can see in the documentation you can pass param to another screen in the second parameter of navigate function.</p>
```<code>navigation.navigate('Screen_Name', { param: 'abc' })
</code>```

Body:
I've got this problem - I can get variables from the props (being sent from MainContainer which contains navigation and those variables. (item.name, item.coordinates.latitude and item.coordinates.longitude work fine on Primary.js, but I can't get them on Map_map.js.

What i'm trying to do is to send the coords (from MainContainer.js through Primary.js which shows names of cities) into  in Map_map.js.
When it gets there, it should place a marker only on the location of the city I clicked on.

Also, I currently have Map_map in the navigation tab and when I remove it from there, I can't navigate to it anymore so I need help with that as well.

Code:
MainContainer.js

import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons';

// Screens
import Primary from './Screens/Primary';
import Secondary from './Screens/Secondary';
import Map_map from './Screens/Map_map';

// Locations
const mesta = [
  {
    name: 'Praha',
    coordinates: {
      latitude: 50.072829,
      longitude: 14.433817
  }},
  ,
  {
    name: 'České Budějovice',
    coordinates: {
      latitude: 48.975250,
      longitude: 14.479161
}},
,
  {
    name: 'Plzeň',
    coordinates: {
      latitude: 49.739296,
      longitude: 13.372455
  }},

  {
    name: 'Karlovy Vary',
    coordinates: {
      latitude: 50.231656,
      longitude: 12.869226
  }},
  {
    name: 'Ústí nad Labem',
    coordinates: {
      latitude: 50.662592,
      longitude: 14.042824
  }},
  {
    name: 'Liberec',
    coordinates: {
      latitude: 50.764136,
      longitude: 15.047840
  }},
  {
    name: 'Hradec Králové',
    coordinates: {
      latitude: 50.210071,
      longitude: 15.829660
  }},
  {
    name: 'Pardubice',
    coordinates: {
      latitude: 50.032558,
      longitude: 15.773678
  }},
  {
    name: 'Jihlava',
    coordinates: {
      latitude: 49.401642,
      longitude: 15.584001
  }},
  {
    name: 'Brno',
    coordinates: {
      latitude: 49.190254,
      longitude: 16.614144
  }},
  {
    name: 'Olomouc',
    coordinates: {
      latitude: 49.590450,
      longitude: 17.259280
  }},
  {
    name: 'Ostrava',
    coordinates: {
      latitude: 49.820469,
      longitude: 18.269387
  }},
  {
    name: 'Zlín',
    coordinates: {
      latitude: 49.224215,
      longitude: 17.668567
  }},
]

//Screen names
const lokace = "Lokace";
const mapa = "Mapa";
const mapa_det = "Mapa_det";

const Tab = createBottomTabNavigator();

function MainContainer() {
  return (
    <NavigationContainer>
      <Tab.Navigator
        initialRouteName={lokace}
        screenOptions={({ route }) => ({
          tabBarIcon: ({ focused, color, size }) => {
            let iconName;
            let rn = route.name;

            if (rn === lokace) {
              iconName = focused ? 'home' : 'home-outline';

            } else if (rn === mapa) {
              iconName = focused ? 'map' : 'map-outline';
            }
            else if (rn === mapa_det) {
              iconName = focused ? 'locate' : 'locate-outline';
            }
            // You can return any component that you like here!
            return <Ionicons name={iconName} size={size} color={color} />;
          },
        })}
        tabBarOptions={{
          activeTintColor: '#007aff',
          inactiveTintColor: 'grey',
          labelStyle: { paddingBottom: 10, fontSize: 10 },
          style: { padding: 10, height: 70}
        }}>

        <Tab.Screen name={lokace} children={() => <Primary towns={mesta}/>}/>
        <Tab.Screen name={mapa} children={() => <Secondary towns={mesta}/>}/>
        <Tab.Screen name={mapa_det} component={Map_map}/>

      </Tab.Navigator>
    </NavigationContainer>
  );
}

export default MainContainer;

(inside "nav" folder): Primary.js, Secondary.js, Map_map.js

Primary.js

import * as React from 'react';
import { StyleSheet, ScrollView, View, Text, Image } from 'react-native';
import { useNavigation } from '@react-navigation/native';

export default function Primary(props)
{
    const navigation = useNavigation();
    const map_map = "Map_map";
    return(
        <ScrollView style=
            {{
                flex: 1,
            }}>
            <View>
                {props.towns.map(item => (
                    <Text
                    style={styles.card}
                    onPress={() => navigation.navigate('Map_map', item.coordinates)}
                    >
                        {item.name}
                        {item.coordinates.latitude }
                        {item.coordinates.longitude}
                    </Text>
                ))}
            </View>
            </ScrollView>
    );
}

const styles = StyleSheet.create({
    card:{
        backgroundColor: "#007aff",
        borderRadius: 50,
        alignItems: 'center',
        margin: 5,
        padding: 10,
        color: 'white',
        fontWeight: 'bold'
    },
    card2:{
        backgroundColor: "#FF3300",
        borderRadius: 50,
        alignItems: 'center',
        margin: 5,
        padding: 10,
        color: 'white',
        fontWeight: 'bold'
    },
  });

Map_map.js

import * as React from 'react';
import { StyleSheet, View, Text, Image } from 'react-native';
import Primary from './Primary.js';
import MapView, {PROVIDER_GOOGLE, Marker} from 'react-native-maps';

function ProfileScreen({ navigation: { goBack } }) {
    return (
      <View>
        <Button onPress={() => goBack()} title="Go back from ProfileScreen" />
      </View>
    );
  }

export default function Map_map({ navigation }) {
    return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <MapView
                style={styles.map}
                provider={PROVIDER_GOOGLE}
                //specify our coordinates.
                initialRegion=
                {{
                latitude: 49.061880,
                longitude: 17.349916,
                latitudeDelta: 0.002,
                longitudeDelta: 0.002,
                }}
            >
                <Marker
                    //coordinate={navigation.getParam(item.coordinates)}
                        // latitude: 49.061880,
                        // longitude: 17.349916,

                />
            </MapView>
        </View>
    );
}
const styles = StyleSheet.create({
    map: {
      height: '100%',
      width: '100%'
    },
  });

Body:
As you can see in the documentation you can pass param to another screen in the second parameter of navigate function.

navigation.navigate('Screen_Name', { param: 'abc' })


来源: stackexchange

问:
Docker: The framework 'Microsoft.WindowsDesktop.App', version '3.1.0' (x64) was not found
I have an existing dotnet core 3.1 web app that builds and deploys to an azure app service.  it works fine.   I am trying to containerize the app.

the build is fine, but when the container runs it gives me

```<code>It was not possible to find any compatible framework version
The framework 'Microsoft.WindowsDesktop.App', version '3.1.0' (x64) was not found.
  - No frameworks were found.
You can resolve the problem by installing the specified framework and/or SDK.
</code>```

my docker

```<code>FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /source

# copy csproj and restore as distinct layers
COPY myreports/*.csproj .

RUN dotnet restore

# copy and publish app and libraries
COPY . .
RUN dotnet publish -c release -o /app

# final stage/image
FROM mcr.microsoft.com/dotnet/runtime:6.0
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "myreports.dll"]
</code>```

I've tried a variety of docker images(inc dotnet/core) and its the same.
my csproj

```<code><Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <RootNamespace>myreports</RootNamespace>
    <UserSecretsId>ed68b972-ed89-4115-8e6c-5f0d032efa4d</UserSecretsId>
    <DockerDefaultTargetOS>Windows</DockerDefaultTargetOS>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Azure.Storage.Blobs" Version="12.8.0" />
    <PackageReference Include="FastReport.Core3.Web" Version="2021.3.0" />
    <PackageReference Include="Microsoft.ApplicationInsights" Version="2.16.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.16.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.PerfCounterCollector" Version="2.16.0" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.9" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.9">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <!--PackageReference Include="Microsoft.Extensions.Logging.ApplicationInsights" Version="2.14.0" /-->
    <PackageReference Include="Microsoft.AspNetCore.AzureAppServices.HostingStartup" Version="3.1.9" />
    <PackageReference Include="Microsoft.Azure.EventGrid" Version="3.0.0" />
    <PackageReference Include="Microsoft.Azure.Management.ResourceManager" Version="1.6.0-preview" />
    <PackageReference Include="Microsoft.IdentityModel.Clients.ActiveDirectory" Version="4.5.0" />
    <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.14.0" />
  </ItemGroup>
</Project>
</code>```

I suspect its this
    <PackageReference Include="FastReport.Core3.Web" Version="2021.3.0" />

But its required as its core to the project.   What gets me is that my config in the (working) app settings is:

答:
Following your answer on changing the image to mcr.microsoft.com/dotnet/framework/sdk:4.8-windowsservercore-ltsc2019

If you did not change your csproj you now have a .NET Core 3.1 app running on .NET 4.8. This could lead to subtle runtime problems. (citation needed)

I would strongly suggest upgrading your csproj to .NET 6 since .NET 3.1 is running out of support in some months anyways.

I might be mistaken but the first step would be to change <TargetFramework>netcoreapp3.1</TargetFramework> to <TargetFramework>net6.0</TargetFramework> and of course follow an upgrade guide online https://learn.microsoft.com/en-us/aspnet/core/migration/31-to-60?view=aspnetcore-6.0&tabs=visual-studio

ContentLicense: CC BY-SA 4.0

Body:
I have an existing dotnet core 3.1 web app that builds and deploys to an azure app service.  it works fine.   I am trying to containerize the app.

the build is fine, but when the container runs it gives me

It was not possible to find any compatible framework version
The framework 'Microsoft.WindowsDesktop.App', version '3.1.0' (x64) was not found.
  - No frameworks were found.
You can resolve the problem by installing the specified framework and/or SDK.

my docker

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /source

# copy csproj and restore as distinct layers
COPY myreports/*.csproj .

RUN dotnet restore

# copy and publish app and libraries
COPY . .
RUN dotnet publish -c release -o /app

# final stage/image
FROM mcr.microsoft.com/dotnet/runtime:6.0
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "myreports.dll"]

I've tried a variety of docker images(inc dotnet/core) and its the same.
my csproj

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <RootNamespace>myreports</RootNamespace>
    <UserSecretsId>ed68b972-ed89-4115-8e6c-5f0d032efa4d</UserSecretsId>
    <DockerDefaultTargetOS>Windows</DockerDefaultTargetOS>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Azure.Storage.Blobs" Version="12.8.0" />
    <PackageReference Include="FastReport.Core3.Web" Version="2021.3.0" />
    <PackageReference Include="Microsoft.ApplicationInsights" Version="2.16.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.16.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.PerfCounterCollector" Version="2.16.0" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.9" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.9">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>

    <PackageReference Include="Microsoft.AspNetCore.AzureAppServices.HostingStartup" Version="3.1.9" />
    <PackageReference Include="Microsoft.Azure.EventGrid" Version="3.0.0" />
    <PackageReference Include="Microsoft.Azure.Management.ResourceManager" Version="1.6.0-preview" />
    <PackageReference Include="Microsoft.IdentityModel.Clients.ActiveDirectory" Version="4.5.0" />
    <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.14.0" />
  </ItemGroup>
</Project>

I suspect its this
    <PackageReference Include="FastReport.Core3.Web" Version="2021.3.0" />

But its required as its core to the project.   What gets me is that my config in the (working) app settings is:


问:
How to map for range values in Python Pandas
I have a dataset like below:

```<code>Customer_ID Policy_No   Age Channel Status  Income
123 5432    5   DD  Lapse   300000
123 5431    1   Agency  Active  420000
234 4352    7   DD  Lapse   650000
</code>```

and a master dataset:

```<code>Group   Attributes  S2SFlag
Age 1 to 5  Yes
Age 6 to 10 No
Channel DD  Yes
Channel Agency  Yes
Status  Lapse   Yes
Status  Active  No
Income  300000 to 500000    Yes
Income  500000 to 700000    No
</code>```

Here, the condition is to check the associated value for the Group and its value from the dataset with the master dataset and pick the S2SFlag column value from the master dataset and create an S2SFlag column in the dataset. The original dataset is returned by querying the database using AWS Lambda.

Also, if post-checking if there is a 'No' value for any of the Group attributes/row then the Flag for that particular group would be 'No'. The expected output is as below:

I have tried the below code but it is giving me the error:

```<code>import pandas as pd
import re

df1 = pd.read_csv('')  # Master table

def to_range(s):
    m = re.match('(\d+) to (\d+)$', s)
    return range(int(m.group(1)), int(m.group(2)) + 1) if m else s

df1 = (df1.assign(Attributes=[to_range(s) for s in df1['Attributes']])
       .explode('Attributes'))

df2 = pd.read_csv('')  # Assuming it as query results

mapping_Age = df1[df1['Group'] == 'Age'].set_index('Attributes')['S2SFlag'] == 'Yes'

mapping_Channel = df1[df1['Group'] == 'Channel'].set_index('Attributes')['S2SFlag'] == 'Yes'

mapping_Status = df1[df1['Group'] == 'Status'].set_index('Attributes')['S2SFlag'] == 'Yes'

mapping_Income = df1[df1['Group'] == 'Income'].set_index('Attributes')['S2SFlag'] == 'Yes'
mapped_Age = df2['Age'].map(mapping_Age)
mapped_Channel = df2['Channel'].map(mapping_Channel)
mapped_Status = df2['Status'].map(mapping_Status)
mapped_Income = df2['Income'].map(mapping_Income)

df2['S2SFlag'] = (mapped_Age & mapped_Status & mapped_Channel & mapped_Income).map({True: 'Yes', False: 'No'})

Traceback (most recent call last):
  File "", line 27, in <module>
    mapped_Income = df2['Income'].map(mapping_Income)
  File "", line 4161, in map
    new_values = super()._map_values(arg, na_action=na_action)
  File "", line 842, in _map_values
    indexer = mapper.index.get_indexer(values)
  File "", line 3442, in get_indexer
    raise InvalidIndexError(self._requires_unique_msg)
pandas.errors.InvalidIndexError: Reindexing only valid with uniquely valued Index objects
</code>```

Also, I tried something like below which also gave me another error:

```<code>import pandas as pd
import re

df1 = pd.read_csv('') #Master table
df2 = pd.read_csv('') #Dataset
df1 = df1[df1['Group'] == 'Income']

for i, j in df2['Income'].iteritems():
for k, l in zip(df1['Attributes'], df1['S2SFlag']):
    start = k.split(" to ")[0]
    end = k.split(" to ")[1]
    if j in range(int(start), int(end)):
        print("J ", j, " l ", l)
        df2['S2SFlag'] = l
</code>```

Output:

```<code>  Customer_ID  Policy_No  Age Channel  Status  Income S2SFlag
0          123       5432    5      DD   Lapse  300000      No
1          123       5431    1  Agency  Active  420000      No
2          234       4352    7      DD   Lapse  650000      No
</code>```

Where am I going wrong?

Update 1:

As per Raymond, everything worked like a charm except for one scenario where I am not getting the output as expected.

Master Data:

```<code>Group   Attributes  S2SFlag
Insured Age Group   1 to 20 Yes
Insured Age Group   21 to 25    Yes
Insured Age Group   26 to 30    Yes
Insured Age Group   31 to 40    Yes
Insured Age Group   41 to 50    Yes
Insured Age Group   51 to 100   Yes
Policy Status   Lapse   Yes
Policy Status   Active  Yes
Policy Status   RPU No
Policy Status   Paid Up/ PPT Over   Yes
Policy Status   Claim settled   Yes
Policy Status   Claim rejected  No
Income Group    0 to 300000 Yes
Income Group    300001 to 500000    Yes
Income Group    500001 to 700000    Yes
Income Group    700001 to 1000000   Yes
Income Group    1000001 to 1500000  Yes
Income Group    1500001 to 1600000  Yes
Marrital status Single  Yes
Marrital status Married Yes
Marrital status Divorced    Yes
Marrital status Married with a child    Yes
Marrital status Single Parent   Yes
Marrital status 2 children  Yes
Occupation  Salaried    Yes
Occupation  Daily wage  No
Occupation  Self employed with <5LPA    No
Occupation  Self employed with >5LPA    Yes
Occupation  House wife  Yes
Occupation  House Husband   Yes
Education   1 to 10 Yes
Education   11 to 12    Yes
Education   Diploma Yes
Education   Graduate    Yes
Education   Post Graduate   Yes
Education   Doctoral    Yes
Fund Value  Positive    Yes
Fund Value  Negative    No
Fund Value  Zero    No
</code>```

When I tried printing the mapped values for Education, it gave me results like below:

```<code>mapped_Education = df2['Education'].map(mapping_Education)
print(mapped_Education)

0     NaN
1     NaN
2    True
Name: Education, dtype: object
</code>```

Dataset:

```<code>Customer_ID Policy_No   Age Status  Income  Marital_Status  Occupation  Education   Fund Value
123 5432    5   Lapse   300000  Single  Salaried    6   Positive
123 5431    1   Active  420000  Married Daily wage  11  Zero
234 4352    7   Lapse   650000  Divorced    Daily wage  Doctoral    Zero
</code>```

Due to this, I am getting output as below:

```<code> Customer_ID  Policy_No  Age  Status  ...  Occupation Education Fund Value S2SFlag
0          123       5432    5   Lapse  ...    Salaried         6   Positive      No
1          123       5431    1  Active  ...  Daily wage        11       Zero      No
2          234       4352    7   Lapse  ...  Daily wage  Doctoral       Zero      No
</code>```

Where S2SFlag for the first record should have been 'Yes'

答:
The error Reindexing only valid with uniquely valued Index objects says that map requires your mapping_Income to have unique index, and the index originates from df1[df1['Group'] == 'Income'].set_index('Attributes') where the 'Attributes' for Income contains exploded values that are not unique.

Your code for exploding is range inclusive, so when you explode the two ranges for Income, 500000 will appear once in each explode, ending up with two 500000 and thus the error. Please try to modify either one of the ranges to exclude its 500000, e.g. make the second range 500001 to 700000.

For Update 1:

I suspect it has to do with data-type again. The exploded value could be integers, but all values of df2['Education'] are string.

One quick fix is to change everything into strings.

#1 add df1['Attributes'] = df1['Attributes'].astype(str) after the line for explode

#2 add df2 = df2.astype(str) before any map to make all contents strings

Body:
I have a dataset like below:

Customer_ID Policy_No   Age Channel Status  Income
123 5432    5   DD  Lapse   300000
123 5431    1   Agency  Active  420000
234 4352    7   DD  Lapse   650000

and a master dataset:

Group   Attributes  S2SFlag
Age 1 to 5  Yes
Age 6 to 10 No
Channel DD  Yes
Channel Agency  Yes
Status  Lapse   Yes
Status  Active  No
Income  300000 to 500000    Yes
Income  500000 to 700000    No

Here, the condition is to check the associated value for the Group and its value from the dataset with the master dataset and pick the S2SFlag column value from the master dataset and create an S2SFlag column in the dataset. The original dataset is returned by querying the database using AWS Lambda.

Also, if post-checking if there is a 'No' value for any of the Group attributes/row then the Flag for that particular group would be 'No'. The expected output is as below:

I have tried the below code but it is giving me the error:

import pandas as pd
import re

df1 = pd.read_csv('')  # Master table

def to_range(s):
    m = re.match('(\d+) to (\d+)$', s)
    return range(int(m.group(1)), int(m.group(2)) + 1) if m else s

df1 = (df1.assign(Attributes=[to_range(s) for s in df1['Attributes']])
       .explode('Attributes'))

df2 = pd.read_csv('')  # Assuming it as query results

mapping_Age = df1[df1['Group'] == 'Age'].set_index('Attributes')['S2SFlag'] == 'Yes'

mapping_Channel = df1[df1['Group'] == 'Channel'].set_index('Attributes')['S2SFlag'] == 'Yes'

mapping_Status = df1[df1['Group'] == 'Status'].set_index('Attributes')['S2SFlag'] == 'Yes'

mapping_Income = df1[df1['Group'] == 'Income'].set_index('Attributes')['S2SFlag'] == 'Yes'
mapped_Age = df2['Age'].map(mapping_Age)
mapped_Channel = df2['Channel'].map(mapping_Channel)
mapped_Status = df2['Status'].map(mapping_Status)
mapped_Income = df2['Income'].map(mapping_Income)

df2['S2SFlag'] = (mapped_Age & mapped_Status & mapped_Channel & mapped_Income).map({True: 'Yes', False: 'No'})

Traceback (most recent call last):
  File "", line 27, in <module>
    mapped_Income = df2['Income'].map(mapping_Income)
  File "", line 4161, in map
    new_values = super()._map_values(arg, na_action=na_action)
  File "", line 842, in _map_values
    indexer = mapper.index.get_indexer(values)
  File "", line 3442, in get_indexer
    raise InvalidIndexError(self._requires_unique_msg)
pandas.errors.InvalidIndexError: Reindexing only valid with uniquely valued Index objects

Also, I tried something like below which also gave me another error:

import pandas as pd
import re

df1 = pd.read_csv('') #Master table
df2 = pd.read_csv('') #Dataset
df1 = df1[df1['Group'] == 'Income']

for i, j in df2['Income'].iteritems():
for k, l in zip(df1['Attributes'], df1['S2SFlag']):
    start = k.split(" to ")[0]
    end = k.split(" to ")[1]
    if j in range(int(start), int(end)):
        print("J ", j, " l ", l)
        df2['S2SFlag'] = l

Output:

  Customer_ID  Policy_No  Age Channel  Status  Income S2SFlag
0          123       5432    5      DD   Lapse  300000      No
1          123       5431    1  Agency  Active  420000      No
2          234       4352    7      DD   Lapse  650000      No

Where am I going wrong?

Update 1:

As per Raymond, everything worked like a charm except for one scenario where I am not getting the output as expected.

Master Data:

Group   Attributes  S2SFlag
Insured Age Group   1 to 20 Yes
Insured Age Group   21 to 25    Yes
Insured Age Group   26 to 30    Yes
Insured Age Group   31 to 40    Yes
Insured Age Group   41 to 50    Yes
Insured Age Group   51 to 100   Yes
Policy Status   Lapse   Yes
Policy Status   Active  Yes
Policy Status   RPU No
Policy Status   Paid Up/ PPT Over   Yes
Policy Status   Claim settled   Yes
Policy Status   Claim rejected  No
Income Group    0 to 300000 Yes
Income Group    300001 to 500000    Yes
Income Group    500001 to 700000    Yes
Income Group    700001 to 1000000   Yes
Income Group    1000001 to 1500000  Yes
Income Group    1500001 to 1600000  Yes
Marrital status Single  Yes
Marrital status Married Yes
Marrital status Divorced    Yes
Marrital status Married with a child    Yes
Marrital status Single Parent   Yes
Marrital status 2 children  Yes
Occupation  Salaried    Yes
Occupation  Daily wage  No
Occupation  Self employed with <5LPA    No
Occupation  Self employed with >5LPA    Yes
Occupation  House wife  Yes
Occupation  House Husband   Yes
Education   1 to 10 Yes
Education   11 to 12    Yes
Education   Diploma Yes
Education   Graduate    Yes
Education   Post Graduate   Yes
Education   Doctoral    Yes
Fund Value  Positive    Yes
Fund Value  Negative    No
Fund Value  Zero    No

When I tried printing the mapped values for Education, it gave me results like below:

mapped_Education = df2['Education'].map(mapping_Education)
print(mapped_Education)

0     NaN
1     NaN
2    True
Name: Education, dtype: object

Dataset:

Customer_ID Policy_No   Age Status  Income  Marital_Status  Occupation  Education   Fund Value
123 5432    5   Lapse   300000  Single  Salaried    6   Positive
123 5431    1   Active  420000  Married Daily wage  11  Zero
234 4352    7   Lapse   650000  Divorced    Daily wage  Doctoral    Zero

Due to this, I am getting output as below:

 Customer_ID  Policy_No  Age  Status  ...  Occupation Education Fund Value S2SFlag
0          123       5432    5   Lapse  ...    Salaried         6   Positive      No
1          123       5431    1  Active  ...  Daily wage        11       Zero      No
2          234       4352    7   Lapse  ...  Daily wage  Doctoral       Zero      No

Where S2SFlag for the first record should have been 'Yes'


问:
Name 'Actor' is not defined
I have a problem with python programming, when I'm trying to write a game (introduced by the book: Coding Games Python DK 3), it says:
name 'Actor' is not defined.

here's my code:

```<code>import pgzrun

from random import randint

WIDTH = 400
HEIGHT = 400

dots = []
lines = []

next_dot = 0

for dot in range(0, 10):
    actor = Actor("dot")
    actor.pos = randint(20, WIDTH -20), randint (20, HEIGHT - 20)
    dots.append(actor)

def draw():
    screen.fill("black")
    number = 1
    for dot in dots:
        screen.draw.text(str(number), (dot.pos[0], dot.pos[1] + 12))
    dot.draw()
    number = number + 1

for line in lines:
    screen.draw.line(line[0], line[1], (100, 0, 0))

pgzrun.go()
</code>```

答: I had the exact same problem at the exact same code. After weeks of deleting and rewriting everything that has to do with python on my computer, I realised that it runs if you make the screen. ... lines comments by writing # in the start of each of them. I haven't found how to fix it yet, but I will inform when I will.</p>

Title: Name 'Actor' is not defined

Body:
I have a problem with python programming, when I'm trying to write a game (introduced by the book: Coding Games Python DK 3), it says:
name 'Actor' is not defined.

here's my code:

import pgzrun

from random import randint

WIDTH = 400
HEIGHT = 400

dots = []
lines = []

next_dot = 0

for dot in range(0, 10):
    actor = Actor("dot")
    actor.pos = randint(20, WIDTH -20), randint (20, HEIGHT - 20)
    dots.append(actor)

def draw():
    screen.fill("black")
    number = 1
    for dot in dots:
        screen.draw.text(str(number), (dot.pos[0], dot.pos[1] + 12))
    dot.draw()
    number = number + 1

for line in lines:
    screen.draw.line(line[0], line[1], (100, 0, 0))

pgzrun.go()


问:
why can't I use the same javascript toggle button twice?
I'm attempting to utilize this javascript toggle button in two separate parts on the same page, but I'm having trouble. I tried altering the id as well, but it didn't work. Is it impossible to complete it, or am I overlooking something? I am not an expert in javascript and am a complete novice, so any help would be greatly appreciated.

function toggleText() {
  var showMoreText = document.getElementById("more");
  var buttonText   = document.querySelector("#moreButton span");
  var moreIcon     = document.querySelector("#moreButton img");

  if (startpoint.style.display === "none") {
    showMoreText.style.display = "none";
    startpoint.style.display = "table-cell";
    buttonText.innerHTML = "Show More";
    buttonText.classList.remove('less');
    moreIcon.classList.remove('less');
  } else {
    showMoreText.style.display = "table-cell";
    startpoint.style.display = "none";
    buttonText.innerHTML = "Show Less";
    buttonText.classList.add('less');
    moreIcon.classList.add('less');
  }
}

function toggleText2() {
  var showMoreText2 = document.getElementById("more2");
  var buttonText2   = document.querySelector("#moreButton2 span");
  var moreIcon2     = document.querySelector("#moreButton2 img");

  if (startpoint.style.display === "none") {
    showMoreText.style.display = "none";
    startpoint.style.display = "table-cell";
    buttonText.innerHTML = "Show More";
    buttonText.classList.remove('less2');
    moreIcon.classList.remove('less2');
  } else {
    showMoreText.style.display = "table-cell";
    startpoint.style.display = "none";
    buttonText.innerHTML = "Show Less";
    buttonText.classList.add('less2');
    moreIcon.classList.add('less2');
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

<div class="container-fluid clientbox text-center">
  <div class="row">
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>

    <div id="startpoint"></div>
    <div id="more">
      <div class="row">
        <div class="col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
        <div class="col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
        <div class=" col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
        <div class="col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
      </div>
    </div>
    <button onclick="toggleText()" id="moreButton">
            <span class="pink">Show More</span>
            <img class="more" src="./images/load-more.png" alt="">
            </button>
  </div>
</div>

<br>
<br>
<br>
<br>

<div class="container-fluid clientbox text-center">
  <div class="row">
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>

    <div id="startpoint2"></div>
    <div id="more2">
      <div class="row">
        <div class="col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
        <div class="col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
        <div class=" col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
        <div class="col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
      </div>
    </div>
    <button onclick="toggleText2()" id="moreButton2">
            <span class="pink2">Show More</span>
            <img class="more2" src="./images/load-more.png" alt="">
            </button>
  </div>
</div></code>```

答:
The correct way to do that:

document.querySelectorAll('button.moreButton').forEach(bt =>
  {
  let
    moreItem = bt.closest('div.row').querySelector('div.more_items')
  , spPink   = bt.querySelector('span.pink')
    ;
  bt.onclick =_=>
    {
    spPink.textContent = moreItem.classList.toggle('noDisplay') ? 'Show More' : 'Show Less'
    }
  })```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.more_items.noDisplay {
  display: none;
}</code>```

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />

      <button class="moreButton">
        Show Less

      </button>

      <button class="moreButton">
        Show Less

      </button>

```

Body:
I'm attempting to utilize this javascript toggle button in two separate parts on the same page, but I'm having trouble. I tried altering the id as well, but it didn't work. Is it impossible to complete it, or am I overlooking something? I am not an expert in javascript and am a complete novice, so any help would be greatly appreciated.

function toggleText() {
  var showMoreText = document.getElementById("more");
  var buttonText   = document.querySelector("#moreButton span");
  var moreIcon     = document.querySelector("#moreButton img");

  if (startpoint.style.display === "none") {
    showMoreText.style.display = "none";
    startpoint.style.display = "table-cell";
    buttonText.innerHTML = "Show More";
    buttonText.classList.remove('less');
    moreIcon.classList.remove('less');
  } else {
    showMoreText.style.display = "table-cell";
    startpoint.style.display = "none";
    buttonText.innerHTML = "Show Less";
    buttonText.classList.add('less');
    moreIcon.classList.add('less');
  }
}

function toggleText2() {
  var showMoreText2 = document.getElementById("more2");
  var buttonText2   = document.querySelector("#moreButton2 span");
  var moreIcon2     = document.querySelector("#moreButton2 img");

  if (startpoint.style.display === "none") {
    showMoreText.style.display = "none";
    startpoint.style.display = "table-cell";
    buttonText.innerHTML = "Show More";
    buttonText.classList.remove('less2');
    moreIcon.classList.remove('less2');
  } else {
    showMoreText.style.display = "table-cell";
    startpoint.style.display = "none";
    buttonText.innerHTML = "Show Less";
    buttonText.classList.add('less2');
    moreIcon.classList.add('less2');
  }
}

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />

    <button onclick="toggleText()" id="moreButton">
            Show More

            </button>

    <button onclick="toggleText2()" id="moreButton2">
            Show More

            </button>

Body:
The correct way to do that:

document.querySelectorAll('button.moreButton').forEach(bt =>
  {
  let
    moreItem = bt.closest('div.row').querySelector('div.more_items')
  , spPink   = bt.querySelector('span.pink')
    ;
  bt.onclick =_=>
    {
    spPink.textContent = moreItem.classList.toggle('noDisplay') ? 'Show More' : 'Show Less'
    }
  })

.more_items.noDisplay {
  display: none;
}

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

  <div class="container-fluid clientbox text-center">
    <div class="row">
      <div class="col-6 col-md-4 col-lg-3">
        <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
      </div>
      <div class="col-6 col-md-4 col-lg-3">
        <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
      </div>
      <div class="col-6 col-md-4 col-lg-3">
        <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
      </div>
      <div class="col-6 col-md-4 col-lg-3">
        <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
      </div>

      <div class="more_items">
        <div class="row">
          <div class="col-6 col-md-4 col-lg-3">
            <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
          </div>
          <div class="col-6 col-md-4 col-lg-3">
            <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
          </div>
          <div class=" col-6 col-md-4 col-lg-3">
            <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
          </div>
          <div class="col-6 col-md-4 col-lg-3">
            <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
          </div>
        </div>
      </div>
      <button class="moreButton">
        <span class="pink">Show Less</span>
        <img class="more" src="./images/load-more.png" alt="">
      </button>
    </div>
  </div>

  <br>
  <br>

  <div class="container-fluid clientbox text-center">
    <div class="row">
      <div class="col-6 col-md-4 col-lg-3">
        <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
      </div>
      <div class="col-6 col-md-4 col-lg-3">
        <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
      </div>
      <div class="col-6 col-md-4 col-lg-3">
        <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
      </div>
      <div class="col-6 col-md-4 col-lg-3">
        <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
      </div>

      <div class="more_items">
        <div class="row">
          <div class="col-6 col-md-4 col-lg-3">
            <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
          </div>
          <div class="col-6 col-md-4 col-lg-3">
            <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
          </div>
          <div class=" col-6 col-md-4 col-lg-3">
            <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
          </div>
          <div class="col-6 col-md-4 col-lg-3">
            <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
          </div>
        </div>
      </div>
      <button class="moreButton">
        <span class="pink">Show Less</span>
        <img class="more" src="./images/load-more.png" alt="">
      </button>
    </div>
  </div>


问:
Mapping string to UUID in go
I'm using mitchellh/mapstructure to map from map[string]interface{} to struct

Is there any way to tell mapstructure to convert string to uuid.UUID?

map[string]interface{}:

{
    "id": "af7926b1-98eb-4c96-a2ba-7e429085b2ad",
    "title": "new title",
}
```
<h5><code>struct</code></h5>
<pre class="lang-golang prettyprint-override"><code>package entities

import (
    "github.com/google/uuid"
)

type Post struct {
    Id      uuid.UUID  `json:"id"`
    Title   string     `json:"title"`
}
</code>```

答:
You could add a DecodeHookFunc:

```<code>func decode(input, output interface{}) error {
    config := &mapstructure.DecoderConfig{
        DecodeHook: mapstructure.ComposeDecodeHookFunc(
            stringToUUIDHookFunc(),
        ),
        Result: &output,
    }

    decoder, err := mapstructure.NewDecoder(config)
    if err != nil {
        return err
    }

    return decoder.Decode(input)
}

func stringToUUIDHookFunc() mapstructure.DecodeHookFunc {
    return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) {
        if f.Kind() != reflect.String {
            return data, nil
        }
        if t != reflect.TypeOf(uuid.UUID{}) {
            return data, nil
        }

        return uuid.Parse(data.(string))
    }
}
</code>```

Source: https://github.com/mitchellh/mapstructure/issues/236

Documentation:
https://pkg.go.dev/github.com/mitchellh/mapstructure#DecodeHookFunc

Title: Mapping string to UUID in go

Body:
I'm using mitchellh/mapstructure to map from map[string]interface{} to struct

Is there any way to tell mapstructure to convert string to uuid.UUID?

map[string]interface{}:

{
    "id": "af7926b1-98eb-4c96-a2ba-7e429085b2ad",
    "title": "new title",
}

struct

package entities

import (
    "github.com/google/uuid"
)

type Post struct {
    Id      uuid.UUID  `json:"id"`
    Title   string     `json:"title"`
}

Body:
You could add a DecodeHookFunc:

func decode(input, output interface{}) error {
    config := &mapstructure.DecoderConfig{
        DecodeHook: mapstructure.ComposeDecodeHookFunc(
            stringToUUIDHookFunc(),
        ),
        Result: &output,
    }

    decoder, err := mapstructure.NewDecoder(config)
    if err != nil {
        return err
    }

    return decoder.Decode(input)
}

func stringToUUIDHookFunc() mapstructure.DecodeHookFunc {
    return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) {
        if f.Kind() != reflect.String {
            return data, nil
        }
        if t != reflect.TypeOf(uuid.UUID{}) {
            return data, nil
        }

        return uuid.Parse(data.(string))
    }
}

Source: https://github.com/mitchellh/mapstructure/issues/236

Documentation:
https://pkg.go.dev/github.com/mitchellh/mapstructure#DecodeHookFunc


问:
Error parsing connection string with AAD user credentials
On Azure account, I have created an AAD user.

I created Azure SQL database and assigned the newly created AAD user as a Server administrator.

The server has both AAD account login and SQL Server login.

I tested connecting to server through SSMS using AAD user, it works. I tested adding other AAD users to database, it works (in SSMS).

Now I'm testing the connection to database from Console app.

I want to connect to database using AAD user credentials.

Console app is supposed to work without user logging in, so I'm want to hardcode user into connection string.

My connection string is:

```<code>string connectionString = @"Server=tcp:test-server.database.windows.net,1433; Authentication=Active Directory Password; Database=mydb; User Id=aad_user_name@myaccount.onmicrosoft.com; Password=mypassword";
</code>```

Console breaks as soon as it tries to create SqlConnection, from what I can see in parsing connection string.

```<code>System.ArgumentException: Keyword not supported: 'authentication'.
   at System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary`2 parsetable, String connectionString, Boolean buildChain, Dictionary`2 synonyms, Boolean firstKey)
   at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary`2 synonyms)
   at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous)
   at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions)
   at System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key)
   at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
   at System.Data.SqlClient.SqlConnection..ctor(String connectionString)
   at MyApp.Program.TestDb() in C:\path\Program.cs:line 28
</code>```

Project file:

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Data.SqlClient" Version="4.1.0" />
    <PackageReference Include="System.Data.SqlClient" Version="4.8.3" />
  </ItemGroup>

</Project>
</code>```

So, I'm using latest .NET 6, Microsoft.Data.SqlClient and System.Data.SqlClient.

答:
I got it. I was not supposed to use System.Data.SqlClient lib at all. There is new implementation of SqlConnection in Microsoft.Data.SqlClient lib and it worked.

Problem was that VS 2022 was suggesting to use System.Data.SqlClient.

Body:
On Azure account, I have created an AAD user.

I created Azure SQL database and assigned the newly created AAD user as a Server administrator.

The server has both AAD account login and SQL Server login.

I tested connecting to server through SSMS using AAD user, it works. I tested adding other AAD users to database, it works (in SSMS).

Now I'm testing the connection to database from Console app.

I want to connect to database using AAD user credentials.

Console app is supposed to work without user logging in, so I'm want to hardcode user into connection string.

My connection string is:

string connectionString = @"Server=tcp:test-server.database.windows.net,1433; Authentication=Active Directory Password; Database=mydb; User Id=aad_user_name@myaccount.onmicrosoft.com; Password=mypassword";

Console breaks as soon as it tries to create SqlConnection, from what I can see in parsing connection string.

System.ArgumentException: Keyword not supported: 'authentication'.
   at System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary`2 parsetable, String connectionString, Boolean buildChain, Dictionary`2 synonyms, Boolean firstKey)
   at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary`2 synonyms)
   at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous)
   at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions)
   at System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key)
   at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
   at System.Data.SqlClient.SqlConnection..ctor(String connectionString)
   at MyApp.Program.TestDb() in C:\path\Program.cs:line 28

Project file:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Data.SqlClient" Version="4.1.0" />
    <PackageReference Include="System.Data.SqlClient" Version="4.8.3" />
  </ItemGroup>

</Project>

So, I'm using latest .NET 6, Microsoft.Data.SqlClient and System.Data.SqlClient.


问:
Get nearest position with Haversine Formula in Spring
I have an entitiy which has two columns in the database like this:

```<code>@Column(name = "latitude", nullable = false)
private float currentPositionLatitude;

@Column(name = "longitude", nullable = false)
private float currentPositionLongitude;
</code>```

And I have multiple entrys in my database(PostgresQl) for the entity with different latitudes and longitudes for all of them. Now I want to give a point (lat,lon) and a radius and show all entitys which are near the point.
I first tried it with the Harversine formula like this in Spring Jpa :

```<code>   String HAVERSINE_PART = "(6371 * acos(cos(radians(:latitude)) * cos(radians(s.latitude)) *" +
        " cos(radians(s.longitude) - radians(:longitude)) + sin(radians(:latitude)) * sin(radians(s.latitude))))";

    @Query("SELECT currentPositionLatitude,currentPositionLongitude FROM Entity WHERE  '%:HAVERSINE_PART%' < :distance ORDER BY '%:HAVERSINE_PART%' DESC")
      public List<Entity> findEntiryWithLocation(
      @Param("currentPositionLatitude") final float latitude,
      @Param("currentPositionLongitude") final float longitude, @Param("distance") final double distance )
</code>```

this didnt work so I tried:

```<code>    @Query("SELECT s FROM Entity s WHERE " + HAVERSINE_PART + " < :distance ORDER BY "+ HAVERSINE_PART + " DESC")
List<Entity> findEntityWithInDistance(
@Param("latitude") double latitude,
 @Param("longitude") double longitude,
 @Param("distance") double distanceWithInKM );
</code>```

this also didnt work so then I tried:

```<code>@Query(value = "SELECT *, earth_distance(ll_to_earth(:latitude, :longitude), ll_to_earth(latitude, longitude)) as distance FROM Car WHERE  (earth_box(ll_to_earth(:latitude, :longitude), :radiusInMeters) @> ll_to_earth(latitude, longitude))ORDER BY distance ASC",
nativeQuery = true)
List<Entity> getPlacesNear ( @Param("latitude") float latitude,
                             @Param("longitude")float longitude,
                             @Param("radiusInMeters") float radiusInMeters);
</code>```

This compiled but when I tried to put in values in my controller I got the error: jdbc error :2022 no dialect mapping

Here my methods for the service and the controller(the datatypes have changed maybe):

```<code>public List<Entity>showNearestEntityByDistances(float latitude, float longitude, float distance){
        return EntityRepository.getPlacesNear(latitude,longitude,distance);
    }
</code>```

and the endpoint:

```<code>@GetMapping("/location")
public List<Entity>showEntityNearby(@RequestParam float latitude,@RequestParam float longitude,@RequestParam float distance){

    return carService.showNearestEntitysByDistances(latitude,longitude,distance);
}
</code>```

I already looked at :
https://www.postgresql.org/docs/current/earthdistance.html
and
postgresql jpa earth_distance query

but it didnt worked. Has anyone an idea what Im doing wrong ?
Thanks in regard.

答:
I got it working changing a few things:</p>
```<code> @Query(value = "SELECT * FROM Entity s WHERE " + HAVERSINE_PART + " < :distance ORDER BY "+ HAVERSINE_PART + " DESC",nativeQuery = true)
List<Entity> findEntityWithInDistance(
@Param("latitude") double latitude,
 @Param("longitude") double longitude,
 @Param("distance") double distanceWithInKM );
</code>```

Body:
I have an entitiy which has two columns in the database like this:

@Column(name = "latitude", nullable = false)
private float currentPositionLatitude;

@Column(name = "longitude", nullable = false)
private float currentPositionLongitude;

And I have multiple entrys in my database(PostgresQl) for the entity with different latitudes and longitudes for all of them. Now I want to give a point (lat,lon) and a radius and show all entitys which are near the point.
I first tried it with the Harversine formula like this in Spring Jpa :

   String HAVERSINE_PART = "(6371 * acos(cos(radians(:latitude)) * cos(radians(s.latitude)) *" +
        " cos(radians(s.longitude) - radians(:longitude)) + sin(radians(:latitude)) * sin(radians(s.latitude))))";

    @Query("SELECT currentPositionLatitude,currentPositionLongitude FROM Entity WHERE  '%:HAVERSINE_PART%' < :distance ORDER BY '%:HAVERSINE_PART%' DESC")
      public List<Entity> findEntiryWithLocation(
      @Param("currentPositionLatitude") final float latitude,
      @Param("currentPositionLongitude") final float longitude, @Param("distance") final double distance )

this didnt work so I tried:

    @Query("SELECT s FROM Entity s WHERE " + HAVERSINE_PART + " < :distance ORDER BY "+ HAVERSINE_PART + " DESC")
List<Entity> findEntityWithInDistance(
@Param("latitude") double latitude,
 @Param("longitude") double longitude,
 @Param("distance") double distanceWithInKM );

this also didnt work so then I tried:

@Query(value = "SELECT *, earth_distance(ll_to_earth(:latitude, :longitude), ll_to_earth(latitude, longitude)) as distance FROM Car WHERE  (earth_box(ll_to_earth(:latitude, :longitude), :radiusInMeters) @> ll_to_earth(latitude, longitude))ORDER BY distance ASC",
nativeQuery = true)
List<Entity> getPlacesNear ( @Param("latitude") float latitude,
                             @Param("longitude")float longitude,
                             @Param("radiusInMeters") float radiusInMeters);

This compiled but when I tried to put in values in my controller I got the error: jdbc error :2022 no dialect mapping

Here my methods for the service and the controller(the datatypes have changed maybe):

public List<Entity>showNearestEntityByDistances(float latitude, float longitude, float distance){
        return EntityRepository.getPlacesNear(latitude,longitude,distance);
    }

and the endpoint:

@GetMapping("/location")
public List<Entity>showEntityNearby(@RequestParam float latitude,@RequestParam float longitude,@RequestParam float distance){

    return carService.showNearestEntitysByDistances(latitude,longitude,distance);
}

I already looked at :
https://www.postgresql.org/docs/current/earthdistance.html
and
postgresql jpa earth_distance query

but it didnt worked. Has anyone an idea what Im doing wrong ?
Thanks in regard.

Body:
I got it working changing a few things:

 @Query(value = "SELECT * FROM Entity s WHERE " + HAVERSINE_PART + " < :distance ORDER BY "+ HAVERSINE_PART + " DESC",nativeQuery = true)
List<Entity> findEntityWithInDistance(
@Param("latitude") double latitude,
 @Param("longitude") double longitude,
 @Param("distance") double distanceWithInKM );


问:
What is the best lossless way to scale up a barcode image in c#
I've come across this problem many times over the years and still live in hope that there is an easy way to do this that I have missed.
I work with barcodes a lot.  They are usually made of black dots or lines on a white background.  Barcode readers generally work faster and more accurately when the edges are crisp and then size of the lines or dots are precise.

Most barcode generation algorithms will give you a compact barcode usually with the smallest element size being one pixel.  A typical QR code could fit in a 21 x 21 grid.  This would be too small to see if printed pixel to pixel on most printers and would typically be scaled up.  The result of scaling it up depends on the method used and although sometimes you are given a choice, often you have no options that make the image suitable.  Even printing directly will often give you expected gray artefacts or forms of dithering.  The most consistent way I have found is to scale the images before they are use daily in other places such as Microsoft Word, lightburn and a few others I use that still give me a headache.

Below I will go through what I have tried and show the results.  I am limiting this to bitmaps only because using vectors here is not something I need on my current project.

My current best resolution is not pretty, it is slow and although I could improve the speed by locking the bits in the bitmap, I am hoping someone has a really simple answer that I had totally missed on my search again this time.

Here is an image of a simple QR code blown up in GIMP.

The problem is, if it is scaled up, it'll often end up looking like this:

Below I created a small test program to go through all the different modes I know of and then generate a matrix of images which I have reproduced below.  The version I currently use is Mode 99 which involves inspecting each pixel and drawing a square.

Does anyone have any better ideas?

```<code>using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace PSWpfCommon.Images
{
    public partial class WPFImageHelper
    {

        public class Test
        {
            public int smode = 0;
            public int imode = 0;
            public int mode = 0;
            public string title = "";
            public Test(int s, int i, int m, string t)
            {
                smode = s;
                imode = i;
                mode = m;
                title = t;
            }
        }

        public static Bitmap TestImage()
        {
            byte[] img =
             {
           0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44,
           0x52, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x15, 0x08, 0x06, 0x00, 0x00, 0x00, 0xA9,
           0x17, 0xA5, 0x96, 0x00, 0x00, 0x00, 0xCF, 0x49, 0x44, 0x41, 0x54, 0x38, 0xCB, 0x9D, 0x54,
           0x5B, 0x0E, 0xC3, 0x30, 0x08, 0xB3, 0xAB, 0xDC, 0xFF, 0xCA, 0xDE, 0xC7, 0xD4, 0x88, 0x7A,
           0x3C, 0xD2, 0x21, 0x55, 0xAD, 0x48, 0xA0, 0xC6, 0x80, 0x09, 0x40, 0x28, 0x4C, 0x12, 0x48,
           0xEE, 0x6F, 0x00, 0x20, 0xF9, 0xF0, 0x67, 0xB6, 0x62, 0x40, 0xB4, 0x98, 0xAC, 0x4A, 0x50,
           0xC5, 0x2D, 0x4F, 0xE2, 0x97, 0x23, 0xB2, 0xEE, 0xE7, 0x31, 0xEE, 0xC2, 0xA1, 0x75, 0x89,
           0xD3, 0xF2, 0x27, 0x73, 0x5E, 0x8F, 0x93, 0x56, 0x01, 0x53, 0xA2, 0xEC, 0x7C, 0x39, 0x2F,
           0x19, 0xCA, 0x58, 0x7A, 0xA4, 0xA0, 0x8A, 0xA3, 0x0E, 0x6A, 0x7A, 0x5B, 0xFE, 0x45, 0x12,
           0xF1, 0xF1, 0x44, 0x59, 0x73, 0xFC, 0x5E, 0x8C, 0x25, 0xF9, 0xED, 0xBE, 0xA4, 0x47, 0x49,
           0xDD, 0x18, 0x79, 0xF9, 0x25, 0xA7, 0xD9, 0xA6, 0x74, 0xE3, 0xE3, 0x48, 0x9D, 0xE3, 0x55,
           0xA1, 0x98, 0xB8, 0xCC, 0x16, 0xE4, 0xF6, 0x5F, 0xBE, 0xDF, 0x8E, 0x74, 0x42, 0x9F, 0x4D,
           0xC0, 0x0F, 0xA7, 0xFE, 0x76, 0x14, 0x5D, 0x65, 0xDB, 0x3F, 0xA9, 0x54, 0xC7, 0x9D, 0x8B,
           0xCD, 0x7D, 0x3E, 0xAA, 0xD4, 0x24, 0x77, 0x99, 0x7F, 0x54, 0xA9, 0xAA, 0x69, 0x7E, 0x3F,
           0xCE, 0xEA, 0xFA, 0x67, 0x9B, 0x3A, 0x2A, 0x24, 0x9D, 0x49, 0x9F, 0x23, 0x99, 0x64, 0x71,
           0x9D, 0xA8, 0x51, 0xC5, 0x6F, 0x36, 0x21, 0x5B, 0xF9, 0x3B, 0x95, 0xAA, 0x1A, 0x52, 0xAD,
           0xB1, 0x24, 0x7C, 0x00, 0x22, 0x8E, 0xDE, 0x4C, 0xC4, 0x8F, 0x11, 0x7F, 0x00, 0x00, 0x00,
           0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
             };

            Bitmap qr;
            using (var ms = new MemoryStream(img))
            {
                qr = new Bitmap(ms);
            }

            int factor = 4;

            var l = new List<Test>();
            for (int i = 0; i <= 7; i++)
                for (int s = 0; s <= 4; s++)
                    l.Add(new Test(s, i, 0, $"s={s} i={i}"));

            l.Add(new Test(2, 8, 99, $"Mode 99"));

            Bitmap fullimage = new Bitmap(((qr.Width * factor) + 20) * 5, ((qr.Height * factor) + 20) * 9);

            fullimage.SetResolution(72, 72);
            var font = new Font("Arial", 10);

            using (var grPhoto = Graphics.FromImage(fullimage))
            using (var blackbrush = new SolidBrush(System.Drawing.Color.Black))
            using (var whitebrush = new SolidBrush(System.Drawing.Color.White))
            {
                grPhoto.InterpolationMode = InterpolationMode.High;

                grPhoto.FillRectangle(whitebrush, 0, 0, fullimage.Width, fullimage.Height);

                foreach (var t in l)
                {
                    var newqr = GrowImage(qr, factor: 4, mode: t.mode, imode: t.imode, smode: t.smode);

                    grPhoto.DrawImage(newqr,
                        t.smode * ((qr.Width * factor) + 20),
                        t.imode * ((qr.Height * factor) + 20));
                    grPhoto.DrawString(t.title, font, blackbrush,
                        t.smode * ((qr.Width * factor) + 20),
                        (t.imode + 1) * ((qr.Height * factor) + 20) - 20);

                }
            }

            fullimage.Save(@"c:\temp\newqr.png", ImageFormat.Png);

            return null;
        }

        public static Bitmap GrowImage(Bitmap im, int factor = 4, int mode = 1, int imode = 0, int smode = 0, int border = 2)
        {
            bool translate = true;

            var bmPhoto = new Bitmap(im.Width * factor + 2 * border, im.Height * factor + border * 2, PixelFormat.Format24bppRgb);

            bmPhoto.SetResolution(72, 72);

            using (var grPhoto = Graphics.FromImage(bmPhoto))
            using (var blackbrush = new SolidBrush(System.Drawing.Color.Black))
            using (var whitebrush = new SolidBrush(System.Drawing.Color.White))
            {
                grPhoto.FillRectangle(whitebrush, 0, 0, bmPhoto.Width, bmPhoto.Height);

                switch (smode)
                {
                    case 0:
                        grPhoto.SmoothingMode = SmoothingMode.Default;
                        break;
                    case 1:
                        grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
                        break;
                    case 2:
                        grPhoto.SmoothingMode = SmoothingMode.HighQuality;
                        break;
                    case 3:
                        grPhoto.SmoothingMode = SmoothingMode.HighSpeed;
                        break;
                    case 4:
                        grPhoto.SmoothingMode = SmoothingMode.None;
                        break;
                    default:
                        break;
                }
                switch (imode)
                {
                    case 0:
                        grPhoto.InterpolationMode = InterpolationMode.Default;
                        break;
                    case 1:
                        grPhoto.InterpolationMode = InterpolationMode.Bicubic;
                        break;
                    case 2:
                        grPhoto.InterpolationMode = InterpolationMode.Bilinear;
                        break;
                    case 3:
                        grPhoto.InterpolationMode = InterpolationMode.High;
                        break;
                    case 4:
                        grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        break;
                    case 5:
                        grPhoto.InterpolationMode = InterpolationMode.HighQualityBilinear;
                        break;
                    case 6:
                        grPhoto.InterpolationMode = InterpolationMode.Low;
                        break;
                    case 7:
                        grPhoto.InterpolationMode = InterpolationMode.NearestNeighbor;
                        break;
                    default:
                        break;
                }

                switch (mode)
                {
                    case 99:
                        // These are what worked best for me...
                        grPhoto.SmoothingMode = SmoothingMode.None;
                        grPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;

                        for (int x = 0; x < im.Width; x++)
                            for (int y = 0; y < im.Height; y++)
                            {
                                var g = im.GetPixel(x, y);
                                if (g.R < 120 && g.B < 120) // Just being really lazy here... if the pixel has not much blue and not much red I'll treat it as black
                                {
                                    grPhoto.FillRectangle(blackbrush, border + factor * x, border + factor * y, factor, factor);

                                }
                            }
                        translate = false;
                        break;
                    default:
                        break;
                }

                if (translate) // If we used mode 99, don't draw the image
                    grPhoto.DrawImage(im, new System.Drawing.Rectangle(border, border, im.Width * factor, im.Height * factor), 0, 0, im.Width, im.Height, System.Drawing.GraphicsUnit.Pixel);
            }

            return bmPhoto;
        }
    }
}

</code>```

答:
This is how I resize a Bitmap in one shot with DrawImage and nearest neighbor sampling.

In your case, I'd prepare the original bitmap with one pixel per logical dot with respect to the geometric dimensions of your pattern (e.g. at 21 x 21)  Then I'd resize that bitmap to a printable/displayable output format using Interpolationmode.NearestNeighbor sampling using the code I'm providing below.

It's important to set PixelOffsetMode.HighQuality. (Unless you want to adjust your coordinates by -0.5f, -0.5f, which is just annoying, so don't bother).

```<code>public static Bitmap Resize(this Bitmap oldBitmap, int newWidth, int newHeight)
{
    Bitmap newBitmap = new Bitmap(newWidth, newHeight, oldBitmap.PixelFormat);
    using (Graphics g = Graphics.FromImage(newBitmap)) {
        RectangleF dst = new RectangleF(0, 0, newWidth, newHeight);
        RectangleF src = new RectangleF(0, 0, oldBitmap.Width, oldBitmap.Height);
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
        g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
        g.DrawImage(oldBitmap, dst, src, GraphicsUnit.Pixel);
    }
    return newBitmap;
}
</code>```

Body:
I've come across this problem many times over the years and still live in hope that there is an easy way to do this that I have missed.
I work with barcodes a lot.  They are usually made of black dots or lines on a white background.  Barcode readers generally work faster and more accurately when the edges are crisp and then size of the lines or dots are precise.

Most barcode generation algorithms will give you a compact barcode usually with the smallest element size being one pixel.  A typical QR code could fit in a 21 x 21 grid.  This would be too small to see if printed pixel to pixel on most printers and would typically be scaled up.  The result of scaling it up depends on the method used and although sometimes you are given a choice, often you have no options that make the image suitable.  Even printing directly will often give you expected gray artefacts or forms of dithering.  The most consistent way I have found is to scale the images before they are use daily in other places such as Microsoft Word, lightburn and a few others I use that still give me a headache.

Below I will go through what I have tried and show the results.  I am limiting this to bitmaps only because using vectors here is not something I need on my current project.

My current best resolution is not pretty, it is slow and although I could improve the speed by locking the bits in the bitmap, I am hoping someone has a really simple answer that I had totally missed on my search again this time.

Here is an image of a simple QR code blown up in GIMP.

The problem is, if it is scaled up, it'll often end up looking like this:

Below I created a small test program to go through all the different modes I know of and then generate a matrix of images which I have reproduced below.  The version I currently use is Mode 99 which involves inspecting each pixel and drawing a square.

Does anyone have any better ideas?

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace PSWpfCommon.Images
{
    public partial class WPFImageHelper
    {

        public class Test
        {
            public int smode = 0;
            public int imode = 0;
            public int mode = 0;
            public string title = "";
            public Test(int s, int i, int m, string t)
            {
                smode = s;
                imode = i;
                mode = m;
                title = t;
            }
        }

        public static Bitmap TestImage()
        {
            byte[] img =
             {
           0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44,
           0x52, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x15, 0x08, 0x06, 0x00, 0x00, 0x00, 0xA9,
           0x17, 0xA5, 0x96, 0x00, 0x00, 0x00, 0xCF, 0x49, 0x44, 0x41, 0x54, 0x38, 0xCB, 0x9D, 0x54,
           0x5B, 0x0E, 0xC3, 0x30, 0x08, 0xB3, 0xAB, 0xDC, 0xFF, 0xCA, 0xDE, 0xC7, 0xD4, 0x88, 0x7A,
           0x3C, 0xD2, 0x21, 0x55, 0xAD, 0x48, 0xA0, 0xC6, 0x80, 0x09, 0x40, 0x28, 0x4C, 0x12, 0x48,
           0xEE, 0x6F, 0x00, 0x20, 0xF9, 0xF0, 0x67, 0xB6, 0x62, 0x40, 0xB4, 0x98, 0xAC, 0x4A, 0x50,
           0xC5, 0x2D, 0x4F, 0xE2, 0x97, 0x23, 0xB2, 0xEE, 0xE7, 0x31, 0xEE, 0xC2, 0xA1, 0x75, 0x89,
           0xD3, 0xF2, 0x27, 0x73, 0x5E, 0x8F, 0x93, 0x56, 0x01, 0x53, 0xA2, 0xEC, 0x7C, 0x39, 0x2F,
           0x19, 0xCA, 0x58, 0x7A, 0xA4, 0xA0, 0x8A, 0xA3, 0x0E, 0x6A, 0x7A, 0x5B, 0xFE, 0x45, 0x12,
           0xF1, 0xF1, 0x44, 0x59, 0x73, 0xFC, 0x5E, 0x8C, 0x25, 0xF9, 0xED, 0xBE, 0xA4, 0x47, 0x49,
           0xDD, 0x18, 0x79, 0xF9, 0x25, 0xA7, 0xD9, 0xA6, 0x74, 0xE3, 0xE3, 0x48, 0x9D, 0xE3, 0x55,
           0xA1, 0x98, 0xB8, 0xCC, 0x16, 0xE4, 0xF6, 0x5F, 0xBE, 0xDF, 0x8E, 0x74, 0x42, 0x9F, 0x4D,
           0xC0, 0x0F, 0xA7, 0xFE, 0x76, 0x14, 0x5D, 0x65, 0xDB, 0x3F, 0xA9, 0x54, 0xC7, 0x9D, 0x8B,
           0xCD, 0x7D, 0x3E, 0xAA, 0xD4, 0x24, 0x77, 0x99, 0x7F, 0x54, 0xA9, 0xAA, 0x69, 0x7E, 0x3F,
           0xCE, 0xEA, 0xFA, 0x67, 0x9B, 0x3A, 0x2A, 0x24, 0x9D, 0x49, 0x9F, 0x23, 0x99, 0x64, 0x71,
           0x9D, 0xA8, 0x51, 0xC5, 0x6F, 0x36, 0x21, 0x5B, 0xF9, 0x3B, 0x95, 0xAA, 0x1A, 0x52, 0xAD,
           0xB1, 0x24, 0x7C, 0x00, 0x22, 0x8E, 0xDE, 0x4C, 0xC4, 0x8F, 0x11, 0x7F, 0x00, 0x00, 0x00,
           0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
             };

            Bitmap qr;
            using (var ms = new MemoryStream(img))
            {
                qr = new Bitmap(ms);
            }

            int factor = 4;

            var l = new List<Test>();
            for (int i = 0; i <= 7; i++)
                for (int s = 0; s <= 4; s++)
                    l.Add(new Test(s, i, 0, $"s={s} i={i}"));

            l.Add(new Test(2, 8, 99, $"Mode 99"));

            Bitmap fullimage = new Bitmap(((qr.Width * factor) + 20) * 5, ((qr.Height * factor) + 20) * 9);

            fullimage.SetResolution(72, 72);
            var font = new Font("Arial", 10);

            using (var grPhoto = Graphics.FromImage(fullimage))
            using (var blackbrush = new SolidBrush(System.Drawing.Color.Black))
            using (var whitebrush = new SolidBrush(System.Drawing.Color.White))
            {
                grPhoto.InterpolationMode = InterpolationMode.High;

                grPhoto.FillRectangle(whitebrush, 0, 0, fullimage.Width, fullimage.Height);

                foreach (var t in l)
                {
                    var newqr = GrowImage(qr, factor: 4, mode: t.mode, imode: t.imode, smode: t.smode);

                    grPhoto.DrawImage(newqr,
                        t.smode * ((qr.Width * factor) + 20),
                        t.imode * ((qr.Height * factor) + 20));
                    grPhoto.DrawString(t.title, font, blackbrush,
                        t.smode * ((qr.Width * factor) + 20),
                        (t.imode + 1) * ((qr.Height * factor) + 20) - 20);

                }
            }

            fullimage.Save(@"c:\temp\newqr.png", ImageFormat.Png);

            return null;
        }

        public static Bitmap GrowImage(Bitmap im, int factor = 4, int mode = 1, int imode = 0, int smode = 0, int border = 2)
        {
            bool translate = true;

            var bmPhoto = new Bitmap(im.Width * factor + 2 * border, im.Height * factor + border * 2, PixelFormat.Format24bppRgb);

            bmPhoto.SetResolution(72, 72);

            using (var grPhoto = Graphics.FromImage(bmPhoto))
            using (var blackbrush = new SolidBrush(System.Drawing.Color.Black))
            using (var whitebrush = new SolidBrush(System.Drawing.Color.White))
            {
                grPhoto.FillRectangle(whitebrush, 0, 0, bmPhoto.Width, bmPhoto.Height);

                switch (smode)
                {
                    case 0:
                        grPhoto.SmoothingMode = SmoothingMode.Default;
                        break;
                    case 1:
                        grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
                        break;
                    case 2:
                        grPhoto.SmoothingMode = SmoothingMode.HighQuality;
                        break;
                    case 3:
                        grPhoto.SmoothingMode = SmoothingMode.HighSpeed;
                        break;
                    case 4:
                        grPhoto.SmoothingMode = SmoothingMode.None;
                        break;
                    default:
                        break;
                }
                switch (imode)
                {
                    case 0:
                        grPhoto.InterpolationMode = InterpolationMode.Default;
                        break;
                    case 1:
                        grPhoto.InterpolationMode = InterpolationMode.Bicubic;
                        break;
                    case 2:
                        grPhoto.InterpolationMode = InterpolationMode.Bilinear;
                        break;
                    case 3:
                        grPhoto.InterpolationMode = InterpolationMode.High;
                        break;
                    case 4:
                        grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        break;
                    case 5:
                        grPhoto.InterpolationMode = InterpolationMode.HighQualityBilinear;
                        break;
                    case 6:
                        grPhoto.InterpolationMode = InterpolationMode.Low;
                        break;
                    case 7:
                        grPhoto.InterpolationMode = InterpolationMode.NearestNeighbor;
                        break;
                    default:
                        break;
                }

                switch (mode)
                {
                    case 99:
                        // These are what worked best for me...
                        grPhoto.SmoothingMode = SmoothingMode.None;
                        grPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;

                        for (int x = 0; x < im.Width; x++)
                            for (int y = 0; y < im.Height; y++)
                            {
                                var g = im.GetPixel(x, y);
                                if (g.R < 120 && g.B < 120) // Just being really lazy here... if the pixel has not much blue and not much red I'll treat it as black
                                {
                                    grPhoto.FillRectangle(blackbrush, border + factor * x, border + factor * y, factor, factor);

                                }
                            }
                        translate = false;
                        break;
                    default:
                        break;
                }

                if (translate) // If we used mode 99, don't draw the image
                    grPhoto.DrawImage(im, new System.Drawing.Rectangle(border, border, im.Width * factor, im.Height * factor), 0, 0, im.Width, im.Height, System.Drawing.GraphicsUnit.Pixel);
            }

            return bmPhoto;
        }
    }
}

Body:
This is how I resize a Bitmap in one shot with DrawImage and nearest neighbor sampling.

In your case, I'd prepare the original bitmap with one pixel per logical dot with respect to the geometric dimensions of your pattern (e.g. at 21 x 21)  Then I'd resize that bitmap to a printable/displayable output format using Interpolationmode.NearestNeighbor sampling using the code I'm providing below.

It's important to set PixelOffsetMode.HighQuality. (Unless you want to adjust your coordinates by -0.5f, -0.5f, which is just annoying, so don't bother).

public static Bitmap Resize(this Bitmap oldBitmap, int newWidth, int newHeight)
{
    Bitmap newBitmap = new Bitmap(newWidth, newHeight, oldBitmap.PixelFormat);
    using (Graphics g = Graphics.FromImage(newBitmap)) {
        RectangleF dst = new RectangleF(0, 0, newWidth, newHeight);
        RectangleF src = new RectangleF(0, 0, oldBitmap.Width, oldBitmap.Height);
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
        g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
        g.DrawImage(oldBitmap, dst, src, GraphicsUnit.Pixel);
    }
    return newBitmap;
}


问:
How to mock prisma with jest-mock
I use prisma to interact with my database and i would like to use jest-mock to mock the findMany call. https://jestjs.io/docs/jest-object#jestmockedtitem-t-deep--false

brands.test.ts

```<code>import { PrismaService } from "@services/mysql.service";
import { mocked } from "jest-mock";
import faker from "@faker-js/faker";
import { GetBrands } from "./brand";
jest.mock("@services/mysql.service");

/**
 * @group unit
 */

describe("Brand", () => {
    afterAll(async () => {});

    const mockedPrismaService = mocked(PrismaService, true);
    it("should get a list of brands", async () => {
        const mockedData = [
            {
                id: faker.datatype.uuid(),
                name: faker.datatype.string(),
                image: {
                    source: "some_source",
                    dtype: "some_dtype",
                },
            },
        ];

        //@ts-ignore - because of relational data mockedData.image
        mockedPrismaService.brand.findMany.mockResolvedValueOnce(mockedData);

        const [response, error] = await GetBrands();

        console.log(response, error);
    });
});
</code>```

mysql.service.ts

```<code>import mysql from "mysql2/promise";
import { Config } from "@config";
import { PrismaClient, Prisma } from "@prisma/client";

export const MySQLEscape = mysql.escape;
export const MySQLPreparedStatement = mysql.format;

export const PrismaService = new PrismaClient({});
export const PrismaHelper = Prisma;
</code>```

However when i run this test i get the following error.

```<code>TypeError: Cannot read properties of undefined (reading 'brand')
</code>```

答:
Factory Mock

One option is to option use the factory approach when mocking your client.

```<code>jest.mock("@services/mysql.service", () => ({
    PrismaService: {
        brand: {
            findMany: jest.fn(() => { })
        }
    },
}));
</code>```

Then within your test, you can mock the findMany function to return your test data, then call the function being tested.

```<code>const mockedData = [...];
PrismaService.brand.findMany.mockResolvedValueOnce(mockedData);
const result = await GetBrands();
</code>```

It's a bit cumbersome, but it works.

Note that in my example, I've implemented GetBrands as follows:

```<code>import { PrismaService } from "@services/mysql.service"

export const GetBrands = async () => {
    const data = await PrismaService.brand.findMany();
    return data;
}
</code>```

Your example

In your example, you're using automatic mocking, and I'm not too familiar with it so I'm not sure how to get it working.

What seems to be happening to cause the error is your PrismaService is undefined when it's imported here:

```<code>import { PrismaService } from "@services/mysql.service";
</code>```

And then calling the mocked function with an undefined parameter returns undefined:

```<code>const mockedPrismaService = mocked(undefined, true); // returns undefined
</code>```

And finally, calling the following is what throws the error:

```<code>mockedPrismaService.brand.findMany.mockResolvedValueOnce(mockedData);
// TypeError: Cannot read properties of undefined (reading 'brand')
</code>```

I would have thought something like this would be what you're after, but this throws an error:

```<code>jest.mock("@services/mysql.service", () => ({
    PrismaService: mocked(PrismaService, true)
}));
//    6 |
//    7 | jest.mock("@services/mysql.service", () => ({
//>   8 |     PrismaService: mocked(PrismaClient, true)
//      |                    ^
//    9 | }));
</code>```

Check out the docs

Might be worth checking out the Prismas documentation on unit testing, as they suggest a couple of pretty different approaches.

Title: How to mock prisma with jest-mock

Body:
I use prisma to interact with my database and i would like to use jest-mock to mock the findMany call. https://jestjs.io/docs/jest-object#jestmockedtitem-t-deep--false

brands.test.ts

import { PrismaService } from "@services/mysql.service";
import { mocked } from "jest-mock";
import faker from "@faker-js/faker";
import { GetBrands } from "./brand";
jest.mock("@services/mysql.service");

/**
 * @group unit
 */

describe("Brand", () => {
    afterAll(async () => {});

    const mockedPrismaService = mocked(PrismaService, true);
    it("should get a list of brands", async () => {
        const mockedData = [
            {
                id: faker.datatype.uuid(),
                name: faker.datatype.string(),
                image: {
                    source: "some_source",
                    dtype: "some_dtype",
                },
            },
        ];

        //@ts-ignore - because of relational data mockedData.image
        mockedPrismaService.brand.findMany.mockResolvedValueOnce(mockedData);

        const [response, error] = await GetBrands();

        console.log(response, error);
    });
});

mysql.service.ts

import mysql from "mysql2/promise";
import { Config } from "@config";
import { PrismaClient, Prisma } from "@prisma/client";

export const MySQLEscape = mysql.escape;
export const MySQLPreparedStatement = mysql.format;

export const PrismaService = new PrismaClient({});
export const PrismaHelper = Prisma;

However when i run this test i get the following error.

TypeError: Cannot read properties of undefined (reading 'brand')

Body:
Factory Mock

One option is to option use the factory approach when mocking your client.

jest.mock("@services/mysql.service", () => ({
    PrismaService: {
        brand: {
            findMany: jest.fn(() => { })
        }
    },
}));

Then within your test, you can mock the findMany function to return your test data, then call the function being tested.

const mockedData = [...];
PrismaService.brand.findMany.mockResolvedValueOnce(mockedData);
const result = await GetBrands();

It's a bit cumbersome, but it works.

Note that in my example, I've implemented GetBrands as follows:

import { PrismaService } from "@services/mysql.service"

export const GetBrands = async () => {
    const data = await PrismaService.brand.findMany();
    return data;
}

Your example

In your example, you're using automatic mocking, and I'm not too familiar with it so I'm not sure how to get it working.

What seems to be happening to cause the error is your PrismaService is undefined when it's imported here:

import { PrismaService } from "@services/mysql.service";

And then calling the mocked function with an undefined parameter returns undefined:

const mockedPrismaService = mocked(undefined, true); // returns undefined

And finally, calling the following is what throws the error:

mockedPrismaService.brand.findMany.mockResolvedValueOnce(mockedData);
// TypeError: Cannot read properties of undefined (reading 'brand')

I would have thought something like this would be what you're after, but this throws an error:

jest.mock("@services/mysql.service", () => ({
    PrismaService: mocked(PrismaService, true)
}));
//    6 |
//    7 | jest.mock("@services/mysql.service", () => ({
//>   8 |     PrismaService: mocked(PrismaClient, true)
//      |                    ^
//    9 | }));

Check out the docs

Might be worth checking out the Prismas documentation on unit testing, as they suggest a couple of pretty different approaches.