Title: How to display the intersection points of y axis?

Body:
library(data.table)
library(survival)
library(survminer)
library(dcurves)

I have df as follows

structure(list(PatientID = c(1001L, 1002L, 1003L, 1004L, 1006L,
1014L, 1015L, 1016L, 1018L, 1022L, 1024L, 1032L, 1040L, 1042L,
1049L, 1056L, 1059L, 1060L, 1066L, 1084L, 1087L, 1090L, 1093L,
1096L, 1097L, 1098L, 1099L, 1200L, 1205L, 1216L, 1221L, 1222L,
1225L, 1226L, 1233L, 1239L), TimeMonths = c(9L, 8L, 69L, 104L,
104L, 100L, 24L, 85L, 100L, 99L, 67L, 58L, 7L, 94L, 93L, 90L,
91L, 90L, 89L, 72L, 84L, 84L, 11L, 82L, 39L, 46L, 82L, 82L, 9L,
34L, 75L, 76L, 52L, 20L, 29L, 70L), Event = c(1L, 0L, 0L, 0L,
0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 1L, 0L, 1L, 1L, 0L, 0L, 1L, 1L, 0L, 0L, 1L, 1L, 1L, 0L
), P1 = c(0.1, 0.03, 0.02, 0.05, 0.01, 0.04, 0.03,
0.06, 0.02, 0.03, 0, 0, 0.11, 0.01, 0.03, 0, 0.01, 0.01, 0.01,
0, 0, 0, 0.05, 0.01, 0, 0, 0, 0, 0.04, 0, 0.07, 0.01, 0.01, 0,
0, 0), Age = c(88L, 49L, 60L, 46L, 50L, 60L, 38L, 74L, 39L, 65L,
80L, 35L, 54L, 40L, 54L, 55L, 60L, 38L, 64L, 74L, 71L, 57L, 55L,
49L, 42L, 30L, 63L, 46L, 47L, 58L, 34L, 72L, 50L, 60L, 73L, 51L
), Grade = c(2L, 2L, 2L, 3L, 3L, 1L, 2L, 2L, 2L, 1L, 2L, 1L,
3L, 1L, 3L, NA, 2L, 3L, 2L, 2L, 2L, NA, 2L, 2L, 2L, 2L, 2L, 1L,
2L, 2L, 2L, 2L, 3L, 2L, 2L, 2L), Tsize = c(2.5, 6, 4, 4, 3.5,
1.8, 1.5, 1.5, 2, 3.5, 4, 2, 4.5, 3, 3, 2, 3, 1.5, 2.5, 5, 5,
3, 6, 3, 2.5, 5, 1.5, 2, 5.5, 5, 3, 6, 4, 3.5, 4, 5), LNstatus = c(0L,
1L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 1L, 0L, 1L, 1L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 1L, 0L, 1L, 0L, 1L, 1L, 1L, 0L, 0L, 1L, 1L, 0L, 1L,
1L, 1L, 0L), Time = c(5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5), Model1 = c(0.0754111003682264, 0.789025824308725, 0.0888669573431788,
0.162944690463524, 0.148205788806964, 0.0232412222825853, 0.335639290548721,
0.427877640015971, 0.0437151408243315, 0.340118759660636, 0.104749557872707,
0.191041558905319, 0.901494025297558, 0.0271621117477482, 0.134690848022469,
NA, 0.0681964605449713, 0.0799110215826685, 0.0617151301818596,
0.129265190806531, 0.760358458474655, NA, 0.805815477115913,
0.0622010539620427, 0.4275233016386, 0.632818820863808, 0.39812097019303,
0.0217733118415042, 0.118190758626649, 0.721016961718498, 0.449778991144841,
0.164102951793386, 0.857780996059435, 0.576334735175668, 0.668186510212559,
0.107238793230798), Model2 = c(0.444752330666943, 0.930853771862407,
0.0980811416950194, 0.311714208416219, 0.108779198079316, 0.0297296718406789,
0.255165235219636, 0.652922467522166, 0.0301952043412281, 0.405213119172736,
0.0800242041001141, 0.0767147984837693, 0.999999999862285, 0.0181219543140756,
0.14865830843794, NA, 0.0496630840467432, 0.0382325860289233,
0.0421016493675688, 0.113455005788149, 0.665969059849803, NA,
0.991966233874329, 0.0424861062828985, 0.206267128670341, 0.453591375821231,
0.180419209497713, 0.00979786791522574, 0.243955485600603, 0.596589087934302,
0.778048018064795, 0.211053490646643, 0.747102269303274, 0.37666971629859,
0.511588083962541, 0.0826035699229486)), class = "data.frame", row.names = c(NA,
-36L))

I tried following code to generate the dca

dca(Surv(Time, Event) ~ Model1 + Model2, data = dfs,
label = list(Model1 = "Model1", Model2 = "Model2"), time = 5, thresholds = 1:35 / 100) %>% plot(smooth = TRUE)

Now I want to display the values of y axis at a specific x value for Model1 and Model2. It's approximately 0.255 and 0.300 respectively

Expected output


来源: stackexchange

问:
How to implement Firebase phone auth without captcha verification using javascript?
I need to implement the firebase phone number authentication in firebase , but i don't need captcha verification. I want to implement by only phone number and otp.

I tried some of the steps, but it not works:

```<code>firebase.auth().settings.appVerificationDisabledForTesting = true;
</code>```

If i use this , get captcha malformed.

Is there any way to solve or any cloud provider will solve it?

ContentLicense: CC BY-SA 4.0

Body:
I need to implement the firebase phone number authentication in firebase , but i don't need captcha verification. I want to implement by only phone number and otp.

I tried some of the steps, but it not works:

firebase.auth().settings.appVerificationDisabledForTesting = true;

If i use this , get captcha malformed.

Is there any way to solve or any cloud provider will solve it?


问:
How to connect Realtime Database firebase with dialogflow chatbot
I want to connect Realtime database firebase with Dialogflow chatbot and how to get some data from Realtime database firebase using Dialogflow. I want when the user ask my chatbot to show the machine water quantity then chatbot will ask for the machine id of which you want to know water quantity, then chatbot access the realtime database firebase to check if the machine is present in database then it will show the water quantity of that machine.

I have tried to connect realtime database firebase this way-

'use strict';

const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');

const firebaseAdmin=require("firebase-admin");

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

 firebaseAdmin.initializeapp({
 credential:firebaseAdmin.credential.applicationDefault(),
 databaseURL:"ws://rtdb.asia-southeast1.firebasedatabase.app/",
 });

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));

  function welcome(agent) {
    agent.add(`Welcome to Akvo chat!`);
  }

  function fallback(agent) {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
  }

//function getFromFirebase(agent){
//return firebaseAdmin.database().ref("board_id").once("value", snapshot=>{
//var boardid=snapshot.val();
  //agent.add(boardid);
