问:
How to create a drawer without TopAppBar in Jetpack Compose - Android
So i am new to Jetpack compose and am trying to figure out how to add the drawer functionality to a button on my view.

A counterpart question that i found for my question in relation to the XML imperative approach Navigation Drawer without Actionbar

Would love to learn about the approach to the same.

答:
You can accomplish this in many ways i guess. I will only post 2 alternatives

1- You can use Scaffold with drawerContent and adding your layout as this content

```<code>val scaffoldState = rememberScaffoldState()

val coroutineScope = rememberCoroutineScope()
val openDrawer: () -> Unit = { coroutineScope.launch { scaffoldState.drawerState.open() } }
val closeDrawer: () -> Unit = { coroutineScope.launch { scaffoldState.drawerState.close() } }

Scaffold(
    scaffoldState = scaffoldState,
    drawerContent = {
        AppDrawer(
            currentRoute = currentRoute,
            navigateToHome = {
                currentRoute = Routes.HOME_ROUTE
                navController.popBackStack()
                navController.navigate(currentRoute)
            },
            navigateToSettings = {
                currentRoute = Routes.SETTINGS_ROUTE
                navController.popBackStack()
                navController.navigate(currentRoute)
            },
            closeDrawer = closeDrawer
        )
    },

) {
    NavHost(
        navController = navController,
        startDestination = Routes.HOME_ROUTE
    ) {
        composable(Routes.HOME_ROUTE) {
            HomeComponent()
        }

        composable(Routes.SETTINGS_ROUTE) {
            SettingsComponent()
        }
    }
}
</code>```

Our drawer content

```<code>@Composable
fun AppDrawer(
    currentRoute: String,
    navigateToHome: () -> Unit,
    navigateToSettings: () -> Unit,
    closeDrawer: () -> Unit
) {

    Column(modifier = Modifier.fillMaxSize()) {
        DrawerHeader()
        DrawerButton(
            icon = Icons.Filled.Home,
            label = "Home",
            isSelected = currentRoute == Routes.HOME_ROUTE,
            action = {
                if (currentRoute != Routes.HOME_ROUTE) {
                    navigateToHome()
                }
                closeDrawer()
            }
        )

        DrawerButton(
            icon = Icons.Filled.Settings,
            label = "Settings",
            isSelected = currentRoute == Routes.SETTINGS_ROUTE,
            action = {
                if (currentRoute != Routes.SETTINGS_ROUTE) {
                    navigateToSettings()
                }
                closeDrawer()
            }
        )
    }
}
</code>```

You need to set scaffoldState to have drawer to be able to open or close with other interactions other than drawable behavior.
openDrawer and closeDrawer lambdas are required if you need to open or close drawer like touching an item on drawer on content.

2- Using ModalDrawer

```<code>@Composable
private fun ModalDrawerComponent() {
    val drawerState = rememberDrawerState(DrawerValue.Closed)
    val coroutineScope = rememberCoroutineScope()
    val openDrawer: () -> Unit = { coroutineScope.launch { drawerState.open() } }
    val closeDrawer: () -> Unit = { coroutineScope.launch { drawerState.close() } }
    var selectedIndex by remember { mutableStateOf(0) }

    ModalDrawer(
        drawerState = drawerState,
        drawerContent = {
            ModalDrawerContentHeader()
            Divider()
            ModelDrawerContentBody(
                selectedIndex,
                onSelected = {
                    selectedIndex = it
                },
                closeDrawer = closeDrawer
            )
        },
        content = {
            Column(modifier = Modifier.fillMaxSize()) {
//                ModalDrawerTopAppBar(openDrawer)
                ModalContent(openDrawer)
            }
        }
    )
}
</code>```

With ModalDrawer you set your Content as you wish if you don't want to add TopAppBar you just don't add it inside content. I commented it here to display that it's not there.

You can check repo that contains implementations here.

Body:
You can accomplish this in many ways i guess. I will only post 2 alternatives

1- You can use Scaffold with drawerContent and adding your layout as this content

val scaffoldState = rememberScaffoldState()

val coroutineScope = rememberCoroutineScope()
val openDrawer: () -> Unit = { coroutineScope.launch { scaffoldState.drawerState.open() } }
val closeDrawer: () -> Unit = { coroutineScope.launch { scaffoldState.drawerState.close() } }

Scaffold(
    scaffoldState = scaffoldState,
    drawerContent = {
        AppDrawer(
            currentRoute = currentRoute,
            navigateToHome = {
                currentRoute = Routes.HOME_ROUTE
                navController.popBackStack()
                navController.navigate(currentRoute)
            },
            navigateToSettings = {
                currentRoute = Routes.SETTINGS_ROUTE
                navController.popBackStack()
                navController.navigate(currentRoute)
            },
            closeDrawer = closeDrawer
        )
    },

) {
    NavHost(
        navController = navController,
        startDestination = Routes.HOME_ROUTE
    ) {
        composable(Routes.HOME_ROUTE) {
            HomeComponent()
        }

        composable(Routes.SETTINGS_ROUTE) {
            SettingsComponent()
        }
    }
}

Our drawer content

@Composable
fun AppDrawer(
    currentRoute: String,
    navigateToHome: () -> Unit,
    navigateToSettings: () -> Unit,
    closeDrawer: () -> Unit
) {

    Column(modifier = Modifier.fillMaxSize()) {
        DrawerHeader()
        DrawerButton(
            icon = Icons.Filled.Home,
            label = "Home",
            isSelected = currentRoute == Routes.HOME_ROUTE,
            action = {
                if (currentRoute != Routes.HOME_ROUTE) {
                    navigateToHome()
                }
                closeDrawer()
            }
        )

        DrawerButton(
            icon = Icons.Filled.Settings,
            label = "Settings",
            isSelected = currentRoute == Routes.SETTINGS_ROUTE,
            action = {
                if (currentRoute != Routes.SETTINGS_ROUTE) {
                    navigateToSettings()
                }
                closeDrawer()
            }
        )
    }
}

You need to set scaffoldState to have drawer to be able to open or close with other interactions other than drawable behavior.
openDrawer and closeDrawer lambdas are required if you need to open or close drawer like touching an item on drawer on content.

2- Using ModalDrawer

@Composable
private fun ModalDrawerComponent() {
    val drawerState = rememberDrawerState(DrawerValue.Closed)
    val coroutineScope = rememberCoroutineScope()
    val openDrawer: () -> Unit = { coroutineScope.launch { drawerState.open() } }
    val closeDrawer: () -> Unit = { coroutineScope.launch { drawerState.close() } }
    var selectedIndex by remember { mutableStateOf(0) }

    ModalDrawer(
        drawerState = drawerState,
        drawerContent = {
            ModalDrawerContentHeader()
            Divider()
            ModelDrawerContentBody(
                selectedIndex,
                onSelected = {
                    selectedIndex = it
                },
                closeDrawer = closeDrawer
            )
        },
        content = {
            Column(modifier = Modifier.fillMaxSize()) {
//                ModalDrawerTopAppBar(openDrawer)
                ModalContent(openDrawer)
            }
        }
    )
}

With ModalDrawer you set your Content as you wish if you don't want to add TopAppBar you just don't add it inside content. I commented it here to display that it's not there.

You can check repo that contains implementations here.


来源: stackexchange

问:
Vector<double> vs. Double.Vector error in F# when using BfgsSolver
I'm trying to use the BfgsSolve method from MathNet.Numerics for F# on a simple test case I wrote, but I'm running into a type mismatching issue.

Here's my code:

```<code>#r "nuget: MathNet.Numerics, 5.0.0-alpha08"
#r "nuget: MathNet.Numerics.FSharp, 5.0.0-alpha08"
open MathNet.Numerics.Optimization
open MathNet.Numerics.LinearAlgebra

let vecGuess = vector [double 1.0]

let sineFuncTest (x : Vector<float>) =
    let xval = x.[0]
    System.Math.Sin (xval ** 2.0  - 1.0 )

let sinegrad (x : Vector<float>) =
    let xval = x.[0]
    vector [2.0 * xval * (System.Math.Cos (xval ** 2.0 - 1.0))]

let result = BfgsSolver.Solve (vecGuess, sineFuncTest ,sinegrad)
</code>```

However the BfgsSolve function won't accept my vecGuess variable. The error I get is: error FS0001: The type 'Vector<double>' is not compatible with the type 'Double.Vector'.

What's the difference between the two? I've tried and failed to create a Double.Vector type.

Thanks.

答:
It will compile and run if you create your guess like this:

open MathNet.Numerics.LinearAlgebra.Double

let vecGuess = DenseVector [|1.0|]
```

I don't know if the answer is correct, though. See this SO question for a similar example.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to use the BfgsSolve method from MathNet.Numerics for F# on a simple test case I wrote, but I'm running into a type mismatching issue.

Here's my code:

#r "nuget: MathNet.Numerics, 5.0.0-alpha08"
#r "nuget: MathNet.Numerics.FSharp, 5.0.0-alpha08"
open MathNet.Numerics.Optimization
open MathNet.Numerics.LinearAlgebra

let vecGuess = vector [double 1.0]

let sineFuncTest (x : Vector<float>) =
    let xval = x.[0]
    System.Math.Sin (xval ** 2.0  - 1.0 )

let sinegrad (x : Vector<float>) =
    let xval = x.[0]
    vector [2.0 * xval * (System.Math.Cos (xval ** 2.0 - 1.0))]

let result = BfgsSolver.Solve (vecGuess, sineFuncTest ,sinegrad)

However the BfgsSolve function won't accept my vecGuess variable. The error I get is: error FS0001: The type 'Vector<double>' is not compatible with the type 'Double.Vector'.

What's the difference between the two? I've tried and failed to create a Double.Vector type.

Thanks.

Body:
It will compile and run if you create your guess like this:

open MathNet.Numerics.LinearAlgebra.Double

let vecGuess = DenseVector [|1.0|]

I don't know if the answer is correct, though. See this SO question for a similar example.


问:
I have question regarding SQL and phpmyadmin queries
I have two table in my database first is shop_details and second one is shopOwner_login

in shop_details table there is column named

```<code>ShopOwner_email
Shop_Pass
</code>```

and same in shopOwner_login table there is

```<code>ShopOwner_Id,
ShopOwner_email,
Shop_Pass
</code>```

Now i want to make a form in which if user enter data in shop details table like shopowner Email and its password it will store on those two table automatically goes

Can i do this if yes please help me for it i also tried foreign key i am so confused with foreign key because i am new to php and MySql please help me.

答: So,d query need to fetch the data looks like - SELECT a.ShopOwner_email Shop_Pass  as EmailId,a.Shop_Pass as Password FROM shop_details as a left join shopOwner_login as b on b.ShopOwner_Id = a.ShopOwner_Id

Body:
I have two table in my database first is shop_details and second one is shopOwner_login

in shop_details table there is column named

ShopOwner_email
Shop_Pass

and same in shopOwner_login table there is

ShopOwner_Id,
ShopOwner_email,
Shop_Pass

Now i want to make a form in which if user enter data in shop details table like shopowner Email and its password it will store on those two table automatically goes

Can i do this if yes please help me for it i also tried foreign key i am so confused with foreign key because i am new to php and MySql please help me.


问:
How To Print String representation of Color in Java
I have an array of colours of size n. In my program, the number of teams is always <= n, and I need to assign each team a unique color. This is my color array:

```<code>private static Color[] TEAM_COLORS = {Color.BLUE, Color.RED, Color.CYAN, Color.GREEN, Color.ORANGE, Color.PINK};
</code>```

When I print information about the players in the console, I want to print what color is associated with them. When I print the color, I get

```<code>java.awt.Color[r=...,g=...,b=...].
</code>```

I understand that this is how Java prints colours. I was wondering if there was a way to instead print BLUE, RED, etc. (so the pre-defined color string).

答:
```<code>  public static String colorToString(Color c) {
    if (c == null)  return "NullColor";
    for (var f : Color.class.getFields()) {
      if (f.getType() != Color.class)  continue;
      try {
        if (c.equals(f.get(null)))  return f.getName().toLowerCase();
      } catch (java.lang.IllegalAccessException e) {
        // Ignore. https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/reflect/Field.html#get(java.lang.Object)
      }
    }
    return c.toString();
  }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an array of colours of size n. In my program, the number of teams is always <= n, and I need to assign each team a unique color. This is my color array:

