问:
Find the LIS with the maximum sum
I have this code for finding the Longest Increasing Subsequence (LIS) but when i test my code I dont get maximum sum, for example:

if I type 20 1 4 3 10 the answer is 1 3 10, but i need 1 4 10
This is my code in C:

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

#define INT_INF 1000

int search_replace(int *lis, int left, int right, int key) {
    int mid;

    for (mid = (left+right)/2; left <= right; mid = (left+right)/2) {
            if (lis[mid] > key) {
                    right = mid - 1;
            } else if (lis[mid] == key) {
                    return mid;
            } else if (mid+1 <= right && lis[mid+1] >= key) {
                    lis[mid+1] = key;
                    return mid+1;
            } else {
                    left = mid + 1;
            }
    }
    if (mid == left) {
            lis[mid] = key;
            return mid;
    }
    lis[mid+1] = key;
    return mid+1;
}

int main() {
    int size, i;

    scanf(" %d", &size);

    int A[size];

    for(i = 0; i < size; i++){
        scanf(" %d", &A[i]);
    }

    int tmp, lis_length = -1;
    int *answer;
    int LIS[size];
    int index[size];

    LIS[0] = A[0];
    for (i = 1; i < size; ++i) {
            LIS[i] = INT_INF;
    }

    for (i = 1; i < size; ++i) {
            index[i] = search_replace(LIS, 0, i, A[i]);
            if (lis_length < index[i]) {
                    lis_length = index[i];
            }
    }

    answer = (int*) malloc((lis_length+1) * sizeof(int));
    for (i = size-1, tmp = lis_length; i >= 0; --i) {
            if (index[i] == tmp) {
                    answer[tmp] = A[i];
                    --tmp;
            }
    }

    printf("LIS: ");
    for (i = 0; i < lis_length+1; ++i) {
            printf("%d ", answer[i]);
    }
    printf("\n");

    return 0;
}
</code>```

first input is for number of elements in array.

I aleready tried with this post: Find the Longest Increasing Subsequence with the Maximum Sum , and few others but no success.

答:
I have analyzed your code and found your problem: you don't have code for finding the lis with maximum sum, you have the simple lis searching only. I have added the missing part and now, the code is working as it should. Also, I wrote my own solution, with another lis searching algorithm and without the binary search.

Note: the (left+right)/2 method for finding the middle value, have a problem - Nearly All Binary Searches and Mergesorts are Broken .

Your code with my addition:

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

#define INT_INF 1000

int search_replace(int *lis, int left, int right, int key) {
    int mid;
    for (mid = (left+right)/2; left <= right; mid = (left+right)/2) {
        if (lis[mid] > key) {
            right = mid - 1;
        } else if (lis[mid] == key) {
            return mid;
        } else if (mid+1 <= right && lis[mid+1] >= key) {
            lis[mid+1] = key;
            return mid+1;
        } else {
            left = mid + 1;
        }
    }
    if (mid == left) {
        lis[mid] = key;
        return mid;
    }
    lis[mid+1] = key;
    return mid+1;
}

int main() {
    int size, i;

    scanf(" %d", &size);

    int A[size];

    for(i = 0; i < size; i++){
        scanf(" %d", &A[i]);
    }

    int tmp, lis_length = -1;
    int LIS[size];
    int index[size];

    LIS[0] = A[0];
    for (i = 1; i < size; ++i) {
        LIS[i] = INT_INF;
    }

    for (i = 1; i < size; ++i) {
        index[i] = search_replace(LIS, 0, i, A[i]);
        if (lis_length < index[i]) {
            lis_length = index[i];
        }
    }

    //////// my addition starts
    int max, j;
    // INT_MAX - the maximum number of the integer type.
    // The "limits.h" header is needed for this.
    int prev = INT_MAX;
    int answer[lis_length + 1];
    // Iterating through the "index" values.
    // On the each iteration, the checking all sequences
    // with the same length
    // and determining the max value among them.
    // Starts from the lis_length and goes to the zero.
    for(i = lis_length; i >= 0; i--) {
        max = INT_MIN;
        for(j = 0; j < size; j++) {
            if(    index[j] == i
                && A[j] > max
                && A[j] < prev) {

                max = A[j];
            }
        }
        answer[i] = max;
        prev = max;
    }
    //////// my addition ends

    printf("LIS: ");
    for (i = 0; i < lis_length+1; ++i) {
        printf("%d ", answer[i]);
    }
    printf("\n");

    return 0;
}
</code>```

This is my solution with comments.

I used this algorithm for the lis determination. Ask questions, if you need.

```<code>#include <stdio.h>
#include <limits.h>

int main() {
    int size = 0;
    int arr_nums[100];
    // Initialize all array values to the one. This is the GCC feature.
    int seq_lens[100] = {[0 ... 99] = 1};

    // Gets input numbers.
    while(scanf("%d", arr_nums + size) == 1) {
        size++;
    }
    // Fill the seq_lens array with sequences's lenghts.
    int i, j;
    int lis_num = 1;
    for(i = 1; i < size; i++) {
        for(j = 0; j <= i; j++) {
            if(     arr_nums[i] > arr_nums[j]
                && (seq_lens[j] + 1 > seq_lens[i])) {

                    seq_lens[i] = seq_lens[j] + 1;
            }
        }
        // Finding the LIS number (the maximum sequence length).
        // If the previous LIS number is lesser then current,
        // change it to the current.
        if(lis_num < seq_lens[i])
            lis_num = seq_lens[i];
    }

    // Finding the LIS with the maximum sum
    int max;
    // INT_MAX - the maximum number of the integer type.
    // The "limits.h" header is needed for this.
    int prev = INT_MAX;
    int lis_arr[lis_num];
    // Iterating through the seq_lens values.
    // On the each iteration, the checking all sequences with the same length
    // and determining the max value among them.
    // Starts from the LIS (the longest sequence number)
    // and goes to the one (the minimum possible sequence number).
    for(i = lis_num; i > 0; i--) {
        max = INT_MIN;
        for(j = 0; j < size; j++) {
            if(    seq_lens[j] == i
                && arr_nums[j] > max
                && arr_nums[j] < prev) {

                max = arr_nums[j];
            }
        }
        lis_arr[i - 1] = max;
        prev = max;
    }

    printf("The longest increasing sequence number is:\n%d\n", lis_num);

    puts("\nThe longest increasing sequence with the max sum is: ");
    for(i = 0; i < lis_num; i++) {
        printf("%d ", lis_arr[i]);
    }
    puts("");

    return 0;
}
</code>```

Input

```<code>0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15
</code>```

Output

```<code>The longest increasing sequence number is:
6

The longest increasing sequence with the max sum is:
0 4 6 9 13 15
</code>```

Title: Find the LIS with the maximum sum

Body:
I have this code for finding the Longest Increasing Subsequence (LIS) but when i test my code I dont get maximum sum, for example:

if I type 20 1 4 3 10 the answer is 1 3 10, but i need 1 4 10
This is my code in C:

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

#define INT_INF 1000

int search_replace(int *lis, int left, int right, int key) {
    int mid;

    for (mid = (left+right)/2; left <= right; mid = (left+right)/2) {
            if (lis[mid] > key) {
                    right = mid - 1;
            } else if (lis[mid] == key) {
                    return mid;
            } else if (mid+1 <= right && lis[mid+1] >= key) {
                    lis[mid+1] = key;
                    return mid+1;
            } else {
                    left = mid + 1;
            }
    }
    if (mid == left) {
            lis[mid] = key;
            return mid;
    }
    lis[mid+1] = key;
    return mid+1;
}

int main() {
    int size, i;

    scanf(" %d", &size);

    int A[size];

    for(i = 0; i < size; i++){
        scanf(" %d", &A[i]);
    }

    int tmp, lis_length = -1;
    int *answer;
    int LIS[size];
    int index[size];

    LIS[0] = A[0];
    for (i = 1; i < size; ++i) {
            LIS[i] = INT_INF;
    }

    for (i = 1; i < size; ++i) {
            index[i] = search_replace(LIS, 0, i, A[i]);
            if (lis_length < index[i]) {
                    lis_length = index[i];
            }
    }

    answer = (int*) malloc((lis_length+1) * sizeof(int));
    for (i = size-1, tmp = lis_length; i >= 0; --i) {
            if (index[i] == tmp) {
                    answer[tmp] = A[i];
                    --tmp;
            }
    }

    printf("LIS: ");
    for (i = 0; i < lis_length+1; ++i) {
            printf("%d ", answer[i]);
    }
    printf("\n");

    return 0;
}

first input is for number of elements in array.

I aleready tried with this post: Find the Longest Increasing Subsequence with the Maximum Sum , and few others but no success.

Body:
I have analyzed your code and found your problem: you don't have code for finding the lis with maximum sum, you have the simple lis searching only. I have added the missing part and now, the code is working as it should. Also, I wrote my own solution, with another lis searching algorithm and without the binary search.

Note: the (left+right)/2 method for finding the middle value, have a problem - Nearly All Binary Searches and Mergesorts are Broken .

Your code with my addition:

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

#define INT_INF 1000

int search_replace(int *lis, int left, int right, int key) {
    int mid;
    for (mid = (left+right)/2; left <= right; mid = (left+right)/2) {
        if (lis[mid] > key) {
            right = mid - 1;
        } else if (lis[mid] == key) {
            return mid;
        } else if (mid+1 <= right && lis[mid+1] >= key) {
            lis[mid+1] = key;
            return mid+1;
        } else {
            left = mid + 1;
        }
    }
    if (mid == left) {
        lis[mid] = key;
        return mid;
    }
    lis[mid+1] = key;
    return mid+1;
}