//});
//}

  // Run the proper function handler based on the matched Dialogflow intent name
  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('Default Fallback Intent', fallback);
 //intentMap.set('board id', getFromFirebase);
  agent.handleRequest(intentMap);
});```

But it shows an error.

Error: " Error happened during Cloud Functions Deployment "

can you please tell me how to do this.

Body:
I want to connect Realtime database firebase with Dialogflow chatbot and how to get some data from Realtime database firebase using Dialogflow. I want when the user ask my chatbot to show the machine water quantity then chatbot will ask for the machine id of which you want to know water quantity, then chatbot access the realtime database firebase to check if the machine is present in database then it will show the water quantity of that machine.

I have tried to connect realtime database firebase this way-

'use strict';

const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');

const firebaseAdmin=require("firebase-admin");

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

 firebaseAdmin.initializeapp({
 credential:firebaseAdmin.credential.applicationDefault(),
 databaseURL:"ws://rtdb.asia-southeast1.firebasedatabase.app/",
 });

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));

  function welcome(agent) {
    agent.add(`Welcome to Akvo chat!`);
  }

  function fallback(agent) {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
  }

//function getFromFirebase(agent){
//return firebaseAdmin.database().ref("board_id").once("value", snapshot=>{
//var boardid=snapshot.val();
  //agent.add(boardid);
//});
//}

  // Run the proper function handler based on the matched Dialogflow intent name
  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('Default Fallback Intent', fallback);
 //intentMap.set('board id', getFromFirebase);
  agent.handleRequest(intentMap);
});

But it shows an error.

Error: " Error happened during Cloud Functions Deployment "

can you please tell me how to do this.


问:
Is it better to use iterators or variables when attempting to split strings
What is a consistent, proper way to split and combine strings in Rust, ideally being as performant as possible?

Just for the sake of it, I wanted to automated my Advent of Code test input by separating it into a different directory. My binaries are named in the format YEAR_PROBLEM#.rs, and the related input files are stored in YEAR\PROBLEM#.txt.

So, for instance, the file 2022_1.rs needs input 2022/1.txt.

I'm trying to take this file and parse through a path I can get through std::env::args. I had a few solutions, but all of them seemed either weird or extremely verbose and over the top. First I thought I could just use split and iterators but that required a lot of unwrapping.

let path = std::env::args()
        .next()
        .unwrap()
        .split('\\')
        .last()
        .unwrap()
        .split_once('.')
        .map(|x| format!("{}\\{}.txt", x.0, x.1))
        .unwrap();
```
<p>Then I thought, just for fun, I would wrap this in a closure that allows me to handle the errors with the <code>?</code> operator (though I feel this is as bad practice as it is strange to read).</p>
<pre class="lang-rs prettyprint-override"><code>let path = || -> Option<String> {
    Some(
        std::env::args()
            .next()?
            .split('\\')
            .last()?
            .split_once('.')?
            .0
            .split_once('_')
            .map(|x| format!("{}\\{}.txt", x.0, x.1))?,
    )
}()
.unwrap();
</code>```

And of course there's the way that uses multiple variables.

let full_path = std::env::args().next().unwrap();
let binary_name = full_path.split('\\').last().unwrap();
let (file_name, _) = binary_name.split_once('.').unwrap();
let (dir, n) = file_name.split_once('_').unwrap();
let path = format!("{}\\{}.txt", dir, n);
```

The last way feels the most intuitive and easiest to read. However, I also like being able to compress things and use iterators and maps to the fullest extent as long as I'm not compromising performance or readability. Also, although performance isn't a major factor here, I mostly want to know in this case for practice for the future

Is using splits, unwraps, or even that nasty closure to let the values be temporarily created and consumed by the iterators better than allocating these strings to variables?

Do I have any misunderstandings about the how iterators function and how their usage might differ compared to declaring variables instead? Also, if there is a clear cut solution in the standard library for this please let me know!

Body:
What is a consistent, proper way to split and combine strings in Rust, ideally being as performant as possible?

Just for the sake of it, I wanted to automated my Advent of Code test input by separating it into a different directory. My binaries are named in the format YEAR_PROBLEM#.rs, and the related input files are stored in YEAR\PROBLEM#.txt.

So, for instance, the file 2022_1.rs needs input 2022/1.txt.

I'm trying to take this file and parse through a path I can get through std::env::args. I had a few solutions, but all of them seemed either weird or extremely verbose and over the top. First I thought I could just use split and iterators but that required a lot of unwrapping.

let path = std::env::args()
        .next()
        .unwrap()
        .split('\\')
        .last()
        .unwrap()
        .split_once('.')
        .map(|x| format!("{}\\{}.txt", x.0, x.1))
        .unwrap();

Then I thought, just for fun, I would wrap this in a closure that allows me to handle the errors with the ? operator (though I feel this is as bad practice as it is strange to read).

let path = || -> Option<String> {
    Some(
        std::env::args()
            .next()?
            .split('\\')
            .last()?
            .split_once('.')?
            .0
            .split_once('_')
            .map(|x| format!("{}\\{}.txt", x.0, x.1))?,
    )
}()
.unwrap();

And of course there's the way that uses multiple variables.

let full_path = std::env::args().next().unwrap();
let binary_name = full_path.split('\\').last().unwrap();
let (file_name, _) = binary_name.split_once('.').unwrap();
let (dir, n) = file_name.split_once('_').unwrap();
let path = format!("{}\\{}.txt", dir, n);

The last way feels the most intuitive and easiest to read. However, I also like being able to compress things and use iterators and maps to the fullest extent as long as I'm not compromising performance or readability. Also, although performance isn't a major factor here, I mostly want to know in this case for practice for the future

Is using splits, unwraps, or even that nasty closure to let the values be temporarily created and consumed by the iterators better than allocating these strings to variables?

Do I have any misunderstandings about the how iterators function and how their usage might differ compared to declaring variables instead? Also, if there is a clear cut solution in the standard library for this please let me know!


问:
Application "Could not create SSL/TLS secure channel"
When i try and download a clickonce application, it shows the error message of:
Application Download did not succeed. Check your network connection, or contact your system administrator or network service provider

Here is my log file

```<code>PLATFORM VERSION INFO
    Windows             : 10.0.19044.0 (Win32NT)
    Common Language Runtime     : 4.0.30319.42000
    System.Deployment.dll       : 4.8.9037.0 built by: NET481REL1
    clr.dll             : 4.8.9037.0 built by: NET481REL1
    dfdll.dll           : 4.8.9037.0 built by: NET481REL1
    dfshim.dll          : 10.0.19041.30000 (WinBuild.160101.0800)

SOURCES
    Deployment url          : https://raw.githubusercontent.com/msarilar/EDEngineer/master/EDEngineer/releases/EDEngineer.application

ERROR SUMMARY
    Below is a summary of the errors, details of these errors are listed later in the log.
    * Activation of https://raw.githubusercontent.com/msarilar/EDEngineer/master/EDEngineer/releases/EDEngineer.application resulted in exception. Following failure messages were detected:
        + Downloading https://raw.githubusercontent.com/msarilar/EDEngineer/master/EDEngineer/releases/EDEngineer.application did not succeed.
        + The request was aborted: Could not create SSL/TLS secure channel.

COMPONENT STORE TRANSACTION FAILURE SUMMARY
    No transaction error was detected.

WARNINGS
    There were no warnings during this operation.

OPERATION PROGRESS STATUS
    * [8/12/2022 5:31:53 PM] : Activation of https://raw.githubusercontent.com/msarilar/EDEngineer/master/EDEngineer/releases/EDEngineer.application has started.

ERROR DETAILS
    Following errors were detected during this operation.
    * [8/12/2022 5:31:53 PM] System.Deployment.Application.DeploymentDownloadException (Unknown subtype)
        - Downloading c did not succeed.
        - Source: System.Deployment
        - Stack trace:
            at System.Deployment.Application.SystemNetDownloader.DownloadSingleFile(DownloadQueueItem next)
            at System.Deployment.Application.SystemNetDownloader.DownloadAllFiles()
            at System.Deployment.Application.FileDownloader.Download(SubscriptionState subState, X509Certificate2 clientCertificate)
            at System.Deployment.Application.DownloadManager.DownloadManifestAsRawFile(Uri& sourceUri, String targetPath, IDownloadNotification notification, DownloadOptions options, ServerInformation& serverInformation)
            at System.Deployment.Application.DownloadManager.DownloadDeploymentManifestDirectBypass(SubscriptionStore subStore, Uri& sourceUri, TempFile& tempFile, SubscriptionState& subState, IDownloadNotification notification, DownloadOptions options, ServerInformation& serverInformation)
            at System.Deployment.Application.DownloadManager.DownloadDeploymentManifestBypass(SubscriptionStore subStore, Uri& sourceUri, TempFile& tempFile, SubscriptionState& subState, IDownloadNotification notification, DownloadOptions options)
            at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl, Uri& deploymentUri)
            at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivationWithRetry(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
--- End of stack trace from previous location where exception was thrown ---
            at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
            at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivationWithRetry(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
            at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state)
        --- Inner Exception ---
        System.Net.WebException
        - The request was aborted: Could not create SSL/TLS secure channel.
        - Source: System
        - Stack trace:
            at System.Net.HttpWebRequest.GetResponse()
            at System.Deployment.Application.SystemNetDownloader.DownloadSingleFile(DownloadQueueItem next)

COMPONENT STORE TRANSACTION DETAILS
    No transaction information is available.

</code>```