private static Color[] TEAM_COLORS = {Color.BLUE, Color.RED, Color.CYAN, Color.GREEN, Color.ORANGE, Color.PINK};

When I print information about the players in the console, I want to print what color is associated with them. When I print the color, I get

java.awt.Color[r=...,g=...,b=...].

I understand that this is how Java prints colours. I was wondering if there was a way to instead print BLUE, RED, etc. (so the pre-defined color string).


问:
Programmatically generate Django models for legacy databases
I'm trying to find out if there is a way to programmatically generate Django models for legacy databases. So given a list of legacy tables, create a model for each one. Here is an example of what I mean

```<code>class Person_001(models.Model):
    id = models.IntegerField(primary_key=True)
    huge_dataset = models.CharField(max_length=70)
    class Meta:
       managed = False
       db_table = 'person_001'
</code>```

So for example, create this model for person_001, person_002 etc...

I realize there may be a more efficient way of storing this data and I am opened to suggestions, but the data has been stored this way because huge_dataset is, well, huge.

答:
I think the documentation will help you tremendously here Django Docs

from the docs --
Auto-generate the models¶

Django comes with a utility called inspectdb that can create models by introspecting an existing database. You can view the output by running this command:

```<code>$ python manage.py inspectdb
</code>```

Save this as a file by using standard Unix output redirection:

```<code>$ python manage.py inspectdb > models.py
</code>```

Body:
I'm trying to find out if there is a way to programmatically generate Django models for legacy databases. So given a list of legacy tables, create a model for each one. Here is an example of what I mean

class Person_001(models.Model):
    id = models.IntegerField(primary_key=True)
    huge_dataset = models.CharField(max_length=70)
    class Meta:
       managed = False
       db_table = 'person_001'

So for example, create this model for person_001, person_002 etc...

I realize there may be a more efficient way of storing this data and I am opened to suggestions, but the data has been stored this way because huge_dataset is, well, huge.

Body:
I think the documentation will help you tremendously here Django Docs

from the docs --
Auto-generate the models¶

Django comes with a utility called inspectdb that can create models by introspecting an existing database. You can view the output by running this command:

$ python manage.py inspectdb

Save this as a file by using standard Unix output redirection:

$ python manage.py inspectdb > models.py


问:
Is it possible to write a dataframe into 2 files of different type?
We can use following api to write dataframe into local files.

```<code>df.write.parquet(path)
df.write.json(path)
</code>```

However, Can I write into a parquet and a json in one time without compute the dataframe twice ?
By the way , I dont want to cache the data in memory, because it's too big.

答:
We can implement an org.apache.spark.sql.execution.datasources.FileFormat to do such thing.

DuplicateOutFormat demo

```<code>/**
 * Very Dangerous Toy Code. DO NOT USE IN PRODUCTION.
 */
class DuplicateOutFormat
  extends FileFormat
    with DataSourceRegister
    with Serializable {
  override def inferSchema(sparkSession: SparkSession, options: Map[String, String], files: Seq[FileStatus]): Option[StructType] = {
    throw new UnsupportedOperationException()
  }

  override def prepareWrite(sparkSession: SparkSession,
                            job: Job,
                            options: Map[String, String],
                            dataSchema: StructType): OutputWriterFactory = {
    val format1 = options("format1")
    val format2 = options("format2")
    val format1Instance = DataSource.lookupDataSource(format1, sparkSession.sessionState.conf)
      .newInstance().asInstanceOf[FileFormat]
    val format2Instance = DataSource.lookupDataSource(format2, sparkSession.sessionState.conf)
      .newInstance().asInstanceOf[FileFormat]

    val writerFactory1 = format1Instance.prepareWrite(sparkSession, job, options, dataSchema)
    val writerFactory2 = format2Instance.prepareWrite(sparkSession, job, options, dataSchema)

    new OutputWriterFactory {
      override def getFileExtension(context: TaskAttemptContext): String = ".dup"

      override def newInstance(path: String, dataSchema: StructType, context: TaskAttemptContext): OutputWriter = {
        val path1 = path.replace(".dup", writerFactory1.getFileExtension(context))
        val path2 = path.replace(".dup", writerFactory2.getFileExtension(context))
        val writer1 = writerFactory1.newInstance(path1, dataSchema, context)
        val writer2 = writerFactory2.newInstance(path2, dataSchema, context)
        new OutputWriter {
          override def write(row: InternalRow): Unit = {
            writer1.write(row)
            writer2.write(row)
          }

          override def close(): Unit = {
            writer1.close()
            writer2.close()
          }
        }
      }
    }
  }

  override def shortName(): String = "dup"
}

</code>```

SPI

we should make a SPI file /META-INF/services/org.apache.spark.sql.sources.DataSourceRegister, content:
com.github.sparkdemo.DuplicateOutFormat.

demo usage

```<code>class DuplicateOutFormatTest extends FunSuite {
  val spark = SparkSession.builder()
    .master("local")
    .getOrCreate()
  val sc = spark.sparkContext

  import spark.implicits._

  test("testDuplicateWrite") {
    val data = Array(
      ("k1", "fa", "20210901", 16),
      ("k2", null, "20210902", 15),
      ("k3", "df", "20210903", 14),
      ("k4", null, "20210904", 13)
    )
    val tempDir = System.getProperty("java.io.tmpdir") + "spark-dup-test" + System.nanoTime()
    val df = sc.parallelize(data).toDF("k", "col2", "day", "col4")
    df.write
      .option("format1", "csv")
      .option("format2", "orc")
      .format("dup").save(tempDir)
    df.show(1000, false)
  }

}
</code>```

WARNING

Spark SQL couple some sth in DataFrameWriter#saveToV1Source and other source code, that we can't change. This custom DuplicateOutFormat is just for demo, lacking of test. Full demo in github.

Body:
We can use following api to write dataframe into local files.

df.write.parquet(path)
df.write.json(path)

However, Can I write into a parquet and a json in one time without compute the dataframe twice ?
By the way , I dont want to cache the data in memory, because it's too big.

Body:
We can implement an org.apache.spark.sql.execution.datasources.FileFormat to do such thing.

DuplicateOutFormat demo

/**
 * Very Dangerous Toy Code. DO NOT USE IN PRODUCTION.
 */
class DuplicateOutFormat
  extends FileFormat
    with DataSourceRegister
    with Serializable {
  override def inferSchema(sparkSession: SparkSession, options: Map[String, String], files: Seq[FileStatus]): Option[StructType] = {
    throw new UnsupportedOperationException()
  }

  override def prepareWrite(sparkSession: SparkSession,
                            job: Job,
                            options: Map[String, String],
                            dataSchema: StructType): OutputWriterFactory = {
    val format1 = options("format1")
    val format2 = options("format2")
    val format1Instance = DataSource.lookupDataSource(format1, sparkSession.sessionState.conf)
      .newInstance().asInstanceOf[FileFormat]
    val format2Instance = DataSource.lookupDataSource(format2, sparkSession.sessionState.conf)
      .newInstance().asInstanceOf[FileFormat]

    val writerFactory1 = format1Instance.prepareWrite(sparkSession, job, options, dataSchema)
    val writerFactory2 = format2Instance.prepareWrite(sparkSession, job, options, dataSchema)

    new OutputWriterFactory {
      override def getFileExtension(context: TaskAttemptContext): String = ".dup"

      override def newInstance(path: String, dataSchema: StructType, context: TaskAttemptContext): OutputWriter = {
        val path1 = path.replace(".dup", writerFactory1.getFileExtension(context))
        val path2 = path.replace(".dup", writerFactory2.getFileExtension(context))
        val writer1 = writerFactory1.newInstance(path1, dataSchema, context)
        val writer2 = writerFactory2.newInstance(path2, dataSchema, context)
        new OutputWriter {
          override def write(row: InternalRow): Unit = {
            writer1.write(row)
            writer2.write(row)
          }

          override def close(): Unit = {
            writer1.close()
            writer2.close()
          }
        }
      }
    }
  }

  override def shortName(): String = "dup"
}

SPI

we should make a SPI file /META-INF/services/org.apache.spark.sql.sources.DataSourceRegister, content:
com.github.sparkdemo.DuplicateOutFormat.

demo usage

class DuplicateOutFormatTest extends FunSuite {
  val spark = SparkSession.builder()
    .master("local")
    .getOrCreate()
  val sc = spark.sparkContext

  import spark.implicits._

  test("testDuplicateWrite") {
    val data = Array(
      ("k1", "fa", "20210901", 16),
      ("k2", null, "20210902", 15),
      ("k3", "df", "20210903", 14),
      ("k4", null, "20210904", 13)
    )
    val tempDir = System.getProperty("java.io.tmpdir") + "spark-dup-test" + System.nanoTime()
    val df = sc.parallelize(data).toDF("k", "col2", "day", "col4")
    df.write
      .option("format1", "csv")
      .option("format2", "orc")
      .format("dup").save(tempDir)
    df.show(1000, false)
  }

}

WARNING

Spark SQL couple some sth in DataFrameWriter#saveToV1Source and other source code, that we can't change. This custom DuplicateOutFormat is just for demo, lacking of test. Full demo in github.


问:
How to Transform X and Y Coordinates to Left and Right Motor Movement
I am trying to implement an EKF Slam to a robot using python. The robot returns an estimate of its current x and y position and an angle (the direction the robot is facing). For my slam however I need this to be left and right motor movements which can be understood as the way a tank is driving: One side is moving more than the other which results in a turning motion.

Is there a formula to calculate l and r from x, y, theta?

答:
This is usually modeled as a differential drive robot. Unfortunately,  there isn't an equation directly relating x, y, and theta to wheel angular excursion (e.g. encoder position) L and R. However,  there is a velocity based relationship,  which can be seen here https://www.mathworks.com/help/robotics/ug/mobile-robot-kinematics-equations.html.

The system is nonholonomic,  which makes designing an observer harder,  but you can use local linear approximations to some degree.