int main() {
    int size, i;

    scanf(" %d", &size);

    int A[size];

    for(i = 0; i < size; i++){
        scanf(" %d", &A[i]);
    }

    int tmp, lis_length = -1;
    int LIS[size];
    int index[size];

    LIS[0] = A[0];
    for (i = 1; i < size; ++i) {
        LIS[i] = INT_INF;
    }

    for (i = 1; i < size; ++i) {
        index[i] = search_replace(LIS, 0, i, A[i]);
        if (lis_length < index[i]) {
            lis_length = index[i];
        }
    }

    //////// my addition starts
    int max, j;
    // INT_MAX - the maximum number of the integer type.
    // The "limits.h" header is needed for this.
    int prev = INT_MAX;
    int answer[lis_length + 1];
    // Iterating through the "index" values.
    // On the each iteration, the checking all sequences
    // with the same length
    // and determining the max value among them.
    // Starts from the lis_length and goes to the zero.
    for(i = lis_length; i >= 0; i--) {
        max = INT_MIN;
        for(j = 0; j < size; j++) {
            if(    index[j] == i
                && A[j] > max
                && A[j] < prev) {

                max = A[j];
            }
        }
        answer[i] = max;
        prev = max;
    }
    //////// my addition ends

    printf("LIS: ");
    for (i = 0; i < lis_length+1; ++i) {
        printf("%d ", answer[i]);
    }
    printf("\n");

    return 0;
}

This is my solution with comments.

I used this algorithm for the lis determination. Ask questions, if you need.

#include <stdio.h>
#include <limits.h>

int main() {
    int size = 0;
    int arr_nums[100];
    // Initialize all array values to the one. This is the GCC feature.
    int seq_lens[100] = {[0 ... 99] = 1};

    // Gets input numbers.
    while(scanf("%d", arr_nums + size) == 1) {
        size++;
    }
    // Fill the seq_lens array with sequences's lenghts.
    int i, j;
    int lis_num = 1;
    for(i = 1; i < size; i++) {
        for(j = 0; j <= i; j++) {
            if(     arr_nums[i] > arr_nums[j]
                && (seq_lens[j] + 1 > seq_lens[i])) {

                    seq_lens[i] = seq_lens[j] + 1;
            }
        }
        // Finding the LIS number (the maximum sequence length).
        // If the previous LIS number is lesser then current,
        // change it to the current.
        if(lis_num < seq_lens[i])
            lis_num = seq_lens[i];
    }

    // Finding the LIS with the maximum sum
    int max;
    // INT_MAX - the maximum number of the integer type.
    // The "limits.h" header is needed for this.
    int prev = INT_MAX;
    int lis_arr[lis_num];
    // Iterating through the seq_lens values.
    // On the each iteration, the checking all sequences with the same length
    // and determining the max value among them.
    // Starts from the LIS (the longest sequence number)
    // and goes to the one (the minimum possible sequence number).
    for(i = lis_num; i > 0; i--) {
        max = INT_MIN;
        for(j = 0; j < size; j++) {
            if(    seq_lens[j] == i
                && arr_nums[j] > max
                && arr_nums[j] < prev) {

                max = arr_nums[j];
            }
        }
        lis_arr[i - 1] = max;
        prev = max;
    }

    printf("The longest increasing sequence number is:\n%d\n", lis_num);

    puts("\nThe longest increasing sequence with the max sum is: ");
    for(i = 0; i < lis_num; i++) {
        printf("%d ", lis_arr[i]);
    }
    puts("");

    return 0;
}

Input

0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15

Output

The longest increasing sequence number is:
6

The longest increasing sequence with the max sum is:
0 4 6 9 13 15


来源: stackexchange

问:
Responsive layout not scrolling vertically in short screens
I have a site I designed and coded that seems to cut off top and bottom on very specific devices that have short screens AND WILL NOT SCROLL. Any ideas on that I can do to keep the picture centered in the browser without any overlapping

Here's a link to jsfiddle:
https://jsfiddle.net/SCATORY/mjyssu7y/

```<code><body>
<div id="container">
<div class="container">
<div class="nav">
    <div class="logo"></div>

</div>
</div>
    <div class="container holder">
    <div class="center">
    <div class="height">
    <h1>Practice yoga. <br>In hypo-microbial style.</h1>
    </div>
    <div class="bag">
    </div>
    <div class="height-2">
    <h2>Introducing ThePureBag™.<br>
The germ-resistant way to carry your yoga gear in style.</h2>
<div class="margin">
<a href="mailto:"><button class="contact">Contact Us</button></a>
</div>
</div>
</div>
    </div>
    </div>
    <div id="grey">
    </div>

</body>
</code>```

答:
Take the position:fixed off of the #container and take the position:absolute off of the .holder. This should make it work.

Position:fixed means that the element won't scroll.

ContentLicense: CC BY-SA 3.0

Body:
I have a site I designed and coded that seems to cut off top and bottom on very specific devices that have short screens AND WILL NOT SCROLL. Any ideas on that I can do to keep the picture centered in the browser without any overlapping

Here's a link to jsfiddle:
https://jsfiddle.net/SCATORY/mjyssu7y/

Practice yoga.
In hypo-microbial style.

Introducing ThePureBag™.

The germ-resistant way to carry your yoga gear in style.

<button class="contact">Contact Us</button>


问:
variable initialization error c++
Working on some code using arrays, however I keep getting the error "variable sized object may not be initialized" for the variables in the array even though I initialize them as 0 in the lines before. Here is a piece of my code where the error is.

```<code>int main(){
int x = 0;
int y = 0;
int items[x][y] = {}; //Here is where I get the error
for(string food; cin >> food; x++)
{
    items[x] = food;
    if(food == "done")
        cout << "Thank you for inputting.\n";
}
for(double price; cin >>price; y++)
{
    items[y] = price;
    if(price == 0)
    {
        double total;
        total += price;
    }
}
</code>```

Any help is appreciated. Thanks!

答:
Your code

```<code>int x = 0;
int y = 0;
int items[x][y] = {};
</code>```

defines a variable length array items, which is not supported in C++ standard, but only in particular extensions. To overcome this, you'd have to declare x and y as const (and with a value > 0, obviously).

But I think you're using the wrong data structure, since it seems that you want to associate a price with the name of a fruit. A map<string,double> is better suited for this task:

```<code>#include <iostream>
#include <map>

int main(){
    std::string food;
    std::map<std::string,double> priceForFood;
    std::cout << "enter food and price or quit to finish:" << std::endl;
    while(std::cin >> food && food != "quit") {
        double price;
        if (std::cin >> price) {
            priceForFood[food]=price;
        }
    }
    for (auto pair : priceForFood) {
        std::cout << pair.first << " cost " << pair.second << std::endl;
    }
    return 0;
}
</code>```

Input:

```<code>enter food and price or quit to finish:
apples 100
oranges 200
quit
</code>```

Output:

```<code>apples cost 100
oranges cost 200
Program ended with exit code: 0
</code>```

Title: variable initialization error c++

Body:
Working on some code using arrays, however I keep getting the error "variable sized object may not be initialized" for the variables in the array even though I initialize them as 0 in the lines before. Here is a piece of my code where the error is.

