问:
Efficiently ranking string matches by number of matched terms
Summary: how to most efficiently count multiple regex matches and rank results by incidence? Are there semantic approaches that should be used instead of regex?

Sample data for illustration:

```<code>sample_string <- c("Total - Main mode of commuting for the employed labour force aged 15 years and over in private households with a usual place of work or no fixed workplace address - 25% sample data",
"Total - Language used most often at work for the population in private households aged 15 years and over who worked since January 1, 2015 - 25% sample data",
"Number of market income recipients aged 15 years and over in private households - 25% sample data",
"Number of employment income recipients aged 15 years and over in private households",
"Total - Major field of study - Classification of Instructional Programs (CIP) 2016 for the population aged 15 years and over in private households - 25% sample data",
"Total - Selected places of birth for the recent immigrant population in private households - 25% sample data",
"Total - Commuting duration for the employed labour force aged 15 years and over in private households with a usual place of work or no fixed workplace address - 25% sample data",
"Number of market income recipients aged 15 years and over in private households",
"Employment income (%)", "Total - Aboriginal ancestry for the population in private households - 25% sample data",
"Without employment income", "With after-tax income", "1 household maintainer",
"Spending 30% or more of income on shelter costs", "Total - Highest certificate, diploma or degree for the population aged 25 to 64 years in private households - 25% sample data"
)
</code>```

And a sample string query containing multiple terms

```<code>sample_query <- c("after tax income")
</code>```

It is easy to check for a match of the string query using grepl.

```<code>sample_string[grepl(sample_query, sample_string)]
</code>```

But obviously this wouldn't work here because there is no exact match, because the actual term is after-tax income. An alternative is to separate the search query into parts and check against that.

```<code>sample_string[grepl(paste(unlist(strsplit(sample_query, " +")), collapse = "|"), sample_string)]
</code>```

This would work, but would return too many results, because it matches against any instance of any of those terms.

```<code>[1] "Number of market income recipients aged 15 years and over in private households - 25% sample data"
[2] "Number of employment income recipients aged 15 years and over in private households"
[3] "Number of market income recipients aged 15 years and over in private households"
[4] "Employment income (%)"
[5] "Without employment income"
[6] "With after-tax income"
[7] "Spending 30% or more of income on shelter costs"
</code>```

The question: how to effectively return the closest match based on number of individual matches?

Applying some of the answers here, and adding ordering and matching leads to monstrosity:

```<code>sample_string[grepl(paste(unlist(strsplit(sample_query, " +")),
                          collapse = "|"),
                    sample_string)][order(-lengths(regmatches(
                      sample_string[grepl(paste(unlist(strsplit(sample_query, " +")),
                                                collapse = "|"),
                                          sample_string)],
                      gregexpr(paste(unlist(
                        strsplit(sample_query, " +")
                      ),
                      collapse = "|"),
                      sample_string[grepl(paste(unlist(strsplit(sample_query, " +")),
                                                collapse = "|"),
                                          sample_string)])
                    )))]
</code>```

Which returns what I want - a list of all strings with at least one match, ordered by the number of matches.

```<code>[1] "With after-tax income"
[2] "Number of market income recipients aged 15 years and over in private households - 25% sample data"
[3] "Number of employment income recipients aged 15 years and over in private households"
[4] "Number of market income recipients aged 15 years and over in private households"
[5] "Employment income (%)"
[6] "Without employment income"
[7] "Spending 30% or more of income on shelter costs"
</code>```

Cleaning the above monstrosity up a little bit:

```<code>to_match <- paste(unlist(strsplit(sample_query, " +")),collapse = "|")
results <- sample_string[grepl(to_match,sample_string)]
results[order(-lengths(regmatches(results,gregexpr(to_match,results))))]
</code>```

I can live with this, but is there a way to make this more concise? And, what I'm wondering is whether this is even the best way to approach this?

I am aware of stringr::str_count and stringi::stri_count_regex. This for a package and I'm trying to avoid adding additional dependencies , but if these are much more efficient I am fine to use that instead.

Or, alternatively, is a string distance alternative a better option? Is it still better when checking against thousands of long strings?

The intent is to help users find relevant information, perhaps there is something a little bit more semantically oriented that would make sense.

答:
I'm sure this can be improved but here is one way of doing what you are after using Levenshtein Distance:

```<code># Desired query scalar: actual_query => character vector
actual_query <- "after tax income"

# Separate words in query: query_words => character vector:
query_words <- unlist(strsplit(tolower(actual_query), "[^a-z]+"))

# Calculate n (scalar) for n-grams: word_count => integer vector
word_count <- length(query_words)

# Split each word preserving any non-character values:
# sentence_word_split => character vector
sentence_word_split <- strsplit(tolower(sample_string), "\\s+")

# Split original sentences into n-grams (relative to query length):
# n_grams => list
n_grams <- lapply(sentence_word_split, function(x){
              sapply(seq_along(x), function(i){
                paste(x[i:min(length(x), ((i+word_count)-1))], sep = " ", collapse = " ")
      }
    )
  }
)

# Rank ngrams based on the frequency of their occurence in sample string:
# ordered_n_gram => character vector
ordered_ngram_count <- trimws(names(sort(table(unlist(n_grams)), decreasing = TRUE)), "both")

# Combine the query with each of its elements: revised_query => character vector
revised_query <- c(actual_query, unlist(strsplit(actual_query, "\\s+")))

# Use levenshtein distance to determine similarity of revised_query
# to the expressions in the ordered_ngram_count: lev_dist_df => data.frame
lev_dist_df <- setNames(data.frame(sapply(seq_along(revised_query),
                    function(i){
                       adist(revised_query[i], ordered_ngram_count)
                      }
                    )), gsub("\\s+", "_", revised_query))

# Example of applying function returning string element in sample string
# with the minimum edit distance: sample_string element => stdout (console)
grep(grep(ordered_ngram_count[sapply(seq_along(ncol(lev_dist_df)),
                                     function(i) {
                                       which.min(lev_dist_df[, i])
                                     })], sample_string,
          value = TRUE),
     sample_string,
     value = TRUE)
</code>```

Cleaner version of above:

```<code># Desired query scalar: sample_query => character vector
sample_query <- "after tax income"

# Separate words in query: query_words => character vector:
query_words <- unlist(strsplit(tolower(sample_query), "[^a-z]+"))

# Calculate n (scalar) for n-grams: word_count => integer vector
word_count <- length(query_words)

# Split each word preserving any non-character values:
# sentence_word_split => character vector
sentence_word_split <- strsplit(tolower(sample_string), "\\s+")

# Split original sentences into n-grams (relative to query length):
# n_grams => list
n_grams <- lapply(sentence_word_split, function(x){
    sapply(seq_along(x), function(i){
      paste(x[i:min(length(x), ((i+word_count)-1))], sep = " ", collapse = " ")
      }
    )
  }
)

# Rank ngrams based on the frequency of their occurence in sample string:
# ordered_n_gram => character vector
ordered_ngram_count <- trimws(names(sort(table(unlist(n_grams)), decreasing = TRUE)), "both")

# Use levenshtein distance to determine similarity of revised_query
# to the expressions in the ordered_ngram_count: lev_dist_df => data.frame
lev_dist_df <- setNames(data.frame(sapply(seq_along(sample_query),
                                          function(i){
                                            adist(sample_query[i], ordered_ngram_count)
                                          })), gsub("\\s+", "_", sample_query))

# Example of applying function returning string element in sample string
# with the minimum edit distance: sample_string element => stdout (console)
grep(grep(ordered_ngram_count[which.min(lev_dist_df[,1])], sample_string,
          value = TRUE), sample_string, value = TRUE)
</code>```

Data:

```<code>sample_string <- c("Total - Main mode of commuting for the employed labour force aged 15 years and over in private households with a usual place of work or no fixed workplace address - 25% sample data",
                   "Total - Language used most often at work for the population in private households aged 15 years and over who worked since January 1, 2015 - 25% sample data",
                   "Number of market income recipients aged 15 years and over in private households - 25% sample data",
                   "Number of employment income recipients aged 15 years and over in private households",
                   "Total - Major field of study - Classification of Instructional Programs (CIP) 2016 for the population aged 15 years and over in private households - 25% sample data",
                   "Total - Selected places of birth for the recent immigrant population in private households - 25% sample data",
                   "Total - Commuting duration for the employed labour force aged 15 years and over in private households with a usual place of work or no fixed workplace address - 25% sample data",
                   "Number of market income recipients aged 15 years and over in private households",
                   "Employment income (%)", "Total - Aboriginal ancestry for the population in private households - 25% sample data",
                   "Without employment income", "With after-tax income", "1 household maintainer",
                   "Spending 30% or more of income on shelter costs", "Total - Highest certificate, diploma or degree for the population aged 25 to 64 years in private households - 25% sample data"
)
</code>```

Body:
Summary: how to most efficiently count multiple regex matches and rank results by incidence? Are there semantic approaches that should be used instead of regex?

Sample data for illustration:

sample_string <- c("Total - Main mode of commuting for the employed labour force aged 15 years and over in private households with a usual place of work or no fixed workplace address - 25% sample data",
"Total - Language used most often at work for the population in private households aged 15 years and over who worked since January 1, 2015 - 25% sample data",
"Number of market income recipients aged 15 years and over in private households - 25% sample data",
"Number of employment income recipients aged 15 years and over in private households",
"Total - Major field of study - Classification of Instructional Programs (CIP) 2016 for the population aged 15 years and over in private households - 25% sample data",
"Total - Selected places of birth for the recent immigrant population in private households - 25% sample data",
"Total - Commuting duration for the employed labour force aged 15 years and over in private households with a usual place of work or no fixed workplace address - 25% sample data",
"Number of market income recipients aged 15 years and over in private households",
"Employment income (%)", "Total - Aboriginal ancestry for the population in private households - 25% sample data",
"Without employment income", "With after-tax income", "1 household maintainer",
"Spending 30% or more of income on shelter costs", "Total - Highest certificate, diploma or degree for the population aged 25 to 64 years in private households - 25% sample data"
)

And a sample string query containing multiple terms

sample_query <- c("after tax income")

It is easy to check for a match of the string query using grepl.

sample_string[grepl(sample_query, sample_string)]

But obviously this wouldn't work here because there is no exact match, because the actual term is after-tax income. An alternative is to separate the search query into parts and check against that.

sample_string[grepl(paste(unlist(strsplit(sample_query, " +")), collapse = "|"), sample_string)]

This would work, but would return too many results, because it matches against any instance of any of those terms.