问:
A way to convert a filtered KStream from Kafka into an array in Java
Is there a way to convert a filtered KStream into an array just as java streams-api has the toArray()-method.

I tried by:

```<code>builder.filter().foreach({ list.add(element);});
</code>```

That did not work at all and I always get an empty array while printing the content.

Is it possible or should I use something else like a K-Table or KSQLDB?

答:
Sure, it's possible, but the foreach action happens in a separate thread than any print outside of it, and that thread will keep running... In other words, if you print the list immediately after the add method within the foreach, then it won't be empty

You'd need to terminate the stream topology and wait for it somehow to get the final list (at which point it would make more sense to use a plain Consumer that you could actually pause/stop polling)

Generally, only use a KTable / KSQL if you want to dedupe the record keys

Body:
Is there a way to convert a filtered KStream into an array just as java streams-api has the toArray()-method.

I tried by:

builder.filter().foreach({ list.add(element);});

That did not work at all and I always get an empty array while printing the content.

Is it possible or should I use something else like a K-Table or KSQLDB?


问:
Map Id's in one dataframe with the corresponding names in another dataframe
I have below 2 dataframes:

```<code>df_1:
|   | assign_to_id |
|   | ------------ |
| 0 | 1, 2         |
| 1 | 2            |
| 2 | 3,4,5        |

df_2:
|   | id          | name       |
|   | ------------| -----------|
| 0 | 1           | John       |
| 1 | 2           | Adam       |
| 2 | 3           | Max        |
| 3 | 4           | Martha     |
| 4 | 5           | Robert     |
</code>```

I want to map the Id's in the df_1 to the names in df_2 by matching their id's

```<code>final_df:
|   | assign_to_name    |
|   | ----------------- |
| 0 | John, Adam        |
| 1 | Adam              |
| 2 | Max,Martha,Robert |
</code>```

I don't know how to achieve this. Looking forward to some help.

答:
Idea is mapping column splitted by , by dictionary and then join back by ,:

```<code>d = df_2.assign(id = df_2['id'].astype(str)).set_index('id')['name'].to_dict()
f = lambda x: ','.join(d[y] for y in x.split(',') if y in d)
df_1['assign_to_name'] = df_1['assign_to_id'].replace('\s+', '', regex=True).apply(f)
print (df_1)
  assign_to_id     assign_to_name
0         1, 2          John,Adam
1            2               Adam
2        3,4,5  Max,Martha,Robert
</code>```

Body:
I have below 2 dataframes:

df_1:
|   | assign_to_id |
|   | ------------ |
| 0 | 1, 2         |
| 1 | 2            |
| 2 | 3,4,5        |

df_2:
|   | id          | name       |
|   | ------------| -----------|
| 0 | 1           | John       |
| 1 | 2           | Adam       |
| 2 | 3           | Max        |
| 3 | 4           | Martha     |
| 4 | 5           | Robert     |

I want to map the Id's in the df_1 to the names in df_2 by matching their id's

final_df:
|   | assign_to_name    |
|   | ----------------- |
| 0 | John, Adam        |
| 1 | Adam              |
| 2 | Max,Martha,Robert |

I don't know how to achieve this. Looking forward to some help.

Body:
Idea is mapping column splitted by , by dictionary and then join back by ,:

d = df_2.assign(id = df_2['id'].astype(str)).set_index('id')['name'].to_dict()
f = lambda x: ','.join(d[y] for y in x.split(',') if y in d)
df_1['assign_to_name'] = df_1['assign_to_id'].replace('\s+', '', regex=True).apply(f)
print (df_1)
  assign_to_id     assign_to_name
0         1, 2          John,Adam
1            2               Adam
2        3,4,5  Max,Martha,Robert


问:
Add dynamic icon beside  tag
I am trying with this example.

I am trying to add down arrow beside 'Show more' and up arrow beside 'Show less' (please refer the image below).

I was trying with the following code example but still no luck.

```<code>$('#nav li').each(function(i) {
$(this).append('<i class="fa' + ' ' + iconsArray[i] + '"></i>')})
</code>```

How can I add the icon beside  tag in the given example?

答:
I have managed to solve the problem by implementing few lines to HTML and to JS.

HTML

```<code><html>
  <head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <title>jQuery Read More/Less Toggle Example</title>
  </head>
  <body>...
  </body>
</html>
</code>```

JS

```<code>var moretext = "Show more <i class='fa fa-angle-down'></i>";
var lesstext = "Show less <i class='fa fa-angle-up'></i>";
</code>```

Title: Add dynamic icon beside <a> tag

Body:
I am trying with this example.

I am trying to add down arrow beside 'Show more' and up arrow beside 'Show less' (please refer the image below).

I was trying with the following code example but still no luck.

$('#nav li').each(function(i) {
$(this).append('')})

How can I add the icon beside  tag in the given example?

Body:
I have managed to solve the problem by implementing few lines to HTML and to JS.

HTML

<html>
  <head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <title>jQuery Read More/Less Toggle Example</title>
  </head>
  <body>...
  </body>
</html>

JS

var moretext = "Show more <i class='fa fa-angle-down'></i>";
var lesstext = "Show less <i class='fa fa-angle-up'></i>";


问:
extracting a list within a list in a tuple which happens to be in a pd.series
```<code>x=
[[(some text,[a]), (some text,[b]), (some text,[c]).........]]
   [[(some text,[d]), (some text,[e]), (some text,[f]).........]]
    [[(some text,[g]), (some text,[h]), (some text,[k]).........]]
    [[(some text,[i]), (some text,[x]), (some text,[y]).........]]
    [[(some text,[z]), (some text,[t]), (some text,[w]).........]]
    [[(some text,[t]), (some text,[g]), (some text,[u]).........]]

type(x)

pandas.core.series.Series
</code>```

I want to create a series that only contains the values of the list within the tuple such as those[a] or [u] or [w].

How can I extract? Thank you.

UPDATE: I realized the way I phrase the question was confusing. I changed it now. It represents my problem better. Basically, I need to extract all [a] or [u] or [w]row by row. This is tokenized text data, they are words in sentences. Sorry for the confusion.

答:
This Should Work:</p>
```<code>old = [[('a', ['b']), ('c', ['d']), ('e', ['f'])]]

def main():
    for item in old:
        for sub_item in item:
            yield sub_item[1]

for x in main():
    print(x)
</code>```

Body:
x=
[[(some text,[a]), (some text,[b]), (some text,[c]).........]]
   [[(some text,[d]), (some text,[e]), (some text,[f]).........]]
    [[(some text,[g]), (some text,[h]), (some text,[k]).........]]
    [[(some text,[i]), (some text,[x]), (some text,[y]).........]]
    [[(some text,[z]), (some text,[t]), (some text,[w]).........]]
    [[(some text,[t]), (some text,[g]), (some text,[u]).........]]

type(x)

pandas.core.series.Series

I want to create a series that only contains the values of the list within the tuple such as those[a] or [u] or [w].

How can I extract? Thank you.

UPDATE: I realized the way I phrase the question was confusing. I changed it now. It represents my problem better. Basically, I need to extract all [a] or [u] or [w]row by row. This is tokenized text data, they are words in sentences. Sorry for the confusion.

Body:
This Should Work:

old = [[('a', ['b']), ('c', ['d']), ('e', ['f'])]]

def main():
    for item in old:
        for sub_item in item:
            yield sub_item[1]

for x in main():
    print(x)


问:
Error loading psycopg2 module: DLL load failed while importing _psycopg: The specified module could not be found
raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: DLL load failed while importing _psycopg: The specified module could not be found.

i have installed letest postgres setup

psycopg2 installed

答:
```<code>pip install psycopg2
</code>```

This worked for me

Body:
pip install psycopg2

This worked for me


问:
Eliminate duplicate field combinations
I want to eliminate duplicate field1/field2 combinations in my DB. My pseudo query below:

```<code> SELECT * WHERE DISTINCT field1 AND field2
</code>```

The table with duplicates is below:

```<code>+-----+--------+--------+--------+
| id  | field1 | field2 | field3 |
+-----+--------+--------+--------+
|  1  |   A    |   B    |   Z    |
|  2  |   A    |   B    |   Q    |
|  3  |   A    |   C    |   K    |
+-----+--------+--------+--------+
</code>```

I want to eliminate rows with duplicate field1/field2 combinations. Row 2 was dropped b/c it was a duplicate of row 1.

```<code>+-----+--------+--------+--------+
| id  | field1 | field2 | field3 |
+-----+--------+--------+--------+
|  1  |   A    |   B    |   Z    |
|  3  |   A    |   C    |   K    |
+-----+--------+--------+--------+
</code>```

答:
This select will narrow your results as you want:

```<code>select id, field1, field2, field3 from testtable1 group by field1,field2;
</code>```

So this will create a new table with the duplicates eliminated:

```<code>create table testtable2 select id, field1, field2, field3 from testtable1 group by field1,field2;
</code>```

Replace testtable1 with the appropriate name of your existing table.

Title: Eliminate duplicate field combinations

Body:
I want to eliminate duplicate field1/field2 combinations in my DB. My pseudo query below:

 SELECT * WHERE DISTINCT field1 AND field2

The table with duplicates is below:

+-----+--------+--------+--------+
| id  | field1 | field2 | field3 |
+-----+--------+--------+--------+
|  1  |   A    |   B    |   Z    |
|  2  |   A    |   B    |   Q    |
|  3  |   A    |   C    |   K    |
+-----+--------+--------+--------+

I want to eliminate rows with duplicate field1/field2 combinations. Row 2 was dropped b/c it was a duplicate of row 1.

+-----+--------+--------+--------+
| id  | field1 | field2 | field3 |
+-----+--------+--------+--------+
|  1  |   A    |   B    |   Z    |
|  3  |   A    |   C    |   K    |
+-----+--------+--------+--------+

Body:
This select will narrow your results as you want:

select id, field1, field2, field3 from testtable1 group by field1,field2;

So this will create a new table with the duplicates eliminated:

create table testtable2 select id, field1, field2, field3 from testtable1 group by field1,field2;

Replace testtable1 with the appropriate name of your existing table.


问:
Why is the first method working but second isn't?
First Method:

```<code>const getWeatherIcon = (iconParameter) => {
   const icon = `https://openweathermap.org/img/wn/${iconParameter}@2x.png`
   return <img src={icon} alt={iconParameter} />
  }
</code>```

```<code><div className="weathericon">
       {getWeatherIcon(weather.weather[0].icon)} //Ex: weather.weather[0].icon=50n
</div>
</code>```

Second Method:

```<code>const getWeatherIcon = (iconParameter) => {
    const icon = `assets/weather/${iconParameter}.svg`
    return <img src={icon} alt={iconParameter} />
  }
</code>```

```<code><div className="weathericon">
     {getWeatherIcon(weather.weather[0].main)} //Ex: weather.weather[0].main=Haze
</div>
</code>```

Here Is My Project Directory

```<code>src
│   App.js
│   index.css
│   index.js
│
└───assets
    └───weather
    |  |    Haze.svg
    │  |    Clear.svg
    │  |    Rain.svg
    |
    └───bg
        |   file111.png
        |   file112.png