int main(){
int x = 0;
int y = 0;
int items[x][y] = {}; //Here is where I get the error
for(string food; cin >> food; x++)
{
    items[x] = food;
    if(food == "done")
        cout << "Thank you for inputting.\n";
}
for(double price; cin >>price; y++)
{
    items[y] = price;
    if(price == 0)
    {
        double total;
        total += price;
    }
}

Any help is appreciated. Thanks!

Body:
Your code

int x = 0;
int y = 0;
int items[x][y] = {};

defines a variable length array items, which is not supported in C++ standard, but only in particular extensions. To overcome this, you'd have to declare x and y as const (and with a value > 0, obviously).

But I think you're using the wrong data structure, since it seems that you want to associate a price with the name of a fruit. A map<string,double> is better suited for this task:

#include <iostream>
#include <map>

int main(){
    std::string food;
    std::map<std::string,double> priceForFood;
    std::cout << "enter food and price or quit to finish:" << std::endl;
    while(std::cin >> food && food != "quit") {
        double price;
        if (std::cin >> price) {
            priceForFood[food]=price;
        }
    }
    for (auto pair : priceForFood) {
        std::cout << pair.first << " cost " << pair.second << std::endl;
    }
    return 0;
}

Input:

enter food and price or quit to finish:
apples 100
oranges 200
quit

Output:

apples cost 100
oranges cost 200
Program ended with exit code: 0


问:
Need a different module name when using Python's Sphinx automodule directive
I have a file layout that looks like:

```<code>/my_module
    __init__.py
    submodule1.py
    submodule2.py
</code>```

I use Sphinx's automodule directive like:

```<code>.. automodule:: my_module.submodule1
</code>```

It produces documents that say my command name is something like: my_module.submodule1.my_function. But my __init__ pulls submodule1 into the my_module namespace. So what I really want is for the documentation to say my_module.my_function instead. Leave out the submodule1, since that's not what users are going to use.

Is there a way to do this?

答:
Not exactly, but you can get close.  There is the ~ (tilde) in standard cross-referencing syntax.

If you prefix the content with ~, the link text will only be the last component of the target. For example,

```<code>:py:meth:`~Queue.Queue.get`
</code>```

will refer to Queue.Queue.get but only display get as the link text. This does not work with all cross-reference roles, but is domain specific.

You might be able to use substitutions or the raw directive, but that would bypass the advantage of using autodoc and its directives.

Body:
I have a file layout that looks like:

/my_module
    __init__.py
    submodule1.py
    submodule2.py

I use Sphinx's automodule directive like:

.. automodule:: my_module.submodule1

It produces documents that say my command name is something like: my_module.submodule1.my_function. But my __init__ pulls submodule1 into the my_module namespace. So what I really want is for the documentation to say my_module.my_function instead. Leave out the submodule1, since that's not what users are going to use.

Is there a way to do this?

Body:
Not exactly, but you can get close.  There is the ~ (tilde) in standard cross-referencing syntax.

If you prefix the content with ~, the link text will only be the last component of the target. For example,

:py:meth:`~Queue.Queue.get`

will refer to Queue.Queue.get but only display get as the link text. This does not work with all cross-reference roles, but is domain specific.

You might be able to use substitutions or the raw directive, but that would bypass the advantage of using autodoc and its directives.


问:
(Spring) Can I use dependency injection inside a loop?
I am currently working on a Spring Boot application that allows users to save categories into a database. I can get my code to "work", however, I think it limits the amount of testing I can do, hence my question.

The controller receives a list of categories. The controller iterates over these categories, validates them and depending on whether they are valid, they are saved to a database. The controller finally returns a list of messages, such that the recipient can identify which category has been accepted or rejected, etc.

I have a list of model messages (List), which upon each iteration, the controller instantiates a new model message (new ModelMessage()) and eventually adds it to the List. Is there a way to inject a new ModelMessage upon each iteration or do I need to use the new keyword? If I do use the new keyword, I feel like this is limiting my testability/tightly coupling my controller to the model message.

The controller:

```<code>@PostMapping("/category")
    public String saveCategoryModelToDatabase(@RequestBody CategoryModelWrapper categoryModelWrapper){
        List<CategoryModel> categoryModelList = categoryModelWrapper.getCategoryModelList();
        modelMessageList.clear();

        for(CategoryModel categoryModel : categoryModelList){
            //Resetting model
            modelMessage = new ModelMessage(); //This tightly couples my method to the ModelMessage class, which is bad for testing?
            //@Autowired modelMessage; <-- something like this? Inject a new ModelMessage with each iteration.
            modelMessage.setName(categoryModel.getName());

            //Resetting categoryModelErrors
            Errors categoryModelErrors = new BeanPropertyBindingResult(categoryModel, "categoryModel");
            categoryModelValidator.validate(categoryModel, categoryModelErrors);

            if(categoryModelErrors.hasErrors()){
                modelMessage.setStatus(ModelMessageStatusEnum.REJECTED);
                modelMessage.setReason(MODEL_MESSAGE_0004);
            }

            if(categoryModelService.save(categoryModel)){
                modelMessage.setStatus(ModelMessageStatusEnum.ACCEPTED);
            }
            else{
                modelMessage.setStatus(ModelMessageStatusEnum.REJECTED);
                modelMessage.setReason(MODEL_MESSAGE_0005);
            }
            modelMessageList.add(modelMessage);
        }

        return gson.toJson(modelMessageList);
    }
</code>```

An example of the response to the recipient:

```<code>[{"name":"Arts","status":"ACCEPTED"},{"name":"Business","status":"ACCEPTED"},{"name":"Gaming","status":"ACCEPTED"},{"name":"Deals","status":"REJECTED","reason":"Category rejected because of an unexpected exception, i.e. possibly due to duplicate keys."}]
</code>```

Thanks for any help :)

答: You could use the ApplicationContext, assuming you have access to it, as a factory for ModelMessage. But, is that really necessary?</p>

Body:
I am currently working on a Spring Boot application that allows users to save categories into a database. I can get my code to "work", however, I think it limits the amount of testing I can do, hence my question.

The controller receives a list of categories. The controller iterates over these categories, validates them and depending on whether they are valid, they are saved to a database. The controller finally returns a list of messages, such that the recipient can identify which category has been accepted or rejected, etc.

I have a list of model messages (List), which upon each iteration, the controller instantiates a new model message (new ModelMessage()) and eventually adds it to the List. Is there a way to inject a new ModelMessage upon each iteration or do I need to use the new keyword? If I do use the new keyword, I feel like this is limiting my testability/tightly coupling my controller to the model message.

The controller:

@PostMapping("/category")
    public String saveCategoryModelToDatabase(@RequestBody CategoryModelWrapper categoryModelWrapper){
        List<CategoryModel> categoryModelList = categoryModelWrapper.getCategoryModelList();
        modelMessageList.clear();

        for(CategoryModel categoryModel : categoryModelList){
            //Resetting model
            modelMessage = new ModelMessage(); //This tightly couples my method to the ModelMessage class, which is bad for testing?
            //@Autowired modelMessage; <-- something like this? Inject a new ModelMessage with each iteration.
            modelMessage.setName(categoryModel.getName());

            //Resetting categoryModelErrors
            Errors categoryModelErrors = new BeanPropertyBindingResult(categoryModel, "categoryModel");
            categoryModelValidator.validate(categoryModel, categoryModelErrors);

            if(categoryModelErrors.hasErrors()){
                modelMessage.setStatus(ModelMessageStatusEnum.REJECTED);
                modelMessage.setReason(MODEL_MESSAGE_0004);
            }

            if(categoryModelService.save(categoryModel)){
                modelMessage.setStatus(ModelMessageStatusEnum.ACCEPTED);
            }
            else{
                modelMessage.setStatus(ModelMessageStatusEnum.REJECTED);
                modelMessage.setReason(MODEL_MESSAGE_0005);
            }
            modelMessageList.add(modelMessage);
        }

        return gson.toJson(modelMessageList);
    }

An example of the response to the recipient:

[{"name":"Arts","status":"ACCEPTED"},{"name":"Business","status":"ACCEPTED"},{"name":"Gaming","status":"ACCEPTED"},{"name":"Deals","status":"REJECTED","reason":"Category rejected because of an unexpected exception, i.e. possibly due to duplicate keys."}]

Thanks for any help :)


问:
Django: Filter for get_foo_display in a Queryset
I've been trying to filter a queryset on a simple model but with no luck so far.

Here is my model:

```<code>class Country(models.Model):
    COUNTRY_CHOICES = (
        ('FR', _(u'France')),
        ('VE', _(u'Venezuela')),
    )

    code = models.CharField(max_length=2, choices=COUNTRY_CHOICES)

    def __unicode__(self):
        return self.get_code_display()
</code>```

And I would like to do something like:

```<code>Country.objects.filter(get_code_display__icontains="france")
Country.objects.filter(code__display__icontains="france")
Country.objects.filter(get_code_display__icontains="france")
</code>```

But none of those above are working. How do you filter on a field that has a choices attribute? I thought the overridden __unicode__ would help but I guess I'm missing something.

答:
You can't do this. filter works at the database level, and the database doesn't know anything about your long names. If you want to do filtering on a value, you need to store that value in the database.

An alternative is to translate the value back into the code, and filter on that:

```<code>country_reverse = dict((v, k) for k, v in COUNTRY_CHOICES)
Country.objects.filter(code=country_reverse['france'])
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I've been trying to filter a queryset on a simple model but with no luck so far.

Here is my model:

class Country(models.Model):
    COUNTRY_CHOICES = (
        ('FR', _(u'France')),
        ('VE', _(u'Venezuela')),
    )

    code = models.CharField(max_length=2, choices=COUNTRY_CHOICES)

    def __unicode__(self):
        return self.get_code_display()

And I would like to do something like:

Country.objects.filter(get_code_display__icontains="france")
Country.objects.filter(code__display__icontains="france")
Country.objects.filter(get_code_display__icontains="france")

But none of those above are working. How do you filter on a field that has a choices attribute? I thought the overridden __unicode__ would help but I guess I'm missing something.

Body:
You can't do this. filter works at the database level, and the database doesn't know anything about your long names. If you want to do filtering on a value, you need to store that value in the database.

An alternative is to translate the value back into the code, and filter on that:

country_reverse = dict((v, k) for k, v in COUNTRY_CHOICES)
Country.objects.filter(code=country_reverse['france'])


问:
Keras: Training loss decrases (accuracy increase) while validation loss increases (accuracy decrease)
I am working on a very sparse dataset with the point of predicting 6 classes.
I have tried working with a lot of models and architectures, but the problem remains the same.

When I start training, the acc for training will slowly start to increase and loss will decrease where as the validation will do the exact opposite.

I have really tried to deal with overfitting, and I simply cannot still believe that this is what is coursing this issue.

What have I tried

Transfer learning on VGG16:

exclude top layer and add dense layer with 256 units and 6 units softmax output layer

finetune the top CNN block

finetune the top 3-4 CNN blocks

To deal with overfitting I use heavy augmentation in Keras and dropout after the 256 dense layer with p=0.5.

Creating own CNN with VGG16-ish architecture:

including batch normalization wherever possible

L2 regularization on each CNN+dense layer

Dropout from anywhere between 0.5-0.8 after each CNN+dense+pooling layer

Heavy data augmentation in "on the fly" in Keras

Realising that perhaps I have too many free parameters:

decreasing the network to only contain 2 CNN blocks + dense + output.

dealing with overfitting in the same manner as above.

Without exception all training sessions are looking like this:
Training & Validation loss+accuracy

The last mentioned architecture looks like this:

```<code>    reg = 0.0001

    model = Sequential()

    model.add(Conv2D(8, (3, 3), input_shape=input_shape, padding='same',
            kernel_regularizer=regularizers.l2(reg)))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(0.7))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.5))

    model.add(Conv2D(16, (3, 3), input_shape=input_shape, padding='same',
            kernel_regularizer=regularizers.l2(reg)))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(0.7))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.5))

    model.add(Flatten())
    model.add(Dense(16, kernel_regularizer=regularizers.l2(reg)))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(0.5))

    model.add(Dense(6))
    model.add(Activation('softmax'))

    model.compile(loss='categorical_crossentropy', optimizer='SGD',metrics=['accuracy'])