[1] "Number of market income recipients aged 15 years and over in private households - 25% sample data"
[2] "Number of employment income recipients aged 15 years and over in private households"
[3] "Number of market income recipients aged 15 years and over in private households"
[4] "Employment income (%)"
[5] "Without employment income"
[6] "With after-tax income"
[7] "Spending 30% or more of income on shelter costs"

The question: how to effectively return the closest match based on number of individual matches?

Applying some of the answers here, and adding ordering and matching leads to monstrosity:

sample_string[grepl(paste(unlist(strsplit(sample_query, " +")),
                          collapse = "|"),
                    sample_string)][order(-lengths(regmatches(
                      sample_string[grepl(paste(unlist(strsplit(sample_query, " +")),
                                                collapse = "|"),
                                          sample_string)],
                      gregexpr(paste(unlist(
                        strsplit(sample_query, " +")
                      ),
                      collapse = "|"),
                      sample_string[grepl(paste(unlist(strsplit(sample_query, " +")),
                                                collapse = "|"),
                                          sample_string)])
                    )))]

Which returns what I want - a list of all strings with at least one match, ordered by the number of matches.

[1] "With after-tax income"
[2] "Number of market income recipients aged 15 years and over in private households - 25% sample data"
[3] "Number of employment income recipients aged 15 years and over in private households"
[4] "Number of market income recipients aged 15 years and over in private households"
[5] "Employment income (%)"
[6] "Without employment income"
[7] "Spending 30% or more of income on shelter costs"

Cleaning the above monstrosity up a little bit:

to_match <- paste(unlist(strsplit(sample_query, " +")),collapse = "|")
results <- sample_string[grepl(to_match,sample_string)]
results[order(-lengths(regmatches(results,gregexpr(to_match,results))))]

I can live with this, but is there a way to make this more concise? And, what I'm wondering is whether this is even the best way to approach this?

I am aware of stringr::str_count and stringi::stri_count_regex. This for a package and I'm trying to avoid adding additional dependencies , but if these are much more efficient I am fine to use that instead.

Or, alternatively, is a string distance alternative a better option? Is it still better when checking against thousands of long strings?

The intent is to help users find relevant information, perhaps there is something a little bit more semantically oriented that would make sense.

Body:
I'm sure this can be improved but here is one way of doing what you are after using Levenshtein Distance:

# Desired query scalar: actual_query => character vector
actual_query <- "after tax income"

# Separate words in query: query_words => character vector:
query_words <- unlist(strsplit(tolower(actual_query), "[^a-z]+"))

# Calculate n (scalar) for n-grams: word_count => integer vector
word_count <- length(query_words)

# Split each word preserving any non-character values:
# sentence_word_split => character vector
sentence_word_split <- strsplit(tolower(sample_string), "\\s+")

# Split original sentences into n-grams (relative to query length):
# n_grams => list
n_grams <- lapply(sentence_word_split, function(x){
              sapply(seq_along(x), function(i){
                paste(x[i:min(length(x), ((i+word_count)-1))], sep = " ", collapse = " ")
      }
    )
  }
)

# Rank ngrams based on the frequency of their occurence in sample string:
# ordered_n_gram => character vector
ordered_ngram_count <- trimws(names(sort(table(unlist(n_grams)), decreasing = TRUE)), "both")

# Combine the query with each of its elements: revised_query => character vector
revised_query <- c(actual_query, unlist(strsplit(actual_query, "\\s+")))

# Use levenshtein distance to determine similarity of revised_query
# to the expressions in the ordered_ngram_count: lev_dist_df => data.frame
lev_dist_df <- setNames(data.frame(sapply(seq_along(revised_query),
                    function(i){
                       adist(revised_query[i], ordered_ngram_count)
                      }
                    )), gsub("\\s+", "_", revised_query))

# Example of applying function returning string element in sample string
# with the minimum edit distance: sample_string element => stdout (console)
grep(grep(ordered_ngram_count[sapply(seq_along(ncol(lev_dist_df)),
                                     function(i) {
                                       which.min(lev_dist_df[, i])
                                     })], sample_string,
          value = TRUE),
     sample_string,
     value = TRUE)

Cleaner version of above:

# Desired query scalar: sample_query => character vector
sample_query <- "after tax income"

# Separate words in query: query_words => character vector:
query_words <- unlist(strsplit(tolower(sample_query), "[^a-z]+"))

# Calculate n (scalar) for n-grams: word_count => integer vector
word_count <- length(query_words)

# Split each word preserving any non-character values:
# sentence_word_split => character vector
sentence_word_split <- strsplit(tolower(sample_string), "\\s+")

# Split original sentences into n-grams (relative to query length):
# n_grams => list
n_grams <- lapply(sentence_word_split, function(x){
    sapply(seq_along(x), function(i){
      paste(x[i:min(length(x), ((i+word_count)-1))], sep = " ", collapse = " ")
      }
    )
  }
)

# Rank ngrams based on the frequency of their occurence in sample string:
# ordered_n_gram => character vector
ordered_ngram_count <- trimws(names(sort(table(unlist(n_grams)), decreasing = TRUE)), "both")

# Use levenshtein distance to determine similarity of revised_query
# to the expressions in the ordered_ngram_count: lev_dist_df => data.frame
lev_dist_df <- setNames(data.frame(sapply(seq_along(sample_query),
                                          function(i){
                                            adist(sample_query[i], ordered_ngram_count)
                                          })), gsub("\\s+", "_", sample_query))

# Example of applying function returning string element in sample string
# with the minimum edit distance: sample_string element => stdout (console)
grep(grep(ordered_ngram_count[which.min(lev_dist_df[,1])], sample_string,
          value = TRUE), sample_string, value = TRUE)

Data:

sample_string <- c("Total - Main mode of commuting for the employed labour force aged 15 years and over in private households with a usual place of work or no fixed workplace address - 25% sample data",
                   "Total - Language used most often at work for the population in private households aged 15 years and over who worked since January 1, 2015 - 25% sample data",
                   "Number of market income recipients aged 15 years and over in private households - 25% sample data",
                   "Number of employment income recipients aged 15 years and over in private households",
                   "Total - Major field of study - Classification of Instructional Programs (CIP) 2016 for the population aged 15 years and over in private households - 25% sample data",
                   "Total - Selected places of birth for the recent immigrant population in private households - 25% sample data",
                   "Total - Commuting duration for the employed labour force aged 15 years and over in private households with a usual place of work or no fixed workplace address - 25% sample data",
                   "Number of market income recipients aged 15 years and over in private households",
                   "Employment income (%)", "Total - Aboriginal ancestry for the population in private households - 25% sample data",
                   "Without employment income", "With after-tax income", "1 household maintainer",
                   "Spending 30% or more of income on shelter costs", "Total - Highest certificate, diploma or degree for the population aged 25 to 64 years in private households - 25% sample data"
)


来源: stackexchange

问:
q agent is learning not to take any actions
I'm training a deep q network to trade stocks; it has two possible actions; 0 : wait, 1 : buy stock if one isn't bought, sell one if one is bought. It gets, as input, the value of the stock it bought, the current value of the stock and the values of the stock for the previous 5 time steps relative to it. So something like

```<code>[5.78, 5.93, -0.1, -0.2, -0.4, -0.5, -0.3]
</code>```

The reward is simply the difference between the price of the sale and the price of the purchase. The reward for any other action is 0, though I've tried having it be negative or something else without results.

simple, right? Unfortunately, the agent always converges on taking the "0" action. Even when I magnify the reward for selling at a profit or any number of things. I'm really pulling my hair out, is there something obvious I've missed?

答: Although something was probably broken with the agent itself, the second agent I wrote exhibited similar behavior. I finally solved the issue by decreasing the learning rate; in the end it had to be about a thousand times lower than it was</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm training a deep q network to trade stocks; it has two possible actions; 0 : wait, 1 : buy stock if one isn't bought, sell one if one is bought. It gets, as input, the value of the stock it bought, the current value of the stock and the values of the stock for the previous 5 time steps relative to it. So something like

[5.78, 5.93, -0.1, -0.2, -0.4, -0.5, -0.3]

The reward is simply the difference between the price of the sale and the price of the purchase. The reward for any other action is 0, though I've tried having it be negative or something else without results.

simple, right? Unfortunately, the agent always converges on taking the "0" action. Even when I magnify the reward for selling at a profit or any number of things. I'm really pulling my hair out, is there something obvious I've missed?


问:
Unity object reference not set to an instance of an object unity
I have a "object reference not set to an instance of an object unity" errors even though I have an instance of object in project.

```<code>26: teslaGun = GameObject.Find("TeslaGun");
27: teslaGunController = teslaGun.GetComponent<TeslaGunController>();

35: arms = GameObject.Find("Arms").gameObject;

47: if (arms.activeSelf)
</code>```

答:
Well, I solved it by having (I suppose) some monkey coding. </p>

```<code>void Start()
    {
        player = GameObject.Find("Player");
        playerController = player.GetComponent<PlayerController>();

        teslaGun = player.transform.Find("TeslaGun").gameObject;
        //teslaGun = GameObject.Find("Player/TeslaGun");
        teslaGunController = teslaGun.GetComponent<TeslaGunController>();

        shotGun = player.transform.Find("ShotGun").gameObject;
        //shotGun = GameObject.Find("Player/ShotGun");
        shotGunController = shotGun.GetComponent<ShotGunController>();

        subMachineGun = player.transform.Find("SubMachineGun").gameObject;
        //subMachineGun = GameObject.Find("Player/SubMachineGun");
        sMGController = subMachineGun.GetComponent<SMGController>();

        arms = player.transform.Find("Arms").gameObject;
        //arms = GameObject.Find("Player/Arms").gameObject;

    }
</code>```

Body:
I have a "object reference not set to an instance of an object unity" errors even though I have an instance of object in project.

26: teslaGun = GameObject.Find("TeslaGun");
27: teslaGunController = teslaGun.GetComponent<TeslaGunController>();

35: arms = GameObject.Find("Arms").gameObject;

47: if (arms.activeSelf)

Body:
Well, I solved it by having (I suppose) some monkey coding.

void Start()
    {
        player = GameObject.Find("Player");
        playerController = player.GetComponent<PlayerController>();

        teslaGun = player.transform.Find("TeslaGun").gameObject;
        //teslaGun = GameObject.Find("Player/TeslaGun");
        teslaGunController = teslaGun.GetComponent<TeslaGunController>();

        shotGun = player.transform.Find("ShotGun").gameObject;
        //shotGun = GameObject.Find("Player/ShotGun");
        shotGunController = shotGun.GetComponent<ShotGunController>();

        subMachineGun = player.transform.Find("SubMachineGun").gameObject;
        //subMachineGun = GameObject.Find("Player/SubMachineGun");
        sMGController = subMachineGun.GetComponent<SMGController>();

        arms = player.transform.Find("Arms").gameObject;
        //arms = GameObject.Find("Player/Arms").gameObject;

    }


