问:
aws upload object to S3 bucket and pass details of data to lambda
Working my way through tutorials for AWS...So ive created an S3 bucket which when a file is dropped into it calls my lambda 'testHelloWorld' which sends an email...this all works fine (see below)

```<code> 'use strict';

console.log('Loading function');

var aws = require('aws-sdk');
var ses = new aws.SES({
   region: 'us-west-2'
});

exports.handler = function(event, context) {
    console.log("Incoming: ", event);
   // var output = querystring.parse(event);

    var eParams = {
        Destination: {
            ToAddresses: ["johnb@hotmail.com"]
        },
        Message: {
            Body: {
                Text: {
                    Data: "Hey! What is up?"
                }
            },
            Subject: {
                Data: "Email Subject!!!"
            }
        },
        Source: "johnb@hotmail.com"
    };

    console.log('===SENDING EMAIL===');
    var email = ses.sendEmail(eParams, function(err, data){
        if(err) console.log(err);
        else {
            console.log("===EMAIL SENT===");
            console.log(data);

            console.log("EMAIL CODE END");
            console.log('EMAIL: ', email);
            context.succeed(event);

        }
    });

};
</code>```

but I want to extend the email to include data on the file that was uploaded to the bucket. I have found How to trigger my Lambda Function once the file is uploaded to s3 bucket which gives a node.js code snippet which should capture the data. I have tried to import this into my existing lambda

```<code> 'use strict';

console.log('Loading function');

var aws = require('aws-sdk');
var ses = new aws.SES({
   region: 'us-west-2'
});
var s3 = new aws.S3({ apiVersion: '2006-03-01', accessKeyId: process.env.ACCESS_KEY, secretAccessKey: process.env.SECRET_KEY, region: process.env.LAMBDA_REGION });

exports.handler = function(event, context, exit){
    console.log("Incoming: ", event);
   // var output = querystring.parse(event);

 // Get the object from the event and show its content type
   // const bucket = event.Records[0].s3.bucket.name;
   // const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
    const params = {
       Bucket: 'bucketName',
       Key: 'keyName',
       Source : 'SourceName',
       Destination : 'DestinationName',
       Message : 'MessageName'
    };

     s3.getObject(function(err, data){
         if (err) {
           console.log('ERROR ' + err);
          // exit(err);
         } else {
           // the data has the content of the uploaded file
           var eParams = {
        Destination: {
            ToAddresses: ["johnboy@hotmail.com"]
        },
        Message: {
            Body: {
                Text: {
                    Data: data
                }
            },
            Subject: {
                Data: "Email Subject!!!"
            }
        },
        Source: "johnboy@hotmail.com"
    };
         }
     });

    console.log('===SENDING EMAIL===');
    var email = ses.sendEmail(eParams, function(err, data){
        if(err) console.log(err);
        else {
            console.log("===EMAIL SENT===");
            console.log(data);

            console.log("EMAIL CODE END");
            console.log('EMAIL: ', email);
            context.succeed(event);

        }
    });

};
</code>```

but this is failing on the params

```<code>message: 'There were 3 validation errors:
</code>```

* MissingRequiredParameter: Missing required key \'Source\' in params
* MissingRequiredParameter: Missing required key \'Destination\' in params
* MissingRequiredParameter: Missing required key \'Message\' in params',
  code: 'MultipleValidationErrors',
  errors:

These source, destination and message are listed in the params, are they not correctly formatted and it isnt picking them up?

I cant find much online....any help appreciated

UPDATE
Ok iv got it working without failing...if i use the test function in the lambda with the following code...

```<code>   'use strict';

console.log('Loading function');

var aws = require('aws-sdk');
var ses = new aws.SES({
   region: 'us-west-2'
});

var s3 = new aws.S3({ apiVersion: '2006-03-01', accessKeyId: process.env.ACCESS_KEY, secretAccessKey: process.env.SECRET_KEY, region: process.env.LAMBDA_REGION });

exports.handler = function(event, context) {
    console.log("Incoming: ", event);
   // var output = querystring.parse(event);

   var testData = null;

   // Get the object from the event and show its content type
   // const bucket = event.Records[0].s3.bucket.name;
   // const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
    const params = {
       Bucket: 'bucket',
       Key: 'key',
    };

     s3.getObject(params, function(err, data){
         if (err) {
           console.log('ERROR ' + err);
           exit(err);
         } else {
           testData = data;
         }
     });

    var eParams = {
        Destination: {
            ToAddresses: ["jim@him.com"]
        },
        Message: {
            Body: {
                Text: { Data: 'testData2' + testData}
            },
            Subject: {
                Data: "Email Subject!!!"
            }
        },
        Source: "jim@him.com"
    };

    console.log('===SENDING EMAIL===');
    var email = ses.sendEmail(eParams, function(err, data){
        if(err) console.log(err);
        else {
            console.log("===EMAIL SENT===");
            console.log(data);

            console.log("EMAIL CODE END");
            console.log('EMAIL: ', email);
            context.succeed(event);

        }
    });

};
</code>```

I get the email with the body- testData2null

So I tried uploading an image through the s3 bucket and I still get the email with the body testData2null

is there anyway to debug this further or does anyone kno who it is saying null. I never actually tested the code from the other post which passes the data over to the email I just assumed it would work. Does anyone else know who to obtain the data from the upload please? thanks

答:
You need to read on how Nodejs works. It is event based and depends on callbacks and promises. You should do -

```<code> s3.getObject(params, function(err, data){
      //This is your callback for s3 API call. DO stuff here
     if (err) {
       console.log('ERROR ' + err);
       exit(err);
     } else {
       testData = data;
        // Got your data. Send the mail here
     }
 });
</code>```

I have added my comments in code above. Since Nodejs is single threaded it will make S3 api call and go ahead. When it is sending mail s3 api call is not complete so data is null. It is better to use promises here.

Anyway read up on callback and promises in nodejs and how it works. But hope this answers your logical error.

Body:
Working my way through tutorials for AWS...So ive created an S3 bucket which when a file is dropped into it calls my lambda 'testHelloWorld' which sends an email...this all works fine (see below)

 'use strict';

console.log('Loading function');

var aws = require('aws-sdk');
var ses = new aws.SES({
   region: 'us-west-2'
});

exports.handler = function(event, context) {
    console.log("Incoming: ", event);
   // var output = querystring.parse(event);

    var eParams = {
        Destination: {
            ToAddresses: ["johnb@hotmail.com"]
        },
        Message: {
            Body: {
                Text: {
                    Data: "Hey! What is up?"
                }
            },
            Subject: {
                Data: "Email Subject!!!"
            }
        },
        Source: "johnb@hotmail.com"
    };

    console.log('===SENDING EMAIL===');
    var email = ses.sendEmail(eParams, function(err, data){
        if(err) console.log(err);
        else {
            console.log("===EMAIL SENT===");
            console.log(data);

            console.log("EMAIL CODE END");
            console.log('EMAIL: ', email);
            context.succeed(event);

        }
    });

};

but I want to extend the email to include data on the file that was uploaded to the bucket. I have found How to trigger my Lambda Function once the file is uploaded to s3 bucket which gives a node.js code snippet which should capture the data. I have tried to import this into my existing lambda

 'use strict';

console.log('Loading function');

var aws = require('aws-sdk');
var ses = new aws.SES({
   region: 'us-west-2'
});
var s3 = new aws.S3({ apiVersion: '2006-03-01', accessKeyId: process.env.ACCESS_KEY, secretAccessKey: process.env.SECRET_KEY, region: process.env.LAMBDA_REGION });

exports.handler = function(event, context, exit){
    console.log("Incoming: ", event);
   // var output = querystring.parse(event);

 // Get the object from the event and show its content type
   // const bucket = event.Records[0].s3.bucket.name;
   // const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
    const params = {
       Bucket: 'bucketName',
       Key: 'keyName',
       Source : 'SourceName',
       Destination : 'DestinationName',
       Message : 'MessageName'
    };

     s3.getObject(function(err, data){
         if (err) {
           console.log('ERROR ' + err);
          // exit(err);
         } else {
           // the data has the content of the uploaded file
           var eParams = {
        Destination: {
            ToAddresses: ["johnboy@hotmail.com"]
        },
        Message: {
            Body: {
                Text: {
                    Data: data
                }
            },
            Subject: {
                Data: "Email Subject!!!"
            }
        },
        Source: "johnboy@hotmail.com"
    };
         }
     });

    console.log('===SENDING EMAIL===');
    var email = ses.sendEmail(eParams, function(err, data){
        if(err) console.log(err);
        else {
            console.log("===EMAIL SENT===");
            console.log(data);

            console.log("EMAIL CODE END");
            console.log('EMAIL: ', email);
            context.succeed(event);

        }
    });

};

but this is failing on the params

message: 'There were 3 validation errors:

* MissingRequiredParameter: Missing required key \'Source\' in params
* MissingRequiredParameter: Missing required key \'Destination\' in params
* MissingRequiredParameter: Missing required key \'Message\' in params',
  code: 'MultipleValidationErrors',
  errors:

These source, destination and message are listed in the params, are they not correctly formatted and it isnt picking them up?

I cant find much online....any help appreciated

UPDATE
Ok iv got it working without failing...if i use the test function in the lambda with the following code...

   'use strict';

console.log('Loading function');

var aws = require('aws-sdk');
var ses = new aws.SES({
   region: 'us-west-2'
});

var s3 = new aws.S3({ apiVersion: '2006-03-01', accessKeyId: process.env.ACCESS_KEY, secretAccessKey: process.env.SECRET_KEY, region: process.env.LAMBDA_REGION });

exports.handler = function(event, context) {
    console.log("Incoming: ", event);
   // var output = querystring.parse(event);

   var testData = null;

   // Get the object from the event and show its content type
   // const bucket = event.Records[0].s3.bucket.name;
   // const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
    const params = {
       Bucket: 'bucket',
       Key: 'key',
    };

     s3.getObject(params, function(err, data){
         if (err) {
           console.log('ERROR ' + err);
           exit(err);
         } else {
           testData = data;
         }
     });

    var eParams = {
        Destination: {
            ToAddresses: ["jim@him.com"]
        },
        Message: {
            Body: {
                Text: { Data: 'testData2' + testData}
            },
            Subject: {
                Data: "Email Subject!!!"
            }
        },
        Source: "jim@him.com"
    };

    console.log('===SENDING EMAIL===');
    var email = ses.sendEmail(eParams, function(err, data){
        if(err) console.log(err);
        else {
            console.log("===EMAIL SENT===");
            console.log(data);

            console.log("EMAIL CODE END");
            console.log('EMAIL: ', email);
            context.succeed(event);

        }
    });

};

I get the email with the body- testData2null

So I tried uploading an image through the s3 bucket and I still get the email with the body testData2null

is there anyway to debug this further or does anyone kno who it is saying null. I never actually tested the code from the other post which passes the data over to the email I just assumed it would work. Does anyone else know who to obtain the data from the upload please? thanks

