问:
Update plot based on user input in shiny
I have a shiny app that basically parses a user-uploaded .txt file (see this question I asked regarding the data input and parsing function), and then produces several plots by calling some plotting functions that are located above my shinyServer call in server.R.

The functions called in my server.R script are:

```<code>    parseR()      # Returns a dataframe (which is the result of parsing
                    the user input entered in `fileInput) ([see here][1] for details)
    senderPosts() # Returns a plot that is shown in tabPanel 1
    wordFreq()    # Returns a plot that is shown in tabPanel 2
    chatCloud()   # Returns a  plot that is shown in tabPanel 3
</code>```

I can successfully get the plot in tabPanel 1 to show the levels of a factor in the dataframe returned by parseR(), but I'm not sure how to use this to actually update the plot.

My question is, how can I update a plot based on user input?

Here is server.R:

```<code>shinyServer(function(input, output, session) {

  data <- reactive({
    req(input$file1)

    inFile <- input$file1

    df <- parseR(file=inFile$datapath) # Call my parser function

    updateSelectInput(session, inputId = 'sender', label = 'Sender',
                      choices = levels(df$sender), selected = levels(df$sender))

    return(df)
  })

  # Main page
  output$contents <- renderTable({
    head(data(), 25)
  })

  # tabPanel 1
  output$postCount <-renderPlot({
    senderPosts(file=input$file1$datapath)

  })

  # tabPanel 2
  output$wordCount <-renderPlot({
    wordFreq(file=input$file1$datapath)

    })

  # tabPanel 3
  output$chatCloud <-renderPlot({
    chatCloud(file=input$file1$datapath)

  })

})
</code>```

ui.R

```<code>library(shiny)

suppressMessages(library("wordcloud"))

shinyUI(fluidPage(
  titlePanel("File plotter"),
  tabsetPanel(
    tabPanel("Upload File",
             titlePanel("Upload your file"),
             sidebarLayout(
               sidebarPanel(
                 fileInput('file1', 'Select your file',
                           accept='.txt'
                           ),

                 tags$br()

               ),
               mainPanel(
                 tableOutput('contents'),
                 plotOutput('messageCount')
               )
             )
    ),

    # tabPanel 1
    tabPanel("Post Count",
             pageWithSidebar(
               headerPanel('Number of posts per user'),
               sidebarPanel(

                 # "Empty inputs" - they will be updated after the data is uploaded
                 selectInput('sender', 'Sender', "")
               ),
               mainPanel(
                 plotOutput('postCount')
               )
             )
    ),

    # tabPanel 2
    tabPanel("Word Frequency",
             pageWithSidebar(
               headerPanel('Most commonly used words'),
               sidebarPanel(

                 # "Empty inputs" - they will be updated after the data is uploaded
                 selectInput('word', 'Sender', "")
               ),
               mainPanel(
                 plotOutput('wordCount')
               )
             )
    ),

    # tabPanel 3
    tabPanel("Chat Cloud",
             pageWithSidebar(
               headerPanel('Most used words'),
               sidebarPanel(

                 # "Empty inputs" - they will be updated after the data is uploaded
                 selectInput('cloud', 'Sender', "")
               ),
               mainPanel(
                 plotOutput('chatCloud')
               )
             )
    )

  )
)
)
</code>```

答:
as I mentioned first you don't want to keep the updateInput in the Reactive function. This is because reactives are lazy evaluation. They are better placed within a observer (observe or observeEvent) which are eager evaluation.

You can then get the value of the User input through input$'inputId'

I would also place the plot calculations in a reactive function but that is not necessary.

```<code>shinyServer(function(input, output, session) {

  data <- reactive({
    req(input$file1)

    inFile <- input$file1

    df <- parseR(file=inFile$datapath) # Call my parser function

    return(df)
  })
  observe({
     df = data()
     updateSelectInput(session, inputId = 'sender', label = 'Sender',
                      choices = levels(df$sender), selected = levels(df$sender))
  })
  # Main page
  output$contents <- renderTable({
    head(data(), 25)
  })

  # tabPanel 1
  output$postCount <-renderPlot({
    senderPosts(file=input$file1$datapath,newParamter = input$sender)

  })

  # tabPanel 2
  output$wordCount <-renderPlot({
    wordFreq(file=input$file1$datapath)

    })

  # tabPanel 3
  output$chatCloud <-renderPlot({
    chatCloud(file=input$file1$datapath)

  })

})
</code>```

Body:
I have a shiny app that basically parses a user-uploaded .txt file (see this question I asked regarding the data input and parsing function), and then produces several plots by calling some plotting functions that are located above my shinyServer call in server.R.

The functions called in my server.R script are:

    parseR()      # Returns a dataframe (which is the result of parsing
                    the user input entered in `fileInput) ([see here][1] for details)
    senderPosts() # Returns a plot that is shown in tabPanel 1
    wordFreq()    # Returns a plot that is shown in tabPanel 2
    chatCloud()   # Returns a  plot that is shown in tabPanel 3

I can successfully get the plot in tabPanel 1 to show the levels of a factor in the dataframe returned by parseR(), but I'm not sure how to use this to actually update the plot.

My question is, how can I update a plot based on user input?

Here is server.R:

shinyServer(function(input, output, session) {

  data <- reactive({
    req(input$file1)

    inFile <- input$file1

    df <- parseR(file=inFile$datapath) # Call my parser function

    updateSelectInput(session, inputId = 'sender', label = 'Sender',
                      choices = levels(df$sender), selected = levels(df$sender))

    return(df)
  })

  # Main page
  output$contents <- renderTable({
    head(data(), 25)
  })

  # tabPanel 1
  output$postCount <-renderPlot({
    senderPosts(file=input$file1$datapath)

  })

  # tabPanel 2
  output$wordCount <-renderPlot({
    wordFreq(file=input$file1$datapath)

    })

  # tabPanel 3
  output$chatCloud <-renderPlot({
    chatCloud(file=input$file1$datapath)

  })

})

ui.R

library(shiny)

suppressMessages(library("wordcloud"))

shinyUI(fluidPage(
  titlePanel("File plotter"),
  tabsetPanel(
    tabPanel("Upload File",
             titlePanel("Upload your file"),
             sidebarLayout(
               sidebarPanel(
                 fileInput('file1', 'Select your file',
                           accept='.txt'
                           ),

                 tags$br()

               ),
               mainPanel(
                 tableOutput('contents'),
                 plotOutput('messageCount')
               )
             )
    ),

    # tabPanel 1
    tabPanel("Post Count",
             pageWithSidebar(
               headerPanel('Number of posts per user'),
               sidebarPanel(

                 # "Empty inputs" - they will be updated after the data is uploaded
                 selectInput('sender', 'Sender', "")
               ),
               mainPanel(
                 plotOutput('postCount')
               )
             )
    ),

    # tabPanel 2
    tabPanel("Word Frequency",
             pageWithSidebar(
               headerPanel('Most commonly used words'),
               sidebarPanel(

                 # "Empty inputs" - they will be updated after the data is uploaded
                 selectInput('word', 'Sender', "")
               ),
               mainPanel(
                 plotOutput('wordCount')
               )
             )
    ),

    # tabPanel 3
    tabPanel("Chat Cloud",
             pageWithSidebar(
               headerPanel('Most used words'),
               sidebarPanel(

                 # "Empty inputs" - they will be updated after the data is uploaded
                 selectInput('cloud', 'Sender', "")
               ),
               mainPanel(
                 plotOutput('chatCloud')
               )
             )
    )

  )
)
)

Body:
as I mentioned first you don't want to keep the updateInput in the Reactive function. This is because reactives are lazy evaluation. They are better placed within a observer (observe or observeEvent) which are eager evaluation.

You can then get the value of the User input through input$'inputId'

I would also place the plot calculations in a reactive function but that is not necessary.

shinyServer(function(input, output, session) {

  data <- reactive({
    req(input$file1)

    inFile <- input$file1

    df <- parseR(file=inFile$datapath) # Call my parser function

    return(df)
  })
  observe({
     df = data()
     updateSelectInput(session, inputId = 'sender', label = 'Sender',
                      choices = levels(df$sender), selected = levels(df$sender))
  })
  # Main page
  output$contents <- renderTable({
    head(data(), 25)
  })

  # tabPanel 1
  output$postCount <-renderPlot({
    senderPosts(file=input$file1$datapath,newParamter = input$sender)

  })

  # tabPanel 2
  output$wordCount <-renderPlot({
    wordFreq(file=input$file1$datapath)

    })

  # tabPanel 3
  output$chatCloud <-renderPlot({
    chatCloud(file=input$file1$datapath)

  })

})


来源: stackexchange

问:
TFS 2017 Build not compiling new .exe
Summary:

The TFS 2017 Build I inherited is not compiling a new exe.

Any ideas on what to to review?

More Detail

A coworker set up a TFS Build and then totally jumped ship (Gave his 2weeks but then stopped coming into work.)

Anyway, he  set up a TFS 2017 Build and it runs successfully (no errors) but when I look at the deployment directory (We are using Octopus Deploy.) it has an older version of the exe (dated 10/11). It looks as though something is working since the .config file is being updated by Octopus.

I am very new to setting up a TFS Build so any ideas would be helpful.

Thank You,

答:
I was able to resolve this issue.

The Version Numbers were not set up correctly.  Octopus Deploy was pulling an old version of the Package from 10/11 because that Version looked like the latest. However, it was not.

To resolve we deleted the old Packages in Octopus Deploy.

ContentLicense: CC BY-SA 3.0

Title: TFS 2017 Build not compiling new .exe


问:
Printing HashMap In Java
I have a HashMap:

private HashMap<TypeKey, TypeValue> example = new HashMap<TypeKey, TypeValue>();
```
<p>Now I would like to run through all the values and print them.</p>
<p>I wrote this:</p>
<pre class="lang-java prettyprint-override"><code>for (TypeValue name : this.example.keySet()) {
    System.out.println(name);
}
</code>```

It doesn't seem to work.

What is the problem?

EDIT:
Another question: Is this collection zero based? I mean if it has 1 key and value will the size be 0 or 1?

答:
A simple print statement with the variable name which contains the reference of the Hash Map would do :

```<code>HashMap<K,V> HM = new HashMap<>(); //empty
System.out.println(HM); //prints key value pairs enclosed in {}
</code>```

This works because the toString()method is already over-ridden in the AbstractMap class which is extended by the HashMap Class
More information from the documentation

Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).

ContentLicense: CC BY-SA 4.0

Title: Printing HashMap In Java

Body:
I have a HashMap:

private HashMap<TypeKey, TypeValue> example = new HashMap<TypeKey, TypeValue>();

Now I would like to run through all the values and print them.

I wrote this:

for (TypeValue name : this.example.keySet()) {
    System.out.println(name);
}

It doesn't seem to work.

What is the problem?

EDIT:
Another question: Is this collection zero based? I mean if it has 1 key and value will the size be 0 or 1?

