问:
trying to create an array of struct pointer but get heap/buffer/etc violation statistically
i have two structs

```<code>typedef enum { False = 0, True = 1 } bool;
//defenition of candy structure
typedef struct _Candy {
    char candy_name[16];
    bool vegan;
}Candy;
typedef struct _Child {
    char child_name[16];
    Candy *candy_of_child;
}Child;
</code>```

now im trying to create an array of pointers that each one is Child type
[*Child,*Child...] etc
now i can initialize it i need to do it dynamically

the function that does in is:

```<code>int AllocateKidsArray(int NumOfKids, Child** ptr_to_child_arr) {
//=================================================
//"AllocateKidsArray" intializing an array of childrens
//Input:  1. int indicating the number of kids
//        2. pointer to an array of children
//Output: 1. return an int value {0}->Success {-1}->Failure
//        2. pointer to an empty initialized array of childerns
//=================================================
// array of length NumOfKids, consisting of Child pointers
Child **ptr_to_childs = malloc(NumOfKids * sizeof(Child*));
int i;
for (i = 0; i < NumOfKids; i++) {
    ptr_to_childs[i] = malloc(sizeof(Child));
    strncpy((*ptr_to_childs[i]).child_name, "", 16);
    (*ptr_to_childs)[i].candy_of_child = NULL;
}
*ptr_to_child_arr = *ptr_to_childs;
//for (i = 0; i < NumOfKids; i++) {
//  free(ptr_to_childs[i]);
//}
//free(ptr_to_childs);
return 0;
}
</code>```

im calling it from the main in the following manner:

```<code>int main(int argc, char** argv) {
//=================================================
if (argc < 3) {
    printf("Incorrect number of arguments. Please invoke the program \n\t./program.exe < input.txt> <output.txt> \n");
    exit(1);
}
int i, lines, checker = 0;
Candy *test = NULL;
char* name_test = NULL;
char* candy_test = NULL;
char* line = "Tamar,Apple\n";
int* NumLinesFile = NULL;
Child *ArrayOfChild = NULL;
.
.
.
//GetNumLines check
printf("%s\n", argv[0]);
printf("%s\n", argv[1]);
printf("%s\n", argv[2]);
GetNumLines(argv[1], &NumLinesFile);
lines = *NumLinesFile;
*NumLinesFile = NULL;
printf("%d\n", lines);
//=================================================
//AllocateKidsArray check
//AllocateKidsArray(lines, &ArrayOfChild);
AllocateKidsArray(lines, &ArrayOfChild);
//ImportKidsArray check
ImportKidsArray(argv[1], lines, &ArrayOfChild);
for (i = 0; i < lines; i++) {
    //ArrayOfChild[i].candy_of_child = (Candy*) malloc(sizeof(Candy*));
    printf("%s,%s\n", ArrayOfChild[i].child_name, ArrayOfChild[i].candy_of_child->candy_name);
}
//=================================================
</code>```

and im statistically get heap/buffer violation
i suspect this function but i dont know what is wrong with it.

after the init of the array i pass it to another function that fills it in:

```<code>int ImportKidsArray(char* file_addr, int num_kids, Child** array_of_kids_to_fill) {
//=================================================
//"ImportKidsArray" reads the file and assign each valid line to cell in the array
//Input:  1. string to a location of a file
//        2. int indicating the number of kids
//        3. pointer to an array of children
//Output: 1. return an int value {0}->Success {-1}->Failure
//        2. pointer to an initialized array of childerns
//=================================================
FILE *fp;
char character;
char line[32];
int i = 0, j = 1, checker = 0, arr_count = 0;
char* TempChild = NULL;
char* TempCandy = NULL;
Child *arr = *array_of_kids_to_fill;

fp = fopen(file_addr, "r");
// Check if file exists
if (fp == NULL) {
    printf("Could not open file %s", file_addr);
    return -1;
}
while (!feof(fp)) {
    fgets(line, 32, fp);
    checker = ParseLine(line, &TempChild, &TempCandy);
    GetCandy(TempCandy, &(arr[arr_count].candy_of_child));
    strncpy((arr[arr_count]).child_name, TempChild, 16);
    arr_count++;

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

please if anyone can help, it will save my life :)

答:
You want to change to ArrayOfChild. Passing it's address from main().

Change it by appropriately de-referencing it.

```<code>*ptr_to_childs = malloc(NumOfKids * sizeof(Child));
</code>```

Then do rest of the operation on *ptr_to_childs. That will retain the change that you made in the called function.

Also check the return value of malloc. And free(using free()) the memory dynamically allocated.

If you notice carefully you will see in the ArrayOfChild() function you are working with a local variable Child **ptr_to_childs. You certainly don't want that as that variable will not be alive when the function ends.

Also while (!feof(fp)) is not appropriate to use. Check this link for that.

Another thing is check the return value of char *fgets(char *str, int n, FILE *stream).

On success, the function returns the same str parameter. If the
  End-of-File is encountered and no characters have been read, the
  contents of str remain unchanged and a NULL is returned.

Body:
i have two structs

typedef enum { False = 0, True = 1 } bool;
//defenition of candy structure
typedef struct _Candy {
    char candy_name[16];
    bool vegan;
}Candy;
typedef struct _Child {
    char child_name[16];
    Candy *candy_of_child;
}Child;

now im trying to create an array of pointers that each one is Child type
[*Child,*Child...] etc
now i can initialize it i need to do it dynamically

the function that does in is:

int AllocateKidsArray(int NumOfKids, Child** ptr_to_child_arr) {
//=================================================
//"AllocateKidsArray" intializing an array of childrens
//Input:  1. int indicating the number of kids
//        2. pointer to an array of children
//Output: 1. return an int value {0}->Success {-1}->Failure
//        2. pointer to an empty initialized array of childerns
//=================================================
// array of length NumOfKids, consisting of Child pointers
Child **ptr_to_childs = malloc(NumOfKids * sizeof(Child*));
int i;
for (i = 0; i < NumOfKids; i++) {
    ptr_to_childs[i] = malloc(sizeof(Child));
    strncpy((*ptr_to_childs[i]).child_name, "", 16);
    (*ptr_to_childs)[i].candy_of_child = NULL;
}
*ptr_to_child_arr = *ptr_to_childs;
//for (i = 0; i < NumOfKids; i++) {
//  free(ptr_to_childs[i]);
//}
//free(ptr_to_childs);
return 0;
}

im calling it from the main in the following manner:

int main(int argc, char** argv) {
//=================================================
if (argc < 3) {
    printf("Incorrect number of arguments. Please invoke the program \n\t./program.exe < input.txt> <output.txt> \n");
    exit(1);
}
int i, lines, checker = 0;
Candy *test = NULL;
char* name_test = NULL;
char* candy_test = NULL;
char* line = "Tamar,Apple\n";
int* NumLinesFile = NULL;
Child *ArrayOfChild = NULL;
.
.
.
//GetNumLines check
printf("%s\n", argv[0]);
printf("%s\n", argv[1]);
printf("%s\n", argv[2]);
GetNumLines(argv[1], &NumLinesFile);
lines = *NumLinesFile;
*NumLinesFile = NULL;
printf("%d\n", lines);
//=================================================
//AllocateKidsArray check
//AllocateKidsArray(lines, &ArrayOfChild);
AllocateKidsArray(lines, &ArrayOfChild);
//ImportKidsArray check
ImportKidsArray(argv[1], lines, &ArrayOfChild);
for (i = 0; i < lines; i++) {
    //ArrayOfChild[i].candy_of_child = (Candy*) malloc(sizeof(Candy*));
    printf("%s,%s\n", ArrayOfChild[i].child_name, ArrayOfChild[i].candy_of_child->candy_name);
}
//=================================================

and im statistically get heap/buffer violation
i suspect this function but i dont know what is wrong with it.

after the init of the array i pass it to another function that fills it in:

int ImportKidsArray(char* file_addr, int num_kids, Child** array_of_kids_to_fill) {
//=================================================
//"ImportKidsArray" reads the file and assign each valid line to cell in the array
//Input:  1. string to a location of a file
//        2. int indicating the number of kids
//        3. pointer to an array of children
//Output: 1. return an int value {0}->Success {-1}->Failure
//        2. pointer to an initialized array of childerns
//=================================================
FILE *fp;
char character;
char line[32];
int i = 0, j = 1, checker = 0, arr_count = 0;
char* TempChild = NULL;
char* TempCandy = NULL;
Child *arr = *array_of_kids_to_fill;

fp = fopen(file_addr, "r");
// Check if file exists
if (fp == NULL) {
    printf("Could not open file %s", file_addr);
    return -1;
}
while (!feof(fp)) {
    fgets(line, 32, fp);
    checker = ParseLine(line, &TempChild, &TempCandy);
    GetCandy(TempCandy, &(arr[arr_count].candy_of_child));
    strncpy((arr[arr_count]).child_name, TempChild, 16);
    arr_count++;

}
return 0;
}

please if anyone can help, it will save my life :)

Body:
You want to change to ArrayOfChild. Passing it's address from main().

Change it by appropriately de-referencing it.

*ptr_to_childs = malloc(NumOfKids * sizeof(Child));

Then do rest of the operation on *ptr_to_childs. That will retain the change that you made in the called function.

Also check the return value of malloc. And free(using free()) the memory dynamically allocated.

If you notice carefully you will see in the ArrayOfChild() function you are working with a local variable Child **ptr_to_childs. You certainly don't want that as that variable will not be alive when the function ends.

Also while (!feof(fp)) is not appropriate to use. Check this link for that.

Another thing is check the return value of char *fgets(char *str, int n, FILE *stream).

On success, the function returns the same str parameter. If the
  End-of-File is encountered and no characters have been read, the
  contents of str remain unchanged and a NULL is returned.


来源: stackexchange

问:
Iterate through an array in wordpress php
I'm trying to iterate through this array with 'foreach' to get [post_title]. But unfortunately it's printing me nothing in my browser. Can anybody explain I can iterate through this array?

```<code>Array
(
[0] => WP_Post Object
    (
        [ID] => 6
        [post_author] => 1
        [post_date] => 2017-11-09 12:56:27
        [post_date_gmt] => 2017-11-09 12:56:27
        [post_content] =>
        [post_title] => Hi everybody
        [post_excerpt] =>
        [post_status] => publish
        [comment_status] => open
        [ping_status] => open
        [post_password] =>
        [post_name] => hi-everybody
        [to_ping] =>
        [pinged] =>
        [post_modified] => 2017-11-09 12:56:27
        [post_modified_gmt] => 2017-11-09 12:56:27
        [post_content_filtered] =>
        [post_parent] => 0
        [menu_order] => 0
        [post_type] => post
        [post_mime_type] =>
        [comment_count] => 0
        [filter] => raw
    )

[1] => WP_Post Object
    (
        [ID] => 1
        [post_author] => 1
        [post_date] => 2017-11-06 22:35:17
        [post_date_gmt] => 2017-11-06 22:35:17
        [post_content] => Welcome to WordPress. This is your first post. Edit or delete it, then start writing!
        [post_title] => Hello world!
        [post_excerpt] =>
        [post_status] => publish
        [comment_status] => open
        [ping_status] => open
        [post_password] =>
        [post_name] => hello-world
        [to_ping] =>
        [pinged] =>
        [post_modified] => 2017-11-06 22:35:17
        [post_modified_gmt] => 2017-11-06 22:35:17
        [post_content_filtered] =>
        [post_parent] => 0
        [menu_order] => 0
        [post_type] => post
        [post_mime_type] =>
        [comment_count] => 1
        [filter] => raw
    )

)
</code>```

Here's my foreach loop code:

```<code>    $my_posts = new WP_Query;
    $myposts = $my_posts->query( array('post_type' => 'post'));

            foreach ($post as $myposts ) {

                        echo $post['post_title'];
                 }
}
</code>```

Again, I need to get the value of post_title but I get no output. Help is appreciated.

答:
Try this:</p>

```<code>$my_posts = new WP_Query;
$myposts = $my_posts->query( array('post_type' => 'post'));
foreach ($post as $myposts ) {
    echo $myposts->post_title;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to iterate through this array with 'foreach' to get [post_title]. But unfortunately it's printing me nothing in my browser. Can anybody explain I can iterate through this array?

Array
(
[0] => WP_Post Object
    (
        [ID] => 6
        [post_author] => 1
        [post_date] => 2017-11-09 12:56:27
        [post_date_gmt] => 2017-11-09 12:56:27
        [post_content] =>
        [post_title] => Hi everybody
        [post_excerpt] =>
        [post_status] => publish
        [comment_status] => open
        [ping_status] => open
        [post_password] =>
        [post_name] => hi-everybody
        [to_ping] =>
        [pinged] =>
        [post_modified] => 2017-11-09 12:56:27
        [post_modified_gmt] => 2017-11-09 12:56:27
        [post_content_filtered] =>
        [post_parent] => 0
        [menu_order] => 0
        [post_type] => post
        [post_mime_type] =>
        [comment_count] => 0
        [filter] => raw
    )

[1] => WP_Post Object
    (
        [ID] => 1
        [post_author] => 1
        [post_date] => 2017-11-06 22:35:17
        [post_date_gmt] => 2017-11-06 22:35:17
        [post_content] => Welcome to WordPress. This is your first post. Edit or delete it, then start writing!
        [post_title] => Hello world!
        [post_excerpt] =>
        [post_status] => publish
        [comment_status] => open
        [ping_status] => open
        [post_password] =>
        [post_name] => hello-world
        [to_ping] =>
        [pinged] =>
        [post_modified] => 2017-11-06 22:35:17
        [post_modified_gmt] => 2017-11-06 22:35:17
        [post_content_filtered] =>
        [post_parent] => 0
        [menu_order] => 0
        [post_type] => post
        [post_mime_type] =>
        [comment_count] => 1
        [filter] => raw
    )

)

Here's my foreach loop code:

    $my_posts = new WP_Query;
    $myposts = $my_posts->query( array('post_type' => 'post'));

            foreach ($post as $myposts ) {

                        echo $post['post_title'];
                 }
}