Body:
You need to read on how Nodejs works. It is event based and depends on callbacks and promises. You should do -

 s3.getObject(params, function(err, data){
      //This is your callback for s3 API call. DO stuff here
     if (err) {
       console.log('ERROR ' + err);
       exit(err);
     } else {
       testData = data;
        // Got your data. Send the mail here
     }
 });

I have added my comments in code above. Since Nodejs is single threaded it will make S3 api call and go ahead. When it is sending mail s3 api call is not complete so data is null. It is better to use promises here.

Anyway read up on callback and promises in nodejs and how it works. But hope this answers your logical error.


来源: stackexchange

问:
Encoding issue in files names and plots labels axis while using a for loop

Hi everyone,

I'm using a for loop in a function to plot  biological indicators. My ggsave command is in the function;

My issue is pretty simple :
when I'm using my loop my plot names (.png) and the axis labels are not written with the good encoding .

```<code>  fun_dens_spe_pm<-function (donnees_dens_sp_1,pm_peche){

dens_sp<-subset(donnees_dens_sp_1, donnees_dens_sp_1$CodeOnema == pm_peche)
dens_sp$Espece<-as.character(dens_sp$nom_sp)

list_sp_pm<-as.list(unique(dens_sp$nom_sp))

# # Test
# Esp<-list_sp_pm[[1]]

dens_par_sp<-function (dens_sp, Esp){

  # Selection de l'espèce i présente sur la station
  dens_sp_i<-subset(dens_sp,dens_sp$nom_sp == Esp)

  # Selection des champs pour création des graphiques

  dens_sp_i<- dens_sp_i[,c("CodeOnema","Date","densite_sp")]
  dens_sp_i$Date<-as.numeric(dens_sp_i$Date)

  # Test du nombre d'années ou l'espèce i est présente sur la chronique
  ifelse(

    # Condition : présence de l'espèce inférieure ou égale à 2 années
    nrow(dens_sp_i) <= 2,

  # Si oui : Graphique si présence "excetpionnelle" d'une espèce
  p_dens_sp_pm <- ggplot(data = dens_sp_i, aes(x= Date, y = densite_sp)) +
    geom_point(size = 3,col = "firebrick") +
    geom_text(aes(x= Date, y = densite_sp,fill = densite_sp),
              label=paste0("Présence exceptionnelle de l'espèce en","",Date), color="firebrick") +
    scale_x_continuous(breaks = scales::pretty_breaks(n = 6))+
    scale_y_continuous(breaks = scales::pretty_breaks(n = 12))+
    labs(x="Années",y ="Densité spécifique (ind/100 m2)") +
    theme(text = element_text(size=11),plot.title = element_text(hjust = 0.5),legend.position="none")+
    ggtitle(paste0("Evolution de la densité de l'espèce"," ",Esp," ",  "sur la station"," ",pm_peche)),

 # Si non : Graphique  si présence "continue" sur la série temporelle

 p_dens_sp_pm<-ggplot(data = dens_sp_i, aes(x= Date, y = densite_sp,fill = densite_sp)) +
    geom_line(size = 1,col = "dodgerblue2",linejoin = "round")+
    geom_point(size = 3,col = "firebrick") +
    scale_x_continuous(breaks = scales::pretty_breaks(n = 6))+
    scale_y_continuous(breaks = scales::pretty_breaks(n = 12))+
    labs(x="Années",y ="Densité spécifique (ind/100 m2)") +
    theme(text = element_text(size=11),plot.title = element_text(hjust = 0.5),legend.position="none")+
    ggtitle(paste0("Evolution de la densité de l'espèce"," ",Esp," ",  "sur la station"," ",pm_peche)))

  # Visualisation du graphique
  p_dens_sp_pm

  # Enregistrement du graphe

  nom_graphe <-paste0("Densité_sp","_",Esp,"_",pm_peche,".png")
  ggsave(plot = p_dens_sp_pm,filename = nom_graphe,device ="png",
         path = paste0("./EEE/graphes/sta_RHP_complete/indicateurs/densite_relative/",pm_peche),
         width = 25, height = 18, units = "cm")
}

# Boucle d'application de la fonction

for (i in seq.int(list_sp_pm)) {

  graphe<-dens_par_sp(dens_sp,list_sp_pm[[i]])
}

}
</code>```

However, when I'm not using the loop everything is okay and I have no encoding issue (See the images in atached files)

without_loop
with_loop

What do I need to change in my code to solve that?

Thanks

strong text

答:
I finally found the solution :

On windows R's source function does not work with files that includes characters that are not part of the current system encoding.
To ensure that you are working with the right encoding use :

```<code>> Sys.setlocale()
</code>```

In my case I got the following :

```<code>[1]"LC_COLLATE=French_France.1252;LC_CTYPE=French_France.1252;LC_MONETARY=French_France.1252;LC_NUMERIC=C;LC_TIME=French_France.1252"
</code>```

My system encoding is "WINDOWS-1252" but my functions' scripts seem to be written in an other one (UTF-8).

Go to

Tools > Global Options > Code > Saving

and set the right  default text encoding. When you reopen your scripts, you just need to replace special characters by the desired one's and don't forget to save.

ContentLicense: CC BY-SA 3.0

Body:
Hi everyone,

I'm using a for loop in a function to plot  biological indicators. My ggsave command is in the function;

My issue is pretty simple :
when I'm using my loop my plot names (.png) and the axis labels are not written with the good encoding .

  fun_dens_spe_pm<-function (donnees_dens_sp_1,pm_peche){

dens_sp<-subset(donnees_dens_sp_1, donnees_dens_sp_1$CodeOnema == pm_peche)
dens_sp$Espece<-as.character(dens_sp$nom_sp)

list_sp_pm<-as.list(unique(dens_sp$nom_sp))

# # Test
# Esp<-list_sp_pm[[1]]

dens_par_sp<-function (dens_sp, Esp){

  # Selection de l'espèce i présente sur la station
  dens_sp_i<-subset(dens_sp,dens_sp$nom_sp == Esp)

  # Selection des champs pour création des graphiques

  dens_sp_i<- dens_sp_i[,c("CodeOnema","Date","densite_sp")]
  dens_sp_i$Date<-as.numeric(dens_sp_i$Date)

  # Test du nombre d'années ou l'espèce i est présente sur la chronique
  ifelse(

    # Condition : présence de l'espèce inférieure ou égale à 2 années
    nrow(dens_sp_i) <= 2,

  # Si oui : Graphique si présence "excetpionnelle" d'une espèce
  p_dens_sp_pm <- ggplot(data = dens_sp_i, aes(x= Date, y = densite_sp)) +
    geom_point(size = 3,col = "firebrick") +
    geom_text(aes(x= Date, y = densite_sp,fill = densite_sp),
              label=paste0("Présence exceptionnelle de l'espèce en","",Date), color="firebrick") +
    scale_x_continuous(breaks = scales::pretty_breaks(n = 6))+
    scale_y_continuous(breaks = scales::pretty_breaks(n = 12))+
    labs(x="Années",y ="Densité spécifique (ind/100 m2)") +
    theme(text = element_text(size=11),plot.title = element_text(hjust = 0.5),legend.position="none")+
    ggtitle(paste0("Evolution de la densité de l'espèce"," ",Esp," ",  "sur la station"," ",pm_peche)),

 # Si non : Graphique  si présence "continue" sur la série temporelle

 p_dens_sp_pm<-ggplot(data = dens_sp_i, aes(x= Date, y = densite_sp,fill = densite_sp)) +
    geom_line(size = 1,col = "dodgerblue2",linejoin = "round")+
    geom_point(size = 3,col = "firebrick") +
    scale_x_continuous(breaks = scales::pretty_breaks(n = 6))+
    scale_y_continuous(breaks = scales::pretty_breaks(n = 12))+
    labs(x="Années",y ="Densité spécifique (ind/100 m2)") +
    theme(text = element_text(size=11),plot.title = element_text(hjust = 0.5),legend.position="none")+
    ggtitle(paste0("Evolution de la densité de l'espèce"," ",Esp," ",  "sur la station"," ",pm_peche)))

  # Visualisation du graphique
  p_dens_sp_pm

  # Enregistrement du graphe

  nom_graphe <-paste0("Densité_sp","_",Esp,"_",pm_peche,".png")
  ggsave(plot = p_dens_sp_pm,filename = nom_graphe,device ="png",
         path = paste0("./EEE/graphes/sta_RHP_complete/indicateurs/densite_relative/",pm_peche),
         width = 25, height = 18, units = "cm")
}

# Boucle d'application de la fonction

for (i in seq.int(list_sp_pm)) {

  graphe<-dens_par_sp(dens_sp,list_sp_pm[[i]])
}

}

However, when I'm not using the loop everything is okay and I have no encoding issue (See the images in atached files)

without_loop
with_loop

What do I need to change in my code to solve that?

Thanks

strong text

Body:
I finally found the solution :

On windows R's source function does not work with files that includes characters that are not part of the current system encoding.
To ensure that you are working with the right encoding use :

> Sys.setlocale()

In my case I got the following :

[1]"LC_COLLATE=French_France.1252;LC_CTYPE=French_France.1252;LC_MONETARY=French_France.1252;LC_NUMERIC=C;LC_TIME=French_France.1252"

My system encoding is "WINDOWS-1252" but my functions' scripts seem to be written in an other one (UTF-8).

Go to

Tools > Global Options > Code > Saving

and set the right  default text encoding. When you reopen your scripts, you just need to replace special characters by the desired one's and don't forget to save.


问:
Declaring char array results segmentation fault in C programming language
I was just creating simple implementation where I read input.txt file which has one line of code containing two numbers separated by space (e.g. 4 4).

I was trying to separate them by delimiting with space first.

And I was trying to use the first value as a size of char array.

However it keeps causing segmentation fault but I have no idea.

```<code>int main(int argc, char **argv){

int number;
int i = 0;
char *token;
char buf[100];
int tempNum[2];

// Open file
FILE * fPointer;
fPointer = fopen("input.txt", "r");

// Read first line
fgets(buf, 1024, fPointer);
token = strtok(buf, " ");
number = atoi(token);

char charArray[number];

while(token != NULL){
    tempNum[i] = atoi(token);
    token = strtok(NULL, "\n");
    printf("%d\n", tempNum[i]);
    i++;
}
</code>```

If I comment out "char charArray[number]" it does not cause segmentation fault. If I comment out only the while loop, it does not cause segmentation fault. But I cannot figure out why it is causing the segmentation in the first place. Please help.

Thank you in advance.

答:
Something like this?</p>