Body:
A simple print statement with the variable name which contains the reference of the Hash Map would do :

HashMap<K,V> HM = new HashMap<>(); //empty
System.out.println(HM); //prints key value pairs enclosed in {}

This works because the toString()method is already over-ridden in the AbstractMap class which is extended by the HashMap Class
More information from the documentation

Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).


问:
Posting form-urlencoded in Angular 5
I'm trying to develop an application using a Spring backend and an Angular 5 frontend. For the login I am using Spring Security and in the frontend I am trying to post the login data as x-www-form-urlencoded. However the backend receives null for both username and password. The Angular 5 documentation for HttpClient provides examples only for posting json data and Http became deprecated.

Any suggestions on how to fix this would be greatly appreciated.

Here is my Angular code:

```<code>constructor(public httpClient: HttpClient) {
    console.log('Hello RestService Provider');
}

login(username: string, password: string) {
    var body = 'username=' + username + '&password=' + password + "&remember-me=" +  false;
    var headers = new HttpHeaders();
    headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
    let options = {headers: headers, withCredentials: true};
    this.callPostWithOptions("login", body, options).then(data=>{
      this.getCurrentUser();
    });
}

callPostWithOptions(address, body, options) {
    return new Promise(resolve => {
      address = this._SERVER_HOST + ":" + this._SERVER_PORT + "/" + address;
      this.httpClient.post(address, body, options)
        .subscribe((data) => {
            resolve(data);
          },
          (err) => {
            console.log("error during POST", err)
          });
    });
}
</code>```

And the server endpoint:

```<code>@RequestMapping(value = "/login", method = RequestMethod.GET)
@CrossOrigin(origins = "*")
public ModelAndView handle() {
    return new ModelAndView("/app/userOverview");
}
</code>```

Edit: I forgot to mention, when I test it with Postman it works without a problem

答:
The new HTTPClient module only works with immutable types. This means that headers and params cannot be modified. The append() operation actually returns a copy of your original, with the added header.

```<code>let headers = new HttpHeaders();
headers.append('...','...');// <- doesn't change the original object, but creates a new one!
</code>```

Instead, you want to capture the returned object:

```<code>let headers = new HttpHeaders();
headers = headers.append('...','...');
</code>```

As a sidenote, I would change callPostWithOptions to use the toPromise() operator:

```<code>callPostWithOptions(address, body, options) {
   address = '...';
   return this.httpClient.post(address, body, options).toPromise();
}
</code>```

Title: Posting form-urlencoded in Angular 5

Body:
I'm trying to develop an application using a Spring backend and an Angular 5 frontend. For the login I am using Spring Security and in the frontend I am trying to post the login data as x-www-form-urlencoded. However the backend receives null for both username and password. The Angular 5 documentation for HttpClient provides examples only for posting json data and Http became deprecated.

Any suggestions on how to fix this would be greatly appreciated.

Here is my Angular code:

constructor(public httpClient: HttpClient) {
    console.log('Hello RestService Provider');
}

login(username: string, password: string) {
    var body = 'username=' + username + '&password=' + password + "&remember-me=" +  false;
    var headers = new HttpHeaders();
    headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
    let options = {headers: headers, withCredentials: true};
    this.callPostWithOptions("login", body, options).then(data=>{
      this.getCurrentUser();
    });
}

callPostWithOptions(address, body, options) {
    return new Promise(resolve => {
      address = this._SERVER_HOST + ":" + this._SERVER_PORT + "/" + address;
      this.httpClient.post(address, body, options)
        .subscribe((data) => {
            resolve(data);
          },
          (err) => {
            console.log("error during POST", err)
          });
    });
}

And the server endpoint:

@RequestMapping(value = "/login", method = RequestMethod.GET)
@CrossOrigin(origins = "*")
public ModelAndView handle() {
    return new ModelAndView("/app/userOverview");
}

Edit: I forgot to mention, when I test it with Postman it works without a problem

Body:
The new HTTPClient module only works with immutable types. This means that headers and params cannot be modified. The append() operation actually returns a copy of your original, with the added header.

let headers = new HttpHeaders();
headers.append('...','...');// <- doesn't change the original object, but creates a new one!

Instead, you want to capture the returned object:

let headers = new HttpHeaders();
headers = headers.append('...','...');

As a sidenote, I would change callPostWithOptions to use the toPromise() operator:

callPostWithOptions(address, body, options) {
   address = '...';
   return this.httpClient.post(address, body, options).toPromise();
}


问:
' variable' was not declared in this scope
I'm new to Arduino coding and I'm not sure what issue I'm having with displaying the variable as serialPrint. Here is part of my code:</p>

```<code>void loop()
{
  int force1raw = analogRead(FSR_PIN1);
  int force2raw = analogRead(FSR_PIN2);
  int force3raw = analogRead(FSR_PIN3);
  float force1 = force1raw;
  float force2 = force2raw;
  float force3 = force3raw;

  for (int i = 0; i < 1000; i++)
  {
    // Use ADC reading to calculate voltage:
    float f1v = force1 * VCC / 1023.0;
    // Use voltage and static resistor value to
    // calculate FSR resistance:
    float f1r = R_DIV * (VCC / f1v - 1.0);
  }
    Serial.println("Resistance 1: " + String(f1r) + " ohms");
    // Estimate force based on slopes in figure 3 of
    // FSR datasheet:
    float force;
    float f1g = 1.0 / f1r; // Calculate conductance
    // Break parabolic curve down into two linear slopes:
    if (f1g <= 600)
      force1f = (f1g - 0.00075) / 0.00000032639;
    else
      force1f =  f1g / 0.000000642857;
    Serial.println("Force 1: " + String(force2f) + " g");
    Serial.println();

    delay(100);
</code>```

答:
Well,

```<code>Serial.println("Resistance 1: " + String(f1r) + " ohms");
</code>```

it uses the variable f1r whose scope just ended.

In C++, when a variable is defined inside a scope (between some { and }), it does not exist outside of it.

Body:
I'm new to Arduino coding and I'm not sure what issue I'm having with displaying the variable as serialPrint. Here is part of my code:

void loop()
{
  int force1raw = analogRead(FSR_PIN1);
  int force2raw = analogRead(FSR_PIN2);
  int force3raw = analogRead(FSR_PIN3);
  float force1 = force1raw;
  float force2 = force2raw;
  float force3 = force3raw;

  for (int i = 0; i < 1000; i++)
  {
    // Use ADC reading to calculate voltage:
    float f1v = force1 * VCC / 1023.0;
    // Use voltage and static resistor value to
    // calculate FSR resistance:
    float f1r = R_DIV * (VCC / f1v - 1.0);
  }
    Serial.println("Resistance 1: " + String(f1r) + " ohms");
    // Estimate force based on slopes in figure 3 of
    // FSR datasheet:
    float force;
    float f1g = 1.0 / f1r; // Calculate conductance
    // Break parabolic curve down into two linear slopes:
    if (f1g <= 600)
      force1f = (f1g - 0.00075) / 0.00000032639;
    else
      force1f =  f1g / 0.000000642857;
    Serial.println("Force 1: " + String(force2f) + " g");
    Serial.println();

    delay(100);

Body:
Well,

Serial.println("Resistance 1: " + String(f1r) + " ohms");

it uses the variable f1r whose scope just ended.

In C++, when a variable is defined inside a scope (between some { and }), it does not exist outside of it.


问:
Create Facebook Posts as Drafts via Graph API
i'm asking here cause i have no more idea. I'm trying to post as a Facebook Page on the Pages Feed. That all works very fine. But now, i need to create Facebook Posts as a Draft.
I've read nearly the whole Graph API Documentation but i didn't find a solution. I'm now able to publish scheduled, live and hidden Posts. But i have no idea how to publish a post as a Draft.

This is my working PHP Code

```<code>$PostObject->setPostMessage($Message);
$PostObject->setPostPlace($Post->getPostLocation());
$PostObject->setPostLink($Post->getPostLink());
$PostObject->setPostScheduledPublishTime($Post->getPostSheduledUnixtimestamp());
$PostObject->setPostAccessToken($Page->getPageAccessToken());
$PostObject->setPostTags($Post->getPostTagged());
$Response = $this->_facebookClient->post(
    '/' . $Page->getPageID() . "/feed",
    $PostObject->toArray()
);
</code>```

Can anybody give me a hint? I'm using the actual Graph API in Version 2.9.

Thank you very much!

答:
I had quite the same task and got crazy about the bad documentation of the "draft" feature within the API.

First of all: it is possible!

Have a look at https://developers.facebook.com/docs/graph-api/reference/page/videos/#Creating - there's a parameter popping up in the "create" section named unpublished_content_typewhich can be DRAFT, SCHEDULED or AD_POST.

The good thing now is: this works for all edges (feed, photo, video). With multiple photos, you need to provide this with each single photo before creating the post itself.

and parameter published needs to be set to false every time of course.

I've tested with every edge successfully and posts are popping up under "Drafts" in the page!

Have fun.

Body:
i'm asking here cause i have no more idea. I'm trying to post as a Facebook Page on the Pages Feed. That all works very fine. But now, i need to create Facebook Posts as a Draft.
I've read nearly the whole Graph API Documentation but i didn't find a solution. I'm now able to publish scheduled, live and hidden Posts. But i have no idea how to publish a post as a Draft.

This is my working PHP Code

$PostObject->setPostMessage($Message);
$PostObject->setPostPlace($Post->getPostLocation());
$PostObject->setPostLink($Post->getPostLink());
$PostObject->setPostScheduledPublishTime($Post->getPostSheduledUnixtimestamp());
$PostObject->setPostAccessToken($Page->getPageAccessToken());
$PostObject->setPostTags($Post->getPostTagged());
$Response = $this->_facebookClient->post(
    '/' . $Page->getPageID() . "/feed",
    $PostObject->toArray()
);

Can anybody give me a hint? I'm using the actual Graph API in Version 2.9.

Thank you very much!


问:
change names in dots to characters
I have a function like this one:

```<code>my_fun <- function(...,x,y){
  list(...)
}
</code>```

I want to be able to feed variable names OR strings to the ellipsis and convert all to character before returning. In my real case I will call a custom function through do.call(custom_fun,list(...)).

Expected output

What I'm asking here is a function my_fun2 that would have the following behavior :

```<code>my_fun2 <- function(...,x,y){
  MAGIC(list(...))
}

identical(my_fun("a",foo= "b == 3",c("c","d"),bar=c("e","f"),c("g","h")),
          my_fun2("a",foo= b == 3,c("c","d"),bar = c("e",f),c(g,h)))
</code>```

should be TRUE and both terms return:

```<code># [[1]]
# [1] "a"
#
# $foo
# [1] "b == 3"
#
# [[3]]
# [1] "c" "d"
#
# $bar
# [1] "e" "f"
#
# [[5]]
# [1] "g" "h"
</code>```

What I tried...

```<code>my_fun2 <- function(...,x,y){
 lapply(pryr::dots(...),as.character)
}

my_fun2("a",b == 3,c("c","d"),c("e",f),c(g,h))
# [[1]]
# [1] "a"
#
# [[2]]
# [1] "==" "b"  "3"
#
# [[3]]
# [1] "c" "c" "d"
#
# [[4]]
# [1] "c" "e" "f"
#
# [[5]]
# [1] "c" "g" "h"
</code>```

Notes

I don't have a good understanding of expressions, quotes, quosures, calls, names.. so I'll appreciate explanations relevant to the case.

I'm fine with solutions using either (or both!) base (substitute, quote etc) and dplyr answers (enquo, quosetc)

答:
I'm not proud but this had to be done...</p>

```<code>library(dplyr)
library(purrr)
library(pryr)
my_fun2 <- function(...,x,y){
  dots0 <- as.character(substitute(alist(...)))[-1]
  vectors <- substr(dots0,1,2) == "c("
  dotsv <- dots0[vectors] %>%
    gsub("\"","",.)    %>%
    gsub("(","('",.,fixed=TRUE)   %>%
    gsub(", ","', '",.,fixed=TRUE)  %>%
    gsub(")","')",.,fixed=TRUE)  %>%
    map(~eval(parse(text=.x)))
  setNames(c(as.list(dots0[!vectors]),dotsv),names(pryr::dots(...)))
}

identical(my_fun2("a",foo= "b == 3",c("c","d"),bar = c("e","f"),c("g","h")),
my_fun2("a",foo= b == 3,c("c","d"),bar = c("e",f),c(g,h)))
# [1] TRUE

# [[1]]
# [1] "a"
#
# $foo
# [1] "b == 3"
#
# [[3]]
# [1] "c" "d"
#
# $bar
# [1] "e" "f"
#
# [[5]]
# [1] "g" "h"
</code>```

Title: change names in dots to characters

Body:
I have a function like this one:

my_fun <- function(...,x,y){
  list(...)
}

I want to be able to feed variable names OR strings to the ellipsis and convert all to character before returning. In my real case I will call a custom function through do.call(custom_fun,list(...)).

Expected output

What I'm asking here is a function my_fun2 that would have the following behavior :

my_fun2 <- function(...,x,y){
  MAGIC(list(...))
}

identical(my_fun("a",foo= "b == 3",c("c","d"),bar=c("e","f"),c("g","h")),
          my_fun2("a",foo= b == 3,c("c","d"),bar = c("e",f),c(g,h)))

should be TRUE and both terms return:

# [[1]]
# [1] "a"
#
# $foo
# [1] "b == 3"
#
# [[3]]
# [1] "c" "d"
#
# $bar
# [1] "e" "f"
#
# [[5]]
# [1] "g" "h"

What I tried...

my_fun2 <- function(...,x,y){
 lapply(pryr::dots(...),as.character)
}

my_fun2("a",b == 3,c("c","d"),c("e",f),c(g,h))
# [[1]]
# [1] "a"
#
# [[2]]
# [1] "==" "b"  "3"
#
# [[3]]
# [1] "c" "c" "d"
#
# [[4]]
# [1] "c" "e" "f"
#
# [[5]]
# [1] "c" "g" "h"

Notes

I don't have a good understanding of expressions, quotes, quosures, calls, names.. so I'll appreciate explanations relevant to the case.

I'm fine with solutions using either (or both!) base (substitute, quote etc) and dplyr answers (enquo, quosetc)

Body:
I'm not proud but this had to be done...

library(dplyr)
library(purrr)
library(pryr)
my_fun2 <- function(...,x,y){
  dots0 <- as.character(substitute(alist(...)))[-1]
  vectors <- substr(dots0,1,2) == "c("
  dotsv <- dots0[vectors] %>%
    gsub("\"","",.)    %>%
    gsub("(","('",.,fixed=TRUE)   %>%
    gsub(", ","', '",.,fixed=TRUE)  %>%
    gsub(")","')",.,fixed=TRUE)  %>%
    map(~eval(parse(text=.x)))
  setNames(c(as.list(dots0[!vectors]),dotsv),names(pryr::dots(...)))
}

identical(my_fun2("a",foo= "b == 3",c("c","d"),bar = c("e","f"),c("g","h")),
my_fun2("a",foo= b == 3,c("c","d"),bar = c("e",f),c(g,h)))
# [1] TRUE

# [[1]]
# [1] "a"
#
# $foo
# [1] "b == 3"
#
# [[3]]
# [1] "c" "d"
#
# $bar
# [1] "e" "f"
#
# [[5]]
# [1] "g" "h"


问:
React js createElement throughs SCRIPT1002: Syntax error in IE11
Hell All
My website is working fine in Chrome in Firefox but not in IE 11.
It is giving SCRIPT1002: Syntax error in line number 243. Please help me to remove this issue.
 js link.
Please let me know if I missed any info.

BR
Ramukumar M

答:
Found the reason, there was a extra comma "," before the last curly bracket ")".
After removing the comma the code worked like expected.
For example

Error Code

Corrected Code

BR
Ramukumar M


问:
is there a single command to squash all commits against the base?
I have a hacky shell script that I use to clean up the history on a feature branch when I'm working with people who don't understand how rebasing works and have hundreds of messy commits and multiple merge commits, meaning it is not possible to do a single squash or fixup interactive rebase.

This script basically creates a single squashed commit out of their branch vs what they are merging to, regardless of how they got there.

this is not interactive rebasing Squash my last X commits together using Git

this is an automated version of Git: How to squash all commits on branch

But it's really hacky, is there an existing git command that does this? Or is there a more idiomatic way to write the script?

```<code>#!/bin/bash
set -e
if [ -n "$(git status -s)" ] ; then
   echo "ERROR: uncommitted changes"
   exit 1
fi
if [ -z "$1" ] ; then
   echo "ERROR: you must provide a base branch"
   exit 1
fi
NAME=`git rev-parse --abbrev-ref HEAD`
CUR=`git rev-parse HEAD`
TO=`git rev-parse $1`
echo "backing up your branch in bak/$CUR"
git checkout -b bak/$CUR
git checkout -b tmp/$CUR
git reset --hard $TO
git merge --squash $CUR
git commit --no-edit
git checkout $NAME
git reset --hard tmp/$CUR
git branch -D tmp/$CUR
echo "created a squash commit against $1 and rewrote your history"
</code>```

答:
... is there an existing git command that does this?

No: it takes at least three to do what you are doing, in terms of the final commits and positions of branch names:

git branch to create a new branch name pointing to the commit identified by HEAD;

git reset --soft to move the current branch name to the target commit without changing the index and work-tree;

git commit to make the new commit.

To obtain the desired log message for the new commit (the one built by git merge --squash) takes additional commands.  To get git merge --squash to build the message for you, you must use git merge --squash or repeat its logic (check merge.branchdesc and merge.log settings, run various Git commands to extract appropriate strings based on those settings).

Or is there a more idiomatic way to write the script?

Well, yes if you wanted to submit it as a contributed script to Git: then you would want to use git-sh-setup and a lot of lower level plumbing commands directly, and insert considerably more error checking (e.g., what should the script do when $1 cannot be git rev-parsed correctly? what should it do in a completely empty repository where even HEAD is invalid?).  But that would make the script a lot more verbose—not quite a ~2000 line monster like the rebase code:

```<code>$ wc -l git-rebase*sh
     103 git-rebase--am.sh
    1042 git-rebase--interactive.sh
     169 git-rebase--merge.sh
     648 git-rebase.sh
    1962 total
</code>```

but still a lot longer than it is now.

Besides that: In general, Git commands that do this sort of thing don't set up a backup branch name at all.  Instead, they rely on Git's reflogs for the branch names, and the ORIG_HEAD name that retains the immediately-previous setting.  If you were to omit the backup branch and use git reset --soft && git commit -F $msg_temp_file, you would get this same behavior—but once again you would have to construct the merge message in a temporary file.  Or, since both git reset and git merge --squash set ORIG_HEAD, if you were to use git merge --squash to create the new merge, you would have to use git update-ref to set ORIG_HEAD back to the correct value.

Both would change the observable behavior significantly, of course.

Body:
I have a hacky shell script that I use to clean up the history on a feature branch when I'm working with people who don't understand how rebasing works and have hundreds of messy commits and multiple merge commits, meaning it is not possible to do a single squash or fixup interactive rebase.

This script basically creates a single squashed commit out of their branch vs what they are merging to, regardless of how they got there.

this is not interactive rebasing Squash my last X commits together using Git

this is an automated version of Git: How to squash all commits on branch

But it's really hacky, is there an existing git command that does this? Or is there a more idiomatic way to write the script?

#!/bin/bash
set -e
if [ -n "$(git status -s)" ] ; then
   echo "ERROR: uncommitted changes"
   exit 1
fi
if [ -z "$1" ] ; then
   echo "ERROR: you must provide a base branch"
   exit 1
fi
NAME=`git rev-parse --abbrev-ref HEAD`
CUR=`git rev-parse HEAD`
TO=`git rev-parse $1`
echo "backing up your branch in bak/$CUR"
git checkout -b bak/$CUR
git checkout -b tmp/$CUR
git reset --hard $TO
git merge --squash $CUR
git commit --no-edit
git checkout $NAME
git reset --hard tmp/$CUR
git branch -D tmp/$CUR
echo "created a squash commit against $1 and rewrote your history"

Body:
... is there an existing git command that does this?

No: it takes at least three to do what you are doing, in terms of the final commits and positions of branch names:

git branch to create a new branch name pointing to the commit identified by HEAD;

git reset --soft to move the current branch name to the target commit without changing the index and work-tree;

git commit to make the new commit.

To obtain the desired log message for the new commit (the one built by git merge --squash) takes additional commands.  To get git merge --squash to build the message for you, you must use git merge --squash or repeat its logic (check merge.branchdesc and merge.log settings, run various Git commands to extract appropriate strings based on those settings).

Or is there a more idiomatic way to write the script?

Well, yes if you wanted to submit it as a contributed script to Git: then you would want to use git-sh-setup and a lot of lower level plumbing commands directly, and insert considerably more error checking (e.g., what should the script do when $1 cannot be git rev-parsed correctly? what should it do in a completely empty repository where even HEAD is invalid?).  But that would make the script a lot more verbose—not quite a ~2000 line monster like the rebase code:

$ wc -l git-rebase*sh
     103 git-rebase--am.sh
    1042 git-rebase--interactive.sh
     169 git-rebase--merge.sh
     648 git-rebase.sh
    1962 total

but still a lot longer than it is now.

Besides that: In general, Git commands that do this sort of thing don't set up a backup branch name at all.  Instead, they rely on Git's reflogs for the branch names, and the ORIG_HEAD name that retains the immediately-previous setting.  If you were to omit the backup branch and use git reset --soft && git commit -F $msg_temp_file, you would get this same behavior—but once again you would have to construct the merge message in a temporary file.  Or, since both git reset and git merge --squash set ORIG_HEAD, if you were to use git merge --squash to create the new merge, you would have to use git update-ref to set ORIG_HEAD back to the correct value.

Both would change the observable behavior significantly, of course.


问:
pyspark and python package performance
I've been using pyspark for work for about a year now and I'm wondering if anyone has any resources to help explain what goes on in the background when someone uses, say, Pandas from an anaconda install. For example, if I'm loading data into a pandas df with the read_csv method, I'm assuming this is NOT a distributed task, right? Likewise, are any python packages you import and use on pyspark also not distributed? Again, I'm inexperienced with the "guts" of how spark works like this, so I apologize for any bad phrasing.

Thanks!

答:
if I'm loading data into a pandas df with the read_csv method, I'm assuming this is NOT a distributed task, right?

Right

Likewise, are any python packages you import and use on pyspark also not distributed?

Indeed they are not.

Pyspark does not change at all the behavior of any other packages you may happen to use. Practically speaking, it is kind of another Python package (nowadays it is even available in PyPi); the distributed part kicks off only when you start transferring data to its own structures (RDDs, Spark dataframes etc), and even then it depends on how exactly you run the script (e.g. running in local mode will not distribute anything).

I'm wondering if anyone has any resources to help explain what goes on in the background when someone uses, say, Pandas from an anaconda install

It should be clear by now that there are not any resources on this, simply because there is nothing specific going on when you use pandas (or numpy, or scikit-learn...) in a Pyspark script.

Title: pyspark and python package performance


问:
Where can I store very large strings?
I tried to store a very large string in an XML file but after having to force close Android Studios a few times because it froze, it turned out to be too many bytes to store. Another option might be to store it in the Java files, but I don't think that's a good idea. Where can I store this and how could I paste it without my computer freezing?</p>

答: You can save your text in a simple .txt file inside assets/res folder or in SQLite Database and can access it whenever needed.

Title: Where can I store very large strings?


问:
How to set axes' step size in Chart.js 2?
I created a simple line chart using chart.js with 3 Y axes:
https://codepen.io/anon/pen/dZVgKw

As you can see, the last one is going from 10 to 20 without any number between. How can I set step size here?

This is how I add an axe:

```<code>{
  id: 'C',
  type: 'linear',
  position: 'left',
  ticks: {
    max: 10,
    min: 20,
  },
}
</code>```

Thanks.

答:
How can I set step size here?

Straight from the samples (Linear Scale, step size):

By setting a stepSize value.

```<code>scales: {
  xAxes: [{
    display: true,
    scaleLabel: {
      display: true,
      labelString: 'Month'
    }
  }],
  yAxes: [{
    display: true,
    scaleLabel: {
      display: true,
      labelString: 'Value'
    },
    ticks: {
      min: 0,
      max: 100,

      // forces step size to be 5 units
      stepSize: 5 // <----- This prop sets the stepSize
    }
  }]
}
</code>```

Here's a live example:

var ctx = document.getElementById('chartJSContainer').getContext('2d')

new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [
      {
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          reverse: false,
          stepSize: 3
        },
      }]
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.js"></script>
<body>
    <canvas id="chartJSContainer" width="600" height="400"></canvas>