Again, I need to get the value of post_title but I get no output. Help is appreciated.

Body:
Try this:

$my_posts = new WP_Query;
$myposts = $my_posts->query( array('post_type' => 'post'));
foreach ($post as $myposts ) {
    echo $myposts->post_title;
}


答:
your code should be like this:</p>

```<code>$my_posts = new WP_Query;
$myposts = $my_posts->query( array('post_type' => 'post'));

foreach ($myposts  as $post )
{
    echo $post->post_title;
}
</code>```

Title: Iterate through an array in wordpress php

Body:
your code should be like this:

$my_posts = new WP_Query;
$myposts = $my_posts->query( array('post_type' => 'post'));

foreach ($myposts  as $post )
{
    echo $post->post_title;
}


问:
Unable to reuse block of code but not sure what to change
I have a limited understanding of html, javascript, and css. I have this code below that creates tab content but I can't seem to keep a tab from First Use and a tab from Second Use open at the same time. I have tried changing class names, ids, function names, etc. but this either breaks it or causes it not to work as intended. What do I need to change in the second block so that they work as two separate entities? How can I keep tabs from both uses open at once? Any help would be greatly appreciated.

/* First Use */

  <button class="tablinks" onclick="openSection(event, 'Section 1')" id="defaultOpen">Hydrogeological Investigations</button>
  <button class="tablinks" onclick="openSection(event, 'Section 2')">Construction Dewatering</button>
  <button class="tablinks" onclick="openSection(event, 'Section 3')">Land Development</button>
  <button class="tablinks" onclick="openSection(event, 'Section 4')">Feature Based Water Balance</button>
  <button class="tablinks" onclick="openSection(event, 'Section 5')">Environmental Monitoring</button>

Hydrogeological Investigations

Section 1 Text Here.

Construction Dewatering

Section 2 text here.

Land Development

Section 3 text here.

Feature Based Water Balance

Section 4 text here.

Environmental Monitoring

Section 5 text here.

/* Second Use */

  <button class="tablinks" onclick="openSection(event, 'Section 1 env')" id="defaultOpenenv">Blah</button>
  <button class="tablinks" onclick="openSection(event, 'Section 2 env')">Blah</button>
  <button class="tablinks" onclick="openSection(event, 'Section 3 env')">Blah</button>
  <button class="tablinks" onclick="openSection(event, 'Section 4 env')">Blah</button>
  <button class="tablinks" onclick="openSection(event, 'Section 5 env')">Blah</button>

Hydrogeological Investigations

Section 1 Text Here. Second Use

Construction Dewatering

Section 2 text here.

Land Development

Section 3 text here.

Feature Based Water Balance

Section 4 text here.

Environmental Monitoring

Section 5 text here.

 ```

答: You need unique id's for this to work. When you click the tab with id Section 2 in the second use, it will open the tab content for Section 2 in the first use.


问:
Unable to show Snacker from thread
I'm working with an adapter that handles its own service call to update its items (not my adapter).  This adapter defines an interface I can pass in to make callbacks to views to show/hide loading indicators.  I want to show a Snacker when a call fails (example: no network connection).  I've defined that method in the interface and added it to my Fragment, and I've updated the adapter to call that method when a service call fails.

```<code>@Override
public void OnLoaded(int count) {
}

@Override
public void OnStartLoading() {
    showRefresh();
}

@Override
public void OnStopLoading() {
    clearRefresh();
}

@Override
public void OnServiceFailure() {
    showSnackBar(getString(R.string.error));
}

protected void showSnackBar(String message) {
    View view = getView();
    if (view != null && getUserVisibleHint()) {
        snackbar = Snackbar.make(view, message, Snackbar.LENGTH_INDEFINITE);
        snackbar.setActionTextColor(ContextCompat.getColor(getContext(), R.color.accent_dark));
        snackbar.setAction(getString(R.string.retry), v -> {
                refreshLayout.setRefreshing(true);
                onRefresh();
                });
        snackbar.show();
    }
}
</code>```

Unfortunately, the Snackbar doesn't show.

Here's the thing:  OnServiceFailure() is being called from a thread.  I've tried wrapping the call to showSnackBar() in activity.runOnUiThread(), but that doesn't seem to solve the problem.  I've also debugged showSnackBar() and it IS finding view and view IS the root FrameLayout.

If I call showSnackBar() anywhere else from the main thread, everything works fine.

I'm not sure where to go from here.

答:
When using an service or thread you can only show a snackbar on the main (UI) thread. for fragments there is a special function inside the view object to post your code to the main thread.

```<code>View view = getView();
view.post()
</code>```

this send your code to the main thread and shows the SnackBar.

Title: Unable to show Snacker from thread

Body:
I'm working with an adapter that handles its own service call to update its items (not my adapter).  This adapter defines an interface I can pass in to make callbacks to views to show/hide loading indicators.  I want to show a Snacker when a call fails (example: no network connection).  I've defined that method in the interface and added it to my Fragment, and I've updated the adapter to call that method when a service call fails.

@Override
public void OnLoaded(int count) {
}

@Override
public void OnStartLoading() {
    showRefresh();
}

@Override
public void OnStopLoading() {
    clearRefresh();
}

@Override
public void OnServiceFailure() {
    showSnackBar(getString(R.string.error));
}

protected void showSnackBar(String message) {
    View view = getView();
    if (view != null && getUserVisibleHint()) {
        snackbar = Snackbar.make(view, message, Snackbar.LENGTH_INDEFINITE);
        snackbar.setActionTextColor(ContextCompat.getColor(getContext(), R.color.accent_dark));
        snackbar.setAction(getString(R.string.retry), v -> {
                refreshLayout.setRefreshing(true);
                onRefresh();
                });
        snackbar.show();
    }
}

Unfortunately, the Snackbar doesn't show.

Here's the thing:  OnServiceFailure() is being called from a thread.  I've tried wrapping the call to showSnackBar() in activity.runOnUiThread(), but that doesn't seem to solve the problem.  I've also debugged showSnackBar() and it IS finding view and view IS the root FrameLayout.

If I call showSnackBar() anywhere else from the main thread, everything works fine.

I'm not sure where to go from here.

Body:
When using an service or thread you can only show a snackbar on the main (UI) thread. for fragments there is a special function inside the view object to post your code to the main thread.

View view = getView();
view.post()

this send your code to the main thread and shows the SnackBar.


问:
Ember 2.16.x: Accessing Ember.Handlebars.Utils.escapeExpression with new import syntax
How does one access the Ember.Handlebars.Utils.escapeExpression function using the new import syntax in Ember 2.16.x and above?

The following code snippet comes from the Writing Helpers section of the Ember docs. (FYI, there are a couple of unrelated errors in the original, which I have cleaned up in the code below.)

import { helper } from "@ember/component/helper";
import Handlebars from "handlebars";
import { htmlSafe } from "@ember/string";

export function makeBold(param /*, ...rest*/ ) {
  let value = Handlebars.Utils.escapeExpression(param);
  return htmlSafe(`<b>${value}</b>`);
}

export default helper(makeBold);
```

If I use the code above, I get the following error:

Could not find module 'handlebars' imported from 'ember-app/helpers/make-bold'

答:
As of right now the Handlebars.Utils.escapeExpression function is not yet exported by the New Module Imports (aka. RFC 176). You should keep using it from the Ember import for now:

```<code>import Ember from 'ember';

Ember.Handlebars.Utils.escapeExpression(...)
</code>```

An open GitHub issue for this exists at https://github.com/ember-cli/ember-rfc176-data/issues/12

The guides page that you linked appears to be mistaken and we need to fix that particular snippet. Sorry about that!

Body:
How does one access the Ember.Handlebars.Utils.escapeExpression function using the new import syntax in Ember 2.16.x and above?

The following code snippet comes from the Writing Helpers section of the Ember docs. (FYI, there are a couple of unrelated errors in the original, which I have cleaned up in the code below.)

import { helper } from "@ember/component/helper";
import Handlebars from "handlebars";
import { htmlSafe } from "@ember/string";

export function makeBold(param /*, ...rest*/ ) {
  let value = Handlebars.Utils.escapeExpression(param);
  return htmlSafe(`<b>${value}</b>`);
}

export default helper(makeBold);

If I use the code above, I get the following error:

Could not find module 'handlebars' imported from 'ember-app/helpers/make-bold'

Body:
As of right now the Handlebars.Utils.escapeExpression function is not yet exported by the New Module Imports (aka. RFC 176). You should keep using it from the Ember import for now:

import Ember from 'ember';

Ember.Handlebars.Utils.escapeExpression(...)