</code>```

Ignore following

It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.

答:
This Worked!!

```<code>const getWeatherIcon = (iconParameter) => {
    const icon = `${iconParameter}.svg`
    return < img src={icon} alt={iconParameter} width='100px' />
  }
</code>```

```<code><div className="weathericon">
                  {getWeatherIcon(weather.weather[0].main)}//Haze, Clear etc.
                </div>
</code>```

File System:

```<code>src
│   App.js
│   index.css
│   index.js
│
└───assets
│   └───bg
│   |   file111.png
│   |   file112.png
│
│
public
│   Clear.svg
│   Clouds.svg
│   Rain.svg
│   Haze.svg
</code>```

Body:
First Method:

const getWeatherIcon = (iconParameter) => {
   const icon = `https://openweathermap.org/img/wn/${iconParameter}@2x.png`
   return
  }

       {getWeatherIcon(weather.weather[0].icon)} //Ex: weather.weather[0].icon=50n

Second Method:

const getWeatherIcon = (iconParameter) => {
    const icon = `assets/weather/${iconParameter}.svg`
    return
  }

     {getWeatherIcon(weather.weather[0].main)} //Ex: weather.weather[0].main=Haze

Here Is My Project Directory

src
│   App.js
│   index.css
│   index.js
│
└───assets
    └───weather
    |  |    Haze.svg
    │  |    Clear.svg
    │  |    Rain.svg
    |
    └───bg
        |   file111.png
        |   file112.png

Ignore following

It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.

Body:
This Worked!!

const getWeatherIcon = (iconParameter) => {
    const icon = `${iconParameter}.svg`
    return < img src={icon} alt={iconParameter} width='100px' />
  }

<div className="weathericon">
                  {getWeatherIcon(weather.weather[0].main)}//Haze, Clear etc.
                </div>

File System:

src
│   App.js
│   index.css
│   index.js
│
└───assets
│   └───bg
│   |   file111.png
│   |   file112.png
│
│
public
│   Clear.svg
│   Clouds.svg
│   Rain.svg
│   Haze.svg


问:
Is this code vulnerable to SQL injection attacks?
Is this code vulnerable to SQL injection attacks?</p>

```<code>$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID, comment_post_ID, comment_author, comment_author_email, comment_date_gmt, comment_approved, comment_type, comment_author_url, SUBSTRING(comment_content,1,70) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) WHERE comment_approved = '1' AND comment_type = '' AND post_password = '' ORDER BY comment_date_gmt DESC LIMIT 5";
</code>```

答:
It depends on a few things that I can't see - or am not knowledgeable enough to know from the code you've posted.
To be vulnerable to SQL injection you must be entering an unescaped string into your database. (EDIT: usually an unescaped, but user definable, string).

I cannot see anywhere in your code that you've escaped the string. PHP offers a function for this:
$string = mysql_real_escape_string($string);
And then that string should be safe to use in the database query.

So for example, don't use:

```<code>$name = $_GET['name'];
mysql_query("INSERT INTO table_name VALUES ('$name')");
</code>```

Instead use:

```<code>$name = mysql_real_escape_string($_GET['name']);
mysql_query("INSERT INTO table_name VALUES ('$name')");
</code>```

And you "should" be protected to SQL Injection providing that there are no vulnerabilities within the "mysql_real_escape_string" function.

Body:
Is this code vulnerable to SQL injection attacks?

$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID, comment_post_ID, comment_author, comment_author_email, comment_date_gmt, comment_approved, comment_type, comment_author_url, SUBSTRING(comment_content,1,70) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) WHERE comment_approved = '1' AND comment_type = '' AND post_password = '' ORDER BY comment_date_gmt DESC LIMIT 5";

Body:
It depends on a few things that I can't see - or am not knowledgeable enough to know from the code you've posted.
To be vulnerable to SQL injection you must be entering an unescaped string into your database. (EDIT: usually an unescaped, but user definable, string).

I cannot see anywhere in your code that you've escaped the string. PHP offers a function for this:
$string = mysql_real_escape_string($string);
And then that string should be safe to use in the database query.

So for example, don't use:

$name = $_GET['name'];
mysql_query("INSERT INTO table_name VALUES ('$name')");

Instead use:

$name = mysql_real_escape_string($_GET['name']);
mysql_query("INSERT INTO table_name VALUES ('$name')");

And you "should" be protected to SQL Injection providing that there are no vulnerabilities within the "mysql_real_escape_string" function.


问:
.net 6 how can I get Configuration before the app is build
I am changing my project from .net 5 to .net 6 and have experienced an issue in the program.cs file with the current error of

Cannot modify ServiceCollection after application is built

I am needing to read the configuration before the app is built but the only current way that I know of getting the configuration is after the app is built . This is part of my code:

```<code>var builder = WebApplication.CreateBuilder(args);

// Add builder.Services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddCors();

var app = builder.Build();

IConfiguration configuration = app.Configuration;

var appSettings = new AppSettings(configuration);
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
builder.Services.AddAuthentication(x => // error happens here we have already used builder.Build()
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidAudience = appSettings.Target,
                    ValidIssuer = appSettings.Target
                };
            });
</code>```

Is there a way of getting IConfiguration before we call builder.Build() ? Since I need the configuration to pass into the class AppSettings which then gets a secret key and allows me to do Authentication on JWT token .

答:
move var app = builder.Build() after authentication configuration.

the .Build() method essentially takes your configuration and gives you a WebApplication that's built upon the WebApplicationBuilder so you cannot modify the app after it's been built

Body:
I am changing my project from .net 5 to .net 6 and have experienced an issue in the program.cs file with the current error of

Cannot modify ServiceCollection after application is built

I am needing to read the configuration before the app is built but the only current way that I know of getting the configuration is after the app is built . This is part of my code:

var builder = WebApplication.CreateBuilder(args);

// Add builder.Services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddCors();

var app = builder.Build();

IConfiguration configuration = app.Configuration;

var appSettings = new AppSettings(configuration);
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
builder.Services.AddAuthentication(x => // error happens here we have already used builder.Build()
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidAudience = appSettings.Target,
                    ValidIssuer = appSettings.Target
                };
            });

Is there a way of getting IConfiguration before we call builder.Build() ? Since I need the configuration to pass into the class AppSettings which then gets a secret key and allows me to do Authentication on JWT token .


问:
TypeError: can only concatenate tuple (not "int") to tuple discord.py
i am trying to make a fish command but it always says

```<code>discord.ext.commands.errors.CommandInvokeError:
Command raised an exception:
TypeError: can only concatenate tuple (not "int") to tuple

</code>```

heres my fish code

```<code>@client.command()

async def fish(ctx):
  user = ctx.author
  users = await get_bank_data()
  amount = random.randint(1,2)
  inv = users[str(user.id)]["inv"]
  for thing in inv:
    n = thing["item"]
    if "fishingrod" in n:
      amt = thing["amount"]
      fishamount = ["fish"],["amount"]
      if amt > 0:
        await ctx.send(f"You found {amount} fish")
        fishamount += amount
      if amt < 0:
        await ctx.send("You don't have a fishing rod!")
</code>```

please help me with my problem

答:
The problem is that you declare fishamount with fishamount = ["fish"],["amount"] so you set it to a tuple which has two lists in it, which each have one string in it:

(["fish"],["amount"])
```

but the you try to use the + operator on the tuple and the int amount, which can't work since you can only add integers to integers and tuples to tuples.
You have to decide what you want to store in the variable.

Body:
i am trying to make a fish command but it always says

discord.ext.commands.errors.CommandInvokeError:
Command raised an exception:
TypeError: can only concatenate tuple (not "int") to tuple

heres my fish code

@client.command()

async def fish(ctx):
  user = ctx.author
  users = await get_bank_data()
  amount = random.randint(1,2)
  inv = users[str(user.id)]["inv"]
  for thing in inv:
    n = thing["item"]
    if "fishingrod" in n:
      amt = thing["amount"]
      fishamount = ["fish"],["amount"]
      if amt > 0:
        await ctx.send(f"You found {amount} fish")
        fishamount += amount
      if amt < 0:
        await ctx.send("You don't have a fishing rod!")

please help me with my problem

Body:
The problem is that you declare fishamount with fishamount = ["fish"],["amount"] so you set it to a tuple which has two lists in it, which each have one string in it:

(["fish"],["amount"])

but the you try to use the + operator on the tuple and the int amount, which can't work since you can only add integers to integers and tuples to tuples.
You have to decide what you want to store in the variable.


问:
Excel vba if three or more consecutive cells are blank then place value on another cell
Im looking for a solution to get the result as in the screenshot. If theres at least 3 blanks or more then change second cell from first blank on first column to "x" :

```<code>Sub findThreeEmptyCells()
Dim lastRow As Long, i As Long
Dim firstEmptyCell As Range

lastRow = Cells(Rows.Count, 5).End(xlUp).Row

For i = 10 To lastRow
If Cells(i + 1, 5).Value = "" And Cells(i + 2, 5).Value = "" Then
    Set firstEmptyCell = Cells(i + 2, 1)
    Exit For
End If
Next i

If firstEmptyCell Is Nothing Then
MsgBox ("There are no two empty cells in a row")
Exit Sub
End If

firstEmptyCell.Value = "x"

End Sub
</code>```

答:
```<code>Sub findThreeEmptyCells()
Dim lastRow As Long, i As Long
Dim firstEmptyCell As Range

lastRow = Cells(Rows.Count, 5).End(xlUp).Row ' Assuming your column A has the most data or is the row you want to check.

For i = 10 To lastRow
If Cells(i + 1, 5).Value = "" And Cells(i + 2, 5).Value = "" And Cells(i + 3, 5).Value = "" Then
    Set firstEmptyCell = Cells(i + 2, 1)
    Exit For
End If
Next i

If firstEmptyCell Is Nothing Then
MsgBox ("There are no two empty cells in a row")
Exit Sub
End If

firstEmptyCell.Value = "x"

End Sub
</code>```

Body:
Im looking for a solution to get the result as in the screenshot. If theres at least 3 blanks or more then change second cell from first blank on first column to "x" :

Sub findThreeEmptyCells()
Dim lastRow As Long, i As Long
Dim firstEmptyCell As Range

lastRow = Cells(Rows.Count, 5).End(xlUp).Row

For i = 10 To lastRow
If Cells(i + 1, 5).Value = "" And Cells(i + 2, 5).Value = "" Then
    Set firstEmptyCell = Cells(i + 2, 1)
    Exit For
End If
Next i

If firstEmptyCell Is Nothing Then
MsgBox ("There are no two empty cells in a row")
Exit Sub
End If

firstEmptyCell.Value = "x"

End Sub


问:
Ansible copy large file in async mode
When trying to upload a file with a size of 1GB to a remote server, It shows following error:

"async is not supported for this task."

Here I'am using async with copy module

Here is my ansible playbook

```<code>- hosts: myhost
  tasks:
    - name: 'copy large file'
      copy:
        src: "large_file"
        dest: "/home/user"
      async:
      poll: 0
      register: copy_sleeper

    - name: 'check on async task'
      async_status:
        jid: "{{ copy_sleeper.ansible_job_id }}"
      register: job_result
      until: job_result.finished
      retries: 5