`

I have tried updating my .net framework, and i can access the url directly from my browser. I have deleted all files in the clickonce installation folder multiple times, and this is coming directly from the setup app, but also happened when the app was updated

Body:
When i try and download a clickonce application, it shows the error message of:
Application Download did not succeed. Check your network connection, or contact your system administrator or network service provider

Here is my log file

PLATFORM VERSION INFO
    Windows             : 10.0.19044.0 (Win32NT)
    Common Language Runtime     : 4.0.30319.42000
    System.Deployment.dll       : 4.8.9037.0 built by: NET481REL1
    clr.dll             : 4.8.9037.0 built by: NET481REL1
    dfdll.dll           : 4.8.9037.0 built by: NET481REL1
    dfshim.dll          : 10.0.19041.30000 (WinBuild.160101.0800)

SOURCES
    Deployment url          : https://raw.githubusercontent.com/msarilar/EDEngineer/master/EDEngineer/releases/EDEngineer.application

ERROR SUMMARY
    Below is a summary of the errors, details of these errors are listed later in the log.
    * Activation of https://raw.githubusercontent.com/msarilar/EDEngineer/master/EDEngineer/releases/EDEngineer.application resulted in exception. Following failure messages were detected:
        + Downloading https://raw.githubusercontent.com/msarilar/EDEngineer/master/EDEngineer/releases/EDEngineer.application did not succeed.
        + The request was aborted: Could not create SSL/TLS secure channel.

COMPONENT STORE TRANSACTION FAILURE SUMMARY
    No transaction error was detected.

WARNINGS
    There were no warnings during this operation.

OPERATION PROGRESS STATUS
    * [8/12/2022 5:31:53 PM] : Activation of https://raw.githubusercontent.com/msarilar/EDEngineer/master/EDEngineer/releases/EDEngineer.application has started.

ERROR DETAILS
    Following errors were detected during this operation.
    * [8/12/2022 5:31:53 PM] System.Deployment.Application.DeploymentDownloadException (Unknown subtype)
        - Downloading c did not succeed.
        - Source: System.Deployment
        - Stack trace:
            at System.Deployment.Application.SystemNetDownloader.DownloadSingleFile(DownloadQueueItem next)
            at System.Deployment.Application.SystemNetDownloader.DownloadAllFiles()
            at System.Deployment.Application.FileDownloader.Download(SubscriptionState subState, X509Certificate2 clientCertificate)
            at System.Deployment.Application.DownloadManager.DownloadManifestAsRawFile(Uri& sourceUri, String targetPath, IDownloadNotification notification, DownloadOptions options, ServerInformation& serverInformation)
            at System.Deployment.Application.DownloadManager.DownloadDeploymentManifestDirectBypass(SubscriptionStore subStore, Uri& sourceUri, TempFile& tempFile, SubscriptionState& subState, IDownloadNotification notification, DownloadOptions options, ServerInformation& serverInformation)
            at System.Deployment.Application.DownloadManager.DownloadDeploymentManifestBypass(SubscriptionStore subStore, Uri& sourceUri, TempFile& tempFile, SubscriptionState& subState, IDownloadNotification notification, DownloadOptions options)
            at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl, Uri& deploymentUri)
            at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivationWithRetry(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
--- End of stack trace from previous location where exception was thrown ---
            at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
            at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivationWithRetry(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
            at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state)
        --- Inner Exception ---
        System.Net.WebException
        - The request was aborted: Could not create SSL/TLS secure channel.
        - Source: System
        - Stack trace:
            at System.Net.HttpWebRequest.GetResponse()
            at System.Deployment.Application.SystemNetDownloader.DownloadSingleFile(DownloadQueueItem next)

COMPONENT STORE TRANSACTION DETAILS
    No transaction information is available.

`

I have tried updating my .net framework, and i can access the url directly from my browser. I have deleted all files in the clickonce installation folder multiple times, and this is coming directly from the setup app, but also happened when the app was updated


问:
"Optional group value" Exception while writing Map<String, Set<String>> to parquet in Spark-Java
I have a POJO model as follows -

```<code>public class Model implements Serializable {
  private Map<String,Set<String>> map;
}
</code>```

which I am trying to write to a parquet file using Spark. The code for the same is follows:

```<code>JavaRDD<Context> dataSet = generate();
JavaPairRDD<Model, Model> outputRDD = dataSet.mapToPair((PairFunction<Context, Model, Model>)
        context -> {
            return new Tuple2<>(context.getMoel1(), context.getModel2());
        });

Dataset<Tuple2<Model, Model>> outputDS = sqlContext.createDataset(JavaPairRDD.toRDD(outputRDD),
        Encoders.tuple(Encoders.bean(Model.class), Encoders.bean(Model.class)));

outputDS.coalesce(numPartitions).write().mode(SaveMode.Overwrite).parquet(outputPath + "v2/");
</code>```

It gives me the following exception because of using a Set<> inside the map.

```<code>Caused by: org.apache.parquet.schema.InvalidSchemaException: Cannot write a schema with an empty group: optional group value {
}
    at org.apache.parquet.schema.TypeUtil$1.visit(TypeUtil.java:27)
    at org.apache.parquet.schema.GroupType.accept(GroupType.java:255)
    at org.apache.parquet.schema.TypeUtil$1.visit(TypeUtil.java:31)
    at org.apache.parquet.schema.GroupType.accept(GroupType.java:255)
    at org.apache.parquet.schema.TypeUtil$1.visit(TypeUtil.java:31)
</code>```

So, I tried making it a Map<String, List<String>> and it worked fine.
However, since this model is used all over the code base, there will be many repurcussions for changing it.

Why is this happening? And how to resolve this?

Thanks in advance!

P.S. I am using Spark 3.1.2

Body:
I have a POJO model as follows -

public class Model implements Serializable {
  private Map<String,Set<String>> map;
}

which I am trying to write to a parquet file using Spark. The code for the same is follows:

JavaRDD<Context> dataSet = generate();
JavaPairRDD<Model, Model> outputRDD = dataSet.mapToPair((PairFunction<Context, Model, Model>)
        context -> {
            return new Tuple2<>(context.getMoel1(), context.getModel2());
        });

Dataset<Tuple2<Model, Model>> outputDS = sqlContext.createDataset(JavaPairRDD.toRDD(outputRDD),
        Encoders.tuple(Encoders.bean(Model.class), Encoders.bean(Model.class)));

outputDS.coalesce(numPartitions).write().mode(SaveMode.Overwrite).parquet(outputPath + "v2/");

It gives me the following exception because of using a Set<> inside the map.