An open GitHub issue for this exists at https://github.com/ember-cli/ember-rfc176-data/issues/12

The guides page that you linked appears to be mistaken and we need to fix that particular snippet. Sorry about that!


问:
Spring cache implementation with Elasticsearch
I've got a service that is distributed between 9 VMs.
I want to create a single cache that will be used between all of them.
up until now I was using separate cache for each VM which gave me inconsistency between all of them.

I already have an elasticsearch that I am using so I was wondering if I can use the ES as a cache layer + spring cache abstraction together.

the service is in Java 8 + Spring Boot + ES 5.2.2

edit:

additional information, the original problem for my service is that I need to return a response in less then 100ms , that is when I've started using a simple spring cache implementation using ConcurrentCacheManager , works just fine for the speed, and the cache should be refreshed every hour~, for now I've got about 1300~ objects that needs to be cached, so on every service startup i have a process that fills the cache with all the responses that I've got and another process that would wake up every hour or so will refresh the entries with updated data. that would occur on each of the 9 vms.
the issues with this system are:
1. i would hit another service multiple of 9 times each hour with all the information it got (it can handle it but it would be better if only one vm would do it)
2. if i need to update a specific entry in cache with new information or delete it all together, i don't have an issue way to remove it from all the vm's that are in my pool.
3. since each vm runs the cache refresh in a slightly different time, the cache won't be aligned across all VM's and the same call to a LB can return different results from different specific VMs.
4. for now i've got only 1300 objects that needs to be cached but it could go exponentially to millions of entries and I don't want to get stuck with out of memory issues.

I understand its not the ideal use of a cache system, and I might use a wrong term for what I want to have but basically I need a good and fast name-value storage system that can be accessed across my service. and it would be great if it can use the spring-cache abstraction because its really easy to use and it's already implemented in my service.

Thanks,
A.

答:
You could easily integrate Hazecast or EHCache as the distributed cache for your spring application. </p>

<p>It might be me, but I find it a weird choice to use Elastic Search as a cache. </p>

Body:
You could easily integrate Hazecast or EHCache as the distributed cache for your spring application.

It might be me, but I find it a weird choice to use Elastic Search as a cache.


问:
not able to locate gradle.properties in toolbox
I'm trying to run ./gradlew build command, which has artifactory_contextUrl property used in build.gradle file.

gradlew.properties is located in C:\Users\XXX.gradle folder, when I build the project in windows Intellij it takes the gradle.properties file in user folder and so gets the contexturl and everything is fine but,

when I try to build the project in docker toolbox it couldnt find it.
Toolbox starts with some location in C folder.

I tried with placing gradle.properties at the same level as build.gradle it works fine in toolbox. Eventually I dont want to keep the gradle.properties at buils.gradle level

What should I do? Does any one has any suggestions?

答:
Well, I guess the docker toolbox (whatever it is, I don't know it) does run with another user account and thus does not find your gradle.properties file in your user directory.

The file is actually called gradle.properties, isn't it? In your question you use gradlew.properties and gradle.properties and only the latter is valid.

To solve your problem you can either make sure the gradle.properties is also in the users home directory that is used in the docker toolbox. To find out which directory this is, you can run Gradle with -d and search for Gradle user home, there it tells you which directory is the one where the gradle.properties is expected.

Alternatively you can use -P artifactory_contextUrl=asdf to set the property from the commandline, or use the system property org.gradle.project.artifactory_contextUrl or environment variable ORG_GRADLE_PROJECT_artifactory_contextUrl to set the project property.


问:
ReactiveUI - The type 'IScheduler' is defined in an assembly that is not referenced
I'm trying to subclass ReactiveList so it responds to changes in a ReactiveDictionary I have written, rather than a parent List.

This is the class and constructor signature for the ReactiveList subclass.

```<code>public class ReactiveDictionaryDerivedList<TKey, TValue, TDerived> : ReactiveList<TDerived>, IReactiveDerivedList<TDerived>
{
    public ReactiveDictionaryDerivedList(
        IReadOnlyReactiveDictionary<TKey, TValue> dict,
        Func<TValue, TDerived> selector,
        Func<TValue, TDerived, bool> derivedValueFinder,
        IScheduler scheduler)
    {
    }
</code>```

Here are the dependencies I have in the project. Notice that I'm using the 4.0.0 preview release of System.Reactive, since this is installed by the ReactiveUI 8.0.0 alpha. (I'm using the ReactiveUI alpha as this seems to be what is recommended these days)

```<code><packages>
  <package id="ReactiveUI" version="8.0.0-alpha0113" targetFramework="net452" />
  <package id="ReactiveUI.WPF" version="8.0.0-alpha0113" targetFramework="net452" />
  <package id="Splat" version="2.0.0" targetFramework="net452" />
  <package id="System.Reactive" version="4.0.0-preview00001" targetFramework="net452" />
</packages>
</code>```

The problem is that the class doesn't compile because of the error:

```<code>error CS0012: The type 'IScheduler' is defined in an assembly that is not referenced.
You must add a reference to assembly 'System.Reactive.Interfaces, Version=3.0.1000.0,
Culture=neutral, PublicKeyToken=94bc3704cddfc263'.
</code>```

Any ideas how to resolve would be appreciated. Advice on the recommended versions for ReactiveUI and System.Reactive would also be nice.

答:
In my WPF app I had to install the System.Reactive.XXXXX packages with version 4.0.0-preview00001 (Core, Interfaces, Linq, PlatformServices, Windows.Threading, Windows.Forms).

All these packages come with the System.Reactive.Compatibility package (nuget link):

Reactive Extensions (Rx) Compatibility Library for enabling v3 apps to
  work with v4

You should try using it in your project.

Body:
I'm trying to subclass ReactiveList so it responds to changes in a ReactiveDictionary I have written, rather than a parent List.

This is the class and constructor signature for the ReactiveList subclass.

public class ReactiveDictionaryDerivedList<TKey, TValue, TDerived> : ReactiveList<TDerived>, IReactiveDerivedList<TDerived>
{
    public ReactiveDictionaryDerivedList(
        IReadOnlyReactiveDictionary<TKey, TValue> dict,
        Func<TValue, TDerived> selector,
        Func<TValue, TDerived, bool> derivedValueFinder,
        IScheduler scheduler)
    {
    }

Here are the dependencies I have in the project. Notice that I'm using the 4.0.0 preview release of System.Reactive, since this is installed by the ReactiveUI 8.0.0 alpha. (I'm using the ReactiveUI alpha as this seems to be what is recommended these days)

<packages>
  <package id="ReactiveUI" version="8.0.0-alpha0113" targetFramework="net452" />
  <package id="ReactiveUI.WPF" version="8.0.0-alpha0113" targetFramework="net452" />
  <package id="Splat" version="2.0.0" targetFramework="net452" />
  <package id="System.Reactive" version="4.0.0-preview00001" targetFramework="net452" />
</packages>

The problem is that the class doesn't compile because of the error:

error CS0012: The type 'IScheduler' is defined in an assembly that is not referenced.
You must add a reference to assembly 'System.Reactive.Interfaces, Version=3.0.1000.0,
Culture=neutral, PublicKeyToken=94bc3704cddfc263'.

Any ideas how to resolve would be appreciated. Advice on the recommended versions for ReactiveUI and System.Reactive would also be nice.


问:
How to aggregate test results in jenkins parallel pipeline?
I have a Jenkinsfile with a definition for parallel test execution, and the task is to grab the test results from both in order to process them in a post step somewhere.

Problem is: How to do this? Searching for anything acting as an example code does not bring up anything - either the examples deal with explaining parallel, or they explain post with junit.

```<code>pipeline {
    agent { node { label 'swarm' } }

    stages {
        stage('Testing') {
            parallel {
                stage('Unittest') {
                    agent { node { label 'swarm' } }

                    steps {
                        sh 'unittest.sh'
                    }
                }

                stage ('Integrationtest') {
                    agent { node { label 'swarm' } }

                    steps {
                        sh 'integrationtest.sh'
                    }
                }
            }
        }
    }
}
</code>```

Defining a post {always{junit(...)}} step at both parallel stages yielded a positive reaction from the BlueOcean GUI, but the test report recorded close to double the amount of tests - very odd, some file must have been scanned twice. Adding this post step to the surrounding "Testing" stage gave an error.

I am missing an example detailing how to post-process test results that get created in a parallel block.

答:
Just to record my solution for the internet:

I came up with stashing the test results in both parallel steps, and adding a final step that unstashes the files, then post-processes them:

```<code>pipeline {
    agent { node { label 'swarm' } }

    stages {
        stage('Testing') {
            parallel {
                stage('Unittest') {
                    agent { node { label 'swarm' } }

                    steps {
                        sh 'rm build/*'
                        sh 'unittest.sh'
                    }
                    post {
                        always {
                            stash includes: 'build/**', name: 'testresult-unittest'
                        }
                    }

                }

                stage ('Integrationtest') {
                    agent { node { label 'swarm' } }

                    steps {
                        sh 'rm build/*'
                        sh 'integrationtest.sh'
                    }

                    post {
                        always {
                            stash includes: 'build/**', name: 'testresult-integrationtest'
                        }
                    }
                }
            }
        }

        stage('Reporting') {
            steps {
                unstash 'testresult-unittest'
                unstash 'testresult-integrationtest'
            }

            post {
                always {
                    junit 'build/*.xml'
                }
            }
        }
    }
}
</code>```

My observation though is that you have to pay attention to clean up your workspace: Both test stages do create one file, but on the second run, both workspaces are inherited from the previous run and have both previously created test results present in the build directory.

So you have to remove any remains of test results before you start a new run, otherwise you'd stash an old version of the test result from the "other" stage. I don't know if there is a better way to do this.

Body:
I have a Jenkinsfile with a definition for parallel test execution, and the task is to grab the test results from both in order to process them in a post step somewhere.

Problem is: How to do this? Searching for anything acting as an example code does not bring up anything - either the examples deal with explaining parallel, or they explain post with junit.

pipeline {
    agent { node { label 'swarm' } }

    stages {
        stage('Testing') {
            parallel {
                stage('Unittest') {
                    agent { node { label 'swarm' } }

                    steps {
                        sh 'unittest.sh'
                    }
                }

                stage ('Integrationtest') {
                    agent { node { label 'swarm' } }

                    steps {
                        sh 'integrationtest.sh'
                    }
                }
            }
        }
    }
}

Defining a post {always{junit(...)}} step at both parallel stages yielded a positive reaction from the BlueOcean GUI, but the test report recorded close to double the amount of tests - very odd, some file must have been scanned twice. Adding this post step to the surrounding "Testing" stage gave an error.

I am missing an example detailing how to post-process test results that get created in a parallel block.

Body:
Just to record my solution for the internet:

I came up with stashing the test results in both parallel steps, and adding a final step that unstashes the files, then post-processes them:

pipeline {
    agent { node { label 'swarm' } }

    stages {
        stage('Testing') {
            parallel {
                stage('Unittest') {
                    agent { node { label 'swarm' } }

                    steps {
                        sh 'rm build/*'
                        sh 'unittest.sh'
                    }
                    post {
                        always {
                            stash includes: 'build/**', name: 'testresult-unittest'
                        }
                    }

                }

                stage ('Integrationtest') {
                    agent { node { label 'swarm' } }

                    steps {
                        sh 'rm build/*'
                        sh 'integrationtest.sh'
                    }

                    post {
                        always {
                            stash includes: 'build/**', name: 'testresult-integrationtest'
                        }
                    }
                }
            }
        }

        stage('Reporting') {
            steps {
                unstash 'testresult-unittest'
                unstash 'testresult-integrationtest'
            }

            post {
                always {
                    junit 'build/*.xml'
                }
            }
        }
    }
}