</code>```

Is there any solutions in this case?

答:
I found that scp and rsync were extremely similar in moving a large 5GB iso to the remote system.  I timed them both at around the 110 - 115 second mark.

I ended up using the following script which also avoids some permissions issues common to rsync

```
- name: async_win_vm_files_migration
  # using ansible user and key from the control system to push rsync copy
  command: >
    rsync -aAXvP --no-g --omit-dir-times --no-perms -e "ssh -p 925 -i /home/ansible/.ssh/id_ed25519"
    --keep-dirlinks
    --exclude={"/dev/*","/proc/*","/sys/*","/tmp/*","/run/*","/mnt/*","/.git/*","/.pyc/*","/.svn/*","/.gvfs/*","/.cache/*","/lost+found"}
    "{{ files_path }}/async_large_files/windows_vms/" ansible@{{ host_ansible_ip }}:/SM/data-drive/sm_virt_machines/
  delegate_to: 127.0.0.1
  become: yes # become root
  # how many seconds ansible should wait between checking to see if done
  # if you know your entire playbook is going to take 2 minutes, you may as well make this close to that.
  # there is no 'too small' number but if you put in more seconds than the entire playbook runs, this will spawn an error
  async: 600 # 5 minutes
  register: sm_async_win_vm_files
```

Title: Ansible copy large file in async mode

Body:
When trying to upload a file with a size of 1GB to a remote server, It shows following error:

"async is not supported for this task."

Here I'am using async with copy module

Here is my ansible playbook

- hosts: myhost
  tasks:
    - name: 'copy large file'
      copy:
        src: "large_file"
        dest: "/home/user"
      async:
      poll: 0
      register: copy_sleeper

    - name: 'check on async task'
      async_status:
        jid: "{{ copy_sleeper.ansible_job_id }}"
      register: job_result
      until: job_result.finished
      retries: 5

Is there any solutions in this case?

Body:
I found that scp and rsync were extremely similar in moving a large 5GB iso to the remote system.  I timed them both at around the 110 - 115 second mark.

I ended up using the following script which also avoids some permissions issues common to rsync

- name: async_win_vm_files_migration
  # using ansible user and key from the control system to push rsync copy
  command: >
    rsync -aAXvP --no-g --omit-dir-times --no-perms -e "ssh -p 925 -i /home/ansible/.ssh/id_ed25519"
    --keep-dirlinks
    --exclude={"/dev/*","/proc/*","/sys/*","/tmp/*","/run/*","/mnt/*","/.git/*","/.pyc/*","/.svn/*","/.gvfs/*","/.cache/*","/lost+found"}
    "{{ files_path }}/async_large_files/windows_vms/" ansible@{{ host_ansible_ip }}:/SM/data-drive/sm_virt_machines/
  delegate_to: 127.0.0.1
  become: yes # become root
  # how many seconds ansible should wait between checking to see if done
  # if you know your entire playbook is going to take 2 minutes, you may as well make this close to that.
  # there is no 'too small' number but if you put in more seconds than the entire playbook runs, this will spawn an error
  async: 600 # 5 minutes
  register: sm_async_win_vm_files


问:
Julia: How do you add/subtract distribution functions?
As part of a mini-project where I am numerically solving a linear differential equation, I have to subtract a probability distribution from another distribution. Is there a way to do this in Julia? When I try:

```<code>a = Chi(3) - Uniform(0,1)
</code>```

There is no method set up for this:

```<code>MethodError: no method matching -(::Chi{Float64}, ::Uniform{Float64})
Closest candidates are:
  -(::UnivariateDistribution, ::Real) at C:\Users\Acer\.julia\packages\Distributions\Fl5RM\src\univariate\locationscale.jl:139
  -(::ChainRulesCore.AbstractThunk, ::Any) at C:\Users\Acer\.julia\packages\ChainRulesCore\sHMAp\src\tangent_types\thunks.jl:30
  -(::ChainRulesCore.ZeroTangent, ::Any) at C:\Users\Acer\.julia\packages\ChainRulesCore\sHMAp\src\tangent_arithmetic.jl:101
  ...
</code>```

答:
As I have said the convolve function is defined in Distributions.jl. Here is a documentation: https://juliastats.org/Distributions.jl/stable/convolution/. However this is not enough for your purposes as commented above.

Let me help you deriving the PDF of Chi(3)-Uniform(0,1) assuming they are independent.

Let X be the distribution you want, then we do Chi(3)+Uniform(-1,0) have its PDF as: f(x) = C(z+1)-C(x). Where C is CDF of Chi(3) distribution.

So there is a closed form for PDF of your distribution in terms of CDF of Chi(3).

(I am doing the computations in my head so it would be good if you double checked them)

Body:
As part of a mini-project where I am numerically solving a linear differential equation, I have to subtract a probability distribution from another distribution. Is there a way to do this in Julia? When I try:

a = Chi(3) - Uniform(0,1)

There is no method set up for this:

MethodError: no method matching -(::Chi{Float64}, ::Uniform{Float64})
Closest candidates are:
  -(::UnivariateDistribution, ::Real) at C:\Users\Acer\.julia\packages\Distributions\Fl5RM\src\univariate\locationscale.jl:139
  -(::ChainRulesCore.AbstractThunk, ::Any) at C:\Users\Acer\.julia\packages\ChainRulesCore\sHMAp\src\tangent_types\thunks.jl:30
  -(::ChainRulesCore.ZeroTangent, ::Any) at C:\Users\Acer\.julia\packages\ChainRulesCore\sHMAp\src\tangent_arithmetic.jl:101
  ...


问:
Scalar Variables from Perl to Python?
I am translating a program from perl to python and I really don't know how to translate a scalar variable to python. My problem is that I want to call the first value that comes in based on all the scalar variables used in the code, a scalar variable when mentioned it refers to the value assigned to it.

the specific area was

```<code>my $min = $_[0];
my $max = $_[1];
</code>```

So these two variables were assigned a value before hand, now what I am trying to do is call my min and let it be the first value that comes, then I want my max to be called as the second value that comes in. Basically, trying to gather the info that was generated to min and max and now bring it to here. Do not understand how to do this in python.

The thing is that I have 3-5 different values assigned to min and also to max, I dont know how to bring in the value.

i am the one who put the question, but I logged in as i think a temporary user and it got deleted. Thanks!

答:
I'm not exactly sure what you are asking for, but just FYI Python does not attach types to the names in the script. The type is the object that the name refers to. So there is not distinction of "scalar" variable or "list context", or anything like that.

So it looks like you have a list. you can do:

```<code>mymin = mylist[0]
mymax = mylist[1]
</code>```

Assuming mylist holds reference to a list object (in Python every name is a reference).

OwnerDisplayName: MIT

Title: Scalar Variables from Perl to Python?

Body:
I am translating a program from perl to python and I really don't know how to translate a scalar variable to python. My problem is that I want to call the first value that comes in based on all the scalar variables used in the code, a scalar variable when mentioned it refers to the value assigned to it.

the specific area was

my $min = $_[0];
my $max = $_[1];

So these two variables were assigned a value before hand, now what I am trying to do is call my min and let it be the first value that comes, then I want my max to be called as the second value that comes in. Basically, trying to gather the info that was generated to min and max and now bring it to here. Do not understand how to do this in python.

The thing is that I have 3-5 different values assigned to min and also to max, I dont know how to bring in the value.

i am the one who put the question, but I logged in as i think a temporary user and it got deleted. Thanks!

Body:
I'm not exactly sure what you are asking for, but just FYI Python does not attach types to the names in the script. The type is the object that the name refers to. So there is not distinction of "scalar" variable or "list context", or anything like that.

So it looks like you have a list. you can do:

mymin = mylist[0]
mymax = mylist[1]

Assuming mylist holds reference to a list object (in Python every name is a reference).


问:
Function to check for NULL and concatenating the strings
I have a SQL statement that concatenates First Name and Last Name of the person. I use the following SQL statement.

```<code>ISNULL(FullName.FirstName, '') + ' ' + ISNULL(FullName.LastName, '')
</code>```

What I need is to change this to add the FirstName and LastName only if they are not both NULL. If one of them is not NULL, use that value.

Examples:

FirstName and LastName are NULL -> NULL

FirstName is John and LastName is NULL -> John

FirstName is NULL and LastName is Doe -> Doe

-> indicates the result

答:
Use CONCAT() to concatenate without any NULL issues

TRIM() to remove any spaces for when one or both fields are missing

NULLIF() to replace '' with NULL if first and last name are both
missing

SQL Server 2017+ Solution

```<code>DROP TABLE IF EXISTS #emp
CREATE TABLE #emp (ID INT IDENTITY(1,1), FirstName VARCHAR(25), LastName VARCHAR(25));

INSERT INTO #emp
VALUES(null,null)
,('John',null)
,('Doe',null)
,('John', 'Doe');

SELECT FullName = NULLIF(TRIM(CONCAT(FirstName,' ',LastName)),'')
    ,*
FROM #emp
</code>```

Body:
I have a SQL statement that concatenates First Name and Last Name of the person. I use the following SQL statement.

ISNULL(FullName.FirstName, '') + ' ' + ISNULL(FullName.LastName, '')

What I need is to change this to add the FirstName and LastName only if they are not both NULL. If one of them is not NULL, use that value.

Examples:

FirstName and LastName are NULL -> NULL

FirstName is John and LastName is NULL -> John

FirstName is NULL and LastName is Doe -> Doe

-> indicates the result

Body:
Use CONCAT() to concatenate without any NULL issues

TRIM() to remove any spaces for when one or both fields are missing

NULLIF() to replace '' with NULL if first and last name are both
missing

SQL Server 2017+ Solution

DROP TABLE IF EXISTS #emp
CREATE TABLE #emp (ID INT IDENTITY(1,1), FirstName VARCHAR(25), LastName VARCHAR(25));

INSERT INTO #emp
VALUES(null,null)
,('John',null)
,('Doe',null)
,('John', 'Doe');

SELECT FullName = NULLIF(TRIM(CONCAT(FirstName,' ',LastName)),'')
    ,*
FROM #emp


问:
Object value becomes undefined on button click in React
I have this problem that when I render first component based on 'switch' case, I get the object values (string) displayed on the screen, but when I 'switch' to another component on 'button' click, the object values (string) disappears in all the components. the values comes from a single object and are passed as props to the components. I have checked the react components on the browser and found the object values becomes undefined whenever I made the first click to move to another component. I could not figure out why this is happening. I need help. Thank you.

This is the code:

This is parent component

```<code>import React, {useState} from 'react';
import OneToFive from './questionOneToFive';
import SixToTen from './questionSixToTen';