```<code>#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>
#include <string.h>

#define BUF_SIZE 1024
#define MAX_INPUT 2

int main(int argc, char **argv) {
    char *token = NULL;
    char *next_token = NULL;
    char buf[BUF_SIZE];
    long tempNum[MAX_INPUT] = { 0 };
    const char *delim = " ";
    char * end = NULL;

    // Init vars
    memset(buf, 0, BUF_SIZE);

    // Open file
    FILE * fPointer = fopen("input.txt", "r");
    if (fPointer == NULL) {
        return 1;
    }

    // Read first line
    if (fgets(buf, BUF_SIZE, fPointer) == NULL) {
        fclose(fPointer);
        return 2;
    }

    // Parse line
    token = strtok_s(buf, delim, &next_token);
    for (int i = 0;((i < MAX_INPUT) && (token != NULL)); i++){
        tempNum[i] = strtol(token, &end, 10);
        if (*end != NULL){
            printf("error in %s\n", token);
        } else {
            printf("%d\n", tempNum[i]);
        }
        token = strtok_s(NULL, delim, &next_token);
    }

    fclose(fPointer);
    return 0;
}
</code>```

Body:
I was just creating simple implementation where I read input.txt file which has one line of code containing two numbers separated by space (e.g. 4 4).

I was trying to separate them by delimiting with space first.

And I was trying to use the first value as a size of char array.

However it keeps causing segmentation fault but I have no idea.

int main(int argc, char **argv){

int number;
int i = 0;
char *token;
char buf[100];
int tempNum[2];

// Open file
FILE * fPointer;
fPointer = fopen("input.txt", "r");

// Read first line
fgets(buf, 1024, fPointer);
token = strtok(buf, " ");
number = atoi(token);

char charArray[number];

while(token != NULL){
    tempNum[i] = atoi(token);
    token = strtok(NULL, "\n");
    printf("%d\n", tempNum[i]);
    i++;
}

If I comment out "char charArray[number]" it does not cause segmentation fault. If I comment out only the while loop, it does not cause segmentation fault. But I cannot figure out why it is causing the segmentation in the first place. Please help.

Thank you in advance.

Body:
Something like this?

#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>
#include <string.h>

#define BUF_SIZE 1024
#define MAX_INPUT 2

int main(int argc, char **argv) {
    char *token = NULL;
    char *next_token = NULL;
    char buf[BUF_SIZE];
    long tempNum[MAX_INPUT] = { 0 };
    const char *delim = " ";
    char * end = NULL;

    // Init vars
    memset(buf, 0, BUF_SIZE);

    // Open file
    FILE * fPointer = fopen("input.txt", "r");
    if (fPointer == NULL) {
        return 1;
    }

    // Read first line
    if (fgets(buf, BUF_SIZE, fPointer) == NULL) {
        fclose(fPointer);
        return 2;
    }

    // Parse line
    token = strtok_s(buf, delim, &next_token);
    for (int i = 0;((i < MAX_INPUT) && (token != NULL)); i++){
        tempNum[i] = strtol(token, &end, 10);
        if (*end != NULL){
            printf("error in %s\n", token);
        } else {
            printf("%d\n", tempNum[i]);
        }
        token = strtok_s(NULL, delim, &next_token);
    }

    fclose(fPointer);
    return 0;
}


问:
Python, reading special word from file
So I have this list of word in a textfile, I did not produce the text file so I do not know the file encoding.

the list : http://s000.tinyupload.com/?file_id=31195244104486221180

Notepad++ tells me that it's ANSI.

When running this script (reader1.py) :

```<code>if __name__ == '__main__':
    words = open("test_list.txt").read().splitlines()
    for word in words:
        print word
        with open("test_list-rewrite.txt", "a") as myfile:
                myfile.write(word + '\n')
</code>```

the word piirilä is displayed as piirilõ in the console, however in the new file it's stored as piirilä

What I wonder is, if I compute the hash256 of the variable word, will it run it on piirilä or piirilõ?

word = word.decode('cp-1252') raise an exception

Thanks

PS : Windows 8.1 64 bits, python 2.7 64 bits

Edit

after some more fidling I found something weird, made this

```<code>#!/usr/bin/env python
# --*-- encoding: utf-8 --*--

import hashlib

word1 = 'piirilä'
word2 = 'piirilõ'
word3 = 'Whatitis'

print word1
print hashlib.sha256(word1).hexdigest()
print word2
print hashlib.sha256(word2).hexdigest()
print word3
print hashlib.sha256(word3).hexdigest()
</code>```

which outputs this :

```<code>piiril├ñ
278394edd22799ae29bc881dc66e45e45a9a18972c45a35208b6a3d71e209a10
piiril├Á
7e158cf465d3afadd865684f979f46a5282ef93127c150b55273801086fa3c09
Whatitis
d338e8077b6c9d3d2f09e4e2d4a2a5f52152b72e9b6bb5c456a67f63d853e75f
</code>```

And I added hashlib.sha256(word).hexdigest() to reader1.py

which then outputs this :

```<code>billycorgan
d94a3821ad2b6d26aedf4db13b551d9e0eefeaf92d0615946cdc0215ec974692
brescos64
8840d0e40a83d711ce0b44ed66a5d1e4df06fbf6c5c168e98af4775c6e19f52b
matvois
ef5e930806489e8fcc8e0746ce5f8cb4c6715a56d2fd73d42b1c711b5e71474f
kbeans
c207d8366f3dbae64357088dee8eeeb35a047b2e021342c82aa0bd8c15753d74
Whatitis
d338e8077b6c9d3d2f09e4e2d4a2a5f52152b72e9b6bb5c456a67f63d853e75f
cphu
1427ebcff066a5386d0649842fb60b014bebfc5a1589896a62488865e8f06c50
de'mystifierait
83665461f98de4c270e6a4d69a445ea2f9079693824c0544a9add4caee5c7dd2
wendelboe
1423bf5d682dafdc72937d92811b5ff9d856681e94204d565cb0f29b809f5e13
ketanshah
f9977718f33f9068f20c52321ef02be3611e7c7a0aebb59421e74f864c259f53
piirilõ
a238ede50bc349279c62399b275cfa3271f63bc5e7499cc40aaa4ff84198666d
gasoline
4325ed4bef2a2a10c97cbb8235f822602efc0f04a900f0eb537f8e9fee9728aa
BabyBlues
8168fce33124ecec74e647f119de5b3cda795dcc69c4237d8cf27b10aca07b94
</code>```

so I get 3 different hashes, which one is the one I want?

答:
I compute the hash256 of the variable word, will it run it on piirilä or piirilõ?

The hash will not run on either one; it will run on the sequence of bytes in your variable, whose last byte represents an õ in one encoding and an ä in a different encoding. Apparently your console has a different default encoding from that of Notepad++, so you see the same byte displayed in different ways.

Your test script contains utf-8 encoded text, which is yet another sequence of bytes (two bytes for each of the accented characters, which is why you see two funny symbols in the output; or try printing repr(word1)). If you want to know the hash of the word that's stored in your file, write a program that reads that from the file and computes its hash.

The real solution to your question is to switch to Python 3. You'll then be able to run this code:

```<code>words = open("test_list.txt", encoding="latin1").read().splitlines()
for word in words:
    print(word)
</code>```

Then you can try out different encodings until you find out the right one (in your case, "latin1" seems right). On Python 2, you can do the same after this import:

```<code>from codecs import open
</code>```

But you'll then have unicode strings instead of str, and various confusing things will probably happen. Switching to Python 3 makes it uncecessary to deal with all that.

Title: Python, reading special word from file

Body:
So I have this list of word in a textfile, I did not produce the text file so I do not know the file encoding.

the list : http://s000.tinyupload.com/?file_id=31195244104486221180

Notepad++ tells me that it's ANSI.

When running this script (reader1.py) :

if __name__ == '__main__':
    words = open("test_list.txt").read().splitlines()
    for word in words:
        print word
        with open("test_list-rewrite.txt", "a") as myfile:
                myfile.write(word + '\n')

the word piirilä is displayed as piirilõ in the console, however in the new file it's stored as piirilä

What I wonder is, if I compute the hash256 of the variable word, will it run it on piirilä or piirilõ?

word = word.decode('cp-1252') raise an exception

Thanks

PS : Windows 8.1 64 bits, python 2.7 64 bits

Edit

after some more fidling I found something weird, made this

#!/usr/bin/env python
# --*-- encoding: utf-8 --*--

import hashlib

word1 = 'piirilä'
word2 = 'piirilõ'
word3 = 'Whatitis'

print word1
print hashlib.sha256(word1).hexdigest()
print word2
print hashlib.sha256(word2).hexdigest()
print word3
print hashlib.sha256(word3).hexdigest()

which outputs this :

piiril├ñ
278394edd22799ae29bc881dc66e45e45a9a18972c45a35208b6a3d71e209a10
piiril├Á
7e158cf465d3afadd865684f979f46a5282ef93127c150b55273801086fa3c09
Whatitis
d338e8077b6c9d3d2f09e4e2d4a2a5f52152b72e9b6bb5c456a67f63d853e75f

And I added hashlib.sha256(word).hexdigest() to reader1.py

which then outputs this :

billycorgan
d94a3821ad2b6d26aedf4db13b551d9e0eefeaf92d0615946cdc0215ec974692
brescos64
8840d0e40a83d711ce0b44ed66a5d1e4df06fbf6c5c168e98af4775c6e19f52b
matvois
ef5e930806489e8fcc8e0746ce5f8cb4c6715a56d2fd73d42b1c711b5e71474f
kbeans
c207d8366f3dbae64357088dee8eeeb35a047b2e021342c82aa0bd8c15753d74
Whatitis
d338e8077b6c9d3d2f09e4e2d4a2a5f52152b72e9b6bb5c456a67f63d853e75f
cphu
1427ebcff066a5386d0649842fb60b014bebfc5a1589896a62488865e8f06c50
de'mystifierait
83665461f98de4c270e6a4d69a445ea2f9079693824c0544a9add4caee5c7dd2
wendelboe
1423bf5d682dafdc72937d92811b5ff9d856681e94204d565cb0f29b809f5e13
ketanshah
f9977718f33f9068f20c52321ef02be3611e7c7a0aebb59421e74f864c259f53
piirilõ
a238ede50bc349279c62399b275cfa3271f63bc5e7499cc40aaa4ff84198666d
gasoline
4325ed4bef2a2a10c97cbb8235f822602efc0f04a900f0eb537f8e9fee9728aa
BabyBlues
8168fce33124ecec74e647f119de5b3cda795dcc69c4237d8cf27b10aca07b94

so I get 3 different hashes, which one is the one I want?

Body:
I compute the hash256 of the variable word, will it run it on piirilä or piirilõ?

The hash will not run on either one; it will run on the sequence of bytes in your variable, whose last byte represents an õ in one encoding and an ä in a different encoding. Apparently your console has a different default encoding from that of Notepad++, so you see the same byte displayed in different ways.

Your test script contains utf-8 encoded text, which is yet another sequence of bytes (two bytes for each of the accented characters, which is why you see two funny symbols in the output; or try printing repr(word1)). If you want to know the hash of the word that's stored in your file, write a program that reads that from the file and computes its hash.

The real solution to your question is to switch to Python 3. You'll then be able to run this code:

words = open("test_list.txt", encoding="latin1").read().splitlines()
for word in words:
    print(word)

Then you can try out different encodings until you find out the right one (in your case, "latin1" seems right). On Python 2, you can do the same after this import:

from codecs import open

But you'll then have unicode strings instead of str, and various confusing things will probably happen. Switching to Python 3 makes it uncecessary to deal with all that.


问:
macvim html5 syntax highlighting in erb templates
I am trying to get syntax highlighting for HTML 5 elements in erb templates working.

I have installed newest rails.vim plugin as well as html5.vim and can't seem to get it to work.

Works fine on .html files.

答:
First of all, just in case you are not already using it, you should install the excellent rails.vim from Tim Pope to work on Ror with Vim. (Do not hesitate to check his other plugins as well)

That being said the likely reason why you don't get the html syntax highlighting is because the file is recognized by Vim as [eruby] and not [html].

To be sure, open an erb file and type:
set filetype?

It will display the type of the file as identified by Vim.

To get both eruby and html5 syntax highlighting working at once, you can open an erb file andtype:

set filetype=eruby.html

I am not sure that multiple filetypes at once are 100% supported though.

If it works, you can add the following line to your .vimrc so that the filetype html is automatically added every time you are opening an *.erb file:
autocmd BufRead,BufNewFile *.erb set filetype=eruby.html

ContentLicense: CC BY-SA 2.5


问:
Oracle pushing me ORA-00902: invalid datatype
```<code>create table accountDetails(
    accountNumber int unique,
    customerId int unique,
    balance int not null,
    password varchar(255) not null,
    type varchar(255) not null check(type in ('Savings','Current')),
    primary key(accountNumber,customerId) )

create table statusDetails(
    customerId int references accountDetails(customerId),
    primarykey(customerId))
</code>```

The last table resulted in an error

答:
The last table resulted in an error

ORA-00902: invalid datatype error happens when we try to define a column using an invalid datatype. It's logical really.

Now, you think you haven't declared a column with an invalid datatype, because you think statusdetails table has only one column, customerid. But if you look at your actual statement you follow that column with this:

```<code>primarykey(customerId))
</code>```

Because you mis-typed primary key Oracle treats that line as an attempt to create a second column. Hence the error, because (customerId) is an invalid datatype. So all you need do is pop in the missing space and Oracle will create the table for you.

```<code>create table statusDetails(
    customerId int references accountDetails(customerId),
    primary key(customerId))
</code>```

You had a compilation error caused by a simple typo. A key skill for a developer is the ability to turn a cool eye on our own code. I urge you to work on acquiring that skill as soon as you can.

Body:
create table accountDetails(
    accountNumber int unique,
    customerId int unique,
    balance int not null,
    password varchar(255) not null,
    type varchar(255) not null check(type in ('Savings','Current')),
    primary key(accountNumber,customerId) )

create table statusDetails(
    customerId int references accountDetails(customerId),
    primarykey(customerId))

The last table resulted in an error

Body:
The last table resulted in an error

ORA-00902: invalid datatype error happens when we try to define a column using an invalid datatype. It's logical really.

Now, you think you haven't declared a column with an invalid datatype, because you think statusdetails table has only one column, customerid. But if you look at your actual statement you follow that column with this:

primarykey(customerId))