My observation though is that you have to pay attention to clean up your workspace: Both test stages do create one file, but on the second run, both workspaces are inherited from the previous run and have both previously created test results present in the build directory.

So you have to remove any remains of test results before you start a new run, otherwise you'd stash an old version of the test result from the "other" stage. I don't know if there is a better way to do this.


问:
Python: average of dictionary key values over panda values
I have a rather complex data structure, namely dictionaries in a panda dataframe. Lets say I have this dataframe.

```<code>trials_ = [1,2,1,2]
stimul_ = [1,1,2,2]
data_ = [[{'peak_voltage': [30.5, 65], 'Spikecount': [2]}], [{'peak_voltage': [30.5, 65, 30], 'Spikecount': [3]}], [{'peak_voltage': [20.1], 'Spikecount': [1]}], 'NaN']
featve  = pd.DataFrame({'trial': trials_, 'stimulus': stimul_, 'data': data_})
featve

    data                                                stimulus    trial
0   [{'peak_voltage': [30.5, 65], 'Spikecount': [2]}]   1           1
1   [{'peak_voltage': [30.5, 65, 30], 'Spikecount'...   1           2
2   [{'peak_voltage': [20.1], 'Spikecount': [1]}]       2           1
3   NaN                                                 2           2
</code>```

I now want to calculate the median and 25% / 75% quartiles of each key element of my dictionaries in my 'data' column (here peak_voltage and Spikecount) for each stimulus over all trials.

One example for the median:
I want the median peak_voltage value when stimulus 1 was applied across all trials [30.5, 65, 20.1] -> 30.5. The same for when stimulus two was applied [30.5, 65, 30, NaN] -> 30.5. And of course the same for Spikecount.

To be honest, I've no idea where to start. If I only wanted to calculate the median regardless of the simulus, I would simply use.

```<code>featve.data.median
</code>```

But this is not what I want. Also, if I didn't have dictionaries but only numbers, I would have used something like

```<code>featve.groupby('stimulus').data.apply(np.nanmedian)
</code>```

But what can I do in my case with dictionaries in a panda table?

EDIT 1

I have 10 stimuli with 16 trials each, resulting in 160 rows in total. The dictionaries are the output of a toolbox called EFEL that I use to find certain characteristics of my data traces (e.g. the timing of peaks of neuronal action potentials). I decided to organize the resulting 160 dictionaries in a panda dataframe to keep track of the data, stimuli and trials at the same time. I don't know if this is unfortunate in the first place.

答:
For what you are asking I would advise restructuring your dataframe. Instead of constructing featve with:

```<code>data_ = [[{'peak_voltage': [30.5, 65], 'Spikecount': [2]}], [{'peak_voltage': [30.5, 65, 30], 'Spikecount': [3]}], [{'peak_voltage': [20.1], 'Spikecount': [1]}], 'NaN']

data_ = {'peak_voltage': [30.5, 65, 30.5, 65, 30, 20.1, np.nan], 'Spikecount': [2,2,3,3,3,1, np.nan], 'trials': [1,1,2,2,2,1,2], 'stimulus': [1,1,1,1,1,2,2]}
featve = pd.DataFrame(data_)
</code>```

The result is the following DataFrame:

```<code>   Spikecount  peak_voltage  stimulus  trials
0         2.0          30.5         1       1
1         2.0          65.0         1       1
2         3.0          30.5         1       2
3         3.0          65.0         1       2
4         3.0          30.0         1       2
5         1.0          20.1         2       1
6         NaN           NaN         2       2
</code>```

On this DataFrame you can group and compute your medians as you would normally.

e.g

```<code>featve.groupby('stimulus').peak_voltage.meadian()
stimulus
1    30.5
2    20.1
Name: peak_voltage, dtype: float64
</code>```

Update

I understand the concerns about not having "Nice" data. Given a strict construct that follows the format of data_ you could use defaultdict to get a nicer dataframe.

```<code>dict_data = defaultdict(list)

for idx in range(len(data_)):
     if isinstance(data_[idx], list):
         for sub in data_[idx]:
             repeats = len(sub['peak_voltage'])
             data_dict['peak_voltage'] += sub['peak_voltage']
             data_dict['Spikecount'] += sub['Spikecount'] * repeats
             data_dict['trial'] += [trials_[idx]] * repeats
             data_dict['stimulus'] += [stimul_[idx]] * repeats
     else:
         data_dict['peak_voltage'].append('NaN')
         data_dict['Spikecount'].append('NaN')
         data_dict['trial'] += [trials_[idx]]
         data_dict['stimulus'] += [stimul_[idx]]

pd.DataFrame(data_dict)
  Spikecount peak_voltage  stimulus  trial
0          2         30.5         1      1
1          2           65         1      1
2          3         30.5         1      2
3          3           65         1      2
4          3           30         1      2
5          1         20.1         2      1
6        NaN          NaN         2      2
</code>```

Body:
I have a rather complex data structure, namely dictionaries in a panda dataframe. Lets say I have this dataframe.

trials_ = [1,2,1,2]
stimul_ = [1,1,2,2]
data_ = [[{'peak_voltage': [30.5, 65], 'Spikecount': [2]}], [{'peak_voltage': [30.5, 65, 30], 'Spikecount': [3]}], [{'peak_voltage': [20.1], 'Spikecount': [1]}], 'NaN']
featve  = pd.DataFrame({'trial': trials_, 'stimulus': stimul_, 'data': data_})
featve

    data                                                stimulus    trial
0   [{'peak_voltage': [30.5, 65], 'Spikecount': [2]}]   1           1
1   [{'peak_voltage': [30.5, 65, 30], 'Spikecount'...   1           2
2   [{'peak_voltage': [20.1], 'Spikecount': [1]}]       2           1
3   NaN                                                 2           2

I now want to calculate the median and 25% / 75% quartiles of each key element of my dictionaries in my 'data' column (here peak_voltage and Spikecount) for each stimulus over all trials.

One example for the median:
I want the median peak_voltage value when stimulus 1 was applied across all trials [30.5, 65, 20.1] -> 30.5. The same for when stimulus two was applied [30.5, 65, 30, NaN] -> 30.5. And of course the same for Spikecount.

To be honest, I've no idea where to start. If I only wanted to calculate the median regardless of the simulus, I would simply use.

featve.data.median

But this is not what I want. Also, if I didn't have dictionaries but only numbers, I would have used something like

featve.groupby('stimulus').data.apply(np.nanmedian)

But what can I do in my case with dictionaries in a panda table?

EDIT 1

I have 10 stimuli with 16 trials each, resulting in 160 rows in total. The dictionaries are the output of a toolbox called EFEL that I use to find certain characteristics of my data traces (e.g. the timing of peaks of neuronal action potentials). I decided to organize the resulting 160 dictionaries in a panda dataframe to keep track of the data, stimuli and trials at the same time. I don't know if this is unfortunate in the first place.

Body:
For what you are asking I would advise restructuring your dataframe. Instead of constructing featve with:

data_ = [[{'peak_voltage': [30.5, 65], 'Spikecount': [2]}], [{'peak_voltage': [30.5, 65, 30], 'Spikecount': [3]}], [{'peak_voltage': [20.1], 'Spikecount': [1]}], 'NaN']

data_ = {'peak_voltage': [30.5, 65, 30.5, 65, 30, 20.1, np.nan], 'Spikecount': [2,2,3,3,3,1, np.nan], 'trials': [1,1,2,2,2,1,2], 'stimulus': [1,1,1,1,1,2,2]}
featve = pd.DataFrame(data_)

The result is the following DataFrame:

   Spikecount  peak_voltage  stimulus  trials
0         2.0          30.5         1       1
1         2.0          65.0         1       1
2         3.0          30.5         1       2
3         3.0          65.0         1       2
4         3.0          30.0         1       2
5         1.0          20.1         2       1
6         NaN           NaN         2       2

On this DataFrame you can group and compute your medians as you would normally.

e.g

featve.groupby('stimulus').peak_voltage.meadian()
stimulus
1    30.5
2    20.1
Name: peak_voltage, dtype: float64

Update

I understand the concerns about not having "Nice" data. Given a strict construct that follows the format of data_ you could use defaultdict to get a nicer dataframe.

dict_data = defaultdict(list)

for idx in range(len(data_)):
     if isinstance(data_[idx], list):
         for sub in data_[idx]:
             repeats = len(sub['peak_voltage'])
             data_dict['peak_voltage'] += sub['peak_voltage']
             data_dict['Spikecount'] += sub['Spikecount'] * repeats
             data_dict['trial'] += [trials_[idx]] * repeats
             data_dict['stimulus'] += [stimul_[idx]] * repeats
     else:
         data_dict['peak_voltage'].append('NaN')
         data_dict['Spikecount'].append('NaN')
         data_dict['trial'] += [trials_[idx]]
         data_dict['stimulus'] += [stimul_[idx]]

pd.DataFrame(data_dict)
  Spikecount peak_voltage  stimulus  trial
0          2         30.5         1      1
1          2           65         1      1
2          3         30.5         1      2
3          3           65         1      2
4          3           30         1      2
5          1         20.1         2      1
6        NaN          NaN         2      2


问:
Go back to debugging after created release version with react-native bundle (Android)
So I have created my Application using React native and just produced my first release-build.
My problem now is that I can't get back to react natives debug-mode.

By following the documentation, this is what i did.

```<code>react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/
</code>```

This code generated the bundled index.android.bundle and index.android.bundle.meta

Now every time I execute react-native run-android, the javascript code-base wont update the application and I am not able to access the development(shake) menu in my app.

If I run react-native bundle again, the code will update.

I guess this is a simple issue, but can't find any information how to return so the app isn't using the bundled version anymore.

答:
Delete assets folder in app/src/main/

Remove this import line if exist : "import com.facebook.react.BuildConfig;" in MainApplication.java

Run "react-native run-android"

And boom!

Body:
So I have created my Application using React native and just produced my first release-build.
My problem now is that I can't get back to react natives debug-mode.

By following the documentation, this is what i did.

react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/

This code generated the bundled index.android.bundle and index.android.bundle.meta

Now every time I execute react-native run-android, the javascript code-base wont update the application and I am not able to access the development(shake) menu in my app.

If I run react-native bundle again, the code will update.

I guess this is a simple issue, but can't find any information how to return so the app isn't using the bundled version anymore.


问:
How to run .APK file on emulator

Possible Duplicate:

  How do you install an APK file in the Android emulator?

I download an APK file and I want to run it on an Android emulator but I don't know how.  Please help me.  Thanks!

答:
Start an Android Emulator (make sure that all supported APIs are included when you created the emulator, we needed to have the Google APIs for instance).

Then simply email yourself a link to the .apk file, and download it directly in the emulator, and click the downloaded file to install it.

Title: How to run .APK file on emulator

ContentLicense: CC BY-SA 2.5


问:
Unresolved reference DaggerApplicationComponent
I'm trying to create my app component, but Dagger does not generate my app component.
here is MyApplication class

```<code>class MyApplication : Application() {

companion object {
    @JvmStatic lateinit var graph: ApplicationComponent
}
@Inject
lateinit var locationManager : LocationManager

override fun onCreate() {
    super.onCreate()
    graph = DaggerApplicationComponent.builder().appModule(AppModule(this)).build()
    graph.inject(this)
  }
}
</code>```

and here is my AppComponent class

```<code>@Singleton
@Component(modules = arrayOf(AppModule::class))
interface ApplicationComponent {
    fun inject(application: MyApplication)
}
</code>```

here is screenshot

this is my project on github

here is error log

```<code>Error:(7, 48) Unresolved reference: DaggerApplicationComponent
Error:(28, 17) Unresolved reference: DaggerApplicationComponent
Error:Execution failed for task ':app:compileDebugKotlin'.
> Compilation error. See log for more details
Information:BUILD FAILED
Information:Total time: 21.184 secs
Error:e: .../MyApplication.kt: (7, 48): Unresolved reference: DaggerApplicationComponent
e: Unresolved reference: DaggerApplicationComponent
FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugKotlin'.
> Compilation error. See log for more details

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

Information:4 errors
Information:0 warnings
Information:See complete output in console
</code>```

答:
you should remove

```<code>kapt {
generateStubs = true}
</code>```

and add to the top of application gradle file

```<code>apply plugin: 'kotlin-kapt'
</code>```

then Dagger will take care of the rest :)

Body:
I'm trying to create my app component, but Dagger does not generate my app component.
here is MyApplication class

class MyApplication : Application() {

companion object {
    @JvmStatic lateinit var graph: ApplicationComponent
}
@Inject
lateinit var locationManager : LocationManager

override fun onCreate() {
    super.onCreate()
    graph = DaggerApplicationComponent.builder().appModule(AppModule(this)).build()
    graph.inject(this)
  }
}

and here is my AppComponent class

@Singleton
@Component(modules = arrayOf(AppModule::class))
interface ApplicationComponent {
    fun inject(application: MyApplication)
}

here is screenshot

this is my project on github

here is error log

Error:(7, 48) Unresolved reference: DaggerApplicationComponent
Error:(28, 17) Unresolved reference: DaggerApplicationComponent
Error:Execution failed for task ':app:compileDebugKotlin'.
> Compilation error. See log for more details
Information:BUILD FAILED
Information:Total time: 21.184 secs
Error:e: .../MyApplication.kt: (7, 48): Unresolved reference: DaggerApplicationComponent
e: Unresolved reference: DaggerApplicationComponent
FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugKotlin'.
> Compilation error. See log for more details

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

Information:4 errors
Information:0 warnings
Information:See complete output in console

Body:
you should remove

kapt {
generateStubs = true}

and add to the top of application gradle file

apply plugin: 'kotlin-kapt'

then Dagger will take care of the rest :)