Caused by: org.apache.parquet.schema.InvalidSchemaException: Cannot write a schema with an empty group: optional group value {
}
    at org.apache.parquet.schema.TypeUtil$1.visit(TypeUtil.java:27)
    at org.apache.parquet.schema.GroupType.accept(GroupType.java:255)
    at org.apache.parquet.schema.TypeUtil$1.visit(TypeUtil.java:31)
    at org.apache.parquet.schema.GroupType.accept(GroupType.java:255)
    at org.apache.parquet.schema.TypeUtil$1.visit(TypeUtil.java:31)

So, I tried making it a Map<String, List<String>> and it worked fine.
However, since this model is used all over the code base, there will be many repurcussions for changing it.

Why is this happening? And how to resolve this?

Thanks in advance!

P.S. I am using Spark 3.1.2


问:
NodeJS app crashes with an out of memory error but it looks like it has plenty left
I am trying to debug an out of memory error in NodeJS.

My script fetches data and pushes it into an array. It looks like this:

```<code>class Fetcher {
  async fetchAll () {
    const hits = []
    let page = 1
    while (true) {
      const result = await fetchData(page)
      hits.push(...result)
      if (!result.length) {
        break
      }
      page++
    }
    return hits
  }
}
</code>```

When running this on a rather long database, I'm facing an out of memory error on pages 50+ (all the pages are approximately of the same size):

If I set up the --max-old-space-size to 8096, the error disappears. If I set it up to 2048, the error rises again.

However, I'm sure that my data is not that space consuming, and I am trying to see what operation exactly is taking so much space so I tried to debug memory usage with a function like this:

```<code>const printMemory = (logger: Logger) => {
  const formatMemory = memory => {
    return `${Math.round(memory / 1024 / 1024 * 100) / 100} MB`
  }
  const used = process.memoryUsage();
  const v8HeapStatistics = v8.getHeapStatistics()
  logger.debug(`V8 [used_heap_size]: ${formatMemory(v8HeapStatistics.used_heap_size)}`)
  logger.debug(`V8 [total_available_size]: ${formatMemory(v8HeapStatistics.total_available_size)}`)
  for (let key in used) {
    logger.debug(`${key} ${formatMemory(used[key])}`);
  }
}
</code>```

This function is supposed to print the memory usage by the process and by V8.

When I run this function inside the loop (where the application crashes), it never exceeds 250MB of usage even if the memory usage grows over time. Example on the last loop before crash:

I'd really like to see something like v8.getHeapStatistics().total_available_size get closer to 0 just before the crash in order to debug my code.

Why is my app crashing with an out of memory error, even if it looks like I still have plenty of available memory?

Body:
I am trying to debug an out of memory error in NodeJS.

My script fetches data and pushes it into an array. It looks like this:

class Fetcher {
  async fetchAll () {
    const hits = []
    let page = 1
    while (true) {
      const result = await fetchData(page)
      hits.push(...result)
      if (!result.length) {
        break
      }
      page++
    }
    return hits
  }
}

When running this on a rather long database, I'm facing an out of memory error on pages 50+ (all the pages are approximately of the same size):

If I set up the --max-old-space-size to 8096, the error disappears. If I set it up to 2048, the error rises again.

However, I'm sure that my data is not that space consuming, and I am trying to see what operation exactly is taking so much space so I tried to debug memory usage with a function like this:

const printMemory = (logger: Logger) => {
  const formatMemory = memory => {
    return `${Math.round(memory / 1024 / 1024 * 100) / 100} MB`
  }
  const used = process.memoryUsage();
  const v8HeapStatistics = v8.getHeapStatistics()
  logger.debug(`V8 [used_heap_size]: ${formatMemory(v8HeapStatistics.used_heap_size)}`)
  logger.debug(`V8 [total_available_size]: ${formatMemory(v8HeapStatistics.total_available_size)}`)
  for (let key in used) {
    logger.debug(`${key} ${formatMemory(used[key])}`);
  }
}

This function is supposed to print the memory usage by the process and by V8.

When I run this function inside the loop (where the application crashes), it never exceeds 250MB of usage even if the memory usage grows over time. Example on the last loop before crash:

I'd really like to see something like v8.getHeapStatistics().total_available_size get closer to 0 just before the crash in order to debug my code.

Why is my app crashing with an out of memory error, even if it looks like I still have plenty of available memory?


问:
Is there a way to remove repetition when there is a common truth condition in python
I am trying to create a Class named poker that organizes the game poker. Right now, I am just creating a program that checks which hand you have. However, while doing this I saw that it is unnecessarily long, and I was wondering if it's possible to shorten it.

```<code>    def IsHighCard(self):
    if Poker.isStraightFlush is False and Poker.IsFourOfaKind is False and Poker.isFullHouse is False and Poker.IsFlush is False and Poker.IsStraight is False and Poker.isThreeOfaKind is False and Poker.IsTwoPairs is False and Poker.IsTwoPairs is False and Poker.IsOnePairs is False:
        return True
    else:
        return False
</code>```

I have so many False statements, and I was wondering if there is a way to make them less redundant.

Also, when referencing a method in my class that is in another method, should I use Poker.IsOnePairs  or Poker.IsOnePairs(self,hand).I'm not sure if I should include the parentheses.

PS: I don't see how that duplicate is relevant. The any() function only works for iterable, I'm not using iterable here.

Body:
I am trying to create a Class named poker that organizes the game poker. Right now, I am just creating a program that checks which hand you have. However, while doing this I saw that it is unnecessarily long, and I was wondering if it's possible to shorten it.

    def IsHighCard(self):
    if Poker.isStraightFlush is False and Poker.IsFourOfaKind is False and Poker.isFullHouse is False and Poker.IsFlush is False and Poker.IsStraight is False and Poker.isThreeOfaKind is False and Poker.IsTwoPairs is False and Poker.IsTwoPairs is False and Poker.IsOnePairs is False:
        return True
    else:
        return False

I have so many False statements, and I was wondering if there is a way to make them less redundant.

Also, when referencing a method in my class that is in another method, should I use Poker.IsOnePairs  or Poker.IsOnePairs(self,hand).I'm not sure if I should include the parentheses.

PS: I don't see how that duplicate is relevant. The any() function only works for iterable, I'm not using iterable here.


问:
Get Value DateTime Javascript "if statement" on asp.net
I'm trying to debug the code, for ExpiredDate & EffectiveDate the value is null. How to get value when a user picks a date?

Code

```<code>    function checkDate() {
        var ExpiredDate = document.getElementById("<%=dtExpiredDate.ClientID %>");
        var EffectiveDate = document.getElementById("<%=dtEffectiveDate.ClientID %>");
        var ddEmpStatus = document.getElementById('<%=ddEmpStatus.ClientID %>');
        var ddEmpStatusVal = ddEmpStatus.value;
        var ddEmpType = "<%=ddEmpType.ClientID %>";
        var ddvalue = $("#" + ddEmpType).val();

        if (ddEmpStatusVal == "Expatriate") {
            if (ExpiredDate < EffectiveDate) {
                alert("Expire Date is before Effective Date!");
                return false;
            }
        }
        if (ddEmpStatusVal == "National") {
            if (ddvalue != "Employee" && ddvalue != "Direct Contract") {
                if (ExpiredDate < EffectiveDate) {
                    alert("Expire Date is before Effective Date!");
                    return false;
                }
            }
        }
    }
</code>```

Body:
I'm trying to debug the code, for ExpiredDate & EffectiveDate the value is null. How to get value when a user picks a date?