Because you mis-typed primary key Oracle treats that line as an attempt to create a second column. Hence the error, because (customerId) is an invalid datatype. So all you need do is pop in the missing space and Oracle will create the table for you.

create table statusDetails(
    customerId int references accountDetails(customerId),
    primary key(customerId))

You had a compilation error caused by a simple typo. A key skill for a developer is the ability to turn a cool eye on our own code. I urge you to work on acquiring that skill as soon as you can.


问:
Java - Print numbers saved to text file in past 24 hours
I can't provide any sample code so this will be more of a question that you could maybe provide me in the right direction.

Essentially, at the end of a game round I am exporting the score(points) to a text file. My text file appears like

```<code>1
3
4
1
2
</code>```

Now what I want to do is, get the top 5 scores that were saved to the text  file in the past 24 hours.

My idea is, once i get the scores that were saved from the past 24 hours, i'll add these to a collection and reverse sort them and use a for loop to print the 5 out. But i have no idea how to get the time.

答:
You are right that you need to change the format of your file. I would want to use either Instant.toString() or LocalDateTime.toString() for generating the time stamps. So each line would become like

```<code>5 2017-11-06T14:52:31.434Z
</code>```

In the example, 5 is the score and 2017-11-06T14:52:31.434Z is an Instant. Neither the string representation of Instant nor of LocalDateTime contains any spaces, so split each line from the file at the space, and you have got the score and the time stamp separately. Feed the timestamp back into Instant.parse() or LocalDateTime.parse().

Read the file from the beginning, skipping time stamps that are more than 24 hours old. Once you meet one that is younger than 24 hours, start adding the scores to your ArrayList.

For determining whether a time stamp is older than 24 hours, compare it to Instant.now().minus(Duration.ofHours(24)) or LocalDateTime.now(ZoneId.of("Europe/Rome")).minusHours(24) (substitute your desired time zone). Those classes have methods isBefore and isAfter for comparison.

Use LocalDateTime only if you are sure that everything happens within one time zone only. Instant is safe across time zones.

Body:
I can't provide any sample code so this will be more of a question that you could maybe provide me in the right direction.

Essentially, at the end of a game round I am exporting the score(points) to a text file. My text file appears like

1
3
4
1
2

Now what I want to do is, get the top 5 scores that were saved to the text  file in the past 24 hours.

My idea is, once i get the scores that were saved from the past 24 hours, i'll add these to a collection and reverse sort them and use a for loop to print the 5 out. But i have no idea how to get the time.

Body:
You are right that you need to change the format of your file. I would want to use either Instant.toString() or LocalDateTime.toString() for generating the time stamps. So each line would become like

5 2017-11-06T14:52:31.434Z

In the example, 5 is the score and 2017-11-06T14:52:31.434Z is an Instant. Neither the string representation of Instant nor of LocalDateTime contains any spaces, so split each line from the file at the space, and you have got the score and the time stamp separately. Feed the timestamp back into Instant.parse() or LocalDateTime.parse().

Read the file from the beginning, skipping time stamps that are more than 24 hours old. Once you meet one that is younger than 24 hours, start adding the scores to your ArrayList.

For determining whether a time stamp is older than 24 hours, compare it to Instant.now().minus(Duration.ofHours(24)) or LocalDateTime.now(ZoneId.of("Europe/Rome")).minusHours(24) (substitute your desired time zone). Those classes have methods isBefore and isAfter for comparison.

Use LocalDateTime only if you are sure that everything happens within one time zone only. Instant is safe across time zones.


问:
New xamarin.forms project creation gives NU11002 Unable to find package Xamarin.Forms with version (>= 250121934.0.0)
Recently i updated my visual studio 2017 enterprise to 15.5.0. I am trying to create xamarin forms project as Blank App, platfom Android + ios, UI Technology Xamarin.Forms, code sharing strategy .net standart. When i try to build the default created project i got the following error;

Severity  Code    Description Project File    Line    Suppression State
  Error NU1102  Unable to find package Xamarin.Forms with version (>=
  250121934.0.0)
    - Found 163 version(s) in nuget.org [ Nearest version: 2.5.0.121934 ]
    - Found 0 version(s) in Microsoft Visual Studio Offline Packages

I can not also remove and install xamarin.forms nuget. Any ideas?

答: i finally found the solution. I opened android sdk manager and install Android 7.1 Nougat SDK (previously android 6.0 was installed). Then i right clicked solution and opened nuget manager. I selected Xamarin.forms package and choose the latest version of package and click install. I refreshed the package in all projects. Now everything works well. </p>


问:
Getting float array from C++ to C#
I have float array inside C++ function.

C++ function

```<code>void bleplugin_GetGolfResult(float* result)
{
    float *array = new float[20];
    for(int i=0; i < 20; i++)
      array[i]= 25;
    result = array;
    //DEBUG PRINTING1
    for(int i=0; i < 20; i++)
       cout << result[i] << endl;//Here is correct
    return;
}
</code>```

Inside C#

```<code>[DllImport ("__Internal")]
private static unsafe extern void bleplugin_GetGolfResult (float* result);

public static unsafe float[] result = new float[20];

public unsafe static void GetGolfREsult(){
    fixed (float* ptr_result = result) //or equivalently "... = &f2[0]" address of f2[0]
    {
        bleplugin_GetGolfResult( ptr_result );
        //DEBUG PRINTING2
        for(int i = 0; i < 20; i++)
            Debug.Log("result data " + ptr_result[i]);
    }
    return;
}
</code>```

I called GetGolfREsult() from another function to get result.

//DEBUG PRINTING1 has correct output.

But //DEBUG PRINTING2 produced 0 only.

What could be wrong?

答:
This line in your C++ code:

```<code>float *array = new float[20];
</code>```

creates a new array, which you operate on in C++. Then control returns to C#, who has it's own array and that's still unchanged. Why don't you write to the array you got?

Title: Getting float array from C++ to C#

Body:
I have float array inside C++ function.

C++ function

void bleplugin_GetGolfResult(float* result)
{
    float *array = new float[20];
    for(int i=0; i < 20; i++)
      array[i]= 25;
    result = array;
    //DEBUG PRINTING1
    for(int i=0; i < 20; i++)
       cout << result[i] << endl;//Here is correct
    return;
}

Inside C#

[DllImport ("__Internal")]
private static unsafe extern void bleplugin_GetGolfResult (float* result);

public static unsafe float[] result = new float[20];

public unsafe static void GetGolfREsult(){
    fixed (float* ptr_result = result) //or equivalently "... = &f2[0]" address of f2[0]
    {
        bleplugin_GetGolfResult( ptr_result );
        //DEBUG PRINTING2
        for(int i = 0; i < 20; i++)
            Debug.Log("result data " + ptr_result[i]);
    }
    return;
}

I called GetGolfREsult() from another function to get result.

//DEBUG PRINTING1 has correct output.

But //DEBUG PRINTING2 produced 0 only.

What could be wrong?

Body:
This line in your C++ code:

float *array = new float[20];

creates a new array, which you operate on in C++. Then control returns to C#, who has it's own array and that's still unchanged. Why don't you write to the array you got?


问:
Sending data from a python dictionary to a javascript file
I'm new to python and javascript so I don't know much about their data sharing capabilities. Below is the dictionary (whose data I want to send) in a database file I have called database.py. How can I take this data and send it to my javascript file "Calendar.js" so I can use it in a function later?</p>

```<code>agenda = {'id' : num,
                  'eventName' : eventName,
                  'eventType' : eventType,
                  'location' : location,
                  'date' : date,
                  'time' : time,
                  'compName' : compName,
                  'attire' : attire,
                  'additional' : additional}
</code>```

答:
As a general rule, consider that JSON (JavaScript Object Notation) is the goto-format if you want to exchange data with javascript.

From Python, you can use the json module to generate such data.

Example:

```<code>d = {"name":"interpolator",
     "children":[{'name':key,"size":value} for key,value in sample.items()]}
j = json.dumps(d, indent=4)
f = open('sample.json', 'w')
print >> f, j
f.close()
</code>```