</body></code>```

Body:
I created a simple line chart using chart.js with 3 Y axes:
https://codepen.io/anon/pen/dZVgKw

As you can see, the last one is going from 10 to 20 without any number between. How can I set step size here?

This is how I add an axe:

{
  id: 'C',
  type: 'linear',
  position: 'left',
  ticks: {
    max: 10,
    min: 20,
  },
}

Thanks.

Body:
How can I set step size here?

Straight from the samples (Linear Scale, step size):

By setting a stepSize value.

scales: {
  xAxes: [{
    display: true,
    scaleLabel: {
      display: true,
      labelString: 'Month'
    }
  }],
  yAxes: [{
    display: true,
    scaleLabel: {
      display: true,
      labelString: 'Value'
    },
    ticks: {
      min: 0,
      max: 100,

      // forces step size to be 5 units
      stepSize: 5 // <----- This prop sets the stepSize
    }
  }]
}

Here's a live example:

var ctx = document.getElementById('chartJSContainer').getContext('2d')

new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [
      {
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          reverse: false,
          stepSize: 3
        },
      }]
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.js"></script>
<body>
    <canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>


问:
How to host MassTransit and RabbitMq
We are working towards an architecture like one below but we will have micro services on cloud and some on premises which will talk to each other using queue(s) and bus(es),

Now I am confused with where we should host MassTransit and RabbitMq, also should it be a ASP.NET Core project on its own ? if yes what I will be doing in it ? starting a bus ? creating queues ? I am not able to move forward with this

答:
The simple MassTransit examples are just that, the absolute simplest examples of interacting with queues.

RabbitMQ is your message broker.  It is hosted separately.

MassTransit is a development framework that makes it much easier to interact with RabbitMQ (or Azure Service Bus) by abstracting away the implementation-specific "plumbing."

You write any number of .NET services that either publish messages to a queue, or subscribe to queues.

Title: How to host MassTransit and RabbitMq


问:
Access Fortran custom type attributes by default
is it possible with modern Fortran (90, 2003 or even 2008) to have a custom type where one of the attributes would be accessed by default:</p>

```<code>program test
    use iso_fortran_env
    type MYTYPE_t
        real(real64) :: data
    end type MYTYPE_t

    type(MYTYPE_T) :: test
    real(real64) :: foo

    ! This works
    test%data = 5.0
    ! Is there a way to be able things like this:
    test = 5.0
    print*, sqrt(test)

    foo = test + 3
end program
</code>```

答:
You must overload all the possible assignments, operators and intrinsics. Yes, it is a lot of work. No, there is no magic faster way that would cause automatic conversion in all contexts.

```<code>module types
    use iso_fortran_env

    implicit none

    type MYTYPE_t
        real(real64) :: data
    contains
        procedure assign
        procedure add
        generic :: assignment(=) => assign
        generic :: operator(+) => add
    end type MYTYPE_t

    interface sqrt
      procedure sqrt_MTYPE
    end interface

contains

    subroutine assign(l,r)
      class(MYTYPE_t), intent(out) :: l
      real(real32), intent(in) :: r
      l%data = r
    end subroutine

    real(real64) function sqrt_MTYPE(x)
      type(MYTYPE_t), intent(in) :: x
      sqrt_MTYPE = sqrt(x%data)
    end function

    real(real64) function add(x, y)
      class(MYTYPE_t), intent(in) :: x
      integer, intent(in) :: y

      add = x%data + y
    end function
end module types

program test_program
    use types

    implicit none

    type(MYTYPE_T) :: test
    real(real64) :: foo

    ! This works
    test%data = 5.0
    ! Is there a way to be able things like this:
    test = 5.0
    print*, sqrt(test)

    foo = test + 3
end program
</code>```

test:

```<code>> gfortran override3.f90
> ./a.out
   2.2360679774997898