问:
Download a file in IE11 with Selenium and Robot class
I try to download a file in IE11 with Selenium WebDriver and Robot class, I am using IntelliJ and running test on a Selenium Grid with IE11.

I don't use element.click() function, because the controls stop there, hence I use sendKeys to focus on donwload button. Download popup appears, here comes Robot class. I try to press Alt+S to save file with help from Robot, but it doesn't press Alt+S on IE, it presses Alt+S on my IntelliJ instead !!!. Here is my code:

```<code>if (webBrowser.equalsIgnoreCase("ie")) {
   WebElement downloadReport = webDriver.findElement(By.id("clientReportDownload"));
   try {
        Robot robot = new Robot();
// sendKeys to focus on Download button and press Enter to download
        downloadReport.sendKeys("");
        downloadReport.sendKeys(Keys.ENTER);
        waitSeconds(2);
// wait for Download popup
        robot.setAutoDelay(250);
// simulate presse Alt + S to save file  -> It presses Alt+S on IntelliJ instead !!!
        robot.keyPress(KeyEvent.VK_ALT);
        robot.keyPress(KeyEvent.VK_S);
        robot.keyRelease(KeyEvent.VK_ALT);
        robot.keyRelease(KeyEvent.VK_S);
        waitSeconds(2);
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }
</code>```

Does anyone have a solution for this?

答:
```<code>    Robot robot;
    try {
            // pressing download button
        dr.findElement(By.xpath("//a[@class='btn btn-primary']")).sendKeys("""");
            robot = new Robot();
            robot.keyPress(KeyEvent.VK_ENTER);
            robot.keyRelease(KeyEvent.VK_ENTER);

            // handling download
         Thread.sleep(2000);
            robot.keyPress(KeyEvent.VK_ALT);
            robot.keyPress(KeyEvent.VK_S);
            Thread.sleep(2000);
            robot.keyRelease(KeyEvent.VK_S);
            robot.keyRelease(KeyEvent.VK_ALT);
            Thread.sleep(2000);
            robot.keyPress(KeyEvent.VK_TAB);
            System.out.println("tab entered ");
            System.out.println("Download completed");
        } catch (Exception e) {
            e.printStackTrace();
        }
</code>```

Body:
I try to download a file in IE11 with Selenium WebDriver and Robot class, I am using IntelliJ and running test on a Selenium Grid with IE11.

I don't use element.click() function, because the controls stop there, hence I use sendKeys to focus on donwload button. Download popup appears, here comes Robot class. I try to press Alt+S to save file with help from Robot, but it doesn't press Alt+S on IE, it presses Alt+S on my IntelliJ instead !!!. Here is my code:

if (webBrowser.equalsIgnoreCase("ie")) {
   WebElement downloadReport = webDriver.findElement(By.id("clientReportDownload"));
   try {
        Robot robot = new Robot();
// sendKeys to focus on Download button and press Enter to download
        downloadReport.sendKeys("");
        downloadReport.sendKeys(Keys.ENTER);
        waitSeconds(2);
// wait for Download popup
        robot.setAutoDelay(250);
// simulate presse Alt + S to save file  -> It presses Alt+S on IntelliJ instead !!!
        robot.keyPress(KeyEvent.VK_ALT);
        robot.keyPress(KeyEvent.VK_S);
        robot.keyRelease(KeyEvent.VK_ALT);
        robot.keyRelease(KeyEvent.VK_S);
        waitSeconds(2);
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }

Does anyone have a solution for this?

Body:
    Robot robot;
    try {
            // pressing download button
        dr.findElement(By.xpath("//a[@class='btn btn-primary']")).sendKeys("&quot;&quot;");
            robot = new Robot();
            robot.keyPress(KeyEvent.VK_ENTER);
            robot.keyRelease(KeyEvent.VK_ENTER);

            // handling download
         Thread.sleep(2000);
            robot.keyPress(KeyEvent.VK_ALT);
            robot.keyPress(KeyEvent.VK_S);
            Thread.sleep(2000);
            robot.keyRelease(KeyEvent.VK_S);
            robot.keyRelease(KeyEvent.VK_ALT);
            Thread.sleep(2000);
            robot.keyPress(KeyEvent.VK_TAB);
            System.out.println("tab entered ");
            System.out.println("Download completed");
        } catch (Exception e) {
            e.printStackTrace();
        }


问:
AWS Lambda not showing cause Exception stacktrace in Python 3.8
I deployed the following code to an AWS Lambda using runtime Python 3.8.

```<code>try:
    raise Exception('my exception')
except Exception as e:
    raise ValueError('my exception 2') from e
</code>```

In CloudWatch, I expect to see exception chaining like this:

```<code>Traceback (most recent call last):
  File "/var/task/handler.py", line 2, in <module>
    raise Exception('my exception')
Exception: my exception

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/var/task/handler.py", line 4, in <module>
    raise ValueError('my exception 2') from e
ValueError: my exception 2
</code>```

Instead, I see only the first exception reported in CloudWatch like this:

```<code>[ERROR] ValueError: my exception 2
Traceback (most recent call last):
  File "/var/task/handler.py", line 21, in pevm_import_budget_file
    raise ValueError('my exception 2') from e
</code>```

Why isn't the direct cause exception from the from statement showing in the log?

答:
The behavior you mention is expected and I have seen the same as well. It seems Lambda does not support chained exceptions currently. However, to get around this, you could add in your own logger to capture the exceptions.

For example, using traceback to retrieve the exception stack:

```<code>import traceback

def lambda_handler(event, context):
    try:
        try:
            raise Exception('my exception')
        except Exception as e1:
            raise ValueError('my exception 2')
    except Exception as e2:
        traceback.print_exception(type(e2), value=e2, tb=e2.__traceback__)

    return {}
</code>```

And the CloudWatch logs look like:

```<code>Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 6, in lambda_handler
    raise Exception('my exception')
Exception: my exception

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 8, in lambda_handler
    raise ValueError('my exception 2')
ValueError: my exception 2
</code>```

Body:
I deployed the following code to an AWS Lambda using runtime Python 3.8.

try:
    raise Exception('my exception')
except Exception as e:
    raise ValueError('my exception 2') from e

In CloudWatch, I expect to see exception chaining like this:

Traceback (most recent call last):
  File "/var/task/handler.py", line 2, in <module>
    raise Exception('my exception')
Exception: my exception

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/var/task/handler.py", line 4, in <module>
    raise ValueError('my exception 2') from e
ValueError: my exception 2

Instead, I see only the first exception reported in CloudWatch like this:

[ERROR] ValueError: my exception 2
Traceback (most recent call last):
  File "/var/task/handler.py", line 21, in pevm_import_budget_file
    raise ValueError('my exception 2') from e

Why isn't the direct cause exception from the from statement showing in the log?

Body:
The behavior you mention is expected and I have seen the same as well. It seems Lambda does not support chained exceptions currently. However, to get around this, you could add in your own logger to capture the exceptions.

For example, using traceback to retrieve the exception stack:

import traceback

def lambda_handler(event, context):
    try:
        try:
            raise Exception('my exception')
        except Exception as e1:
            raise ValueError('my exception 2')
    except Exception as e2:
        traceback.print_exception(type(e2), value=e2, tb=e2.__traceback__)

    return {}

And the CloudWatch logs look like:

Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 6, in lambda_handler
    raise Exception('my exception')
Exception: my exception

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 8, in lambda_handler
    raise ValueError('my exception 2')
ValueError: my exception 2


问:
how to write a backtracking concatenated parser in haskell
I'm trying to get a parser created from concatenated parsers to backtrack in parsec.

here's the code:

```<code>ab = (try $ char 'a') <|> (try $ char 'b')
cd = (try $ char 'b') <|> (try $ char 'c')
abcd = (try $ many1 ab) >> (try cd)
</code>```

here, when I run

```<code>parse abcd "parser"
</code>```

with the input "aaaaaaaaaaaaaac", it works,
but it errors on "aaaaaaaaaaaaab", which should be acceptable.

Any insights as to what I can do to get this to work

Thanks in advance

答:
Aadit's answer will work fine.  Alternatively, if you just want to parse the text and don't need any return value, you can use manyTill:

import Text.Parsec
import Text.Parsec.Char
import Text.Parsec.String

ab :: Parser Char
ab = char 'a' <|> char 'b'

bc :: Parser Char
bc = char 'b' <|> char 'c'

abbc :: Parser ()
abbc = ab >> manyTill ab bc >> return ()
```

<p>It works:</p>

```> parse abbc "" "aaaaaaaaaaaaaac"
Right ()
> parse abbc "" "aaaaaaaaaaaaaab"
Right ()
```

However, if you actually want the parsed text, then manyTill is not as convenient since it will only return the values parsed by its first argument, not the second.  (In this example I've discarded those values by calling return ().)

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get a parser created from concatenated parsers to backtrack in parsec.

here's the code:

ab = (try $ char 'a') <|> (try $ char 'b')
cd = (try $ char 'b') <|> (try $ char 'c')
abcd = (try $ many1 ab) >> (try cd)

here, when I run

parse abcd "parser"

with the input "aaaaaaaaaaaaaac", it works,
but it errors on "aaaaaaaaaaaaab", which should be acceptable.

Any insights as to what I can do to get this to work

Thanks in advance

Body:
Aadit's answer will work fine.  Alternatively, if you just want to parse the text and don't need any return value, you can use manyTill:

import Text.Parsec
import Text.Parsec.Char
import Text.Parsec.String

ab :: Parser Char
ab = char 'a' <|> char 'b'

bc :: Parser Char
bc = char 'b' <|> char 'c'

abbc :: Parser ()
abbc = ab >> manyTill ab bc >> return ()

It works:

> parse abbc "" "aaaaaaaaaaaaaac"
Right ()
> parse abbc "" "aaaaaaaaaaaaaab"
Right ()

However, if you actually want the parsed text, then manyTill is not as convenient since it will only return the values parsed by its first argument, not the second.  (In this example I've discarded those values by calling return ().)


问:
Embedding Lagom read-side processor in a non-Lagom application
I have a Lagom service which writes events for persistent entities to cassandra.
I would like to process those events from another application (not lagom-based) by embedding a read-side processor which would connect to the same cassandra.

I did not find any documentation on how to embed lagom services or read-side processors into existing java/scala applications, is it possible?

答:
It isn't recommended to have multiple services sharing the same database. This causes tight coupling between the services and can make it hard to upgrade in the future.

Instead, you can use the Lagom Message Broker Topic Producer API to publish events to a Kafka topic. Then, you can consume these from another application, either using Lagom with the Message Broker Consumer API, or using any other Kafka client.


问:
ftell at a position past 2GB
On a 32-bit system, what does ftell return if the current position indicator of a file opened in binary mode is past the 2GB point? In the C99 standard, is this undefined behavior since ftell must return a long int (maximum value being 2**31-1)?

答:
This worked for me on Windows32/MinGW to play with a 6GB file

```<code>#define _FILE_OFFSET_BITS 64
#include<stdio.h>

int main() {
    FILE *f = fopen("largefile.zip","rb");
    fseeko64(f, 0, SEEK_END);
    off64_t size = ftello64(f);

    printf("%llu\n", size);
}

gcc readlargefile.c -c -std=C99 -o readlargefile.exe
</code>```

Every single detail, the macro, the compiler option, matters.

Title: ftell at a position past 2GB

Body:
This worked for me on Windows32/MinGW to play with a 6GB file

#define _FILE_OFFSET_BITS 64
#include<stdio.h>

int main() {
    FILE *f = fopen("largefile.zip","rb");
    fseeko64(f, 0, SEEK_END);
    off64_t size = ftello64(f);

    printf("%llu\n", size);
}

gcc readlargefile.c -c -std=C99 -o readlargefile.exe

Every single detail, the macro, the compiler option, matters.


问:
Typescript property as string, how do I get the interface
Why do I get this error? How do I give languages an interface when its a object literal in another external module?

Element implicitly has an any type because expression of type string can't be used to index type { en: { title: string; }; es: { title: string; }; fi: { title: string; }; }.

No index signature with a parameter of type string was found on type { en: { title: string; }; es: { title: string; }; fi: { title: string; }; }.ts(7053)

export const languages = {
  en: {
    title: "English"
  },
  es: {
    title: "Español"
  },
  fi: {
    title: "Suomalainen"
  }
}
```

<pre class="lang-js prettyprint-override"><code>import React from 'react';
import { languages } from './utils/languageData'

interface IProps {
  lang: string
}

function LanguageSelect(props: IProps) {
  const { lang } = props

  const getText = (langId: string, propVal: string): string => {
    const result = languages[langId][propVal]
    const txt = result ? 'error' : result
    return txt
  }

  return (
    <div className="LanguageSelect" data-test="languageSelect-box">
      <div className="languageArea">{getText(lang, 'title')}</div>
    </div>
  );
}

export default LanguageSelect;
</code>```

答:
You can export the languages variable like this,

interface Lang {
    [key: string] : {
        [title: string]: string
    }
}

export const languages: Lang = {
    en : {
        title: "English"
    },
    es: {
        title: "Español"
    },
    fi: {
        title: "Suomalainen"
    }
}
```

Accessing the values like const result = languages[langId][propVal] should not produce the error. Try on typescript playground Playground Link

Body:
Why do I get this error? How do I give languages an interface when its a object literal in another external module?

Element implicitly has an any type because expression of type string can't be used to index type { en: { title: string; }; es: { title: string; }; fi: { title: string; }; }.

No index signature with a parameter of type string was found on type { en: { title: string; }; es: { title: string; }; fi: { title: string; }; }.ts(7053)

export const languages = {
  en: {
    title: "English"
  },
  es: {
    title: "Español"
  },
  fi: {
    title: "Suomalainen"
  }
}

import React from 'react';
import { languages } from './utils/languageData'

interface IProps {
  lang: string
}

function LanguageSelect(props: IProps) {
  const { lang } = props

  const getText = (langId: string, propVal: string): string => {
    const result = languages[langId][propVal]
    const txt = result ? 'error' : result
    return txt
  }

  return (

{getText(lang, 'title')}

  );
}

export default LanguageSelect;

Body:
You can export the languages variable like this,

interface Lang {
    [key: string] : {
        [title: string]: string
    }
}

export const languages: Lang = {
    en : {
        title: "English"
    },
    es: {
        title: "Español"
    },
    fi: {
        title: "Suomalainen"
    }
}

Accessing the values like const result = languages[langId][propVal] should not produce the error. Try on typescript playground Playground Link


问:
Hosting an .apk file on over own site
I got requirement to host my .apk file on one public site other than android market or any other app stores. In android market, after registred in to the market the downloded .apk will automatically installed on mobile without any manual action. So I am willing to create one URL and host my .apk file in to that and want to download that .apk in to the android mobile and it has to install automatically.

How can I do that....plz share if any code or links are there regrading this.

答:
```<code>{
        String url = "http://www.server.com/yourapp.apk";
        String PATH = Environment.getExternalStorageDirectory() + "/download/";
        File file = new File(PATH);
        file.mkdirs();
        File outputFile = new File(file, "yourapp.apk");
        downloadFile(url, outputFile);
        installApp(context);
}

private static void downloadFile(String url, File outputFile) {
    try {
        URL u = new URL(url);
        URLConnection conn = u.openConnection();
        int contentLength = conn.getContentLength();

        DataInputStream stream = new DataInputStream(u.openStream());

        byte[] buffer = new byte[contentLength];
        stream.readFully(buffer);
        stream.close();

        DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
        fos.write(buffer);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        Log.e("FileNotFoundException",e+"");
        return;
    } catch (IOException e) {
        Log.e("IOException",e+"");
        return;
    }
}

private static void installApp(Context mycontext) {
    Intent installer = new Intent();
    installer.setAction(android.content.Intent.ACTION_VIEW);
    String PATH = "file://" + Environment.getExternalStorageDirectory() + "/download/yourapp.apk";
    installer.setDataAndType(Uri.parse(PATH), "application/vnd.android.package-archive");
    mycontext.startActivity(installer);
}
</code>```

Title: Hosting an .apk file on over own site


问:
Why occur KotlinNullPointerException in this code?
I'm making a chat app.
When I send the message, it is storaged in firebase real-time database and will be display users with whom i have messages.

but, in this process, occur the KotlinNullPointerExcpetion.

You can read below codes.

First, codes when I send the message. (MessageActivity.kt)

```<code>sendBtn.setOnClickListener(object : View.OnClickListener{
        override fun onClick(v: View?) {
            var msg = msgSendBox.text.toString()
            if(!msg.equals("")) {
                sendMessage(firebaseUser.uid, receiverId, msgSendBox.text.toString())
                msgSendBox.setText("")
            }
        }
    })
</code>```

.
.

```<code>private fun sendMessage(sender : String, receiver : String, message : String){
    var reference = FirebaseDatabase.getInstance().getReference()

    var hashMap : HashMap<String, Object> = HashMap();
    hashMap.put("sender", sender as Object)
    hashMap.put("receiver", receiver as Object)
    hashMap.put("message", message as Object)

    reference.child("Chats").push().setValue(hashMap)
}
</code>```

and codes that display all users.(UserListFragment.kt)

```<code>private fun readUsers(){
    var firebaseUser = FirebaseAuth.getInstance().currentUser
    var reference = FirebaseDatabase.getInstance().getReference("Users")

    reference.addValueEventListener(object : ValueEventListener{
        override fun onDataChange(dataSnapShot: DataSnapshot) {

            for(snapShot in dataSnapShot.children){
                var user = snapShot.getValue(User::class.java)

                assert(user != null)
                assert(firebaseUser != null)
                if(!(user?.id.equals(firebaseUser?.uid))){
                    mUsers.add(user!!)
                }
            }

            userAdapter = UserAdapter(context!!, mUsers)

            recyclerView.adapter = userAdapter
        }

        override fun onCancelled(p0: DatabaseError) {

        }
    })
}
</code>```

and codes that display users whom i have messages(ChatListFragment.kt)

```<code>private fun readChat(){
    mUsers = ArrayList()

    reference = FirebaseDatabase.getInstance().getReference("Users")

    reference.addValueEventListener(object : ValueEventListener{
        override fun onDataChange(dataSnapShot: DataSnapshot) {
            mUsers.clear()

            for(snapShot in dataSnapShot.children){
                var user = snapShot.getValue(User::class.java) as User

                for(mId in usersList) {
                    assert(user != null)
                    if (user.id.equals(mId)) {
                        mUsers.add(user)
                    }
                }

            }
            userAdapter = UserAdapter(context!!, mUsers)
            recyclerView.adapter = userAdapter
        }

        override fun onCancelled(p0: DatabaseError) {

        }
    })
}
</code>```

in this codes, it occurs the errors like below.

```<code>    Process: com.techtown.breadchatapp, PID: 7773
kotlin.KotlinNullPointerException
    at com.techtown.breadchatapp.fragment.UserListFragment$readUsers$1.onDataChange(UserListFragment.kt:65)
    at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.2.1:75)
    at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.2.1:63)
    at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.2.1:55)
    at android.os.Handler.handleCallback(Handler.java:907)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:216)
    at android.app.ActivityThread.main(ActivityThread.java:7506)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:956)
</code>```

答: From your comment if its not mUsers then it will be your context. You are using the !! operator which if context is null it will throw the KotlinNullPointerExcpetion

Body:
I'm making a chat app.
When I send the message, it is storaged in firebase real-time database and will be display users with whom i have messages.

but, in this process, occur the KotlinNullPointerExcpetion.

You can read below codes.

First, codes when I send the message. (MessageActivity.kt)

sendBtn.setOnClickListener(object : View.OnClickListener{
        override fun onClick(v: View?) {
            var msg = msgSendBox.text.toString()
            if(!msg.equals("")) {
                sendMessage(firebaseUser.uid, receiverId, msgSendBox.text.toString())
                msgSendBox.setText("")
            }
        }
    })

.
.

private fun sendMessage(sender : String, receiver : String, message : String){
    var reference = FirebaseDatabase.getInstance().getReference()

    var hashMap : HashMap<String, Object> = HashMap();
    hashMap.put("sender", sender as Object)
    hashMap.put("receiver", receiver as Object)
    hashMap.put("message", message as Object)

    reference.child("Chats").push().setValue(hashMap)
}

and codes that display all users.(UserListFragment.kt)

private fun readUsers(){
    var firebaseUser = FirebaseAuth.getInstance().currentUser
    var reference = FirebaseDatabase.getInstance().getReference("Users")

    reference.addValueEventListener(object : ValueEventListener{
        override fun onDataChange(dataSnapShot: DataSnapshot) {

            for(snapShot in dataSnapShot.children){
                var user = snapShot.getValue(User::class.java)

                assert(user != null)
                assert(firebaseUser != null)
                if(!(user?.id.equals(firebaseUser?.uid))){
                    mUsers.add(user!!)
                }
            }

            userAdapter = UserAdapter(context!!, mUsers)

            recyclerView.adapter = userAdapter
        }

        override fun onCancelled(p0: DatabaseError) {

        }
    })
}

and codes that display users whom i have messages(ChatListFragment.kt)

private fun readChat(){
    mUsers = ArrayList()

    reference = FirebaseDatabase.getInstance().getReference("Users")

    reference.addValueEventListener(object : ValueEventListener{
        override fun onDataChange(dataSnapShot: DataSnapshot) {
            mUsers.clear()

            for(snapShot in dataSnapShot.children){
                var user = snapShot.getValue(User::class.java) as User

                for(mId in usersList) {
                    assert(user != null)
                    if (user.id.equals(mId)) {
                        mUsers.add(user)
                    }
                }

            }
            userAdapter = UserAdapter(context!!, mUsers)
            recyclerView.adapter = userAdapter
        }

        override fun onCancelled(p0: DatabaseError) {

        }
    })
}

in this codes, it occurs the errors like below.

    Process: com.techtown.breadchatapp, PID: 7773
kotlin.KotlinNullPointerException
    at com.techtown.breadchatapp.fragment.UserListFragment$readUsers$1.onDataChange(UserListFragment.kt:65)
    at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.2.1:75)
    at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.2.1:63)
    at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.2.1:55)
    at android.os.Handler.handleCallback(Handler.java:907)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:216)
    at android.app.ActivityThread.main(ActivityThread.java:7506)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:956)