Now, for the actual communication with javascript, you can either write the JSON in a file and process it asynchronously, or use something like protobuf/grpc.

Body:
I'm new to python and javascript so I don't know much about their data sharing capabilities. Below is the dictionary (whose data I want to send) in a database file I have called database.py. How can I take this data and send it to my javascript file "Calendar.js" so I can use it in a function later?

agenda = {'id' : num,
                  'eventName' : eventName,
                  'eventType' : eventType,
                  'location' : location,
                  'date' : date,
                  'time' : time,
                  'compName' : compName,
                  'attire' : attire,
                  'additional' : additional}

Body:
As a general rule, consider that JSON (JavaScript Object Notation) is the goto-format if you want to exchange data with javascript.

From Python, you can use the json module to generate such data.

Example:

d = {"name":"interpolator",
     "children":[{'name':key,"size":value} for key,value in sample.items()]}
j = json.dumps(d, indent=4)
f = open('sample.json', 'w')
print >> f, j
f.close()

Now, for the actual communication with javascript, you can either write the JSON in a file and process it asynchronously, or use something like protobuf/grpc.


问:
Cordova/Phonegap Splashscreen - iOS - Not showing custom images
Recently apple released a new specification to move to a new style of storyboard splashscreens that allows for different device sizes on a smaller number of splashscreens. To configure our application for use with the iPhone X, this new system needs to be adopted to allow full screen viewing. Our app file structure is as follows:

ROOT

config.xml

res

screen

ios

Default@2x~iphone~anyany.png

Default@2x~iphone~comany.png

Default@2x~iphone~comcom.png

Default@3x~iphone~anyany.png

Default@3x~iphone~anycom.png

Default@3x~iphone~comany.png

Default@2x~ipad~anyany.png

Default@2x~ipad~comany.png

www

app files

When prepping for upload to phonegap build, the config.xml, res folder and inner contents of the www folder are moved to one folder. However when downloading the app to my device, the default splashscreen shows.

Current config.xml layout (running cordova v7)

```<code><platform name="ios">
    <preference name="deployment-target" value="7.0" />
    <icon height="512" src="res/icon/iTunesArtwork.png" width="512" />
    <icon height="1024" src="res/icon/ios/iTunesArtwork@2x.png" width="1024" />
    <icon height="180" src="res/icon/ios/Icon-60@3x.png" width="180" />
    <icon height="120" src="res/icon/ios/Icon-60@2x.png" width="120" />
    <icon height="60" src="res/icon/ios/Icon-60.png" width="60" />
    <icon height="76" src="res/icon/ios/Icon-76.png" width="76" />
    <icon height="152" src="res/icon/ios/Icon-76@2x.png" width="152" />
    <icon height="40" src="res/icon/ios/Icon-Small-40.png" width="40" />
    <icon height="80" src="res/icon/ios/Icon-Small-40@2x.png" width="80" />
    <icon height="120" src="res/icon/ios/Icon-Small-40@3x.png" width="120" />
    <icon height="29" src="res/icon/ios/Icon-Small.png" width="29" />
    <icon height="58" src="res/icon/ios/Icon-Small@2x.png" width="58" />
    <icon height="87" src="res/icon/ios/Icon-Small@3x.png" width="87" />

    <splash src="res/screen/ios/Default@2x~iphone~anyany.png" />
    <splash src="res/screen/ios/Default@2x~iphone~comany.png" />
    <splash src="res/screen/ios/Default@2x~iphone~comcom.png" />
    <splash src="res/screen/ios/Default@3x~iphone~anyany.png" />
    <splash src="res/screen/ios/Default@3x~iphone~anycom.png" />
    <splash src="res/screen/ios/Default@3x~iphone~comany.png" />
    <splash src="res/screen/ios/Default@2x~ipad~anyany.png" />
    <splash src="res/screen/ios/Default@2x~ipad~comany.png" />
</platform>

<plugin name="cordova-plugin-splashscreen" spec="~4.0.0" />
<preference name="ShowSplashScreenSpinner" value="false" />
</code>```

The expected outcome is for the custom images to show, and for the app to take the full screen on my iPhone X. Instead it is showing as follows:

https://imgur.com/a/ehtCy

Any help to resolve this issue would be much appriciated, as i can't seem to find a recent forum thread for anyone with this issue.

答: Self-sorted answer. Currently PhoneGap Build (the service I am using is not using the iOS 4.5.1 release which is necessary for the latest iPhone X full screens. Hopefully, 4.5.1 will be in the cloud service soon. </p>

Body:
Recently apple released a new specification to move to a new style of storyboard splashscreens that allows for different device sizes on a smaller number of splashscreens. To configure our application for use with the iPhone X, this new system needs to be adopted to allow full screen viewing. Our app file structure is as follows:

ROOT

config.xml

res

screen

ios

Default@2x~iphone~anyany.png

Default@2x~iphone~comany.png

Default@2x~iphone~comcom.png

Default@3x~iphone~anyany.png

Default@3x~iphone~anycom.png

Default@3x~iphone~comany.png

Default@2x~ipad~anyany.png

Default@2x~ipad~comany.png

www

app files

When prepping for upload to phonegap build, the config.xml, res folder and inner contents of the www folder are moved to one folder. However when downloading the app to my device, the default splashscreen shows.

Current config.xml layout (running cordova v7)

<platform name="ios">
    <preference name="deployment-target" value="7.0" />
    <icon height="512" src="res/icon/iTunesArtwork.png" width="512" />
    <icon height="1024" src="res/icon/ios/iTunesArtwork@2x.png" width="1024" />
    <icon height="180" src="res/icon/ios/Icon-60@3x.png" width="180" />
    <icon height="120" src="res/icon/ios/Icon-60@2x.png" width="120" />
    <icon height="60" src="res/icon/ios/Icon-60.png" width="60" />
    <icon height="76" src="res/icon/ios/Icon-76.png" width="76" />
    <icon height="152" src="res/icon/ios/Icon-76@2x.png" width="152" />
    <icon height="40" src="res/icon/ios/Icon-Small-40.png" width="40" />
    <icon height="80" src="res/icon/ios/Icon-Small-40@2x.png" width="80" />
    <icon height="120" src="res/icon/ios/Icon-Small-40@3x.png" width="120" />
    <icon height="29" src="res/icon/ios/Icon-Small.png" width="29" />
    <icon height="58" src="res/icon/ios/Icon-Small@2x.png" width="58" />
    <icon height="87" src="res/icon/ios/Icon-Small@3x.png" width="87" />

    <splash src="res/screen/ios/Default@2x~iphone~anyany.png" />
    <splash src="res/screen/ios/Default@2x~iphone~comany.png" />
    <splash src="res/screen/ios/Default@2x~iphone~comcom.png" />
    <splash src="res/screen/ios/Default@3x~iphone~anyany.png" />
    <splash src="res/screen/ios/Default@3x~iphone~anycom.png" />
    <splash src="res/screen/ios/Default@3x~iphone~comany.png" />
    <splash src="res/screen/ios/Default@2x~ipad~anyany.png" />
    <splash src="res/screen/ios/Default@2x~ipad~comany.png" />
</platform>

<plugin name="cordova-plugin-splashscreen" spec="~4.0.0" />
<preference name="ShowSplashScreenSpinner" value="false" />

The expected outcome is for the custom images to show, and for the app to take the full screen on my iPhone X. Instead it is showing as follows:

https://imgur.com/a/ehtCy

Any help to resolve this issue would be much appriciated, as i can't seem to find a recent forum thread for anyone with this issue.


问:
JavaFx buttons click in order then play
I am looking to have buttons play in the order in which they are clicked. For example, if I click buttons 3, 4, and 6 I would like to then click a "play" button and this button then clicks the same pattern I clicked.</p>

答:
This piece of code makes it looks like the button was pressed

```<code>button.arm();
PauseTransition pause = new PauseTransition(Duration.seconds(0.5));
pause.setOnFinished(e -> {
    button.disarm();
});
pause.play();
</code>```

If you want the button to actually fire not just look like it did then add button.fire(); after the button.disarm();

Then you just need to record the buttons that are pressed

Title: JavaFx buttons click in order then play

Body:
This piece of code makes it looks like the button was pressed

button.arm();
PauseTransition pause = new PauseTransition(Duration.seconds(0.5));
pause.setOnFinished(e -> {
    button.disarm();
});
pause.play();

If you want the button to actually fire not just look like it did then add button.fire(); after the button.disarm();

Then you just need to record the buttons that are pressed


问:
Web service with jQuery; No web services found at
I am using jQuery to call a web service in order to send an email (from user feedback page). All pages are HTML.

I added a folder called "Services" and placed the web service files there (easg.asmx and easg.asmx.cs). It works fine when I test it from within VS 2017.

However, when I publish and deploy to server I get "No web services found at /services/easg.asmx".

I can run localhost/website/services/easg.asmx and it displays one single method available. I am not sure why from within the page it says no web service is found.

Web service is part of the application and on the same server; it is not a different project.

This is the (partial) code:

.aspx page:

```<code><section id="contact" class="bg-light">
    <div class="container">
        <div class="row">
            <div class="col-sm-12 ml-sm-auto col-md-10 pt-4">
                <h1>Contact us</h1>

                <form id="sendmail" method="POST" action="">
                    <div class="form-group">
                        <input type="email" class="form-control" id="inputEmail" aria-describedby="emailHelp" placeholder="Email Address">
                    </div>
                    <div class="form-group">
                        <input type="email" class="form-control" id="inputName" aria-describedby="nameHelp" placeholder="First and Last Name">
                    </div>
                    <div class="form-group">
                        <input type="email" class="form-control" id="inputPhone" aria-describedby="phoneHelp" placeholder="Contact Number">
                    </div>
                    <div class="form-group">
                        <label for="inputMsg">Feedback/Questions</label>
                        <textarea class="form-control" id="inputMsg" rows="3"></textarea>
                    </div>
                    <button type="submit" id="btnSubmit" class="btn btn-primary">Submit</button>
                </form>
            </div>
        </div>
    </div>
</section>

<script type="text/javascript">
    $("#btnSubmit").click(function () {
        debugger
        $("#sendmail").validate();

        if ($("#sendmail").valid()) {
            $.ajax({
                type: "POST",
                url: "/services/easg.asmx/SendEmail",
                cache: false,
                contentType: "application/json; charset=utf-8",
                data: "{ 'Msg': '" + $("#inputMsg").val() + "', " + "'To': 'someone@somewhere.com'," + "'From': '" + $("#inputEmail").val() + "'," + "'Name': '" + $("#inputName").val() + "'," + "'Subject': 'Guide Feedback'," + "'Phone': '" + $("#inputPhone").val() + "'" + "}",
                dataType: "json",
                complete: function (transport) {
                    alert(transport.status);
                    if (transport.status == 200) {
                        alert('Your message was sent; thank you for your feedback');
                    }
                    else {
                        alert("Failed to send feedback; please try again later. Status Code: " + transport.status);
                    }
                }
            });
        }
        //so that the page doesn't post back
        return false;
    });
</script>
</code>```

Web Service located in Services\easg.asmx.cs:

```<code>namespace EAStyleGuide
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]

    public class easg : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(UseHttpGet = true)]

        private void SendEmail(string Msg, string To, string From, string Name, string Subject, string Phone)
        {
            using (var message = new MailMessage())
            {
                message.From = new MailAddress(From);
                message.To.Add(new MailAddress(To));
                message.Subject = Subject;
                message.Body = GetMailBody(From, Msg, Phone, Name);
                message.Priority = MailPriority.Normal;
                message.IsBodyHtml = false;

                SmtpClient sc = new SmtpClient("mailrelay.blah.com");
                sc.Credentials = new NetworkCredential();

            try
            {
                sc.Send(message);
            }
            catch (SmtpFailedRecipientsException FRE)
            {
            }
            catch (SmtpException smtpEx)
            {
            }
            catch (Exception generalEx)
            {
            }
        }
        return;
    }
</code>```

答: I had to change url: "/services/easg.asmx/SendEmail", to url: "services/easg.asmx/SendEmail" (get rid of backslash before "services".</p>

Body:
I am using jQuery to call a web service in order to send an email (from user feedback page). All pages are HTML.

I added a folder called "Services" and placed the web service files there (easg.asmx and easg.asmx.cs). It works fine when I test it from within VS 2017.

However, when I publish and deploy to server I get "No web services found at /services/easg.asmx".

I can run localhost/website/services/easg.asmx and it displays one single method available. I am not sure why from within the page it says no web service is found.

Web service is part of the application and on the same server; it is not a different project.

This is the (partial) code:

.aspx page:

Contact us

                <form id="sendmail" method="POST" action="">

                        <input type="email" class="form-control" id="inputEmail" aria-describedby="emailHelp" placeholder="Email Address">

                        <input type="email" class="form-control" id="inputName" aria-describedby="nameHelp" placeholder="First and Last Name">

                        <input type="email" class="form-control" id="inputPhone" aria-describedby="phoneHelp" placeholder="Contact Number">

                        Feedback/Questions
                        <textarea class="form-control" id="inputMsg" rows="3"></textarea>

                    <button type="submit" id="btnSubmit" class="btn btn-primary">Submit</button>
                </form>

Web Service located in Services\easg.asmx.cs:

namespace EAStyleGuide
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]

    public class easg : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(UseHttpGet = true)]

        private void SendEmail(string Msg, string To, string From, string Name, string Subject, string Phone)
        {
            using (var message = new MailMessage())
            {
                message.From = new MailAddress(From);
                message.To.Add(new MailAddress(To));
                message.Subject = Subject;
                message.Body = GetMailBody(From, Msg, Phone, Name);
                message.Priority = MailPriority.Normal;
                message.IsBodyHtml = false;

                SmtpClient sc = new SmtpClient("mailrelay.blah.com");
                sc.Credentials = new NetworkCredential();

            try
            {
                sc.Send(message);
            }
            catch (SmtpFailedRecipientsException FRE)
            {
            }
            catch (SmtpException smtpEx)
            {
            }
            catch (Exception generalEx)
            {
            }
        }
        return;
    }