const Signup = () => {

const [fields, setFields] = useState({
    step: 1,
    qOne: 'What is the name of your father?',
    qTwo: 'What is the first state you visited in Nigeria?',
    qThree: 'What type of phone are you using?',
});

const { step } = fields;
const { qOne, qTwo} = fields;
const values = { qOne, qTwo}

    const nextStep = () => {
    const { step } = fields;
    setFields( {step : step + 1} );

}

 const prevStep = () => {
    const { step } = fields;
    setFields( {step: step - 1} );

}

switch(step) {
    case 1:
        return (
            <OneToFive
            nextStep={nextStep}
            values={values}
            />
        );
    case 2:
        return (
            <SixToTen
            nextStep={nextStep}
            prevStep={prevStep}
            values={values}
            />
        );
    case 3:
        return <h1>Eleven to Fifteen</h1>
    case 4:
        return <h1>Sixteen to Twenty</h1>
    default:
        return <h1>Error page not found</h1>
}

}

export default Signup;
</code>```

This is the first component.

```<code>const OneToFive = ({nextStep, values}) => {

const contee = (e) => {
    e.preventDefault();
    nextStep();
}

return (
    <div className="bg-green-200 mx-auto my-10 w-2/4 p-10 shadow-lg shadow-green-500 rounded-lg">
        <h3><span className="font-bold">Q 1:</span> {values.qOne}</h3>
        <div className="my-3">
            <input type="radio" name="mathQOne" value="abubakar"/>
            <label htmlFor=""> abubakar</label>
            <br />
            <input type="radio" name="mathQOne" value="usman"/>
            <label htmlFor=""> usman</label>
            <br />
            <input type="radio" name="mathQOne" value="shehu"/>
            <label htmlFor=""> shehu</label>
            <br />
            <input type="radio" name="mathQOne" value="bello"/>
            <label htmlFor=""> bello</label>
        </div>
}
export default OneToFive;
</code>```

This is the second component

```<code>const SixToTen = ({nextStep, prevStep, values}) => {

 const contee = (e) => {
    e.preventDefault();
    nextStep();
}

const prev = (e) => {
    e.preventDefault();
    prevStep();
}

return (
 <h3><span className="font-bold">Q 2:</span> {values.qTwo}</h3>
        <div className="my-3">
            <input type="radio" name="mathQTwo" value="abuja"/>
            <label htmlFor=""> abuja</label>
            <br />
            <input type="radio" name="mathQTwo" value="kaduna"/>
            <label htmlFor=""> kaduna</label>
            <br />
            <input type="radio" name="mathQTwo" value="maiduguri"/>
            <label htmlFor=""> maiduguri</label>
            <br />
            <input type="radio" name="mathQTwo" value="kano"/>
            <label htmlFor=""> kano</label>
        </div>

   <div className="flex flex-row gap-3">
        <div className="flex flex-1 justify-start">
             <button className="bg-green-500 text-white p-3 mt-10 rounded-lg shadow-sm shadow-pink-600" onClick={prev}>Previous</button>
        </div>

       <div className="flex flex-1 justify-end">
             <button className="bg-green-500 text-white p-3 mt-10 rounded-lg shadow-sm shadow-pink-600" onClick={contee}>Next</button>
       </div>

    </div>

    </div>

)
}

export default SixToTen;
</code>```

答:
Your nextStep and prevStep functions are both replacing your original fields state variable with an object with nothing but step.

In other words, you start off with fields set to:

```<code>{
    step: 1,
    qOne: 'What is the name of your father?',
    qTwo: 'What is the first state you visited in Nigeria?',
    qThree: 'What type of phone are you using?',
}
</code>```

Then, when you call nextStep, it does setFields({step: step + 1}), so you end up with fields being:

```<code>{
  step: 2
}
</code>```

I think what you want here is to change the step, but leave the other properties unchanged. Try these functions instead:

```<code>const nextStep = () => {
    const { step } = fields;
    setFields( {...fields, step: step + 1} );
};

const prevStep = () => {
    const { step } = fields;
    setFields( {...fields, step: step - 1} );
};
</code>```

Using the spread operator, all properties from the fields are copied to the new value, and then the step is incremented/decremented.

You could achieve the same without the spread operator like this:

```<code>const nextStep = () => {
    const { step, qOne, qTwo, qThree } = fields;
    setFields( {step: step + 1, qOne, qTwo, qThree} );
};

const prevStep = () => {
    const { step, qOne, qTwo, qThree } = fields;
    setFields( {step: step - 1, qOne, qTwo, qThree} );
};
</code>```

This is perhaps easier to understand, but it's also more verbose, especially if you ever have more than three questions!

Body:
I have this problem that when I render first component based on 'switch' case, I get the object values (string) displayed on the screen, but when I 'switch' to another component on 'button' click, the object values (string) disappears in all the components. the values comes from a single object and are passed as props to the components. I have checked the react components on the browser and found the object values becomes undefined whenever I made the first click to move to another component. I could not figure out why this is happening. I need help. Thank you.

This is the code:

This is parent component

import React, {useState} from 'react';
import OneToFive from './questionOneToFive';
import SixToTen from './questionSixToTen';

const Signup = () => {

const [fields, setFields] = useState({
    step: 1,
    qOne: 'What is the name of your father?',
    qTwo: 'What is the first state you visited in Nigeria?',
    qThree: 'What type of phone are you using?',
});

const { step } = fields;
const { qOne, qTwo} = fields;
const values = { qOne, qTwo}

    const nextStep = () => {
    const { step } = fields;
    setFields( {step : step + 1} );

}

 const prevStep = () => {
    const { step } = fields;
    setFields( {step: step - 1} );

}

switch(step) {
    case 1:
        return (
            <OneToFive
            nextStep={nextStep}
            values={values}
            />
        );
    case 2:
        return (
            <SixToTen
            nextStep={nextStep}
            prevStep={prevStep}
            values={values}
            />
        );
    case 3:
        return
Eleven to Fifteen

    case 4:
        return
Sixteen to Twenty

    default:
        return
Error page not found

}

}

export default Signup;

This is the first component.

const OneToFive = ({nextStep, values}) => {

const contee = (e) => {
    e.preventDefault();
    nextStep();
}

return (

Q 1: {values.qOne}

            <input type="radio" name="mathQOne" value="abubakar"/>
             abubakar

            <input type="radio" name="mathQOne" value="usman"/>
             usman

            <input type="radio" name="mathQOne" value="shehu"/>
             shehu

            <input type="radio" name="mathQOne" value="bello"/>
             bello

}
export default OneToFive;

This is the second component

const SixToTen = ({nextStep, prevStep, values}) => {

 const contee = (e) => {
    e.preventDefault();
    nextStep();
}

const prev = (e) => {
    e.preventDefault();
    prevStep();
}

return (

Q 2: {values.qTwo}

            <input type="radio" name="mathQTwo" value="abuja"/>
             abuja

            <input type="radio" name="mathQTwo" value="kaduna"/>
             kaduna

            <input type="radio" name="mathQTwo" value="maiduguri"/>
             maiduguri

            <input type="radio" name="mathQTwo" value="kano"/>
             kano

             <button className="bg-green-500 text-white p-3 mt-10 rounded-lg shadow-sm shadow-pink-600" onClick={prev}>Previous</button>

             <button className="bg-green-500 text-white p-3 mt-10 rounded-lg shadow-sm shadow-pink-600" onClick={contee}>Next</button>

)
}

export default SixToTen;

Body:
Your nextStep and prevStep functions are both replacing your original fields state variable with an object with nothing but step.

In other words, you start off with fields set to:

{
    step: 1,
    qOne: 'What is the name of your father?',
    qTwo: 'What is the first state you visited in Nigeria?',
    qThree: 'What type of phone are you using?',
}

Then, when you call nextStep, it does setFields({step: step + 1}), so you end up with fields being:

{
  step: 2
}

I think what you want here is to change the step, but leave the other properties unchanged. Try these functions instead:

const nextStep = () => {
    const { step } = fields;
    setFields( {...fields, step: step + 1} );
};

const prevStep = () => {
    const { step } = fields;
    setFields( {...fields, step: step - 1} );
};

Using the spread operator, all properties from the fields are copied to the new value, and then the step is incremented/decremented.

You could achieve the same without the spread operator like this:

const nextStep = () => {
    const { step, qOne, qTwo, qThree } = fields;
    setFields( {step: step + 1, qOne, qTwo, qThree} );
};

const prevStep = () => {
    const { step, qOne, qTwo, qThree } = fields;
    setFields( {step: step - 1, qOne, qTwo, qThree} );
};

This is perhaps easier to understand, but it's also more verbose, especially if you ever have more than three questions!


问:
Not able to attach google form in my website when using helmet
I am not able to attach the google form to my website while using helmet js. What could be the code to allow it?

iframe

```<code><iframe src="https://docs.google.com/forms/d/e/..." width="600" height="850px" class="col-12" frameborder="0" marginheight="0" marginwidth="0">Loading…</iframe>
</code>```

Helmet Middleware

```<code>app.use(helmet({
    contentSecurityPolicy: {
        directives: {
            frameSrc: ["'self'", "https://docs.google.com/forms"],
        }
    },
}));
</code>```

Error on Client-Side

Refused to frame 'https://docs.google.com/forms' because it violates
the following Content Security Policy directive: "default-src 'self'".
Note that 'frame-src' was not explicitly set, so 'default-src' is used
as a fallback.

答:
Finally, I got the solution.

We need to set COEP (Cross-Origin-Embedder-Policy) response header if we want to embed any link with the website.

```<code>app.use(helmet({
    contentSecurityPolicy: {
        directives: {
            "frame-ancestors": ["'self'", "*.google.com/"],
            frameSrc: ["'self'", "*.google.com/"],
            childSrc: ["'self'", "*.google.com/"]
        }
    },
    // crossOriginEmbedderPolicy: false
}));

app.use((req, res, next) => {
    res.header("Cross-Origin-Embedder-Policy", "cross-origin")
    next()
})
</code>```

Body:
I am not able to attach the google form to my website while using helmet js. What could be the code to allow it?

iframe

Loading…

Helmet Middleware

app.use(helmet({
    contentSecurityPolicy: {
        directives: {
            frameSrc: ["'self'", "https://docs.google.com/forms"],
        }
    },
}));

Error on Client-Side

Refused to frame 'https://docs.google.com/forms' because it violates
the following Content Security Policy directive: "default-src 'self'".
Note that 'frame-src' was not explicitly set, so 'default-src' is used
as a fallback.

Body:
Finally, I got the solution.

We need to set COEP (Cross-Origin-Embedder-Policy) response header if we want to embed any link with the website.

app.use(helmet({
    contentSecurityPolicy: {
        directives: {
            "frame-ancestors": ["'self'", "*.google.com/"],
            frameSrc: ["'self'", "*.google.com/"],
            childSrc: ["'self'", "*.google.com/"]
        }
    },
    // crossOriginEmbedderPolicy: false
}));

app.use((req, res, next) => {
    res.header("Cross-Origin-Embedder-Policy", "cross-origin")
    next()
})


问:
When I add AngularFireAuth to my constructor the site doesn't show up
The title says it all.

This is my code with Angular Fire Auth.

Nothing shows up.

```<code>export class HomeComponent implements OnInit {

  constructor(public afAuth: AngularFireAuth) {
  }

  ngOnInit(): void {
  }

}
</code>```

And when i remove it

```<code>export class HomeComponent implements OnInit {

  constructor() {
  }

  ngOnInit(): void {
  }
}
</code>```

it works

答:
import firebase from "firebase/compat";

It was the error in this import. It should've been.

import firebase from "firebase/compat/app";

Body:
The title says it all.

This is my code with Angular Fire Auth.

Nothing shows up.

export class HomeComponent implements OnInit {

  constructor(public afAuth: AngularFireAuth) {
  }

  ngOnInit(): void {
  }

}

And when i remove it

export class HomeComponent implements OnInit {

  constructor() {
  }

  ngOnInit(): void {
  }
}

it works


问:
Type error: Type 'string' is not assignable to type 'Colors'
I have a status component button that receives props of color and title, the color has different colors defined in typescript

the component instance runs when I run it on localhost but throw an error when I try to build the application

Type error: Type 'string' is not assignable
to type 'Colors'.

Main Components

```<code>import React from 'react'

import styled from 'styled-components'
import capitalizeFirstLetter from '../../utils/capitalize-first-letter'

type Colors =
  | 'primary'
  | 'secondary'
  | 'success'
  | 'danger'
  | 'warning'
  | 'info'
  | 'light'
  | 'dark'
  | 'link'

const Styles = styled.button`
  outline: 0;
  border: 1px solid;
  background: #fff;
  padding: 5px 10px;
  font-size: 12px;
  border-radius: 50px;
  ${({ color }) => color === 'primary' && 'border-color: #0098db; color: #0098db;'}
  ${({ color }) => color === 'secondary' && 'border-color: #6c757d; color: #6c757d;'}
${({ color }) => color === 'success' && 'border-color: #6aea87; color: #6aea87;'}
${({ color }) => color === 'danger' && 'border-color: #dc3545; color: #dc3545;'}
${({ color }) => color === 'warning' && 'border-color: #ffc107; color: #ffc107;'}
${({ color }) => color === 'info' && 'border-color: #17a2b8; color: #17a2b8;'}
${({ color }) => color === 'light' && 'border-color: #f8f9fa; color: #212529;'}
${({ color }) => color === 'dark' && 'border-color: #343a40; color: #343a40;'}
`
export default function StatusButton({ title, color }: { title: string; color: Colors }) {
  return <Styles color={color}>{capitalizeFirstLetter(title)}</Styles>
}

</code>```

Component Instance

```<code><StatusButton title={`${blog.status.isPublished ? 'Online' : 'Offline'}`} color={`${blog.status.isPublished ? 'success' : 'warning'}`}/>
</code>```

答:
 <Alert onClose={handleMessageClose}
 severity={messageType == "success" ? "success" : messageType == "error" ? "error" : messageType == "info" ? "info" : "warning"}
 sx={{ width: '100%' }}>
 {message}
</Alert>```

Body:
I have a status component button that receives props of color and title, the color has different colors defined in typescript

the component instance runs when I run it on localhost but throw an error when I try to build the application

Type error: Type 'string' is not assignable
to type 'Colors'.

Main Components

import React from 'react'

import styled from 'styled-components'
import capitalizeFirstLetter from '../../utils/capitalize-first-letter'

type Colors =
  | 'primary'
  | 'secondary'
  | 'success'
  | 'danger'
  | 'warning'
  | 'info'
  | 'light'
  | 'dark'
  | 'link'

const Styles = styled.button`
  outline: 0;
  border: 1px solid;
  background: #fff;
  padding: 5px 10px;
  font-size: 12px;
  border-radius: 50px;
  ${({ color }) => color === 'primary' && 'border-color: #0098db; color: #0098db;'}
  ${({ color }) => color === 'secondary' && 'border-color: #6c757d; color: #6c757d;'}
${({ color }) => color === 'success' && 'border-color: #6aea87; color: #6aea87;'}
${({ color }) => color === 'danger' && 'border-color: #dc3545; color: #dc3545;'}
${({ color }) => color === 'warning' && 'border-color: #ffc107; color: #ffc107;'}
${({ color }) => color === 'info' && 'border-color: #17a2b8; color: #17a2b8;'}
${({ color }) => color === 'light' && 'border-color: #f8f9fa; color: #212529;'}
${({ color }) => color === 'dark' && 'border-color: #343a40; color: #343a40;'}
`
export default function StatusButton({ title, color }: { title: string; color: Colors }) {
  return
}

Component Instance

<StatusButton title={`${blog.status.isPublished ? 'Online' : 'Offline'}`} color={`${blog.status.isPublished ? 'success' : 'warning'}`}/>


问:
Migrate folder in /storage/emulated/0/<my_folder> from Android 10 to 11
In my existing app(Android 10) I have a folder under /storage/emulated/0/<my_folder>. After looking to various sources on Google Developers I don't think that it's possible to longer access the /storage/emulated/0/<my_folder> directory under Android 11, because of the changes made in storage access permission.

Of course I can create these folder under Android 11 inside the so called "scoped storage" as mentioned by Google. But if a user updates the app from 10 to 11, how can I access the old folder for copying the files inside to the new folder inside "scoped storage" when I am on Android 11?

Or is there some other way to migrate this folder under /storage/emulated/0/<my_folder> safely?

答:
Ever since Scoped storage introduction, you can no longer create your folders under root directory without special permission, I.E manage external storage, but i doubt play store will allow that access to your app if the core functionality isnt affected,
You can do one of the following

store your required files in respected folders [Recommended] (Documents for docs, DCIM for images/videos, Music for audio files and so on)

Require Permission to folder by open document tree intent (Last resort)


问:
Azure MSSQL to GCP Cloud SQL (MSSQL) - Migrate symmetric keys and Certificates
We have encrypted certain columns in our Azure MS-SQL database with our symmetric keys/certificates

CREATE SYMMETRIC KEY JanainaKey09
WITH ALGORITHM = AES_256
ENCRYPTION BY CERTIFICATE Shipping04;
GO
```

We have more than 100,000 records and now looking to migrate to GCP Cloud SQL for SQL Server(MSSQL Engine) and need to migrate the symmetric key and certificates also, along with the data. How to do it? There are a few suggestions to create new keys and certs in the new environment which will pose us a challenge that existing data cannot be decrypted at all.

How to migrate keys and certs also? please help guide

答:
If you have encrypted the entire database then can import the data with the keys and certificate using an encrypted BAK file. You need to first create an Encrypted backup file.
Then you can upload that file to Google Cloud Storage. Later you can use gcloud beta sql import bak CLI command to import with the certificate and private key.

You can refer Export and import using BAK files for steps in detail.

If you have encrypted certain columns on SQL, then Google Cloud KMS service should help you. You can refer to Column level encryption in GCP for the steps and process of how to do it.

Body:
We have encrypted certain columns in our Azure MS-SQL database with our symmetric keys/certificates

CREATE SYMMETRIC KEY JanainaKey09
WITH ALGORITHM = AES_256
ENCRYPTION BY CERTIFICATE Shipping04;
GO

We have more than 100,000 records and now looking to migrate to GCP Cloud SQL for SQL Server(MSSQL Engine) and need to migrate the symmetric key and certificates also, along with the data. How to do it? There are a few suggestions to create new keys and certs in the new environment which will pose us a challenge that existing data cannot be decrypted at all.

How to migrate keys and certs also? please help guide


问:
How to store Django hashed password without the User object?
I have a Django application that allows web visitors to create there own accounts. Once they create an account with a passwords, they should receive and email containing activation code. When a web-visitor creates a new account, they need to receive an activation email containing a unique key.

Obviously, I can do all this using Django's built-in authentication system. I've done it before without any problems. However, in this application, I don't want to pollute my Users table with inactive users. I only want activated users to appear in the Users table. So although I will use Django's account system for authenticating activated users, until they become activated, I'm rolling my own system. I'm keeping all the data about not-yet-activated users in a separate Django Model object (called UserActivation). And I will be managing the sending of the activation email myself.

The problem I'm having is that I don't want to store the user-submitted password in Plain text. I want to store it in my UserActivation object in a field called "password" in the same hashed-format it would appear in the User table. To put it into the user object, I would have done myUser.set_password("plainTextPassword"). How can I get this same value and stuff it into UserActivation.password?

From looking at this doc, it seems that there is a make_password() function that returns the value that I need. But I still need a User object to call that method. How can I conver "plainTextPassword" to hashed password without going through the User object?

答:
views.py

from django.contrib.auth.hashers import make_password, check_password

print("password hashing!!!!")

```<code>    password = make_password('password')
    print(password)
    signup_obj = Signuup(firstname=first_name,
                         lastname=last_name,
                         email=email,
                         password=password)
    signup_obj.register()
</code>```

password = make_password('password') that will convert the password to hash but must use that code of line before register/save the object....

Body:
views.py

from django.contrib.auth.hashers import make_password, check_password

print("password hashing!!!!")

    password = make_password('password')
    print(password)
    signup_obj = Signuup(firstname=first_name,
                         lastname=last_name,
                         email=email,
                         password=password)
    signup_obj.register()

password = make_password('password') that will convert the password to hash but must use that code of line before register/save the object....


问:
Install htop/atop in android device
Is there any way to install htop and atop in my android device? ie for installing atop in my linux pc I can use apt install atop in a terminal. Similarly is there any way to install atop in my adb device?

答:
alternative to htop to show all system processes you can use top command
from an adb shell as you mentioned

Title: Install htop/atop in android device


问:
Pandas: filter one dataframe by multiple, simultaneous column values of another dataframe
I have a filtered dataframe called correct_df and a raw dataframe example_df.

```<code>example_df = pd.DataFrame({'Test': ['Test_1', 'Test_1', 'Test_1', 'Test_2', 'Test_2', 'Test_2', 'Test_3', 'Test_3', 'Test_3'], 'A': [1, 2, 3, 1, 2, 3, 1, 2, 3]})
other_df = pd.DataFrame({'Test': ['Test_1', 'Test_1', 'Test_3', 'Test_3'], 'A': [1, 2, 1, 3]})
</code>```

Desired result:

I want the indexes of example_df where 'Test' and 'A' column values both match the combined row value of correct_df.

I have tried:

```<code>result = example_df.loc[ (example_df['Test'].isin(other_df['Test'])) & (example_df['A'].isin(other_df['A'])) ]
result

    Test    A
0   Test_1  1
1   Test_1  2
2   Test_1  3
6   Test_3  1
7   Test_3  2
8   Test_3  3
</code>```

But as these two conditions are separated, the resulting value only applies the conditions on single columns without chaining them i.e. A then also B, not A and B. How do I get the .loc of both column conditions?

答:
Use DataFrame.reset_index for avoid lost indices and then DataFrame.merge:

```<code>result = example_df.reset_index().merge(other_df, on=['Test','A'])
print (result)
   index    Test  A
0      0  Test_1  1
1      1  Test_1  2
2      6  Test_3  1
3      8  Test_3  3
</code>```

```<code>result = (example_df.reset_index()
                    .merge(other_df, on=['Test','A'])
                    .set_index('index')
                    .rename_axis(None))
print (result)
     Test  A
0  Test_1  1
1  Test_1  2
6  Test_3  1
8  Test_3  3
</code>```

Another idea with MultiIndex with Index.isin and filtering in boolean indexing:

```<code>result = example_df[example_df.set_index(['Test','A']).index
                              .isin(other_df.set_index(['Test','A']).index)]
print (result)
     Test  A
0  Test_1  1
1  Test_1  2
6  Test_3  1
8  Test_3  3
</code>```

Body:
I have a filtered dataframe called correct_df and a raw dataframe example_df.

example_df = pd.DataFrame({'Test': ['Test_1', 'Test_1', 'Test_1', 'Test_2', 'Test_2', 'Test_2', 'Test_3', 'Test_3', 'Test_3'], 'A': [1, 2, 3, 1, 2, 3, 1, 2, 3]})
other_df = pd.DataFrame({'Test': ['Test_1', 'Test_1', 'Test_3', 'Test_3'], 'A': [1, 2, 1, 3]})

Desired result:

I want the indexes of example_df where 'Test' and 'A' column values both match the combined row value of correct_df.

I have tried:

result = example_df.loc[ (example_df['Test'].isin(other_df['Test'])) & (example_df['A'].isin(other_df['A'])) ]
result

    Test    A
0   Test_1  1
1   Test_1  2
2   Test_1  3
6   Test_3  1
7   Test_3  2
8   Test_3  3

But as these two conditions are separated, the resulting value only applies the conditions on single columns without chaining them i.e. A then also B, not A and B. How do I get the .loc of both column conditions?

Body:
Use DataFrame.reset_index for avoid lost indices and then DataFrame.merge:

result = example_df.reset_index().merge(other_df, on=['Test','A'])
print (result)
   index    Test  A
0      0  Test_1  1
1      1  Test_1  2
2      6  Test_3  1
3      8  Test_3  3

result = (example_df.reset_index()
                    .merge(other_df, on=['Test','A'])
                    .set_index('index')
                    .rename_axis(None))
print (result)
     Test  A
0  Test_1  1
1  Test_1  2
6  Test_3  1
8  Test_3  3

Another idea with MultiIndex with Index.isin and filtering in boolean indexing:

result = example_df[example_df.set_index(['Test','A']).index
                              .isin(other_df.set_index(['Test','A']).index)]
print (result)
     Test  A
0  Test_1  1
1  Test_1  2
6  Test_3  1
8  Test_3  3


问:
Running JupyterLab as a Desktop Application in Windows 10
Cristopher Roach wrote the blog of "Running Jupyter Lab as a Desktop Application" for Mac users. It did not  work for Anaconda users in Windows 10. Eventually, what I did is the below:

Go to the directory of C:\ProgramData\Anaconda3\Scripts

Find the file of jupyter-lab.exe and make the link of the file in Taskbars. Note: With some reasons, the message of the  "Widows could not create the shortcut. Check to see if the disk is full" popped up when I tried to make the link on the Desktop.

Right click on the link of jupyter-lab.exe and go to Properties.

Download the icon file of Jupyterlab and save it as Jupyterlab.ico in the folder of C:\ProgramData\Anaconda3\Menu\Jupyterlab.ico (=`%ALLUSERSPROFILE%\Anaconda3\Menu\Jupyterlab.ico )

