问:
use flutter_bluetooth_serial package
I wrote an application to connect to the hc-05 model and send data, but I am getting an error.
I think it's a bug in this package. I also tried to connect the hc-05 module, my computer and my colleague's phone, but I always get the same error.

first my codes

```<code>import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Motor Control',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MotorControlPage(),
    );
  }
}

class MotorControlPage extends StatefulWidget {
  @override
  _MotorControlPageState createState() => _MotorControlPageState();
}

class _MotorControlPageState extends State<MotorControlPage> {
  // Initialize Bluetooth connection and device object
  BluetoothConnection? connection;
  BluetoothDevice? device;

  // Initialize connection status
  bool _connected = false;

  Uint8List? bytes2 = utf8.encode("FORWARD") as Uint8List?;
  Uint8List? bytes3 = utf8.encode("REVERSE") as Uint8List?;
  Uint8List? bytes4 = utf8.encode("STOP") as Uint8List?;

  // Function to connect to STM32
  void _connect() async {
    // Get the list of available Bluetooth devices
    List<BluetoothDevice> devices =
        await FlutterBluetoothSerial.instance.getBondedDevices();

    // Connect to the first device in the list
    device = devices[0];
    connection = await BluetoothConnection.toAddress(device!.address);
    setState(() {
      // Update the connection status
      _connected = true;
    });
  }

  // Function to disconnect from STM32
  void _disconnect() {
    // Disconnect from STM32
    connection!.dispose();
    setState(() {
      // Update the connection status
      _connected = false;
    });
  }

  // Function to move motor forward
  void _forward() {
    // Send "FORWARD" command to STM32
    connection!.output.add(bytes2!);
  }

  // Function to move motor backward
  void _reverse() {
    // Send "REVERSE" command to STM32
    connection!.output.add(bytes3!);
  }

  // Function to stop motor
  void _stop() {
    // Send "STOP" command to STM32
    connection!.output.add(bytes4!);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Motor Control"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // Display "Connect" button if not connected, "Disconnect" button if connected
          _connected
              ? ElevatedButton(
                  child: const Text("Disconnect"),
                  onPressed: _disconnect,
                )
              : ElevatedButton(
                  child: Text("Connect"),
                  onPressed: _connect,
                ),
          // Display "Forward", "Reverse" and "Stop" buttons if connected
          _connected
              ? Column(
                  children: [
                    // Hold down "Forward" button to continuously move motor forward
                    ButtonTheme(
                      minWidth: 200,
                      child: ElevatedButton.icon(
                        icon: Icon(Icons.arrow_forward),
                        label: Text("Forward"),
                        onPressed: _forward,
                        onLongPress: _forward,
                      ),
                    ),
                    // Hold down "Reverse" button to continuously move motor backward
                    ButtonTheme(
                      minWidth: 200,
                      child: ElevatedButton.icon(
                        icon: Icon(Icons.stop),
                        label: Text("Forward"),
                        onPressed: _reverse,
                        onLongPress: _reverse,
                      ),
                    ),
                    // "Stop" button to stop motor
                    ButtonTheme(
                      minWidth: 200,
                      child: ElevatedButton.icon(
                        icon: Icon(Icons.stop),
                        label: Text("Stop"),
                        onPressed: _stop,
                      ),
                    ),
                  ],
                )
              : Container(),
        ],
      ),
    );
  }
}

</code>```

and the error I get

enter image description here

I don't think it's my fault and I want it fixed

Title: use flutter_bluetooth_serial package

Body:
I wrote an application to connect to the hc-05 model and send data, but I am getting an error.
I think it's a bug in this package. I also tried to connect the hc-05 module, my computer and my colleague's phone, but I always get the same error.

first my codes

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Motor Control',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MotorControlPage(),
    );
  }
}

class MotorControlPage extends StatefulWidget {
  @override
  _MotorControlPageState createState() => _MotorControlPageState();
}

class _MotorControlPageState extends State<MotorControlPage> {
  // Initialize Bluetooth connection and device object
  BluetoothConnection? connection;
  BluetoothDevice? device;

  // Initialize connection status
  bool _connected = false;

  Uint8List? bytes2 = utf8.encode("FORWARD") as Uint8List?;
  Uint8List? bytes3 = utf8.encode("REVERSE") as Uint8List?;
  Uint8List? bytes4 = utf8.encode("STOP") as Uint8List?;

  // Function to connect to STM32
  void _connect() async {
    // Get the list of available Bluetooth devices
    List<BluetoothDevice> devices =
        await FlutterBluetoothSerial.instance.getBondedDevices();

    // Connect to the first device in the list
    device = devices[0];
    connection = await BluetoothConnection.toAddress(device!.address);
    setState(() {
      // Update the connection status
      _connected = true;
    });
  }

  // Function to disconnect from STM32
  void _disconnect() {
    // Disconnect from STM32
    connection!.dispose();
    setState(() {
      // Update the connection status
      _connected = false;
    });
  }

  // Function to move motor forward
  void _forward() {
    // Send "FORWARD" command to STM32
    connection!.output.add(bytes2!);
  }

  // Function to move motor backward
  void _reverse() {
    // Send "REVERSE" command to STM32
    connection!.output.add(bytes3!);
  }

  // Function to stop motor
  void _stop() {
    // Send "STOP" command to STM32
    connection!.output.add(bytes4!);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Motor Control"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // Display "Connect" button if not connected, "Disconnect" button if connected
          _connected
              ? ElevatedButton(
                  child: const Text("Disconnect"),
                  onPressed: _disconnect,
                )
              : ElevatedButton(
                  child: Text("Connect"),
                  onPressed: _connect,
                ),
          // Display "Forward", "Reverse" and "Stop" buttons if connected
          _connected
              ? Column(
                  children: [
                    // Hold down "Forward" button to continuously move motor forward
                    ButtonTheme(
                      minWidth: 200,
                      child: ElevatedButton.icon(
                        icon: Icon(Icons.arrow_forward),
                        label: Text("Forward"),
                        onPressed: _forward,
                        onLongPress: _forward,
                      ),
                    ),
                    // Hold down "Reverse" button to continuously move motor backward
                    ButtonTheme(
                      minWidth: 200,
                      child: ElevatedButton.icon(
                        icon: Icon(Icons.stop),
                        label: Text("Forward"),
                        onPressed: _reverse,
                        onLongPress: _reverse,
                      ),
                    ),
                    // "Stop" button to stop motor
                    ButtonTheme(
                      minWidth: 200,
                      child: ElevatedButton.icon(
                        icon: Icon(Icons.stop),
                        label: Text("Stop"),
                        onPressed: _stop,
                      ),
                    ),
                  ],
                )
              : Container(),
        ],
      ),
    );
  }
}

and the error I get

enter image description here

I don't think it's my fault and I want it fixed


来源: stackexchange

问:
Subtracting values from two different Tables with Many To Many Relationship
I Have two tables,** table1 = products**

Product
QTY

Product1
20

product2
10

product3
15

product2
10

product1
5

products table contains same products which are purchased on different date and have different price but same name.

Table2 : InvoiceItems table

table 2 contains invoices for above products

Relationship

```<code>class Products extends Model
{

    public function soldproducts(): HasMany
    {
        return $this->hasMany(InvoiceItem::class, 'product_id','id');
    }

}
</code>```
```<code>class InvoiceItem extends Model
{
   public function products()
    {
        return $this->belongsToMany('App\Models\Products', 'product_id','id');
    }
}
</code>```

I grouped both tables by their name

```<code>$table1=   DB::table('products')
        ->groupBy('products.name')
        ->select(DB::raw('products.name, sum(products.qty) as totalqty'))
        ->get();

</code>```
```<code>$table2 = DB::table('invoice_items')
        ->groupBy('invoice_items.name')
        ->select(DB::raw('invoice_items.name, sum(invoice_items.product_qty) as soldqty'))
        ->get();
</code>```

Both above query giving desired result but

I need difference Balance QTy = totalqty - soldqty

How can I substract these two tables?

ContentLicense: CC BY-SA 4.0

Body:
I Have two tables,** table1 = products**

Product
QTY

Product1
20

product2
10

product3
15

product2
10

product1
5

products table contains same products which are purchased on different date and have different price but same name.

Table2 : InvoiceItems table

table 2 contains invoices for above products

Relationship

class Products extends Model
{

    public function soldproducts(): HasMany
    {
        return $this->hasMany(InvoiceItem::class, 'product_id','id');
    }

}

class InvoiceItem extends Model
{
   public function products()
    {
        return $this->belongsToMany('App\Models\Products', 'product_id','id');
    }
}

I grouped both tables by their name

$table1=   DB::table('products')
        ->groupBy('products.name')
        ->select(DB::raw('products.name, sum(products.qty) as totalqty'))
        ->get();