问:
Xamarin TabbedPages MVVM Binding
How to bind tabbed page with different view models?
To make it clearer I have this tabbed page:

```<code><TabbedPage.Children>
    <tabPages:Page1/>
    <tabPages:Page2/>
    <tabPages:Page3/>
</TabbedPage.Children>
</code>```

These 3 pages have different view models. However, the problem is the view models of each pages won't bind. Is there a specific way in order to do this?

To test if my view models for each pages works, I inlined the code in tabbed page:
e.g.

```<code><TabbedPage.Children>
    <ContentPage Title="Test">
    <Label Text="{Binding TestBind}"/>
    </ContentPage>
</TabbedPage.Children>
</code>```

And for bind it to the view model of the tabbed page (parent) - this method works. However, if I do it separately, the view models wouldn't bind.
E.g.

```<code>public class Page1ViewModel : BaseViewModel
{
        public Page1ViewModel()
        {
            TestBind = "Test";
        }
        private string _TestBind;
        public string TestBind
        {
            get { return _TestBind; }
            set { SetProperty(ref _TestBind, value); }
        }
}
</code>```

Using it this way, it wouldn't bind

答:
Why not just set the BindingContext of each TabPage to each ViewModel:

```<code><TabbedPage.Children>
    <tabPages:Page1 BindingContext="{Binding viewModel1}" />
    <tabPages:Page2 BindingContext="{Binding viewModel2}" />
    <tabPages:Page3 BindingContext="{Binding viewModel3}"/>
</TabbedPage.Children>
</code>```

Those ViewModels would have to exist as properties in the parent VM.

Title: Xamarin TabbedPages MVVM Binding

Body:
How to bind tabbed page with different view models?
To make it clearer I have this tabbed page:

<TabbedPage.Children>
    <tabPages:Page1/>
    <tabPages:Page2/>
    <tabPages:Page3/>
</TabbedPage.Children>

These 3 pages have different view models. However, the problem is the view models of each pages won't bind. Is there a specific way in order to do this?

To test if my view models for each pages works, I inlined the code in tabbed page:
e.g.

<TabbedPage.Children>
    <ContentPage Title="Test">

    </ContentPage>
</TabbedPage.Children>

And for bind it to the view model of the tabbed page (parent) - this method works. However, if I do it separately, the view models wouldn't bind.
E.g.

public class Page1ViewModel : BaseViewModel
{
        public Page1ViewModel()
        {
            TestBind = "Test";
        }
        private string _TestBind;
        public string TestBind
        {
            get { return _TestBind; }
            set { SetProperty(ref _TestBind, value); }
        }
}

Using it this way, it wouldn't bind

Body:
Why not just set the BindingContext of each TabPage to each ViewModel:

<TabbedPage.Children>
    <tabPages:Page1 BindingContext="{Binding viewModel1}" />
    <tabPages:Page2 BindingContext="{Binding viewModel2}" />
    <tabPages:Page3 BindingContext="{Binding viewModel3}"/>
</TabbedPage.Children>

Those ViewModels would have to exist as properties in the parent VM.


问:
JVM crashes while trying to run Junit test case
While trying to run a Junit test case, eclipse crashes.
Junit is using the same JRE as the workspace.
Worspace is using Oracles JVM jdk1.8.0_151.jdk as in the Eclipse.ini below
Logs show as below:

```<code>#A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007fff7dc97010, pid=2898, tid=0x0000000000000307
#
# JRE version: Java(TM) SE Runtime Environment (8.0_151-b12) (build 1.8.0_151-b12)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.151-b12 mixed mode bsd-amd64 compressed oops)
# Problematic frame:
# C  [libsystem_platform.dylib+0x5010]  _platform_memmove$VARIANT$Haswell+0xf0
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
</code>```

Not sure if this is related:
https://bugs.openjdk.java.net/browse/JDK-8184898

If this is really the case, where do I add this param, in Eclipse.ini? Adding that didnt help either.

My Eclipse.ini looks like this:

```<code>../Eclipse/plugins/org.eclipse.equinox.launcher_1.3.201.v20161025-1711.jar
--launcher.library
../Eclipse/plugins/org.eclipse.equinox.launcher.cocoa.macosx.x86_64_1.1.401.v20161122-1740
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
-showsplash
org.eclipse.platform
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vm
/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home/bin
-vmargs
-Dosgi.requiredJavaVersion=1.8
-XX:+UseG1GC
-XX:+UseStringDeduplication
-XstartOnFirstThread
-Dorg.eclipse.swt.internal.carbon.smallFonts
-Dosgi.requiredJavaVersion=1.8
-Xms1024m
-Xmx4048m
-Xdock:icon=../Resources/Eclipse.icns
-XstartOnFirstThread
-Dorg.eclipse.swt.internal.carbon.smallFonts
-Dsun.zip.disableMemoryMapping=true
</code>```

Tried increasing the memory too. Didnt help. Thanks in advance.

答:
This is a known issue which has already been fixed in Eclipse Oxygen:

Eclipse bug 502711 - [Cocoa][10.12] crashes on „macOS Sierra“ related to NSCopyBits

Upgrading at least the Eclipse platform should fix the problem.

Body:
While trying to run a Junit test case, eclipse crashes.
Junit is using the same JRE as the workspace.
Worspace is using Oracles JVM jdk1.8.0_151.jdk as in the Eclipse.ini below
Logs show as below:

#A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007fff7dc97010, pid=2898, tid=0x0000000000000307
#
# JRE version: Java(TM) SE Runtime Environment (8.0_151-b12) (build 1.8.0_151-b12)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.151-b12 mixed mode bsd-amd64 compressed oops)
# Problematic frame:
# C  [libsystem_platform.dylib+0x5010]  _platform_memmove$VARIANT$Haswell+0xf0
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.

Not sure if this is related:
https://bugs.openjdk.java.net/browse/JDK-8184898

If this is really the case, where do I add this param, in Eclipse.ini? Adding that didnt help either.

My Eclipse.ini looks like this:

../Eclipse/plugins/org.eclipse.equinox.launcher_1.3.201.v20161025-1711.jar
--launcher.library
../Eclipse/plugins/org.eclipse.equinox.launcher.cocoa.macosx.x86_64_1.1.401.v20161122-1740
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
-showsplash
org.eclipse.platform
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vm
/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home/bin
-vmargs
-Dosgi.requiredJavaVersion=1.8
-XX:+UseG1GC
-XX:+UseStringDeduplication
-XstartOnFirstThread
-Dorg.eclipse.swt.internal.carbon.smallFonts
-Dosgi.requiredJavaVersion=1.8
-Xms1024m
-Xmx4048m
-Xdock:icon=../Resources/Eclipse.icns
-XstartOnFirstThread
-Dorg.eclipse.swt.internal.carbon.smallFonts
-Dsun.zip.disableMemoryMapping=true

Tried increasing the memory too. Didnt help. Thanks in advance.


问:
java.lang.IllegalArgumentException @$Proxy21 error in Java Appium PageFactory initElements
I have suddenly started facing below error:

java.lang.IllegalArgumentException: If you use a '@$Proxy21' annotation, you must not also use a '@$Proxy23' annotation
  at io.appium.java_client.pagefactory.DefaultElementByBuilder.checkDisallowedAnnotationPairs(DefaultElementByBuilder.java:46)
    at io.appium.java_client.pagefactory.DefaultElementByBuilder.assertValidAnnotations(DefaultElementByBuilder.java:87)

I am using below code to init elements:

```<code>  PageFactory.initElements(new AppiumFieldDecorator(appiumDriver, 6, TimeUnit.SECONDS), this);
</code>```

It was working all fine & without any major changes its now failing.

Appium version: 1.7.1

My POM.xml