</code>```

Body:
is it possible with modern Fortran (90, 2003 or even 2008) to have a custom type where one of the attributes would be accessed by default:

program test
    use iso_fortran_env
    type MYTYPE_t
        real(real64) :: data
    end type MYTYPE_t

    type(MYTYPE_T) :: test
    real(real64) :: foo

    ! This works
    test%data = 5.0
    ! Is there a way to be able things like this:
    test = 5.0
    print*, sqrt(test)

    foo = test + 3
end program

Body:
You must overload all the possible assignments, operators and intrinsics. Yes, it is a lot of work. No, there is no magic faster way that would cause automatic conversion in all contexts.

module types
    use iso_fortran_env

    implicit none

    type MYTYPE_t
        real(real64) :: data
    contains
        procedure assign
        procedure add
        generic :: assignment(=) => assign
        generic :: operator(+) => add
    end type MYTYPE_t

    interface sqrt
      procedure sqrt_MTYPE
    end interface

contains

    subroutine assign(l,r)
      class(MYTYPE_t), intent(out) :: l
      real(real32), intent(in) :: r
      l%data = r
    end subroutine

    real(real64) function sqrt_MTYPE(x)
      type(MYTYPE_t), intent(in) :: x
      sqrt_MTYPE = sqrt(x%data)
    end function

    real(real64) function add(x, y)
      class(MYTYPE_t), intent(in) :: x
      integer, intent(in) :: y

      add = x%data + y
    end function
end module types

program test_program
    use types

    implicit none

    type(MYTYPE_T) :: test
    real(real64) :: foo

    ! This works
    test%data = 5.0
    ! Is there a way to be able things like this:
    test = 5.0
    print*, sqrt(test)

    foo = test + 3
end program

test:

> gfortran override3.f90
> ./a.out
   2.2360679774997898


问:
RecyclerView items change size after refresh
I have a RecyclerView as the following image presents:

This is the setup code for this RecyclerView:

```<code>RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 2);
dataRecyclerView.setLayoutManager(layoutManager);
dataRecyclerView.addItemDecoration(new GridSpacingItemDecoration(...);
dataRecyclerView.setItemAnimator(new DefaultItemAnimator());
</code>```

after starting a new activity where I update the selected item of the RecyclerView, the RecyclerView is re-populated with new data to reflect the new change, but I get the following result:

And when I scroll down, I get this gap:

I tried calling RecyclerView#invalidate(), #invalidateItemDecorations(), #requestLayout() after the refresh but to no avail; & I'm also not calling setHasFixedSize(true) on the RecyclerView.

What is the problem exactly ? How can I resize the child items so as they wrap their content precisely after refreshing?

(P.S: I tried refreshing without making any changes & nothing happened, which proves my theory that the issue arises only when a child item's height changes.)

答:
That's quite late but I have also experienced this problem. This could be helpful for those still having the same bug.

In my case the solution was checking if there are any item decoration for recyclerview:

recyclerView.addItemDecoration(new SpacesItemDecoration(8));

This line was called everytime recyclerview is updated and was make recyclerview items getting smaller. Hope it helps the other.

Happy Coding,
Baki

Body:
I have a RecyclerView as the following image presents:

This is the setup code for this RecyclerView:

RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 2);
dataRecyclerView.setLayoutManager(layoutManager);
dataRecyclerView.addItemDecoration(new GridSpacingItemDecoration(...);
dataRecyclerView.setItemAnimator(new DefaultItemAnimator());

after starting a new activity where I update the selected item of the RecyclerView, the RecyclerView is re-populated with new data to reflect the new change, but I get the following result:

And when I scroll down, I get this gap:

I tried calling RecyclerView#invalidate(), #invalidateItemDecorations(), #requestLayout() after the refresh but to no avail; & I'm also not calling setHasFixedSize(true) on the RecyclerView.

What is the problem exactly ? How can I resize the child items so as they wrap their content precisely after refreshing?

(P.S: I tried refreshing without making any changes & nothing happened, which proves my theory that the issue arises only when a child item's height changes.)


答: I Think your best option is to store them in a database

Title: Where can I store very large strings?

Body: I tried to store a very large string in an XML file but after having to force close Android Studios a few times because it froze, it turned out to be too many bytes to store. Another option might be to store it in the Java files, but I don't think that's a good idea. Where can I store this and how could I paste it without my computer freezing?


问:
Authentication method calling problem on iPhone
When I have established SSL connection with NSURLConnection, I need to change certificates in credentials to make new request. But when I make new request, canAuthenticateAgainstProtectionSpace method don't fires and request use credentials which were setted to previous request. I've already tried to add '#' to the end of the URL, clear cookies,  but nothing works.</p>

答:
Have you impelemented the NSURLConnection delegate protocol,because that can be the only known cause why the       canAuthenticateAgainstProtectionSpace method is not fired.

Take a look at

```<code>@protocol NSURLAuthenticationChallengeSender <NSObject>
</code>```

in the Apple documentation

Also have a look at this thread.

Cheers

ContentLicense: CC BY-SA 2.5

Body:
Have you impelemented the NSURLConnection delegate protocol,because that can be the only known cause why the       canAuthenticateAgainstProtectionSpace method is not fired.

Take a look at

@protocol NSURLAuthenticationChallengeSender <NSObject>

in the Apple documentation

Also have a look at this thread.

Cheers


问:
Rails 4 has_many through for many to many association fails when creating association
Here is my schema:

```<code>create_table :policies do |t|
  t.string :name

  t.timestamps
end

create_table :permissions do |t|
  t.string :name
  t.string :method
  t.string :controller

  t.timestamps
end

create_join_table :policies, :permissions do |t|
  t.index :policy_id
  t.index :permission_id
end
</code>```

And here is the code I am using to create the records and their associations:

```<code>policy = Policy.create! name: "View All"
permission = Permission.create!({
  name: "View Events",
  method: "index",
  controller: "Events"
})

policy.permissions << permission
</code>```

And its returning the following error:

```<code>ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation "permission_policies" does not exist
</code>```

The table name that was created through the migration is policies_permissions

I wonder if this is an issue with the class names not being inferred properly

答:
Swap the positions of permissions and policies in the migration so that you create permissions_policies instead of policies_permissions. Rails infers the class names for a join table in alphabetical order.

See this answer for more information on join table naming conventions.

Body:
Here is my schema:

create_table :policies do |t|
  t.string :name

  t.timestamps
end

create_table :permissions do |t|
  t.string :name
  t.string :method
  t.string :controller

  t.timestamps
end

create_join_table :policies, :permissions do |t|
  t.index :policy_id
  t.index :permission_id
end

And here is the code I am using to create the records and their associations:

policy = Policy.create! name: "View All"
permission = Permission.create!({
  name: "View Events",
  method: "index",
  controller: "Events"
})

policy.permissions << permission

And its returning the following error:

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation "permission_policies" does not exist

The table name that was created through the migration is policies_permissions

I wonder if this is an issue with the class names not being inferred properly


问:
PHP: associate an array with another array both taken from curl
I have the following code that fetches arrays from a cURL.

```<code>$codici_hotel_arr = array();
foreach($data_destin['results'] as $key=>$val) {
    $codici_hotel_arr[] = '"' . $val['hotel_code'] . '"';
    $codici_price_arr[] = '"' . $val['products'][0]['price'] . '"';
}
$codici_definitivi = implode(', ', $codici_hotel_arr);
$codici_prezzi = implode(', ', $codici_price_arr);
</code>```

The code returns these values:

```<code>**$codici_definitivi:**
"1074d0", "19f726", "1072ba", "183444", "1071bf", "112438", "1b326e", "15d8ab", "19d885", "193e61", "10aab2", "107155", "110669", "189b95", "16d78f", "18dd7d"

**$codici_prezzi**
"160.16", "234.32", "256.88", "325.42", "342.22", "353.30", "365.78", "372.84", "395.72", "478.75", "503.36", "543.39", "584.61", "584.61", "597.70", "601.63".
</code>```

I would need to get a $codici_prezzi for each $codici_definitivi.
As a response of a string cURL, both codes are as follows:

1074d0 -> 160.16;

19f726 -> 234.32;

1072ba -> 256.88;

etc...

It's possible?

Thank you

答:
```<code>$new_codici_prezzi = array();
if(count($codici_definitivi) === count($codici_prezzi)){
    for($i = 0; $i < count($codici_definitivi); $i++){
        $new_codici_prezzi[$codici_definitivi[$i]] = $codici_prezzi[$i];
    }
}
</code>```

<p>//After that, $new_codici_prezzi is your new array.</p>

Body:
I have the following code that fetches arrays from a cURL.

$codici_hotel_arr = array();
foreach($data_destin['results'] as $key=>$val) {
    $codici_hotel_arr[] = '"' . $val['hotel_code'] . '"';
    $codici_price_arr[] = '"' . $val['products'][0]['price'] . '"';
}
$codici_definitivi = implode(', ', $codici_hotel_arr);
$codici_prezzi = implode(', ', $codici_price_arr);

The code returns these values:

**$codici_definitivi:**
"1074d0", "19f726", "1072ba", "183444", "1071bf", "112438", "1b326e", "15d8ab", "19d885", "193e61", "10aab2", "107155", "110669", "189b95", "16d78f", "18dd7d"

**$codici_prezzi**
"160.16", "234.32", "256.88", "325.42", "342.22", "353.30", "365.78", "372.84", "395.72", "478.75", "503.36", "543.39", "584.61", "584.61", "597.70", "601.63".

I would need to get a $codici_prezzi for each $codici_definitivi.
As a response of a string cURL, both codes are as follows:

1074d0 -> 160.16;

19f726 -> 234.32;

1072ba -> 256.88;

etc...

It's possible?

Thank you

Body:
$new_codici_prezzi = array();
if(count($codici_definitivi) === count($codici_prezzi)){
    for($i = 0; $i < count($codici_definitivi); $i++){
        $new_codici_prezzi[$codici_definitivi[$i]] = $codici_prezzi[$i];
    }
}

//After that, $new_codici_prezzi is your new array.


问:
Checking the equality of lists of Comparable objects in Groovy
I'm writing a test using the Spock framework and I found a strange bavior when testing equality of lists.

When I compare two lists like

```<code>sourceList == targetList
</code>```

and those lists contains Comparable objects of the same type, those objects are tested for equality using its compareTo methods instead of equals.

Is there any simple way how to force Groovy to use equals when testing equality on such lists?

Here is a simple test specification where the test should fail, but it does not.

```<code>class Test extends Specification {

def "list test"() {
    when:
        def listA = [[index: 1, text: "1"] as Bean, [index: 2, text: "2"] as Bean]
        def listB = [[index: 1, text: "1"] as Bean, [index: 2, text: "3"] as Bean]

    then:
        listA == listB
}

class Bean implements Comparable<Bean> {

    int index
    String text

    @Override
    public int compareTo(Bean o) {
        return index.compareTo(o.index);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + index;
        result = prime * result + ((text == null) ? 0 : text.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (!(obj instanceof Bean)) {
            return false;
        }
        Bean other = (Bean) obj;
        if (index != other.index) {
            return false;
        }
        if (text == null) {
            if (other.text != null) {
                return false;
            }
        } else if (!text.equals(other.text)) {
            return false;
        }
        return true;
    }

}

}
</code>```

答:
Asking for a simple method is subjective. The key to this answer is that, in Groovy, the is() method will check object equality.

Consider this new method on ArrayList. If appropriate, it will zip together the two lists and call is() on each pair of items.

```<code>ArrayList.metaClass.myCompare = { listB ->
    def result = false
    def listA = delegate
    if (listB && listA.size() == listB.size()) {
        def zipped = [listA, listB].transpose()
        result = zipped.inject(true){ ok, pair ->
            ok && pair[0].is(pair[1])
        }
    }
    result
}
</code>```

then:

```<code>def beanA = new Bean(index: 1, text: 'a')
def beanA1 = new Bean(index: 1, text: 'a')
def beanB = new Bean(index: 2, text: 'b')

assert [beanA, beanB].myCompare([beanA, beanB])
assert ! [beanA, beanB].myCompare([beanA1, beanB])
assert ! [beanA, beanB].myCompare([beanA])
assert ! [beanA, beanB].myCompare(null)
assert ! [beanA, beanB].myCompare([])
</code>```

Body:
I'm writing a test using the Spock framework and I found a strange bavior when testing equality of lists.

When I compare two lists like

sourceList == targetList

and those lists contains Comparable objects of the same type, those objects are tested for equality using its compareTo methods instead of equals.

Is there any simple way how to force Groovy to use equals when testing equality on such lists?

Here is a simple test specification where the test should fail, but it does not.

class Test extends Specification {

def "list test"() {
    when:
        def listA = [[index: 1, text: "1"] as Bean, [index: 2, text: "2"] as Bean]
        def listB = [[index: 1, text: "1"] as Bean, [index: 2, text: "3"] as Bean]

    then:
        listA == listB
}

class Bean implements Comparable<Bean> {

    int index
    String text

    @Override
    public int compareTo(Bean o) {
        return index.compareTo(o.index);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + index;
        result = prime * result + ((text == null) ? 0 : text.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (!(obj instanceof Bean)) {
            return false;
        }
        Bean other = (Bean) obj;
        if (index != other.index) {
            return false;
        }
        if (text == null) {
            if (other.text != null) {
                return false;
            }
        } else if (!text.equals(other.text)) {
            return false;
        }
        return true;
    }

}

}

Body:
Asking for a simple method is subjective. The key to this answer is that, in Groovy, the is() method will check object equality.

Consider this new method on ArrayList. If appropriate, it will zip together the two lists and call is() on each pair of items.

ArrayList.metaClass.myCompare = { listB ->
    def result = false
    def listA = delegate
    if (listB && listA.size() == listB.size()) {
        def zipped = [listA, listB].transpose()
        result = zipped.inject(true){ ok, pair ->
            ok && pair[0].is(pair[1])
        }
    }
    result
}

then:

def beanA = new Bean(index: 1, text: 'a')
def beanA1 = new Bean(index: 1, text: 'a')
def beanB = new Bean(index: 2, text: 'b')

assert [beanA, beanB].myCompare([beanA, beanB])
assert ! [beanA, beanB].myCompare([beanA1, beanB])
assert ! [beanA, beanB].myCompare([beanA])
assert ! [beanA, beanB].myCompare(null)
assert ! [beanA, beanB].myCompare([])


问:
DI: How much to inject?
I'm writing my second real life application, which uses DI. Overall I think it have let to a better design. But there are some code smells, that I don't know how to solve.

I prefer to use constructor injection and have often observed that I need about 5 or more objects to be injected in the constructor. It seems to be too many, maybe it's a design problem, not getting the SRP right. But I think that my use of DI also is to be blamed.

I'm looking for "best practices" or "rule of thumb", in general I seem to inject everything, that isn't in the .Net framework, is that overdoing it?

To get things started, here are two examples of objects that I inject, but am uncertain about.

Objects that are true singletons like application configuration or those small util classes, do you inject them?
They seems to be injected very often, the only reason to inject them seems to be allow to change the value for testing, but Ayende seems to have solved the problem in another way: http://ayende.com/Blog/archive/2008/07/07/Dealing-with-time-in-tests.aspx.

Common objects such as logging, that are used in almost every object, should they be injected?

答:
The rule of thumb I often use is that I inject things that are in the way of properly writing unit tests. When doing this you will sometimes end up abstracting away BCL classes (such as DateTime.Now, File, etc), and sometimes your own stuff. Good things to inject are services (such as ICustomerService, ICustomerUnitOfWorkFactory, or ICustomerRepository). Don't inject things like entities, DTOs and messages.

There are other reasons for injecting objects however, such as to be able to replace modules at a later time (for instance switch implementations for validation, UI, or O/RM), to allow parallel development within or across teams, and to lower maintenance.

I prefer to use constructor injection
  and have often observed that I need
  about 5 or more objects to be injected
  in the constructor.

As you already noted yourself, having many dependencies could be caused by not adhering to the SRP. What you can do however, is grouping common dependencies with there logic into an aggregate service and inject that into consumers. Also see Mark Seemann's article about Aggregate Services.

Objects that are true singletons like
  application configuration or those
  small util classes, do you inject
  them?

I am personally not a fan of the way Ayende proposes it. This is an Ambient Context, which is a specific sort of service locator construct. Doing this hides the dependency, because classes can call that static class without you having to inject it. Explicitly injecting it makes it much clearer that you need to unit test time. Besides that, it makes it hard to write tests for frameworks such as MSTest who tend to run tests in parallel. Without any countermeasures, it makes your tests very unreliable. A better solution -for the DateTime.Now example- is to have an IClock interface, as is suggested here. As you can see, that answer scores much higher than Ayende approach, that is shown in the same SO question.

Common objects such as logging, that
  are used in almost every object,
  should they be injected?

I inject them in my code, because that makes the dependencies clear. Note however, that in my code I still hardly ever have to inject a logger. Think hard about every line you want to log and it isn't really a failure (or a cross-cutting concern that should be placed elsewhere). I usually throw an exception when something happened that I didn't expect. It allows me to find bugs fast. Or to put it in other words: Don't filter, but fail fast. And please ask yourself: "Do I log too much?"

I hope this helps.

Title: DI: How much to inject?


问:
How can I make a hidden panel toggle on focus or click?
I'm trying to make a panel that appears when focused or clicked. Originally it was on click only and it is easy to set it up that way, but for accessibility I needed to make it so it also expanded when someone tabbed to it (on focus). I tried making it so it opens on focus only since a click will focus as well, but then it wouldn't close when clicked on after open because the focus was still enabled. Anyone got an idea to how to make this work?

```<code>$('.online-banking a.button.toggleClosed').one("click focusin", function() {
    $(this).removeClass('toggleClosed');
    $(this).addClass('toggleOpen');
    $('.online-banking-slidedown').slideDown(function() {
        $('.online-banking-slidedown input[type="text"]').focus();
    });
});
$('.online-banking a.button.toggleOpen').one("click focusout", function() {
    $(this).removeClass('toggleOpen');
    $(this).addClass('toggleClosed');
    $('.online-banking-slidedown').slideUp(function() {
        $('.online-banking-slidedown input[type="text"]').blur();
    });
</code>```

and here's the HTML

```<code><div class="online-banking">
    <a href="#" class="button toggleClosed">Online <span>Banking</span> Login</a>
    <div class="online-banking-slidedown">
        <form id="login" name="login" method="post" action="login.aspx">
            <input type="radio" name="radio" value="radio" id="banking_personal" checked="checked">
            <label class="personal" for="banking_personal">Personal</label>
            <input type="radio" name="radio" value="radio" id="banking_business">
            <label class="business" for="banking_business">Business</label>
            <input name="LoginName" type="text" maxlength="25" autocomplete="off" placeholder="User ID">
            <input type="submit" value="Sign In" data-category="Login" data-action="Click" data-label="Button" data-value="">
        </form>
    </div>
</div>
</code>```

答:
I think you may have the wrong idea when it comes to accessibility(AODA). Your button which is an anchor is NOT hidden, only some contents are hidden. So there is no need to bind focus on the anchor, the only real to do here for AODA is to set focus on the content that shows after you clicked on the button. So the user knows that something happened.

Or you could announce that some content was just shown to the user. When user clicks on the button again (close) the focus should just remain on the anchor, so there should not be any to dos there.

To set focus on the content, say a div, you just need to give it a tabindex="-1" and then you can programmatically focus it with js.

It looks like you are already setting focus to the input after the slide down is done, which is great.

You can remove

```<code>$('.online-banking-slidedown').slideUp(function() {
    $('.online-banking-slidedown input[type="text"]').blur();
});
</code>```

Because when you clicked on the button to close it, the focus is already on the button and there is no need to blur.

Revert your code back to when you only bound click and you should be good to go

Body:
I'm trying to make a panel that appears when focused or clicked. Originally it was on click only and it is easy to set it up that way, but for accessibility I needed to make it so it also expanded when someone tabbed to it (on focus). I tried making it so it opens on focus only since a click will focus as well, but then it wouldn't close when clicked on after open because the focus was still enabled. Anyone got an idea to how to make this work?

$('.online-banking a.button.toggleClosed').one("click focusin", function() {
    $(this).removeClass('toggleClosed');
    $(this).addClass('toggleOpen');
    $('.online-banking-slidedown').slideDown(function() {
        $('.online-banking-slidedown input[type="text"]').focus();
    });
});
$('.online-banking a.button.toggleOpen').one("click focusout", function() {
    $(this).removeClass('toggleOpen');
    $(this).addClass('toggleClosed');
    $('.online-banking-slidedown').slideUp(function() {
        $('.online-banking-slidedown input[type="text"]').blur();
    });

and here's the HTML

    Online Banking Login

        <form id="login" name="login" method="post" action="login.aspx">
            <input type="radio" name="radio" value="radio" id="banking_personal" checked="checked">
            Personal
            <input type="radio" name="radio" value="radio" id="banking_business">
            Business
            <input name="LoginName" type="text" maxlength="25" autocomplete="off" placeholder="User ID">
            <input type="submit" value="Sign In" data-category="Login" data-action="Click" data-label="Button" data-value="">
        </form>

Body:
I think you may have the wrong idea when it comes to accessibility(AODA). Your button which is an anchor is NOT hidden, only some contents are hidden. So there is no need to bind focus on the anchor, the only real to do here for AODA is to set focus on the content that shows after you clicked on the button. So the user knows that something happened.

Or you could announce that some content was just shown to the user. When user clicks on the button again (close) the focus should just remain on the anchor, so there should not be any to dos there.

To set focus on the content, say a div, you just need to give it a tabindex="-1" and then you can programmatically focus it with js.

It looks like you are already setting focus to the input after the slide down is done, which is great.

You can remove

$('.online-banking-slidedown').slideUp(function() {
    $('.online-banking-slidedown input[type="text"]').blur();
});

Because when you clicked on the button to close it, the focus is already on the button and there is no need to blur.

Revert your code back to when you only bound click and you should be good to go


问:
SQL WHERE Like Clause not returning all results
I have a strange one that I have been scratching my head over for the past few hours.

I have a relatively simple TSQL

```<code>SELECT
  LTRIM(RTRIM(bom_comp_code)) [bom_comp_code]
  , bom_product
  , bom.actual_partnumber
FROM
  dbo.MRP_ALL bom
WHERE
  bom.bom_product = 'F00434'
</code>```

This returns 500 rows of a result like - perfect

```<code>[bom_comp_code]  [bom_product]  [actual_partnumber]
M03275           F00434         99292922
M03275           F00434         99292922
B01869           F00434         99292922
B01869           F00434         99292922
M03275           F00434         99292922
M03275           F00434         99292922
B01869           F00434         99292922
...
...
B01869           F00434         99292922
B01869           F00434         99292922
M03275           F00434         1110-011
M03275           F00434         1110-011
</code>```

Now I am only interested in bom_comp_code that start with an M, so naturally I use the following TSQL

```<code>SELECT
  LTRIM(RTRIM(bom_comp_code)) [bom_comp_code]
  , bom_product
  , bom.actual_partnumber
FROM
  dbo.MRP_ALL bom
WHERE
  bom.bom_product = 'F00434'
AND LTRIM(RTRIM(bom.bom_comp_code)) like 'M%'
</code>```

But this only returns one row!

```<code>[bom_comp_code]  [bom_product]  [actual_partnumber]
M03275           F00434         1110-011
</code>```

I cannot for the life of me understand why only one row is returned when there are 224 in the table that match my criteria

The LTRIM / RTRIM was me thinking there was whitespace around the bom_comp_code field, but this did not work.

I have also tried this around bom_product too just in case.

What could possible be stopping all my rows from returning?

答:
I had a similar problem and I had special characters just as "Juan Carlos Oropeza" mentions above.

Using the function in this answer https://stackoverflow.com/a/14211957/7141065, I was able to update the column in question and run queries as normal after that.

Body:
I have a strange one that I have been scratching my head over for the past few hours.

I have a relatively simple TSQL

SELECT
  LTRIM(RTRIM(bom_comp_code)) [bom_comp_code]
  , bom_product
  , bom.actual_partnumber
FROM
  dbo.MRP_ALL bom
WHERE
  bom.bom_product = 'F00434'

This returns 500 rows of a result like - perfect

[bom_comp_code]  [bom_product]  [actual_partnumber]
M03275           F00434         99292922
M03275           F00434         99292922
B01869           F00434         99292922
B01869           F00434         99292922
M03275           F00434         99292922
M03275           F00434         99292922
B01869           F00434         99292922
...
...
B01869           F00434         99292922
B01869           F00434         99292922
M03275           F00434         1110-011
M03275           F00434         1110-011

Now I am only interested in bom_comp_code that start with an M, so naturally I use the following TSQL

SELECT
  LTRIM(RTRIM(bom_comp_code)) [bom_comp_code]
  , bom_product
  , bom.actual_partnumber
FROM
  dbo.MRP_ALL bom
WHERE
  bom.bom_product = 'F00434'
AND LTRIM(RTRIM(bom.bom_comp_code)) like 'M%'

But this only returns one row!

[bom_comp_code]  [bom_product]  [actual_partnumber]
M03275           F00434         1110-011

I cannot for the life of me understand why only one row is returned when there are 224 in the table that match my criteria

The LTRIM / RTRIM was me thinking there was whitespace around the bom_comp_code field, but this did not work.

I have also tried this around bom_product too just in case.

What could possible be stopping all my rows from returning?


问:
Is it possible to use HTTP (NOT HTTPS) over port 443?
I wonder if it is possible to communicate plain HTTP (no SSL) over the TCP port 443?

Trying to change the address of my WCF based server to use the port 443 (but no SSL) fails with this message:

```<code>Shunra.Common.Wcf.ShunraServiceHost - Open failed with exception
System.ServiceModel.AddressAlreadyInUseException: HTTP could not register URL http://+:443/NC/. Another application has already registered this URL with HTTP.SYS. ---> System.Net.HttpListenerException: Failed to listen on prefix 'http://+:443/NC/' because it conflicts with an existing registration on the machine.
   at System.Net.HttpListener.AddAllPrefixes()
   at System.Net.HttpListener.Start()
   at System.ServiceModel.Channels.SharedHttpTransportManager.OnOpen()
   --- End of inner exception stack trace ---
   at System.ServiceModel.Channels.SharedHttpTransportManager.OnOpen()
   at System.ServiceModel.Channels.TransportManager.Open(TransportChannelListener channelListener)
   at System.ServiceModel.Channels.TransportManagerContainer.Open(SelectTransportManagersCallback selectTransportManagerCallback)
   at System.ServiceModel.Channels.TransportChannelListener.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.HttpChannelListener.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open()
   at Shunra.Common.Wcf.ShunraServiceHost.Open() in c:\dev\windows\Common\Shunra.Common\Wcf\ShunraServiceHost.cs:line 65
</code>```

And this is not the matter of HTTP namespace reservation, since the user is an administrator.

So, I am wondering whether there is a special treatment of the port 443 as to only allow HTTPS over it.

Thanks.

答:
Notice that the error message says

Another application has already registered this URL with HTTP.SYS.

So this seems to indicate that another application already uses port 443, and that this is the problem. You can only have several applications listen on the same port if they differ in their host header.

Body:
I wonder if it is possible to communicate plain HTTP (no SSL) over the TCP port 443?

Trying to change the address of my WCF based server to use the port 443 (but no SSL) fails with this message:

Shunra.Common.Wcf.ShunraServiceHost - Open failed with exception
System.ServiceModel.AddressAlreadyInUseException: HTTP could not register URL http://+:443/NC/. Another application has already registered this URL with HTTP.SYS. ---> System.Net.HttpListenerException: Failed to listen on prefix 'http://+:443/NC/' because it conflicts with an existing registration on the machine.
   at System.Net.HttpListener.AddAllPrefixes()
   at System.Net.HttpListener.Start()
   at System.ServiceModel.Channels.SharedHttpTransportManager.OnOpen()
   --- End of inner exception stack trace ---
   at System.ServiceModel.Channels.SharedHttpTransportManager.OnOpen()
   at System.ServiceModel.Channels.TransportManager.Open(TransportChannelListener channelListener)
   at System.ServiceModel.Channels.TransportManagerContainer.Open(SelectTransportManagersCallback selectTransportManagerCallback)
   at System.ServiceModel.Channels.TransportChannelListener.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.HttpChannelListener.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open()
   at Shunra.Common.Wcf.ShunraServiceHost.Open() in c:\dev\windows\Common\Shunra.Common\Wcf\ShunraServiceHost.cs:line 65

And this is not the matter of HTTP namespace reservation, since the user is an administrator.

So, I am wondering whether there is a special treatment of the port 443 as to only allow HTTPS over it.

Thanks.


问:
BTOUCH:error BI1017:Do not know how to make a signature for System.Int32* in method get_IssueTransport
I am binding JMC objective C static library to Xamarin compatible one, currently I am trying to build my binding project now(which contains ApiDefinition.cs, StructsAndEnums.cs and libJmcSDK.a) but when I try to build this Xamarin binding project I'm getting the following error:

BTOUCH: error BI1017: btouch: Do not know how to make a signature for System.Int32* in method 'get_IssueTransport'.

When I try to search for get_IssueTransport method, their is no search results for this, trying to find the System.Int32 signature as well but not able to find in throughout solution.

Any help in resolving this issue is much appreciated in advance. Thanks.

答:
Answer

Remove unsafe keyword and * from int.

 Like:

unsafe int*


问:
Calling a method using jni: Bad JNI oop argument
I'm trying to call a method using jni (java native interface), but it crashes when I'm calling the method. I read the documentation, so I found out that I need to use objects of the type "jvalue" as parameters, but, how can I convert a jobject/j to a jvalue?

Here's my current code:

```<code>    jclass unsafeClass = (*env).FindClass("sun/misc/Unsafe");
    jfieldID unsafeObjFieldID = (*env).GetStaticFieldID(unsafeClass, "theUnsafe", "Lsun/misc/Unsafe;");

    jobject theUnsafe = (*env).GetStaticObjectField(unsafeClass, unsafeObjFieldID);

    jmethodID defineClassID = (*env).GetMethodID(unsafeClass, "defineClass", "(Ljava/lang/String;[BIILjava/lang/ClassLoader;Ljava/security/ProtectionDomain;)Ljava/lang/Class;");

    jsize dataSize = (*env).GetArrayLength(arr);
    jbyte* data = (*env).GetByteArrayElements(arr, NULL);
    jstring name = (*env).NewStringUTF("Test");
    jint n0 = (jint) 0;

    // In this method it crashes ._.
    (*env).CallObjectMethod(theUnsafe, defineClassID, name, data, n0, dataSize, classLoader, NULL);
</code>```

hs_err_pid (if it would help): http://paste.reflex.rip/okugaluyok.go

EDIT: I found the startparam "-Xcheck:jni", now I got a little error message.

```<code>FATAL ERROR in native method: Bad JNI oop argument
</code>```

答:
I know this is old and outdated, but this seems to be the only thread with this particular error message.  I do not have the same setup as the OP but I found that when I tried to do this

```<code>env->CallStaticVoidMethod(jcls, mainMethod);
</code>```

I would receive this same error.  This was to invoke the main static method of my main class.  It also produced the same error message "Bad JNI oop argument".

I fixed this by creating a new (empty) jobjectArray and passed it to the method, and it fixed my error.

```<code>jobjectArray args;
args = env->NewObjectArray(0, env->FindClass("java/lang/String"), 0);
env->CallStaticVoidMethod(jcls, mainMethod, args);
</code>```

Body:
I'm trying to call a method using jni (java native interface), but it crashes when I'm calling the method. I read the documentation, so I found out that I need to use objects of the type "jvalue" as parameters, but, how can I convert a jobject/j to a jvalue?

Here's my current code:

    jclass unsafeClass = (*env).FindClass("sun/misc/Unsafe");
    jfieldID unsafeObjFieldID = (*env).GetStaticFieldID(unsafeClass, "theUnsafe", "Lsun/misc/Unsafe;");

    jobject theUnsafe = (*env).GetStaticObjectField(unsafeClass, unsafeObjFieldID);

    jmethodID defineClassID = (*env).GetMethodID(unsafeClass, "defineClass", "(Ljava/lang/String;[BIILjava/lang/ClassLoader;Ljava/security/ProtectionDomain;)Ljava/lang/Class;");

    jsize dataSize = (*env).GetArrayLength(arr);
    jbyte* data = (*env).GetByteArrayElements(arr, NULL);
    jstring name = (*env).NewStringUTF("Test");
    jint n0 = (jint) 0;

    // In this method it crashes ._.
    (*env).CallObjectMethod(theUnsafe, defineClassID, name, data, n0, dataSize, classLoader, NULL);

hs_err_pid (if it would help): http://paste.reflex.rip/okugaluyok.go

EDIT: I found the startparam "-Xcheck:jni", now I got a little error message.

FATAL ERROR in native method: Bad JNI oop argument

Body:
I know this is old and outdated, but this seems to be the only thread with this particular error message.  I do not have the same setup as the OP but I found that when I tried to do this

env->CallStaticVoidMethod(jcls, mainMethod);

I would receive this same error.  This was to invoke the main static method of my main class.  It also produced the same error message "Bad JNI oop argument".

I fixed this by creating a new (empty) jobjectArray and passed it to the method, and it fixed my error.

jobjectArray args;
args = env->NewObjectArray(0, env->FindClass("java/lang/String"), 0);
env->CallStaticVoidMethod(jcls, mainMethod, args);


问:
Is it possible to access the compressed data before decompression in HttpClient?
I'm working on the Google Cloud Storage .NET client
library. There are three features (between .NET, my client
library, and the Storage service) that are combining in an
unpleasant way:

When downloading files (objects in Google Cloud Storage
terminology), the server includes a hash of the stored data. My
client code then validates that hash against the data it's
downloaded.

A separate feature of Google Cloud Storage is that the user can
set the Content-Encoding of the object, and that's included as a
header when downloading, when the request contains a matching
Accept-Encoding. (For the moment, let's ignore the behavior when the
request doesn't include that...)

HttpClientHandler can decompress gzip (or deflate) content
automatically and transparently.

When all three of these are combined, we get into trouble. Here's a
short but complete program demonstrating that, but without using my
client library (and hitting a publicly accessible file):

```<code>using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        string url = "https://www.googleapis.com/download/storage/v1/b/"
            + "storage-library-test-bucket/o/gzipped-text.txt?alt=media";
        var handler = new HttpClientHandler
        {
            AutomaticDecompression = DecompressionMethods.GZip
        };
        var client = new HttpClient(handler);

        var response = await client.GetAsync(url);
        byte[] content = await response.Content.ReadAsByteArrayAsync();
        string text = Encoding.UTF8.GetString(content);
        Console.WriteLine($"Content: {text}");

        var hashHeader = response.Headers.GetValues("X-Goog-Hash").FirstOrDefault();
        Console.WriteLine($"Hash header: {hashHeader}");

        using (var md5 = MD5.Create())
        {
            var md5Hash = md5.ComputeHash(content);
            var md5HashBase64 = Convert.ToBase64String(md5Hash);
            Console.WriteLine($"MD5 of content: {md5HashBase64}");
        }
    }
}
</code>```

.NET Core project file:

```<code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <LangVersion>7.1</LangVersion>
  </PropertyGroup>
</Project>
</code>```

Output:

```<code>Content: hello world
Hash header: crc32c=T1s5RQ==,md5=xhF4M6pNFRDQnvaRRNVnkA==
MD5 of content: XrY7u+Ae7tCTyyK7j1rNww==
</code>```

As you can see, the MD5 of the content isn't the same as the MD5
part of the X-Goog-Hash header. (In my client library I'm using the crc32c
hash, but that shows the same behavior.)

This isn't a bug in HttpClientHandler - it's expected, but a pain
when I want to validate the hash. Basically, I need to at the
content before and after decompression. And I can't find any way
of doing that.

To clarify my requirements somewhat, I know how to prevent the decompression in HttpClient and instead decompress afterwards when reading from the stream - but I need to be able to do this without changing any the code that uses the resulting HttpResponseMessage from the HttpClient. (There's a lot of code that deals with responses, and I want to only make the change in one central place.)

I have a plan, which I've prototyped and which works as far as I've
found so far, but is a bit ugly. It involves creating a three-layer
handler:

HttpClientHandler with automatic decompression disabled.

A new handler which replaces the content stream with a new Stream subclass
which delegates to the original content stream, but hashes the data as it's read.

A decompression-only handler, based on the Microsoft DecompressionHandler code.

While this works, it has disadvantages of:

Open source licensing: checking exactly what I need to do in order
to create a new file in my repo based on the MIT-licensed
Microsoft code

Effectively forking the MS code, which means I should probably
make a regular check to see if any bugs have been found in it

The Microsoft code uses internal members of the assembly, so it
doesn't port as cleanly as it might.

If Microsoft made DecompressionHandler public, that would help a
lot - but that's likely to be in a longer timeframe than I need.

What I'm looking for is an alternative approach if possible -
something I've missed that lets me get at the content before
decompression. I don't want to reinvent HttpClient - the response
is often chunked for example, and I don't want to have to get into
that side of things. It's a pretty specific interception point that
I'm looking for.

答:
I managed to get the headerhash correct by:

creating a custom handler that inherits HttpClientHandler

overriding SendAsync

read as byte the response using base.SendAsync

Compress it using GZipStream

Hashing the Gzip Md5 to base64 (using your code)

this issue is, as you said "before decompression" is not really respected here

The idea is to get this if working as you would like
https://github.com/dotnet/corefx/blob/master/src/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseParser.cs#L80-L91

it matches

```<code>class Program
{
    const string url = "https://www.googleapis.com/download/storage/v1/b/storage-library-test-bucket/o/gzipped-text.txt?alt=media";

    static async Task Main()
    {
        //await HashResponseContent(CreateHandler(DecompressionMethods.None));
        //await HashResponseContent(CreateHandler(DecompressionMethods.GZip));
        await HashResponseContent(new MyHandler());

        Console.ReadLine();
    }

    private static HttpClientHandler CreateHandler(DecompressionMethods decompressionMethods)
    {
        return new HttpClientHandler { AutomaticDecompression = decompressionMethods };
    }

    public static async Task HashResponseContent(HttpClientHandler handler)
    {
        //Console.WriteLine($"Using AutomaticDecompression : '{handler.AutomaticDecompression}'");
        //Console.WriteLine($"Using SupportsAutomaticDecompression : '{handler.SupportsAutomaticDecompression}'");
        //Console.WriteLine($"Using Properties : '{string.Join('\n', handler.Properties.Keys.ToArray())}'");

        var client = new HttpClient(handler);

        var response = await client.GetAsync(url);
        byte[] content = await response.Content.ReadAsByteArrayAsync();
        string text = Encoding.UTF8.GetString(content);
        Console.WriteLine($"Content: {text}");

        var hashHeader = response.Headers.GetValues("X-Goog-Hash").FirstOrDefault();
        Console.WriteLine($"Hash header: {hashHeader}");
        byteArrayToMd5(content);

        Console.WriteLine($"=====================================================================");
    }

    public static string byteArrayToMd5(byte[] content)
    {
        using (var md5 = MD5.Create())
        {
            var md5Hash = md5.ComputeHash(content);
            return Convert.ToBase64String(md5Hash);
        }
    }

    public static byte[] Compress(byte[] contentToGzip)
    {
        using (MemoryStream resultStream = new MemoryStream())
        {
            using (MemoryStream contentStreamToGzip = new MemoryStream(contentToGzip))
            {
                using (GZipStream compressionStream = new GZipStream(resultStream, CompressionMode.Compress))
                {
                    contentStreamToGzip.CopyTo(compressionStream);
                }
            }

            return resultStream.ToArray();
        }
    }
}

public class MyHandler : HttpClientHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var response = await base.SendAsync(request, cancellationToken);
        var responseContent = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

        Program.byteArrayToMd5(responseContent);

        var compressedResponse = Program.Compress(responseContent);
        var compressedResponseMd5 = Program.byteArrayToMd5(compressedResponse);

        Console.WriteLine($"recompressed response to md5 : {compressedResponseMd5}");

        return response;
    }
}
</code>```

Body:
I'm working on the Google Cloud Storage .NET client
library. There are three features (between .NET, my client
library, and the Storage service) that are combining in an
unpleasant way:

When downloading files (objects in Google Cloud Storage
terminology), the server includes a hash of the stored data. My
client code then validates that hash against the data it's
downloaded.

A separate feature of Google Cloud Storage is that the user can
set the Content-Encoding of the object, and that's included as a
header when downloading, when the request contains a matching
Accept-Encoding. (For the moment, let's ignore the behavior when the
request doesn't include that...)

HttpClientHandler can decompress gzip (or deflate) content
automatically and transparently.

When all three of these are combined, we get into trouble. Here's a
short but complete program demonstrating that, but without using my
client library (and hitting a publicly accessible file):

using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        string url = "https://www.googleapis.com/download/storage/v1/b/"
            + "storage-library-test-bucket/o/gzipped-text.txt?alt=media";
        var handler = new HttpClientHandler
        {
            AutomaticDecompression = DecompressionMethods.GZip
        };
        var client = new HttpClient(handler);

        var response = await client.GetAsync(url);
        byte[] content = await response.Content.ReadAsByteArrayAsync();
        string text = Encoding.UTF8.GetString(content);
        Console.WriteLine($"Content: {text}");

        var hashHeader = response.Headers.GetValues("X-Goog-Hash").FirstOrDefault();
        Console.WriteLine($"Hash header: {hashHeader}");

        using (var md5 = MD5.Create())
        {
            var md5Hash = md5.ComputeHash(content);
            var md5HashBase64 = Convert.ToBase64String(md5Hash);
            Console.WriteLine($"MD5 of content: {md5HashBase64}");
        }
    }
}

.NET Core project file:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <LangVersion>7.1</LangVersion>
  </PropertyGroup>
</Project>

Output:

Content: hello world
Hash header: crc32c=T1s5RQ==,md5=xhF4M6pNFRDQnvaRRNVnkA==
MD5 of content: XrY7u+Ae7tCTyyK7j1rNww==

As you can see, the MD5 of the content isn't the same as the MD5
part of the X-Goog-Hash header. (In my client library I'm using the crc32c
hash, but that shows the same behavior.)

This isn't a bug in HttpClientHandler - it's expected, but a pain
when I want to validate the hash. Basically, I need to at the
content before and after decompression. And I can't find any way
of doing that.

To clarify my requirements somewhat, I know how to prevent the decompression in HttpClient and instead decompress afterwards when reading from the stream - but I need to be able to do this without changing any the code that uses the resulting HttpResponseMessage from the HttpClient. (There's a lot of code that deals with responses, and I want to only make the change in one central place.)

I have a plan, which I've prototyped and which works as far as I've
found so far, but is a bit ugly. It involves creating a three-layer
handler:

HttpClientHandler with automatic decompression disabled.

A new handler which replaces the content stream with a new Stream subclass
which delegates to the original content stream, but hashes the data as it's read.

A decompression-only handler, based on the Microsoft DecompressionHandler code.

While this works, it has disadvantages of:

Open source licensing: checking exactly what I need to do in order
to create a new file in my repo based on the MIT-licensed
Microsoft code

Effectively forking the MS code, which means I should probably
make a regular check to see if any bugs have been found in it

The Microsoft code uses internal members of the assembly, so it
doesn't port as cleanly as it might.

If Microsoft made DecompressionHandler public, that would help a
lot - but that's likely to be in a longer timeframe than I need.

What I'm looking for is an alternative approach if possible -
something I've missed that lets me get at the content before
decompression. I don't want to reinvent HttpClient - the response
is often chunked for example, and I don't want to have to get into
that side of things. It's a pretty specific interception point that
I'm looking for.

Body:
I managed to get the headerhash correct by:

creating a custom handler that inherits HttpClientHandler

overriding SendAsync

read as byte the response using base.SendAsync

Compress it using GZipStream

Hashing the Gzip Md5 to base64 (using your code)

this issue is, as you said "before decompression" is not really respected here

The idea is to get this if working as you would like
https://github.com/dotnet/corefx/blob/master/src/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseParser.cs#L80-L91

it matches

class Program
{
    const string url = "https://www.googleapis.com/download/storage/v1/b/storage-library-test-bucket/o/gzipped-text.txt?alt=media";

    static async Task Main()
    {
        //await HashResponseContent(CreateHandler(DecompressionMethods.None));
        //await HashResponseContent(CreateHandler(DecompressionMethods.GZip));
        await HashResponseContent(new MyHandler());

        Console.ReadLine();
    }

    private static HttpClientHandler CreateHandler(DecompressionMethods decompressionMethods)
    {
        return new HttpClientHandler { AutomaticDecompression = decompressionMethods };
    }

    public static async Task HashResponseContent(HttpClientHandler handler)
    {
        //Console.WriteLine($"Using AutomaticDecompression : '{handler.AutomaticDecompression}'");
        //Console.WriteLine($"Using SupportsAutomaticDecompression : '{handler.SupportsAutomaticDecompression}'");
        //Console.WriteLine($"Using Properties : '{string.Join('\n', handler.Properties.Keys.ToArray())}'");

        var client = new HttpClient(handler);

        var response = await client.GetAsync(url);
        byte[] content = await response.Content.ReadAsByteArrayAsync();
        string text = Encoding.UTF8.GetString(content);
        Console.WriteLine($"Content: {text}");

        var hashHeader = response.Headers.GetValues("X-Goog-Hash").FirstOrDefault();
        Console.WriteLine($"Hash header: {hashHeader}");
        byteArrayToMd5(content);

        Console.WriteLine($"=====================================================================");
    }

    public static string byteArrayToMd5(byte[] content)
    {
        using (var md5 = MD5.Create())
        {
            var md5Hash = md5.ComputeHash(content);
            return Convert.ToBase64String(md5Hash);
        }
    }

    public static byte[] Compress(byte[] contentToGzip)
    {
        using (MemoryStream resultStream = new MemoryStream())
        {
            using (MemoryStream contentStreamToGzip = new MemoryStream(contentToGzip))
            {
                using (GZipStream compressionStream = new GZipStream(resultStream, CompressionMode.Compress))
                {
                    contentStreamToGzip.CopyTo(compressionStream);
                }
            }

            return resultStream.ToArray();
        }
    }
}

public class MyHandler : HttpClientHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var response = await base.SendAsync(request, cancellationToken);
        var responseContent = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

        Program.byteArrayToMd5(responseContent);

        var compressedResponse = Program.Compress(responseContent);
        var compressedResponseMd5 = Program.byteArrayToMd5(compressedResponse);

        Console.WriteLine($"recompressed response to md5 : {compressedResponseMd5}");

        return response;
    }
}