问:
Center text in footer with google doc extension script
Here is my code. The family and size work but it doesn't center.    </p>

```<code>function styleFooter() {
  var body = DocumentApp.getActiveDocument();
  var foot = body.getFooter();
  var style = {};
  style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;
  style[DocumentApp.Attribute.FONT_FAMILY] = 'Helvetica Neue';
  style[DocumentApp.Attribute.FONT_SIZE] = 9;
  foot.setAttributes(style);
}
</code>```

答:
It's because you need to getParagraphs() and iterate each paragraph of the footer. Try this, it worked for me:

```<code>function styleFooter() {
  var body = DocumentApp.getActiveDocument();
  var foot = body.getFooter().getParagraphs(); // gets a list of your footer paragraphs
  var style = {};
  style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;
  style[DocumentApp.Attribute.FONT_FAMILY] = 'Helvetica Neue';
  style[DocumentApp.Attribute.FONT_SIZE] = 9;

  // iterates each of your footer paragraphs
  foot.forEach(function(element) {
    element.setAttributes(style);
  })
}
</code>```

From the Google Docs documentation:

A HorizontalRule can be contained within a ListItem or Paragraph, but cannot itself contain any other element.

Body:
Here is my code. The family and size work but it doesn't center.

function styleFooter() {
  var body = DocumentApp.getActiveDocument();
  var foot = body.getFooter();
  var style = {};
  style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;
  style[DocumentApp.Attribute.FONT_FAMILY] = 'Helvetica Neue';
  style[DocumentApp.Attribute.FONT_SIZE] = 9;
  foot.setAttributes(style);
}

Body:
It's because you need to getParagraphs() and iterate each paragraph of the footer. Try this, it worked for me:

function styleFooter() {
  var body = DocumentApp.getActiveDocument();
  var foot = body.getFooter().getParagraphs(); // gets a list of your footer paragraphs
  var style = {};
  style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;
  style[DocumentApp.Attribute.FONT_FAMILY] = 'Helvetica Neue';
  style[DocumentApp.Attribute.FONT_SIZE] = 9;

  // iterates each of your footer paragraphs
  foot.forEach(function(element) {
    element.setAttributes(style);
  })
}

From the Google Docs documentation:

A HorizontalRule can be contained within a ListItem or Paragraph, but cannot itself contain any other element.


来源: stackexchange

问:
Datatables - Row grouping with checkboxes
I have an array of the following data:

```<code>{"Id":1,"ProgramName":"Adobe Reader XI
(11.0.23)","FileName":"AcroBroker.exe","FileHash":"1bfb99860246e334c00e4427b54afc3e"}
</code>```

I want to use datatables to show a grid of this data grouped by program name with a checkbox on each row(and group name row too !), if user clicks on the checkbox of the group row all of its children will be checked, something like this but with datatables plugin !

http://jsfiddle.net/Suninsky/564RP/12/

答:
I managed to solve this issue by this, I override the startRender of DataTables like this:

```<code> rowGroup: {
                dataSrc: 'ProgramName',
                startRender: function(rows, group) {
                    rows.every(function(rowIdx, tableLoop, rowLoop) {
                        var rowData = this.data();
                        $(this.node()).addClass(group.replace(/[^A-Za-z0-9]/g, ''));
                    });
                    return "<input type='checkbox' class='program-name-checkbox' data-program='" +
                        group.replace(/[^A-Za-z0-9]/g, '') + "'/>" + group + '(' + rows.count() + ')';
                }
            }
</code>```

and by the help of this code I mark the child checkboxes when their parent is clicked:

```<code>   $(document).ajaxComplete(function() {
            $('.program-name-checkbox').on('click',
                function(event) {
                    debugger;
                    var programName = $(this).data('program');
                    var childs = $('tr.' + programName).find("input[type='checkbox']");

                    if (this.checked) {
                        childs.prop('checked', true);
                    } else {
                        childs.prop('checked', false);
                    }
                });
        });
</code>```

Edit: I just found that the checkboxes extension of Datatables does not recognize thoses checkboxes that I have set pragmatically, I somehow need to use this api cells().checkboxes.select(state) for setting the child checkboxes.

ContentLicense: CC BY-SA 3.0

Body:
I have an array of the following data:

{"Id":1,"ProgramName":"Adobe Reader XI
(11.0.23)","FileName":"AcroBroker.exe","FileHash":"1bfb99860246e334c00e4427b54afc3e"}

I want to use datatables to show a grid of this data grouped by program name with a checkbox on each row(and group name row too !), if user clicks on the checkbox of the group row all of its children will be checked, something like this but with datatables plugin !

http://jsfiddle.net/Suninsky/564RP/12/

Body:
I managed to solve this issue by this, I override the startRender of DataTables like this:

 rowGroup: {
                dataSrc: 'ProgramName',
                startRender: function(rows, group) {
                    rows.every(function(rowIdx, tableLoop, rowLoop) {
                        var rowData = this.data();
                        $(this.node()).addClass(group.replace(/[^A-Za-z0-9]/g, ''));
                    });
                    return "<input type='checkbox' class='program-name-checkbox' data-program='" +
                        group.replace(/[^A-Za-z0-9]/g, '') + "'/>" + group + '(' + rows.count() + ')';
                }
            }

and by the help of this code I mark the child checkboxes when their parent is clicked:

   $(document).ajaxComplete(function() {
            $('.program-name-checkbox').on('click',
                function(event) {
                    debugger;
                    var programName = $(this).data('program');
                    var childs = $('tr.' + programName).find("input[type='checkbox']");

                    if (this.checked) {
                        childs.prop('checked', true);
                    } else {
                        childs.prop('checked', false);
                    }
                });
        });

Edit: I just found that the checkboxes extension of Datatables does not recognize thoses checkboxes that I have set pragmatically, I somehow need to use this api cells().checkboxes.select(state) for setting the child checkboxes.


问:
How to display documents from folder?
How can i display word documents, pdf documents in the browser using files from the web folder? So if a user uploads a pdf report and wants to see it in the browser, how can i allow that to happen? Can HTML5 be of use?</p>

答:
From your comment about displaying images, it seems like what you want is to embed the PDF or Word file in the page.  The easiest thing to do is use an iframe, like so:

```<code><iframe src="http://myserver.com/userUploads/foobar.doc" width="500px" height="500px">
</iframe>
</code>```

However, the different widgets for different document types will look substantially different and may not provide all the functionality you would expect (as in this example).  In addition, not all browsers will be configured with a way to display the document inline - some will prompt the user to download the file.

Uploading the documents to something like Scribd will provide a more uniform experience across document types and browsers; however, depending on how important it is for these documents to be private, Scribd may not be a good solution.

ContentLicense: CC BY-SA 2.5

Title: How to display documents from folder?

Body:
From your comment about displaying images, it seems like what you want is to embed the PDF or Word file in the page.  The easiest thing to do is use an iframe, like so:

<iframe src="http://myserver.com/userUploads/foobar.doc" width="500px" height="500px">
</iframe>

However, the different widgets for different document types will look substantially different and may not provide all the functionality you would expect (as in this example).  In addition, not all browsers will be configured with a way to display the document inline - some will prompt the user to download the file.

Uploading the documents to something like Scribd will provide a more uniform experience across document types and browsers; however, depending on how important it is for these documents to be private, Scribd may not be a good solution.


问:
Can I run my command with out lein run?
I currently run a simple cli I wrote by calling: lein run my-cli-command arg --option

How can I call my command without needing to include lein run? This is what i'm after: my-cli-command arg --option

Do I need to convert it to an binary or executable and if so how?

答:
As of Clojure 1.9 there are new CLI tools! See this guide for installation. You can create an executable script like this:

```<code>#!/usr/local/bin/clojure
(println "Hello World! from" *ns*)
(require '[clojure.walk :as walk])
(walk/postwalk-demo {:woo ::yeah})
</code>```

Then make the script executable and execute it:

```<code>$ chmod +x my_script
$ ./my_script
Hello World! from #object[clojure.lang.Namespace 0x1ebea008 user]
Walked: :woo
Walked: :user/yeah
Walked: [:woo :user/yeah]
Walked: {:woo :user/yeah}
</code>```

Start-up time seems improved as well. It takes a little over a second to run a trivial script (just print a string) on a recent MBP:

```<code>time ./hello
Hello World!
./hello  1.51s user 0.12s system 184% cpu 0.887 total
</code>```

Title: Can I run my command with out lein run?

Body:
As of Clojure 1.9 there are new CLI tools! See this guide for installation. You can create an executable script like this:

#!/usr/local/bin/clojure
(println "Hello World! from" *ns*)
(require '[clojure.walk :as walk])
(walk/postwalk-demo {:woo ::yeah})

Then make the script executable and execute it:

$ chmod +x my_script
$ ./my_script
Hello World! from #object[clojure.lang.Namespace 0x1ebea008 user]
Walked: :woo
Walked: :user/yeah
Walked: [:woo :user/yeah]
Walked: {:woo :user/yeah}

Start-up time seems improved as well. It takes a little over a second to run a trivial script (just print a string) on a recent MBP:

time ./hello
Hello World!
./hello  1.51s user 0.12s system 184% cpu 0.887 total


问:
"void value not ignored as it ought to be" - What is wrong?
I created a class "semaphore" with a method "reader" this way:

```<code>void semaforo::reader(sem_t x, sem_t y,sem_t z,sem_t rsem,sem_t wsem){
    cout<<"----------------"<<endl;
    cout<<"Leitor esta Lendo"<<endl;
    sem_wait(&z);
    sem_wait(&rsem);
    sem_wait(&x);
    int aux = readcountM(0);
    if(aux ==1){
        sem_wait(&wsem);
    }
    sem_post(&x);
    sem_post(&rsem);
    sem_post(&z);
    prints(1);
    sem_wait(&x);
    aux = readcountN(aux);
    if(aux == 0){
        sem_post(&wsem);
    }
    sem_post(&x);
}
</code>```

In my main.cpp, I created these auxiliary variables, and instanced my class as follows:

```<code>sem_t x,y,z,rsem,wsem;
pthread_t read[3],write[2];

thread *teste2 = new thread();

// the following line triggers the error
teste2->pthread_creation(&read[0],NULL,(void *)teste->reader(x, y, z, rsem, wsem),NULL);
</code>```

With this I get the following error:

void value not ignored as it ought to be

答:
Your method "reader" returns void.

You use that invalid return value as a parameter to "pthread_creation". Casting void to pointer-to-void (which you seem to try) is not changing anything, not to say it is futile.

You cannot make a value from what a method returns, if it returns void.

That is what the error/warning is telling you.

Body:
I created a class "semaphore" with a method "reader" this way:

void semaforo::reader(sem_t x, sem_t y,sem_t z,sem_t rsem,sem_t wsem){
    cout<<"----------------"<<endl;
    cout<<"Leitor esta Lendo"<<endl;
    sem_wait(&z);
    sem_wait(&rsem);
    sem_wait(&x);
    int aux = readcountM(0);
    if(aux ==1){
        sem_wait(&wsem);
    }
    sem_post(&x);
    sem_post(&rsem);
    sem_post(&z);
    prints(1);
    sem_wait(&x);
    aux = readcountN(aux);
    if(aux == 0){
        sem_post(&wsem);
    }
    sem_post(&x);
}

In my main.cpp, I created these auxiliary variables, and instanced my class as follows:

sem_t x,y,z,rsem,wsem;
pthread_t read[3],write[2];

thread *teste2 = new thread();

// the following line triggers the error
teste2->pthread_creation(&read[0],NULL,(void *)teste->reader(x, y, z, rsem, wsem),NULL);

With this I get the following error:

void value not ignored as it ought to be


问:
Getting the total count of all the documents in buckets
When I'm searching by the following aggregation:

```<code>"aggregations": {
"codes": {
  "terms": {
    "field": "code"
  },
  "aggs": {
    "dates": {
      "date_range": {
        "field": "created_time",
        "ranges": [
          {
            "from": "2017-12-06T00:00:00.000",
            "to": "2017-12-06T16:00:00.000"
          },
          {
            "from": "2017-12-07T00:00:00.000",
            "to": "2017-12-07T23:59:59.999"
          }
        ]
      }
    }
  }
}
}
</code>```

I get the following result:

```<code>"aggregations": {
"codes": {
  "buckets": [
    {
      "key": "123456",
      "doc_count": 104005499,
      "dates": {
        "buckets": [
          {
            "key": "2017-12-05T20:00:00.000Z-2017-12-06T12:00:00.000Z",
            "from_as_string": "2017-12-05T20:00:00.000Z",
            "to_as_string": "2017-12-06T12:00:00.000Z",
            "doc_count": 156643
          },
          {
            "key": "2017-12-06T20:00:00.000Z-2017-12-07T19:59:59.999Z",
            "from_as_string": "2017-12-06T20:00:00.000Z",
            "to_as_string": "2017-12-07T19:59:59.999Z",
            "doc_count": 11874
          }
        ]
      }
    },
    ...
  ]
 }
}
</code>```

So now I have a list of buckets of buckets. I need to have a total count value for each bucket, which is the sum of doc_counts of the buckets inside. For example, the total count for my first bucket should be 156643 + 11874 = 168517.
I've tried using Sub Bucket aggregation, but

```<code> "totalcount": {
      "sum_bucket": {
        "buckets_path": "dates"
      }
    }
</code>```

this is not going to work, because "buckets_path must reference either a number value or a single value numeric metric aggregation, got: org.elasticsearch.search.aggregations.bucket.range.date.InternalDateRange.Bucket". Any ideas how should I do this?

答:
Looks like this is a known problem. There's a discussion on Elastic forum, where I have found a hack to solve it (thanks to Ruslan_Didyk, the author, btw):

```<code>POST my_aggs/my_doc/_search
{
  "size": 0,
  "aggregations": {
    "codes": {
      "terms": {
        "field": "code"
      },
      "aggs": {
        "dates": {
          "date_range": {
            "field": "created_time",
            "ranges": [
              {
                "from": "2017-12-06T00:00:00.000",
                "to": "2017-12-06T16:00:00.000"
              },
              {
                "from": "2017-12-07T00:00:00.000",
                "to": "2017-12-07T23:59:59.999"
              }
            ]
          },
          "aggs": {
            "my_cnt": {
              "value_count": {
                "field": "created_time"
              }
            }
          }
        },
        "totalcount": {
          "stats_bucket": {
            "buckets_path": "dates>my_cnt"
          }
        }
      }
    }
  }
}
</code>```

The reason why you can't make only totalcount is because date_range implicitly creates sub-buckets and pipeline aggregations cannot handle it (I would say it is a bug of Elasticsearch).

So the hack is to add another sub-aggregation to dates: my_cnt that just counts the amount of documents in the bucket. (Note that I used value_count aggregation on created_time field assuming it's present in all documents and has only one value.)

Given the set of documents like this:

```<code>{"code":"1234","created_time":"2017-12-06T01:00:00"}
{"code":"1234","created_time":"2017-12-06T17:00:00"}
{"code":"1234","created_time":"2017-12-07T01:00:00"}
{"code":"1234","created_time":"2017-12-06T02:00:00"}
{"code":"1235","created_time":"2017-12-07T18:00:00"}
{"code":"1234","created_time":"2017-12-07T18:00:00"}
</code>```

The result of the aggregation will be:

```<code>  "aggregations": {
    "codes": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "1234",
          "doc_count": 5,
          "dates": {
            "buckets": [
              {
                "key": "2017-12-06T00:00:00.000Z-2017-12-06T16:00:00.000Z",
                "from": 1512518400000,
                "from_as_string": "2017-12-06T00:00:00.000Z",
                "to": 1512576000000,
                "to_as_string": "2017-12-06T16:00:00.000Z",
                "doc_count": 2,
                "my_cnt": {
                  "value": 2
                }
              },
              {
                "key": "2017-12-07T00:00:00.000Z-2017-12-07T23:59:59.999Z",
                "from": 1512604800000,
                "from_as_string": "2017-12-07T00:00:00.000Z",
                "to": 1512691199999,
                "to_as_string": "2017-12-07T23:59:59.999Z",
                "doc_count": 2,
                "my_cnt": {
                  "value": 2
                }
              }
            ]
          },
          "totalcount": {
            "count": 2,
            "min": 2,
            "max": 2,
            "avg": 2,
            "sum": 4
          }
        },
        {
          "key": "1235",
          "doc_count": 1,
          "dates": {
            "buckets": [
              {
                "key": "2017-12-06T00:00:00.000Z-2017-12-06T16:00:00.000Z",
                "from": 1512518400000,
                "from_as_string": "2017-12-06T00:00:00.000Z",
                "to": 1512576000000,
                "to_as_string": "2017-12-06T16:00:00.000Z",
                "doc_count": 0,
                "my_cnt": {
                  "value": 0
                }
              },
              {
                "key": "2017-12-07T00:00:00.000Z-2017-12-07T23:59:59.999Z",
                "from": 1512604800000,
                "from_as_string": "2017-12-07T00:00:00.000Z",
                "to": 1512691199999,
                "to_as_string": "2017-12-07T23:59:59.999Z",
                "doc_count": 1,
                "my_cnt": {
                  "value": 1
                }
              }
            ]
          },
          "totalcount": {
            "count": 1,
            "min": 1,
            "max": 1,
            "avg": 1,
            "sum": 1
          }
        }
      ]
    }
  }
</code>```

The desired value is under totalcount.sum.

Some considerations

As I already said, this is valid only if the assumption that created_time is always present and is exactly one holds. If in a different situation the field under date_range aggregation would have several values (e.g. update_time to indicate all updates of a document), then sum will no longer be equal to the actual number of the matched documents (if these dates overlap).

In this case you can always go with filter aggregation with a range query inside.

Hope that helps!

Body:
When I'm searching by the following aggregation:

"aggregations": {
"codes": {
  "terms": {
    "field": "code"
  },
  "aggs": {
    "dates": {
      "date_range": {
        "field": "created_time",
        "ranges": [
          {
            "from": "2017-12-06T00:00:00.000",
            "to": "2017-12-06T16:00:00.000"
          },
          {
            "from": "2017-12-07T00:00:00.000",
            "to": "2017-12-07T23:59:59.999"
          }
        ]
      }
    }
  }
}
}

I get the following result:

"aggregations": {
"codes": {
  "buckets": [
    {
      "key": "123456",
      "doc_count": 104005499,
      "dates": {
        "buckets": [
          {
            "key": "2017-12-05T20:00:00.000Z-2017-12-06T12:00:00.000Z",
            "from_as_string": "2017-12-05T20:00:00.000Z",
            "to_as_string": "2017-12-06T12:00:00.000Z",
            "doc_count": 156643
          },
          {
            "key": "2017-12-06T20:00:00.000Z-2017-12-07T19:59:59.999Z",
            "from_as_string": "2017-12-06T20:00:00.000Z",
            "to_as_string": "2017-12-07T19:59:59.999Z",
            "doc_count": 11874
          }
        ]
      }
    },
    ...
  ]
 }
}

So now I have a list of buckets of buckets. I need to have a total count value for each bucket, which is the sum of doc_counts of the buckets inside. For example, the total count for my first bucket should be 156643 + 11874 = 168517.
I've tried using Sub Bucket aggregation, but

 "totalcount": {
      "sum_bucket": {
        "buckets_path": "dates"
      }
    }

this is not going to work, because "buckets_path must reference either a number value or a single value numeric metric aggregation, got: org.elasticsearch.search.aggregations.bucket.range.date.InternalDateRange.Bucket". Any ideas how should I do this?

Body:
Looks like this is a known problem. There's a discussion on Elastic forum, where I have found a hack to solve it (thanks to Ruslan_Didyk, the author, btw):

POST my_aggs/my_doc/_search
{
  "size": 0,
  "aggregations": {
    "codes": {
      "terms": {
        "field": "code"
      },
      "aggs": {
        "dates": {
          "date_range": {
            "field": "created_time",
            "ranges": [
              {
                "from": "2017-12-06T00:00:00.000",
                "to": "2017-12-06T16:00:00.000"
              },
              {
                "from": "2017-12-07T00:00:00.000",
                "to": "2017-12-07T23:59:59.999"
              }
            ]
          },
          "aggs": {
            "my_cnt": {
              "value_count": {
                "field": "created_time"
              }
            }
          }
        },
        "totalcount": {
          "stats_bucket": {
            "buckets_path": "dates>my_cnt"
          }
        }
      }
    }
  }
}

The reason why you can't make only totalcount is because date_range implicitly creates sub-buckets and pipeline aggregations cannot handle it (I would say it is a bug of Elasticsearch).

So the hack is to add another sub-aggregation to dates: my_cnt that just counts the amount of documents in the bucket. (Note that I used value_count aggregation on created_time field assuming it's present in all documents and has only one value.)

Given the set of documents like this:

{"code":"1234","created_time":"2017-12-06T01:00:00"}
{"code":"1234","created_time":"2017-12-06T17:00:00"}
{"code":"1234","created_time":"2017-12-07T01:00:00"}
{"code":"1234","created_time":"2017-12-06T02:00:00"}
{"code":"1235","created_time":"2017-12-07T18:00:00"}
{"code":"1234","created_time":"2017-12-07T18:00:00"}

The result of the aggregation will be:

  "aggregations": {
    "codes": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "1234",
          "doc_count": 5,
          "dates": {
            "buckets": [
              {
                "key": "2017-12-06T00:00:00.000Z-2017-12-06T16:00:00.000Z",
                "from": 1512518400000,
                "from_as_string": "2017-12-06T00:00:00.000Z",
                "to": 1512576000000,
                "to_as_string": "2017-12-06T16:00:00.000Z",
                "doc_count": 2,
                "my_cnt": {
                  "value": 2
                }
              },
              {
                "key": "2017-12-07T00:00:00.000Z-2017-12-07T23:59:59.999Z",
                "from": 1512604800000,
                "from_as_string": "2017-12-07T00:00:00.000Z",
                "to": 1512691199999,
                "to_as_string": "2017-12-07T23:59:59.999Z",
                "doc_count": 2,
                "my_cnt": {
                  "value": 2
                }
              }
            ]
          },
          "totalcount": {
            "count": 2,
            "min": 2,
            "max": 2,
            "avg": 2,
            "sum": 4
          }
        },
        {
          "key": "1235",
          "doc_count": 1,
          "dates": {
            "buckets": [
              {
                "key": "2017-12-06T00:00:00.000Z-2017-12-06T16:00:00.000Z",
                "from": 1512518400000,
                "from_as_string": "2017-12-06T00:00:00.000Z",
                "to": 1512576000000,
                "to_as_string": "2017-12-06T16:00:00.000Z",
                "doc_count": 0,
                "my_cnt": {
                  "value": 0
                }
              },
              {
                "key": "2017-12-07T00:00:00.000Z-2017-12-07T23:59:59.999Z",
                "from": 1512604800000,
                "from_as_string": "2017-12-07T00:00:00.000Z",
                "to": 1512691199999,
                "to_as_string": "2017-12-07T23:59:59.999Z",
                "doc_count": 1,
                "my_cnt": {
                  "value": 1
                }
              }
            ]
          },
          "totalcount": {
            "count": 1,
            "min": 1,
            "max": 1,
            "avg": 1,
            "sum": 1
          }
        }
      ]
    }
  }

The desired value is under totalcount.sum.

Some considerations

As I already said, this is valid only if the assumption that created_time is always present and is exactly one holds. If in a different situation the field under date_range aggregation would have several values (e.g. update_time to indicate all updates of a document), then sum will no longer be equal to the actual number of the matched documents (if these dates overlap).

In this case you can always go with filter aggregation with a range query inside.

Hope that helps!


问:
Distribute UWP App to App Center (aka Mobile Center) using VSTS Task
I'm currently working together with Microsoft on a case where one of your UWP Apps is crashing after start. After a lot of debugging around msbuild I recognized that the crash only occurs when the resulting appxbundle file is distributed over Microsoft App Center (aka Mobile Center). This is also only the case when the appxbundle is uploaded to App Center with the VSTS built in task "App Center distribute".

When I upload the appxbundle manually using the App Center Portal it all works fine, even when consumed through App Center.

Furthermore I noticed that the appxbundle is 18MB in size after build, but is only 14MB in size when uploaded to App Center using the VSTS task (size is shown in App Center Portal). The file is not corrupt after a download but it seems to miss some files in the bundle - what is this task doing? Opening and modifying the appxbundle? uhhhhhh.

Anybody having a similar issue?

答:
I've worked around this issue for the moment by replacing the built-in task with the App Center CLI and a simple powershell script to archive the same.

```<code>param(
    [Parameter(Mandatory=$true)]
    [String]
    $Token,
    # Name of the App, e.g. 'org/app'
    [Parameter(Mandatory=$true)]
    [String]
    $App,
    # Name of the distribution Group, e.g. 'Collaborators'
    [Parameter(Mandatory=$true)]
    [String]
    $Group
)

$binaryFile = (Get-ChildItem MyApp_*_x64.appxbundle -Recurse).FullName
appcenter distribute release -g $Group -f "$binaryFile" -a $App --debug --token $Token
</code>```

To make this script work, you need the latest version of App Center CLI which can be found here.

On a build agent with NPM package manager present, you can simply run npm install -g appcenter-cli to install the latest version. Afterwards the above script should execute.

Body:
I've worked around this issue for the moment by replacing the built-in task with the App Center CLI and a simple powershell script to archive the same.

param(
    [Parameter(Mandatory=$true)]
    [String]
    $Token,
    # Name of the App, e.g. 'org/app'
    [Parameter(Mandatory=$true)]
    [String]
    $App,
    # Name of the distribution Group, e.g. 'Collaborators'
    [Parameter(Mandatory=$true)]
    [String]
    $Group
)

$binaryFile = (Get-ChildItem MyApp_*_x64.appxbundle -Recurse).FullName
appcenter distribute release -g $Group -f "$binaryFile" -a $App --debug --token $Token

To make this script work, you need the latest version of App Center CLI which can be found here.

On a build agent with NPM package manager present, you can simply run npm install -g appcenter-cli to install the latest version. Afterwards the above script should execute.

ContentLicense: CC BY-SA 4.0


问:
groupby sub ranges of ranges - pandas
I am trying to do a quite complex groupby operation with pandas.
Consider two data frames:

```<code>df1:
begin, end, y
0, 3, string10
3, 7, string11

df2:
begin, end, x
0, 2, string1
1, 2, string2
3, 4, string3
4, 6, string4
</code>```

This two DF represents time slots with some properties. DF1 contains large time slots and its borders will always be bigger than DF2.
Also each begin end in DF2 will always be contained or equal to one of the time slots in DF1.

What I need to do is to group DF2 according to DF1 slots keeping their properties:

```<code>result:
index, slot, begin_df2, end_df2, x, y
0, (0,3), 0, 2, string1, string10
 , (0,3), 1, 2, string2, string10
1, (3,6), 3, 4, string3, string11
 , (3,6), 4, 6, string4, string11
</code>```

I can't find a reasonable flow at pandas API for this I tried to check:
Pandas Groupby Range of Values

But it is more for grouping single values in a range.

答:
If your interval do not have intersection with each other in df1 </p>

```<code>df1['key']=df1.iloc[:,:1].mean(1)
df2['key']=df2.iloc[:,:1].mean(1)
df=pd.merge_asof(df2,df1,on='key')
df
Out[401]:
   begin_x   end_x         x  key  begin_y   end_y          y
0        0       2   string1  0.0        0       3   string10
1        1       2   string2  1.0        0       3   string10
2        3       4   string3  3.0        3       7   string11
3        4       6   string4  4.0        3       7   string11
</code>```

Title: groupby sub ranges of ranges - pandas

Body:
I am trying to do a quite complex groupby operation with pandas.
Consider two data frames:

df1:
begin, end, y
0, 3, string10
3, 7, string11

df2:
begin, end, x
0, 2, string1
1, 2, string2
3, 4, string3
4, 6, string4

This two DF represents time slots with some properties. DF1 contains large time slots and its borders will always be bigger than DF2.
Also each begin end in DF2 will always be contained or equal to one of the time slots in DF1.

What I need to do is to group DF2 according to DF1 slots keeping their properties:

result:
index, slot, begin_df2, end_df2, x, y
0, (0,3), 0, 2, string1, string10
 , (0,3), 1, 2, string2, string10
1, (3,6), 3, 4, string3, string11
 , (3,6), 4, 6, string4, string11

I can't find a reasonable flow at pandas API for this I tried to check:
Pandas Groupby Range of Values

But it is more for grouping single values in a range.

Body:
If your interval do not have intersection with each other in df1

df1['key']=df1.iloc[:,:1].mean(1)
df2['key']=df2.iloc[:,:1].mean(1)
df=pd.merge_asof(df2,df1,on='key')
df
Out[401]:
   begin_x   end_x         x  key  begin_y   end_y          y
0        0       2   string1  0.0        0       3   string10
1        1       2   string2  1.0        0       3   string10
2        3       4   string3  3.0        3       7   string11
3        4       6   string4  4.0        3       7   string11


问:
What is the result of adding an Object and an Array in javascript?
I tried this code in the address bar:

javascript: alert({} + [])

The result is: [object Object].

javascript: alert(typeof ({} + []))

The result is: string.

Can somebody explain to me what's going on?

答:
Basically the toString method will be invoked. You can actually override the default behavior by writing a toString method that returns a number.

```<code>var obj1 = {
        toString: function () {
            return 1;
        }
    },
    obj2 = {
        toString: function () {
            return 2;
        }
};
alert(typeof (obj1 + obj2));
</code>```

Body:
Basically the toString method will be invoked. You can actually override the default behavior by writing a toString method that returns a number.

var obj1 = {
        toString: function () {
            return 1;
        }
    },
    obj2 = {
        toString: function () {
            return 2;
        }
};
alert(typeof (obj1 + obj2));


问:
How do I retrieve a viewmodel from another viewmodel?
I have this ViewModel which incorporates 3 other viewmodels and a list:

```<code>public class GroupPageViewModel{
    public string GroupName { get; set; }
    public GroupSelectViewModel _groupSelectVM {get; set;}
    public List<User> _users { get; set; }
    public ViewModelStudent _studentVM { get; set; }
    public ViewModelGroupMembers _groupMembersVM { get; set; }
}
</code>```

In the view I can access each of these sub-ViewModels by Model._groupSelectVM, each of the sub-ViewModels are associated with a partial view. The problem arises when I need to refresh just one or two partial views, I'm not sure how to access the inner ViewModels returned in an Ajax success, and as I'm relatively new to MVC and asp.net in general. And I literally know next to nothing about JavaScript, jquery or Ajax.

How would I go about getting a specific ViewModel from the main ViewModel in an Ajax success?

This is just one example for the clarification requested all the others are pretty much the same (although some of them might need to update mutliple partial views -

From the controller:

```<code>[HttpPost]
public ActionResult Index(string groupChoice = "0", string newGroup = "")
    {
        string groupName = "";

        if (groupChoice == "0" && newGroup != "")
        {
            if (ModelState.IsValid)
            {
                Group group = new Group
                {
                    GroupName = newGroup,
                    Active = true
                };

                db.Groups.Add(group);
                db.SaveChanges();
                PopulateLists();
            }
        }
        else if (groupList == null)
        {
            groupList = (List<SelectListItem>)Session["groupList"];
            Session["groupName"] = groupName = groupList.Where(m => m.Value == groupChoice).FirstOrDefault().Text;
            MembersInSpecificGroup(groupName, groupMembers, groupMembersList);
            groupPageVM._groupMembersVM = groupMembers;
        }

        return View("GroupSelection", groupPageVM);
    }
</code>```

The script:

```<code>$(document).ready(function () {
        $('#selectedGroup').change(function () {
            var data = {
                groupChoice: $('#selectedGroup').val()
            };

            var groupChoice = $('#selectedGroup').val();
            $.ajax({
                url: '/Group/Index/',
                type: 'POST',
                data: { groupChoice: groupChoice },
                success: function (data) {
                    setTimeout(function () {
                        delayGroupSuccess(data);
                    }, delay);

                }
            });
        })
    });
    function delayGroupSuccess(data) {
        $("#groupSelect").html(data);
    }
</code>```

The main page:

@model EMBAProgram.ViewModels.GroupPageViewModel
@{ Layout = "~/Views/Shared/_Layout.cshtml"; }

Group Selection

  @{ Html.RenderPartial("_GroupSelect", Model._groupSelectVM);}

    @{Html.RenderPartial("_Students", Model._studentVM);}

    @{ Html.RenderPartial("_GroupMembers", Model._groupMembersVM);}

    @{ Html.RenderPartial("_Users", Model._users);}

```
</div>
</div>
</p>

<p>The partial view:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>@model EMBAProgram.ViewModels.ViewModelGroupMembers

<div class="table-responsive" id="groupResults">
  <table class="table table-condensed table-responsive">
    <thead>
      <tr>
        <th>@Html.DisplayName("M-Number")</th>
        <th>@Html.DisplayName("Name")</th>
        <th>@Html.DisplayName("Student")</th>
      </tr>
    </thead>
    <tbody>
      @foreach (var item in Model._groupVM) {
      <tr>
        <td>@Html.DisplayFor(m => item.MNumber)</td>
        <td>@Html.DisplayFor(m => item.Name)</td>
        <td>@Html.DisplayFor(m => item.Student)</td>
      </tr>
      }
    </tbody>
  </table>
</div></code>```

Basically I need to be able pull the ViewModel for the partial view from the main ViewModel (which I believe is what is being returned in the Ajax,) and refresh the partial view.

答:
I removed the original answer, it's available in the edit log if folks want to see it I think. But it was taking up too much space and was incorrect.

You can return multiple partial views, I thought it was a built in way to get them to a string (I was in a rush in my comment), but I've got a working example.

In the controller I have the following:

```<code>public ActionResult Index()
{
    var model = new TestViewModel
    {
        Students = GetStudents(),
        Categories = GetCategories(),
        Groups = GetGroups()
    };

    return View("Index", model);
}

// Returns multiple partial views as strings.
public ActionResult StudentsAndGroups()
{
    return Json(new
    {
        Students = RenderRazorViewToString("_Students", GetStudents()),
        Groups = RenderRazorViewToString("_Groups", GetGroups())
    }, JsonRequestBehavior.AllowGet);
}

// Creates a string from a Partial View render.
private string RenderRazorViewToString(string viewName, object model)
{

    ControllerContext.Controller.ViewData.Model = model;

    using (var stringWriter = new StringWriter())
    {
        var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        var viewContext = new ViewContext(ControllerContext, viewResult.View, ControllerContext.Controller.ViewData, ControllerContext.Controller.TempData, stringWriter);
        viewResult.View.Render(viewContext, stringWriter);
        viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
        return stringWriter.GetStringBuilder().ToString();
    }
}
</code>```

I have my main index view that looks like the following:

```<code><button class="refresh">Refresh</button>

<div class="row">
    <div class="col-md-4 students">
        @{
            Html.RenderPartial("_Students", Model.Students);
        }
    </div>

    <div class="col-md-4">
        @{
            Html.RenderPartial("_Category", Model.Categories);
        }
    </div>

    <div class="col-md-4 groups">
        @{
            Html.RenderPartial("_Groups", Model.Groups);
        }
    </div>
</div>

@section scripts
{
    <script type="text/javascript">
        $(".refresh").click(function () {
            $.get("/Home/StudentsAndGroups", function (d) {
                $(".students").html(d.Students);
                $(".groups").html(d.Groups);
            })
        });
    </script>
}
</code>```

The controller action StudentsAndGroups turns two partial views into strings. From there, the javascript calls that view and accesses the elements and returns them.

Helper method for rendering a view as a string was found here: https://stackoverflow.com/a/34968687/6509508

Body:
I have this ViewModel which incorporates 3 other viewmodels and a list:

public class GroupPageViewModel{
    public string GroupName { get; set; }
    public GroupSelectViewModel _groupSelectVM {get; set;}
    public List<User> _users { get; set; }
    public ViewModelStudent _studentVM { get; set; }
    public ViewModelGroupMembers _groupMembersVM { get; set; }
}

In the view I can access each of these sub-ViewModels by Model._groupSelectVM, each of the sub-ViewModels are associated with a partial view. The problem arises when I need to refresh just one or two partial views, I'm not sure how to access the inner ViewModels returned in an Ajax success, and as I'm relatively new to MVC and asp.net in general. And I literally know next to nothing about JavaScript, jquery or Ajax.

How would I go about getting a specific ViewModel from the main ViewModel in an Ajax success?

This is just one example for the clarification requested all the others are pretty much the same (although some of them might need to update mutliple partial views -

From the controller:

[HttpPost]
public ActionResult Index(string groupChoice = "0", string newGroup = "")
    {
        string groupName = "";

        if (groupChoice == "0" && newGroup != "")
        {
            if (ModelState.IsValid)
            {
                Group group = new Group
                {
                    GroupName = newGroup,
                    Active = true
                };

                db.Groups.Add(group);
                db.SaveChanges();
                PopulateLists();
            }
        }
        else if (groupList == null)
        {
            groupList = (List<SelectListItem>)Session["groupList"];
            Session["groupName"] = groupName = groupList.Where(m => m.Value == groupChoice).FirstOrDefault().Text;
            MembersInSpecificGroup(groupName, groupMembers, groupMembersList);
            groupPageVM._groupMembersVM = groupMembers;
        }

        return View("GroupSelection", groupPageVM);
    }

The script:

$(document).ready(function () {
        $('#selectedGroup').change(function () {
            var data = {
                groupChoice: $('#selectedGroup').val()
            };

            var groupChoice = $('#selectedGroup').val();
            $.ajax({
                url: '/Group/Index/',
                type: 'POST',
                data: { groupChoice: groupChoice },
                success: function (data) {
                    setTimeout(function () {
                        delayGroupSuccess(data);
                    }, delay);

                }
            });
        })
    });
    function delayGroupSuccess(data) {
        $("#groupSelect").html(data);
    }

The main page:

@model EMBAProgram.ViewModels.GroupPageViewModel
@{ Layout = "~/Views/Shared/_Layout.cshtml"; }

Group Selection

  @{ Html.RenderPartial("_GroupSelect", Model._groupSelectVM);}

    @{Html.RenderPartial("_Students", Model._studentVM);}

    @{ Html.RenderPartial("_GroupMembers", Model._groupMembersVM);}

    @{ Html.RenderPartial("_Users", Model._users);}

The partial view:

@model EMBAProgram.ViewModels.ViewModelGroupMembers

        @Html.DisplayName("M-Number")
        @Html.DisplayName("Name")
        @Html.DisplayName("Student")

      @foreach (var item in Model._groupVM) {

        @Html.DisplayFor(m => item.MNumber)
        @Html.DisplayFor(m => item.Name)
        @Html.DisplayFor(m => item.Student)

      }

Basically I need to be able pull the ViewModel for the partial view from the main ViewModel (which I believe is what is being returned in the Ajax,) and refresh the partial view.

Body:
I removed the original answer, it's available in the edit log if folks want to see it I think. But it was taking up too much space and was incorrect.

You can return multiple partial views, I thought it was a built in way to get them to a string (I was in a rush in my comment), but I've got a working example.

In the controller I have the following:

public ActionResult Index()
{
    var model = new TestViewModel
    {
        Students = GetStudents(),
        Categories = GetCategories(),
        Groups = GetGroups()
    };

    return View("Index", model);
}

// Returns multiple partial views as strings.
public ActionResult StudentsAndGroups()
{
    return Json(new
    {
        Students = RenderRazorViewToString("_Students", GetStudents()),
        Groups = RenderRazorViewToString("_Groups", GetGroups())
    }, JsonRequestBehavior.AllowGet);
}

// Creates a string from a Partial View render.
private string RenderRazorViewToString(string viewName, object model)
{

    ControllerContext.Controller.ViewData.Model = model;

    using (var stringWriter = new StringWriter())
    {
        var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        var viewContext = new ViewContext(ControllerContext, viewResult.View, ControllerContext.Controller.ViewData, ControllerContext.Controller.TempData, stringWriter);
        viewResult.View.Render(viewContext, stringWriter);
        viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
        return stringWriter.GetStringBuilder().ToString();
    }
}

I have my main index view that looks like the following:

<button class="refresh">Refresh</button>

<div class="row">
    <div class="col-md-4 students">
        @{
            Html.RenderPartial("_Students", Model.Students);
        }
    </div>

    <div class="col-md-4">
        @{
            Html.RenderPartial("_Category", Model.Categories);
        }
    </div>

    <div class="col-md-4 groups">
        @{
            Html.RenderPartial("_Groups", Model.Groups);
        }
    </div>
</div>

@section scripts
{
    <script type="text/javascript">
        $(".refresh").click(function () {
            $.get("/Home/StudentsAndGroups", function (d) {
                $(".students").html(d.Students);
                $(".groups").html(d.Groups);
            })
        });
    </script>
}

The controller action StudentsAndGroups turns two partial views into strings. From there, the javascript calls that view and accesses the elements and returns them.

Helper method for rendering a view as a string was found here: https://stackoverflow.com/a/34968687/6509508


问:
How many users are connected to my Shiny application?
I work on a Shiny application with shinydashboard and somewhere in the app I want to show a notification telling the user how many other users are connected to the application at the same time.

I came up with a first piece of code that seems to work:

```<code>library(shiny)
ui=fluidPage(uiOutput("text"))
number.users <- 0 # global variable
server= function(input, output, session){
     already.counted = FALSE
     autoInvalidate = reactiveTimer(2000)
     observe({
          if (!already.counted) {
               already.counted <- TRUE
               number.users <<- number.users + 1
          }
     })
     output$text = renderUI({
          autoInvalidate()
          h1(paste0("There are ", number.users, " user(s) connected to this app"))
          })
     onSessionEnded(function(){number.users <<- number.users - 1})
}
</code>```

However it's not very "clean" and I'm afraid that my call to observe and the invalidate every 2 secs are adding some useless computing time to my (already heavy) app. I was wondering if there was some kind of function in shiny that triggers an event at the start of each new session, something like onsessionstart()  that I could use directly to increment the global variable number.users, and a way to notify other sessions that a new session has been opened? Or is there any simpler way to go?

Thanks

答:
The root server function is called once for every new session, and effectively serves as the "onSessionStart" callback. I think what you're doing is fine, except the observe isn't really necessary.

To share global state between sessions in a more reactive manner, you can initialize a reactiveVal or reactiveValues object in global scope (outside of a reactive context), and then take a reactive dependency on it within each session. Any updates to these reactive values will immediately propagate to all other sessions.

```<code>library(shiny)

users = reactiveValues(count = 0)

ui = fluidPage(uiOutput("text"))

server = function(input, output, session) {
  onSessionStart = isolate({
    users$count = users$count + 1
  })

  onSessionEnded(function() {
    isolate({
      users$count = users$count - 1
    })
  })

  output$text = renderUI({
    h1(paste0("There are ", users$count, " user(s) connected to this app"))
  })
}

shinyApp(ui, server)
</code>```

Btw, a more complex example of inter-session communication, though maybe a bit old now, is the Shiny chat room app - http://shiny.rstudio.com/gallery/chat-room.html

Body:
I work on a Shiny application with shinydashboard and somewhere in the app I want to show a notification telling the user how many other users are connected to the application at the same time.

I came up with a first piece of code that seems to work:

library(shiny)
ui=fluidPage(uiOutput("text"))
number.users <- 0 # global variable
server= function(input, output, session){
     already.counted = FALSE
     autoInvalidate = reactiveTimer(2000)
     observe({
          if (!already.counted) {
               already.counted <- TRUE
               number.users <<- number.users + 1
          }
     })
     output$text = renderUI({
          autoInvalidate()
          h1(paste0("There are ", number.users, " user(s) connected to this app"))
          })
     onSessionEnded(function(){number.users <<- number.users - 1})
}

However it's not very "clean" and I'm afraid that my call to observe and the invalidate every 2 secs are adding some useless computing time to my (already heavy) app. I was wondering if there was some kind of function in shiny that triggers an event at the start of each new session, something like onsessionstart()  that I could use directly to increment the global variable number.users, and a way to notify other sessions that a new session has been opened? Or is there any simpler way to go?

Thanks

Body:
The root server function is called once for every new session, and effectively serves as the "onSessionStart" callback. I think what you're doing is fine, except the observe isn't really necessary.

To share global state between sessions in a more reactive manner, you can initialize a reactiveVal or reactiveValues object in global scope (outside of a reactive context), and then take a reactive dependency on it within each session. Any updates to these reactive values will immediately propagate to all other sessions.

library(shiny)

users = reactiveValues(count = 0)

ui = fluidPage(uiOutput("text"))

server = function(input, output, session) {
  onSessionStart = isolate({
    users$count = users$count + 1
  })

  onSessionEnded(function() {
    isolate({
      users$count = users$count - 1
    })
  })

  output$text = renderUI({
    h1(paste0("There are ", users$count, " user(s) connected to this app"))
  })
}

shinyApp(ui, server)

Btw, a more complex example of inter-session communication, though maybe a bit old now, is the Shiny chat room app - http://shiny.rstudio.com/gallery/chat-room.html


问:
ffmpeg color, size and amplitude
Trying to get ffmpeg to create an audio waveform while being able to control the image size, color, and amplitude. I have tried this (and many variations) but it just returns unmatched " .

```<code>ffmpeg -i input -filter_complex "aformat=channel_layouts=mono,compand=gain=-3,showwavespic=s=1000x350,color=s=1000x350:color=A072FD” -frames:v 1 output.png
</code>```

Thoughts?

答:
Use

```<code>ffmpeg -i input -filter_complex
        "aformat=channel_layouts=mono,
         compand=gain=-3,
         showwavespic=s=1000x350:colors=A072FD"
       -frames:v 1 output.png
</code>```

Your closing quote is curly which doesn't match the opening straight quote. Besides that, by putting a , after s=1000x350, you prematurely terminated the arguments for showwavespic.

Title: ffmpeg color, size and amplitude

Body:
Trying to get ffmpeg to create an audio waveform while being able to control the image size, color, and amplitude. I have tried this (and many variations) but it just returns unmatched " .

ffmpeg -i input -filter_complex "aformat=channel_layouts=mono,compand=gain=-3,showwavespic=s=1000x350,color=s=1000x350:color=A072FD” -frames:v 1 output.png

Thoughts?

Body:
Use

ffmpeg -i input -filter_complex
        "aformat=channel_layouts=mono,
         compand=gain=-3,
         showwavespic=s=1000x350:colors=A072FD"
       -frames:v 1 output.png

Your closing quote is curly which doesn't match the opening straight quote. Besides that, by putting a , after s=1000x350, you prematurely terminated the arguments for showwavespic.


问:
Sample image with CMYK channels and HSI channels?
I am learning OpenCV and would like to find any sample images which has CMYK channels and HSI channels. Thanks for providing.</p>

答:
http://www.rgb2cmyk.org helps you convert any RGB color space images to CMYK color space. It is very difficult to get CMYK images directly becuase JPEG does not support CMYK space, but JPEG2000 supports it, which market has not moved into yet.

Another way of doing it is to read a RGB image and convert to HSI. The transformation from RGB to HSI is called CV_RGB2HLS in OpenCV.


问:
Failed to get FirebaseDatabase instance. Specify DatabaseURL within FirebaseApp
FirebaseApp throws an exception when invoke FirebaseDatabase.getInstance().

Error message

Failed to get FirebaseDatabase instance: Specify DatabaseURL within
FirebaseApp or from your getInstance() call.

Firebase project configured correctly. Authentication works without issue, but cannot connect to firebase.

Here is my app level gradle.build file

build.gradle

```<code>dependencies {
    .....

    //Firebase database
    implementation 'com.google.firebase:firebase-database:11.6.2'
    // Firebase Invitation
    implementation 'com.google.firebase:firebase-invites:11.6.2'
    // Firebase Authentication
    implementation 'com.google.firebase:firebase-auth:11.6.2'
    // Google Sign In SDK (only required for Google Sign In)
    implementation 'com.google.android.gms:play-services-auth:11.6.2'

    // people api request libraries
    implementation 'com.google.api-client:google-api-client:1.22.0'
    implementation 'com.google.api-client:google-api-client-android:1.22.0'
    implementation 'com.google.apis:google-api-services-people:v1-rev4-1.22.0'
    compile project(':customsupport')
}

apply plugin: 'com.google.gms.google-services'
</code>```

And project level build.gradle file

```<code>buildscript {
    repositories {
        jcenter()
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.android.tools.build:gradle:3.0.1'
        classpath 'com.google.gms:google-services:3.1.2'

        // We recommend changing it to the latest version from our changelog:
        // https://docs.fabric.io/android/changelog.html#fabric-gradle-plugin
        classpath 'io.fabric.tools:gradle:1.24.4'
    }
}
</code>```

An DatabaseException will occur in FirebaseDatabase.class

```<code>public static synchronized FirebaseDatabase getInstance(FirebaseApp var0, String var1) {
        if(TextUtils.isEmpty(var1)) {
            throw new DatabaseException("Failed to get FirebaseDatabase instance: Specify DatabaseURL within FirebaseApp or from your getInstance() call.");
        } else {
...
}
</code>```

答:
You can go to the Firebase console:
 1-Select your project. 2-From "Realtime Database" tap on the left menu go to the "Data" tab and here you can easily access  the database URL needed which you can find it at the first line,then please use the following line of code:

DatabaseRefernce mdatabaseref=FirebaseDatabase.getInstance().getReferenceFromUrl(url);.

and you are all set.
 for example you can find the URL in this picture underlined by red

Please have a look on this:
Assign a firebase database url(String) to a Database Reference variable?

Body:
FirebaseApp throws an exception when invoke FirebaseDatabase.getInstance().

Error message

Failed to get FirebaseDatabase instance: Specify DatabaseURL within
FirebaseApp or from your getInstance() call.

Firebase project configured correctly. Authentication works without issue, but cannot connect to firebase.

Here is my app level gradle.build file

build.gradle

dependencies {
    .....

    //Firebase database
    implementation 'com.google.firebase:firebase-database:11.6.2'
    // Firebase Invitation
    implementation 'com.google.firebase:firebase-invites:11.6.2'
    // Firebase Authentication
    implementation 'com.google.firebase:firebase-auth:11.6.2'
    // Google Sign In SDK (only required for Google Sign In)
    implementation 'com.google.android.gms:play-services-auth:11.6.2'

    // people api request libraries
    implementation 'com.google.api-client:google-api-client:1.22.0'
    implementation 'com.google.api-client:google-api-client-android:1.22.0'
    implementation 'com.google.apis:google-api-services-people:v1-rev4-1.22.0'
    compile project(':customsupport')
}

apply plugin: 'com.google.gms.google-services'

And project level build.gradle file

buildscript {
    repositories {
        jcenter()
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.android.tools.build:gradle:3.0.1'
        classpath 'com.google.gms:google-services:3.1.2'

        // We recommend changing it to the latest version from our changelog:
        // https://docs.fabric.io/android/changelog.html#fabric-gradle-plugin
        classpath 'io.fabric.tools:gradle:1.24.4'
    }
}

An DatabaseException will occur in FirebaseDatabase.class

public static synchronized FirebaseDatabase getInstance(FirebaseApp var0, String var1) {
        if(TextUtils.isEmpty(var1)) {
            throw new DatabaseException("Failed to get FirebaseDatabase instance: Specify DatabaseURL within FirebaseApp or from your getInstance() call.");
        } else {
...
}


问:
Call array variable inside of array in php
I want to call array variable inside the current array. Something like this:

```<code>$conv= array (
"hello" => array("Hello", "Hi", "Hello, how are you?"),
"helo" => array_merge($conv['hello'])
);
print_r($conv['helo']);
</code>```

How can I do this.
thanks.

答:
If you want to define your function directly when you create the array, then you need to declare helo value as anonymous function, refer current array as global variable and return something you need

```<code>$conv = array(
"hello" => array("Hello", "Hi", "Hello, how are you?"),
"helo" => function() {
        global $conv;
        return array_merge($conv['hello'], array("Bye", "See you"));
    }
);
print_r($conv['helo']());
</code>```

Note that when you need the value returned from that function you need to call it as a function like above $conv['helo']() while calling just $conv['helo'] will return a Closure object.

UPDATE

According to what you're asking in comments, it seems that you just want to get a copy of hello value through a function

```<code>$conv = array(
"hello" => array("Hello", "Hi", "Hello, how are you?"),
"helo" => function() {
        global $conv;
        return $conv["hello"];
    }
);
print_r($conv['helo']());
</code>```

Body:
I want to call array variable inside the current array. Something like this:

$conv= array (
"hello" => array("Hello", "Hi", "Hello, how are you?"),
"helo" => array_merge($conv['hello'])
);
print_r($conv['helo']);

How can I do this.
thanks.

Body:
If you want to define your function directly when you create the array, then you need to declare helo value as anonymous function, refer current array as global variable and return something you need

$conv = array(
"hello" => array("Hello", "Hi", "Hello, how are you?"),
"helo" => function() {
        global $conv;
        return array_merge($conv['hello'], array("Bye", "See you"));
    }
);
print_r($conv['helo']());

Note that when you need the value returned from that function you need to call it as a function like above $conv['helo']() while calling just $conv['helo'] will return a Closure object.

UPDATE

According to what you're asking in comments, it seems that you just want to get a copy of hello value through a function

$conv = array(
"hello" => array("Hello", "Hi", "Hello, how are you?"),
"helo" => function() {
        global $conv;
        return $conv["hello"];
    }
);
print_r($conv['helo']());


问:
Java: String not printed
I am reading some data from a file and each line is assigned to one cell of the String array. For some reason when I try to print the array after reading the file(lines 8-10), I get nothing printed. When I print the line in the While loop(line 5) I get the line printed correctly.

```<code>    1: int count = 0;
    2: String[] s = new String[300];

    3: while(!StdIn.isEmpty()) {
    4:  s[count]=StdIn.readLine();
    5:  System.out.println(s[count]);
    6:  count++;
    7: }

    8:  for(int i=0;i<count;i++) {
    9:   System.out.println(s[i]);
   10: }
</code>```

Same code using Scanner:

```<code>    Scanner in = new Scanner(System.in);

    int count = 0;
    String[] s = new String[300];

    while(in.hasNextLine()) {
        s[count]=in.nextLine();
        System.out.println(s[count]);
        count++;
    }
    for(int i=0;i<count;i++) {
        System.out.println(s[i]);
    }
</code>```

I can't figure out what's wrong with my code.

Thanks in advance.

EDIT: When the last line has been read, the in.hasNextLine() is not returning anything. It got stuck at the count++. See photo -> DEBUGGER

答: This will only work with a file but when using System.in here the in.hasNextLine() never gives false. You need to provide it with a condition to break the while loop.

Title: Java: String not printed

Body:
I am reading some data from a file and each line is assigned to one cell of the String array. For some reason when I try to print the array after reading the file(lines 8-10), I get nothing printed. When I print the line in the While loop(line 5) I get the line printed correctly.

    1: int count = 0;
    2: String[] s = new String[300];

    3: while(!StdIn.isEmpty()) {
    4:  s[count]=StdIn.readLine();
    5:  System.out.println(s[count]);
    6:  count++;
    7: }

    8:  for(int i=0;i<count;i++) {
    9:   System.out.println(s[i]);
   10: }

Same code using Scanner:

    Scanner in = new Scanner(System.in);

    int count = 0;
    String[] s = new String[300];

    while(in.hasNextLine()) {
        s[count]=in.nextLine();
        System.out.println(s[count]);
        count++;
    }
    for(int i=0;i<count;i++) {
        System.out.println(s[i]);
    }

I can't figure out what's wrong with my code.

Thanks in advance.

EDIT: When the last line has been read, the in.hasNextLine() is not returning anything. It got stuck at the count++. See photo -> DEBUGGER


问:
Android database (SQLite) returns a non-empty cursor from an empty table
I verified using SQLite Database Browser that the table contains no rows. I stepped through the query builder code to get the generated query and ran the query in SQLite Database Broswer. The query returned zero rows. But still, the cursor returned by Android's SQLiteQueryBuilder.query method returns true on cursor.moveToFirst() call and returns null values.

Anyone seen something like this before?

答:
I think you should do something like:</p>

```<code>if (c.getCount()>0) {
    c.moveToFirst();
</code>```

Body:
I think you should do something like:

if (c.getCount()>0) {
    c.moveToFirst();


问:
How to change image on dynamic checkboxes?
I'm new to JQuery and would really appreciate some help!
I have dynamic checkboxes which has an icon and image on it (checkbox is hidden)...

```<code> plcUserReq.Controls.Add(new LiteralControl("
<div data-toggle='buttons' style='margin-top:-3px'>
  <label class='btn' for='Lines' style='padding:0px 0px 0px 0px; margin:0px 0px 0px 0px'>
     <input type='checkbox' autocomplete='off' name='chkbx' value='" + UID.ToString() + "'id='chk'"+ UID.ToString() + i.ToString() +"/>
           <i class='btn fa fa-plus-square-o' aria-hidden = 'true'>
                 <img src='http://localhost:3162/images/moderator-red.gif'></i></label></div>"));
</code>```

I want the image and icon to change on click....when each checkbox is clicked...

This is the script I'm trying with...

```<code>$("[name='chkbx']").change(function () {
        if ($(this).is(':checked'))
            {
             $(this).next().find('i').attr('class', 'btn fa fa-check-square-o');
             $(this).next().find('img').attr('src', 'http://localhost:3162/images/moderator-red.gif');
            }
        else
        {
            $(this).next().find('i').attr('class', 'btn fa fa-plus-square-o');
            $(this).next().find('img').attr('src', 'http://localhost:3162/images/moderator-blue.gif');
        }
});
</code>```

Nothing happens when any of the checkboxes are clicked...I can't seem to figure what the problem is with my JQuery..
Please help! I'm stuck!

JSFiddle : https://jsfiddle.net/Lgxacm9m/3/

When checked (it should look like this) : https://jsfiddle.net/m278c236/1/

答:
In jQuery, the # is used for identifying elements by a certain id. Your checkbox does not have and id of chkbx, but rather it has a name of chkbx. So:

$("#chkbx").change(function() {

should be:

$("[name='chkbx']").change(function () {

EDIT: If the event still is not firing, it is possible that your event handler attempts to bind before the checkbox element is loaded into the DOM. You can resolve this by ensuring that the the code only executes once the entire page has been rendered. To accomplish this, edit your code as follows:

```<code>$(function() {
   $(document).on("change", "[name='chkbx']", change(function () {
      alert("At least the event is firing...");
      if ($(this).is(':checked'))
        {
          $(this).next().find('i').attr('class', 'btn fa fa-check-square-o');
          $(this).next().find('img').attr('src', 'http://localhost:3162/images/moderator-red.gif');
        }
        else
        {
          $(this).next().find('i').attr('class', 'btn fa fa-plus-square-o');
          $(this).next().find('img').attr('src', 'http://localhost:3162/images/moderator-blue.gif');
        }
   });
});
</code>```

The $(function() { }) is shorthand for $(document).ready()

Body:
I'm new to JQuery and would really appreciate some help!
I have dynamic checkboxes which has an icon and image on it (checkbox is hidden)...

 plcUserReq.Controls.Add(new LiteralControl("

     <input type='checkbox' autocomplete='off' name='chkbx' value='" + UID.ToString() + "'id='chk'"+ UID.ToString() + i.ToString() +"/>

"));

I want the image and icon to change on click....when each checkbox is clicked...

This is the script I'm trying with...

$("[name='chkbx']").change(function () {
        if ($(this).is(':checked'))
            {
             $(this).next().find('i').attr('class', 'btn fa fa-check-square-o');
             $(this).next().find('img').attr('src', 'http://localhost:3162/images/moderator-red.gif');
            }
        else
        {
            $(this).next().find('i').attr('class', 'btn fa fa-plus-square-o');
            $(this).next().find('img').attr('src', 'http://localhost:3162/images/moderator-blue.gif');
        }
});

Nothing happens when any of the checkboxes are clicked...I can't seem to figure what the problem is with my JQuery..
Please help! I'm stuck!

JSFiddle : https://jsfiddle.net/Lgxacm9m/3/

When checked (it should look like this) : https://jsfiddle.net/m278c236/1/

Body:
In jQuery, the # is used for identifying elements by a certain id. Your checkbox does not have and id of chkbx, but rather it has a name of chkbx. So:

$("#chkbx").change(function() {

should be:

$("[name='chkbx']").change(function () {

EDIT: If the event still is not firing, it is possible that your event handler attempts to bind before the checkbox element is loaded into the DOM. You can resolve this by ensuring that the the code only executes once the entire page has been rendered. To accomplish this, edit your code as follows:

$(function() {
   $(document).on("change", "[name='chkbx']", change(function () {
      alert("At least the event is firing...");
      if ($(this).is(':checked'))
        {
          $(this).next().find('i').attr('class', 'btn fa fa-check-square-o');
          $(this).next().find('img').attr('src', 'http://localhost:3162/images/moderator-red.gif');
        }
        else
        {
          $(this).next().find('i').attr('class', 'btn fa fa-plus-square-o');
          $(this).next().find('img').attr('src', 'http://localhost:3162/images/moderator-blue.gif');
        }
   });
});

The $(function() { }) is shorthand for $(document).ready()


问:
How to fix the provisioning profile error in objective c?
After using Automatically manage signing  also its showing the error.

1).WatchSwift Extension requires a provisioning profile. Select a provisioning profile for the "Debug" build configuration in the project editor.

2).Code signing is required for product type 'WatchKit Extension' in SDK 'watchOS 3.2'

答:
Set the automatic provisioning profile for the WatchKit and WatchKit Extension target

Go to Capabilities Tab and select the Appgroups then only you can use the WatchKit as its some dependency requirement.

Go that the AppID on developer portal and link it with AppGroup ID created first in the AppGroup section and then enabling in the APPID liek you enable push.

After this, the profiles will get expired So make sure to regenerate it again in the Profiles or else Xcode will regenerate it for you.

Once you have done all this you may see an APPNAME.entitlement file added to the Xcode project which looks something like thi:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>application-identifier</key>
    <string>TEAMID.com.yourapp.bundleID</string>
    <key>com.apple.security.application-groups</key>
    <array>
        <string>group.yourapp.bundleID</string> . //This is one your created in Apple AooGroup section.
    </array>
    <key>keychain-access-groups</key>
    <array>
        <string>TEAMID.yourkeychaingroups</string> //optional
    </array>
    <key>com.apple.developer.pass-type-identifiers</key>
    <array>
        <string>TEAMID.*</string>
    </array>
    <key>com.apple.developer.siri</key> . //optional
    <true/>
    <key>get-task-allow</key>
    <false/>
</dict>
</plist>
</code>```

Note your details may vary based on your target.

WatchKit Target Entitlement may show this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>application-identifier</key>
    <string>TEAMID.com.yourapp.bundleID.watchkitapp</string>
    <key>keychain-access-groups</key>
    <array>
        <string>TEAMID.com.yourapp.bundleID.watchkitapp</string>
    </array>
</dict>
</plist>
</code>```

WatchKitExtension Target Entitlement may show this:

```<code>   <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.security.application-groups</key>
    <array>
        <string>group.yourapp.bundleID</string>
    </array>
</dict>
</plist>
</code>```

Finally refer the apple doc if still issue exist:https://developer.apple.com/library/content/documentation/IDEs/Conceptual/AppDistributionGuide/ConfiguringYourApp/ConfiguringYourApp.html

Body:
Set the automatic provisioning profile for the WatchKit and WatchKit Extension target

Go to Capabilities Tab and select the Appgroups then only you can use the WatchKit as its some dependency requirement.

Go that the AppID on developer portal and link it with AppGroup ID created first in the AppGroup section and then enabling in the APPID liek you enable push.

After this, the profiles will get expired So make sure to regenerate it again in the Profiles or else Xcode will regenerate it for you.

Once you have done all this you may see an APPNAME.entitlement file added to the Xcode project which looks something like thi:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>application-identifier</key>
    <string>TEAMID.com.yourapp.bundleID</string>
    <key>com.apple.security.application-groups</key>
    <array>
        <string>group.yourapp.bundleID</string> . //This is one your created in Apple AooGroup section.
    </array>
    <key>keychain-access-groups</key>
    <array>
        <string>TEAMID.yourkeychaingroups</string> //optional
    </array>
    <key>com.apple.developer.pass-type-identifiers</key>
    <array>
        <string>TEAMID.*</string>
    </array>
    <key>com.apple.developer.siri</key> . //optional
    <true/>
    <key>get-task-allow</key>
    <false/>
</dict>
</plist>

Note your details may vary based on your target.

WatchKit Target Entitlement may show this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>application-identifier</key>
    <string>TEAMID.com.yourapp.bundleID.watchkitapp</string>
    <key>keychain-access-groups</key>
    <array>
        <string>TEAMID.com.yourapp.bundleID.watchkitapp</string>
    </array>
</dict>
</plist>

WatchKitExtension Target Entitlement may show this:

   <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.security.application-groups</key>
    <array>
        <string>group.yourapp.bundleID</string>
    </array>
</dict>
</plist>

Finally refer the apple doc if still issue exist:https://developer.apple.com/library/content/documentation/IDEs/Conceptual/AppDistributionGuide/ConfiguringYourApp/ConfiguringYourApp.html


问:
StructureMap Generic Ctor Named Instance

Update

I solved this problem with the following code, but it's not the solution I'm looking for. This is still an open bounty for a more generic solution. If we ever have a table that isn't an int or string for the key value we'll have to add to this manually to make it work.

```<code>c.For(typeof(ILogDifferencesCommand<,>)).Use(typeof(LogDifferencesCommand<,>))
                .Ctor<ILogDifferencesLogger<int>>()
                .Named(AppSettingsManager.Get("logDifferences:Target"))
                .Ctor<string>()
                .Named(AppSettingsManager.Get("logDifferences:Target"));
</code>```

Original Question

I have three types of loggers, and I've defined named instances in my container for them:

```<code>c.For(typeof(ILogDifferencesLogger<>))
    .Use(typeof(LogDifferencesAllLogger<>))
    .Named("all");
c.For(typeof(ILogDifferencesLogger<>))
    .Use(typeof(LogDifferencesNLogLogger<>))
    .Named("nlog");
c.For(typeof(ILogDifferencesLogger<>))
    .Use(typeof(LogDifferencesDatabaseLogger<>))
    .Named("database");
</code>```

The LogDifferencesCommand receives an ILogDifferencesLogger<> as its only argument:

```<code>public LogDifferencesCommand(ILogDifferencesLogger<TKey> logDifferencesLogger)
{
    this.logDifferencesLogger = logDifferencesLogger;
}
</code>```

How do I properly configure the ILogDifferencesCommand<> to grab the right named instance based off of an application setting? Right now I've got something like this:

```<code>c.For(typeof(ILogDifferencesCommand<,>))
    .Use(typeof(LogDifferencesCommand<,>));
</code>```

The issue I'm having is I can't pull in the Ctor<> because I can't use unbound generics with that signature, so then I can't use the Named method off the Ctor for that.

For example, I could do something like this, but that wouldn't hit all possible types:

```<code>c.For(typeof(ILogDifferencesCommand<,>)).Use(typeof(LogDifferencesCommand<,>))
    .Ctor<ILogDifferencesLogger<int>>()
    .Named(AppSettingsManager.Get("logDifferences:Target"));
</code>```

But the problem then is I'd have to handle every TKey type the system uses.

Class and Interface Definitions

```<code>public class LogDifferencesCommand<TModel, TKey> : ILogDifferencesCommand<TModel, TKey>
    where TModel : class, IIdModel<TKey>
{
    public LogDifferencesCommand(ILogDifferencesLogger<TKey> logDifferencesLogger)
    {
        this.logDifferencesLogger = logDifferencesLogger;
    }
}

public interface ILogDifferencesCommand<TModel, TKey>
    where TModel : class, IIdModel<TKey>
{
    List<LogDifference> CalculateDifferences(TModel x, TModel y);

    void LogDifferences(TModel x, TModel y, string tableName, string keyField, string userId, int? clientId);

    void RegisterCustomDisplayNameObserver(WeakReference<ICustomDisplayNameObserver<TModel>> observer);

    void RegisterCustomChangeDateObserver(WeakReference<ICustomChangeDateObserver<TModel>> observer);
}

public interface ILogDifferencesLogger<TKey>
{
    void LogDifferences(string tableName, string keyField, string userId, TKey id, List<LogDifference> differences, int? clientId);
}
</code>```

The reason TKey is required is because of the IIdModel interface.

答:
One option that comes to mind:

```<code>var loggers = new Dictionary<string, ConfiguredInstance>();
loggers.Add("all", c.For(typeof(ILogDifferencesLogger<>))
    .Use(typeof(LogDifferencesAllLogger<>)));
loggers.Add("nlog", c.For(typeof(ILogDifferencesLogger<>))
    .Use(typeof(LogDifferencesNLogLogger<>)));
loggers.Add("database", c.For(typeof(ILogDifferencesLogger<>))
    .Use(typeof(LogDifferencesDatabaseLogger<>)));
foreach (var kv in loggers) {
    // if you still need them named
    // if you only used names for this concrete scenario - you probably don't
    // so can remove it
    kv.Value.Named(kv.Key);
}
c.For(typeof(LogDifferencesCommand<>))
    .Use(typeof(LogDifferencesCommand<>))
    // add explicit instance as dependency
    .Dependencies.Add(typeof(ILogDifferencesLogger<>), loggers[AppSettingsManager.Get("logDifferences:Target")]);
</code>```

Update. As we've figured out in comments, this doesn't work for your specific case when LogDifferencesCommand has multiple type arguments. For some reason (and I think it's a bug) - structure map tries to create closed generic type ILogDifferencesLogger<>, but when doing that - passes generic type arguments from LogDifferencesCommand. Maybe worth firing an issue at their github. You can workaround it like this:

```<code>public class GenericTypesWorkaroundInstance : Instance
{
    private readonly Instance _target;
    private readonly Func<Type[], Type[]> _chooseTypes;
    public GenericTypesWorkaroundInstance(Instance target, Func<Type[], Type[]> chooseTypes) {
        _target = target;
        _chooseTypes = chooseTypes;
        ReturnedType = _target.ReturnedType;
    }

    public override Instance CloseType(Type[] types) {
        // close type correctly by ignoring wrong type arguments
        return _target.CloseType(_chooseTypes(types));
    }

    public override IDependencySource ToDependencySource(Type pluginType) {
        throw new NotSupportedException();
    }

    public override string Description => "Correctly close types over open generic instance";
    public override Type ReturnedType { get; }
}
</code>```

And then doing

```<code>commandReg.Dependencies.Add(
    commandReg.Constructor.GetParameters().First(
        p => p.ParameterType.IsGenericType && p.ParameterType.GetGenericTypeDefinition() == typeof(ILogDifferencesLogger<>)).Name,
        new GenericTypesWorkaroundInstance(
            loggers[AppSettingsManager.Get("logDifferences:Target")],
            // specify which types are correct
            types => types.Skip(1).ToArray()));
</code>```

And it works, but I cannot say that I like it.

Body:
Update

I solved this problem with the following code, but it's not the solution I'm looking for. This is still an open bounty for a more generic solution. If we ever have a table that isn't an int or string for the key value we'll have to add to this manually to make it work.

c.For(typeof(ILogDifferencesCommand<,>)).Use(typeof(LogDifferencesCommand<,>))
                .Ctor<ILogDifferencesLogger<int>>()
                .Named(AppSettingsManager.Get("logDifferences:Target"))
                .Ctor<string>()
                .Named(AppSettingsManager.Get("logDifferences:Target"));

Original Question

I have three types of loggers, and I've defined named instances in my container for them:

c.For(typeof(ILogDifferencesLogger<>))
    .Use(typeof(LogDifferencesAllLogger<>))
    .Named("all");
c.For(typeof(ILogDifferencesLogger<>))
    .Use(typeof(LogDifferencesNLogLogger<>))
    .Named("nlog");
c.For(typeof(ILogDifferencesLogger<>))
    .Use(typeof(LogDifferencesDatabaseLogger<>))
    .Named("database");

The LogDifferencesCommand receives an ILogDifferencesLogger<> as its only argument:

public LogDifferencesCommand(ILogDifferencesLogger<TKey> logDifferencesLogger)
{
    this.logDifferencesLogger = logDifferencesLogger;
}

How do I properly configure the ILogDifferencesCommand<> to grab the right named instance based off of an application setting? Right now I've got something like this:

c.For(typeof(ILogDifferencesCommand<,>))
    .Use(typeof(LogDifferencesCommand<,>));

The issue I'm having is I can't pull in the Ctor<> because I can't use unbound generics with that signature, so then I can't use the Named method off the Ctor for that.

For example, I could do something like this, but that wouldn't hit all possible types:

c.For(typeof(ILogDifferencesCommand<,>)).Use(typeof(LogDifferencesCommand<,>))
    .Ctor<ILogDifferencesLogger<int>>()
    .Named(AppSettingsManager.Get("logDifferences:Target"));

But the problem then is I'd have to handle every TKey type the system uses.

Class and Interface Definitions

public class LogDifferencesCommand<TModel, TKey> : ILogDifferencesCommand<TModel, TKey>
    where TModel : class, IIdModel<TKey>
{
    public LogDifferencesCommand(ILogDifferencesLogger<TKey> logDifferencesLogger)
    {
        this.logDifferencesLogger = logDifferencesLogger;
    }
}

public interface ILogDifferencesCommand<TModel, TKey>
    where TModel : class, IIdModel<TKey>
{
    List<LogDifference> CalculateDifferences(TModel x, TModel y);

    void LogDifferences(TModel x, TModel y, string tableName, string keyField, string userId, int? clientId);

    void RegisterCustomDisplayNameObserver(WeakReference<ICustomDisplayNameObserver<TModel>> observer);

    void RegisterCustomChangeDateObserver(WeakReference<ICustomChangeDateObserver<TModel>> observer);
}

public interface ILogDifferencesLogger<TKey>
{
    void LogDifferences(string tableName, string keyField, string userId, TKey id, List<LogDifference> differences, int? clientId);
}

The reason TKey is required is because of the IIdModel interface.

Body:
One option that comes to mind:

var loggers = new Dictionary<string, ConfiguredInstance>();
loggers.Add("all", c.For(typeof(ILogDifferencesLogger<>))
    .Use(typeof(LogDifferencesAllLogger<>)));
loggers.Add("nlog", c.For(typeof(ILogDifferencesLogger<>))
    .Use(typeof(LogDifferencesNLogLogger<>)));
loggers.Add("database", c.For(typeof(ILogDifferencesLogger<>))
    .Use(typeof(LogDifferencesDatabaseLogger<>)));
foreach (var kv in loggers) {
    // if you still need them named
    // if you only used names for this concrete scenario - you probably don't
    // so can remove it
    kv.Value.Named(kv.Key);
}
c.For(typeof(LogDifferencesCommand<>))
    .Use(typeof(LogDifferencesCommand<>))
    // add explicit instance as dependency
    .Dependencies.Add(typeof(ILogDifferencesLogger<>), loggers[AppSettingsManager.Get("logDifferences:Target")]);

Update. As we've figured out in comments, this doesn't work for your specific case when LogDifferencesCommand has multiple type arguments. For some reason (and I think it's a bug) - structure map tries to create closed generic type ILogDifferencesLogger<>, but when doing that - passes generic type arguments from LogDifferencesCommand. Maybe worth firing an issue at their github. You can workaround it like this:

public class GenericTypesWorkaroundInstance : Instance
{
    private readonly Instance _target;
    private readonly Func<Type[], Type[]> _chooseTypes;
    public GenericTypesWorkaroundInstance(Instance target, Func<Type[], Type[]> chooseTypes) {
        _target = target;
        _chooseTypes = chooseTypes;
        ReturnedType = _target.ReturnedType;
    }

    public override Instance CloseType(Type[] types) {
        // close type correctly by ignoring wrong type arguments
        return _target.CloseType(_chooseTypes(types));
    }

    public override IDependencySource ToDependencySource(Type pluginType) {
        throw new NotSupportedException();
    }

    public override string Description => "Correctly close types over open generic instance";
    public override Type ReturnedType { get; }
}

And then doing

commandReg.Dependencies.Add(
    commandReg.Constructor.GetParameters().First(
        p => p.ParameterType.IsGenericType && p.ParameterType.GetGenericTypeDefinition() == typeof(ILogDifferencesLogger<>)).Name,
        new GenericTypesWorkaroundInstance(
            loggers[AppSettingsManager.Get("logDifferences:Target")],
            // specify which types are correct
            types => types.Skip(1).ToArray()));

And it works, but I cannot say that I like it.


问:
How to call Events in Interfaces C#?
So i have a design problem. I have a mouse class that has delegates and events. ie MouseButtonPressed, MouseMoved. and such that are getting called by a state engine.

What i want to have happen is to create an interface like IClickable or IDraggable or somthing and have events inside those interfaces that get called when the mouse event gets called.

```<code>public interface IClickable

public event MouseDevice.ButtonClickedHandler<MouseButtons, MouseState> Clicked;
</code>```

then in the MouseDevice class it has

```<code>public delegate void ButtonClickedHandler<O, S>(object sender, InputDeviceEventArgs<O, S> e);
</code>```

and

```<code>public event ButtonClickedHandler<MouseButtons, MouseState> ButtonClicked;
</code>```

So basically I want to have Clicked be called when buttonClicked gets called.

Is there a way to do this?

答:
You mean something like this?</p>

```<code>public class MouseDevice {
    public delegate void ButtonClickedHandler<O, E>(O sender, E e);
}

public interface IClickable<O,E> {
    event MouseDevice.ButtonClickedHandler<O,E> Clicked;
}

public class StateMachine : IClickable<Control,MouseEventArgs>
{

    public event MouseDevice.ButtonClickedHandler<Control, MouseEventArgs> Clicked;

    protected void OnButtonClicked(Control sender,MouseEventArgs e) {
        if (Clicked != null){
            Clicked(sender, e);
        }
    }
}

public class Test {
    public static void main(string[] args)
    {
        StateMachine m = new StateMachine();
        m.Clicked += new MouseDevice.ButtonClickedHandler<Control, MouseEventArgs>(m_Clicked);
    }

    static void m_Clicked(Control sender, MouseEventArgs e)
    {
        //Handle Click Event...
    }
}
</code>```

OwnerDisplayName: Eibach

LastEditorDisplayName: lagerdalek

Title: How to call Events in Interfaces C#?

Body:
So i have a design problem. I have a mouse class that has delegates and events. ie MouseButtonPressed, MouseMoved. and such that are getting called by a state engine.

What i want to have happen is to create an interface like IClickable or IDraggable or somthing and have events inside those interfaces that get called when the mouse event gets called.

public interface IClickable

public event MouseDevice.ButtonClickedHandler<MouseButtons, MouseState> Clicked;

then in the MouseDevice class it has

public delegate void ButtonClickedHandler<O, S>(object sender, InputDeviceEventArgs<O, S> e);

and

public event ButtonClickedHandler<MouseButtons, MouseState> ButtonClicked;

So basically I want to have Clicked be called when buttonClicked gets called.

Is there a way to do this?

Body:
You mean something like this?

public class MouseDevice {
    public delegate void ButtonClickedHandler<O, E>(O sender, E e);
}

public interface IClickable<O,E> {
    event MouseDevice.ButtonClickedHandler<O,E> Clicked;
}

public class StateMachine : IClickable<Control,MouseEventArgs>
{

    public event MouseDevice.ButtonClickedHandler<Control, MouseEventArgs> Clicked;

    protected void OnButtonClicked(Control sender,MouseEventArgs e) {
        if (Clicked != null){
            Clicked(sender, e);
        }
    }
}

public class Test {
    public static void main(string[] args)
    {
        StateMachine m = new StateMachine();
        m.Clicked += new MouseDevice.ButtonClickedHandler<Control, MouseEventArgs>(m_Clicked);
    }

    static void m_Clicked(Control sender, MouseEventArgs e)
    {
        //Handle Click Event...
    }
}

OwnerDisplayName: Igor Zelaya

LastEditorDisplayName: Igor Zelaya


问:
Where to put metadata in use with EF and global resources
I have a project with a website and a assembly project containing logic functions used by several other projects.

The entity framework model is in the logic project so it can be used between projects.
I have also created partial classes here with Metadata (display name, required attributes and such).

So far so good.. But now when I'm implementing localization I need to get the display names from the global resources, which is in the website project. Even if there is some way to add a reference to this, it would make a circular reference.

Anyone got a good idea of how to set this up? It's not to late to move the metadata to the website if that is what I should do.

答:
You shouldn't put any globalization or formatting attributes on your models. You should use View Models inside your web tier. Those view models are classes which are specifically tailored to the needs of a given view. It is those view models that will contain attributes about the formatting and globalization required by this specific view.

So here's the usual controller action workflow:

The action queries a repository to fetch a model

The action maps this model to a view model

The action returns passes this view model to the view

To ease the mapping between your models and view models you could use AutoMapper.


问:
How do javascripts extends work?
 Update : Post by @Bergi on this thread explains the need to use Reflect.construct instead of just calling the parent constructor. This shifts the question to "What's the technical difference between Constructor.call() and Reflect.construct()". Thanks for all the comments.

For quite a while I have been extending all sorts of types by setting the prototype of my new prototype to the one that is to be extended. E.g. If I wanted to extend the class "Person" i'd create my extending prototype by calling NewType.prototype=Object.create(Person.prototype); for something like:

```<code>const B = function(){
    return A.call(this);
};

B.prototype = Object.create(A.prototype);

B.prototype.extra_method = function(){
    console.log('hello');
}
</code>```

Recently I have noticed tho that this method is not as capable as the ES6 class extends. For example if I wanted to extend a builtin type, I can only really do that with the class extends keyword. Why is that?

Example A (does not work):

```<code>const ArrayExt = function(){
    this.extra_variable = 'hello!';
    return Array.call(this,...arguments);
}

ArrayExt.prototype = Object.create(Array.prototype);

ArrayExt.prototype.extra_method = function(){
    console.log('Method called!');
}

var inst = new ArrayExt(1,2,3);

inst.push(4);
inst.length == 4 //seems to work right?

inst.extra_method == undefined //not included
inst.extra_variable == undefined //not included (why?)
</code>```

Example B (works):

```<code>const ArrayExt = class extends Array{
    constructor(){
        super(...arguments);
        this.extra_variable = 'Hello!';
    }

    extra_method(){
        console.log('I actually am here now!');
    }
};

var inst = new ArrayExt(1,2,3);

inst.push(4);
inst.length == 4 //works
inst.extra_variable == 'Hello!' //works
inst.extra_method() //'I actually am here now!' works
</code>```

答:
What's the technical difference between Constructor.call() and Reflect.construct()

It's a different usage of the function object. It's the same as the difference between Example() and new Example().

The two expressions always did different things, resolving to two different internal methods (named [[call]] and [[construct]]) that an object could have. ES6 just introduced new types of functions where only one of them works (arrows, methods: call; class constructors: construct). Functions created from  function syntax always did enable both (even when it was not desirable).

Title: How do javascripts extends work?

Body:
 Update : Post by @Bergi on this thread explains the need to use Reflect.construct instead of just calling the parent constructor. This shifts the question to "What's the technical difference between Constructor.call() and Reflect.construct()". Thanks for all the comments.

For quite a while I have been extending all sorts of types by setting the prototype of my new prototype to the one that is to be extended. E.g. If I wanted to extend the class "Person" i'd create my extending prototype by calling NewType.prototype=Object.create(Person.prototype); for something like:

const B = function(){
    return A.call(this);
};

B.prototype = Object.create(A.prototype);

B.prototype.extra_method = function(){
    console.log('hello');
}

Recently I have noticed tho that this method is not as capable as the ES6 class extends. For example if I wanted to extend a builtin type, I can only really do that with the class extends keyword. Why is that?

Example A (does not work):

const ArrayExt = function(){
    this.extra_variable = 'hello!';
    return Array.call(this,...arguments);
}

ArrayExt.prototype = Object.create(Array.prototype);

ArrayExt.prototype.extra_method = function(){
    console.log('Method called!');
}

var inst = new ArrayExt(1,2,3);

inst.push(4);
inst.length == 4 //seems to work right?

inst.extra_method == undefined //not included
inst.extra_variable == undefined //not included (why?)

Example B (works):

const ArrayExt = class extends Array{
    constructor(){
        super(...arguments);
        this.extra_variable = 'Hello!';
    }

    extra_method(){
        console.log('I actually am here now!');
    }
};

var inst = new ArrayExt(1,2,3);

inst.push(4);
inst.length == 4 //works
inst.extra_variable == 'Hello!' //works
inst.extra_method() //'I actually am here now!' works


问:
RTS AI: where to start?
I'd like to begin tinkering around with an RTS AI, but I'm having trouble finding a good environment to work with, ie a game that has been already created. I have looked at Spring RTS and Bos Wars, but they don't seem to be conducive to creating simple examples.

I am not totally opposed to writing my own game environment, it would just take a long time. Does anyone have a suggestion as to how I can get my feet wet without programming my own game?

答:
I can not say anything about the other projects, but i can speak for Spring RTS:

It supports a plugin system for AI Interfaces, and as of January 2011, comes with a Native (C/C++) and a JVM (Java, Groovy, JRuby, ...) AI Interface plugin. A Python plugin is quite mayor already, but not yet considered stable. There are lots of C++ AIs to be used as reference, while for Java, there is a small tutorial and a few AIs.

As the base of all the interfaces is the same (the engine), they are very similar in nature, so it is also possible to use C++ AIs as a reference when writing a Java AI and vice versa.

The AI development forum and the #ai channel on the lobby (also reachable through IRC) may be of use too.

The engine has already been used for at least 7 AIs developed during university thesis.

The engine its self is mostly written in C++, uses the CMake build system and compiles on Linux+GCC and Windows+MinGW (unofficially also on MSVC). You may want to follow the guide under Development - Compiling on the projects homepage, which explains how to compile the engine, and in turn also gets you the source code of the engine and a few AIs.

OwnerDisplayName: awegawef

Title: RTS AI: where to start?


问:
Chrome error on localhost
I get the following an error while I work on localhost with Chrome. I get this error even if the page is empty:

Uncaught TypeError: Cannot read property 'appendChild' of undefined
      at lstr.js:26

(lstr.js is Chrome file)

Error line:

1

And I don't know if it's related to this, but there's a tag called shadow on console:

I am not getting an error while I work with another browser. I use wampserver and this error is repeating when I use ajax. How can I eliminate this error?

答: This is because of chrome extension.remove makegif-video-capture fixed the issue</p>

Title: Chrome error on localhost