$table2 = DB::table('invoice_items')
        ->groupBy('invoice_items.name')
        ->select(DB::raw('invoice_items.name, sum(invoice_items.product_qty) as soldqty'))
        ->get();

Both above query giving desired result but

I need difference Balance QTy = totalqty - soldqty

How can I substract these two tables?


问:
URLError: <urlopen error [WinError 10060] # Unable to import Seaborn inbuilt dataset
'''
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline

tips = sns.load_dataset('tips')

'''

Getting Error********

unable to import seaborn inbuilt dataset.

URL Error: <URL open error [Win Error 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond>
'''


问:
Databricks - seprating columns + using schema
I wrote a set of code to create a chart, I am trying to show this chart in 2 ways; with and without the schema function. When I have my code without schema, my problem is that the columns are all shown in one column, and I don't know how to separate them:

```<code># File location and type
file_location = "/databricks-datasets/cs110x/ml-20m/data-001/movies.csv.gz"
file_type = "csv"

# CSV options
infer_schema = "true"
first_row_is_header = "false"
delimiter = "::"

df_movies = spark.read.format(file_type) \
  .option("inferSchema", infer_schema) \
  .option("header", first_row_is_header) \
  .option("sep", delimiter) \
  .load(file_location)

print(df_movies.count())
display(df_movies)
</code>```

Result:

And when I add schema, columns get separated but I get null values:

```<code>from pyspark.sql.types import *

movies_schema = StructType([
  StructField('movieId', IntegerType()),
  StructField('title', StringType()),
  StructField('genres', StringType())
])

# File location and type
file_location = "/databricks-datasets/cs110x/ml-20m/data-001/movies.csv.gz"
file_type = "csv"

# CSV options
infer_schema = "true"
first_row_is_header = "false"
delimiter = "::"

df_movies = spark.read.format(file_type) \
  .schema(movies_schema) \
  .option("header", first_row_is_header) \
  .option("sep", delimiter) \
  .load(file_location)

print(df_movies.count())
display(df_movies)
</code>```

Result:

I appreciate it if you could tell me how I can separate columns in the first section and how I can solve the problem with the null values in the second part.

Body:
I wrote a set of code to create a chart, I am trying to show this chart in 2 ways; with and without the schema function. When I have my code without schema, my problem is that the columns are all shown in one column, and I don't know how to separate them:

# File location and type
file_location = "/databricks-datasets/cs110x/ml-20m/data-001/movies.csv.gz"
file_type = "csv"

# CSV options
infer_schema = "true"
first_row_is_header = "false"
delimiter = "::"

df_movies = spark.read.format(file_type) \
  .option("inferSchema", infer_schema) \
  .option("header", first_row_is_header) \
  .option("sep", delimiter) \
  .load(file_location)

print(df_movies.count())
display(df_movies)

Result:

And when I add schema, columns get separated but I get null values:

from pyspark.sql.types import *

movies_schema = StructType([
  StructField('movieId', IntegerType()),
  StructField('title', StringType()),
  StructField('genres', StringType())
])

# File location and type
file_location = "/databricks-datasets/cs110x/ml-20m/data-001/movies.csv.gz"
file_type = "csv"

# CSV options
infer_schema = "true"
first_row_is_header = "false"
delimiter = "::"

df_movies = spark.read.format(file_type) \
  .schema(movies_schema) \
  .option("header", first_row_is_header) \
  .option("sep", delimiter) \
  .load(file_location)

print(df_movies.count())
display(df_movies)

Result:

I appreciate it if you could tell me how I can separate columns in the first section and how I can solve the problem with the null values in the second part.


问:
vue3 click event interferes with bootstrap js processing of dropdown
This is my first question asked here, so please be forgiving.
Asked the same question on dev.to, got no comment or answer after 1 week...

I'm using vue3, vite, bootstrap.

I'm working on a small app. One page loads some data from my server and passes it to a component to render a bootstrap dropdown. If the user selects an item from dropdown, the button type/color should change.
The first time I open the dropdown and select something, the color changes but the dropdown does not close. If I click the main dropdown button again, it closes, after that the dropdown works as intended.

I nailed down the problem to line 20 in the child component,

```<code>selectOption(optionId, event) {
this.bSelectedOption = true;
</code>```

where vue listens for the @click event and sets a boolean value to true, which changes classes in the template (line 29)

```<code><button
:class="bSelectedOption ? 'btn-success' : 'btn-danger'"
class="btn dropdown-toggle"
</code>```

Commenting out line 20 or removing the dynamic

```<code>:class
</code>```

makes bootstrap dropdown close on clik, but obviously does not change the  color anymore.

example code on codesandbox.io

I guess the first time around something happens in the event chain of click, maybe bootstrap get's some unfinished data while vue is working on the classes? But why opening the dropdown a second and nth time works flawlessly?

I hope to have some sort of feedback to this problem in order to find a solution :)

Body:
This is my first question asked here, so please be forgiving.
Asked the same question on dev.to, got no comment or answer after 1 week...

I'm using vue3, vite, bootstrap.

I'm working on a small app. One page loads some data from my server and passes it to a component to render a bootstrap dropdown. If the user selects an item from dropdown, the button type/color should change.
The first time I open the dropdown and select something, the color changes but the dropdown does not close. If I click the main dropdown button again, it closes, after that the dropdown works as intended.

I nailed down the problem to line 20 in the child component,

selectOption(optionId, event) {
this.bSelectedOption = true;

where vue listens for the @click event and sets a boolean value to true, which changes classes in the template (line 29)

<button
:class="bSelectedOption ? 'btn-success' : 'btn-danger'"
class="btn dropdown-toggle"

Commenting out line 20 or removing the dynamic

:class

makes bootstrap dropdown close on clik, but obviously does not change the  color anymore.

example code on codesandbox.io

I guess the first time around something happens in the event chain of click, maybe bootstrap get's some unfinished data while vue is working on the classes? But why opening the dropdown a second and nth time works flawlessly?

I hope to have some sort of feedback to this problem in order to find a solution :)


问:
Python: Modify already defined list in the both senses, modify the entry values, modify the number of values
This is a python code I was designed to get input values from users. Here I already have defined a list of integers, but I want to modify these values as well as increase the number of values in this. For example, the list "scores" given here contains 6 values, I want to build a program that should contain more than 6 values in the list and modify the first 6 values according to user input.

I tried the following:

```<code>    scores = [43, 12, 6, 78, 2, 14]
    #updating this list and increasing the number of values it is carrying by user input
    n = int(input("How many values you want to include in a list: "))
    for i in range(n):
        print("for ", i, "student:")
        score = int(input("Enter the score :"))
        #scores.append(score)
        if i in range(n):
            scores[i] = score
        else:
            scores.append(score)

    print(scores)
</code>```

and I am expecting to modify the list "scores", which should contain more than 6 values and the first 6 values of that list should be according to the values inserted by the user.

Someone, please guide me if this is possible to modify a list of integers with simultaneously increasing the number of values in it. Thank you!

Body:
This is a python code I was designed to get input values from users. Here I already have defined a list of integers, but I want to modify these values as well as increase the number of values in this. For example, the list "scores" given here contains 6 values, I want to build a program that should contain more than 6 values in the list and modify the first 6 values according to user input.

I tried the following:

    scores = [43, 12, 6, 78, 2, 14]
    #updating this list and increasing the number of values it is carrying by user input
    n = int(input("How many values you want to include in a list: "))
    for i in range(n):
        print("for ", i, "student:")
        score = int(input("Enter the score :"))
        #scores.append(score)
        if i in range(n):
            scores[i] = score
        else:
            scores.append(score)

    print(scores)

and I am expecting to modify the list "scores", which should contain more than 6 values and the first 6 values of that list should be according to the values inserted by the user.

Someone, please guide me if this is possible to modify a list of integers with simultaneously increasing the number of values in it. Thank you!


问:
Yarn Build error on Jenkins TS2322: Type '{ children: Element; key:
`TS2322: Type '{ children: Element; key: any; as: ForwardRefExoticComponent<NavLinkProps & RefAttributes>; to: any; activeClassName: string; className: string; }' is not assignable to type 'IntrinsicAttributes & Omit<NavLinkProps & RefAttributes, BsPrefixProps<ForwardRefExoticComponent<NavLinkProps & RefAttributes<...>>> & NavLinkProps> & BsPrefixProps<...> & NavLinkProps & { ...; }'.
Property 'activeClassName' does not exist on type 'IntrinsicAttributes & Omit<NavLinkProps & RefAttributes, BsPrefixProps<ForwardRefExoticComponent<NavLinkProps & RefAttributes<...>>> & NavLinkProps> & BsPrefixProps<...> & NavLinkProps & { ...; }'.
59 |                     as={NavLink}
60 |                     to={subitems.path}

61 |                     activeClassName="text-white rna-analytictab-item-active"
|                     ^^^^^^^^^^^^^^^
62 |                     className="rna-analytictab-item"
63 |                   >
64 |

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.`

This is the error I'm getting on Jenkins but on running it on /tmp location its working. Locally also its working file. The problem comes only when its in /var/lib/jenkins/workspace/ Yarn version is 1.22.17 and node is 14.19


问:
How to create the equivalent of an AND Excel function to assess the equivalent of two Excel COUNTIF functions, but in R instead
This question is based on the answer I got to a previous question I asked on here. The question is, how can I do what I could do in Excel using its AND function in the following manner (warning, I am likely going to confuse some of you here because I am just going to put the two working R equivalents of COUNTIFs I already have working as the two arguments in Excel's AND function):

```<code>AND(sum(unlist(BM1_TPRs) < 1, na.rm = TRUE),  sum(FPRs == 0, na.rm = TRUE))
</code>```

Either that, or, the simplified version I figured out myself after implementing the previous answer:

```<code>TPRs <- unlist(BM1_TPRs)
num_Under <- sum(TPRs < 1, na.rm = TRUE)

FPRs <- unlist(BM1_FPRs)
num_null_FPR <- sum(FPRs == 0, na.rm = TRUE)

AND(num_Under, num_null_FPR)
</code>```

Again, BM1_TPRs and BM1_FPRs are just lists with 20k numeric elements, all of which are within the range [0, 1]. So, my actual goal here is to count how many times both the TPR is less than 1 and the FPR is 1.

I have tried this:

```<code>nUnder = intersect((TPRs < 1), (FPRs == 0))
</code>```

But it does not work at all.

Body:
This question is based on the answer I got to a previous question I asked on here. The question is, how can I do what I could do in Excel using its AND function in the following manner (warning, I am likely going to confuse some of you here because I am just going to put the two working R equivalents of COUNTIFs I already have working as the two arguments in Excel's AND function):

AND(sum(unlist(BM1_TPRs) < 1, na.rm = TRUE),  sum(FPRs == 0, na.rm = TRUE))

Either that, or, the simplified version I figured out myself after implementing the previous answer:

TPRs <- unlist(BM1_TPRs)
num_Under <- sum(TPRs < 1, na.rm = TRUE)

FPRs <- unlist(BM1_FPRs)
num_null_FPR <- sum(FPRs == 0, na.rm = TRUE)

AND(num_Under, num_null_FPR)

Again, BM1_TPRs and BM1_FPRs are just lists with 20k numeric elements, all of which are within the range [0, 1]. So, my actual goal here is to count how many times both the TPR is less than 1 and the FPR is 1.

I have tried this:

nUnder = intersect((TPRs < 1), (FPRs == 0))

But it does not work at all.


问:
Troubleshooting Navigation Issues on the Onboarding to HomeScreen Transition
Hello I couldn't navigate from Onboarding to HomeScreen. I'm not sure what I do wrong. It gives error such as The 'navigation' object hasn't been initialized yet. This might happen if you don't have a navigator mounted, or if the navigator hasn't finished mounting. See https://reactnavigation.org/docs/navigating-without-navigation-prop#handling-initialization
for more details.

```<code>//AppRoot.js
  const [isFirstLaunch, setFirstLaunch] = useState(null);
  useEffect(() => {
    AsyncStorage.getItem("onboardingCompleted").then((value) => {
      if (value == null) {
        setFirstLaunch(true);
      } else {
        setFirstLaunch(false);
      }
    });
  }, []);
  return (
    <NavigationContainer
      ref={navigationRef}
      onReady={() =>
        (routeNameRef.current =
          navigationRef?.current?.getCurrentRoute()?.name ?? "")
      }
      onStateChange={() => {
        const previousRouteName = routeNameRef.current;
        const currentRouteName =
          navigationRef?.current?.getCurrentRoute()?.name;
        trackScreenView(previousRouteName, currentRouteName);
        console.log(previousRouteName, " -> ", currentRouteName);
        // Save the current route name for later comparison
        routeNameRef.current = currentRouteName;
      }}
      theme={themeToSet === "dark" ? DarkModeTheme : LightModeTheme}
    >
      <Loader visible={isLoading} />
      {isFirstLaunch == false ? <HomeScreen /> : <OnboardingScreen />}
    </NavigationContainer>
  );
</code>```
```<code>// Onboarding
const OnboardingScreen = () => {
  const navigation = useNavigation();

  const [currentPage, setCurrentPage] = useState(0);
  const pages = [
    <WelcomeScreen onGetStarted={() => setCurrentPage(1)} />,
    <PersonalizationScreen1 />,
    <PersonalizationScreen2 />,
    <NotificationScreen />,
    <WidgetScreen />,
    <PaywallScreen />,
    <EndScreen />,
  ];
  const onContinue = () => {
    if (currentPage === pages.length - 1) {
      AsyncStorage.setItem("onboardingCompleted", "true");
    } else {
      setCurrentPage(currentPage + 1);
    }
  };

  return <View>{React.cloneElement(pages[currentPage], { onContinue })}</View>;
};

export default OnboardingScreen;

</code>```
```<code>//HomeScreen
const Tab = createBottomTabNavigator();

const HomeBottomNavigation = () => {
  const { colors } = useTheme();
  const { t } = useTranslation();
  return (
    <Tab.Navigator
      id="BottomNavigation"
      initialRouteName="Users"
      screenOptions={({ route, navigation }) => ({
        headerShown: false,
        tabBarIcon: ({ focused, color, size }) => {
          let iconName;
          if (route.name === "UsersStack") {
            iconName = focused ? "people" : "people-outline";
          } else if (route.name === "SettingsStack") {
            iconName = focused ? "settings" : "settings-outline";
          } else if (route.name === "Feedback") {
            iconName = focused ? "newspaper" : "newspaper-outline";
          } else if (route.name === "More") {
            iconName = focused ? "apps" : "apps-outline";
          }
          return <Icon name={iconName} size={size} color={color} />;
        },
        tabBarActiveTintColor: colors.text,
        tabBarInactiveTintColor: "gray",
        unmountOnBlur: true,
      })}
    >
      <Tab.Screen
        name="UsersStack"
        component={UsersStackScreen}
        options={{ headerShown: false, title: t("users") }}
      />
      <Tab.Screen
        name="SettingsStack"
        component={SettingsStackScreen}
        options={{ headerShown: false, title: t("settings") }}
      />
      <Tab.Screen
        name="Feedback"
        component={FeedbackScreen}
        options={{ headerShown: false, title: t("feedback") }}
      />
      <Tab.Screen
        name="More"
        component={MoreScreen}
        options={{ headerShown: false, title: t("more") }}
      />
    </Tab.Navigator>
  );
};

export default HomeBottomNavigation;
</code>```
```<code>//Onboarding Stack
const Stack = createNativeStackNavigator();

const OnboardingStackNavigation = () => {
  return (
    <Stack.Navigator
      id="OnboardingNavigation"
      initialRouteName="Onboarding"
      screenOptions={({ route, navigation }) => {
        ({ headerShown: false });
      }}
    >
      <Stack.Screen
        name="Onboarding"
        component={OnboardingScreen}
        options={{ headerShown: false }}
      />
      <Stack.Screen
        name="Home"
        component={UsersScreen}
        options={{ headerShown: false }}
      />
    </Stack.Navigator>
  );
};
</code>```

I have tried passing setFirstLaunch to onboarding screen and tried to manage that.
I have tried navigating inside Onboarding.
I have tried button triggered navigation.

Body:
Hello I couldn't navigate from Onboarding to HomeScreen. I'm not sure what I do wrong. It gives error such as The 'navigation' object hasn't been initialized yet. This might happen if you don't have a navigator mounted, or if the navigator hasn't finished mounting. See https://reactnavigation.org/docs/navigating-without-navigation-prop#handling-initialization
for more details.

//AppRoot.js
  const [isFirstLaunch, setFirstLaunch] = useState(null);
  useEffect(() => {
    AsyncStorage.getItem("onboardingCompleted").then((value) => {
      if (value == null) {
        setFirstLaunch(true);
      } else {
        setFirstLaunch(false);
      }
    });
  }, []);
  return (
    <NavigationContainer
      ref={navigationRef}
      onReady={() =>
        (routeNameRef.current =
          navigationRef?.current?.getCurrentRoute()?.name ?? "")
      }
      onStateChange={() => {
        const previousRouteName = routeNameRef.current;
        const currentRouteName =
          navigationRef?.current?.getCurrentRoute()?.name;
        trackScreenView(previousRouteName, currentRouteName);
        console.log(previousRouteName, " -> ", currentRouteName);
        // Save the current route name for later comparison
        routeNameRef.current = currentRouteName;
      }}
      theme={themeToSet === "dark" ? DarkModeTheme : LightModeTheme}
    >
      <Loader visible={isLoading} />
      {isFirstLaunch == false ? <HomeScreen /> : <OnboardingScreen />}
    </NavigationContainer>
  );

// Onboarding
const OnboardingScreen = () => {
  const navigation = useNavigation();

  const [currentPage, setCurrentPage] = useState(0);
  const pages = [
    <WelcomeScreen onGetStarted={() => setCurrentPage(1)} />,
    <PersonalizationScreen1 />,
    <PersonalizationScreen2 />,
    <NotificationScreen />,
    <WidgetScreen />,
    <PaywallScreen />,
    <EndScreen />,
  ];
  const onContinue = () => {
    if (currentPage === pages.length - 1) {
      AsyncStorage.setItem("onboardingCompleted", "true");
    } else {
      setCurrentPage(currentPage + 1);
    }
  };

  return <View>{React.cloneElement(pages[currentPage], { onContinue })}</View>;
};

export default OnboardingScreen;

//HomeScreen
const Tab = createBottomTabNavigator();

const HomeBottomNavigation = () => {
  const { colors } = useTheme();
  const { t } = useTranslation();
  return (
    <Tab.Navigator
      id="BottomNavigation"
      initialRouteName="Users"
      screenOptions={({ route, navigation }) => ({
        headerShown: false,
        tabBarIcon: ({ focused, color, size }) => {
          let iconName;
          if (route.name === "UsersStack") {
            iconName = focused ? "people" : "people-outline";
          } else if (route.name === "SettingsStack") {
            iconName = focused ? "settings" : "settings-outline";
          } else if (route.name === "Feedback") {
            iconName = focused ? "newspaper" : "newspaper-outline";
          } else if (route.name === "More") {
            iconName = focused ? "apps" : "apps-outline";
          }
          return <Icon name={iconName} size={size} color={color} />;
        },
        tabBarActiveTintColor: colors.text,
        tabBarInactiveTintColor: "gray",
        unmountOnBlur: true,
      })}
    >
      <Tab.Screen
        name="UsersStack"
        component={UsersStackScreen}
        options={{ headerShown: false, title: t("users") }}
      />
      <Tab.Screen
        name="SettingsStack"
        component={SettingsStackScreen}
        options={{ headerShown: false, title: t("settings") }}
      />
      <Tab.Screen
        name="Feedback"
        component={FeedbackScreen}
        options={{ headerShown: false, title: t("feedback") }}
      />
      <Tab.Screen
        name="More"
        component={MoreScreen}
        options={{ headerShown: false, title: t("more") }}
      />
    </Tab.Navigator>
  );
};

export default HomeBottomNavigation;

//Onboarding Stack
const Stack = createNativeStackNavigator();

const OnboardingStackNavigation = () => {
  return (
    <Stack.Navigator
      id="OnboardingNavigation"
      initialRouteName="Onboarding"
      screenOptions={({ route, navigation }) => {
        ({ headerShown: false });
      }}
    >
      <Stack.Screen
        name="Onboarding"
        component={OnboardingScreen}
        options={{ headerShown: false }}
      />
      <Stack.Screen
        name="Home"
        component={UsersScreen}
        options={{ headerShown: false }}
      />
    </Stack.Navigator>
  );
};

I have tried passing setFirstLaunch to onboarding screen and tried to manage that.
I have tried navigating inside Onboarding.
I have tried button triggered navigation.


问:
Plotly Scatter3D plot with consistent gradient
I'm trying to visualize temperature curves from different source in a 3D scatter plot. I have set colorscale='Turbo' so that hotter region will be read and colder region will be blue. But I cannot plot multiple scatter line with consistent color gradient. I understand the problem is occurring because I'm drawing multiple line separately. But I couldn't find a way to do it at a time. I can do it for line plots. But line cannot be drawn with gradient.

Here is the visualization.

For a curve negative temperature is shown as red.

My code:

fig = go.Figure(go.Scatter3d(x=ch6_data['time'],  y=ch6_data['channel'], z=ch6_data['Ch6'], mode='markers', marker=dict(color=ch6_data['Ch6'], colorscale='Turbo', size=1, showscale=True)))

fig.add_trace(
    go.Scatter3d(x=ch1_data['time'],  y=ch1_data['channel'], z=ch1_data['Ch1'], mode='markers', marker=dict(color=ch1_data['Ch1'], colorscale='Turbo', size=1, showscale=True))
)

```

Is there any way to plot separate temperature curves with consistent gradient?

Body:
I'm trying to visualize temperature curves from different source in a 3D scatter plot. I have set colorscale='Turbo' so that hotter region will be read and colder region will be blue. But I cannot plot multiple scatter line with consistent color gradient. I understand the problem is occurring because I'm drawing multiple line separately. But I couldn't find a way to do it at a time. I can do it for line plots. But line cannot be drawn with gradient.

Here is the visualization.

For a curve negative temperature is shown as red.

My code:

fig = go.Figure(go.Scatter3d(x=ch6_data['time'],  y=ch6_data['channel'], z=ch6_data['Ch6'], mode='markers', marker=dict(color=ch6_data['Ch6'], colorscale='Turbo', size=1, showscale=True)))

fig.add_trace(
    go.Scatter3d(x=ch1_data['time'],  y=ch1_data['channel'], z=ch1_data['Ch1'], mode='markers', marker=dict(color=ch1_data['Ch1'], colorscale='Turbo', size=1, showscale=True))
)

Is there any way to plot separate temperature curves with consistent gradient?


问:
Visio control is resetting to old data when show() is called
I have a project which contains multiple forms that have a microsoft visio activex control in them.
For some reason they keep interfering with one another.  Here's a snip it of my code, simplified:

```<code>private void OpenRDM()
{
   if (RDMform == null)
   {
      // Constructor opens a new form, and populates a Visio control on it
      RDMform = new RDM.MainForm();
   }
   RDMform.Show();
}

private void OpenPSM()
{
   if (PSMform == null)
   {
      // Constructor opens a new form, and populates a Visio control on it
      PSMform = new PSM.MainForm();
   }
   PSMform.Show();  // Problem occurs here, PSM Visio control gains contents of RDM's Visio Control
}

public void main()
{
   OpenRDM();
   RDMform.Hide();
   OpenPSM();
   PSMForm.Hide();
}
</code>```

I can call one of these functions and it works fine, but if I hide the form, and then call the other one, its Visio control loads with the contents of the first form, instead of the correct new stuff.  I traced it, and the second Visio control is populated just fine, until the second Show() method is called, at which point it mysteriously goes back to the contents of the first Visio control.

I can't figure out what is going on here, Visio seems to think that they are the same control.

Edit*
In response to comment about setting the .src property.  The source is a behemoth, so I can't reasonably post everything it does.  But here's those lines.
in RDM:

```<code>If visioControl.Src <> TemplateFullName Then
   visioControl.Src = TemplateFullName
Else
   visioControl.Src = ""
   visioControl.Src = TemplateFullName
End If
</code>```

in PSM:

```<code>drawingControl.Src = string.Empty;
drawingControl.Src = vstFilepath;
InitializeFlowDiagram(dbFilepath); // updates shapes from database values
</code>```

Both modules actually use the same visio diagram including page names, they just display it in different ways.  So I'd like to be able to back and forth between them without having to reload everything.  Maybe the activeWindow is involved in the problem, I'll have to do more research.

ContentLicense: CC BY-SA 3.0

Body:
I have a project which contains multiple forms that have a microsoft visio activex control in them.
For some reason they keep interfering with one another.  Here's a snip it of my code, simplified:

private void OpenRDM()
{
   if (RDMform == null)
   {
      // Constructor opens a new form, and populates a Visio control on it
      RDMform = new RDM.MainForm();
   }
   RDMform.Show();
}

private void OpenPSM()
{
   if (PSMform == null)
   {
      // Constructor opens a new form, and populates a Visio control on it
      PSMform = new PSM.MainForm();
   }
   PSMform.Show();  // Problem occurs here, PSM Visio control gains contents of RDM's Visio Control
}

public void main()
{
   OpenRDM();
   RDMform.Hide();
   OpenPSM();
   PSMForm.Hide();
}

I can call one of these functions and it works fine, but if I hide the form, and then call the other one, its Visio control loads with the contents of the first form, instead of the correct new stuff.  I traced it, and the second Visio control is populated just fine, until the second Show() method is called, at which point it mysteriously goes back to the contents of the first Visio control.

I can't figure out what is going on here, Visio seems to think that they are the same control.

Edit*
In response to comment about setting the .src property.  The source is a behemoth, so I can't reasonably post everything it does.  But here's those lines.
in RDM:

If visioControl.Src <> TemplateFullName Then
   visioControl.Src = TemplateFullName
Else
   visioControl.Src = ""
   visioControl.Src = TemplateFullName
End If

in PSM:

drawingControl.Src = string.Empty;
drawingControl.Src = vstFilepath;
InitializeFlowDiagram(dbFilepath); // updates shapes from database values

Both modules actually use the same visio diagram including page names, they just display it in different ways.  So I'd like to be able to back and forth between them without having to reload everything.  Maybe the activeWindow is involved in the problem, I'll have to do more research.


问:
How do I redirect my customer to another site once they have clicked the UPI pay button
So I have basically created a UPI pay button. I want the link to automatically redirect once it evokes the UPI payment apps. For eg once customer clicks on pay button, UPI app show and in background he gets redirected.

I was expecting that customer can got to payment checking page once they click the UPI pay button


问:
Cause of slowdowns when using alternate methods of loading a pandas dataframe?
I am routinely loading large (~8gb) .csv files as a dataframe for my script. Due to issues with functions provided by pandas not fitting my needs, I decided to partition this large dataframe into a dictionary. Each day of data inside of the dataframe is stored as a separate, smaller dataframe accessible by the date as a key for the dictionary. (This allowed for very fast lookup times in the subsequent simulation process, each loop of which covers every single date.)

Because searching over the large dataframe for all rows that matched each successive date was time consuming, I rewrote the process to store chunks of the .csv in a list along with the minimum and maximum date in that chunk. Then I loaded it into the dictionary as before, and if part of the data was split across multiple chunks, I concatenated the two dataframes together.

This worked without any immediately noticeable flaws; the process of breaking the dataframe into the dictionary went from ~40 minutes to about fifteen seconds and the rest of the script executed without errors. However, I noticed that the average time to process a portion of the data went up to ~3.5 seconds per cycle compared to my prior benchmark of ~2.5 seconds.

This is not the first time I've noticed something like this. A few months ago, for faster testing and debugging purposes, I created a smaller .csv file via pandas that only contained the most recent two years of data, which translated to about an ~800mb file and much faster loading time. However, the time to process a portion of that data went up to ~20 seconds from the prior benchmark of ~12 seconds. I could not find any meaningful difference between the two tables; they had the same column types and the same number of columns. Nonetheless, processing the smaller table consistently led to slower simulation compared to simply loading the original, complete .csv as a dataframe. I especially note this because that slowdown predated the introduction of splitting the dataframe into daily tables inside of a dictionary.

To summarize my current process:

Load in the .csv (in chunks of 20000 lines)

Concatenate the chunks into a single dataframe

Breakout each day of data from the dataframe into a dictionary

Simulate

The new process:

Load in the .csv (in chunks of 20000 lines)

Breakout each day of data from all chunks whose max and minimum date straddle or match the specified date into a dictionary

Simulate

The breakout stage of the new process is much faster, but simulation is much slower.

I'm still fairly new to pandas, so this problem is perplexing to me. It seems as if the original .csv is "pure," and further handling of a dataframe created from it dilutes this purity and slows my simulation process.
In the first case, I loaded the .csv, concatenated its chunks into a dataframe, performed a .loc call to get a subset of rows from the dataframe, saved the result as a separate .csv, and loaded that in place of the original .csv.
In the second case, I have loaded the .csv without concatenating its chunks, peformed a .loc call to get a subset of rows from those specific chunks, and concatenated the results in the results of a dictionary.

One thing I did notice this time, however, was that my new process consistently results in a 10.5 GB dictionary, while the older process results in a 12.2 GB dictionary. So there is something about the new process that resulted in a considerably smaller table that processes slower than the benchmark.

The old method:

chunkList = [chunk for chunk in pandas.read_csv(f'{SOURCE}_candles.csv', chunksize=20000, low_memory=False)]
candles = pandas.concat(chunkList)
del chunkList

print("Got candles")

# Data type insurance...

candles['tm_uuid'] = candles['tm_uuid'].astype("string")
candles['ticker'] = candles['ticker'].astype("string")
candles['price_date'] = pandas.to_datetime(candles['price_date']).dt.date

# Specify the start date; don't want to waste time looking at days we don't care about

candles = candles.loc[(candles['price_date'] >= simul_date), :]

# Now get the active dates to use as keys for the dictionary.

activeDates = candles[CandleColumn.PRICE_DATE.value].unique().tolist()

print("Got active dates")

timerTest = time.time()
candlesDict = {}

# Now breakout into the dictionary

for date in activeDates:
    candlesDict[date] = candles.loc[(candles[CandleColumn.PRICE_DATE.value] == date), :]
    candlesDict[date].set_index(CandleColumn.TM_UUID.value, drop=False, inplace=True)
    print(f"Finished {date}")

print(f"Done in {time.time() - timerTest}")
print(f"Candles dictionary uses {sum([sys.getsizeof(candlesDict[date]) for date in activeDates]) / 1024}kb")

# We no longer need the candles table, so clear it from memory!
del candles
```
<p>And the new method:</p>
<pre class="lang-py prettyprint-override"><code>candles = [chunk for chunk in pandas.read_csv(f'{SOURCE}_candles.csv', chunksize=20000, low_memory=False)]

# Data type insurance...

for table in candles:
    table['tm_uuid'] = table['tm_uuid'].astype("string")
    table['ticker'] = table['ticker'].astype("string")
    table['price_date'] = pandas.to_datetime(table['price_date']).dt.date

# Specify the start date; don't want to waste time looking at days we don't care about

# todo this method is bad practice, create new list and copy. Maybe inplace drop of specified rows?
# Removing this does not improve processing speed...
for index, table in enumerate(candles):
    candles[index] = table.loc[(table['price_date'] >= simul_date), :]

# Now get the active dates to use as keys for the dictionary.

activeDatesUnflattened = [table[CandleColumn.PRICE_DATE.value].unique().tolist() for table in candles]
# Not much point to the .unique() call anymore eh?
activeDates = list(set(list(chain.from_iterable(activeDatesUnflattened))))
activeDates.sort()
del activeDatesUnflattened

timerTest = time.time()
candlesDict = {}
tableDates = []

# Capture the min and max dates for each table in the list

for table in candles:
    tableDates.append((table[CandleColumn.PRICE_DATE.value].min(), table[CandleColumn.PRICE_DATE.value].max()))

# Now breakout into the dictionary

for date in activeDates:
    for index, table in enumerate(candles):
        if date >= tableDates[index][0] and date <= tableDates[index][1]:
            # The date is within the bounds of the table
            if date in candlesDict.keys():
                # If there is a table there, we need to concat the two and make sure the index
                candlesDict[date] = pandas.concat([(table.loc[(table[CandleColumn.PRICE_DATE.value] == date), :]).set_index(CandleColumn.TM_UUID.value, drop=False, inplace=True), candlesDict[date]])
                # todo Faster way to preserve index?
            else:
                candlesDict[date] = table.loc[(table[CandleColumn.PRICE_DATE.value] == date), :]
                candlesDict[date].set_index(CandleColumn.TM_UUID.value, drop=False, inplace=True)
        else:
            continue
    print(f"Finished {date}")

print(f"Done in {time.time() - timerTest}")
print(f"Candles dictionary uses {sum([sys.getsizeof(candlesDict[date]) for date in activeDates]) / 1024}kb")

# We no longer need the candles table, so clear it from memory!
del candles
</code>```

Body:
I am routinely loading large (~8gb) .csv files as a dataframe for my script. Due to issues with functions provided by pandas not fitting my needs, I decided to partition this large dataframe into a dictionary. Each day of data inside of the dataframe is stored as a separate, smaller dataframe accessible by the date as a key for the dictionary. (This allowed for very fast lookup times in the subsequent simulation process, each loop of which covers every single date.)

Because searching over the large dataframe for all rows that matched each successive date was time consuming, I rewrote the process to store chunks of the .csv in a list along with the minimum and maximum date in that chunk. Then I loaded it into the dictionary as before, and if part of the data was split across multiple chunks, I concatenated the two dataframes together.

This worked without any immediately noticeable flaws; the process of breaking the dataframe into the dictionary went from ~40 minutes to about fifteen seconds and the rest of the script executed without errors. However, I noticed that the average time to process a portion of the data went up to ~3.5 seconds per cycle compared to my prior benchmark of ~2.5 seconds.

This is not the first time I've noticed something like this. A few months ago, for faster testing and debugging purposes, I created a smaller .csv file via pandas that only contained the most recent two years of data, which translated to about an ~800mb file and much faster loading time. However, the time to process a portion of that data went up to ~20 seconds from the prior benchmark of ~12 seconds. I could not find any meaningful difference between the two tables; they had the same column types and the same number of columns. Nonetheless, processing the smaller table consistently led to slower simulation compared to simply loading the original, complete .csv as a dataframe. I especially note this because that slowdown predated the introduction of splitting the dataframe into daily tables inside of a dictionary.

To summarize my current process:

Load in the .csv (in chunks of 20000 lines)

Concatenate the chunks into a single dataframe

Breakout each day of data from the dataframe into a dictionary

Simulate

The new process:

Load in the .csv (in chunks of 20000 lines)

Breakout each day of data from all chunks whose max and minimum date straddle or match the specified date into a dictionary

Simulate

The breakout stage of the new process is much faster, but simulation is much slower.

I'm still fairly new to pandas, so this problem is perplexing to me. It seems as if the original .csv is "pure," and further handling of a dataframe created from it dilutes this purity and slows my simulation process.
In the first case, I loaded the .csv, concatenated its chunks into a dataframe, performed a .loc call to get a subset of rows from the dataframe, saved the result as a separate .csv, and loaded that in place of the original .csv.
In the second case, I have loaded the .csv without concatenating its chunks, peformed a .loc call to get a subset of rows from those specific chunks, and concatenated the results in the results of a dictionary.

One thing I did notice this time, however, was that my new process consistently results in a 10.5 GB dictionary, while the older process results in a 12.2 GB dictionary. So there is something about the new process that resulted in a considerably smaller table that processes slower than the benchmark.

The old method:

chunkList = [chunk for chunk in pandas.read_csv(f'{SOURCE}_candles.csv', chunksize=20000, low_memory=False)]
candles = pandas.concat(chunkList)
del chunkList

print("Got candles")

# Data type insurance...

candles['tm_uuid'] = candles['tm_uuid'].astype("string")
candles['ticker'] = candles['ticker'].astype("string")
candles['price_date'] = pandas.to_datetime(candles['price_date']).dt.date

# Specify the start date; don't want to waste time looking at days we don't care about

candles = candles.loc[(candles['price_date'] >= simul_date), :]

# Now get the active dates to use as keys for the dictionary.

activeDates = candles[CandleColumn.PRICE_DATE.value].unique().tolist()

print("Got active dates")

timerTest = time.time()
candlesDict = {}

# Now breakout into the dictionary

for date in activeDates:
    candlesDict[date] = candles.loc[(candles[CandleColumn.PRICE_DATE.value] == date), :]
    candlesDict[date].set_index(CandleColumn.TM_UUID.value, drop=False, inplace=True)
    print(f"Finished {date}")

print(f"Done in {time.time() - timerTest}")
print(f"Candles dictionary uses {sum([sys.getsizeof(candlesDict[date]) for date in activeDates]) / 1024}kb")

# We no longer need the candles table, so clear it from memory!
del candles

And the new method:

candles = [chunk for chunk in pandas.read_csv(f'{SOURCE}_candles.csv', chunksize=20000, low_memory=False)]

# Data type insurance...

for table in candles:
    table['tm_uuid'] = table['tm_uuid'].astype("string")
    table['ticker'] = table['ticker'].astype("string")
    table['price_date'] = pandas.to_datetime(table['price_date']).dt.date

# Specify the start date; don't want to waste time looking at days we don't care about

# todo this method is bad practice, create new list and copy. Maybe inplace drop of specified rows?
# Removing this does not improve processing speed...
for index, table in enumerate(candles):
    candles[index] = table.loc[(table['price_date'] >= simul_date), :]

# Now get the active dates to use as keys for the dictionary.

activeDatesUnflattened = [table[CandleColumn.PRICE_DATE.value].unique().tolist() for table in candles]
# Not much point to the .unique() call anymore eh?
activeDates = list(set(list(chain.from_iterable(activeDatesUnflattened))))
activeDates.sort()
del activeDatesUnflattened

timerTest = time.time()
candlesDict = {}
tableDates = []

# Capture the min and max dates for each table in the list

for table in candles:
    tableDates.append((table[CandleColumn.PRICE_DATE.value].min(), table[CandleColumn.PRICE_DATE.value].max()))

# Now breakout into the dictionary

for date in activeDates:
    for index, table in enumerate(candles):
        if date >= tableDates[index][0] and date <= tableDates[index][1]:
            # The date is within the bounds of the table
            if date in candlesDict.keys():
                # If there is a table there, we need to concat the two and make sure the index
                candlesDict[date] = pandas.concat([(table.loc[(table[CandleColumn.PRICE_DATE.value] == date), :]).set_index(CandleColumn.TM_UUID.value, drop=False, inplace=True), candlesDict[date]])
                # todo Faster way to preserve index?
            else:
                candlesDict[date] = table.loc[(table[CandleColumn.PRICE_DATE.value] == date), :]
                candlesDict[date].set_index(CandleColumn.TM_UUID.value, drop=False, inplace=True)
        else:
            continue
    print(f"Finished {date}")

print(f"Done in {time.time() - timerTest}")
print(f"Candles dictionary uses {sum([sys.getsizeof(candlesDict[date]) for date in activeDates]) / 1024}kb")

# We no longer need the candles table, so clear it from memory!
del candles


问:
Can I have separate definition and declaration for a template in c++?
I'm learning templates and I noticed that I cannot seem to declare and define a template separately. With a function, I'd declare it before main and define it after main to keep good readability. But it seems like I have to write the whole template at once, and before main. But I want my main function to be at the top. Surely there would be a way to do this but I couldn't find it.

'''

```<code>#include <iostream>

using std::cout;
using std::endl;

template <typename T>
void Print(T a);

int main(void)
{
    Print("Hey");
    // free variables
    return 0;
}

void Print(T a)
{
    cout << a << endl;
}
</code>```

'''

Body:
I'm learning templates and I noticed that I cannot seem to declare and define a template separately. With a function, I'd declare it before main and define it after main to keep good readability. But it seems like I have to write the whole template at once, and before main. But I want my main function to be at the top. Surely there would be a way to do this but I couldn't find it.

'''

#include <iostream>

using std::cout;
using std::endl;

template <typename T>
void Print(T a);

int main(void)
{
    Print("Hey");
    // free variables
    return 0;
}

void Print(T a)
{
    cout << a << endl;
}

'''


问:
c# Generic class for handling static method
I want to have a base generic class to handle model conversion.
Below are the model interfaces

    public interface IRawModel
    {
    }

    public interface IDtoModel
    {
    }

    public interface IRawDto<T1, T2>
        where T1 : IRawModel
        where T2 : IDtoModel
    {
        ///
        /// Get DTO model.
        ///
        /// <param name="item">Raw item</param>
        /// <returns>DTO item</returns>
        static T2 GetDto(T1 item) => throw new NotImplementedException();
    }
```
<p>Model classes</p>
<pre class="lang-cs prettyprint-override"><code>    public class UserDto : IDtoModel
    {
        /// <summary>
        /// Gets or sets firstname.
        /// </summary>
        public string? FirstName { get; set; }

        /// <summary>
        /// Gets or sets lastname.
        /// </summary>
        public string? LastName { get; set; }

        /// <summary>
        /// Gets or sets email.
        /// </summary>
        public string? Email { get; set; }
    }

    public class User : IRawModel, IRawDto<User, UserDto>
    {

        /// <summary>
        /// Gets or sets first name.
        /// </summary>
        public string FirstName { get; set; }

        /// <summary>
        /// Gets or sets last name.
        /// </summary>
        public string LastName { get; set; }

        /// <summary>
        /// Gets or sets email.
        /// </summary>
        public string Email { get; set; }

        /// <summary>
        /// Gets DTO model.
        /// </summary>
        /// <param name="user">User</param>
        /// <returns>User DTO</returns>
        public static UserDto GetDto(User user) => new UserDto
        {

            Email = user.Email,
            FirstName = user.FirstName,
            LastName = user.LastName,

        };
    }

</code>```

When i get a collection of users and to handle conversion in generic way i created below base class

    public class BaseRepository<T1, T2, T3>
        where T1 : IRawModel
        where T2 : IDtoModel
        where T3 : IRawDto<T1, T2>
    {
        ///
        /// Convert collection
        ///
        /// <param name="items">T3 items</param>
        /// <returns>DTO items</returns>
        public IEnumerable<T2> GetDtos(IEnumerable<T3> items)
        {
            IEnumerable<T2> result = Enumerable.Empty<T2>();

            // Something like this, not able to figure out
            //result = items
            //    .Select(x => T3.GetDto((T1)x))
            //    .ToList();

            return result;
        }
    }
```

I read interfaces can't have static methods until some c# 8.
Is this an overkill for a conversion, should i implement this conversion in individual classes?

Body:
I want to have a base generic class to handle model conversion.
Below are the model interfaces

    public interface IRawModel
    {
    }

    public interface IDtoModel
    {
    }

    public interface IRawDto<T1, T2>
        where T1 : IRawModel
        where T2 : IDtoModel
    {
        ///
        /// Get DTO model.
        ///
        /// <param name="item">Raw item</param>
        /// <returns>DTO item</returns>
        static T2 GetDto(T1 item) => throw new NotImplementedException();
    }

Model classes

    public class UserDto : IDtoModel
    {
        ///
        /// Gets or sets firstname.
        ///
        public string? FirstName { get; set; }

        ///
        /// Gets or sets lastname.
        ///
        public string? LastName { get; set; }

        ///
        /// Gets or sets email.
        ///
        public string? Email { get; set; }
    }

    public class User : IRawModel, IRawDto<User, UserDto>
    {

        ///
        /// Gets or sets first name.
        ///
        public string FirstName { get; set; }

        ///
        /// Gets or sets last name.
        ///
        public string LastName { get; set; }

        ///
        /// Gets or sets email.
        ///
        public string Email { get; set; }

        ///
        /// Gets DTO model.
        ///
        /// <param name="user">User</param>
        /// <returns>User DTO</returns>
        public static UserDto GetDto(User user) => new UserDto
        {

            Email = user.Email,
            FirstName = user.FirstName,
            LastName = user.LastName,

        };
    }

When i get a collection of users and to handle conversion in generic way i created below base class

    public class BaseRepository<T1, T2, T3>
        where T1 : IRawModel
        where T2 : IDtoModel
        where T3 : IRawDto<T1, T2>
    {
        ///
        /// Convert collection
        ///
        /// <param name="items">T3 items</param>
        /// <returns>DTO items</returns>
        public IEnumerable<T2> GetDtos(IEnumerable<T3> items)
        {
            IEnumerable<T2> result = Enumerable.Empty<T2>();

            // Something like this, not able to figure out
            //result = items
            //    .Select(x => T3.GetDto((T1)x))
            //    .ToList();

            return result;
        }
    }

I read interfaces can't have static methods until some c# 8.
Is this an overkill for a conversion, should i implement this conversion in individual classes?


问:
How to solve YellowbrickTypeError: The supplied model is not a clustering estimator; try a classifier or regression score visualizer instead?
I am trying to visualize the silhouette score for the fuzzy c-means clustering method using yellowbrick's silhouette visualizer. This same code works perfectly fine for k-means clustering. However, it provides the following error for the fuzzy c-means clustering method.

```<code>import matplotlib.pyplot as plt
from fcmeans import FCM
from yellowbrick.cluster import SilhouetteVisualizer

model = FCM(n_clusters=5, random_state=0)
visualizer = SilhouetteVisualizer(model, colors='yellowbrick')

visualizer.fit(X)
visualizer.show()
</code>```

error:

```<code> YellowbrickTypeError                      Traceback (most recent call last)
 Input In [24], in <cell line: 6>()
  3 from yellowbrick.cluster import SilhouetteVisualizer
  5 model = FCM(n_clusters=5, random_state=0)
  ----> 6 visualizer = SilhouetteVisualizer(model, colors='yellowbrick')
    8 visualizer.fit(X)
    9 visualizer.show()

File C:\ProgramData\Anaconda3\lib\site-packages\yellowbrick\cluster\silhouette.py:118, in SilhouetteVisualizer.__init__(self, estimator, ax, colors, is_fitted, **kwargs)
115 def __init__(self, estimator, ax=None, colors=None, is_fitted="auto", **kwargs):
116
117     # Initialize the visualizer bases
--> 118     super(SilhouetteVisualizer, self).__init__(estimator, ax=ax, **kwargs)
120     # Visual Properties
121     # Use colors if it is given, otherwise attempt to use colormap which
122     # which will override colors. If neither is found, default to None.
123     # The colormap may yet still be found in resolve_colors
124     self.colors = colors

File C:\ProgramData\Anaconda3\lib\site-packages\yellowbrick\cluster\base.py:45, in
 ClusteringScoreVisualizer.__init__(self, estimator, ax, fig, force_model, **kwargs)
 43 def __init__(self, estimator, ax=None, fig=None, force_model=False, **kwargs):
 44     if not force_model and not isclusterer(estimator):
 ---> 45         raise YellowbrickTypeError(
 46             "The supplied model is not a clustering estimator; try a "
 47             "classifier or regression score visualizer instead!"
 48         )
 49     self.force_model = force_model
 50     super(ClusteringScoreVisualizer, self).__init__(
 51         estimator, ax=ax, fig=fig, **kwargs
 52     )
</code>```

YellowbrickTypeError: The supplied model is not a clustering estimator; try a classifier or
regression score visualizer instead!
Kindly help me in solving this issue.

Body:
I am trying to visualize the silhouette score for the fuzzy c-means clustering method using yellowbrick's silhouette visualizer. This same code works perfectly fine for k-means clustering. However, it provides the following error for the fuzzy c-means clustering method.

import matplotlib.pyplot as plt
from fcmeans import FCM
from yellowbrick.cluster import SilhouetteVisualizer

model = FCM(n_clusters=5, random_state=0)
visualizer = SilhouetteVisualizer(model, colors='yellowbrick')

visualizer.fit(X)
visualizer.show()

error:

 YellowbrickTypeError                      Traceback (most recent call last)
 Input In [24], in <cell line: 6>()
  3 from yellowbrick.cluster import SilhouetteVisualizer
  5 model = FCM(n_clusters=5, random_state=0)
  ----> 6 visualizer = SilhouetteVisualizer(model, colors='yellowbrick')
    8 visualizer.fit(X)
    9 visualizer.show()

File C:\ProgramData\Anaconda3\lib\site-packages\yellowbrick\cluster\silhouette.py:118, in SilhouetteVisualizer.__init__(self, estimator, ax, colors, is_fitted, **kwargs)
115 def __init__(self, estimator, ax=None, colors=None, is_fitted="auto", **kwargs):
116
117     # Initialize the visualizer bases
--> 118     super(SilhouetteVisualizer, self).__init__(estimator, ax=ax, **kwargs)
120     # Visual Properties
121     # Use colors if it is given, otherwise attempt to use colormap which
122     # which will override colors. If neither is found, default to None.
123     # The colormap may yet still be found in resolve_colors
124     self.colors = colors

File C:\ProgramData\Anaconda3\lib\site-packages\yellowbrick\cluster\base.py:45, in
 ClusteringScoreVisualizer.__init__(self, estimator, ax, fig, force_model, **kwargs)
 43 def __init__(self, estimator, ax=None, fig=None, force_model=False, **kwargs):
 44     if not force_model and not isclusterer(estimator):
 ---> 45         raise YellowbrickTypeError(
 46             "The supplied model is not a clustering estimator; try a "
 47             "classifier or regression score visualizer instead!"
 48         )
 49     self.force_model = force_model
 50     super(ClusteringScoreVisualizer, self).__init__(
 51         estimator, ax=ax, fig=fig, **kwargs
 52     )

YellowbrickTypeError: The supplied model is not a clustering estimator; try a classifier or
regression score visualizer instead!
Kindly help me in solving this issue.


问:
On manjaro ssh-add only works in the window i execute it in
I'm pretty new to stack overflow, so I don't know how to refer to previous question. I understand that
eval ssh-agent -c

starts my ssh-agent in my instance, and that I can then execute ssh-add. How do I get ssh-agent to come up at start-up, and how do I get the passphrase to be global? I'm running Rocky on another machine and ssh-agent seems to already be working whenever I fire up a new window.  I'm using the newest version of Manjaro-kde

In Manjaro-kde, running tcsh in a new window, I issued

eval ssh-agent -c

which started ssh-agent. I then used ssh-add with the appropriate passphrase, and, in that window, I can use a dsa or rsa public key without reissuing the passphrase. However, when I bring up another window, ssh-agent is not running, so I have to go through exactly the same process. This gets really old.

On my Rocky machine, I never have to start ssh-agent, and I only have to issue ssh-add in one window for the passphrase to be known in all windows.

I want the Rocky behavior on Manjaro.


问:
Taiwind in react not working properly , while absolute and top-[200px] is given to a div element
Here is the screenshot of HTML

when i select H from the drop down and click on submit button , i want to add that H to ui with incresing top by 20px , but while it reaches beyond 180px it does not work anymore and stays at 0px.

Here is how it showing in browser

here is what i tried

```<code>import react from "react";
import "../index.css";
import { useState, useRef, useEffect } from "react";
function Main() {
           const [value, setValue] = useState("default");
           const [selectedValue, setSelectedValue] = useState("default");
           const [values, setValues] = useState([]);
  const [row, setRow] = useState(0);
  const [column, setColumn] = useState(0);

  function handleChange(e) {
    setSelectedValue(e.target.value);
  }
  function submit(e) {
    e.preventDefault();
    if (selectedValue === "default") {
      alert("select a value");
      return;
    }
    setValue(selectedValue);

    if (selectedValue === value) {
      setColumn(column + 20);
    } else {
    }
    setValues([...values, { row: row, column: column, value: selectedValue }]);
  }

  return (
    <>
      <div className="h-screen p-2">
        <form
          onSubmit={submit}
          className="flex mt-10 justify-center gap-1 max-w-sm mx-auto"
        >
          <select
            className="border border-black p-2 w-full"
            name="value"
            onChange={handleChange}
          >
            <option value="default">Select Value</option>
            <option value="H">H</option>
            <option value="T">T</option>
          </select>
          <button className={`bg-black text-white p-2`}>Submit</button>
        </form>
        <div className="flex justify-center mt-12">
          <div className="relative h-screen border w-full">
            {values.map((m, i) => {
              return (
                <div
                  key={i}
                  className={`absolute top-[${m.column}px]  left-[${m.row}px]`}
                >
                  {m.value}
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </>
  );
}

export default Main;
</code>```

Body:
Here is the screenshot of HTML

when i select H from the drop down and click on submit button , i want to add that H to ui with incresing top by 20px , but while it reaches beyond 180px it does not work anymore and stays at 0px.

Here is how it showing in browser

here is what i tried

import react from "react";
import "../index.css";
import { useState, useRef, useEffect } from "react";
function Main() {
           const [value, setValue] = useState("default");
           const [selectedValue, setSelectedValue] = useState("default");
           const [values, setValues] = useState([]);
  const [row, setRow] = useState(0);
  const [column, setColumn] = useState(0);

  function handleChange(e) {
    setSelectedValue(e.target.value);
  }
  function submit(e) {
    e.preventDefault();
    if (selectedValue === "default") {
      alert("select a value");
      return;
    }
    setValue(selectedValue);

    if (selectedValue === value) {
      setColumn(column + 20);
    } else {
    }
    setValues([...values, { row: row, column: column, value: selectedValue }]);
  }

  return (
    <>

        <form
          onSubmit={submit}
          className="flex mt-10 justify-center gap-1 max-w-sm mx-auto"
        >
          <select
            className="border border-black p-2 w-full"
            name="value"
            onChange={handleChange}
          >
            <option value="default">Select Value</option>
            <option value="H">H</option>
            <option value="T">T</option>
          </select>
          <button className={`bg-black text-white p-2`}>Submit</button>
        </form>

            {values.map((m, i) => {
              return (
                <div
                  key={i}
                  className={`absolute top-[${m.column}px]  left-[${m.row}px]`}
                >
                  {m.value}

              );
            })}

    </>
  );
}

export default Main;


问:
Can a Google Cloud Function communicate through a WebSocket?
Our many end users will, through a web browser, read and write in partly overlapping data.
When a user makes a change, a related change should be broadcasted to relevant other users.

Example use case: Several end users, each on their own device, look at a calendar with available time blocks to make an appointment. One of them creates an appointment, causing that a time block is not available for others anymore. The calendar on the screens of those others is updated accordingly and immediately.

Technically this would mean:

Browser sends 'create appointment' event through WebSocket

This event spins up a Cloud Function, which does the following (and then terminates):

Reserve the required capacity in the database

If this causes that the used time block is not available anymore for other users: Broadcast a 'not available anymore' event through the WebSockets of those other users that are viewing this time block.

In Google Cloud this is possible using an Apigee Java callout, where the Java (if needed) calls a Cloud Function, as described on https://cloud.google.com/apigee/docs/api-platform/develop/how-create-java-callout. However, Apigee runs in Kubernetes (https://cloud.google.com/apigee/docs/hybrid/kubernetes-resources), causing the overhead of containers being up at moments when they are not or sparsely used.

Google Clouds API Gateway https://cloud.google.com/api-gateway doesn't support WebSockets: https://issuetracker.google.com/issues/176472002?pli=1

Is there a way to accomplish our goal through a Cloud Function, without any container?


问:
How to phrase the csv file from remote in my shared mudule of Kotlin multi-platform mobile project
As the title says, is there an efficient and convenient way to help me parse and read csv files in the common directory of the KMM project?

I tried some third-party csv parsing libraries, but none of them seem to support kmm... I also tried using kotlin-csv in shared gradle, but it didn't seem to work.

Can someone help me?


问:
ValidationError: Invalid options object. Style Loader has been initialized using an options object that does not match the API schema

how to solve this type of issue??
Module build failed (from ./node_modules/@angular-devkit/build-angular/node_modules/style-loader/dist/cjs.js):
ValidationError: Invalid options object. Style Loader has been initialized using an options object that does not match the API schema.

options should be an object:
object { injectType?, attributes?, insert?, base?, esModule? }

How to solve this issue..


问:
NextJS MUI props geting overwritten from normal css
I am currently tranfering my CRA project into a NextJS app. Unfortunately I am facing a weird bug. The MUI props get overwritten from the globals.css file. I would like to fix this issue so the css class is not overwritting the MUI pros anymore.

The css class is called default-flex:

```<code>.default-flex {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}
</code>```

Example MUI code:

```<code><Box sx={{display: {xs: "flex", lg: "none"}}} className='default-flex'>
  <Button variant='contained'}>Click me!</Button>
</Box>
</code>```

Also, if I would add something like justifyContent: "left" to the Box, the css class would overwrite it with justify-content: space-between;

What happens when running this code is that the Box is always visible (display is flex coming from the css class). It should normally only be visible on xs devices.

I was following this tutorial => https://dev.to/hajhosein/nextjs-mui-v5-tutorial-2k35

Template repo => https://github.com/HPouyanmehr/muxt

I hope someone can help me!

Body:
I am currently tranfering my CRA project into a NextJS app. Unfortunately I am facing a weird bug. The MUI props get overwritten from the globals.css file. I would like to fix this issue so the css class is not overwritting the MUI pros anymore.

The css class is called default-flex:

.default-flex {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

Example MUI code:

<Box sx={{display: {xs: "flex", lg: "none"}}} className='default-flex'>
  <Button variant='contained'}>Click me!</Button>
</Box>

Also, if I would add something like justifyContent: "left" to the Box, the css class would overwrite it with justify-content: space-between;

What happens when running this code is that the Box is always visible (display is flex coming from the css class). It should normally only be visible on xs devices.

I was following this tutorial => https://dev.to/hajhosein/nextjs-mui-v5-tutorial-2k35

Template repo => https://github.com/HPouyanmehr/muxt

I hope someone can help me!


问:
Creating Coupon code with custom rules in woocommerce
 I need help to creating woocommerce coupon code with custom conditions

for example: coupon code: NEW

 if total order value between: 1000 to 10000 apply 5% discount

or

 if total order value between 10001 to 20000 apply 10% discount

or

 if total order value between 20001 to 30000 apply 15% discount.

I need help to creating woocommerce coupon code with custom conditions

for example: coupon code: NEW

if total order value between: 1000 to 10000 apply 5% discount
or
if total order value between 10001 to 20000 apply 10% discount
or
if total order value between 20001 to 30000 apply 15% discount.


问:
I am creating a figma plugin. When I show the checkbox nothing is displayed
https://github.com/nirsky/figma-plugin-react-template.

It is developed by cloning the above template.

If you place input type="radio" in components/App.tsx, the plugin will not be displayed on figma.

What should I do if I want to place a checkbox when creating a figma plug-in?

```<code>import React from "react";
import "../styles/ui.css";

function App() {

  React.useEffect(() => {
    // This is how we read messages sent from the plugin controller
    window.onmessage = (event) => {
      const { type, message } = event.data.pluginMessage;
      if (type === "create-rectangles") {
        console.log(`Figma Says: ${message}`);
      }
    };
  }, []);

  return (
    <div>
      <img src={require("../assets/logo.png")} />
      <h2>Simple</h2>
      <div>
        <input type="radio">Selection</input>
      </div>
    </div>
  );
}

export default App;

</code>```

Body:
https://github.com/nirsky/figma-plugin-react-template.

It is developed by cloning the above template.

If you place input type="radio" in components/App.tsx, the plugin will not be displayed on figma.

What should I do if I want to place a checkbox when creating a figma plug-in?

import React from "react";
import "../styles/ui.css";

function App() {

  React.useEffect(() => {
    // This is how we read messages sent from the plugin controller
    window.onmessage = (event) => {
      const { type, message } = event.data.pluginMessage;
      if (type === "create-rectangles") {
        console.log(`Figma Says: ${message}`);
      }
    };
  }, []);

  return (

Simple

        <input type="radio">Selection</input>

  );
}

export default App;