Code

    function checkDate() {
        var ExpiredDate = document.getElementById("<%=dtExpiredDate.ClientID %>");
        var EffectiveDate = document.getElementById("<%=dtEffectiveDate.ClientID %>");
        var ddEmpStatus = document.getElementById('<%=ddEmpStatus.ClientID %>');
        var ddEmpStatusVal = ddEmpStatus.value;
        var ddEmpType = "<%=ddEmpType.ClientID %>";
        var ddvalue = $("#" + ddEmpType).val();

        if (ddEmpStatusVal == "Expatriate") {
            if (ExpiredDate < EffectiveDate) {
                alert("Expire Date is before Effective Date!");
                return false;
            }
        }
        if (ddEmpStatusVal == "National") {
            if (ddvalue != "Employee" && ddvalue != "Direct Contract") {
                if (ExpiredDate < EffectiveDate) {
                    alert("Expire Date is before Effective Date!");
                    return false;
                }
            }
        }
    }


问:
go-libp2p pubsub example not working in multithreaded environment
I am a beginner and am currently playing with the pubsub example from libp2p given here https://github.com/libp2p/go-libp2p/tree/master/examples/pubsub/basic-chat-with-rendezvous

I have been able to build the code and run the binary in different terminals and it works.
I am trying to automate this process from the main.go program itself where I can create a few threads to spin up new agents where they
publish messages to the network and the rest of the peers subscribe to it.
I have provided the modified code I have built currently but it doesnt seem to work. The peers cannot discover each other.

func main() {
    help := flag.Bool("help", false, "Display Help")
    cfg := parseFlags()

    if *help {
        fmt.Printf("Simple example for peer discovery using mDNS. mDNS is great when you have multiple peers in local LAN.")
        fmt.Printf("Usage: \n   Run './chat-with-mdns'\nor Run './chat-with-mdns -host [host] -port [port] -rendezvous [string] -pid [proto ID]'\n")

        os.Exit(0)
    }

    fmt.Printf("[*] Listening on: %s with port: %d\n", cfg.listenHost, cfg.listenPort)
    var wg sync.WaitGroup

    for i := 0; i < 5; i++ {
        // Spawn a thread for each iteration in the loop.
        // Pass 'i' into the goroutine's function
        //   in order to make sure each goroutine
        //   uses a different value for 'i'.
        wg.Add(5)
        go func(i int) {
            // At the end of the goroutine, tell the WaitGroup
            //   that another thread has completed.
            defer wg.Done()
            ctx := context.Background()
            r := rand.Reader

            // Creates a new RSA key pair for this host.
            prvKey, _, err := crypto.GenerateKeyPairWithReader(crypto.RSA, 2048, r)
            if err != nil {
                panic(err)
            }

            // 0.0.0.0 will listen on any interface device.
            sourceMultiAddr, _ := multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%d", cfg.listenHost, cfg.listenPort))

            // libp2p.New constructs a new libp2p Host.
            // Other options can be added here.
            host, err := libp2p.New(
                libp2p.ListenAddrs(sourceMultiAddr),
                libp2p.Identity(prvKey),
            )
            if err != nil {
                panic(err)
            }

            // Set a function as stream handler.
            // This function is called when a peer initiates a connection and starts a stream with this peer.
            host.SetStreamHandler(protocol.ID(cfg.ProtocolID), handleStream)

            fmt.Printf("\n[*] Your Multiaddress Is: /ip4/%s/tcp/%v/p2p/%s\n", cfg.listenHost, cfg.listenPort, host.ID().Pretty())

            peerChan := initMDNS(host, cfg.RendezvousString)
            for { // allows multiple peers to join
                peer := <-peerChan // will block untill we discover a peer // the code currently hangs here
                fmt.Println("Found peer:", peer, ", connecting")

                if err := host.Connect(ctx, peer); err != nil {
                    fmt.Println("Connection failed:", err)
                    continue
                }
                //** this part of the code is experimental and is not accessed by any thread yet **//
                stream, err := host.NewStream(ctx, peer.ID, protocol.ID(cfg.ProtocolID))

                if err != nil {
                    fmt.Println("Stream open failed", err)
                } else {
                    rw := bufio.NewReadWriter(bufio.NewReader(stream), bufio.NewWriter(stream))

                    go writeData(rw)
                    go readData(rw)
                    fmt.Println("Connected to:", peer)
                }
                //** this part of the code is experimental and is not accessed by any thread yet **//
            }

        }(i)
    }
    fmt.Println("exit")

    wg.Wait()

    fmt.Println("Finished for loop")
}
```

But this doesn't seem to work. Are there any examples I can look at currently for solving this error.

Body:
I am a beginner and am currently playing with the pubsub example from libp2p given here https://github.com/libp2p/go-libp2p/tree/master/examples/pubsub/basic-chat-with-rendezvous

I have been able to build the code and run the binary in different terminals and it works.
I am trying to automate this process from the main.go program itself where I can create a few threads to spin up new agents where they
publish messages to the network and the rest of the peers subscribe to it.
I have provided the modified code I have built currently but it doesnt seem to work. The peers cannot discover each other.

func main() {
    help := flag.Bool("help", false, "Display Help")
    cfg := parseFlags()

    if *help {
        fmt.Printf("Simple example for peer discovery using mDNS. mDNS is great when you have multiple peers in local LAN.")
        fmt.Printf("Usage: \n   Run './chat-with-mdns'\nor Run './chat-with-mdns -host [host] -port [port] -rendezvous [string] -pid [proto ID]'\n")

        os.Exit(0)
    }

    fmt.Printf("[*] Listening on: %s with port: %d\n", cfg.listenHost, cfg.listenPort)
    var wg sync.WaitGroup

    for i := 0; i < 5; i++ {
        // Spawn a thread for each iteration in the loop.
        // Pass 'i' into the goroutine's function
        //   in order to make sure each goroutine
        //   uses a different value for 'i'.
        wg.Add(5)
        go func(i int) {
            // At the end of the goroutine, tell the WaitGroup
            //   that another thread has completed.
            defer wg.Done()
            ctx := context.Background()
            r := rand.Reader

            // Creates a new RSA key pair for this host.
            prvKey, _, err := crypto.GenerateKeyPairWithReader(crypto.RSA, 2048, r)
            if err != nil {
                panic(err)
            }

            // 0.0.0.0 will listen on any interface device.
            sourceMultiAddr, _ := multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%d", cfg.listenHost, cfg.listenPort))

            // libp2p.New constructs a new libp2p Host.
            // Other options can be added here.
            host, err := libp2p.New(
                libp2p.ListenAddrs(sourceMultiAddr),
                libp2p.Identity(prvKey),
            )
            if err != nil {
                panic(err)
            }

            // Set a function as stream handler.
            // This function is called when a peer initiates a connection and starts a stream with this peer.
            host.SetStreamHandler(protocol.ID(cfg.ProtocolID), handleStream)

            fmt.Printf("\n[*] Your Multiaddress Is: /ip4/%s/tcp/%v/p2p/%s\n", cfg.listenHost, cfg.listenPort, host.ID().Pretty())

            peerChan := initMDNS(host, cfg.RendezvousString)
            for { // allows multiple peers to join
                peer := <-peerChan // will block untill we discover a peer // the code currently hangs here
                fmt.Println("Found peer:", peer, ", connecting")

                if err := host.Connect(ctx, peer); err != nil {
                    fmt.Println("Connection failed:", err)
                    continue
                }
                //** this part of the code is experimental and is not accessed by any thread yet **//
                stream, err := host.NewStream(ctx, peer.ID, protocol.ID(cfg.ProtocolID))

                if err != nil {
                    fmt.Println("Stream open failed", err)
                } else {
                    rw := bufio.NewReadWriter(bufio.NewReader(stream), bufio.NewWriter(stream))

                    go writeData(rw)
                    go readData(rw)
                    fmt.Println("Connected to:", peer)
                }
                //** this part of the code is experimental and is not accessed by any thread yet **//
            }

        }(i)
    }
    fmt.Println("exit")

    wg.Wait()

    fmt.Println("Finished for loop")
}

But this doesn't seem to work. Are there any examples I can look at currently for solving this error.


问:
TypeScript fails to convert `any` type to the strongly defined type
I have a data model in one of my projects which resembles (but it is not identical to) the data returned by an API. When I call that API (using any client, let's say axios), TypeScript fails to correctly assign the returned data to the corresponding type. To make it clear, let's look at this code:

```<code>type MyType = {
    name: string,
    isValid: boolean
}