问:
PHP Foreach inside foreach display data in table row
How can I display data in a tablerow inside a foreach function? The agenda variable works fine, the rows variable is the one making problems, I need it inside a  tag

```<code><?php
$agenda = $days = json_decode(get_field( "field_uc_content_json" ));
unset($agenda[0]); ?>

<table class="table">
    <thead>
        <tr>
          <th> Day </th>
          <th>Description</th>
          <th>Hours</th>
        </tr>
    </thead>
<tbody>
   <?php foreach($agenda as $column) { ?>
   <tr>
    <td><?php echo $column[0]; ?></td>
    <td><?php
    $rows = explode( "\n", $column[1]);
    foreach ($rows as $row) { ?>
    <tr> <?php echo $row; ?> </tr>
    <?php    } ?>
   </td>
</tbody>
</table>
</code>```

The second foreach

vardump agenda

vardump rows

答:
I think it is work fine now.I tested it.

```<code><table class="table">
    <thead>
        <tr style="background: #8da80c;">
          <th> Day </th>
          <th>Description</th>
          <th>Hours</th>
        </tr>
    </thead>
<tbody>
   <?php foreach($agenda as $column) { ?>
   <tr style="background: #e0e545;">
    <td style="padding: 14px;"><?php echo $column[0]; ?></td>
    <td style="padding: 14px;"><?php echo $column[1]; ?></td>
     <td style="padding: 14px;"><?php echo $column[2]; ?></td>
   </tr>
   <?php } ?>
</tbody>
</table>
</code>```

I tested with these values

```<code>  ```
<?php
$agenda = array (array("montag","Lorem ipsum dolor sit amet","08:00"),array("montag","Lorem ipsum dolor sit amet","08:00"),array("montag","Lorem ipsum dolor sit amet","08:00"));

print_r($agenda);
?>
     ```
</code>```

Body:
How can I display data in a tablerow inside a foreach function? The agenda variable works fine, the rows variable is the one making problems, I need it inside a  tag

<?php
$agenda = $days = json_decode(get_field( "field_uc_content_json" ));
unset($agenda[0]); ?>

           Day
          Description
          Hours

   <?php foreach($agenda as $column) { ?>

    <?php echo $column[0]; ?>
    <?php
    $rows = explode( "\n", $column[1]);
    foreach ($rows as $row) { ?>

 <?php echo $row; ?>

    <?php    } ?>

The second foreach

vardump agenda

vardump rows

Body:
I think it is work fine now.I tested it.

<table class="table">
    <thead>
        <tr style="background: #8da80c;">
          <th> Day </th>
          <th>Description</th>
          <th>Hours</th>
        </tr>
    </thead>
<tbody>
   <?php foreach($agenda as $column) { ?>
   <tr style="background: #e0e545;">
    <td style="padding: 14px;"><?php echo $column[0]; ?></td>
    <td style="padding: 14px;"><?php echo $column[1]; ?></td>
     <td style="padding: 14px;"><?php echo $column[2]; ?></td>
   </tr>
   <?php } ?>
</tbody>
</table>

I tested with these values

  <pre>
<?php
$agenda = array (array("montag","Lorem ipsum dolor sit amet","08:00"),array("montag","Lorem ipsum dolor sit amet","08:00"),array("montag","Lorem ipsum dolor sit amet","08:00"));

print_r($agenda);
?>
     </pre>


问:
How to compare a slice with a vector in Rust?
How do I compare an array slice with a vector in Rust? The code in question:

```<code>fn parse<R: io::Read>(reader: R, fixed: &[u8]) -> io::Result<bool> {
    let mut buf = vec![0; fixed.len()];
    match reader.read(&mut buf) {
        Ok(n) => Ok(n == fixed.len() && fixed == &mut buf),
        Err(e) => Err(e)
    }
}
</code>```

The error that I get:

error[E0277]: the trait bound `[u8]: std::cmp::PartialEq<std::vec::Vec<u8>>` is not satisfied
  --> src/main.rs:32:47
   |
32 |         Ok(n) => Ok(n == fixed.len() && fixed == &mut buf),
   |                                               ^^ can't compare `[u8]` with `std::vec::Vec<u8>`
   |
   = help: the trait `std::cmp::PartialEq<std::vec::Vec<u8>>` is not implemented for `[u8]`
```

The answer must be simple but it is eluding me.

答:
As the error message states:

the trait std::cmp::PartialEq<std::vec::Vec<u8>> is not implemented for [u8]

However, the opposite direction is implemented:

```<code>Ok(n) => Ok(n == fixed.len() && buf == fixed),
</code>```

Additionally, you will need to mark your parameter as mutable: mut reader: R.

Read::read_exact performs the n == fixed.len() check for you.

Allocating a vector full of zeroes is not as efficient as it could be. You could instead limit the input and read into a vector, allocating as you go:

```<code>fn parse<R>(reader: R, fixed: &[u8]) -> io::Result<bool>
where
    R: Read,
{
    let mut buf = Vec::with_capacity(fixed.len());
    reader
        .take(fixed.len() as u64)
        .read_to_end(&mut buf)
        .map(|_| buf == fixed)
}
</code>```

The implementation of equality for slices already compares the lengths of the two sides, so I've also removed that, while switching to using combinators.

Body:
How do I compare an array slice with a vector in Rust? The code in question:

fn parse<R: io::Read>(reader: R, fixed: &[u8]) -> io::Result<bool> {
    let mut buf = vec![0; fixed.len()];
    match reader.read(&mut buf) {
        Ok(n) => Ok(n == fixed.len() && fixed == &mut buf),
        Err(e) => Err(e)
    }
}

The error that I get:

error[E0277]: the trait bound `[u8]: std::cmp::PartialEq<std::vec::Vec<u8>>` is not satisfied
  --> src/main.rs:32:47
   |
32 |         Ok(n) => Ok(n == fixed.len() && fixed == &mut buf),
   |                                               ^^ can't compare `[u8]` with `std::vec::Vec<u8>`
   |
   = help: the trait `std::cmp::PartialEq<std::vec::Vec<u8>>` is not implemented for `[u8]`

The answer must be simple but it is eluding me.

Body:
As the error message states:

the trait std::cmp::PartialEq<std::vec::Vec<u8>> is not implemented for [u8]

However, the opposite direction is implemented:

Ok(n) => Ok(n == fixed.len() && buf == fixed),

Additionally, you will need to mark your parameter as mutable: mut reader: R.

Read::read_exact performs the n == fixed.len() check for you.

Allocating a vector full of zeroes is not as efficient as it could be. You could instead limit the input and read into a vector, allocating as you go:

fn parse<R>(reader: R, fixed: &[u8]) -> io::Result<bool>
where
    R: Read,
{
    let mut buf = Vec::with_capacity(fixed.len());
    reader
        .take(fixed.len() as u64)
        .read_to_end(&mut buf)
        .map(|_| buf == fixed)
}

The implementation of equality for slices already compares the lengths of the two sides, so I've also removed that, while switching to using combinators.


问:
Does Swift executable binary need the .swiftmodule, .swiftdoc and .build files to run?
I'm writing my Swift app for Ubuntu using Vapor. And my mission is to have the smallest Docker image for production. I've trimmed down my image significantly but I wanted to know, just out of curiosity, does my final executable need all the compiled .module, .doc and .build files in the same directory?

答:
tl;dr: No.

The folders/files you listed are byproducts of the build process and can be safely discarded.

When it comes to distribution, your application is just like any other Linux executable. You must have all dynamically linked libraries available on the target system.

These include the runtime libraries of the Swift toolchain plus any compiled C modules your application (or the framework beneath it) links with (*).

You can check the dependencies of the executable using the ldd command.
Some of them are available as packages, some of them will need to be copied to the target system manually.

(*) In case of a Vapor 2 application, such C modules are libCHTTP.so and libCSQLite.so, which are placed in your build folder.


问:
missing } after property list
I am trying to implement a content slider using jQuery in one of my website; however I keep getting this error:

```<code>missing } after property list
</code>```

Here is my code:

```<code><script type='text/javascript'>

featuredcontentslider.init({
id: 'slider1',
contentsource: ['inline', ''],
toc: '#increment',
nextprev: ['prev', 'next'],
revealtype: 'click',
enablefade: [true, 0.1],
autorotate: [true, 3000]
});
</script>
</code>```

When I click on view source in Firefox I found that the last curly bracket is missing but in the file the code is fine, and using firebug debug console I got this error:

```<code>missing } after property list
</code>```

I tried many things, searched for missing commas, eliminate most of the lines but could not find the source of the problem.

EDIT:
Firebug points to this line:

```<code>});
</code>```

as the one with error.

I just checked the script in IE8, Chrome and firefox and in all of the three broweser i get the code like this:

```<code><script type='text/javascript'>