Click Change Icon and copy %ALLUSERSPROFILE%\Anaconda3\Menu\Jupyterlab.ico in "Look for icons in this file".

Done!

Many steps were required to go through. Is there any simpler way?

答:
For Windows 10/11 use a PowerShell script file.  Create a file named JupyterLab.ps1 (or any name you wish) and add two lines.  The first line (which can be omitted) will change the working folder.  The second line starts Jupyter Lab.

C:\Users\myusername\Documents\Programs
jupyter lab

Right click on the desktop and create an empty shortcut.  In the Targe box you have to include the following line to modify the execution policy or the shortcut will just open the Windows PowerShell editor instead of executing the script.

Target:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File "C:\Users\myusername\Documents\Programs\JupyterLab.ps1"

Start In:
\your working directory


问:
Python creating video from images using opencv
I was trying to create a video to show the dynamic variation of the data, like just continuously showing the images one by one quickly, so I used images (the images just called 1,2,3,4,.....) and wrote the following code:

```<code>import cv2
import numpy as np

img=[]
for i in range(0,5):
    img.append(cv2.imread(str(i)+'.png'))

height,width,layers=img[1].shape

video=cv2.VideoWriter('video.avi',-1,1,(width,height))

for j in range(0,5):
    video.write(img)

cv2.destroyAllWindows()
video.release()
</code>```