const myType : MyType = JSON.parse(`
    {
        "name": "test"
    }
`)

console.log(myType.isValid)
</code>```

The mechanism of calling an API and assigning the response to a type is exactly as I described in the code. However, if we run this code we will see that isValid is not defined on the object. This is while isValid has a boolean type which should fall back to the default value of false. Does it mean that TypeScript does NOT have any casting mechanism and it simply acts as a linter in this case?

Body:
I have a data model in one of my projects which resembles (but it is not identical to) the data returned by an API. When I call that API (using any client, let's say axios), TypeScript fails to correctly assign the returned data to the corresponding type. To make it clear, let's look at this code:

type MyType = {
    name: string,
    isValid: boolean
}

const myType : MyType = JSON.parse(`
    {
        "name": "test"
    }
`)

console.log(myType.isValid)

The mechanism of calling an API and assigning the response to a type is exactly as I described in the code. However, if we run this code we will see that isValid is not defined on the object. This is while isValid has a boolean type which should fall back to the default value of false. Does it mean that TypeScript does NOT have any casting mechanism and it simply acts as a linter in this case?


问:
How do I make a post request with dynamic values for some attributes stored in external JSON file?
I have a BDD automation framework setup with Selenium WebDriver and Cucumber with Java. I have configured Rest Assured and I am currently using one JSON payload which is stored in an external JSON file. I am directly reading this JSON file into byte array and then converting the same to String and sending the payload to a post request.

Till now, everything was static and hence, this was working without any issue. However, now the requirement is to send a couple of attributes with dynamic values everytime I make a post call. I know how to send a complete dynamic payload using POJOs but I am looking for a different solution where I can read the payload from the same JSON file and can send dynamic values for few required attributes. Please let me know if this is possible.

Attaching the code for reference.

File which reads the JSON file and sends the payload to post request

public class AddOrderAPIActions {

    ConfigReader configReader = new ConfigReader();
    Properties prop;

    public AddOrderAPIActions() {

        prop = configReader.init_prop();

    }

    //Setting up the API URI

    public void setURI() {

        String URI = prop.getProperty("apiURI");
        RestAssured.baseURI = URI;
    }

    //Sending the request payload via POST method

    public String sendRequestPayload() throws IOException {

        //read data from local JSON file then store in byte array

        byte[] b = Files.readAllBytes(Paths.get("./src/test/resources/data/addOrder.json"));

        //convert byte array to string

        String bdy = new String(b);

        //input details with header and body

        Response response =  given().header("Content-type", "application/json").queryParam("api_key", prop.getProperty("apiKey")).body(bdy)

                //adding post method

                .when().post().then().log().all().extract().response();

        JsonPath jp = response.jsonPath();

        String shipmentNumber = jp.get("data.shipmentDetails[0].shipmentNumber");

        System.out.println("Shipment Number is "+ shipmentNumber);

        return shipmentNumber;

    }

}
```
<p><strong>The JSON file with payload</strong></p>
<pre class="lang-json prettyprint-override"><code>    [
        {
            "originDetails": {
                "originCode": "Dynamic_Value",
                "originStartTime": "",
                "originEndTime": "",
                "senderName": "Origin Name",
                "senderContactNumber": "9999999999",
                "senderAddress": "Bali, Indonesia",
                "senderPincode": "201001",
                "senderCity": "Delhi",
                "senderCountry": "India"
            },

    ]
</code>```

Here, I want to send a dynamic value for "originCode" attribute and rest of the attributes should be sent as read from the JSON file.

Thanks in advance.

Body:
I have a BDD automation framework setup with Selenium WebDriver and Cucumber with Java. I have configured Rest Assured and I am currently using one JSON payload which is stored in an external JSON file. I am directly reading this JSON file into byte array and then converting the same to String and sending the payload to a post request.

Till now, everything was static and hence, this was working without any issue. However, now the requirement is to send a couple of attributes with dynamic values everytime I make a post call. I know how to send a complete dynamic payload using POJOs but I am looking for a different solution where I can read the payload from the same JSON file and can send dynamic values for few required attributes. Please let me know if this is possible.

Attaching the code for reference.

File which reads the JSON file and sends the payload to post request

public class AddOrderAPIActions {

    ConfigReader configReader = new ConfigReader();
    Properties prop;

    public AddOrderAPIActions() {

        prop = configReader.init_prop();

    }

    //Setting up the API URI

    public void setURI() {

        String URI = prop.getProperty("apiURI");
        RestAssured.baseURI = URI;
    }

    //Sending the request payload via POST method

    public String sendRequestPayload() throws IOException {

        //read data from local JSON file then store in byte array

        byte[] b = Files.readAllBytes(Paths.get("./src/test/resources/data/addOrder.json"));

        //convert byte array to string

        String bdy = new String(b);

        //input details with header and body

        Response response =  given().header("Content-type", "application/json").queryParam("api_key", prop.getProperty("apiKey")).body(bdy)

                //adding post method

                .when().post().then().log().all().extract().response();

        JsonPath jp = response.jsonPath();

        String shipmentNumber = jp.get("data.shipmentDetails[0].shipmentNumber");

        System.out.println("Shipment Number is "+ shipmentNumber);

        return shipmentNumber;

    }

}

The JSON file with payload

    [
        {
            "originDetails": {
                "originCode": "Dynamic_Value",
                "originStartTime": "",
                "originEndTime": "",
                "senderName": "Origin Name",
                "senderContactNumber": "9999999999",
                "senderAddress": "Bali, Indonesia",
                "senderPincode": "201001",
                "senderCity": "Delhi",
                "senderCountry": "India"
            },

    ]

Here, I want to send a dynamic value for "originCode" attribute and rest of the attributes should be sent as read from the JSON file.

Thanks in advance.


问:
Getting error when upgrading webpack to 5.75.0 (latest)
When I tried to upgrade imports-loader to latest I am getting error as

this.getOptions is not a function

so i upgraded web pack from 4.29.6 to 5.75.0 and now I am getting below error:

**[webpack-cli] TypeError: webpack.optimize.OccurrenceOrderPlugin is not a constructor**

Can anyone pls suggest any solution for the above error??


问:
VSCode's built in runner or Code runner extension
I saw the Code runner extension but I don't what's the difference between the extension and the built in runner of VSCode. Which one should I use?

I haven't tried the extension yet. Should I try it?


问:
Truncating a table in Supabase/Postgres using JS
I have a table called events in Supabase. I'm looking for a way to truncate the table using JavaScript instead of the SQL Editor in Supabase.

I have a function that I call in my js file.

const resetEventTables = async () => {
    const { error } = await supabase.rpc('reset_event_related_tables');
    if (error) console.error(error);
};
```
<p>Running <code>reset_event_related_tables</code> executes this function in Supabase:</p>
<pre class="lang-sql prettyprint-override"><code>TRUNCATE TABLE events RESTART IDENTITY CASCADE;
</code>```

But it gives me an error when running the function in js

{
  code: '42501',
  details: null,
  hint: null,
  message: 'must be owner of sequence events_id_seq'
}
```

I can't seem to find the solution somewhere else. And yes, I used the secret API key for this when instantiating the supabase object.

Body:
I have a table called events in Supabase. I'm looking for a way to truncate the table using JavaScript instead of the SQL Editor in Supabase.

I have a function that I call in my js file.

const resetEventTables = async () => {
    const { error } = await supabase.rpc('reset_event_related_tables');
    if (error) console.error(error);
};

Running reset_event_related_tables executes this function in Supabase:

TRUNCATE TABLE events RESTART IDENTITY CASCADE;

But it gives me an error when running the function in js

{
  code: '42501',
  details: null,
  hint: null,
  message: 'must be owner of sequence events_id_seq'
}

I can't seem to find the solution somewhere else. And yes, I used the secret API key for this when instantiating the supabase object.


问:
How can i use G729 in gstreamer?
i am streaming the audio date using gstreamer and would like to use g729 codec for the audio.

gst-launch-1.0 alsasrc ! audioresample ! audio/x-raw, rate=8000 ! udpsink host=destination IP port=5000
using the above pipeline for normal audio streaming.

Title: How can i use G729 in gstreamer?


问:
Uncaught Error: Class 'Google\\ApiCore\\Serializer' not found in /mnt/e/htdocs/firestore-test/vendor/google/cloud-core/src/GrpcRequestWrapper.php:93
I'm having troubles with connecting to my firestore and read data from it.

HERE IS THE Error that occurred:

[Uncaught Error: Class 'Google\ApiCore\Serializer' not found in /mnt/e/htdocs/firestore-test/vendor/google/cloud-core/src/GrpcRequestWrapper.php:93 ]

Composer:

FIRESTORE DATABASE:

HERE IS MY CODE.

```<code><?php

require __DIR__.'/vendor/autoload.php';
use Google\Cloud\Firestore\FirestoreClient;

$firestore = new FirestoreClient();

$document01 = $firestore->collection("Book")->document("

m4ZEpHNcZN7NQW6Hn2Lg");

$document01Snap = $document01->snapshot();

echo $document01Snap->exists() ? "EXISTS" : "DOES NOT EXIST -_-";
echo PHP_EOL;
var_dump($document01Snap->data());
echo PHP_EOL;
</code>```

Body:
I'm having troubles with connecting to my firestore and read data from it.

HERE IS THE Error that occurred:

[Uncaught Error: Class 'Google\ApiCore\Serializer' not found in /mnt/e/htdocs/firestore-test/vendor/google/cloud-core/src/GrpcRequestWrapper.php:93 ]

Composer:

FIRESTORE DATABASE:

HERE IS MY CODE.

<?php

require __DIR__.'/vendor/autoload.php';
use Google\Cloud\Firestore\FirestoreClient;

$firestore = new FirestoreClient();

$document01 = $firestore->collection("Book")->document("

m4ZEpHNcZN7NQW6Hn2Lg");

$document01Snap = $document01->snapshot();

echo $document01Snap->exists() ? "EXISTS" : "DOES NOT EXIST -_-";
echo PHP_EOL;
var_dump($document01Snap->data());
echo PHP_EOL;


问:
Qt iOS app crash in completion handler callback with EXC_BAD_ACCESS
I'm writing a Qt app on iOS which uses the MLKit FaceDetector. I have a FaceDetector class which has the following method:

void FaceDetector::runFaceDetection(const QImage &image)
{
  // initialize a MLKFaceDetector
  [mlkFaceDetector processImage:visionImage
                      completion:^(NSArray<MLKFace *> *_Nullable faces, NSError *_Nullable error) {

       if (error != nil) {
           // process error
       }

       DetectionResults results; // DetectionResults is just another of my classes

       // process results using faces

       setResults(results);
       emit detectionComplete(true);
    }];
}
```
<p>where <code>setResults</code> and <code>detectionComplete</code> are other member function of the FaceDetector</p>
<p>I use the FaceDetector in a <code>FaceDetectionFilter</code> class:</p>
<p>FaceDetectionFilter.h</p>
<pre class="lang-cpp prettyprint-override"><code>class FaceDetectionFilter : public QAbstractVideoFilter {
private:
  FaceDetector        m_FaceDetector;
}

</code>```

Basically I use the FaceDetectionFilter in my QML with Camera and VideoOutput component, and the VideoOutput is able to detect faces, so far so good.

However, the app occasionally crashes when I close my camera page while the filter is running, i.e. the page is popped out of the app's stackview. XCode shows EXC_BAD_ACCESS error in the setResults or detectionComplete line in the runFaceDetection method.

I think this is due to when the camera page is popped, the FaceDetectionFilter and thus the FaceDetector object is destroyed. But once in a while the completion handler callback is executed after the object destruction, resulting in illegal memory access.

I tried to fix this by adding a m_Initialized boolean member to the FaceDetector class, and setting it to false in the destructor:

FaceDetector ::~FaceDetector ()
{
  m_Initialized = false;
}
```
<p>and in the runFaceDetection method:</p>
<pre class="lang-cpp prettyprint-override"><code>void FaceDetector::runFaceDetection(const QImage &image)
{
  // initialize a MLKFaceDetector
  [mlkFaceDetector processImage:visionImage
                      completion:^(NSArray<MLKFace *> *_Nullable faces, NSError *_Nullable error) {

       if (!m_Initialized) {
           qDebug() << "FaceDetector destroyed, stop processing";
           return;
       }
       if (error != nil) {
           // process error
       }
       // continue processing
    }];
}
</code>```

This seems to fix the crash, and I can see that when I close the camera, occasionally the "stop processing" line is printed.

However, very rarely the app still crashes and it seems the m_Initialized guard is not working (but I've only been able to reproduce this once, it's so rare that I'm not even sure if that really happened). I think this rare case occurs when the FaceDetector destruction happens between the m_Initialized guard and the setResults line, therefore making the guard check fail.

My question is: are there any other better way to solve this issue? I've searched online for a while and found some answers from the Objective C side related to the use of __block  or the concept of "retain" the object. Or, from C++ side the use of shared_ptr to manage object lifetime. I guess the key is find a way to know if the object itself is destroyed in the completion handler, or am I missing something?

Body:
I'm writing a Qt app on iOS which uses the MLKit FaceDetector. I have a FaceDetector class which has the following method:

void FaceDetector::runFaceDetection(const QImage &image)
{
  // initialize a MLKFaceDetector
  [mlkFaceDetector processImage:visionImage
                      completion:^(NSArray<MLKFace *> *_Nullable faces, NSError *_Nullable error) {

       if (error != nil) {
           // process error
       }

       DetectionResults results; // DetectionResults is just another of my classes

       // process results using faces

       setResults(results);
       emit detectionComplete(true);
    }];
}

where setResults and detectionComplete are other member function of the FaceDetector

I use the FaceDetector in a FaceDetectionFilter class:

FaceDetectionFilter.h

class FaceDetectionFilter : public QAbstractVideoFilter {
private:
  FaceDetector        m_FaceDetector;
}

Basically I use the FaceDetectionFilter in my QML with Camera and VideoOutput component, and the VideoOutput is able to detect faces, so far so good.

However, the app occasionally crashes when I close my camera page while the filter is running, i.e. the page is popped out of the app's stackview. XCode shows EXC_BAD_ACCESS error in the setResults or detectionComplete line in the runFaceDetection method.

I think this is due to when the camera page is popped, the FaceDetectionFilter and thus the FaceDetector object is destroyed. But once in a while the completion handler callback is executed after the object destruction, resulting in illegal memory access.

I tried to fix this by adding a m_Initialized boolean member to the FaceDetector class, and setting it to false in the destructor:

FaceDetector ::~FaceDetector ()
{
  m_Initialized = false;
}

and in the runFaceDetection method:

void FaceDetector::runFaceDetection(const QImage &image)
{
  // initialize a MLKFaceDetector
  [mlkFaceDetector processImage:visionImage
                      completion:^(NSArray<MLKFace *> *_Nullable faces, NSError *_Nullable error) {

       if (!m_Initialized) {
           qDebug() << "FaceDetector destroyed, stop processing";
           return;
       }
       if (error != nil) {
           // process error
       }
       // continue processing
    }];
}

This seems to fix the crash, and I can see that when I close the camera, occasionally the "stop processing" line is printed.

However, very rarely the app still crashes and it seems the m_Initialized guard is not working (but I've only been able to reproduce this once, it's so rare that I'm not even sure if that really happened). I think this rare case occurs when the FaceDetector destruction happens between the m_Initialized guard and the setResults line, therefore making the guard check fail.

My question is: are there any other better way to solve this issue? I've searched online for a while and found some answers from the Objective C side related to the use of __block  or the concept of "retain" the object. Or, from C++ side the use of shared_ptr to manage object lifetime. I guess the key is find a way to know if the object itself is destroyed in the completion handler, or am I missing something?


问:
fastapi instrument with opentelemetry.propagators.cloud_trace_propagator
Just looking around to see if anyone has a working POC using the FastApi auto instruments along with GCP. Turns out that the fastApi Middleware makes a call to the CloudTraceFormatPropagator when we set

```<code>set_global_textmap(CloudTraceFormatPropagator())

</code>```

however the carrier is not correct and returns to many values ( carrier in this case is a HTTPScope

ive tried the below,  I need to be able to do distributed tracing which you can see within the foobar

```<code>import fastapi
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
import time
import requests

from starlette.middleware.base import BaseHTTPMiddleware
from typing import Callable,  Tuple
from uuid import uuid4

from fastapi import Request
from opentelemetry import metrics, trace
from opentelemetry.exporter.cloud_monitoring import (
    CloudMonitoringMetricsExporter,
)
from opentelemetry.exporter.cloud_trace import CloudTraceSpanExporter
from opentelemetry.propagate import set_global_textmap, inject, extract
from opentelemetry.propagators.cloud_trace_propagator import (
    CloudTraceFormatPropagator,
)
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor,SimpleSpanProcessor

set_global_textmap(CloudTraceFormatPropagator())

resource = Resource.create(
    {
        "service.name": "fastapi_e2e_server",
        "service.namespace": "examples",
        "service.instance.id": "instance123",
    }
)

tracer_provider = TracerProvider()
cloud_trace_exporter = CloudTraceSpanExporter()
tracer_provider.add_span_processor(
    # BatchSpanProcessor buffers spans and sends them in batches in a
    # background thread. The default parameters are sensible, but can be
    # tweaked to optimize your performance
    SimpleSpanProcessor(cloud_trace_exporter)
)

meter_provider = MeterProvider(
    metric_readers=[
        PeriodicExportingMetricReader(
            CloudMonitoringMetricsExporter(), export_interval_millis=5000
        )
    ],
    resource=resource,
)

trace.set_tracer_provider(tracer_provider)
metrics.set_meter_provider(meter_provider)

tracer = trace.get_tracer(__name__)
meter = metrics.get_meter(__name__)

app = fastapi.FastAPI(title="whata")

def the_injection():
    headers={}
    inject(headers)
    return headers

@app.get("/foobar")
def foobar(request: Request):
    with tracer.start_as_current_span("Get Alerts Parent span") as parent:
        span = trace.get_current_span()
        span.add_event("endpoint Called", {
            "url": request.url.path
            })

        with tracer.start_as_current_span("Get Alerts child span") as child:
            head = the_injection()
            res = requests.get("http://0.0.0.0:8082/target", headers=head)
        return res.text

FastAPIInstrumentor.instrument_app(app)

</code>```

Body:
Just looking around to see if anyone has a working POC using the FastApi auto instruments along with GCP. Turns out that the fastApi Middleware makes a call to the CloudTraceFormatPropagator when we set

set_global_textmap(CloudTraceFormatPropagator())

however the carrier is not correct and returns to many values ( carrier in this case is a HTTPScope

ive tried the below,  I need to be able to do distributed tracing which you can see within the foobar

import fastapi
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
import time
import requests

from starlette.middleware.base import BaseHTTPMiddleware
from typing import Callable,  Tuple
from uuid import uuid4

from fastapi import Request
from opentelemetry import metrics, trace
from opentelemetry.exporter.cloud_monitoring import (
    CloudMonitoringMetricsExporter,
)
from opentelemetry.exporter.cloud_trace import CloudTraceSpanExporter
from opentelemetry.propagate import set_global_textmap, inject, extract
from opentelemetry.propagators.cloud_trace_propagator import (
    CloudTraceFormatPropagator,
)
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor,SimpleSpanProcessor

set_global_textmap(CloudTraceFormatPropagator())

resource = Resource.create(
    {
        "service.name": "fastapi_e2e_server",
        "service.namespace": "examples",
        "service.instance.id": "instance123",
    }
)

tracer_provider = TracerProvider()
cloud_trace_exporter = CloudTraceSpanExporter()
tracer_provider.add_span_processor(
    # BatchSpanProcessor buffers spans and sends them in batches in a
    # background thread. The default parameters are sensible, but can be
    # tweaked to optimize your performance
    SimpleSpanProcessor(cloud_trace_exporter)
)

meter_provider = MeterProvider(
    metric_readers=[
        PeriodicExportingMetricReader(
            CloudMonitoringMetricsExporter(), export_interval_millis=5000
        )
    ],
    resource=resource,
)

trace.set_tracer_provider(tracer_provider)
metrics.set_meter_provider(meter_provider)

tracer = trace.get_tracer(__name__)
meter = metrics.get_meter(__name__)

app = fastapi.FastAPI(title="whata")

def the_injection():
    headers={}
    inject(headers)
    return headers

@app.get("/foobar")
def foobar(request: Request):
    with tracer.start_as_current_span("Get Alerts Parent span") as parent:
        span = trace.get_current_span()
        span.add_event("endpoint Called", {
            "url": request.url.path
            })

        with tracer.start_as_current_span("Get Alerts child span") as child:
            head = the_injection()
            res = requests.get("http://0.0.0.0:8082/target", headers=head)
        return res.text

FastAPIInstrumentor.instrument_app(app)


问:
error C2131: expression did not evaluate to a constant int num[count];
```<code>#include <stdio.h>

int main() {
    int i, count;
    int sum = 0;
    scanf_s("%d", &count);
    int num[count];
    for (i = 1; i <= count; i++) {
        printf("Enter %d number: \n", i);
        scanf_s("%d", &num[i]);
        sum = sum + num[i];
    }
    int average = sum / count;
    printf("Average = %d", average);
}
</code>```

Getting error while running this code in visual studio 17. How to write
int num[count];

Body:
#include <stdio.h>

int main() {
    int i, count;
    int sum = 0;
    scanf_s("%d", &count);
    int num[count];
    for (i = 1; i <= count; i++) {
        printf("Enter %d number: \n", i);
        scanf_s("%d", &num[i]);
        sum = sum + num[i];
    }
    int average = sum / count;
    printf("Average = %d", average);
}

Getting error while running this code in visual studio 17. How to write
int num[count];


问:
Need help matching descriptions in Kubernetes YAML file
I am reading Core Kubernetes by Vyas and Love.  This is from page 141, section 7.3.  It seems that the annotations and the location indicated by the arrows don't match. I have redone the matching using the numbers and brackets.  Could someone tell me if I have done anything wrong?  TIA!