featuredcontentslider.init({
id: 'slider1',
contentsource: ['inline', ''],
toc: '#increment',
nextprev: ['prev', 'next'],
revealtype: 'click',
enablefade: [true, 0.1],
autorotate: [true, 3000]
);  <---- notice the missing bracket
</script>
</code>```

I also tried to write one line only like so:

```<code>featuredcontentslider.init({  id: 'slider1'  });
</code>```

and still ended up with the same error. In localhost the script works fine, however in the actual website the script is functioning correctly.

I am wondering is there a possibility that other js code in the page might affect the behaviour of this one?

答:
Hmmm... this smells somewhat like a website cache error.

Perhaps the } was missing at one time, and even though you fixed it, your website is still serving the old file.

Have you tried:

clearing the cache in your browser? (to see if it's browser-side)

using curl or wget to view the raw javascript file (to see if there's a stale server-side cache)

Title: missing } after property list

Body:
I am trying to implement a content slider using jQuery in one of my website; however I keep getting this error:

missing } after property list

Here is my code:

When I click on view source in Firefox I found that the last curly bracket is missing but in the file the code is fine, and using firebug debug console I got this error:

missing } after property list

I tried many things, searched for missing commas, eliminate most of the lines but could not find the source of the problem.

EDIT:
Firebug points to this line:

});

as the one with error.

I just checked the script in IE8, Chrome and firefox and in all of the three broweser i get the code like this:

I also tried to write one line only like so:

featuredcontentslider.init({  id: 'slider1'  });

and still ended up with the same error. In localhost the script works fine, however in the actual website the script is functioning correctly.

I am wondering is there a possibility that other js code in the page might affect the behaviour of this one?


问:
Capturing first group and separately third + fourth group (REGEX)
I'm trying to create two separate regexes that capture two specific parts of a string:

Example string: 3027-20171110020655-test-5

I need to capture first: 3027 and second: test-5
The second group may not always have a hyphen in it.

I have so far created: [^\-]+
This creates 4 separate capture groups -- I'm not sure how to narrow it down further.

答:
You can use this regex using negated character classes and anchors:

```<code>^([^-]+)-[^-]*-([^-]+)(?:-([^-]+))?$
</code>```

Where last group is an optional match.

RegEx Demo

Body:
You can use this regex using negated character classes and anchors:

^([^-]+)-[^-]*-([^-]+)(?:-([^-]+))?$

Where last group is an optional match.

RegEx Demo


问:
Remove duplicates by multiple conditions
I have data where an individual (Name) appears multiple times in a eggphase category. I would like for there only to be one sample per individual but I don't just want to keep the first one the R finds. I would like to keep the one where the group appears most in all other categories. Hopefully my example helps make this clear.

```<code>library(tidyverse)
myDF <- read.table(text="Tissue Food Eggphase Name Group
  wb fl after Kia a
  wb fl after Kia c
  wb wf before Kia b
  wb fl before Lucy c
  wb fl after Lucy b
  wb fl after Lucy c
  wb fl yolkdep Jess c
  wb fl yolkdep Betty a
  wb fl yolkdep Betty b", header = TRUE)
</code>```

I would like to just keep the rows where Name appears once grouped by Tissue, Food and Eggphase BUT I want to select the row where Group appears in most if not all different eggphases (with the same Tissue and Food combinations).

```<code>   #results I want
  Tissue Food Eggphase  Name Group
1     wb   fl    after   Kia     c
2     wb   wf   before   Kia     b
3     wb   fl   before  Lucy     c
4     wb   fl    after  Lucy     c
5     wb   fl  yolkdep  Jess     c
6     wb   fl  yolkdep Betty     b
</code>```

I tried

```<code>one_bird <- myDF %>%
  distinct(Tissue, Food, Eggphase, Name, .keep_all = TRUE)
</code>```

but it only keeps the first entry

```<code>  Tissue Food Eggphase  Name Group
1     wb   fl    after   Kia     a
2     wb   wf   before   Kia     b
3     wb   fl   before  Lucy     c
4     wb   fl    after  Lucy     b
5     wb   fl  yolkdep  Jess     c
6     wb   fl  yolkdep Betty     b
</code>```

Any ideas in how to tell it select the row where Groupappears in most (if not all) of the eggphases within a Tissue Food combination?
In my example the group that appears the most within the Tissue and Food combination of wb and fl is c and b but Kia doesn't appear in Group b and so c is a better option. Like this example, my data has duplicates which are from groups which are not the most common Group, how do I make it choose next most common just for that row?

I hope I have made enough sense.

答:
I guess this post and answer should give me reason to learn dplyr and tidyverse, but since I've put in the effort to give a answer that works, here it is:</p>

```<code>myDF <- read.table(text="Tissue Food Eggphase Name Group
  wb fl after Kia a
  wb fl after Kia c
  wb wf before Kia b
  wb fl before Lucy c
  wb fl after Lucy b
  wb fl after Lucy c
  wb fl yolkdep Jess c
  wb fl yolkdep Betty a
  wb fl yolkdep Betty b", header = TRUE)

# I usually have the following setting active: options(stringsAsFactors=F)
# The following might error without such a setting

# Create a var that indicates a duplicate or a record with a duplicate
myDF$duplicate <- duplicated(myDF[,c('Name','Eggphase','Tissue','Food')])
myDF$duplicate <- ifelse(duplicated(myDF[,c('Name','Eggphase','Tissue','Food')],fromLast=T),yes=T, no=myDF$duplicate)

# Count eggphases by group
eggphaseCount <- with(myDF,aggregate(x=list(Group_phaseCt=Eggphase),by=list(Group=Group),FUN=function(x) length(unique(x))))
# Merge to DF
myDF <- merge(myDF,eggphaseCount,by='Group',all=T)

# Get the max # of egphases by name
scale <- with(myDF,aggregate(x=list(PhaseMax=Group_phaseCt),by=list(Name=Name),FUN=max))
# Add to DF
myDF <- merge(myDF,scale,by='Name',all=T)

# Take the ratio
myDF$bestRatio <- with(myDF,Group_phaseCt/PhaseMax)
# Keep only those that aren't a duplicate, or are a duplicate and have the highest ratio
myDF2 <- myDF[with(myDF,which(duplicate==FALSE | (duplicate==TRUE & bestRatio==1))),]
</code>```

Body:
I have data where an individual (Name) appears multiple times in a eggphase category. I would like for there only to be one sample per individual but I don't just want to keep the first one the R finds. I would like to keep the one where the group appears most in all other categories. Hopefully my example helps make this clear.

library(tidyverse)
myDF <- read.table(text="Tissue Food Eggphase Name Group
  wb fl after Kia a
  wb fl after Kia c
  wb wf before Kia b
  wb fl before Lucy c
  wb fl after Lucy b
  wb fl after Lucy c
  wb fl yolkdep Jess c
  wb fl yolkdep Betty a
  wb fl yolkdep Betty b", header = TRUE)

I would like to just keep the rows where Name appears once grouped by Tissue, Food and Eggphase BUT I want to select the row where Group appears in most if not all different eggphases (with the same Tissue and Food combinations).

   #results I want
  Tissue Food Eggphase  Name Group
1     wb   fl    after   Kia     c
2     wb   wf   before   Kia     b
3     wb   fl   before  Lucy     c
4     wb   fl    after  Lucy     c
5     wb   fl  yolkdep  Jess     c
6     wb   fl  yolkdep Betty     b

I tried

one_bird <- myDF %>%
  distinct(Tissue, Food, Eggphase, Name, .keep_all = TRUE)

but it only keeps the first entry

  Tissue Food Eggphase  Name Group
1     wb   fl    after   Kia     a
2     wb   wf   before   Kia     b
3     wb   fl   before  Lucy     c
4     wb   fl    after  Lucy     b
5     wb   fl  yolkdep  Jess     c
6     wb   fl  yolkdep Betty     b

Any ideas in how to tell it select the row where Groupappears in most (if not all) of the eggphases within a Tissue Food combination?
In my example the group that appears the most within the Tissue and Food combination of wb and fl is c and b but Kia doesn't appear in Group b and so c is a better option. Like this example, my data has duplicates which are from groups which are not the most common Group, how do I make it choose next most common just for that row?

I hope I have made enough sense.

Body:
I guess this post and answer should give me reason to learn dplyr and tidyverse, but since I've put in the effort to give a answer that works, here it is:

myDF <- read.table(text="Tissue Food Eggphase Name Group
  wb fl after Kia a
  wb fl after Kia c
  wb wf before Kia b
  wb fl before Lucy c
  wb fl after Lucy b
  wb fl after Lucy c
  wb fl yolkdep Jess c
  wb fl yolkdep Betty a
  wb fl yolkdep Betty b", header = TRUE)

# I usually have the following setting active: options(stringsAsFactors=F)
# The following might error without such a setting

# Create a var that indicates a duplicate or a record with a duplicate
myDF$duplicate <- duplicated(myDF[,c('Name','Eggphase','Tissue','Food')])
myDF$duplicate <- ifelse(duplicated(myDF[,c('Name','Eggphase','Tissue','Food')],fromLast=T),yes=T, no=myDF$duplicate)

# Count eggphases by group
eggphaseCount <- with(myDF,aggregate(x=list(Group_phaseCt=Eggphase),by=list(Group=Group),FUN=function(x) length(unique(x))))
# Merge to DF
myDF <- merge(myDF,eggphaseCount,by='Group',all=T)

# Get the max # of egphases by name
scale <- with(myDF,aggregate(x=list(PhaseMax=Group_phaseCt),by=list(Name=Name),FUN=max))
# Add to DF
myDF <- merge(myDF,scale,by='Name',all=T)

# Take the ratio
myDF$bestRatio <- with(myDF,Group_phaseCt/PhaseMax)
# Keep only those that aren't a duplicate, or are a duplicate and have the highest ratio
myDF2 <- myDF[with(myDF,which(duplicate==FALSE | (duplicate==TRUE & bestRatio==1))),]


问:
Mass downcase a field for all records in rails
When I first implemented a User model , I allowed the user to type upper or lowercase email for their login info. The problem is that its a mobile app, and sometimes autocaps happen so the user would not get authenticated. I've changed the CREATE method to downcase the email first. However, this causes people with existing accounts to not be consistent

So how can I add a migration to mass update the email field in the users table to downcase it?

答:
You can simply go with</p>

```<code>User.update_all('email = lower(email)')
</code>```

Body:
You can simply go with

User.update_all('email = lower(email)')


问:
Cannot assign foreign key with item ID
I am trying to auto assign a value to a foreign key, so that the model is automatically associated with another model. This is done when an entry is made by a form. I get the following error

```<code>ValueError at /nodiso/createaction/23/
Cannot assign "'23'": "LeadActions.lead" must be a "Leads" instance.
</code>```

This is the two models:

```<code>class Leads(models.Model):
    company = models.ManyToManyField(Company)
    user = models.ManyToManyField(settings.AUTH_USER_MODEL)
    name = models.CharField(max_length=265)
    email = models.EmailField(max_length=265)
    tel = models.IntegerField()
    dateenq = models.DateField(auto_now_add=True,null=True)

    def get_absolute_url(self):
      return reverse('nodisoapp:leadlist')

    def __str__(self):
       return self.name

class LeadActions(models.Model):
    lead = models.ForeignKey(Leads)
    name = models.CharField(max_length=265)
    crdate = models.DateField(auto_now_add=True)
    Duedate = models.DateField()
    creator = models.CharField(max_length=265)
    overdue = models.IntegerField(null=True,blank=True)

    def get_absolute_url(self):
      return reverse('nodisoapp:leadlist')

    def __str__(self):
      return self.name
</code>```

This is the View

```<code>class ActionCreateView(LoginRequiredMixin, generic.CreateView):
    login_url = '/scrty/login/'
    template_name = "nodiso/actioncreate.html"
    form_class = forms.LeadActionCreateForm
    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.lead = self.kwargs['pk']
        self.object.creator = self.request.user
        self.object.save()
        return super(LeadCreateView, self).form_valid(form)
</code>```

This is the model form

```<code>class LeadActionCreateForm(forms.ModelForm):
    class Meta:
        model = models.LeadActions
        fields = ['name','Duedate']
</code>```

I would appreciate the help.

答:
You have two problems here.

One, you need to use the lead_id field name if you have the PK of the related instance rather than an instance object.

Two, kwargs matched from the URI regexp are strings, while PK values are integers. Assuming your uris regexp is properly restrictive, you can just convert it using int. So combining the two:

```<code>self.object.lead = int(self.kwargs['pk'])
</code>```

Title: Cannot assign foreign key with item ID

Body:
I am trying to auto assign a value to a foreign key, so that the model is automatically associated with another model. This is done when an entry is made by a form. I get the following error

ValueError at /nodiso/createaction/23/
Cannot assign "'23'": "LeadActions.lead" must be a "Leads" instance.

This is the two models:

class Leads(models.Model):
    company = models.ManyToManyField(Company)
    user = models.ManyToManyField(settings.AUTH_USER_MODEL)
    name = models.CharField(max_length=265)
    email = models.EmailField(max_length=265)
    tel = models.IntegerField()
    dateenq = models.DateField(auto_now_add=True,null=True)

    def get_absolute_url(self):
      return reverse('nodisoapp:leadlist')

    def __str__(self):
       return self.name

class LeadActions(models.Model):
    lead = models.ForeignKey(Leads)
    name = models.CharField(max_length=265)
    crdate = models.DateField(auto_now_add=True)
    Duedate = models.DateField()
    creator = models.CharField(max_length=265)
    overdue = models.IntegerField(null=True,blank=True)

    def get_absolute_url(self):
      return reverse('nodisoapp:leadlist')

    def __str__(self):
      return self.name

This is the View

class ActionCreateView(LoginRequiredMixin, generic.CreateView):
    login_url = '/scrty/login/'
    template_name = "nodiso/actioncreate.html"
    form_class = forms.LeadActionCreateForm
    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.lead = self.kwargs['pk']
        self.object.creator = self.request.user
        self.object.save()
        return super(LeadCreateView, self).form_valid(form)

This is the model form

class LeadActionCreateForm(forms.ModelForm):
    class Meta:
        model = models.LeadActions
        fields = ['name','Duedate']

I would appreciate the help.

Body:
You have two problems here.

One, you need to use the lead_id field name if you have the PK of the related instance rather than an instance object.

Two, kwargs matched from the URI regexp are strings, while PK values are integers. Assuming your uris regexp is properly restrictive, you can just convert it using int. So combining the two:

self.object.lead = int(self.kwargs['pk'])


问:
VPN metrics in Cloudwatch
Recently I have configured the ALARM in Cloudwatch for tracking VPN Tunnel connection. It is well known that 0 indicates tunnel is DOWN and 1 indicates tunnel is UP. When Connection is down, I have seen some data points on the graph shown as 0.66, 0.75.

So what does that mean, is the connection is DOWN or UP?

答:
The correct statistic for each metric depends on your use case, and the underling metric.

From CloudWatch Concepts - Statistics

Statistics are metric data aggregations over specified periods of
  time. CloudWatch provides statistics based on the metric data points
  provided by your custom data or provided by other AWS services to
  CloudWatch. Aggregations are made using the namespace, metric name,
  dimensions, and the data point unit of measure, within the time period
  you specify. The following table describes the available statistics.

Given the VPN metric above, try using the Maximum or Minimum statistics for the alarm. You are using the Average statistic, which, as you noted, will not produce meaningful data for your use case.

Minimum

The lowest value observed during the specified period. You can use this value to determine low volumes of activity for your application.

Maximum

The highest value observed during the specified period. You can use this value to determine high volumes of activity for your application.

Title: VPN metrics in Cloudwatch


问:
spring cloud gateway and eureka server
I have been trying to find a running example of spring cloud gateway integrated with eureka server and also with some Hystrix examples but I could't find so far.
Are there any place where I could find it? I really would like to see spring cloud gateway in use, replacing my current Zuul API service.

Thanks!

答:
You can use Spring Cloud Gateway in conjunction with Spring Cloud Config and Spring Cloud Eureka. In such way, configuration of a Gateway may look like:

```<code>@Bean
public RouteLocator customRouteLocator(
   return Routes.locator()
        .route("admin")
        .predicate(path("/admin/**"))
        .filter(rewritePath("/admin/(?<segment>.*)", "/${segment}"))
        //.uri("http://localhost:3000")
        .uri("lb://admin") // as registered in Eureka
        .build();
}
</code>```

And, as was said by spencergibb, add the discovery capability:

```<code>@Bean
public DiscoveryClientRouteDefinitionLocator discoveryClientRouteLocator(DiscoveryClient discoveryClient) {
    return new DiscoveryClientRouteDefinitionLocator(discoveryClient);
}
</code>```

This is actual for Finchley.M3.

Title: spring cloud gateway and eureka server

Body:
You can use Spring Cloud Gateway in conjunction with Spring Cloud Config and Spring Cloud Eureka. In such way, configuration of a Gateway may look like:

@Bean
public RouteLocator customRouteLocator(
   return Routes.locator()
        .route("admin")
        .predicate(path("/admin/**"))
        .filter(rewritePath("/admin/(?<segment>.*)", "/${segment}"))
        //.uri("http://localhost:3000")
        .uri("lb://admin") // as registered in Eureka
        .build();
}

And, as was said by spencergibb, add the discovery capability:

@Bean
public DiscoveryClientRouteDefinitionLocator discoveryClientRouteLocator(DiscoveryClient discoveryClient) {
    return new DiscoveryClientRouteDefinitionLocator(discoveryClient);
}

This is actual for Finchley.M3.


问:
Re-enabling Microsoft Word Add-In after Error
We are developing a COM Add-In for Microsoft Word (only local, not for cloud usage). One of our customers had the problem, that each time he started Word, he had to manually activate the Add-In (Word Options > Add-Ins > Go... > tick the checkbox for the corresponding Add-In). I could reproduce this behavior by forcing an error in the Add-In coding which caused Word to crash. When starting Word the next time, I got the following message:

Of course I saw this message several times before. But: back then the consequence of clicking on "Yes" was that the Add-In was disabled. In that case it was sufficient to re-enable it one time (as described above). The next time the Add-In was started, you didn't have to enable it any more.

But now, additionally to disabling the Add-In, there is a registry key created. That key has the name of the Add-In and is located at the following path: HKEY_CURRENT_USER/SOFTWARE/Microsoft/Office/15.0/Word/AddInLoadTimes.

And it seems that this key causes the behavior described at the beginning. Because if I delete the key, start Word, enable the Add-In, close word, set the "LoadBehavior" key in the registry to "3" and then restart word, everything is fine again.

Now my question: is there a user-friendly alternative to enable the Add-In? Since the fewest of our users have administrative privileges, we cannot ask them to change some registry keys in order to fix the problem.

I hope that someone can help me with this.

Best regards

Timo

答:
The path we took to avoid this issue, was to check in the code any static initialize methods / properties (which are invoked when word tries to activates the addin), which potentially could throw exceptions (IO work, REST api requests ... etc) and added to them try / catch blogs with some notification to the user that the activation of the addin failed + logging of the exception.

Side Note: At the time we have struggled the same issue we could not find anything but the registry key which you have mention to resolve this behaviour, but we faced the same security restriction, so this was not an option.


问:
ASP.NET Core - MVC. Drop down populate issue
I'm using vs 2017 and chrome.

I have an ASP.Net Core MVC app. It has a drop down that isn't showing the items correctly. The items displayed should be: Comedy, Western and Romantic.

Here's the debug image. The items shows the array and the text {MvcMovie.Modesl.Genre} and as I click each, the item text shows as I want.

I select the genres from the database and return them as as List and cast it to a SelectList as that is what is it is rendered as HTML a  element with the collection of SelectListItem objects.

However, when I look at the Raw View, I only see the text {MvcMovie.Modesl.Genre} which is what is being shown in the drop down.

I populate the movieGenreVM and return it as a view in the Index action method.

```<code>      public IActionResult Index(string movieGenre, string searchStringEntered)
    {
        // A list of genre objects.
        SelectList genresList;

        // A list of movie objects.
        List<Movie> moviesList;

        // Instantiate the View model.
        var movieGenreVM = new MovieGenreViewModel();

        // Get a list of genres from the database.
        genresList = new SelectList(GetGenres(movieGenre));

        // Get a list of movies from the database.
        moviesList = GetMovies(searchStringEntered);

        // Sets the models property which is then used in the dropdown of Genres.
        movieGenreVM.genres = genresList;

        // Creates a List object.
        // Movie is populated from the database and used to generate an HTML table of loaded movies.
        movieGenreVM.movies = moviesList;

        // Passing the MovieGenreViewModel.
        // Return the IActionResult - the Index.cshtml. A view template to generate an HTML response to the browser.
        return View(movieGenreVM);
    }

namespace MvcMovie.Models
{
public class MovieGenreViewModel
{
    // A list of movies.
    public List<Movie> movies;

    // A SelectList containing the list of genres.
    public SelectList genres;

    // Contains the selected genre.
    public string movieGenre { get; set; }
  }
}
</code>```

The genre models is:

```<code>public class Genre
{
    public string MovieGenre { get; set; }

    // Constructor.
    public Genre()
    {
    }

    public Genre(string a_MovieGenre)
    {
        MovieGenre = a_MovieGenre;
    }
}
</code>```

Here's the population of the genre list code:

```<code>    // Create a list of genres.
    private List<Genre> _genre = new List<Genre>();

    public List<Genre> Genre
    {
        get
        {
            return _genre;
        }
    }

    public List<Genre> GetGenres(string movieGenre)
    {
        Boolean errorSw = false;

        // Declare the reader and initialize.
        SqlDataReader GenresDataReader = null;

        try
        {
            // Open the connection.
            dbFunc.OpenDB();

            // Get the list of distinct Genres by executing a stored procedure.
            SqlCommand GenresCmd = new SqlCommand("dbo.SelectGenres", dbFunc.objConn);
            GenresCmd.Parameters.Clear();
            GenresCmd.CommandType = CommandType.StoredProcedure;
            GenresCmd.Parameters.Add("@SearchText", SqlDbType.VarChar).Value = movieGenre;

            // Set the reader.
            GenresDataReader = GenresCmd.ExecuteReader();

            // Loop thru the results returned.
            while (GenresDataReader.Read())
            {
                // Add to the list of genres - creates a new row for the collection.
                Genre.Add(new Genre(GenresDataReader["Genre"].ToString()));
            }
        }
        catch (Exception ex)
        {
            errorSw = true;
        }
        finally
        {
            if (GenresDataReader != null)
            {
                GenresDataReader.Close();
            }

            dbFunc.CloseDB();
        }

        // Return the list of genre objects.
        return Genre;
    }
</code>```

Here's the view:

@model MvcMovie.Models.MovieGenreViewModel

@{
    ViewData["Title"] = "Index";
}

List of Movies

    Create New

<form asp-controller="Movies" asp-action="Index" method="get">

        @* A dropdown. *@
        <select asp-for="movieGenre" asp-items="Model.genres">
            <option value="">All</option>
        </select>

        Title: <input type="text" name="searchStringEntered">

        <input type="submit" value="Filter" />

</form>

@* Shows the list of movies. *@

                @Html.DisplayNameFor(model => model.movies[0].Title)

                @Html.DisplayNameFor(model => model.movies[0].ReleaseDate)

                @Html.DisplayNameFor(model => model.movies[0].Genre)

                @Html.DisplayNameFor(model => model.movies[0].Price)

                @Html.DisplayNameFor(model => model.movies[0].Rating)

        @foreach (var item in Model.movies) {

                    @Html.DisplayFor(modelItem => item.Title)

                    @Html.DisplayFor(modelItem => item.ReleaseDate)

                    @Html.DisplayFor(modelItem => item.Genre)

                    @Html.DisplayFor(modelItem => item.Price)

                    @Html.DisplayFor(modelItem => item.Rating)

                    Edit |
                    Details |
                    Delete

         }

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

<p>This tutorial is using Entity Framework but I am converting it to using ADO.net and stored procedures. The EF version of the drop down works fine.</p>

<p>Here is the the EF versions Index action method. The genre is just the text - no Id associated with it.</p>

```    public async Task<IActionResult> Index(string movieGenre, string searchStringEntered)
    {
        IQueryable<string> genreQuery = from m in _context.Movie
                                        orderby m.Genre
                                        select m.Genre;

        var movies = from m in _context.Movie
                     select m;

        if (!String.IsNullOrEmpty(searchStringEntered))
        {
            movies = movies.Where(s => s.Title.Contains(searchStringEntered));
        }

        if (!String.IsNullOrEmpty(movieGenre))
        {
            movies = movies.Where(x => x.Genre == movieGenre);
        }

        // Instantiate the model.
        var movieGenreVM = new MovieGenreViewModel();

        // The SelectList of genres is created by projecting the distinct genres.
        // Sets the models property which is then used in the dropdown of Genres.
        movieGenreVM.genres = new SelectList(await genreQuery.Distinct().ToListAsync());

        // Creates a List object.
        // Movie is populated from the database and used to generate an HTML table of loaded movies.
        movieGenreVM.movies = await movies.ToListAsync();

        return View(movieGenreVM);
    }
```

答:
From your screenshot,  it is clear that your SelectList is missing the DataTextField and DataValueField. So the SELECT tag helper do not know which property should be used for the text and which should be used for Value.

The solution is to specifiy it when you create the SelectList object.Since your Genre entity class has only one property MovieGenre, you can use that for both Text and Value

```<code>var generesList = new SelectList(GetGenres(movieGenre),"MovieGenre","MovieGenre");
var vm=new MovieGenreViewModel { genres= generesList};
return View(vm);
</code>```

Now in your view, you can use Select tag helper with this genres property

```<code>@model MovieGenreViewModel
<select asp-for="movieGenre" asp-items="@Model.genres"></select>
</code>```

The select tag helper will use the DataValueField property value for the option value attribute and DataTextField property value for the option text.

Or Since you only have one property in your enter code hereGenre class, you can pass the list of strings to the SelectList constructor. The below will also work.

```<code>var gList=GetGenres(movieGenre);
var generesList = new SelectList(gList.Select(a=>a.MovieGenre));
var vm=new MovieGenreViewModel { genres= generesList};
return View(vm);
</code>```

Here is a post explaining different options to use the SELECT tag helper, for your reference

Select Tag Helper in ASP.NET Core MVC

Body:
I'm using vs 2017 and chrome.

I have an ASP.Net Core MVC app. It has a drop down that isn't showing the items correctly. The items displayed should be: Comedy, Western and Romantic.

Here's the debug image. The items shows the array and the text {MvcMovie.Modesl.Genre} and as I click each, the item text shows as I want.

I select the genres from the database and return them as as List and cast it to a SelectList as that is what is it is rendered as HTML a  element with the collection of SelectListItem objects.

However, when I look at the Raw View, I only see the text {MvcMovie.Modesl.Genre} which is what is being shown in the drop down.

I populate the movieGenreVM and return it as a view in the Index action method.

      public IActionResult Index(string movieGenre, string searchStringEntered)
    {
        // A list of genre objects.
        SelectList genresList;

        // A list of movie objects.
        List<Movie> moviesList;

        // Instantiate the View model.
        var movieGenreVM = new MovieGenreViewModel();

        // Get a list of genres from the database.
        genresList = new SelectList(GetGenres(movieGenre));

        // Get a list of movies from the database.
        moviesList = GetMovies(searchStringEntered);

        // Sets the models property which is then used in the dropdown of Genres.
        movieGenreVM.genres = genresList;

        // Creates a List object.
        // Movie is populated from the database and used to generate an HTML table of loaded movies.
        movieGenreVM.movies = moviesList;

        // Passing the MovieGenreViewModel.
        // Return the IActionResult - the Index.cshtml. A view template to generate an HTML response to the browser.
        return View(movieGenreVM);
    }

namespace MvcMovie.Models
{
public class MovieGenreViewModel
{
    // A list of movies.
    public List<Movie> movies;

    // A SelectList containing the list of genres.
    public SelectList genres;

    // Contains the selected genre.
    public string movieGenre { get; set; }
  }
}

The genre models is:

public class Genre
{
    public string MovieGenre { get; set; }

    // Constructor.
    public Genre()
    {
    }

    public Genre(string a_MovieGenre)
    {
        MovieGenre = a_MovieGenre;
    }
}

Here's the population of the genre list code:

    // Create a list of genres.
    private List<Genre> _genre = new List<Genre>();

    public List<Genre> Genre
    {
        get
        {
            return _genre;
        }
    }

    public List<Genre> GetGenres(string movieGenre)
    {
        Boolean errorSw = false;

        // Declare the reader and initialize.
        SqlDataReader GenresDataReader = null;

        try
        {
            // Open the connection.
            dbFunc.OpenDB();

            // Get the list of distinct Genres by executing a stored procedure.
            SqlCommand GenresCmd = new SqlCommand("dbo.SelectGenres", dbFunc.objConn);
            GenresCmd.Parameters.Clear();
            GenresCmd.CommandType = CommandType.StoredProcedure;
            GenresCmd.Parameters.Add("@SearchText", SqlDbType.VarChar).Value = movieGenre;

            // Set the reader.
            GenresDataReader = GenresCmd.ExecuteReader();

            // Loop thru the results returned.
            while (GenresDataReader.Read())
            {
                // Add to the list of genres - creates a new row for the collection.
                Genre.Add(new Genre(GenresDataReader["Genre"].ToString()));
            }
        }
        catch (Exception ex)
        {
            errorSw = true;
        }
        finally
        {
            if (GenresDataReader != null)
            {
                GenresDataReader.Close();
            }

            dbFunc.CloseDB();
        }

        // Return the list of genre objects.
        return Genre;
    }

Here's the view:

@model MvcMovie.Models.MovieGenreViewModel

@{
    ViewData["Title"] = "Index";
}

List of Movies

    Create New

<form asp-controller="Movies" asp-action="Index" method="get">

        @* A dropdown. *@
        <select asp-for="movieGenre" asp-items="Model.genres">
            <option value="">All</option>
        </select>

        Title: <input type="text" name="searchStringEntered">

        <input type="submit" value="Filter" />

</form>

@* Shows the list of movies. *@

                @Html.DisplayNameFor(model => model.movies[0].Title)

                @Html.DisplayNameFor(model => model.movies[0].ReleaseDate)

                @Html.DisplayNameFor(model => model.movies[0].Genre)

                @Html.DisplayNameFor(model => model.movies[0].Price)

                @Html.DisplayNameFor(model => model.movies[0].Rating)

        @foreach (var item in Model.movies) {

                    @Html.DisplayFor(modelItem => item.Title)

                    @Html.DisplayFor(modelItem => item.ReleaseDate)

                    @Html.DisplayFor(modelItem => item.Genre)

                    @Html.DisplayFor(modelItem => item.Price)

                    @Html.DisplayFor(modelItem => item.Rating)

                    Edit |
                    Details |
                    Delete

         }

This tutorial is using Entity Framework but I am converting it to using ADO.net and stored procedures. The EF version of the drop down works fine.

Here is the the EF versions Index action method. The genre is just the text - no Id associated with it.

    public async Task<IActionResult> Index(string movieGenre, string searchStringEntered)
    {
        IQueryable<string> genreQuery = from m in _context.Movie
                                        orderby m.Genre
                                        select m.Genre;

        var movies = from m in _context.Movie
                     select m;

        if (!String.IsNullOrEmpty(searchStringEntered))
        {
            movies = movies.Where(s => s.Title.Contains(searchStringEntered));
        }

        if (!String.IsNullOrEmpty(movieGenre))
        {
            movies = movies.Where(x => x.Genre == movieGenre);
        }

        // Instantiate the model.
        var movieGenreVM = new MovieGenreViewModel();

        // The SelectList of genres is created by projecting the distinct genres.
        // Sets the models property which is then used in the dropdown of Genres.
        movieGenreVM.genres = new SelectList(await genreQuery.Distinct().ToListAsync());

        // Creates a List object.
        // Movie is populated from the database and used to generate an HTML table of loaded movies.
        movieGenreVM.movies = await movies.ToListAsync();

        return View(movieGenreVM);
    }

Body:
From your screenshot,  it is clear that your SelectList is missing the DataTextField and DataValueField. So the SELECT tag helper do not know which property should be used for the text and which should be used for Value.

The solution is to specifiy it when you create the SelectList object.Since your Genre entity class has only one property MovieGenre, you can use that for both Text and Value

var generesList = new SelectList(GetGenres(movieGenre),"MovieGenre","MovieGenre");
var vm=new MovieGenreViewModel { genres= generesList};
return View(vm);

Now in your view, you can use Select tag helper with this genres property

@model MovieGenreViewModel
<select asp-for="movieGenre" asp-items="@Model.genres"></select>

The select tag helper will use the DataValueField property value for the option value attribute and DataTextField property value for the option text.

Or Since you only have one property in your enter code hereGenre class, you can pass the list of strings to the SelectList constructor. The below will also work.

var gList=GetGenres(movieGenre);
var generesList = new SelectList(gList.Select(a=>a.MovieGenre));
var vm=new MovieGenreViewModel { genres= generesList};
return View(vm);

Here is a post explaining different options to use the SELECT tag helper, for your reference

Select Tag Helper in ASP.NET Core MVC