```<code>   <dependencies>

    <dependency>
        <groupId>com.github.fge</groupId>
        <artifactId>json-schema-validator</artifactId>
        <version>2.0.0</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>${jackson.version}</version>
    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>${selenium.java.version}</version>
    </dependency>

    <dependency>
        <groupId>com.vimalselvam</groupId>
        <artifactId>cucumber-extentsreport</artifactId>
        <version>${cucumber.extentsreport.version}</version>
    </dependency>

    <dependency>
        <groupId>io.appium</groupId>
        <artifactId>java-client</artifactId>
        <version>${appium.java-client.version}</version>
        <!--<version>5.0.0-BETA5</version>-->
    </dependency>

    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>${log4j.version}</version>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>${cucumber-java.version}</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.jayway.jsonpath/json-path -->
    <dependency>
        <groupId>com.jayway.jsonpath</groupId>
        <artifactId>json-path</artifactId>
        <version>${json-path.version}</version>
    </dependency>

    <dependency>
        <groupId>org.monte.screenrecorder</groupId>
        <artifactId>MonteScreenRecorder</artifactId>
        <version>10</version>
        <scope>system</scope>
        <systemPath>${basedir}/lib/monte-screen-recorder-0.7.7.jar</systemPath>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>${cucumber-junit.version}</version>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-core</artifactId>
        <version>${cucumber-junit.version}</version>
    </dependency>

    <dependency>
        <groupId>com.googlecode.json-simple</groupId>
        <artifactId>json-simple</artifactId>
        <version>${json-simple.version}</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-chrome-driver -->
    <!--<dependency>-->
    <!--<groupId>org.seleniumhq.selenium</groupId>-->
    <!--<artifactId>selenium-chrome-driver</artifactId>-->
    <!--<version>3.3.1</version>-->
    <!--</dependency>-->
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <!--<dependency>-->
        <!--<groupId>org.springframework</groupId>-->
        <!--<artifactId>spring-context</artifactId>-->
        <!--<version>${spring-context.version}</version>-->
    <!--</dependency>-->
    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-library</artifactId>
        <version>${hamcrest-library.version}</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-jvm-deps</artifactId>
        <version>1.0.5</version>
        <scope>test</scope>
    </dependency>

    <!--Exploratory Cucumber-TestNG Fusion-->
    <!--<dependency>-->
        <!--<groupId>info.cukes</groupId>-->
        <!--<artifactId>cucumber-testng</artifactId>-->
        <!--<version>1.2.4</version>-->
        <!--<scope>compile</scope>-->
        <!--<exclusions>-->
            <!--<exclusion>-->
                <!--<groupId>junit</groupId>-->
                <!--<artifactId>junit</artifactId>-->
            <!--</exclusion>-->
        <!--</exclusions>-->
    <!--</dependency>-->

    <!--<dependency>-->
        <!--<groupId>info.cukes</groupId>-->
        <!--<artifactId>cucumber-spring</artifactId>-->
        <!--<version>${cucumber-spring.version}</version>-->
        <!--<scope>test</scope>-->
    <!--</dependency>-->

    <!--<dependency>-->
        <!--<groupId>org.springframework</groupId>-->
        <!--<artifactId>spring-context</artifactId>-->
        <!--<version>4.3.8.RELEASE</version>-->
        <!--<scope>test</scope>-->
    <!--</dependency>-->
    <!--<dependency>-->
        <!--<groupId>org.springframework</groupId>-->
        <!--<artifactId>spring-test</artifactId>-->
        <!--<version>4.3.8.RELEASE</version>-->
        <!--<scope>test</scope>-->
    <!--</dependency>-->

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-picocontainer</artifactId>
        <version>1.2.5</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.junit</groupId>
        <artifactId>junit5-engine</artifactId>
        <version>5.0.0-ALPHA</version>
    </dependency>
    <dependency>
        <groupId>com.relevantcodes</groupId>
        <artifactId>extentreports</artifactId>
        <version>2.41.2</version>
        <scope>test</scope>
    </dependency>

    <!--<dependency>-->
        <!--<groupId>org.testobject</groupId>-->
        <!--<artifactId>testobject-appium-java-api</artifactId>-->
        <!--<version>0.1.0</version>-->
    <!--</dependency>-->

    <dependency>
        <groupId>com.vimalselvam</groupId>
        <artifactId>cucumber-extentsreport</artifactId>
        <version>2.0.4</version>
    </dependency>

    <dependency>
        <groupId>com.aventstack</groupId>
        <artifactId>extentreports</artifactId>
        <version>3.0.2</version>
    </dependency>

    <dependency>
        <groupId>com.browserstack</groupId>
        <artifactId>browserstack-local-java</artifactId>
        <version>0.1.0</version>
    </dependency>

    <dependency>
        <groupId>report.donut</groupId>
        <artifactId>donut</artifactId>
        <version>1.1</version>
    </dependency>

    <!--<dependency>-->
        <!--<groupId>com.browserstack</groupId>-->
        <!--<artifactId>automate-testassist</artifactId>-->
        <!--<version>0.7.2-SNAPSHOT</version>-->
    <!--</dependency>-->

    <!--<dependency>-->
        <!--<groupId>com.browserstack</groupId>-->
        <!--<artifactId>browserstack-integration</artifactId>-->
        <!--<version>LATEST</version>-->
    <!--</dependency>-->

</dependencies>
</code>```

I am not able to figure out why I have suddenly started to get this error.

答:
Make sure to use latest client library, which is 5.0.4 since you are on Appium 1.7.1.

Clean maven cache from .m2\repository and install dependencies from scratch.

It also maybe the case you mixed incompatible annotations while defining some element. Check here for working examples

Body:
I have suddenly started facing below error:

java.lang.IllegalArgumentException: If you use a '@$Proxy21' annotation, you must not also use a '@$Proxy23' annotation
  at io.appium.java_client.pagefactory.DefaultElementByBuilder.checkDisallowedAnnotationPairs(DefaultElementByBuilder.java:46)
    at io.appium.java_client.pagefactory.DefaultElementByBuilder.assertValidAnnotations(DefaultElementByBuilder.java:87)

I am using below code to init elements:

  PageFactory.initElements(new AppiumFieldDecorator(appiumDriver, 6, TimeUnit.SECONDS), this);

It was working all fine & without any major changes its now failing.

Appium version: 1.7.1

My POM.xml

   <dependencies>

    <dependency>
        <groupId>com.github.fge</groupId>
        <artifactId>json-schema-validator</artifactId>
        <version>2.0.0</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>${jackson.version}</version>
    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>${selenium.java.version}</version>
    </dependency>

    <dependency>
        <groupId>com.vimalselvam</groupId>
        <artifactId>cucumber-extentsreport</artifactId>
        <version>${cucumber.extentsreport.version}</version>
    </dependency>

    <dependency>
        <groupId>io.appium</groupId>
        <artifactId>java-client</artifactId>
        <version>${appium.java-client.version}</version>

    </dependency>

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>${log4j.version}</version>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>${cucumber-java.version}</version>
    </dependency>

    <dependency>
        <groupId>com.jayway.jsonpath</groupId>
        <artifactId>json-path</artifactId>
        <version>${json-path.version}</version>
    </dependency>

    <dependency>
        <groupId>org.monte.screenrecorder</groupId>
        <artifactId>MonteScreenRecorder</artifactId>
        <version>10</version>
        <scope>system</scope>
        <systemPath>${basedir}/lib/monte-screen-recorder-0.7.7.jar</systemPath>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>${cucumber-junit.version}</version>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-core</artifactId>
        <version>${cucumber-junit.version}</version>
    </dependency>

    <dependency>
        <groupId>com.googlecode.json-simple</groupId>
        <artifactId>json-simple</artifactId>
        <version>${json-simple.version}</version>
    </dependency>

    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-library</artifactId>
        <version>${hamcrest-library.version}</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-jvm-deps</artifactId>
        <version>1.0.5</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-picocontainer</artifactId>
        <version>1.2.5</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.junit</groupId>
        <artifactId>junit5-engine</artifactId>
        <version>5.0.0-ALPHA</version>
    </dependency>
    <dependency>
        <groupId>com.relevantcodes</groupId>
        <artifactId>extentreports</artifactId>
        <version>2.41.2</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>com.vimalselvam</groupId>
        <artifactId>cucumber-extentsreport</artifactId>
        <version>2.0.4</version>
    </dependency>

    <dependency>
        <groupId>com.aventstack</groupId>
        <artifactId>extentreports</artifactId>
        <version>3.0.2</version>
    </dependency>

    <dependency>
        <groupId>com.browserstack</groupId>
        <artifactId>browserstack-local-java</artifactId>
        <version>0.1.0</version>
    </dependency>

    <dependency>
        <groupId>report.donut</groupId>
        <artifactId>donut</artifactId>
        <version>1.1</version>
    </dependency>

</dependencies>

I am not able to figure out why I have suddenly started to get this error.


问:
C++ - enum vs. const vs. #define
At the end of the article here: http://www.learncpp.com/cpp-tutorial/45-enumerated-types/, it mentions the following:

Finally, as with constant variables, enumerated types show up in the debugger, making them more useful than #defined values in this regard.

How is the bold sentence above achieved?

Thanks.

答:
#define values are replaced by the pre-processor with the value they are declared as, so in the debugger, it only sees the value, not the #defined name, e.g. if you have #define NUMBER_OF_CATS 10, in the debugger you'll see only 10 (since the pre-processor has replaced every instance of NUMBER_OF_CATS in your code with 10.

An enumerated type is a type in itself and the values are constant instances of this type, and so the pre-processor leaves it alone and you'll see the symbolic description of the value in the debugger.

Title: C++ - enum vs. const vs. #define


问:
How to import Dictionary text file and check for word matches?
I generate a random string of 500 characters and want to check for words.

```<code>bliduuwfhbgphwhsyzjnlfyizbjfeeepsbpgplpbhaegyepqcjhhotovnzdtlracxrwggbcmjiglasjvmscvxwazmutqiwppzcjhijjbguxfnduuphhsoffaqwtmhmensqmyicnciaoczumjzyaaowbtwjqlpxuuqknxqvmnueknqcbvkkmildyvosczlbnlgumohosemnfkmndtiubfkminlriytmbtrzhwqmovrivxxojbpirqahatmydqgulammsnfgcvgfncqkpxhgikulsjynjrjypxwvlkvwvigvjvuydbjfizmbfbtjprxkmiqpfuyebllzezbxozkiidpplvqkqlgdlvjbfeticedwomxgawuphocisaejeonqehoipzsjgbfdatbzykkurrwwtajeajeornrhyoqadljfjyizzfluetynlrpoqojxxqmmbuaktjqghqmusjfvxkkyoewgyckpbmismwyfebaucsfueuwgio
</code>```

I import a Dictionary Words txt file and check the string to see if it contains each word. If a match is found, it's added to a list.

I read using Dictionary<> is faster than Array for a words list.

When I use that method, I can see the cpu working the foreach loop in the debugger, and my loop counter goes up, about 10,000+ times in 10 seconds, but the loop continues on forever and does not return any results.

When I use Array for Dictionary, the program works, but slower at around 500 times in 10 seconds.

Not Working

Using Dictionary<>