and a error was raised:

```<code>TypeError: image is not a numpy array, neither a scalar
</code>```

I think I used the list in a wrong way but I'm not sure. So where did I do wrong?

答:
You can use this pip package. It provides CLI commands to make video from images.

img_to_vid.py -f images_directory

Body:
I was trying to create a video to show the dynamic variation of the data, like just continuously showing the images one by one quickly, so I used images (the images just called 1,2,3,4,.....) and wrote the following code:

import cv2
import numpy as np

img=[]
for i in range(0,5):
    img.append(cv2.imread(str(i)+'.png'))

height,width,layers=img[1].shape

video=cv2.VideoWriter('video.avi',-1,1,(width,height))

for j in range(0,5):
    video.write(img)

cv2.destroyAllWindows()
video.release()

and a error was raised:

TypeError: image is not a numpy array, neither a scalar

I think I used the list in a wrong way but I'm not sure. So where did I do wrong?


问:
Docker compose fails with 'COPY failed: stat usr/src/app/dist: file does not exist' - only on github actions
I'm creating web application (angular + nest.js) and I'm trying to make multi stage build - I want to reduce size of docker image.

Angular build works good.

Nest.js one builds successfully on my pc using docker compose build, but fails on github actions with following error: Status: COPY failed: stat usr/src/app/dist: file does not exist, Code: 1

What can i do to fix it?

Dockerfile:

```<code>FROM node:16.13.1-alpine AS build
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install --only=development
RUN npm run build
COPY . .

FROM node:16.13.1-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install --only=production
COPY . .
COPY --from=build /usr/src/app/dist ./dist
EXPOSE 7000
CMD ["node", "dist/main"]
</code>```

previous single stage Dockerfile (builds successfully):

```<code>FROM node:16.13.1-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
RUN npm run build
COPY . .
EXPOSE 7000
CMD [ "npm", "start" ]
</code>```

docker-compose.yml:

```<code>version: '3.8'

services:
  backend:
    container_name: nestjs
    image: ghcr.io/<gh-nickname/repo-name>/backend
    build:
      context: backend
      dockerfile: Dockerfile
    ports:
    - 7000:7000
  frontend:
    container_name: angular
    image: ghcr.io/<gh-nickname/repo-name>/frontend
    build:
      context: frontend
      dockerfile: Dockerfile
    ports:
    - 8000:80
</code>```

github workflow file:

```<code>name: Build and publish to github packages

on:
  push:
    branches:
      - master

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  build-and-push-image:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
    - name: Checkout
      uses: actions/checkout@v2

    - name: Log in to the Container registry
      uses: docker/login-action@v1
      with:
        registry: ${{ env.REGISTRY }}
        username: ${{ github.actor }}
        password: ${{ secrets.GITHUB_TOKEN }}

    - name: Extract metadata (tags, labels) for Docker
      id: meta
      uses: docker/metadata-action@v3
      with:
        images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}

    - name: Build image
      run: docker compose build

    - name: Publish image
      run: docker compose push
</code>```

答:
Try with the following Dockerfile:

FROM node:16.13.1-alpine AS build
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install --only=development
RUN npm run build
COPY . .

FROM node:16.13.1-alpine
COPY --from=build /usr/src/app/dist ./dist
EXPOSE 7000
CMD ["node", "dist/main"]```

Body:
I'm creating web application (angular + nest.js) and I'm trying to make multi stage build - I want to reduce size of docker image.

Angular build works good.

Nest.js one builds successfully on my pc using docker compose build, but fails on github actions with following error: Status: COPY failed: stat usr/src/app/dist: file does not exist, Code: 1

What can i do to fix it?

Dockerfile:

FROM node:16.13.1-alpine AS build
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install --only=development
RUN npm run build
COPY . .

FROM node:16.13.1-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install --only=production
COPY . .
COPY --from=build /usr/src/app/dist ./dist
EXPOSE 7000
CMD ["node", "dist/main"]

previous single stage Dockerfile (builds successfully):

FROM node:16.13.1-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
RUN npm run build
COPY . .
EXPOSE 7000
CMD [ "npm", "start" ]

docker-compose.yml:

version: '3.8'

services:
  backend:
    container_name: nestjs
    image: ghcr.io/<gh-nickname/repo-name>/backend
    build:
      context: backend
      dockerfile: Dockerfile
    ports:
    - 7000:7000
  frontend:
    container_name: angular
    image: ghcr.io/<gh-nickname/repo-name>/frontend
    build:
      context: frontend
      dockerfile: Dockerfile
    ports:
    - 8000:80

github workflow file:

name: Build and publish to github packages

on:
  push:
    branches:
      - master

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  build-and-push-image:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
    - name: Checkout
      uses: actions/checkout@v2

    - name: Log in to the Container registry
      uses: docker/login-action@v1
      with:
        registry: ${{ env.REGISTRY }}
        username: ${{ github.actor }}
        password: ${{ secrets.GITHUB_TOKEN }}

    - name: Extract metadata (tags, labels) for Docker
      id: meta
      uses: docker/metadata-action@v3
      with:
        images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}

    - name: Build image
      run: docker compose build

    - name: Publish image
      run: docker compose push


问:
passing argument to boto3 e2 start script
any idea how I can modify this to passing the instance id as argument instead of putting it in the script?</p>
```<code>import boto3

def stop_instance(instance_id):
    ec2 = boto3.client("ec2", region_name="us-west-1")
    response = ec2.stop_instances(InstanceIds=[instance_id])
    print(response)

stop_instance()
</code>```

答: If your objective if to stop all EC2 instances via Python script, you can first call the describe-instances method to dynamically build a list of all the running EC2 instances (pull id values based on the state property = running). From there you can pass that list into your function to stop them all, as the stop-instances method can handle a list of ids.</p>

Body:
any idea how I can modify this to passing the instance id as argument instead of putting it in the script?

import boto3

def stop_instance(instance_id):
    ec2 = boto3.client("ec2", region_name="us-west-1")
    response = ec2.stop_instances(InstanceIds=[instance_id])
    print(response)

stop_instance()


问:
Memory Limit in Spark/kafka
Is there any way to set limit of number of records while consuming data from Kafka.
i.e. I have 1000 Records in Kafka, after consuming events from Kafka, Placing at HDFS location. I  am trying to add the configuration(by spark  submit command) so at a time it can only read and process 100 records instead of consuming all the 1000 records, so this way it will consume less memory.</p>

答:
There's a setting maxOffsetsPerTrigger to limit the number of records to fetch

To limit total memory, though, can either force the Spark executors to have a fixed heap size, and you can try passing kafka.max.poll.records config option to the readStream options to be more explicit to the consumer for limiting polled records.

You could alternatively use Kafka Connect HDFS Sink, which has a flush.size parameter for records per file.

Note that HDFS prefers larger files, and not lots of tiny ones

Title: Memory Limit in Spark/kafka