</code>```

And the data is augmented by the generator in Keras and is loaded with flow_from_directory:

```<code>    train_datagen = ImageDataGenerator(rotation_range=10,
                                width_shift_range=0.05,
                                height_shift_range=0.05,
                                shear_range=0.05,
                                zoom_range=0.05,
                                rescale=1/255.,
                                fill_mode='nearest',
                                channel_shift_range=0.2*255)
    train_generator = train_datagen.flow_from_directory(
                train_data_dir,
                target_size=(img_width, img_height),
                batch_size=batch_size,
                shuffle = True,
                class_mode='categorical')

    validation_datagen = ImageDataGenerator(rescale=1/255.)
    validation_generator = validation_datagen.flow_from_directory(
                                            validation_data_dir,
                                            target_size=(img_width, img_height),
                                            batch_size=1,
                                            shuffle = True,
                                            class_mode='categorical')
</code>```

答:
What I can think of by analyzing your metric outputs (from the link you provided):

Seems to me that approximately near epoch 30 your model is starting to overfit. Therefore you can try stopping your training in that iteration, or well just train it for ~30 epochs (or the exact number). The Keras Callbacks may be useful here, specially the ModelCheckpoint to enable you to stop your training when desired (Ctrl +C) or when certain criteria is met. Here is an example of basic ModelCheckpoint use:

```<code>#save best True saves only if the metric improves
chk = ModelCheckpoint("myModel.h5", monitor='val_loss', save_best_only=False)
callbacks_list = [chk]
#pass callback on fit
history = model.fit(X, Y, ... , callbacks=callbacks_list)
</code>```

(Edit:) As suggested in comments, another option you have available is to use the EarlyStopping callback, where you can specify the minimum change tolerated and the 'patience' or epochs without such improvement before stopping the training. If using this, you have to pass it to the callbacks argument as explained before.

At the current setup you model has (and with the modifications you have tried) that point in your training seems to be the optimal training time for your case; training it further will bring no benefits to your model (in fact, will make it generalize worse).

Given you have tried several modifications, one thing you can do is to try to increase your Network Depth, to give it more capacity. Try adding more layers, one at a time, and check for improvements. Also, you usually you want to start with simpler models first, before attempting a multi-layer solution.

If a simple model doesn't work, add one layer and test again, repeating until satisfied or possible. And by simple I mean really simple, have you tried a non-convolutional approach? Although CNN are great for images, maybe you are overkilling it here.

If nothing seems to work, maybe it is time to get more data, or to generate more data from the one you have by sampling or other techniques. For that last suggestion, try checking this keras blog I have found really useful. Deep learning algorithms usually require substantial amount of training data, specially for complex models, like images, so be aware this may not be an easy task. Hope this helps.

Body:
I am working on a very sparse dataset with the point of predicting 6 classes.
I have tried working with a lot of models and architectures, but the problem remains the same.

When I start training, the acc for training will slowly start to increase and loss will decrease where as the validation will do the exact opposite.

I have really tried to deal with overfitting, and I simply cannot still believe that this is what is coursing this issue.

What have I tried

Transfer learning on VGG16:

exclude top layer and add dense layer with 256 units and 6 units softmax output layer

finetune the top CNN block

finetune the top 3-4 CNN blocks

To deal with overfitting I use heavy augmentation in Keras and dropout after the 256 dense layer with p=0.5.

Creating own CNN with VGG16-ish architecture:

including batch normalization wherever possible

L2 regularization on each CNN+dense layer

Dropout from anywhere between 0.5-0.8 after each CNN+dense+pooling layer

Heavy data augmentation in "on the fly" in Keras

Realising that perhaps I have too many free parameters:

decreasing the network to only contain 2 CNN blocks + dense + output.

dealing with overfitting in the same manner as above.

Without exception all training sessions are looking like this:
Training & Validation loss+accuracy

The last mentioned architecture looks like this:

    reg = 0.0001

    model = Sequential()

    model.add(Conv2D(8, (3, 3), input_shape=input_shape, padding='same',
            kernel_regularizer=regularizers.l2(reg)))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(0.7))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.5))

    model.add(Conv2D(16, (3, 3), input_shape=input_shape, padding='same',
            kernel_regularizer=regularizers.l2(reg)))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(0.7))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.5))

    model.add(Flatten())
    model.add(Dense(16, kernel_regularizer=regularizers.l2(reg)))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(0.5))

    model.add(Dense(6))
    model.add(Activation('softmax'))

    model.compile(loss='categorical_crossentropy', optimizer='SGD',metrics=['accuracy'])

And the data is augmented by the generator in Keras and is loaded with flow_from_directory:

    train_datagen = ImageDataGenerator(rotation_range=10,
                                width_shift_range=0.05,
                                height_shift_range=0.05,
                                shear_range=0.05,
                                zoom_range=0.05,
                                rescale=1/255.,
                                fill_mode='nearest',
                                channel_shift_range=0.2*255)
    train_generator = train_datagen.flow_from_directory(
                train_data_dir,
                target_size=(img_width, img_height),
                batch_size=batch_size,
                shuffle = True,
                class_mode='categorical')

    validation_datagen = ImageDataGenerator(rescale=1/255.)
    validation_generator = validation_datagen.flow_from_directory(
                                            validation_data_dir,
                                            target_size=(img_width, img_height),
                                            batch_size=1,
                                            shuffle = True,
                                            class_mode='categorical')

Body:
What I can think of by analyzing your metric outputs (from the link you provided):

Seems to me that approximately near epoch 30 your model is starting to overfit. Therefore you can try stopping your training in that iteration, or well just train it for ~30 epochs (or the exact number). The Keras Callbacks may be useful here, specially the ModelCheckpoint to enable you to stop your training when desired (Ctrl +C) or when certain criteria is met. Here is an example of basic ModelCheckpoint use:

#save best True saves only if the metric improves
chk = ModelCheckpoint("myModel.h5", monitor='val_loss', save_best_only=False)
callbacks_list = [chk]
#pass callback on fit
history = model.fit(X, Y, ... , callbacks=callbacks_list)

(Edit:) As suggested in comments, another option you have available is to use the EarlyStopping callback, where you can specify the minimum change tolerated and the 'patience' or epochs without such improvement before stopping the training. If using this, you have to pass it to the callbacks argument as explained before.

At the current setup you model has (and with the modifications you have tried) that point in your training seems to be the optimal training time for your case; training it further will bring no benefits to your model (in fact, will make it generalize worse).

Given you have tried several modifications, one thing you can do is to try to increase your Network Depth, to give it more capacity. Try adding more layers, one at a time, and check for improvements. Also, you usually you want to start with simpler models first, before attempting a multi-layer solution.

If a simple model doesn't work, add one layer and test again, repeating until satisfied or possible. And by simple I mean really simple, have you tried a non-convolutional approach? Although CNN are great for images, maybe you are overkilling it here.

If nothing seems to work, maybe it is time to get more data, or to generate more data from the one you have by sampling or other techniques. For that last suggestion, try checking this keras blog I have found really useful. Deep learning algorithms usually require substantial amount of training data, specially for complex models, like images, so be aware this may not be an easy task. Hope this helps.


问:
Authenticate JWT with Guardian 1 and Phoenix 1.3
Ive made a project that can be found here:

https://github.com/rootkc/phx_auth_api

When I try to post to:

```<code>http://0.0.0.0:4000/api/login
</code>```

with the body:

```<code>{ "user": { "username": "kenneth", "password": "kenneth" } }
</code>```

That is a user that is in the database.
I get the response:

```<code>{
"data": {
    "token": "eyJhbGciOiJIUzUxM[...]gbPVHTsSvrCA"
}
</code>```

}

When i then put that token in the header:
Àuthorization: :token
of the call http://0.0.0.0:4000/api/users that has the Guardian pipeline plug
I get back the message: unauthenticated

And i have no idea, what i'm doing wrong. This is my first real Phoenix project and i tried to follow various guide but the {:guardian, "~> 1.0-beta"} seems to be quite new, with bad documentation.

答:
Believe or not, but Guardian is very well documented library and it's very popular for Elixir and Phoenix projects.

Please check this article for simple API authentication.

How exactly you wanted to put the header? You should use Guardian's already defined functions.

Guardian.encode_and_sign returns you {:ok, token, map} and you need this token to be passed to the header.
Then, guardian uses plug VerifyHeader that expects token to be in form

```<code>Authorization: token
</code>```

It's totally up to you how you want to mix up usage of guardian functions, but article from above is very nice introduction.

Edit
Assuming that you are running Elixir 1.5.x, you can try to run your server in IEx and then debug what's going on: iex -S mix phx.server. Simply use break! controller_name.action_name and try to click this action in webbrowser / postman etc.

Also you can debug Guardian functions this way.

Edit 2

In PhxAuthApi.Auth.Guardian you don't encode the token anywhere, but in PhxAuthApi.Auth.Pipeline you request that e.g. it has particular claims, but you didn't provide them.

You over engineered this auth by creating your custom modules that doesn't work properly.

Body:
Ive made a project that can be found here:

https://github.com/rootkc/phx_auth_api

When I try to post to:

http://0.0.0.0:4000/api/login

with the body:

{ "user": { "username": "kenneth", "password": "kenneth" } }

That is a user that is in the database.
I get the response:

{
"data": {
    "token": "eyJhbGciOiJIUzUxM[...]gbPVHTsSvrCA"
}

}

When i then put that token in the header:
Àuthorization: :token
of the call http://0.0.0.0:4000/api/users that has the Guardian pipeline plug
I get back the message: unauthenticated

And i have no idea, what i'm doing wrong. This is my first real Phoenix project and i tried to follow various guide but the {:guardian, "~> 1.0-beta"} seems to be quite new, with bad documentation.

Body:
Believe or not, but Guardian is very well documented library and it's very popular for Elixir and Phoenix projects.

Please check this article for simple API authentication.

How exactly you wanted to put the header? You should use Guardian's already defined functions.

Guardian.encode_and_sign returns you {:ok, token, map} and you need this token to be passed to the header.
Then, guardian uses plug VerifyHeader that expects token to be in form

Authorization: token

It's totally up to you how you want to mix up usage of guardian functions, but article from above is very nice introduction.

Edit
Assuming that you are running Elixir 1.5.x, you can try to run your server in IEx and then debug what's going on: iex -S mix phx.server. Simply use break! controller_name.action_name and try to click this action in webbrowser / postman etc.

Also you can debug Guardian functions this way.

Edit 2

In PhxAuthApi.Auth.Guardian you don't encode the token anywhere, but in PhxAuthApi.Auth.Pipeline you request that e.g. it has particular claims, but you didn't provide them.

You over engineered this auth by creating your custom modules that doesn't work properly.


问:
How do I fix this convergence error? Python 3 statsmodels
This question pertains to Python 3 statsmodels and its general linear model class.

Whenever I have an array of values for my endogenous variable such that the values are more than an order of magnitude apart, the GLM does not converge and it throws an exception. Here is a coded example of what I mean.

```<code>import pandas as pd
import pyarrow.parquet as pq
import numpy as np
import statsmodels.api as sm
import matplotlib.pyplot as plt
import math

col = ["a", \
       "b", \
       "c", \
       "d", \
       "e", \
       "f", \
       "g", \
       "h"]

df = pd.DataFrame(np.random.randint(low=1, high=100, size=(20, 8)), columns=col)
df["a"] = [0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01]
df2 = pd.DataFrame(np.random.randint(low=1, high=100, size=(20, 8)), columns=col)
df2["a"] = np.random.randint(low=10000, high=99999, size=(20, 1))
df3 = pd.DataFrame(np.random.randint(low=1, high=100, size=(20, 8)), columns=col)
df3["a"] = [0.01, \
            0.01, \
            0.01, \
            0.01, \
            0.01, \
            0.01, \
            np.random.randint(low=10000, high=99999), \
            0.01, \
            0.01, \
            0.01, \
            0.01, \
            0.01, \
            np.random.randint(low=10000, high=99999), \
            0.01, \
            0.01, \
            0.01, \
            0.01, \
            0.01, \
            0.01, \
            0.01]
try:
    actual = df[["a"]]

    fml1 = "a ~ log(b) + c + d + e + f + g"

    data1 = df[["b", "c", "d", "e", "f", "g"]]

    model = sm.GLM(actual, data1, formula=fml1, family=sm.families.Tweedie(link_power=1.1)).fit()
    model_pred = model.predict()
    print("SUCCESS")
except:
    print("FAILURE")
try:
    actual = df2[["a"]]

    fml1 = "a ~ log(b) + c + d + e + f + g"

    data1 = df2[["b", "c", "d", "e", "f", "g"]]

    model = sm.GLM(actual, data1, formula=fml1, family=sm.families.Tweedie(link_power=1.1)).fit()
    model_pred = model.predict()
    print("SUCCESS")
except:
    print("FAILURE")
try:
    actual = df3[["a"]]

    fml1 = "a ~ log(b) + c + d + e + f + g"

    data1 = df3[["b", "c", "d", "e", "f", "g"]]

    model = sm.GLM(actual, data1, formula=fml1, family=sm.families.Tweedie(link_power=1.1)).fit()
    model_pred = model.predict()
    print("SUCCESS")
except:
    print("FAILURE")
</code>```

If you run this code, you should get an exception only on the last set of data. Why is this? How do I get the GLM to converge? Are there alternatives?

答:
It seems that fitting parameters of Tweedie distributions is not easy. Indeed, a set of parameter  is valid only if for all observations  the positivity of the dot products is verified, i.e. , otherwise the value that is used in prediction is undefined as a negative real number cannot be elevated to a non-integer power value.

Hence in most optimizers, this relationship should be maintained across all iterations and it can be tough to maintain especially if the data contains values with different orders of magnitude.

Then, I see two main solutions to deal with this problem

The easiest one: Force your coefficients  to be positive. As in your case all observations  are positive you will remain in the feasible set. This can be done using Newton solver and a callback for example:

```<code>    model = sm.GLM(actual, data1, formula=fml1,
                   family=sm.families.Tweedie(link_power=1.1))

    def callback(x):
        x[x < 0] = 0

    result = model.fit(method='newton', disp=True, start_params=np.ones(6),
                       callback=callback)
</code>```

This will converge every time but will reach a solution in which all coefficients are positive, i.e. there is no inhibition effect.

Another solution might be looking at the conjugate solvers. For some reasons, they perform better with these constraints. This can be done using Conjugate Gradient "cg" and Newton Conjugate Gradient "ncg" methods.
They might not converge every time but chances are they will. You can play with the start_params vector it doesn't but it is not an exact science. In your case, you can try the following setting:

```<code>model = sm.GLM(actual, data1, formula=fml1,
               family=sm.families.Tweedie(link_power=1.1))
result = model.fit(method='cg', disp=True, start_params=0.1 * np.ones(6))
</code>```

PS: I'm not an expert on Tweedie distributions but I have been working on other Poisson like distributions that are facing the same problems.

Body:
This question pertains to Python 3 statsmodels and its general linear model class.

Whenever I have an array of values for my endogenous variable such that the values are more than an order of magnitude apart, the GLM does not converge and it throws an exception. Here is a coded example of what I mean.

import pandas as pd
import pyarrow.parquet as pq
import numpy as np
import statsmodels.api as sm
import matplotlib.pyplot as plt
import math

col = ["a", \
       "b", \
       "c", \
       "d", \
       "e", \
       "f", \
       "g", \
       "h"]

df = pd.DataFrame(np.random.randint(low=1, high=100, size=(20, 8)), columns=col)
df["a"] = [0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01]
df2 = pd.DataFrame(np.random.randint(low=1, high=100, size=(20, 8)), columns=col)
df2["a"] = np.random.randint(low=10000, high=99999, size=(20, 1))
df3 = pd.DataFrame(np.random.randint(low=1, high=100, size=(20, 8)), columns=col)
df3["a"] = [0.01, \
            0.01, \
            0.01, \
            0.01, \
            0.01, \
            0.01, \
            np.random.randint(low=10000, high=99999), \
            0.01, \
            0.01, \
            0.01, \
            0.01, \
            0.01, \
            np.random.randint(low=10000, high=99999), \
            0.01, \
            0.01, \
            0.01, \
            0.01, \
            0.01, \
            0.01, \
            0.01]
try:
    actual = df[["a"]]

    fml1 = "a ~ log(b) + c + d + e + f + g"

    data1 = df[["b", "c", "d", "e", "f", "g"]]

    model = sm.GLM(actual, data1, formula=fml1, family=sm.families.Tweedie(link_power=1.1)).fit()
    model_pred = model.predict()
    print("SUCCESS")
except:
    print("FAILURE")
try:
    actual = df2[["a"]]

    fml1 = "a ~ log(b) + c + d + e + f + g"

    data1 = df2[["b", "c", "d", "e", "f", "g"]]

    model = sm.GLM(actual, data1, formula=fml1, family=sm.families.Tweedie(link_power=1.1)).fit()
    model_pred = model.predict()
    print("SUCCESS")
except:
    print("FAILURE")
try:
    actual = df3[["a"]]

    fml1 = "a ~ log(b) + c + d + e + f + g"

    data1 = df3[["b", "c", "d", "e", "f", "g"]]

    model = sm.GLM(actual, data1, formula=fml1, family=sm.families.Tweedie(link_power=1.1)).fit()
    model_pred = model.predict()
    print("SUCCESS")
except:
    print("FAILURE")

If you run this code, you should get an exception only on the last set of data. Why is this? How do I get the GLM to converge? Are there alternatives?

Body:
It seems that fitting parameters of Tweedie distributions is not easy. Indeed, a set of parameter  is valid only if for all observations  the positivity of the dot products is verified, i.e. , otherwise the value that is used in prediction is undefined as a negative real number cannot be elevated to a non-integer power value.

Hence in most optimizers, this relationship should be maintained across all iterations and it can be tough to maintain especially if the data contains values with different orders of magnitude.

Then, I see two main solutions to deal with this problem

The easiest one: Force your coefficients  to be positive. As in your case all observations  are positive you will remain in the feasible set. This can be done using Newton solver and a callback for example:

    model = sm.GLM(actual, data1, formula=fml1,
                   family=sm.families.Tweedie(link_power=1.1))

    def callback(x):
        x[x < 0] = 0

    result = model.fit(method='newton', disp=True, start_params=np.ones(6),
                       callback=callback)

This will converge every time but will reach a solution in which all coefficients are positive, i.e. there is no inhibition effect.

Another solution might be looking at the conjugate solvers. For some reasons, they perform better with these constraints. This can be done using Conjugate Gradient "cg" and Newton Conjugate Gradient "ncg" methods.
They might not converge every time but chances are they will. You can play with the start_params vector it doesn't but it is not an exact science. In your case, you can try the following setting:

model = sm.GLM(actual, data1, formula=fml1,
               family=sm.families.Tweedie(link_power=1.1))
result = model.fit(method='cg', disp=True, start_params=0.1 * np.ones(6))

PS: I'm not an expert on Tweedie distributions but I have been working on other Poisson like distributions that are facing the same problems.


问:
Using Template Strings to get object property
// why it dont give output as soni, Angular 2 using typescript    </p>

```<code>let u = { lastname: 'soni' };
    let xx = '${u.lastname}';
    console.log(xx);
</code>```

答:
Use the other single quote:</p>

```<code>let xx = `${u.lastname}`;
</code>```

Body:
// why it dont give output as soni, Angular 2 using typescript

let u = { lastname: 'soni' };
    let xx = '${u.lastname}';
    console.log(xx);

Body:
Use the other single quote:

let xx = `${u.lastname}`;


问:
OutOfMemoryError while deploying after deploying container on AWS
I am trying to deploy an application (https://github.com/DivanteLtd/open-loyalty/) to amazon web services or AWS. This app has a docker-compose file. So, i am directly running 'ecs-cli compose up' from ecs-cli from my local machine.

It runs succesfully and runs all the containers, but after some time what it shows an error.

```<code>ExitCode: 137 Reason: OutOfMemoryError: Container killed due to memory usage
</code>```

I don't understand what's its for. Can you please help?

Thank You.

答:
Docker has an OOM-killer that lurks in the dark and is killing your instance.

This happens either because your container needs more memory than allowed in its mem_limit setting (defined in your aws compose yml file), or because your docker host is running out of memory.

You'd typically address this by tweaking the mem_limit settings for each of your containers and/or by switching to a larger EC2 instance.

Body:
I am trying to deploy an application (https://github.com/DivanteLtd/open-loyalty/) to amazon web services or AWS. This app has a docker-compose file. So, i am directly running 'ecs-cli compose up' from ecs-cli from my local machine.

It runs succesfully and runs all the containers, but after some time what it shows an error.

ExitCode: 137 Reason: OutOfMemoryError: Container killed due to memory usage

I don't understand what's its for. Can you please help?

Thank You.


问:
Exporting data from SCADA system
I am trying to create VBscript to export process data from a SCADA system (WinCC RT Professional) to periodically archive all process variables. The data are stored in SQL table that can be accessed through a connectivity pack. I managed to make the script working when exporting one tag (process variable), but I would like to loop over all tags in the system (about 60), collect them in another recordset and then all data from this recordset save in one csv-file. I have created RecSet that collects all variables (fields) of one tag (Time, Process Variable etc.), I only need values from Field 4 (the same field for all tags). I would then like to copy this field in another recordset - RecSetColl which collects all required data (Field 4) from all tags and finally save them in the CSV file. Thank you very much for any help.</p>

```<code>Sub DataExport()

Dim fso         'FileSystemObject
Dim f           'File
Dim ts          'TextStream
Dim path        'Path
Dim ArchiveDate 'Archive date

'Name of CSV-file
ArchiveDate = ArchiveDate & Now
ArchiveDate = Replace(ArchiveDate,"/","")
ArchiveDate = Replace(ArchiveDate," ","")
ArchiveDate = Replace(ArchiveDate,":","")
ArchiveDate = "MDF_" & ArchiveDate

'Path to the csv-file
path = "D:\Historical_data\" & ArchiveDate & ".csv"

'Create Filesystemobject and CSV-file if not exists:
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FileExists(path) Then
    fso.CreateTextFile(path)
Else
    MsgBox "File already exists!"
    Exit Sub
End If

'Create object and open it for writing
Set f = fso.GetFile(path)
Set ts = f.OpenAsTextStream(2,-2)

ts.WriteLine("Tag-Name;ValueID;Date/Time;Process-Value")    'Header

'Generate String for the CSV-Filename
Dim Pro         'Provider
Dim DSN         'Data Source Name
Dim DS          'Data Source
Dim ConnString  'Connection String
Dim MachineNameRT   'Name of the PC from WinCC-RT
Dim DSNRT       'Data Source Name from WinnCC-RT

Dim Conn        'Connection to ADODB
Dim RecSet      'RecordSet
Dim RecSetColl  'RecordSet storing data to be saved to the CSV-file
Dim Command     'Query
Dim CommandText 'Command-Text
Dim i

'Read the name of the PC-Station and the DSN-Name from WinCC-RT
Set MachineNameRT = HMIRuntime.Tags("@LocalMachineName")
Set DSNRT = HMIRuntime.Tags("@DatasourceNameRT")

'Preparing the Connection-String
Pro = "Provider=WinCCOLEDBProvider.1;"  'First instance of WinCCOLEDB
DSN = "Catalog=" & DSNRT.Read & ";"     'Name of Runtime-Database
DS = "Data Source=" & MachineNameRT.Read & "\WinCC" 'Data Source

'Build the complete String:
ConnString = Pro + DSN + DS

'Make Connection
Set Conn = CreateObject("ADODB.Connection")
Conn.ConnectionString = ConnString
Conn.CursorLocation = 3
Conn.open

Set RecSetColl = CreateObject("ADODB.Recordset")

With RecSetColl.Fields
    .Append "Time1", adChar
    .Append "AHU_RUN", adChar
    .Append "Time2", adChar
    .Append "TT01", adChar
    .Append "TT02", adChar
End With

For i = 0 To 4

    Set RecSet = CreateObject("ADODB.Recordset")
    Set Command = CreateObject("ADODB.Command")

    Command.CommandType = 1

    Set Command.ActiveConnection = Conn

    'Building the complete string
    CommandText = "Tag:R," & i & ",'0000-00-00 12:00:00.000','0000-00-00 00:00:00.000'"

    Command.CommandText = CommandText

    Set RecSet = Command.Execute

    RecSet.MoveFirst

    RecSetColl.Fields(i) = RecSet.Fields(4) 'RecSet.Fields(4) stores a proces value

    RecSet.Close
    Set RecSet = Nothing
    Set Command = Nothing
Next

'Writing recordsets to CSV-file
Do While Not RecSetColl.EOF
    ts.WriteLine (RecSetColl.Fields(0).Value & ";" & RecSetColl.Fields(1).Value & ";" & RecSetColl.Fields(2).Value & ";" & RecSetColl.Fields(3).Value & ";" & RecSetColl.Fields(4).Value & ";" & RecSetColl.Fields(5).Value)
    RecSetColl.MoveNext
Loop

RecSetColl.Close
Set RecSetColl = Nothing
Conn.close
Set Conn = Nothing

ts.Close
Set fso = Nothing
Set f = Nothing
Set ts = Nothing

End Sub
</code>```

答:
I do not really know whats not working, but a guess;

Does ValueID = 0 , (the "i" in the "for 0 to 4" ) exist in your project?

In the table "Archive" you will find the valid ValueIDs, starts with "1" in all my projects. It's simple to see in SQL Management Studio, perhaps sometimes 0 exist.

To get all the values exported, query the "Archive" table first and then ask for data in a loop using whatever ValueID's is returned.

//PerD

Title: Exporting data from SCADA system

Body:
I am trying to create VBscript to export process data from a SCADA system (WinCC RT Professional) to periodically archive all process variables. The data are stored in SQL table that can be accessed through a connectivity pack. I managed to make the script working when exporting one tag (process variable), but I would like to loop over all tags in the system (about 60), collect them in another recordset and then all data from this recordset save in one csv-file. I have created RecSet that collects all variables (fields) of one tag (Time, Process Variable etc.), I only need values from Field 4 (the same field for all tags). I would then like to copy this field in another recordset - RecSetColl which collects all required data (Field 4) from all tags and finally save them in the CSV file. Thank you very much for any help.

Sub DataExport()

Dim fso         'FileSystemObject
Dim f           'File
Dim ts          'TextStream
Dim path        'Path
Dim ArchiveDate 'Archive date

'Name of CSV-file
ArchiveDate = ArchiveDate & Now
ArchiveDate = Replace(ArchiveDate,"/","")
ArchiveDate = Replace(ArchiveDate," ","")
ArchiveDate = Replace(ArchiveDate,":","")
ArchiveDate = "MDF_" & ArchiveDate

'Path to the csv-file
path = "D:\Historical_data\" & ArchiveDate & ".csv"

'Create Filesystemobject and CSV-file if not exists:
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FileExists(path) Then
    fso.CreateTextFile(path)
Else
    MsgBox "File already exists!"
    Exit Sub
End If

'Create object and open it for writing
Set f = fso.GetFile(path)
Set ts = f.OpenAsTextStream(2,-2)

ts.WriteLine("Tag-Name;ValueID;Date/Time;Process-Value")    'Header

'Generate String for the CSV-Filename
Dim Pro         'Provider
Dim DSN         'Data Source Name
Dim DS          'Data Source
Dim ConnString  'Connection String
Dim MachineNameRT   'Name of the PC from WinCC-RT
Dim DSNRT       'Data Source Name from WinnCC-RT

Dim Conn        'Connection to ADODB
Dim RecSet      'RecordSet
Dim RecSetColl  'RecordSet storing data to be saved to the CSV-file
Dim Command     'Query
Dim CommandText 'Command-Text
Dim i

'Read the name of the PC-Station and the DSN-Name from WinCC-RT
Set MachineNameRT = HMIRuntime.Tags("@LocalMachineName")
Set DSNRT = HMIRuntime.Tags("@DatasourceNameRT")

'Preparing the Connection-String
Pro = "Provider=WinCCOLEDBProvider.1;"  'First instance of WinCCOLEDB
DSN = "Catalog=" & DSNRT.Read & ";"     'Name of Runtime-Database
DS = "Data Source=" & MachineNameRT.Read & "\WinCC" 'Data Source

'Build the complete String:
ConnString = Pro + DSN + DS

'Make Connection
Set Conn = CreateObject("ADODB.Connection")
Conn.ConnectionString = ConnString
Conn.CursorLocation = 3
Conn.open

Set RecSetColl = CreateObject("ADODB.Recordset")

With RecSetColl.Fields
    .Append "Time1", adChar
    .Append "AHU_RUN", adChar
    .Append "Time2", adChar
    .Append "TT01", adChar
    .Append "TT02", adChar
End With

For i = 0 To 4

    Set RecSet = CreateObject("ADODB.Recordset")
    Set Command = CreateObject("ADODB.Command")

    Command.CommandType = 1

    Set Command.ActiveConnection = Conn

    'Building the complete string
    CommandText = "Tag:R," & i & ",'0000-00-00 12:00:00.000','0000-00-00 00:00:00.000'"

    Command.CommandText = CommandText

    Set RecSet = Command.Execute

    RecSet.MoveFirst

    RecSetColl.Fields(i) = RecSet.Fields(4) 'RecSet.Fields(4) stores a proces value

    RecSet.Close
    Set RecSet = Nothing
    Set Command = Nothing
Next

'Writing recordsets to CSV-file
Do While Not RecSetColl.EOF
    ts.WriteLine (RecSetColl.Fields(0).Value & ";" & RecSetColl.Fields(1).Value & ";" & RecSetColl.Fields(2).Value & ";" & RecSetColl.Fields(3).Value & ";" & RecSetColl.Fields(4).Value & ";" & RecSetColl.Fields(5).Value)
    RecSetColl.MoveNext
Loop

RecSetColl.Close
Set RecSetColl = Nothing
Conn.close
Set Conn = Nothing

ts.Close
Set fso = Nothing
Set f = Nothing
Set ts = Nothing

End Sub


问:
Display info with PHP json_decode
I am trying to extract different info from a json returned output via json_decode, however I cannot seem to access the info:

JSON:

```<code>{"photos":{"page":1,"pages":8,"perpage":100,"total":"784","photo":[
{"id":"3453456456","owner":"1111111111@N03","secret":"xxxxxxxx","server":"4544","farm":5,"title":"XXXXXXX","ispublic":1,"isfriend":0,"isfamily":0},
{"id":"5468564564","owner":"1111111111@N03","secret":"xxxxxxxx","server":"4529","farm":5,"title":"XXXXXXX","ispublic":1,"isfriend":0,"isfamily":0},
</code>```

PHP:

```<code>$photos = json_decode($json);
foreach($photos as $photo){
$id = $photo->id;
$owner = $photo->owner;
$secret = $photo->secret;
echo $id.'<br/>';
echo $owner.'<br/>';
echo $secret.'<br/>';
}
</code>```

答:
Because of the depth of the JSON you have to start your loop at the right level. Here is an example:

```<code>$json = '{"photos":{"page":1,"pages":8,"perpage":100,"total":"784","photo":[
{"id":"3453456456","owner":"1111111111@N03","secret":"xxxxxxxx","server":"4544","farm":5,"title":"XXXXXXX","ispublic":1,"isfriend":0,"isfamily":0},
{"id":"5468564564","owner":"1111111111@N03","secret":"xxxxxxxx","server":"4529","farm":5,"title":"XXXXXXX","ispublic":1,"isfriend":0,"isfamily":0}]}}';

$photos = json_decode($json);

foreach($photos->photos->photo as $photo){
 $id = $photo->id;
 $owner = $photo->owner;
 $secret = $photo->secret;
 echo $id.'<br/>';
 echo $owner.'<br/>';
 echo $secret.'<br/>';
}
</code>```

Note the first level in your JSON is "photos" and the second is "photo".

Title: Display info with PHP json_decode

Body:
I am trying to extract different info from a json returned output via json_decode, however I cannot seem to access the info:

JSON:

{"photos":{"page":1,"pages":8,"perpage":100,"total":"784","photo":[
{"id":"3453456456","owner":"1111111111@N03","secret":"xxxxxxxx","server":"4544","farm":5,"title":"XXXXXXX","ispublic":1,"isfriend":0,"isfamily":0},
{"id":"5468564564","owner":"1111111111@N03","secret":"xxxxxxxx","server":"4529","farm":5,"title":"XXXXXXX","ispublic":1,"isfriend":0,"isfamily":0},

PHP:

$photos = json_decode($json);
foreach($photos as $photo){
$id = $photo->id;
$owner = $photo->owner;
$secret = $photo->secret;
echo $id.'
';
echo $owner.'
';
echo $secret.'
';
}

Body:
Because of the depth of the JSON you have to start your loop at the right level. Here is an example:

$json = '{"photos":{"page":1,"pages":8,"perpage":100,"total":"784","photo":[
{"id":"3453456456","owner":"1111111111@N03","secret":"xxxxxxxx","server":"4544","farm":5,"title":"XXXXXXX","ispublic":1,"isfriend":0,"isfamily":0},
{"id":"5468564564","owner":"1111111111@N03","secret":"xxxxxxxx","server":"4529","farm":5,"title":"XXXXXXX","ispublic":1,"isfriend":0,"isfamily":0}]}}';

$photos = json_decode($json);

foreach($photos->photos->photo as $photo){
 $id = $photo->id;
 $owner = $photo->owner;
 $secret = $photo->secret;
 echo $id.'<br/>';
 echo $owner.'<br/>';
 echo $secret.'<br/>';
}

Note the first level in your JSON is "photos" and the second is "photo".


问:
Maven build cannot find symbol when accessing project lombok annotated methods,
I'm using project lombok for the first time and I have problems compiling the project via maven when I run the build I receive errors where methods annotated with project lombok annotations are called.

This is the annotated parameter:

```<code>    private @Getter @Setter String paymentNonce = null;
</code>```

and in this line for example the maven breaks the build:

```<code>if (!StringUtilities.isNullOrEmpty(getPaymentNonce())) {
</code>```

this is my maven dependency

```<code><dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.4</version>
</dependency>
</code>```

the maven error:

```<code>[INFO] Compiling 158 source files to C:\java\repos\luna\cloudflow\cloudflow-ejb\target\classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] \java\repos\luna\cloudflow\cloudflow-ejb\src\main\java\si\arctur\controller\PaymentProcessor.java:[94,38] error: cannot find symbol
[ERROR] \java\repos\luna\cloudflow\cloudflow-ejb\src\main\java\si\arctur\controller\PaymentProcessor.java:[97,106] error: cannot find symbol
[ERROR] \java\repos\luna\cloudflow\cloudflow-ejb\src\main\java\si\arctur\controller\PaymentProcessor.java:[142,2] error: cannot find symbol
[ERROR] \java\repos\luna\cloudflow\cloudflow-ejb\src\main\java\si\arctur\controller\ShoppingCart.java:[27,6] error: cannot find symbol
[ERROR] \java\repos\luna\cloudflow\cloudflow-ejb\src\main\java\si\arctur\controller\ShoppingCart.java:[32,75] error: cannot find symbol
.....
</code>```

I'm using java 8

答: try to specify  parameter for "lombok" module within dependencies.I faced the same issue and resolved this by this work around.</p>

Body:
I'm using project lombok for the first time and I have problems compiling the project via maven when I run the build I receive errors where methods annotated with project lombok annotations are called.

This is the annotated parameter:

    private @Getter @Setter String paymentNonce = null;

and in this line for example the maven breaks the build:

if (!StringUtilities.isNullOrEmpty(getPaymentNonce())) {

this is my maven dependency

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.4</version>
</dependency>

the maven error:

[INFO] Compiling 158 source files to C:\java\repos\luna\cloudflow\cloudflow-ejb\target\classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] \java\repos\luna\cloudflow\cloudflow-ejb\src\main\java\si\arctur\controller\PaymentProcessor.java:[94,38] error: cannot find symbol
[ERROR] \java\repos\luna\cloudflow\cloudflow-ejb\src\main\java\si\arctur\controller\PaymentProcessor.java:[97,106] error: cannot find symbol
[ERROR] \java\repos\luna\cloudflow\cloudflow-ejb\src\main\java\si\arctur\controller\PaymentProcessor.java:[142,2] error: cannot find symbol
[ERROR] \java\repos\luna\cloudflow\cloudflow-ejb\src\main\java\si\arctur\controller\ShoppingCart.java:[27,6] error: cannot find symbol
[ERROR] \java\repos\luna\cloudflow\cloudflow-ejb\src\main\java\si\arctur\controller\ShoppingCart.java:[32,75] error: cannot find symbol
.....

I'm using java 8


问:
How to insert/store a string value in influxdb measurement?
I am trying to insert some string value in influx db but keep getting 400 error. I am iusing python requests module to connect to influxdb. Here is my code:

```<code>description = '"' + some_str + '"'
payload = "%s, name=%s, description=%s, count=%d %d" %(measurement, name, description,count,timestamp)
requests.post(influx_uri, data=payload, headers= headers)
</code>```

I keep getting this error:

```<code>400 {"error":"unable to parse 'sample,name=sample, description=\"some_str\", count=1 15106068120000000' : missing tag key"}
</code>```

I don't know how this is getting generated description=\"some_str\"

答:
OK. Another attempt.

By reading the docs there's no mention of putting quotes around long strings. Instead they say you should escape spaces with a backslash:

Escaping Characters

If a tag key, tag value, or field key contains a space , comma ,, or
  an equals sign = it must be escaped using the backslash character .
  Backslash characters do not need to be escaped. Commas , and spaces
  will also need to be escaped for measurements, though equals signs =
  do not.

Moreover you shouldn't have spaces after commas. So I suggest you try:

```<code>description = "some\ str"
payload = "%s,name=%s,description=%s,count=%d %d" % (measurement, name, description,count,timestamp)
</code>```

Body:
I am trying to insert some string value in influx db but keep getting 400 error. I am iusing python requests module to connect to influxdb. Here is my code:

description = '"' + some_str + '"'
payload = "%s, name=%s, description=%s, count=%d %d" %(measurement, name, description,count,timestamp)
requests.post(influx_uri, data=payload, headers= headers)

I keep getting this error:

400 {"error":"unable to parse 'sample,name=sample, description=\"some_str\", count=1 15106068120000000' : missing tag key"}

I don't know how this is getting generated description=\"some_str\"

Body:
OK. Another attempt.

By reading the docs there's no mention of putting quotes around long strings. Instead they say you should escape spaces with a backslash:

Escaping Characters

If a tag key, tag value, or field key contains a space , comma ,, or
  an equals sign = it must be escaped using the backslash character .
  Backslash characters do not need to be escaped. Commas , and spaces
  will also need to be escaped for measurements, though equals signs =
  do not.

Moreover you shouldn't have spaces after commas. So I suggest you try:

description = "some\ str"
payload = "%s,name=%s,description=%s,count=%d %d" % (measurement, name, description,count,timestamp)


问:
How can I generate database tables from C# classes?
Does anyone know a way to auto-generate database tables for a given class?  I'm not looking for an entire persistence layer - I already have a data access solution I'm using, but I suddenly have to store a lot of information from a large number of classes and I really don't want to have to create all these tables by hand.  For example, given the following class:

```<code>class Foo
{
    private string property1;
    public string Property1
    {
        get { return property1; }
        set { property1 = value; }
    }

    private int property2;
    public int Property2
    {
        get { return property2; }
        set { property2 = value; }
    }
}
</code>```

I'd expect the following SQL:

```<code>CREATE TABLE Foo
(
    Property1 VARCHAR(500),
    Property2 INT
)
</code>```

I'm also wondering how you could handle complex types.  For example, in the previously cited class, if we changed that to be :

```<code>class Foo
{
    private string property1;
    public string Property1
    {
        get { return property1; }
        set { property1 = value; }
    }

    private System.Management.ManagementObject property2;
    public System.Management.ManagementObject Property2
    {
        get { return property2; }
        set { property2 = value; }
    }
}
</code>```

How could I handle this?

I've looked at trying to auto-generate the database scripts by myself using reflection to enumerate through each class' properties, but it's clunky and the complex data types have me stumped.

答: I think for complex data types, you should extend them by specifying a ToDB() method which holds their own implementation for creating tables in the DB, and this way it becomes auto-recursive.</p>

OwnerDisplayName: VanOrman

Body:
Does anyone know a way to auto-generate database tables for a given class?  I'm not looking for an entire persistence layer - I already have a data access solution I'm using, but I suddenly have to store a lot of information from a large number of classes and I really don't want to have to create all these tables by hand.  For example, given the following class:

class Foo
{
    private string property1;
    public string Property1
    {
        get { return property1; }
        set { property1 = value; }
    }

    private int property2;
    public int Property2
    {
        get { return property2; }
        set { property2 = value; }
    }
}

I'd expect the following SQL:

CREATE TABLE Foo
(
    Property1 VARCHAR(500),
    Property2 INT
)

I'm also wondering how you could handle complex types.  For example, in the previously cited class, if we changed that to be :

class Foo
{
    private string property1;
    public string Property1
    {
        get { return property1; }
        set { property1 = value; }
    }

    private System.Management.ManagementObject property2;
    public System.Management.ManagementObject Property2
    {
        get { return property2; }
        set { property2 = value; }
    }
}

How could I handle this?

I've looked at trying to auto-generate the database scripts by myself using reflection to enumerate through each class' properties, but it's clunky and the complex data types have me stumped.

OwnerDisplayName: Vaibhav


问:
How to validate this scenario in ASP.NET MVC?
First, a little bit of context (cause I know you all love it!):

I have a model called Note. It has a field called Type which, in the database, is an integer value that designates which type of object this note belongs to (1 = Customer, 2 = Sales Lead, etc). A second field called Source designates the ID of the specific object that this note belongs to.

For example, if I wanted to add a note to Customer #34, I would set Type to 1 and Source to 34.

To help make things a little more readable, I have an Enum called DataObjectType that contains a mapping for each of the possible Type integer values to a friendly name. So, for example, DataObjectType.Customer is the same as a value of 1 in the Type field.

Next, I have a custom route:

```<code>/Notes/New/{type}/{id}
</code>```

and two controller actions to handle the creation of a new note:

```<code>[AcceptVerbs(HttpVerbs.Get)]
public ActionResult New(DataObjectType type, int id) {
    Note note = new Note { Type = type, Source = id };
    return View(note);
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Note note) {
    // This is just an example
    note.Persist();
    return View("New", note);
}
</code>```

First of all, I need to make sure that the value supplied to the {type} route value is valid for the DataObjectType enum. Can this be done with a route constraint? At the moment, the type argument of New() will accept any integer, whether it exists in DataObjectType or not.

Second, I need to make sure that the object the user is trying to add the note to actually exists in the database before showing the New Note form at all. I could do this in the New() method easily, but there may come a time when a user posts the data directly to Create() without ever visiting New(). In such a case, I also need to verify that the object exists in the Create() method. What's the best way to do this in both methods without duplicating code?

答:
You are correct that both the New and the Create actions need to ensure that they have a valid model passed to them. The correct place to do this is in a model binder. The model binder should add a model state error if an invalid object (or Id) is passed. New and Create can likely use the same model binder(s).

Don't confuse route constraints with user input validation. Route constraints simply help the routing system find the appropriate route when you don't specify the route yourself (i.e., when you use Html.ActionLink instead of RouteLink). If you use named routes, and you should, then the constraint is not needed to find the appropriate route, because you have specified the route directly. Route constraints are intended to prevent a certain route from being selected for actions it is not designed to handle, and are not the place to validate user input.

The feature you are asking for is a kind of user input validation, even though user input in question happens to be in the URL. If you are going to go beyond this simple, single case, you might want to look into using a validation framework, as this will make other types of validation much simpler. Here is one which looks interesting to me.

OwnerDisplayName: David Brown

Body:
First, a little bit of context (cause I know you all love it!):

I have a model called Note. It has a field called Type which, in the database, is an integer value that designates which type of object this note belongs to (1 = Customer, 2 = Sales Lead, etc). A second field called Source designates the ID of the specific object that this note belongs to.

For example, if I wanted to add a note to Customer #34, I would set Type to 1 and Source to 34.

To help make things a little more readable, I have an Enum called DataObjectType that contains a mapping for each of the possible Type integer values to a friendly name. So, for example, DataObjectType.Customer is the same as a value of 1 in the Type field.

Next, I have a custom route:

/Notes/New/{type}/{id}

and two controller actions to handle the creation of a new note:

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult New(DataObjectType type, int id) {
    Note note = new Note { Type = type, Source = id };
    return View(note);
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Note note) {
    // This is just an example
    note.Persist();
    return View("New", note);
}

First of all, I need to make sure that the value supplied to the {type} route value is valid for the DataObjectType enum. Can this be done with a route constraint? At the moment, the type argument of New() will accept any integer, whether it exists in DataObjectType or not.

Second, I need to make sure that the object the user is trying to add the note to actually exists in the database before showing the New Note form at all. I could do this in the New() method easily, but there may come a time when a user posts the data directly to Create() without ever visiting New(). In such a case, I also need to verify that the object exists in the Create() method. What's the best way to do this in both methods without duplicating code?

LastEditorDisplayName: David Brown

OwnerDisplayName: Craig Stuntz


问:
conditionally overriding/rewriting a class in magento
I know that I can override/rewrite a model class from my module using the following syntax in the config.xml for my module.:

```<code><config>
    <global>
        <models>
            <moduletooverride>
                <rewrite>
                    <modeltooverride>Mycompany_Mymodule_Model_Myfolder_Myclass</customer>
                </rewrite>
            </moduletooverride>
         </models>
     </global>
</config>
</code>```

But what if I want this to be conditional (e.g. based on some setting in my modules adminhtml configuration section?)

Is there any syntax for this?

Alternatively is there a way for my rewritten class to get to the class as it was before my rewrite? (to allow it to call its "predecessor".

答:
There's no built in configuration option that will allow you to conditionally rewrite a class like this.

However, a rewritten class is just an extended class, so all standard OOP rules apply, including using parent::  So something like

```<code>class My_Rewritten_Class extends Class_I_Rewrote
{

    public function theMethodIRewrote($param, $options)
    {
        $original_results = parent::theMethodIRewrote($param, $options);
        if(!Mage::getStoreConfigFlag('path/to_my/on_or_off_flag'))
        {
            return $original_results
        }

        //continue with the rewrite
    }
}
</code>```

Finally, although I've never tried it, you should be able to get a reference to to parsed config options with

```<code>$config->Mage::getConfig();
</code>```

And then manually set or unset your rewrite option using its setOptions method.

Body:
I know that I can override/rewrite a model class from my module using the following syntax in the config.xml for my module.:

<config>
    <global>
        <models>
            <moduletooverride>
                <rewrite>
                    <modeltooverride>Mycompany_Mymodule_Model_Myfolder_Myclass</customer>
                </rewrite>
            </moduletooverride>
         </models>
     </global>
</config>

But what if I want this to be conditional (e.g. based on some setting in my modules adminhtml configuration section?)

Is there any syntax for this?

Alternatively is there a way for my rewritten class to get to the class as it was before my rewrite? (to allow it to call its "predecessor".

Body:
There's no built in configuration option that will allow you to conditionally rewrite a class like this.

However, a rewritten class is just an extended class, so all standard OOP rules apply, including using parent::  So something like

class My_Rewritten_Class extends Class_I_Rewrote
{

    public function theMethodIRewrote($param, $options)
    {
        $original_results = parent::theMethodIRewrote($param, $options);
        if(!Mage::getStoreConfigFlag('path/to_my/on_or_off_flag'))
        {
            return $original_results
        }

        //continue with the rewrite
    }
}

Finally, although I've never tried it, you should be able to get a reference to to parsed config options with

$config->Mage::getConfig();

And then manually set or unset your rewrite option using its setOptions method.