```<code>// Random Message
public string message = Random(500);

// Dictionary Words Reference
public Dictionary<string, string> dictionary = new Dictionary<string, string>();

// Matches Found
public static List<string> matches = new List<string>();

public MainWindow()
{
    InitializeComponent();

    // Import Dictionary File
    dictionary = File
                    .ReadLines(@"C:\dictionary.txt")
                    .Select((v, i) => new { Index = i, Value = v })
                    .GroupBy(p => p.Index / 2)
                    .ToDictionary(g => g.First().Value, g => g.Last().Value);

    // If Message Contains word, add to Matches List
    foreach (KeyValuePair<string, string> entry in dictionary)
    {
        if (message.Contains(entry.Value))
        {
            matches.Add(entry.Value);
        }
    }
}
</code>```

Working

Using Array

```<code>// Random Message
public string message = Random(500);

// Dictionary Words Reference
public string[] dictionary = File.ReadAllLines(@"C:\dictionary.txt");

// Matches Found
public List<string> matches = new List<string>();

public MainWindow()
{
    InitializeComponent();

    // If Message Contains word, add to Matches List
    foreach (var entry in dictionary)
    {
        if (message.Contains(entry))
        {
            matches.Add(entry);
        }
    }
}
</code>```

答:
I doubt if you want Dictionary<string, string> as a dictionary ;) HashSet<string> will be enough:

```<code>  using System.Linq;

  ...

  string source = "bliduuwfhbgphwhsyzjnlfyizbj";

  HashSet<string> allWords = new HashSet<string>(File
    .ReadLines(@"C:\dictionary.txt")
    .Select(line => line.Trim())
    .Where(line => !string.IsNullOrEmpty(line)), StringComparer.OrdinalIgnoreCase);

  int shortestWord = allWords.Min(word => word.Length);
  int longestWord = allWords.Max(word => word.Length);

  // If you want duplicates, change HashSet<string> to List<string>
  HashSet<string> wordsFound = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

  for (int length = shortestWord; length <= longestWord; ++length) {
    for (int position = 0; position <= source.Length - length; ++position) {
      string extract = source.Substring(position, length);

      if (allWords.Contains(extract))
        wordsFound.Add(extract);
    }
  }
</code>```

Test: for

https://raw.githubusercontent.com/dolph/dictionary/master/popular.txt

dictionary donwloaded as C:\dictionary.txt file

```<code>  Console.WriteLine(string.Join(", ", wordsFound.OrderBy(x => x)));
</code>```

we have output

```<code>  id, li, lid
</code>```

Body:
I generate a random string of 500 characters and want to check for words.

bliduuwfhbgphwhsyzjnlfyizbjfeeepsbpgplpbhaegyepqcjhhotovnzdtlracxrwggbcmjiglasjvmscvxwazmutqiwppzcjhijjbguxfnduuphhsoffaqwtmhmensqmyicnciaoczumjzyaaowbtwjqlpxuuqknxqvmnueknqcbvkkmildyvosczlbnlgumohosemnfkmndtiubfkminlriytmbtrzhwqmovrivxxojbpirqahatmydqgulammsnfgcvgfncqkpxhgikulsjynjrjypxwvlkvwvigvjvuydbjfizmbfbtjprxkmiqpfuyebllzezbxozkiidpplvqkqlgdlvjbfeticedwomxgawuphocisaejeonqehoipzsjgbfdatbzykkurrwwtajeajeornrhyoqadljfjyizzfluetynlrpoqojxxqmmbuaktjqghqmusjfvxkkyoewgyckpbmismwyfebaucsfueuwgio

I import a Dictionary Words txt file and check the string to see if it contains each word. If a match is found, it's added to a list.

I read using Dictionary<> is faster than Array for a words list.

When I use that method, I can see the cpu working the foreach loop in the debugger, and my loop counter goes up, about 10,000+ times in 10 seconds, but the loop continues on forever and does not return any results.

When I use Array for Dictionary, the program works, but slower at around 500 times in 10 seconds.

Not Working

Using Dictionary<>

// Random Message
public string message = Random(500);

// Dictionary Words Reference
public Dictionary<string, string> dictionary = new Dictionary<string, string>();

// Matches Found
public static List<string> matches = new List<string>();

public MainWindow()
{
    InitializeComponent();

    // Import Dictionary File
    dictionary = File
                    .ReadLines(@"C:\dictionary.txt")
                    .Select((v, i) => new { Index = i, Value = v })
                    .GroupBy(p => p.Index / 2)
                    .ToDictionary(g => g.First().Value, g => g.Last().Value);

    // If Message Contains word, add to Matches List
    foreach (KeyValuePair<string, string> entry in dictionary)
    {
        if (message.Contains(entry.Value))
        {
            matches.Add(entry.Value);
        }
    }
}

Working

Using Array

// Random Message
public string message = Random(500);

// Dictionary Words Reference
public string[] dictionary = File.ReadAllLines(@"C:\dictionary.txt");

// Matches Found
public List<string> matches = new List<string>();

public MainWindow()
{
    InitializeComponent();

    // If Message Contains word, add to Matches List
    foreach (var entry in dictionary)
    {
        if (message.Contains(entry))
        {
            matches.Add(entry);
        }
    }
}

Body:
I doubt if you want Dictionary<string, string> as a dictionary ;) HashSet<string> will be enough:

  using System.Linq;

  ...

  string source = "bliduuwfhbgphwhsyzjnlfyizbj";

  HashSet<string> allWords = new HashSet<string>(File
    .ReadLines(@"C:\dictionary.txt")
    .Select(line => line.Trim())
    .Where(line => !string.IsNullOrEmpty(line)), StringComparer.OrdinalIgnoreCase);

  int shortestWord = allWords.Min(word => word.Length);
  int longestWord = allWords.Max(word => word.Length);

  // If you want duplicates, change HashSet<string> to List<string>
  HashSet<string> wordsFound = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

  for (int length = shortestWord; length <= longestWord; ++length) {
    for (int position = 0; position <= source.Length - length; ++position) {
      string extract = source.Substring(position, length);

      if (allWords.Contains(extract))
        wordsFound.Add(extract);
    }
  }

Test: for

https://raw.githubusercontent.com/dolph/dictionary/master/popular.txt

dictionary donwloaded as C:\dictionary.txt file

  Console.WriteLine(string.Join(", ", wordsFound.OrderBy(x => x)));

we have output

  id, li, lid


问:
How to modify paths to work for every user? (Python)
Ok I know this is probably a very simple question to answer but I don't know how to find the answer (I don't know the technical words used for this concept,etc)

I have a folder path like this one. Obviously where I've written "MYUSERNAME" I'd normally write my real username

C:\Users\MYUSERNAME\Desktop\Test

I'm using that path for a python code that I've previously compiled, and I want my friends to use that code without having to change the code. How do I automatically fill that "MYUSERNAME" with the username of the current user?
I've tried writing "User" and such in there but nothing works. Even if I have to add a few lines of code I don't care.

答:
The Path library in Python can probably help you out here. For example, the below snippet provides the home path of the logged in user:

```<code>import os
from pathlib import Path
home = str(Path.home())
myPath = os.path.join(home, "Desktop", "Test")
#This gives the required path, i.e `C:\Users\MYUSERNAME\Desktop\Test` for the logged in user running the code
</code>```

There are a few caveats here, and the above snippet doesn't work as expected if the user is logged on to a domain on windows and has their profile home folder set in active directory. However, your question specifies no such constraint so this should be good enough.

Body:
The Path library in Python can probably help you out here. For example, the below snippet provides the home path of the logged in user:

import os
from pathlib import Path
home = str(Path.home())
myPath = os.path.join(home, "Desktop", "Test")
#This gives the required path, i.e `C:\Users\MYUSERNAME\Desktop\Test` for the logged in user running the code

There are a few caveats here, and the above snippet doesn't work as expected if the user is logged on to a domain on windows and has their profile home folder set in active directory. However, your question specifies no such constraint so this should be good enough.


答:
The problem is that you use the assignment operator on the parameter result which prevents the data from being transferred to the C# array on return.

Using the following C++ example:

```<code>void z(int * x)
{
  x = new int(4);
}

int main()
{
  int * x = new int(-2);
  z(x);
  cout<<*x<<endl;
}
</code>```

The output for this is -2 not 4 because you use the assignment operator on the parameter.

Title: Getting float array from C++ to C#

Body:
The problem is that you use the assignment operator on the parameter result which prevents the data from being transferred to the C# array on return.

Using the following C++ example:

void z(int * x)
{
  x = new int(4);
}

int main()
{
  int * x = new int(-2);
  z(x);
  cout<<*x<<endl;
}

The output for this is -2 not 4 because you use the assignment operator on the parameter.


问:
Android : close all the activities when Login activity is started
I have two activity Login and Main, when the user start the application, the Main activity start and verify if the user is login, if not, the app redirect the user to the login activity.

All that works fine, but the problem when the Back Button click in login activity the app start the activity Main, I want the app exit..
Any help please.

答:
It works for me adding</p>

```<code>i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
</code>```

Body:
It works for me adding

i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);


问:
mmap and kernel memory
I understand from mmap() internals that a mmap read works by
- causing a page fault
- copying file data from disk to internal kernel buffer
- mapping the kernel buffer to user space

My questions are:

What happens to the kernel mapping to the buffer? if it still exists, dont we have a problem here of user application gaining access to kernel memory?

cant we run out of physical memory this way? I'd assume the kernel needs a minimum amount of physical memory to provide decent level of performance, and if we keep allocating it's buffers to mmapped user space buffer we'd eventually run out of buffers.

during a write, does the relevant memory gets mapped temporarily to a kernel buffer? if and this is a shared maping, another user process may access and again gain access to what is now kernel memory

Thanks, and sorry if these questions are pretty basic, but I did not find a clear answer.

答:
I'm not a kernel hacker by any means, but this is what I've gathered:

I'm not entirely sure when it comes to the question of whether the kernel "relinquishes" its mapping to physical memory, since the kernel can access any physical memory it pleases. However, it would obviously be impermissible for the kernel to keep using that physical memory for its own purposes (e.g. as an internal pipe buffer) if user processes can access that memory as well, for the sake of both the user process and for the sake of the kernel. The kernel will simply designate those pages as part of the filesystem cache (if backed by a file) and not mess with them.

Yes, to the same extent that any process or number of processes can limit the amount of physical memory present for the kernel by requesting lots of resources like pipes. However, the kernel keeps track of how much physical memory is available and will start to page out userland memory to the disk when the remaining amount of physical memory runs low. Kernel memory itself typically should not be paged out to the disk for reasons including performance. Though the nice thing about mmap()ed memory backed by  a file is that it's trivial to page out to the disk; no swap space needs to be allocated.

If you mean a write to available memory mapped to userland virtual address space (i.e. memcpy(), not write()), no. The whole point of mmap() is to map userland virtual address space to physical memory to allow reads and writes without resorting to system calls. Syncs to the disk will be performed directly by the kernel without additional copying to kernel buffers.

Title: mmap and kernel memory