问:
Ubuntu 18.04.4 qemu-commandline options fails
Trying to virt-install a Fedora-coreos VM I have a known working ignition file from a Fedora install so it is valid.

When I run the command:

virt-install --connect qemu:///system -n fedora-core --memory 2048 --os-variant=fedora28 --import --graphics=none --disk size=10,backing_store=/data2/virtlib-images/fedora-coreos-31.20200323.3.2-qemu.x86_64.qcow2 --qemu-commandline="-fw_cfg name=opt/com.coreos/config,file=corebk.ign"

the error is

Starting install...
Allocating 'fedora-core.qcow2'                                                       |  10 GB  00:00:00
ERROR    internal error: process exited while connecting to monitor: 2020-04-17T00:02:22.907508Z qemu-system-x86_64: -fw_cfg name=opt/com.coreos/config,file=corebk.ign: can't load corebk.ign
Removing disk 'fedora-core.qcow2'                                                    |    0 B  00:00:00
Domain installation does not appear to have been successful.
```

It appears the -fw_cfg " flags are not working.
saw oldpost about qemu-kvm-ev being the missing package checked for pakage but not available in 18.04.4.
Any Ideas?

答:
The ignition file is not found.
I quote from Fedora CoreOS - Getting Started

When using virt-install, you must specify absolute paths to the image and the Ignition file.

Late answer, I know, but for future reference.

Body:
Trying to virt-install a Fedora-coreos VM I have a known working ignition file from a Fedora install so it is valid.

When I run the command:

virt-install --connect qemu:///system -n fedora-core --memory 2048 --os-variant=fedora28 --import --graphics=none --disk size=10,backing_store=/data2/virtlib-images/fedora-coreos-31.20200323.3.2-qemu.x86_64.qcow2 --qemu-commandline="-fw_cfg name=opt/com.coreos/config,file=corebk.ign"

the error is

Starting install...
Allocating 'fedora-core.qcow2'                                                       |  10 GB  00:00:00
ERROR    internal error: process exited while connecting to monitor: 2020-04-17T00:02:22.907508Z qemu-system-x86_64: -fw_cfg name=opt/com.coreos/config,file=corebk.ign: can't load corebk.ign
Removing disk 'fedora-core.qcow2'                                                    |    0 B  00:00:00
Domain installation does not appear to have been successful.

It appears the -fw_cfg " flags are not working.
saw oldpost about qemu-kvm-ev being the missing package checked for pakage but not available in 18.04.4.
Any Ideas?


问:
Javascript fetch API chain "then"
I'm kind of new to JS and can't figure out how to make the following work:

I'd like to run functions (for test reasons console) in the different stages of the fetch API. Like run console when fetch started because of click –> then when fetch received a response (text) -> then when the fetch response has been parsed -> and finally when the parsed response text has replaced the HTML of an existing DOM-element.

```<code>var doFetch = (url) => {
  fetch(url, {
    method: "GET",
    headers: new Headers({
        'X-Requested-With': 'fetch'
    })
  }){
    console.log("fetch request started because of click on element");
  }
  .then(response => response.text();
    console.log("fetch request has received the response text");
  )
  .then(response => {
    let content = new DOMParser().parseFromString(text, "text/html");
    console.log("the received request response text was DOMparsed");
  })
  .then(response => {
    let main = content.querySelector('main').innerHTML;
    console.log("the parsed response content replaced current HTML");
  }
};
</code>```

Any tips on how to correct the code would be gladly welcomed!

答:
In order to do chaining you need to return from each .then block. Aslo your first console.log() post the fetch function had incorrect syntax

```<code>var doFetch = (url) => {

  fetch(url, {
    method: "GET",
    headers: 'X-Requested-With': 'fetch'
  })
  .then(response => {
     console.log("fetch request has received the response text");
     return response.text();

  })
  .then(response => {
    let content = new DOMParser().parseFromString(text, "text/html");
    console.log("the received request response text was DOMparsed");
    return content
  })
  .then(content => {
    let main = content.querySelector('main').innerHTML;
    console.log("the parsed response content replaced current HTML");
  });
  console.log("fetch request started because of click on element"); // This will be executed first
};
</code>```

Title: Javascript fetch API chain "then"

Body:
I'm kind of new to JS and can't figure out how to make the following work:

I'd like to run functions (for test reasons console) in the different stages of the fetch API. Like run console when fetch started because of click –> then when fetch received a response (text) -> then when the fetch response has been parsed -> and finally when the parsed response text has replaced the HTML of an existing DOM-element.

var doFetch = (url) => {
  fetch(url, {
    method: "GET",
    headers: new Headers({
        'X-Requested-With': 'fetch'
    })
  }){
    console.log("fetch request started because of click on element");
  }
  .then(response => response.text();
    console.log("fetch request has received the response text");
  )
  .then(response => {
    let content = new DOMParser().parseFromString(text, "text/html");
    console.log("the received request response text was DOMparsed");
  })
  .then(response => {
    let main = content.querySelector('main').innerHTML;
    console.log("the parsed response content replaced current HTML");
  }
};

Any tips on how to correct the code would be gladly welcomed!

Body:
In order to do chaining you need to return from each .then block. Aslo your first console.log() post the fetch function had incorrect syntax

var doFetch = (url) => {

  fetch(url, {
    method: "GET",
    headers: 'X-Requested-With': 'fetch'
  })
  .then(response => {
     console.log("fetch request has received the response text");
     return response.text();

  })
  .then(response => {
    let content = new DOMParser().parseFromString(text, "text/html");
    console.log("the received request response text was DOMparsed");
    return content
  })
  .then(content => {
    let main = content.querySelector('main').innerHTML;
    console.log("the parsed response content replaced current HTML");
  });
  console.log("fetch request started because of click on element"); // This will be executed first
};


问:
Create a file in 700 (drwx------) directory using Dockerfile
I am using the gitlab-runner base image for my docker file

```<code>FROM gitlab/gitlab-runner:alpine
WORKDIR /app

RUN touch /etc/gitlab-runner/config.toml   # it doesn't work because of drwx------ direcotry
RUN touch /etc/config.toml                 # it worked because etc is   drwxr-xr-x directory

COPY . /app
...
...

ENTRYPOINT ["yarn"]
CMD ["run", "start"]
</code>```

Inspecting the images using a tool

When the image is created I couldn't see the config.toml file in the etc/gitlab-runner directory

Is it hidden?

How can I create config.toml file under etc/gitlab-runner directory

Also, wondering what purpose of the certs folder? what does it contain? Actually I wanted to mount the config.toml file to the host machine so that the runner details are syn always when the container is destroyed.

答:
The gitlab/gitlab-runner image declares a VOLUME for /etc/gitlab-runner, so any RUN commands that affect that directory are ignored.

You don't need any Dockerfile changes to inject things like config files using docker run -v options (the file doesn't need to already exist in the base image and you don't need a VOLUME directive).  You can use any location in the container as the target for a bind mount.  If it's a file, it must exist on the host first, and at startup time the host content will always hide whatever was in the image.

Body:
I am using the gitlab-runner base image for my docker file

FROM gitlab/gitlab-runner:alpine
WORKDIR /app

RUN touch /etc/gitlab-runner/config.toml   # it doesn't work because of drwx------ direcotry
RUN touch /etc/config.toml                 # it worked because etc is   drwxr-xr-x directory

COPY . /app
...
...

ENTRYPOINT ["yarn"]
CMD ["run", "start"]

Inspecting the images using a tool

When the image is created I couldn't see the config.toml file in the etc/gitlab-runner directory

Is it hidden?

How can I create config.toml file under etc/gitlab-runner directory

Also, wondering what purpose of the certs folder? what does it contain? Actually I wanted to mount the config.toml file to the host machine so that the runner details are syn always when the container is destroyed.


问:
Create a Mobile Responsive Version of a PowerBI report that is Published to the Web
I've recently published a specific PowerBI report and despite creating a 'Phone' View on PowerBI Desktop this didn't show up in the final embed code.

I've looked into PowerBI Embedded Playground and managed to generate the relevant access tokens and even try it out, but still couldn't figure out how to modify the code in such a way to generate a mobile view.

The questions and answers below somehow didn't give me the insight I needed, still somehow need some additional work:

Mobile view is not being shown for embedded powerbi report

Create Report in Embed View via PowerBI API

Power BI RS web embedding in mobile web browser

What do I need to do to get started? Which documentation do I need to look into exactly? I need to embed this report in a Sharepoint 2010 Page and I need it to be mobile responsive on page load and not via a seperate link.

答:
This isn't related to the access token in any way. It is generated before configuring the embedding process. To embed the report in phone view, you must specify MobilePortrait layout type in the embed configuration, i.e. something like this:

```<code>var config = {
    .....
    settings: {
        filterPaneEnabled: true,
        navContentPaneEnabled: true,
        layoutType: models.LayoutType.MobilePortrait <-- THIS ONE
    }
};
</code>```

If you omit layoutType, it will be shown in the landscape view (i.e. like in the desktop). For more information about the configuration see Embed Configuration Details, and for embedding in general you should start from Embedding Basics.

Body:
This isn't related to the access token in any way. It is generated before configuring the embedding process. To embed the report in phone view, you must specify MobilePortrait layout type in the embed configuration, i.e. something like this:

var config = {
    .....
    settings: {
        filterPaneEnabled: true,
        navContentPaneEnabled: true,
        layoutType: models.LayoutType.MobilePortrait <-- THIS ONE
    }
};

If you omit layoutType, it will be shown in the landscape view (i.e. like in the desktop). For more information about the configuration see Embed Configuration Details, and for embedding in general you should start from Embedding Basics.


问:
Frontend SVN client, closest thing to Tortoise for the mac
Just wondering what is the best frontend SVN client like Tortoise for the mac.

Andrei

答: I would say SCPlugin -  http://scplugin.tigris.org/</p>


问:
#grpc node client allow signed certificate
i have a self signed grpc service on server, and got it working for dart server with dart client.
But i could not figure how to bypass or allow self signed certificate for node client..
I've tried this:

```<code>const sslCreds = await grpc.credentials.createSsl(
    fs.readFileSync('./ssl/client.crt'),
    null, // privatekey
    null, // certChain
    {
      checkServerIdentity: function(host, info) {
  console.log('verify?', host, info);
  if (
    host.startsWith('127.0.0.1') ||
    host.startsWith('logs.example.com')
  ) {
    return true;
  }
  console.log('verify other?', host);
  return true;
},
    },
  );

  // sslCreds.options.checkServerIdentity = checkCert;

  const gLogClient = new synagieLogGrpc.LoggerClient(
    'host:port',
    sslCreds,
  );

</code>```

but when i call, my validation checkServerIdentity did not call.

anyone have any clue?

答:
after checking out multiple github issues, and testing for 2 days,
this code below works.
critical point is, actual host:port is the destination, which could be localhost. but we will need to override the ssl target name with the actual generated ssl domain.

for sample of tls generation:
https://github.com/grpc/grpc-node/issues/1451

```<code>const host = 'localhost';
const port = 8088;;
const hostPort = `${host}:${port}`;
const gLogClient = new synagieLogGrpc.LoggerClient(hostPort, sslCreds, {
  'grpc.ssl_target_name_override': 'actual_tlsdomain.example.com',
});
</code>```

Body:
i have a self signed grpc service on server, and got it working for dart server with dart client.
But i could not figure how to bypass or allow self signed certificate for node client..
I've tried this:

const sslCreds = await grpc.credentials.createSsl(
    fs.readFileSync('./ssl/client.crt'),
    null, // privatekey
    null, // certChain
    {
      checkServerIdentity: function(host, info) {
  console.log('verify?', host, info);
  if (
    host.startsWith('127.0.0.1') ||
    host.startsWith('logs.example.com')
  ) {
    return true;
  }
  console.log('verify other?', host);
  return true;
},
    },
  );

  // sslCreds.options.checkServerIdentity = checkCert;

  const gLogClient = new synagieLogGrpc.LoggerClient(
    'host:port',
    sslCreds,
  );

but when i call, my validation checkServerIdentity did not call.

anyone have any clue?

Body:
after checking out multiple github issues, and testing for 2 days,
this code below works.
critical point is, actual host:port is the destination, which could be localhost. but we will need to override the ssl target name with the actual generated ssl domain.

for sample of tls generation:
https://github.com/grpc/grpc-node/issues/1451

const host = 'localhost';
const port = 8088;;
const hostPort = `${host}:${port}`;
const gLogClient = new synagieLogGrpc.LoggerClient(hostPort, sslCreds, {
  'grpc.ssl_target_name_override': 'actual_tlsdomain.example.com',
});


问:
Search and Search All in COBOL
I want to know the result when we try to search an item in COBOL using SEARCH or SEARCH ALL and this item appears multiple times in the table.
Will any of the two will find all the occurrences ?</p>

答:
Will any of the two will find all the occurrences ?

No. Either SEARCH will identify one, and only one, table element.

The SEARCH statement is used to search a table for a table element that satisfies the specified condition and to adjust the value of the associated index to indicate that table element.

For SEARCH, the final value, of the index or identifier, will be the first table element that matches the conditions.

For SEARCH ALL, the final setting of the search index is equal to one of them, but it is undefined which one.

Title: Search and Search All in COBOL


问:
Best style for message passing between threads?
I want to asynchroniously call functions in various threads, each of which has a specific state, so I send messages to a given thread and let that thread act on those messages. What I wonder is what is the most reasonable style for those messages. I can think of three possibilities. (All the examples exclude thread mechanics, so as not to complicate them.)

Keyword-based messages, with dispatch on state and keyword.

(defclass state () ())

(defgeneric dispatch (object method args))

(defmethod dispatch ((object state) (method (eql :bazinga)) args)
  (destructuring-bind (arg1 arg2) args
    (format t "arg1 = ~a, arg2 = ~a~%" arg1 arg2)))

(let ((state (make-instance 'state))
      (msg '(:bazinga 10 20))) ; message example
  (dispatch state (car msg) (cdr msg)))
```

<ol start="2">
<li>Function-based messages, with dispatch on state.</li>
</ol>

<pre class="lang-lisp prettyprint-override"><code>(defclass state () ())

(defgeneric bazinga (object arg1 arg2))

(defmethod bazinga ((object state) arg1 arg2)
  (format t "arg1 = ~a, arg2 = ~a~%" arg1 arg2))

(let ((state (make-instance 'state))
      (msg (list #'bazinga 10 20))) ; message example
  (apply (car msg) state (cdr msg)))
</code>```

2.1 Function-based messages, with dispatch on state and with arguments passed via closure (from a comment from RowPJ)

(defclass state () ())

(defgeneric bazinga (object arg1 arg2))

(defmethod bazinga ((object state) arg1 arg2)
  (format t "arg1 = ~a, arg2 = ~a~%" arg1 arg2))

(let ((state (make-instance 'state))
      (msg (lambda (obj) (bazinga obj 10 20))))
  (funcall msg state))
```

<ol start="3">
<li>Function-based messages, with "hardcoded dispatch".</li>
</ol>

<pre class="lang-lisp prettyprint-override"><code>(defclass state () ()) ; could be a structure instead

(defun state-bazinga (object arg1 arg2)
  (format t "arg1 = ~a, arg2 = ~a~%" arg1 arg2))

(let ((state (make-instance 'state))
      (msg (list #'state-bazinga 10 20))) ; message example
  (apply (car msg) state (cdr msg)))
</code>```

3.1 - analogously with 2.1, skipping here.

I'm unlikely to have any sort of object hierarchy, so it feels to me there is no real difference between these styles. Is it indeed just a matter of personal preference then, or are there objective pros and cons? Will any of these styles likely be easier to use or, instead, more limiting down the road as the program growth? I know it's not a clear cut question, but hopefully it's still reasonably clear what I'm asking.

答:
call functions in various threads

A basic model would be a waiting loop which watches its own queue / mailbox and executes the functions put into that queue / mailbox.

Put whatever function you want into that queue.

This can be extended to enqueue both the function and its args.

The LispWorks GUI library uses that model: apply-in-pane-process.

The mental model is simply that APPLY is executing in a specific process: apply-in-process <process> <function> <args>. In Lisp I would first think functional. APPLY is a basic function calling operator. Now use a similar version, which just does APPLY in a specific process. One can then apply a lambda, a closure, a named function, a CLOS function, ...

With that one can implement all kinds of calling convention one wants.

Body:
I want to asynchroniously call functions in various threads, each of which has a specific state, so I send messages to a given thread and let that thread act on those messages. What I wonder is what is the most reasonable style for those messages. I can think of three possibilities. (All the examples exclude thread mechanics, so as not to complicate them.)

Keyword-based messages, with dispatch on state and keyword.

(defclass state () ())

(defgeneric dispatch (object method args))

(defmethod dispatch ((object state) (method (eql :bazinga)) args)
  (destructuring-bind (arg1 arg2) args
    (format t "arg1 = ~a, arg2 = ~a~%" arg1 arg2)))

(let ((state (make-instance 'state))
      (msg '(:bazinga 10 20))) ; message example
  (dispatch state (car msg) (cdr msg)))

Function-based messages, with dispatch on state.

(defclass state () ())

(defgeneric bazinga (object arg1 arg2))

(defmethod bazinga ((object state) arg1 arg2)
  (format t "arg1 = ~a, arg2 = ~a~%" arg1 arg2))

(let ((state (make-instance 'state))
      (msg (list #'bazinga 10 20))) ; message example
  (apply (car msg) state (cdr msg)))

2.1 Function-based messages, with dispatch on state and with arguments passed via closure (from a comment from RowPJ)

(defclass state () ())

(defgeneric bazinga (object arg1 arg2))

(defmethod bazinga ((object state) arg1 arg2)
  (format t "arg1 = ~a, arg2 = ~a~%" arg1 arg2))

(let ((state (make-instance 'state))
      (msg (lambda (obj) (bazinga obj 10 20))))
  (funcall msg state))

Function-based messages, with "hardcoded dispatch".

(defclass state () ()) ; could be a structure instead

(defun state-bazinga (object arg1 arg2)
  (format t "arg1 = ~a, arg2 = ~a~%" arg1 arg2))

(let ((state (make-instance 'state))
      (msg (list #'state-bazinga 10 20))) ; message example
  (apply (car msg) state (cdr msg)))

3.1 - analogously with 2.1, skipping here.

I'm unlikely to have any sort of object hierarchy, so it feels to me there is no real difference between these styles. Is it indeed just a matter of personal preference then, or are there objective pros and cons? Will any of these styles likely be easier to use or, instead, more limiting down the road as the program growth? I know it's not a clear cut question, but hopefully it's still reasonably clear what I'm asking.


问:
CSS - hiding the overflow of an image isn't working
I have a problem with my website banner. When I view my banner image on a phone screen, the text on the banner is too small to see. Due to this, I made the width of my image 120% (on CSS) so the text would be larger on a phone screen. When I did this, the banner just extended longer than the website length - but I want the excess banner to be cut off. I tried to solve this by using 'overflow: hidden' but it didn't work. Ultimately, I just want to crop the excess length off my banner but I don't know how.

HTML:

```<code><div class="content">
        <div class="banner">
            <img src="images/large_banner.png" width="1440" height="80" alt="Sister banner"/>
        </div>
</div>
</code>```

CSS:

```<code>@media only screen and (max-width: 550px){
    .banner{
            height: auto;
            width: 120%;
            overflow: hidden;
           }
}
</code>```

答:
You put width to the wrong place. You should paste height and width for image and put overflow: hidden; to div .banner.

Here's an example

img{
  width:100%;
}

@media only screen and (max-width: 480px){
  .content{
    width:360px;
    margin:0 auto;
  }
  .banner{
    width:90%;
    margin: 0 auto;
    overflow: hidden;
  }
    .banner img{
       width: 250%;
       margin-left:-138px;
     }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">
        <div class="banner">
            <img src="http://man-centr.uz/image/cache/catalog/slider/slider2-1920x641.jpg" alt="Sister banner"/>
        </div>
</div></code>```

Body:
I have a problem with my website banner. When I view my banner image on a phone screen, the text on the banner is too small to see. Due to this, I made the width of my image 120% (on CSS) so the text would be larger on a phone screen. When I did this, the banner just extended longer than the website length - but I want the excess banner to be cut off. I tried to solve this by using 'overflow: hidden' but it didn't work. Ultimately, I just want to crop the excess length off my banner but I don't know how.

HTML:

CSS:

@media only screen and (max-width: 550px){
    .banner{
            height: auto;
            width: 120%;
            overflow: hidden;
           }
}

Body:
You put width to the wrong place. You should paste height and width for image and put overflow: hidden; to div .banner.

Here's an example

img{
  width:100%;
}

@media only screen and (max-width: 480px){
  .content{
    width:360px;
    margin:0 auto;
  }
  .banner{
    width:90%;
    margin: 0 auto;
    overflow: hidden;
  }
    .banner img{
       width: 250%;
       margin-left:-138px;
     }
}

<div class="content">
        <div class="banner">
            <img src="http://man-centr.uz/image/cache/catalog/slider/slider2-1920x641.jpg" alt="Sister banner"/>
        </div>
</div>


问:
Time limit with the "ms" package
```<code>let giveawayDuration = response2.first();

// Limit duration to max 15d
            if (giveawayDuration > ms('15d')) {
                const l1 = new Discord.MessageEmbed()
                .setColor('#ff0000')
                .setDescription(❌ Your duration cannot be more than 15 Days!)
                return message.channel.send(l1);
            }
</code>```

It whyever blocks every duration, someone knows why/what I have done wrong?

const ms = require('ms');

const response2 = await message.channel.awaitMessages(m => m.author.id === message.author.id, { max: 1 });

答: The solution is to make it : "ms(giveawayDuration.content) > ms('15d')"</p>

Title: Time limit with the "ms" package

Body:
let giveawayDuration = response2.first();

// Limit duration to max 15d
            if (giveawayDuration > ms('15d')) {
                const l1 = new Discord.MessageEmbed()
                .setColor('#ff0000')
                .setDescription(❌ Your duration cannot be more than 15 Days!)
                return message.channel.send(l1);
            }

It whyever blocks every duration, someone knows why/what I have done wrong?

const ms = require('ms');

const response2 = await message.channel.awaitMessages(m => m.author.id === message.author.id, { max: 1 });


问:
"for loop" with a changing variable name in Powershell
I have a function as shown here. It takes as an argument, an array with 8 values.

It supposed to go through textbox2 -> check for string inside it, if so goto textbox3 and write the first value of the array, and the general rule if textbox$i isn't empty, print inside textbox$i+1 the value of $passarray[$counter] and add $counter + 1.

The function will halt when it reaches an empty textbox.

I have a few problems here, first I need to find a way to make sure the inside of the if statement that the word $textbox is changing, $textbox2, $textbox4, $textbox6 and so on.

As it is written here it doesn't do the job

```<code>Function FillBoxes ($passarray) {
 $counter =0
  For ($i=2; $i -lt 17; $i=$i+2){
          if ($textbox$i.textlength -gt 0) {
                $TextBox$i+1.text =  $passarray[$counter]
                $counter++}
                }

 }

how can i do it correcrtly?

</code>```

答:
I think the get-variable cmdlet will resolve your issue.

```<code>$i = 2;

$testEcho_2 = 'Hello'

Get-Variable -Name ('testEcho_' + $i) -ValueOnly

Write-Host $(Get-Variable -Name ('testEcho_' + $i) -ValueOnly)

$tmp = ('testEcho_' + $i)

New-Variable -Name "testEcho_$i" -Value 'After Mod' -Force

Write-Host $(Get-Variable -Name ('testEcho_' + $i) -ValueOnly)
</code>```

see also: Evaluate a variable within a variable in Powershell

Body:
I have a function as shown here. It takes as an argument, an array with 8 values.

It supposed to go through textbox2 -> check for string inside it, if so goto textbox3 and write the first value of the array, and the general rule if textbox$i isn't empty, print inside textbox$i+1 the value of $passarray[$counter] and add $counter + 1.

The function will halt when it reaches an empty textbox.

I have a few problems here, first I need to find a way to make sure the inside of the if statement that the word $textbox is changing, $textbox2, $textbox4, $textbox6 and so on.

As it is written here it doesn't do the job

Function FillBoxes ($passarray) {
 $counter =0
  For ($i=2; $i -lt 17; $i=$i+2){
          if ($textbox$i.textlength -gt 0) {
                $TextBox$i+1.text =  $passarray[$counter]
                $counter++}
                }

 }

how can i do it correcrtly?

Body:
I think the get-variable cmdlet will resolve your issue.

$i = 2;

$testEcho_2 = 'Hello'

Get-Variable -Name ('testEcho_' + $i) -ValueOnly

Write-Host $(Get-Variable -Name ('testEcho_' + $i) -ValueOnly)

$tmp = ('testEcho_' + $i)

New-Variable -Name "testEcho_$i" -Value 'After Mod' -Force

Write-Host $(Get-Variable -Name ('testEcho_' + $i) -ValueOnly)

see also: Evaluate a variable within a variable in Powershell


问:
Kogito: Is it possible to embed Kogito DMN editor in a web application?
In my project, I use DMN to model rules which gets executed using the drools DMN engine along with java code. It is expected to have 1000+ DMN rules in the project. I am trying to find a way to manage these DMN rules. Currently business-central is used to build these DMN rules and then it is downloaded to the project folder. As one DMN model has dependency on other, it is getting hard to import and export DMNs in business-central. I am planning to build a web application which will help to manage these DMN rules.

Is there any tool that helps to manage the DMN rules so that I don't have to build one?

I have explored kogito online DMN editor, is it possible to embed the DMN editor inside other web application (Iframe or npm package). If possible, does it have APIs for interaction like loading a DMN and saving?

答:
This is a very broad question, for which I invite you to start a conversation on the Drools-usage mailing-list and/or the Kogito mailing-list.

It seems you are looking to manage the whole project as a web application, in terms of assets (DMNs, etc.) and their dependencies. I assume this will need features like versioning, access control, etc. all features which are covered already by Business Central.

I would advise you should try to rely on Business Central as much as possible, and customise only the parts which are necessary. For instance you can use APIs to export the project locally if needed, etc.

Kogito editors are more oriented for a developer experience (for instance integration with VS Code), not about serving project management as a web application (that is the focus of Business Central). That said Kogito editor offer a BPMN editor and DMN editor as a Chrome extension as well, which can be beneficial if your "project management" needs can be handled by github.

The choice depends really on many factors and what features are required by the web application you mention, how many of the features are you looking to leverage from the existing projects or reimplement yourself.

I recommend for you to continue this discussion on the suggested mailing-list as this is a very broad question which can better benefit from an iterative exchange.


问:
How to check Visual Studio 2010 Professional licence key validity
I bought Visual Studio 2010 Professional from a third party supplier.  I input the key and it all seems to work but when starting up the program it says that it is licensed to 'Microsoft' rather than to me.

How can I check whether the license key I was given upon purchasing Visual Studio 2010 Professional is valid?

答:
Are you using a 64-bit version of Windows? There is a known issue with license information on such systems.

To resolve this issue we have to follow the steps below. This is a two step process. First the registry needs to modified, this will show the data in Help About dialog box. >Then we have to follow the next set of process to register the values to appear in the
  splash screen.

IMPORTANT Note: Please ensure you have taken a backup of the registry before making any changes.

Steps for Help About dialog:

On a x86 bit (32 bit OS) computer follow the below path:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\10.0\Registration\UserName
  HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\RegisteredOrganization

On a x64 bit (64 bit OS) computer follow the below path:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\10.0\Registration\UserName
  HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\RegisteredOrganization

Changing the UserName will change the first line in the help about dialog.
  Changing the RegisteredOrganization will change the second line in the help about dialog.

Steps to fix the splash screen:

On a x86 bit(32 bit OS) computer follow the below path:
  "C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe" /setup

On a x64 bit (64 bit OS) computer follow the below path:
  "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe" /setup

Launch Visual Studio 2010 to check if both the issues are resolved or not. Also create a new project to
  check that the new information is auto populated.

Original link: http://connect.microsoft.com/VisualStudio/feedback/details/568947/64-visual-studio-2010


问:
Can't install TTFQuery via pip install
I was trying to use TTFQuery module but when i write the command pip3 install TTFQuery it returns the following error.

```<code>ERROR: Command errored out with exit status 1:
        command: 'c:\users\pranon rahman\appdata\local\programs\python\python37\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\PRANON~1\\AppData\\Local\\Temp\\pip-install-z2hpgfba\\TTFQuery\\setup.py'"'"'; __file__='"'"'C:\\Users\\PRANON~1\\AppData\\Local\\Temp\\pip-install-z2hpgfba\\TTFQuery\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);
        code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\PRANON~1\AppData\Local\Temp\pip-pip-egg-info-2u2rs2sz'
         cwd: C:\Users\PRANON~1\AppData\Local\Temp\pip-install-z2hpgfba\TTFQuery\
    Complete output (6 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\PRANON~1\AppData\Local\Temp\pip-install-z2hpgfba\TTFQuery\setup.py", line 11
        except ImportError, err:
                          ^
    SyntaxError: invalid syntax

ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
</code>```

答:
TTFQuery 1.0.5, last released in 2012. The code is obviously only for Python 2.

There is a beta release 2.0.0b1 from 2018. Try

```<code>pip install TTFQuery==2.0.0b1
</code>```

Title: Can't install TTFQuery via pip install

Body:
I was trying to use TTFQuery module but when i write the command pip3 install TTFQuery it returns the following error.

ERROR: Command errored out with exit status 1:
        command: 'c:\users\pranon rahman\appdata\local\programs\python\python37\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\PRANON~1\\AppData\\Local\\Temp\\pip-install-z2hpgfba\\TTFQuery\\setup.py'"'"'; __file__='"'"'C:\\Users\\PRANON~1\\AppData\\Local\\Temp\\pip-install-z2hpgfba\\TTFQuery\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);
        code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\PRANON~1\AppData\Local\Temp\pip-pip-egg-info-2u2rs2sz'
         cwd: C:\Users\PRANON~1\AppData\Local\Temp\pip-install-z2hpgfba\TTFQuery\
    Complete output (6 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\PRANON~1\AppData\Local\Temp\pip-install-z2hpgfba\TTFQuery\setup.py", line 11
        except ImportError, err:
                          ^
    SyntaxError: invalid syntax

ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

Body:
TTFQuery 1.0.5, last released in 2012. The code is obviously only for Python 2.

There is a beta release 2.0.0b1 from 2018. Try

pip install TTFQuery==2.0.0b1


问:
Create a global variable in TypeScript
In JavaScript I can just do this:

```<code> something = 'testing';
</code>```

And then in another file:

```<code> if (something === 'testing')
</code>```

and it will have something be defined (as long as they were called in the correct order).

I can't seem to figure out how to do that in TypeScript.

This is what I have tried.

In a .d.ts file:

```<code>interface Window { something: string; }
</code>```

Then in my main.ts file:

```<code> window.something = 'testing';
</code>```

then in another file:

```<code> if (window.something  === 'testing')
</code>```

And this works.  But I want to be able to lose the window. part of it and just have my something be global. Is there a way to do that in TypeScript?

(In case someone is interested, I am really trying to setup my logging for my application.  I want to be able to call log.Debug from any file without having to import and create objects.)

答:
This is working for me, as described in this thread:</p>

```<code>declare let something: string;
something = 'foo';
</code>```

Title: Create a global variable in TypeScript

Body:
In JavaScript I can just do this:

 something = 'testing';

And then in another file:

 if (something === 'testing')

and it will have something be defined (as long as they were called in the correct order).

I can't seem to figure out how to do that in TypeScript.

This is what I have tried.

In a .d.ts file:

interface Window { something: string; }

Then in my main.ts file:

 window.something = 'testing';

then in another file:

 if (window.something  === 'testing')

And this works.  But I want to be able to lose the window. part of it and just have my something be global. Is there a way to do that in TypeScript?

(In case someone is interested, I am really trying to setup my logging for my application.  I want to be able to call log.Debug from any file without having to import and create objects.)

Body:
This is working for me, as described in this thread:

declare let something: string;
something = 'foo';


答:
each then block will execute if previous then block return.

Your first console.log statement should be at the start of the doFetch function. It cannot be written where it is currently written in your code.

You should also chain a catch block at the end to catch any errors that might occur in the promise chain.

As a side note, you should use const or let keywords to declare variables instead of var.

```<code>const doFetch = (url) => {
  console.log("fetch request started because of click on element");

  fetch(url, {
    method: "GET",
    headers: 'X-Requested-With': 'fetch'
  })
  .then(response => {
    console.log("fetch request has received the response text");
    return response.text();
  })
  .then(response => {
    console.log("the received request response text was DOMparsed");
    return new DOMParser().parseFromString(text, "text/html");
  })
  .then(response => {
    let main = content.querySelector('main').innerHTML;
    console.log("the parsed response content replaced current HTML");
  })
  .catch(error => console.log(error));
};
</code>```

Title: Javascript fetch API chain "then"

Body:
each then block will execute if previous then block return.

Your first console.log statement should be at the start of the doFetch function. It cannot be written where it is currently written in your code.

You should also chain a catch block at the end to catch any errors that might occur in the promise chain.

As a side note, you should use const or let keywords to declare variables instead of var.

const doFetch = (url) => {
  console.log("fetch request started because of click on element");

  fetch(url, {
    method: "GET",
    headers: 'X-Requested-With': 'fetch'
  })
  .then(response => {
    console.log("fetch request has received the response text");
    return response.text();
  })
  .then(response => {
    console.log("the received request response text was DOMparsed");
    return new DOMParser().parseFromString(text, "text/html");
  })
  .then(response => {
    let main = content.querySelector('main').innerHTML;
    console.log("the parsed response content replaced current HTML");
  })
  .catch(error => console.log(error));
};


问:
How to determine question in decision tree?
Lets say we have a decision tree having question at node is petal length >= 2.5 ,so how does it decide value 2.5 ?</p>

答:
Decision trees use a recursive binary partitioning procedure in order to split the data in groups that are as homogeneous as possible, in terms of the outcome variable.

So the procedure loops through all the explanatory variables and tries a split at each level. It then chooses the split that partitions the data into the fewest misclassifications for the outcome variable.

For a more thorough explanation see this overview or if you have access to it the following book:

Breiman, L.; Friedman, J. H.; Olshen, R. A. and Stone, C. J. Classification and regression trees. Monterey, CA: Wadsworth and Brooks-Cole, 1984


问:
get and set in TypeScript
I'm trying to create get and set method for a property:

```<code>private _name: string;

Name() {
    get:
    {
        return this._name;
    }
    set:
    {
        this._name = ???;
    }
}
</code>```

What's the keyword to set a value?

答:
If you are looking for way to use get and set on any object (not a class) Proxy  may be usefull:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

```<code>const target = {
  message1: "hello",
  message2: "everyone"
};

const handler3 = {
  get: function (target, prop, receiver) {
    if (prop === "message2") {
      return "world";
    }
    return Reflect.get(...arguments);
  },
};

const proxy3 = new Proxy(target, handler3);

console.log(proxy3.message1); // hello
console.log(proxy3.message2); // world
</code>```

Note: be aware that this is new api not supported and required polifill for older browsers

Title: get and set in TypeScript

Body:
I'm trying to create get and set method for a property:

private _name: string;

Name() {
    get:
    {
        return this._name;
    }
    set:
    {
        this._name = ???;
    }
}

What's the keyword to set a value?

Body:
If you are looking for way to use get and set on any object (not a class) Proxy  may be usefull:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

const target = {
  message1: "hello",
  message2: "everyone"
};

const handler3 = {
  get: function (target, prop, receiver) {
    if (prop === "message2") {
      return "world";
    }
    return Reflect.get(...arguments);
  },
};

const proxy3 = new Proxy(target, handler3);

console.log(proxy3.message1); // hello
console.log(proxy3.message2); // world

Note: be aware that this is new api not supported and required polifill for older browsers


问:
MVC using DTO classes in ViewModels
When using Entity Framework code-first for example, is it advisable to use DTO classes inside your view model? Or should you directly use the entity classes?

I currently do it this way to not have to use [NotMapped] attribute and set some calculated properties on my DTO instead.

I guess it also has the benefit of not having to apply validation annotations directly on the entity class.

The reason for this question is if this is the correct way to go. What are your thoughts?

答:
You're on the right path. Definitely don't use EF models in your ViewModel. It creates a coupling between the database and the UI.

However... Using the dtos in viewmodel are but can cause problems when your UI diverges from the underlying api.

Unless it's a very small application I would tend to have models that I compose to make ViewModels and use something like AutoMapper to transfer the data between the UI model and the DTO.

You can use the same technique on the back end to transfer data bewteen the DTO and the EF model.

This keeps the DTO simple as it only has one job - transferring data at the api level. It neither knows nor cares about the UI or the database.

Title: MVC using DTO classes in ViewModels


问:
PinchZoom.js not working on iOS devices after 13.4 update by Apple
So I have run into a problem again with this plugin- PinchZoom.js which started happening after the 13.4 update by Apple for iOS devices.

The problem is that the double tap feature has suddenly stopped working completely on iOS devices now.

For a concrete test, you can refer to the plugin demo page: http://manuelstofer.github.io/pinchzoom/demo/pinchzoom.html

On iOS devices, you won't be able to double tap to zoom in the image whereas this was working fine in previous versions of iOS.

I have even dived down in the source code of the plugin but I am not sure what is causing the double tap TO NOT work in iOS devices after the update.

If anyone has any idea/workaround for this, it would be very helpful.

Thanks

答:
On all browsers there used to be a delay of 300-350ms on touchstart events. Apparently, on iOS there still is. You can test this by logging tap events and time in the touchstart event listener.

And for your issue, you could either solve it by modifying pinchzoom.js to use touchend which has no delay instead of touchstart, or by preventing default behaviour on the touchstart.

I chose the latter and added event.preventDefault() to the touchstart event listener. You can do that too, until the developer provides an official solution.

```<code>el.addEventListener('touchstart', function (event) {
    event.preventDefault(); //add this

    if (target.enabled) {
        firstMove = true;
        fingers = event.touches.length;
        detectDoubleTap(event);
    }
});
</code>```

Body:
On all browsers there used to be a delay of 300-350ms on touchstart events. Apparently, on iOS there still is. You can test this by logging tap events and time in the touchstart event listener.

And for your issue, you could either solve it by modifying pinchzoom.js to use touchend which has no delay instead of touchstart, or by preventing default behaviour on the touchstart.

I chose the latter and added event.preventDefault() to the touchstart event listener. You can do that too, until the developer provides an official solution.

el.addEventListener('touchstart', function (event) {
    event.preventDefault(); //add this

    if (target.enabled) {
        firstMove = true;
        fingers = event.touches.length;
        detectDoubleTap(event);
    }
});


答:
If first column is index is created new helper Index by sorted tuples:

```<code>g = df.index.map(lambda x: tuple(sorted(x.split('>'))))
</code>```

And then before aggregation is converted index to column by DataFrame.reset_index:

```<code>df = (df.reset_index()
        .groupby(g)
        .agg({'from_to':'first',
              'essential_move':'sum',
              'non-essential_move':'sum'})
        .reset_index(drop=True))
print (df)
                from_to  essential_move  non-essential_move
0         placeA>placeB            11.0                13.0
1         placeC>placeD             5.0                 2.0
</code>```

Title: pandas combining AB groups with BA, discarding BA

Body:
+-----------------------+----------------+--------------------+
| route_group_essential | essential_move | non-essential_move |
+-----------------------+----------------+--------------------+
| from_to               |                |                    |
| placeA>placeB         |           11.0 |               11.0 |
| placeB>placeA         |              0 |                2.0 |
| placeC>placeD         |            3.0 |                1.0 |
| placeD>placeC         |            2.0 |                1.0 |
+-----------------------+----------------+--------------------+

I want to combine A>B and B>A rows and sum up its values, discarding one row.

Expected output :

+-----------------------+----------------+--------------------+
| route_group_essential | essential_move | non-essential_move |
+-----------------------+----------------+--------------------+
| from_to               |                |                    |
| placeA>placeB         |           11.0 |               13.0 |
| placeC>placeD         |            5.0 |                2.0 |
+-----------------------+----------------+--------------------+

Body:
If first column is index is created new helper Index by sorted tuples:

g = df.index.map(lambda x: tuple(sorted(x.split('>'))))

And then before aggregation is converted index to column by DataFrame.reset_index:

df = (df.reset_index()
        .groupby(g)
        .agg({'from_to':'first',
              'essential_move':'sum',
              'non-essential_move':'sum'})
        .reset_index(drop=True))
print (df)
                from_to  essential_move  non-essential_move
0         placeA>placeB            11.0                13.0
1         placeC>placeD             5.0                 2.0