问:
Trying to compare space complexities of 2 sorting algorithms. Don't know how to interpret the answer
I have 2 sorting algorithms, merge sort and insertion sort. I am trying to examine how much ram memory they allocate during execution, to do a comparison. Both are sorting an array of  1000 elements, integers between 0-999.

The programs are compiled to a binary called main (merge_sort/main and insertion_sort/main). So I am running:

```<code>memusage -T ./main
</code>```

on both algorithms.

both returns:

```<code>heap total: 73728, heap peak: 73728, stack peak: 6144
</code>```

Why does they return the same? Shouldn't merge sort allocate more memory than insertion sort? Am I even using memusage correct?

I have also tried to examine them using Valgrind, which also returns same for both:

```<code>==26544== HEAP SUMMARY:
==26544==     in use at exit: 0 bytes in 0 blocks
==26544==   total heap usage: 2 allocs, 2 frees, 73,728 bytes allocated
</code>```

My theory is: that either I dont know what I am doing,

or that the list that is sorted is to small. Therefore the memory usage looks the same.

Code:

Merge sort

```<code>/* C program for Merge Sort */
#include<stdlib.h>
#include<stdio.h>
#include<time.h>

// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
    int i, j, k;
    int n1 = m - l + 1;
    int n2 = r - m;

    /* create temp arrays */
    int L[n1], R[n2];

    /* Copy data to temp arrays L[] and R[] */
    for (i = 0; i < n1; i++)
        L[i] = arr[l + i];
    for (j = 0; j < n2; j++)
        R[j] = arr[m + 1+ j];

    /* Merge the temp arrays back into arr[l..r]*/
    i = 0; // Initial index of first subarray
    j = 0; // Initial index of second subarray
    k = l; // Initial index of merged subarray
    while (i < n1 && j < n2)
    {
        if (L[i] <= R[j])
        {
            arr[k] = L[i];
            i++;
        }
        else
        {
            arr[k] = R[j];
            j++;
        }
        k++;
    }

    /* Copy the remaining elements of L[], if there
    are any */
    while (i < n1)
    {
        arr[k] = L[i];
        i++;
        k++;
    }

    /* Copy the remaining elements of R[], if there
    are any */
    while (j < n2)
    {
        arr[k] = R[j];
        j++;
        k++;
    }
}

/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void mergeSort(int arr[], int l, int r)
{
    if (l < r)
    {
        // Same as (l+r)/2, but avoids overflow for
        // large l and h
        int m = l+(r-l)/2;

        // Sort first and second halves
        mergeSort(arr, l, m);
        mergeSort(arr, m+1, r);

        merge(arr, l, m, r);
    }
}

/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray(int A[], int size)
{
    int i;
    for (i=0; i < size; i++)
        printf("%d ", A[i]);
    printf("\n");
}

/* Driver program to test above functions */
int main()
{
    int arr[] = {
        397, 326, 157, 581, 198, 158, 107, 479, 919, 288, 118, 14, 384, 389, 354, 905, 648, 24, 639, 279, 846, 896, 901, 491, 827, 502, 119, 520, 544, 688, 433, 542, 280, 834, 574, 739, 168, 714, 367, 547, 555, 616, 71, 583, 77, 372, 380, 414, 80, 828, 671, 900, 710, 852, 810, 471, 493, 832, 310, 579, 605, 174, 19, 576, 162, 695, 635, 851, 265, 48, 536, 228, 754, 300, 610, 272, 619, 825, 770, 147, 9, 813, 525, 135, 768, 654, 889, 446, 910, 678, 432, 172, 618, 41, 839, 589, 304, 484, 765, 357, 427, 617, 75, 683, 930, 593, 341, 149, 733, 27, 556, 474, 987, 156, 501, 665, 370, 523, 142, 420, 114, 798, 989, 382, 543, 879, 294, 305, 684, 331, 443, 383, 625, 647, 780, 811, 34, 621, 744, 842, 150, 938, 301, 495, 965, 392, 634, 358, 570, 789, 266, 242, 709, 278, 932, 57, 952, 475, 984, 136, 133, 637, 734, 207, 697, 362, 344, 332, 89, 529, 188, 164, 124, 317, 103, 257, 514, 364, 356, 203, 112, 831, 867, 644, 815, 452, 456, 260, 291, 90, 13, 21, 160, 217, 251, 459, 213, 110, 455, 56, 753, 127, 349, 884, 434, 982, 224, 410, 104, 540, 640, 973, 486, 945, 201, 166, 99, 535, 229, 725, 361, 483, 190, 743, 998, 409, 159, 102, 55, 219, 720, 33, 971, 859, 335, 887, 538, 363, 557, 696, 11, 951, 51, 845, 231, 723, 569, 63, 903, 185, 406, 505, 833, 309, 49, 599, 788, 511, 990, 196, 324, 803, 247, 970, 440, 504, 627, 205, 656, 308, 948, 690, 551, 819, 988, 608, 67, 519, 907, 510, 603, 256, 597, 880, 893, 214, 95, 270, 915, 179, 298, 378, 550, 953, 717, 321, 992, 863, 796, 868, 604, 152, 368, 15, 284, 17, 925, 808, 799, 841, 946, 974, 450, 546, 682, 91, 666, 402, 283, 736, 567, 679, 125, 299, 319, 762, 849, 785, 264, 797, 623, 401, 689, 140, 461, 171, 454, 624, 853, 724, 191, 130, 86, 451, 87, 109, 38, 61, 413, 348, 289, 829, 969, 670, 528, 588, 937, 766, 885, 237, 823, 592, 184, 73, 239, 643, 180, 10, 195, 277, 787, 431, 562, 390, 338, 146, 638, 85, 424, 652, 2, 631, 685, 405, 35, 387, 912, 333, 740, 692, 769, 66, 554, 565, 926, 223, 322, 826, 657, 858, 703, 1, 986, 312, 246, 31, 577, 323, 145, 439, 375, 39, 170, 106, 478, 978, 716, 254, 756, 37, 360, 350, 463, 269, 52, 64, 386, 509, 997, 429, 379, 655, 916, 878, 553, 794, 807, 197, 16, 840, 947, 860, 920, 963, 70, 183, 572, 763, 192, 729, 340, 238, 209, 469, 151, 167, 292, 303, 129, 847, 749, 4, 218, 216, 924, 215, 784, 243, 394, 836, 782, 476, 268, 78, 54, 590, 81, 908, 23, 704, 428, 778, 976, 680, 211, 622, 131, 273, 236, 487, 416, 767, 854, 870, 255, 837, 336, 611, 958, 233, 991, 3, 764, 83, 7, 541, 244, 792, 790, 0, 407, 418, 812, 334, 32, 872, 883, 537, 518, 72, 293, 886, 220, 866, 42, 730, 929, 891, 126, 470, 686, 329, 28, 568, 563, 659, 186, 706, 923, 497, 942, 844, 850, 492, 783, 715, 415, 153, 120, 448, 496, 468, 398, 620, 369, 373, 629, 79, 835, 711, 750, 311, 738, 346, 881, 121, 911, 50, 612, 498, 395, 955, 490, 774, 944, 506, 584, 664, 445, 173, 524, 561, 252, 713, 359, 771, 595, 96, 458, 956, 967, 422, 507, 177, 515, 342, 488, 759, 274, 275, 385, 816, 983, 306, 263, 830, 897, 760, 82, 426, 5, 698, 200, 981, 276, 559, 613, 154, 532, 735, 84, 345, 909, 94, 202, 302, 580, 508, 44, 134, 374, 898, 100, 993, 116, 712, 943, 646, 552, 975, 800, 6, 824, 328, 318, 960, 245, 708, 548, 403, 60, 931, 499, 676, 88, 894, 465, 921, 817, 693, 591, 957, 818, 721, 596, 649, 935, 261, 747, 391, 917, 314, 296, 460, 376, 412, 227, 240, 139, 871, 776, 691, 513, 93, 606, 531, 464, 694, 977, 108, 69, 259, 466, 417, 58, 737, 786, 43, 707, 933, 307, 74, 719, 653, 327, 746, 913, 262, 922, 731, 199, 494, 804, 877, 873, 732, 285, 727, 47, 210, 927, 914, 194, 758, 602, 582, 566, 941, 598, 809, 672, 966, 258, 137, 961, 902, 467, 92, 105, 316, 29, 234, 781, 675, 286, 226, 353, 857, 777, 472, 68, 985, 480, 330, 250, 248, 282, 962, 838, 176, 208, 40, 175, 178, 281, 396, 444, 436, 560, 521, 895, 366, 377, 586, 578, 212, 641, 232, 687, 571, 876, 585, 117, 101, 862, 701, 934, 939, 968, 189, 53, 677, 573, 869, 113, 642, 65, 607, 143, 979, 645, 856, 352, 20, 522, 249, 355, 148, 22, 473, 742, 98, 347, 419, 477, 705, 674, 757, 899, 430, 489, 425, 949, 726, 950, 123, 667, 399, 297, 594, 650, 587, 503, 141, 442, 748, 221, 775, 500, 339, 668, 400, 45, 814, 516, 663, 996, 772, 882, 230, 267, 722, 404, 821, 204, 755, 12, 702, 435, 822, 315, 630, 673, 848, 438, 482, 408, 928, 512, 371, 779, 626, 235, 527, 462, 904, 651, 661, 411, 752, 36, 980, 761, 485, 855, 241, 222, 287, 46, 802, 801, 206, 453, 111, 874, 295, 59, 628, 806, 290, 575, 600, 337, 728, 995, 138, 609, 875, 193, 30, 658, 558, 76, 481, 890, 745, 615, 132, 614, 795, 393, 351, 741, 564, 805, 457, 313, 545, 632, 964, 381, 25, 533, 26, 633, 62, 530, 751, 517, 936, 791, 820, 155, 940, 365, 843, 8, 918, 662, 225, 681, 388, 187, 660, 144, 793, 773, 181, 421, 161, 423, 447, 169, 994, 669, 700, 163, 526, 999, 959, 437, 449, 888, 271, 954, 18, 253, 320, 892, 864, 718, 865, 601, 699, 972, 549, 115, 441, 128, 861, 539, 165, 534, 325, 636, 122, 97, 182, 906, 343
    };
    int n = sizeof(arr)/sizeof(arr[0]);

    clock_t begin = clock();

    /* here, do your time-consuming job */
    mergeSort(arr, 0, n-1);

    clock_t end = clock();
    double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;

    printf("Merge: %.10f", time_spent);
    printf("\n");
    return 0;
}
</code>```

Insertion sort

```<code>// C program for insertion sort
#include <math.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>

/* Function to sort an array using insertion sort*/
void insertionSort(int arr[], int n)
{
    int i, key, j;
    for (i = 1; i < n; i++) {
        key = arr[i];
        j = i - 1;

        /* Move elements of arr[0..i-1], that are
        greater than key, to one position ahead
        of their current position */
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        arr[j + 1] = key;
    }
}

// A utility function to print an array of size n
void printArray(int arr[], int n)
{
    int i;
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
}

/* Driver program to test insertion sort */
int main()
{
    int arr[] = {
        397, 326, 157, 581, 198, 158, 107, 479, 919, 288, 118, 14, 384, 389, 354, 905, 648, 24, 639, 279, 846, 896, 901, 491, 827, 502, 119, 520, 544, 688, 433, 542, 280, 834, 574, 739, 168, 714, 367, 547, 555, 616, 71, 583, 77, 372, 380, 414, 80, 828, 671, 900, 710, 852, 810, 471, 493, 832, 310, 579, 605, 174, 19, 576, 162, 695, 635, 851, 265, 48, 536, 228, 754, 300, 610, 272, 619, 825, 770, 147, 9, 813, 525, 135, 768, 654, 889, 446, 910, 678, 432, 172, 618, 41, 839, 589, 304, 484, 765, 357, 427, 617, 75, 683, 930, 593, 341, 149, 733, 27, 556, 474, 987, 156, 501, 665, 370, 523, 142, 420, 114, 798, 989, 382, 543, 879, 294, 305, 684, 331, 443, 383, 625, 647, 780, 811, 34, 621, 744, 842, 150, 938, 301, 495, 965, 392, 634, 358, 570, 789, 266, 242, 709, 278, 932, 57, 952, 475, 984, 136, 133, 637, 734, 207, 697, 362, 344, 332, 89, 529, 188, 164, 124, 317, 103, 257, 514, 364, 356, 203, 112, 831, 867, 644, 815, 452, 456, 260, 291, 90, 13, 21, 160, 217, 251, 459, 213, 110, 455, 56, 753, 127, 349, 884, 434, 982, 224, 410, 104, 540, 640, 973, 486, 945, 201, 166, 99, 535, 229, 725, 361, 483, 190, 743, 998, 409, 159, 102, 55, 219, 720, 33, 971, 859, 335, 887, 538, 363, 557, 696, 11, 951, 51, 845, 231, 723, 569, 63, 903, 185, 406, 505, 833, 309, 49, 599, 788, 511, 990, 196, 324, 803, 247, 970, 440, 504, 627, 205, 656, 308, 948, 690, 551, 819, 988, 608, 67, 519, 907, 510, 603, 256, 597, 880, 893, 214, 95, 270, 915, 179, 298, 378, 550, 953, 717, 321, 992, 863, 796, 868, 604, 152, 368, 15, 284, 17, 925, 808, 799, 841, 946, 974, 450, 546, 682, 91, 666, 402, 283, 736, 567, 679, 125, 299, 319, 762, 849, 785, 264, 797, 623, 401, 689, 140, 461, 171, 454, 624, 853, 724, 191, 130, 86, 451, 87, 109, 38, 61, 413, 348, 289, 829, 969, 670, 528, 588, 937, 766, 885, 237, 823, 592, 184, 73, 239, 643, 180, 10, 195, 277, 787, 431, 562, 390, 338, 146, 638, 85, 424, 652, 2, 631, 685, 405, 35, 387, 912, 333, 740, 692, 769, 66, 554, 565, 926, 223, 322, 826, 657, 858, 703, 1, 986, 312, 246, 31, 577, 323, 145, 439, 375, 39, 170, 106, 478, 978, 716, 254, 756, 37, 360, 350, 463, 269, 52, 64, 386, 509, 997, 429, 379, 655, 916, 878, 553, 794, 807, 197, 16, 840, 947, 860, 920, 963, 70, 183, 572, 763, 192, 729, 340, 238, 209, 469, 151, 167, 292, 303, 129, 847, 749, 4, 218, 216, 924, 215, 784, 243, 394, 836, 782, 476, 268, 78, 54, 590, 81, 908, 23, 704, 428, 778, 976, 680, 211, 622, 131, 273, 236, 487, 416, 767, 854, 870, 255, 837, 336, 611, 958, 233, 991, 3, 764, 83, 7, 541, 244, 792, 790, 0, 407, 418, 812, 334, 32, 872, 883, 537, 518, 72, 293, 886, 220, 866, 42, 730, 929, 891, 126, 470, 686, 329, 28, 568, 563, 659, 186, 706, 923, 497, 942, 844, 850, 492, 783, 715, 415, 153, 120, 448, 496, 468, 398, 620, 369, 373, 629, 79, 835, 711, 750, 311, 738, 346, 881, 121, 911, 50, 612, 498, 395, 955, 490, 774, 944, 506, 584, 664, 445, 173, 524, 561, 252, 713, 359, 771, 595, 96, 458, 956, 967, 422, 507, 177, 515, 342, 488, 759, 274, 275, 385, 816, 983, 306, 263, 830, 897, 760, 82, 426, 5, 698, 200, 981, 276, 559, 613, 154, 532, 735, 84, 345, 909, 94, 202, 302, 580, 508, 44, 134, 374, 898, 100, 993, 116, 712, 943, 646, 552, 975, 800, 6, 824, 328, 318, 960, 245, 708, 548, 403, 60, 931, 499, 676, 88, 894, 465, 921, 817, 693, 591, 957, 818, 721, 596, 649, 935, 261, 747, 391, 917, 314, 296, 460, 376, 412, 227, 240, 139, 871, 776, 691, 513, 93, 606, 531, 464, 694, 977, 108, 69, 259, 466, 417, 58, 737, 786, 43, 707, 933, 307, 74, 719, 653, 327, 746, 913, 262, 922, 731, 199, 494, 804, 877, 873, 732, 285, 727, 47, 210, 927, 914, 194, 758, 602, 582, 566, 941, 598, 809, 672, 966, 258, 137, 961, 902, 467, 92, 105, 316, 29, 234, 781, 675, 286, 226, 353, 857, 777, 472, 68, 985, 480, 330, 250, 248, 282, 962, 838, 176, 208, 40, 175, 178, 281, 396, 444, 436, 560, 521, 895, 366, 377, 586, 578, 212, 641, 232, 687, 571, 876, 585, 117, 101, 862, 701, 934, 939, 968, 189, 53, 677, 573, 869, 113, 642, 65, 607, 143, 979, 645, 856, 352, 20, 522, 249, 355, 148, 22, 473, 742, 98, 347, 419, 477, 705, 674, 757, 899, 430, 489, 425, 949, 726, 950, 123, 667, 399, 297, 594, 650, 587, 503, 141, 442, 748, 221, 775, 500, 339, 668, 400, 45, 814, 516, 663, 996, 772, 882, 230, 267, 722, 404, 821, 204, 755, 12, 702, 435, 822, 315, 630, 673, 848, 438, 482, 408, 928, 512, 371, 779, 626, 235, 527, 462, 904, 651, 661, 411, 752, 36, 980, 761, 485, 855, 241, 222, 287, 46, 802, 801, 206, 453, 111, 874, 295, 59, 628, 806, 290, 575, 600, 337, 728, 995, 138, 609, 875, 193, 30, 658, 558, 76, 481, 890, 745, 615, 132, 614, 795, 393, 351, 741, 564, 805, 457, 313, 545, 632, 964, 381, 25, 533, 26, 633, 62, 530, 751, 517, 936, 791, 820, 155, 940, 365, 843, 8, 918, 662, 225, 681, 388, 187, 660, 144, 793, 773, 181, 421, 161, 423, 447, 169, 994, 669, 700, 163, 526, 999, 959, 437, 449, 888, 271, 954, 18, 253, 320, 892, 864, 718, 865, 601, 699, 972, 549, 115, 441, 128, 861, 539, 165, 534, 325, 636, 122, 97, 182, 906, 343,
    };

    int n = sizeof(arr)/sizeof(arr[0]);

    //printf("n: %d", n);
    //printf("Unsorted array: ");
    //printArray(arr, n);
    //printf("\n");
    clock_t begin = clock();

    /* here, do your time-consuming job */
    insertionSort(arr, n);

    clock_t end = clock();
    double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;

    //printf("Sorted array: ");
    //printArray(arr, n);
    //printf("\n");

    printf("Inser: %.10f", time_spent);
    printf("\n");

    return 0;
}
</code>```

答:
The memusage and valgrind results you report are consistent with each other: each shows a total of 73728 bytes dynamically allocated.  And that right there should have given you pause, because there are no calls to dynamic memory allocation functions in your sources.  Those bytes are not attributable to your sort functions; they must arise from allocations performed by the standard library in its setup code or in one of the few library functions you call.

Since memusage and the libmemusage.so on which it relies are provided by glibc, one would not expect them to report on glibc's own usage, and indeed, for me they don't.  I cannot explain why you see a different result, but as a wild guess, perhaps you're using mismatched versions of glibc and libmemusage.so.

BUT, you might say, what about stack usage?  Shouldn't the two approaches use different amounts of stack?  And shouldn't they use some stack, not 0 as reported in comments?  Here you have to understand that the underlying libmemusage operates by wrapping selected memory allocation functions, not all functions.  Per the memusage docs, it computes stack usage like so:

Before the first call to any monitored function, the stack pointer
  address (base stack pointer) is saved.  After each [monitored] function call, the
  actual stack pointer address is read and the difference from the base
  stack pointer computed. The maximum of these differences is then the
  stack peak.

(Emphasis added.)  Thus,

memusage provides only an estimate of stack usage, and that estimate is made by sampling the stack pointer around calls to monitored functions.

Therefore, for your particular programs, memusage does not report anything about your sort algorithm's stack usage, because your code makes no calls to monitored functions.

You can work around that by manually instrumenting your code so that libmemusage will see its stack usage.  For example, insert

```<code>free(malloc(0));
</code>```

at the beginning of main() to ensure that a stack-usage low point is recorded, and insert calls to a function such as

```<code>void usage_instrumentation(void) {
    free(malloc(0));
}
</code>```

into each of your other functions.  A function call should be used elsewhere than main in order to capture the stack usage of the calling function; malloc and free should be called directly in main to capture a low point excluding main's usage, so that that usage is included in the final estimate.  Additionally, compile with function inlining (and maybe all optimizations) disabled to avoid this mechanism being defeated by your compiler.

If I do that then, for me, memusage reports 4304 bytes of stack usage for your insertion sort and 8496 for your merge sort, with the difference being slightly larger than the size of your array.  That's just as I would expect.

Body:
I have 2 sorting algorithms, merge sort and insertion sort. I am trying to examine how much ram memory they allocate during execution, to do a comparison. Both are sorting an array of  1000 elements, integers between 0-999.

The programs are compiled to a binary called main (merge_sort/main and insertion_sort/main). So I am running:

memusage -T ./main

on both algorithms.

both returns:

heap total: 73728, heap peak: 73728, stack peak: 6144

Why does they return the same? Shouldn't merge sort allocate more memory than insertion sort? Am I even using memusage correct?

I have also tried to examine them using Valgrind, which also returns same for both:

==26544== HEAP SUMMARY:
==26544==     in use at exit: 0 bytes in 0 blocks
==26544==   total heap usage: 2 allocs, 2 frees, 73,728 bytes allocated

My theory is: that either I dont know what I am doing,

or that the list that is sorted is to small. Therefore the memory usage looks the same.

Code:

Merge sort

/* C program for Merge Sort */
#include<stdlib.h>
#include<stdio.h>
#include<time.h>

// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
    int i, j, k;
    int n1 = m - l + 1;
    int n2 = r - m;

    /* create temp arrays */
    int L[n1], R[n2];

    /* Copy data to temp arrays L[] and R[] */
    for (i = 0; i < n1; i++)
        L[i] = arr[l + i];
    for (j = 0; j < n2; j++)
        R[j] = arr[m + 1+ j];

    /* Merge the temp arrays back into arr[l..r]*/
    i = 0; // Initial index of first subarray
    j = 0; // Initial index of second subarray
    k = l; // Initial index of merged subarray
    while (i < n1 && j < n2)
    {
        if (L[i] <= R[j])
        {
            arr[k] = L[i];
            i++;
        }
        else
        {
            arr[k] = R[j];
            j++;
        }
        k++;
    }

    /* Copy the remaining elements of L[], if there
    are any */
    while (i < n1)
    {
        arr[k] = L[i];
        i++;
        k++;
    }

    /* Copy the remaining elements of R[], if there
    are any */
    while (j < n2)
    {
        arr[k] = R[j];
        j++;
        k++;
    }
}

/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void mergeSort(int arr[], int l, int r)
{
    if (l < r)
    {
        // Same as (l+r)/2, but avoids overflow for
        // large l and h
        int m = l+(r-l)/2;

        // Sort first and second halves
        mergeSort(arr, l, m);
        mergeSort(arr, m+1, r);

        merge(arr, l, m, r);
    }
}

/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray(int A[], int size)
{
    int i;
    for (i=0; i < size; i++)
        printf("%d ", A[i]);
    printf("\n");
}

/* Driver program to test above functions */
int main()
{
    int arr[] = {
        397, 326, 157, 581, 198, 158, 107, 479, 919, 288, 118, 14, 384, 389, 354, 905, 648, 24, 639, 279, 846, 896, 901, 491, 827, 502, 119, 520, 544, 688, 433, 542, 280, 834, 574, 739, 168, 714, 367, 547, 555, 616, 71, 583, 77, 372, 380, 414, 80, 828, 671, 900, 710, 852, 810, 471, 493, 832, 310, 579, 605, 174, 19, 576, 162, 695, 635, 851, 265, 48, 536, 228, 754, 300, 610, 272, 619, 825, 770, 147, 9, 813, 525, 135, 768, 654, 889, 446, 910, 678, 432, 172, 618, 41, 839, 589, 304, 484, 765, 357, 427, 617, 75, 683, 930, 593, 341, 149, 733, 27, 556, 474, 987, 156, 501, 665, 370, 523, 142, 420, 114, 798, 989, 382, 543, 879, 294, 305, 684, 331, 443, 383, 625, 647, 780, 811, 34, 621, 744, 842, 150, 938, 301, 495, 965, 392, 634, 358, 570, 789, 266, 242, 709, 278, 932, 57, 952, 475, 984, 136, 133, 637, 734, 207, 697, 362, 344, 332, 89, 529, 188, 164, 124, 317, 103, 257, 514, 364, 356, 203, 112, 831, 867, 644, 815, 452, 456, 260, 291, 90, 13, 21, 160, 217, 251, 459, 213, 110, 455, 56, 753, 127, 349, 884, 434, 982, 224, 410, 104, 540, 640, 973, 486, 945, 201, 166, 99, 535, 229, 725, 361, 483, 190, 743, 998, 409, 159, 102, 55, 219, 720, 33, 971, 859, 335, 887, 538, 363, 557, 696, 11, 951, 51, 845, 231, 723, 569, 63, 903, 185, 406, 505, 833, 309, 49, 599, 788, 511, 990, 196, 324, 803, 247, 970, 440, 504, 627, 205, 656, 308, 948, 690, 551, 819, 988, 608, 67, 519, 907, 510, 603, 256, 597, 880, 893, 214, 95, 270, 915, 179, 298, 378, 550, 953, 717, 321, 992, 863, 796, 868, 604, 152, 368, 15, 284, 17, 925, 808, 799, 841, 946, 974, 450, 546, 682, 91, 666, 402, 283, 736, 567, 679, 125, 299, 319, 762, 849, 785, 264, 797, 623, 401, 689, 140, 461, 171, 454, 624, 853, 724, 191, 130, 86, 451, 87, 109, 38, 61, 413, 348, 289, 829, 969, 670, 528, 588, 937, 766, 885, 237, 823, 592, 184, 73, 239, 643, 180, 10, 195, 277, 787, 431, 562, 390, 338, 146, 638, 85, 424, 652, 2, 631, 685, 405, 35, 387, 912, 333, 740, 692, 769, 66, 554, 565, 926, 223, 322, 826, 657, 858, 703, 1, 986, 312, 246, 31, 577, 323, 145, 439, 375, 39, 170, 106, 478, 978, 716, 254, 756, 37, 360, 350, 463, 269, 52, 64, 386, 509, 997, 429, 379, 655, 916, 878, 553, 794, 807, 197, 16, 840, 947, 860, 920, 963, 70, 183, 572, 763, 192, 729, 340, 238, 209, 469, 151, 167, 292, 303, 129, 847, 749, 4, 218, 216, 924, 215, 784, 243, 394, 836, 782, 476, 268, 78, 54, 590, 81, 908, 23, 704, 428, 778, 976, 680, 211, 622, 131, 273, 236, 487, 416, 767, 854, 870, 255, 837, 336, 611, 958, 233, 991, 3, 764, 83, 7, 541, 244, 792, 790, 0, 407, 418, 812, 334, 32, 872, 883, 537, 518, 72, 293, 886, 220, 866, 42, 730, 929, 891, 126, 470, 686, 329, 28, 568, 563, 659, 186, 706, 923, 497, 942, 844, 850, 492, 783, 715, 415, 153, 120, 448, 496, 468, 398, 620, 369, 373, 629, 79, 835, 711, 750, 311, 738, 346, 881, 121, 911, 50, 612, 498, 395, 955, 490, 774, 944, 506, 584, 664, 445, 173, 524, 561, 252, 713, 359, 771, 595, 96, 458, 956, 967, 422, 507, 177, 515, 342, 488, 759, 274, 275, 385, 816, 983, 306, 263, 830, 897, 760, 82, 426, 5, 698, 200, 981, 276, 559, 613, 154, 532, 735, 84, 345, 909, 94, 202, 302, 580, 508, 44, 134, 374, 898, 100, 993, 116, 712, 943, 646, 552, 975, 800, 6, 824, 328, 318, 960, 245, 708, 548, 403, 60, 931, 499, 676, 88, 894, 465, 921, 817, 693, 591, 957, 818, 721, 596, 649, 935, 261, 747, 391, 917, 314, 296, 460, 376, 412, 227, 240, 139, 871, 776, 691, 513, 93, 606, 531, 464, 694, 977, 108, 69, 259, 466, 417, 58, 737, 786, 43, 707, 933, 307, 74, 719, 653, 327, 746, 913, 262, 922, 731, 199, 494, 804, 877, 873, 732, 285, 727, 47, 210, 927, 914, 194, 758, 602, 582, 566, 941, 598, 809, 672, 966, 258, 137, 961, 902, 467, 92, 105, 316, 29, 234, 781, 675, 286, 226, 353, 857, 777, 472, 68, 985, 480, 330, 250, 248, 282, 962, 838, 176, 208, 40, 175, 178, 281, 396, 444, 436, 560, 521, 895, 366, 377, 586, 578, 212, 641, 232, 687, 571, 876, 585, 117, 101, 862, 701, 934, 939, 968, 189, 53, 677, 573, 869, 113, 642, 65, 607, 143, 979, 645, 856, 352, 20, 522, 249, 355, 148, 22, 473, 742, 98, 347, 419, 477, 705, 674, 757, 899, 430, 489, 425, 949, 726, 950, 123, 667, 399, 297, 594, 650, 587, 503, 141, 442, 748, 221, 775, 500, 339, 668, 400, 45, 814, 516, 663, 996, 772, 882, 230, 267, 722, 404, 821, 204, 755, 12, 702, 435, 822, 315, 630, 673, 848, 438, 482, 408, 928, 512, 371, 779, 626, 235, 527, 462, 904, 651, 661, 411, 752, 36, 980, 761, 485, 855, 241, 222, 287, 46, 802, 801, 206, 453, 111, 874, 295, 59, 628, 806, 290, 575, 600, 337, 728, 995, 138, 609, 875, 193, 30, 658, 558, 76, 481, 890, 745, 615, 132, 614, 795, 393, 351, 741, 564, 805, 457, 313, 545, 632, 964, 381, 25, 533, 26, 633, 62, 530, 751, 517, 936, 791, 820, 155, 940, 365, 843, 8, 918, 662, 225, 681, 388, 187, 660, 144, 793, 773, 181, 421, 161, 423, 447, 169, 994, 669, 700, 163, 526, 999, 959, 437, 449, 888, 271, 954, 18, 253, 320, 892, 864, 718, 865, 601, 699, 972, 549, 115, 441, 128, 861, 539, 165, 534, 325, 636, 122, 97, 182, 906, 343
    };
    int n = sizeof(arr)/sizeof(arr[0]);

    clock_t begin = clock();

    /* here, do your time-consuming job */
    mergeSort(arr, 0, n-1);

    clock_t end = clock();
    double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;

    printf("Merge: %.10f", time_spent);
    printf("\n");
    return 0;
}

Insertion sort

// C program for insertion sort
#include <math.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>

/* Function to sort an array using insertion sort*/
void insertionSort(int arr[], int n)
{
    int i, key, j;
    for (i = 1; i < n; i++) {
        key = arr[i];
        j = i - 1;

        /* Move elements of arr[0..i-1], that are
        greater than key, to one position ahead
        of their current position */
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        arr[j + 1] = key;
    }
}

// A utility function to print an array of size n
void printArray(int arr[], int n)
{
    int i;
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
}

/* Driver program to test insertion sort */
int main()
{
    int arr[] = {
        397, 326, 157, 581, 198, 158, 107, 479, 919, 288, 118, 14, 384, 389, 354, 905, 648, 24, 639, 279, 846, 896, 901, 491, 827, 502, 119, 520, 544, 688, 433, 542, 280, 834, 574, 739, 168, 714, 367, 547, 555, 616, 71, 583, 77, 372, 380, 414, 80, 828, 671, 900, 710, 852, 810, 471, 493, 832, 310, 579, 605, 174, 19, 576, 162, 695, 635, 851, 265, 48, 536, 228, 754, 300, 610, 272, 619, 825, 770, 147, 9, 813, 525, 135, 768, 654, 889, 446, 910, 678, 432, 172, 618, 41, 839, 589, 304, 484, 765, 357, 427, 617, 75, 683, 930, 593, 341, 149, 733, 27, 556, 474, 987, 156, 501, 665, 370, 523, 142, 420, 114, 798, 989, 382, 543, 879, 294, 305, 684, 331, 443, 383, 625, 647, 780, 811, 34, 621, 744, 842, 150, 938, 301, 495, 965, 392, 634, 358, 570, 789, 266, 242, 709, 278, 932, 57, 952, 475, 984, 136, 133, 637, 734, 207, 697, 362, 344, 332, 89, 529, 188, 164, 124, 317, 103, 257, 514, 364, 356, 203, 112, 831, 867, 644, 815, 452, 456, 260, 291, 90, 13, 21, 160, 217, 251, 459, 213, 110, 455, 56, 753, 127, 349, 884, 434, 982, 224, 410, 104, 540, 640, 973, 486, 945, 201, 166, 99, 535, 229, 725, 361, 483, 190, 743, 998, 409, 159, 102, 55, 219, 720, 33, 971, 859, 335, 887, 538, 363, 557, 696, 11, 951, 51, 845, 231, 723, 569, 63, 903, 185, 406, 505, 833, 309, 49, 599, 788, 511, 990, 196, 324, 803, 247, 970, 440, 504, 627, 205, 656, 308, 948, 690, 551, 819, 988, 608, 67, 519, 907, 510, 603, 256, 597, 880, 893, 214, 95, 270, 915, 179, 298, 378, 550, 953, 717, 321, 992, 863, 796, 868, 604, 152, 368, 15, 284, 17, 925, 808, 799, 841, 946, 974, 450, 546, 682, 91, 666, 402, 283, 736, 567, 679, 125, 299, 319, 762, 849, 785, 264, 797, 623, 401, 689, 140, 461, 171, 454, 624, 853, 724, 191, 130, 86, 451, 87, 109, 38, 61, 413, 348, 289, 829, 969, 670, 528, 588, 937, 766, 885, 237, 823, 592, 184, 73, 239, 643, 180, 10, 195, 277, 787, 431, 562, 390, 338, 146, 638, 85, 424, 652, 2, 631, 685, 405, 35, 387, 912, 333, 740, 692, 769, 66, 554, 565, 926, 223, 322, 826, 657, 858, 703, 1, 986, 312, 246, 31, 577, 323, 145, 439, 375, 39, 170, 106, 478, 978, 716, 254, 756, 37, 360, 350, 463, 269, 52, 64, 386, 509, 997, 429, 379, 655, 916, 878, 553, 794, 807, 197, 16, 840, 947, 860, 920, 963, 70, 183, 572, 763, 192, 729, 340, 238, 209, 469, 151, 167, 292, 303, 129, 847, 749, 4, 218, 216, 924, 215, 784, 243, 394, 836, 782, 476, 268, 78, 54, 590, 81, 908, 23, 704, 428, 778, 976, 680, 211, 622, 131, 273, 236, 487, 416, 767, 854, 870, 255, 837, 336, 611, 958, 233, 991, 3, 764, 83, 7, 541, 244, 792, 790, 0, 407, 418, 812, 334, 32, 872, 883, 537, 518, 72, 293, 886, 220, 866, 42, 730, 929, 891, 126, 470, 686, 329, 28, 568, 563, 659, 186, 706, 923, 497, 942, 844, 850, 492, 783, 715, 415, 153, 120, 448, 496, 468, 398, 620, 369, 373, 629, 79, 835, 711, 750, 311, 738, 346, 881, 121, 911, 50, 612, 498, 395, 955, 490, 774, 944, 506, 584, 664, 445, 173, 524, 561, 252, 713, 359, 771, 595, 96, 458, 956, 967, 422, 507, 177, 515, 342, 488, 759, 274, 275, 385, 816, 983, 306, 263, 830, 897, 760, 82, 426, 5, 698, 200, 981, 276, 559, 613, 154, 532, 735, 84, 345, 909, 94, 202, 302, 580, 508, 44, 134, 374, 898, 100, 993, 116, 712, 943, 646, 552, 975, 800, 6, 824, 328, 318, 960, 245, 708, 548, 403, 60, 931, 499, 676, 88, 894, 465, 921, 817, 693, 591, 957, 818, 721, 596, 649, 935, 261, 747, 391, 917, 314, 296, 460, 376, 412, 227, 240, 139, 871, 776, 691, 513, 93, 606, 531, 464, 694, 977, 108, 69, 259, 466, 417, 58, 737, 786, 43, 707, 933, 307, 74, 719, 653, 327, 746, 913, 262, 922, 731, 199, 494, 804, 877, 873, 732, 285, 727, 47, 210, 927, 914, 194, 758, 602, 582, 566, 941, 598, 809, 672, 966, 258, 137, 961, 902, 467, 92, 105, 316, 29, 234, 781, 675, 286, 226, 353, 857, 777, 472, 68, 985, 480, 330, 250, 248, 282, 962, 838, 176, 208, 40, 175, 178, 281, 396, 444, 436, 560, 521, 895, 366, 377, 586, 578, 212, 641, 232, 687, 571, 876, 585, 117, 101, 862, 701, 934, 939, 968, 189, 53, 677, 573, 869, 113, 642, 65, 607, 143, 979, 645, 856, 352, 20, 522, 249, 355, 148, 22, 473, 742, 98, 347, 419, 477, 705, 674, 757, 899, 430, 489, 425, 949, 726, 950, 123, 667, 399, 297, 594, 650, 587, 503, 141, 442, 748, 221, 775, 500, 339, 668, 400, 45, 814, 516, 663, 996, 772, 882, 230, 267, 722, 404, 821, 204, 755, 12, 702, 435, 822, 315, 630, 673, 848, 438, 482, 408, 928, 512, 371, 779, 626, 235, 527, 462, 904, 651, 661, 411, 752, 36, 980, 761, 485, 855, 241, 222, 287, 46, 802, 801, 206, 453, 111, 874, 295, 59, 628, 806, 290, 575, 600, 337, 728, 995, 138, 609, 875, 193, 30, 658, 558, 76, 481, 890, 745, 615, 132, 614, 795, 393, 351, 741, 564, 805, 457, 313, 545, 632, 964, 381, 25, 533, 26, 633, 62, 530, 751, 517, 936, 791, 820, 155, 940, 365, 843, 8, 918, 662, 225, 681, 388, 187, 660, 144, 793, 773, 181, 421, 161, 423, 447, 169, 994, 669, 700, 163, 526, 999, 959, 437, 449, 888, 271, 954, 18, 253, 320, 892, 864, 718, 865, 601, 699, 972, 549, 115, 441, 128, 861, 539, 165, 534, 325, 636, 122, 97, 182, 906, 343,
    };

    int n = sizeof(arr)/sizeof(arr[0]);

    //printf("n: %d", n);
    //printf("Unsorted array: ");
    //printArray(arr, n);
    //printf("\n");
    clock_t begin = clock();

    /* here, do your time-consuming job */
    insertionSort(arr, n);

    clock_t end = clock();
    double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;

    //printf("Sorted array: ");
    //printArray(arr, n);
    //printf("\n");

    printf("Inser: %.10f", time_spent);
    printf("\n");

    return 0;
}

Body:
The memusage and valgrind results you report are consistent with each other: each shows a total of 73728 bytes dynamically allocated.  And that right there should have given you pause, because there are no calls to dynamic memory allocation functions in your sources.  Those bytes are not attributable to your sort functions; they must arise from allocations performed by the standard library in its setup code or in one of the few library functions you call.

Since memusage and the libmemusage.so on which it relies are provided by glibc, one would not expect them to report on glibc's own usage, and indeed, for me they don't.  I cannot explain why you see a different result, but as a wild guess, perhaps you're using mismatched versions of glibc and libmemusage.so.

BUT, you might say, what about stack usage?  Shouldn't the two approaches use different amounts of stack?  And shouldn't they use some stack, not 0 as reported in comments?  Here you have to understand that the underlying libmemusage operates by wrapping selected memory allocation functions, not all functions.  Per the memusage docs, it computes stack usage like so:

Before the first call to any monitored function, the stack pointer
  address (base stack pointer) is saved.  After each [monitored] function call, the
  actual stack pointer address is read and the difference from the base
  stack pointer computed. The maximum of these differences is then the
  stack peak.

(Emphasis added.)  Thus,

memusage provides only an estimate of stack usage, and that estimate is made by sampling the stack pointer around calls to monitored functions.

Therefore, for your particular programs, memusage does not report anything about your sort algorithm's stack usage, because your code makes no calls to monitored functions.

You can work around that by manually instrumenting your code so that libmemusage will see its stack usage.  For example, insert

free(malloc(0));

at the beginning of main() to ensure that a stack-usage low point is recorded, and insert calls to a function such as

void usage_instrumentation(void) {
    free(malloc(0));
}

into each of your other functions.  A function call should be used elsewhere than main in order to capture the stack usage of the calling function; malloc and free should be called directly in main to capture a low point excluding main's usage, so that that usage is included in the final estimate.  Additionally, compile with function inlining (and maybe all optimizations) disabled to avoid this mechanism being defeated by your compiler.

If I do that then, for me, memusage reports 4304 bytes of stack usage for your insertion sort and 8496 for your merge sort, with the difference being slightly larger than the size of your array.  That's just as I would expect.


来源: stackexchange

问:
How do I update the checkout cart with radio button to have no taxes?
I'm trying to give tax exempt status to user on checkout by having them hit yes on radio button and then upload their tax exempt docs.

I got the radio and file upload working but can't seem to have it update the tax amount on the checkout page.

And I saw this solution Add Tax Exempt form on checkout in woocommerce and tried altering to match my set up but it's not working. PHP is not my strong suit, so I'm sure I messed up somewhere.

Part that I'm having the issue with. It's not updating the tax.

```<code>add_action( 'woocommerce_checkout_update_order_review', 'taxexempt_checkout_update_order_review');
function taxexempt_checkout_update_order_review( $post_data ) {
  global $woocommerce;

  $woocommerce->customer->set_is_vat_exempt(false);

  parse_str($post_data);

  if ( isset($uhave_tax_exempt) && $uhave_tax_exempt == '1')
    $woocommerce->customer->set_is_vat_exempt(true);
}
</code>```

Part that is working to display radio button and file upload.

```<code>function add_radio_field(){
    $radioFile   = "";
    $radioFile   .='<div class="customfield_cover"><label for="some_field_name" class="">Tax Exempt? </label><div id="radio_cover_id">';
    $radioFile .='<input name="uhave_tax_exempt" class="tax_exempt" type="radio" value="1" >Yes    <input class="tax_exempt" name="uhave_tax_exempt" type="radio" value="2" >No';
    $radioFile .='</div></div>';
    echo $radioFile;
 }
add_action('woocommerce_before_order_notes','add_radio_field');

function add_file_field(){
     $uploadFile   = "";
     $uploadFile   .='<div class="customfield_cover custom_file_upload_cvr" style="display:none;" >
     <label for="some_field_name" class="">Attach tax exempt / Resale certificate </label>
     <div id="upload_CNIC_image" style="position:relative;left:15px;">';
     $uploadFile .='<input id="custom_file_upload" name="tax_exempt_attachmentfile" accept="file_extension|image/*|application/pdf|application/msword" type="file"  multiple="true" />
     <input type="hidden" value="" name="uploaded_docs" id="uploaded_docs" />
     <input type="hidden" value="" name="uploaded_docs_org" id="uploaded_org" />
     <div class="remove_uploaded"></div>
     ';
     $uploadFile .='</div></div>';
     echo $uploadFile;
 }
add_action('woocommerce_before_order_notes','add_file_field');
</code>```

答: Might not fully solve the situation but $woocommerce->customer->set_is_vat_exempt(FALSE); will not work as the boolean values in PHP are all lower case so I would replace this line with $woocommerce->customer->set_is_vat_exempt(false);

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to give tax exempt status to user on checkout by having them hit yes on radio button and then upload their tax exempt docs.

I got the radio and file upload working but can't seem to have it update the tax amount on the checkout page.

And I saw this solution Add Tax Exempt form on checkout in woocommerce and tried altering to match my set up but it's not working. PHP is not my strong suit, so I'm sure I messed up somewhere.

Part that I'm having the issue with. It's not updating the tax.

add_action( 'woocommerce_checkout_update_order_review', 'taxexempt_checkout_update_order_review');
function taxexempt_checkout_update_order_review( $post_data ) {
  global $woocommerce;

  $woocommerce->customer->set_is_vat_exempt(false);

  parse_str($post_data);

  if ( isset($uhave_tax_exempt) && $uhave_tax_exempt == '1')
    $woocommerce->customer->set_is_vat_exempt(true);
}

Part that is working to display radio button and file upload.

function add_radio_field(){
    $radioFile   = "";
    $radioFile   .='
Tax Exempt?
';
    $radioFile .='<input name="uhave_tax_exempt" class="tax_exempt" type="radio" value="1" >Yes    <input class="tax_exempt" name="uhave_tax_exempt" type="radio" value="2" >No';
    $radioFile .='

';
    echo $radioFile;
 }
add_action('woocommerce_before_order_notes','add_radio_field');

function add_file_field(){
     $uploadFile   = "";
     $uploadFile   .='

     Attach tax exempt / Resale certificate

';
     $uploadFile .='<input id="custom_file_upload" name="tax_exempt_attachmentfile" accept="file_extension|image/*|application/pdf|application/msword" type="file"  multiple="true" />
     <input type="hidden" value="" name="uploaded_docs" id="uploaded_docs" />
     <input type="hidden" value="" name="uploaded_docs_org" id="uploaded_org" />

     ';
     $uploadFile .='

';
     echo $uploadFile;
 }
add_action('woocommerce_before_order_notes','add_file_field');


问:
How to implement SSL in Zend MVC
I have implemented secure pages before by using a specific secure folder (eg https folder vs http folder on the server).  I have started using Zend Framework and would like parts of the application (eg login) to use https.  I have searched on google and even here but could not find anything that explains how to handle this.  Can I have https for specific controllers/actions?  Thanks.</p>

答:
The cleanest way is to have an .ini file for the SSL config where you can enable SSL support for model/controller/action levels, like so:

Let's say you have a module/controller/action like this:

SSLModule->IndexController->testAction

```
<code>
## ini file (can be config.ini also)
ssl.modules.SSLModule.require_ssl = true  //-> entire module requires SSL
ssl.modules.SSLModule.Index.require_ssl = true  //-> entire controller requires SSL
ssl.modules.SSLModule.Index.test.require_ssl = true  //-> single action requires SSL
</code>
```

You parse this either through config, or separately, and in your Bootstrap file you can include a controllerplugin, like mine here.

There are many other ways to do this, but I think you get the idea!

```
<code>
class Application_Controllerplugins_Ssl extends Zend_Controller_Plugin_Abstract
{

    public function preDispatch ( Zend_Controller_Request_Abstract $request )
    {

        $shouldSecureUrl = false;

        //get the config settings for SSL
        $options = Application_ServiceManager::getConfig()->ssl;

        //if config is empty, exit
        if (!is_object($options))
            return;

        //simpler to use
        $options = $options->toArray();

        //only use it production environment
        if ( APPLICATION_ENV == 'production' )
        {

            if (

                ( isset($options['modules'][$request->module]['require_ssl']) && $options['modules'][$request->module]['require_ssl'] )  ||
                ( isset($options['modules'][$request->module][$request->controller]['require_ssl']) && $options['modules'][$request->module][$request->controller]['require_ssl'] )  ||
                ( isset($options['modules'][$request->module][$request->controller][$request->action]['require_ssl']) && $options['modules'][$request->module][$request->controller][$request->action]['require_ssl'] )

            )
            {

                $shouldSecureUrl = true;

            }

            if ( $shouldSecureUrl )
            {

                $this->_secureUrl($request);

            }
        }
    }

    protected function _secureUrl ( Zend_Controller_Request_Abstract $request )
    {

        $server = $request->getServer();
        $hostname = $server['HTTP_HOST'];

        if ( ! $request->isSecure() )
        {
            $url = Zend_Controller_Request_Http::SCHEME_HTTPS . "://" . $hostname .
             $request->getPathInfo();

            $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
            $redirector->setGoToUrl($url);
            $redirector->redirectAndExit();
        }
    }
}
</code>
```

I forgot to mention: to add it in your bootstrap:

```
<code>
$Zend_Controller_Front->registerPlugin( new Application_Controllerplugins_Ssl() );
</code>
```

ContentLicense: CC BY-SA 2.5

Title: How to implement SSL in Zend MVC

Body:
The cleanest way is to have an .ini file for the SSL config where you can enable SSL support for model/controller/action levels, like so:

Let's say you have a module/controller/action like this:

SSLModule->IndexController->testAction

## ini file (can be config.ini also)
ssl.modules.SSLModule.require_ssl = true  //-> entire module requires SSL
ssl.modules.SSLModule.Index.require_ssl = true  //-> entire controller requires SSL
ssl.modules.SSLModule.Index.test.require_ssl = true  //-> single action requires SSL

You parse this either through config, or separately, and in your Bootstrap file you can include a controllerplugin, like mine here.

There are many other ways to do this, but I think you get the idea!

class Application_Controllerplugins_Ssl extends Zend_Controller_Plugin_Abstract
{

    public function preDispatch ( Zend_Controller_Request_Abstract $request )
    {

        $shouldSecureUrl = false;

        //get the config settings for SSL
        $options = Application_ServiceManager::getConfig()->ssl;

        //if config is empty, exit
        if (!is_object($options))
            return;

        //simpler to use
        $options = $options->toArray();

        //only use it production environment
        if ( APPLICATION_ENV == 'production' )
        {

            if (

                ( isset($options['modules'][$request->module]['require_ssl']) && $options['modules'][$request->module]['require_ssl'] )  ||
                ( isset($options['modules'][$request->module][$request->controller]['require_ssl']) && $options['modules'][$request->module][$request->controller]['require_ssl'] )  ||
                ( isset($options['modules'][$request->module][$request->controller][$request->action]['require_ssl']) && $options['modules'][$request->module][$request->controller][$request->action]['require_ssl'] )

            )
            {

                $shouldSecureUrl = true;

            }

            if ( $shouldSecureUrl )
            {

                $this->_secureUrl($request);

            }
        }
    }

    protected function _secureUrl ( Zend_Controller_Request_Abstract $request )
    {

        $server = $request->getServer();
        $hostname = $server['HTTP_HOST'];

        if ( ! $request->isSecure() )
        {
            $url = Zend_Controller_Request_Http::SCHEME_HTTPS . "://" . $hostname .
             $request->getPathInfo();

            $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
            $redirector->setGoToUrl($url);
            $redirector->redirectAndExit();
        }
    }
}

I forgot to mention: to add it in your bootstrap:

$Zend_Controller_Front->registerPlugin( new Application_Controllerplugins_Ssl() );

ContentLicense: CC BY-SA 3.0


问:
HOW TO Loopback storage setup - AWS S3
I have tried to follow the docs
to get started with loopback 3.x and aws.

Yet, no matter what. this is the response :

"error": {
    "statusCode": 400,
    "name": "AuthorizationHeaderMalformed",
    "message": "The authorization header is malformed; the Credential is mal-formed; expecting \"<YOUR-AKID>/YYYYMMDD/REGION/SERVICE/aws4_request\".",
    "code": "AuthorizationHeaderMalformed"
  }
}

I have found this
But i have no idea what is going on there.

have someone solved this issue ?

答:
I think you have the key and the keyId in reverse way

AWS_ACCESS_KEY is the equivalent of the keyId and AWS_SECRET_KEY the key.

Title: HOW TO Loopback storage setup - AWS S3


问:
How do I set an environment variable in the shebang (#!) of a script that will be run by Bash?
Or, why doesn't this work, assuming you correctly set the file as executable? (On my system it just hangs, but can be killed with ^C.)

```<code>#!/usr/bin/env TEST=TEST python
print('hello')
</code>```

While this does:

```<code>#!/usr/bin/env python
print('hello')
</code>```

As does this:

```<code>[fred@pc build]$ /usr/bin/env TEST=TEST python hello.py
hello
</code>```

答:
On some systems, including Linux, the effect of the

```<code>#!/usr/bin/env TEST=TEST python
</code>```

line in 'hello.py' if you run it with './hello.py' is the same as running

```<code>/usr/bin/env 'TEST=TEST python' ./hello.py
</code>```

Notice that 'TEST=TEST python' is all one argument.  This causes 'env' to set the TEST environment variable to 'TEST python' and then run ./hello.py with exec.  Then the shebang line is processed again, and the process repeats recursively.  The overall effect is to have env execed over and over again until the process is interrupted.  If you run top on the system while the execing is going on you'll see a very busy process.

See the Shebang (Unix) Wikipedia article for information about how the #! mechanism works.  It includes some details of differences between how it is handled on different systems.

It's not possible to set environment variables on the shebang line on Linux, and many other systems.  You'll need to either set them in the program itself or, if that is not appropriate, use a wrapper program (e.g. a trivial shell program) to run the Python program.

Body:
Or, why doesn't this work, assuming you correctly set the file as executable? (On my system it just hangs, but can be killed with ^C.)

#!/usr/bin/env TEST=TEST python
print('hello')

While this does:

#!/usr/bin/env python
print('hello')

As does this:

[fred@pc build]$ /usr/bin/env TEST=TEST python hello.py
hello

Body:
On some systems, including Linux, the effect of the

#!/usr/bin/env TEST=TEST python

line in 'hello.py' if you run it with './hello.py' is the same as running

/usr/bin/env 'TEST=TEST python' ./hello.py

Notice that 'TEST=TEST python' is all one argument.  This causes 'env' to set the TEST environment variable to 'TEST python' and then run ./hello.py with exec.  Then the shebang line is processed again, and the process repeats recursively.  The overall effect is to have env execed over and over again until the process is interrupted.  If you run top on the system while the execing is going on you'll see a very busy process.

See the Shebang (Unix) Wikipedia article for information about how the #! mechanism works.  It includes some details of differences between how it is handled on different systems.

It's not possible to set environment variables on the shebang line on Linux, and many other systems.  You'll need to either set them in the program itself or, if that is not appropriate, use a wrapper program (e.g. a trivial shell program) to run the Python program.


问:
Disable "most recently used items" for Business Process Flow lookups
We are using Account to store multiple account-types: vendor, a distributor, a supplier, a partner. In some scenarios we only want to allow an operator to select a 'vendor' Account which we've achieved by setting a lookup filter.

However, the recently used items list seems to bypass this filter and just show all Accounts regardless of type, so we need to disable it via the below options

These options only apply to that instance of the control. When the same field is included in a Business Process Flow, the recent items appear again.

How can we replicate this behaviour for lookups in a Business Process Flow?

I don't mind if this is done via JavaScript, as long as it uses supported methods. I haven't been able to spot the correct property here MSDN

答:
The trick is to add the same lookup attribute in another form section, set the property “Disable most recently used items for this field” by checking the checkbox in form control. This will replicate the setting to BPF field also.

Later you can remove the field from form section & the setting persists in BPF field.

Disable Recent Records in Business Process Flow


问:
Paste first page and last page a document (docx) into another docx
i have some word files from which i am trying to extract the first and last page and copy into another document.

I have tried the following code i am able to get it partially working , the first page is copied to the new document , however i am not able to get the last page copy working as  the last page overwrites the first page copied. how do i move the courser to end page prior to last page is copied.

```<code>Sub getfirstlast()

Dim Counter As Long, Source As Document, Target As Document
Dim strFolderA As String
Dim strFileSpec As String
Dim strFileName As String
Dim objDocA As Word.Document

strFolderA = InputBox("Enter path to document:")
strFileSpec = "*.docx"
strFileName = Dir(strFolderA & strFileSpec)

Set objDocA = Documents.Add
 Documents.Open (strFolderA & strFileName)

Set Source = ActiveDocument
ActiveDocument.PageSetup.Orientation = wdOrientLandscape
Selection.HomeKey unit:=wdStory
Pages = Source.BuiltInDocumentProperties(wdPropertyPages)

Counter = 0
'MsgBox "number of pages:" & Pages

While Counter < Pages
   Counter = Counter + 1

 'first page
  If Counter = 1 Then
    Source.Bookmarks("\Page").Range.Copy
    Set Target = objDocA
    Target.Range.Paste

 End If

   'last page
   If Counter = Pages Then

    Source.Bookmarks("\Page").Range.Copy
    Set Target = objDocA
    Target.Activate
    Selection.EndKey unit:=wdStory
    Target.Range.Paste

 End If

Wend

Target.PageSetup.Orientation = wdOrientLandscape
Target.SaveAs FileName:=strFolderA & Replace(strFileName, ".docx", "_.docx")
Target.Close

End Sub
</code>```

答:
I've made some alterations to the code in the question in order to streamline the task.

What's supposed to happen with the path and file name information, as well as opening a document, wasn't clear in the context of a reproducible procedure. I commented out the Documents.Open line, but made a suggestion based on the assumption that this is supposed to be the source document. The code I tested uses the line below that, with ActiveDocument.

It's possible to jump directly to a particular page using the GoTo method. This will be faster than looping the pages, especially in a large document.

Using GoTo and the built-in \Pages bookmark require the Selection object and that the source document be the active one.

Writing to the Target, however, can use a Range object. Note that it's better to use a separate object, rather than Document.Range for this kind of work. Then, the trick is to Collapse the Range in order to add information (instead of replacing the range content).

While the Copy/Paste approach in the question does work, it's more efficient to work with the Range.FormattedText property to transfer content within or between Word documents. This also leaves the user's Clipboard content intact.

```<code>Sub getfirstlastPagesToNewDocument()
    Dim Counter As Long, Pages As Long, Source As Document
    Dim strFolderA As String
    Dim strFileSpec As String
    Dim strFileName As String
    Dim objDocA As Word.Document
    Dim rngTarget As Word.Range, rngSource As Word.Range

    strFolderA = InputBox("Enter path to document:")
    strFileSpec = "*.docx"
    strFileName = Dir(strFolderA & strFileSpec)
    '??SEt Source = Documents.Open (strFolderA & strFileName)
    Set Source = ActiveDocument
    Set objDocA = Documents.Add
    Set rngTarget = objDocA.content

    Source.PageSetup.Orientation = wdOrientLandscape
    Source.Activate
    Selection.HomeKey unit:=wdStory
    Pages = Source.BuiltInDocumentProperties(wdPropertyPages)

    Selection.GoTo What:=Word.wdGoToAbsolute, Which:=Word.wdGoToPage, Count:=1
    Set rngSource = Selection.Bookmarks("\Page").Range
    rngTarget.FormattedText = rngSource.FormattedText
'    Selection.Bookmarks("\Page").Range.Copy
'    rngTarget.Paste

    Selection.GoTo What:=Word.wdGoToAbsolute, Which:=Word.wdGoToPage, Count:=Pages
    Set rngSource = Selection.Bookmarks("\Page").Range
'    Selection.Bookmarks("\Page").Range.Copy
    rngTarget.Collapse wdCollapseEnd
    rngTarget.FormattedText = rngSource.FormattedText
'    rngTarget.Paste

    objDocA.PageSetup.Orientation = wdOrientLandscape
    objDocA.SaveAs fileName:=strFolderA & Replace(strFileName, ".docx", "_.docx")
    objDocA.Close

End Sub
</code>```

Body:
i have some word files from which i am trying to extract the first and last page and copy into another document.

I have tried the following code i am able to get it partially working , the first page is copied to the new document , however i am not able to get the last page copy working as  the last page overwrites the first page copied. how do i move the courser to end page prior to last page is copied.

Sub getfirstlast()

Dim Counter As Long, Source As Document, Target As Document
Dim strFolderA As String
Dim strFileSpec As String
Dim strFileName As String
Dim objDocA As Word.Document

strFolderA = InputBox("Enter path to document:")
strFileSpec = "*.docx"
strFileName = Dir(strFolderA & strFileSpec)

Set objDocA = Documents.Add
 Documents.Open (strFolderA & strFileName)

Set Source = ActiveDocument
ActiveDocument.PageSetup.Orientation = wdOrientLandscape
Selection.HomeKey unit:=wdStory
Pages = Source.BuiltInDocumentProperties(wdPropertyPages)

Counter = 0
'MsgBox "number of pages:" & Pages

While Counter < Pages
   Counter = Counter + 1

 'first page
  If Counter = 1 Then
    Source.Bookmarks("\Page").Range.Copy
    Set Target = objDocA
    Target.Range.Paste

 End If

   'last page
   If Counter = Pages Then

    Source.Bookmarks("\Page").Range.Copy
    Set Target = objDocA
    Target.Activate
    Selection.EndKey unit:=wdStory
    Target.Range.Paste

 End If

Wend

Target.PageSetup.Orientation = wdOrientLandscape
Target.SaveAs FileName:=strFolderA & Replace(strFileName, ".docx", "_.docx")
Target.Close

End Sub

Body:
I've made some alterations to the code in the question in order to streamline the task.

What's supposed to happen with the path and file name information, as well as opening a document, wasn't clear in the context of a reproducible procedure. I commented out the Documents.Open line, but made a suggestion based on the assumption that this is supposed to be the source document. The code I tested uses the line below that, with ActiveDocument.

It's possible to jump directly to a particular page using the GoTo method. This will be faster than looping the pages, especially in a large document.

Using GoTo and the built-in \Pages bookmark require the Selection object and that the source document be the active one.

Writing to the Target, however, can use a Range object. Note that it's better to use a separate object, rather than Document.Range for this kind of work. Then, the trick is to Collapse the Range in order to add information (instead of replacing the range content).

While the Copy/Paste approach in the question does work, it's more efficient to work with the Range.FormattedText property to transfer content within or between Word documents. This also leaves the user's Clipboard content intact.

Sub getfirstlastPagesToNewDocument()
    Dim Counter As Long, Pages As Long, Source As Document
    Dim strFolderA As String
    Dim strFileSpec As String
    Dim strFileName As String
    Dim objDocA As Word.Document
    Dim rngTarget As Word.Range, rngSource As Word.Range

    strFolderA = InputBox("Enter path to document:")
    strFileSpec = "*.docx"
    strFileName = Dir(strFolderA & strFileSpec)
    '??SEt Source = Documents.Open (strFolderA & strFileName)
    Set Source = ActiveDocument
    Set objDocA = Documents.Add
    Set rngTarget = objDocA.content

    Source.PageSetup.Orientation = wdOrientLandscape
    Source.Activate
    Selection.HomeKey unit:=wdStory
    Pages = Source.BuiltInDocumentProperties(wdPropertyPages)

    Selection.GoTo What:=Word.wdGoToAbsolute, Which:=Word.wdGoToPage, Count:=1
    Set rngSource = Selection.Bookmarks("\Page").Range
    rngTarget.FormattedText = rngSource.FormattedText
'    Selection.Bookmarks("\Page").Range.Copy
'    rngTarget.Paste

    Selection.GoTo What:=Word.wdGoToAbsolute, Which:=Word.wdGoToPage, Count:=Pages
    Set rngSource = Selection.Bookmarks("\Page").Range
'    Selection.Bookmarks("\Page").Range.Copy
    rngTarget.Collapse wdCollapseEnd
    rngTarget.FormattedText = rngSource.FormattedText
'    rngTarget.Paste

    objDocA.PageSetup.Orientation = wdOrientLandscape
    objDocA.SaveAs fileName:=strFolderA & Replace(strFileName, ".docx", "_.docx")
    objDocA.Close

End Sub


问:
Powershell Get -ChildItem: filtering csv files and -Recurse not working
I created a short powershell script to convert csv files from Unicode to UTF-8 encoding. My script outputs new files with the the original file name preceded by UTF8. I'm running into two issues:

I'm trying to only run the powershell script on csv files. Currently the script runs on every file in the directory, including the powershell script (it outputs a new file called UTF8pshell_script if the powershell script was called pshell_script for example). The other methods where I've tried to only run the script on csv files just end up making the script not do anything.

I'm trying to run the script on sub-directories. The first issue is that output files created from csv files in subdirectories have no content inside them whatsoever. If the script is ran in the same directory as the csv file this problem does not arise. This is not crucial but I am also uncertain how to get output files created from those in subdirectories to be outputted in the same subdirectories (currently they are outputted in the main directory where the powershell script is).
as

```<code>    Get-Content -Encoding Unicode $_ | Out-File -Encoding UTF8
    Get-ChildItem -Recurse | ForEach-Object {Get-Content -Encoding Unicode $_ | Out-File -Encoding UTF8 "UTF8$_"}
</code>```

The desired output is the powershell script running on only csv files, and outputting files to the same subdirectories where the files they were created form are.

答:
if you specify the file extension at the end of Get-ChildItem.
This will get only the files with the .csv extension.

By specifying the File path in Out-File it will send it to the specified directory.

```<code>Get-ChildItem -Path C:\folder\*.csv -Recurse | ForEach-Object {Get-Content -Encoding Unicode $_ | Out-File -FilePath C:\Folder -Encoding UTF8 "UTF8$_"}
</code>```

Body:
I created a short powershell script to convert csv files from Unicode to UTF-8 encoding. My script outputs new files with the the original file name preceded by UTF8. I'm running into two issues:

I'm trying to only run the powershell script on csv files. Currently the script runs on every file in the directory, including the powershell script (it outputs a new file called UTF8pshell_script if the powershell script was called pshell_script for example). The other methods where I've tried to only run the script on csv files just end up making the script not do anything.

I'm trying to run the script on sub-directories. The first issue is that output files created from csv files in subdirectories have no content inside them whatsoever. If the script is ran in the same directory as the csv file this problem does not arise. This is not crucial but I am also uncertain how to get output files created from those in subdirectories to be outputted in the same subdirectories (currently they are outputted in the main directory where the powershell script is).
as

    Get-Content -Encoding Unicode $_ | Out-File -Encoding UTF8
    Get-ChildItem -Recurse | ForEach-Object {Get-Content -Encoding Unicode $_ | Out-File -Encoding UTF8 "UTF8$_"}

The desired output is the powershell script running on only csv files, and outputting files to the same subdirectories where the files they were created form are.

Body:
if you specify the file extension at the end of Get-ChildItem.
This will get only the files with the .csv extension.

By specifying the File path in Out-File it will send it to the specified directory.

Get-ChildItem -Path C:\folder\*.csv -Recurse | ForEach-Object {Get-Content -Encoding Unicode $_ | Out-File -FilePath C:\Folder -Encoding UTF8 "UTF8$_"}


问:
Downloading GRIB files directly into Matlab
I want to read in data from the GFS weather forecasting model. The NOAA has some URL links from which the data can be downloaded, e.g.:

https://nomads.ncep.noaa.gov/cgi-bin/filter_gfs_0p25_1hr.pl?file=gfs.t06z.pgrb2.0p25.f005&lev_surface=on&var_CAPE=on&leftlon=0&rightlon=360&toplat=90&bottomlat=-90&dir=%2Fgfs.2019053006

In the internet browser, this link automatically downloads a file (but which format?). In Matlab I do the following:

fullURL = ['https://nomads.ncep.noaa.gov/cgi-bin/filter_gfs_0p25_1hr.pl?file=gfs.t06z.pgrb2.0p25.f011&lev_surface=on&var_CAPE=on&leftlon=0&rightlon=360&toplat=90&bottomlat=-90&dir=%2Fgfs.2019053006'];

filename = 'cape_test.anl';

urlwrite(fullURL,filename);
```

These files open well in GIS software such as QGIS or ArcGIS. But how can I now read in these files automatically in MatLab so I can display them with the imagesc() command? Trying NCToolbox didn't work.

答:
Why don't you download the file first. Then build a script to look up directories inside a folder.

Could even source from the browser download folder.

```<code>% Directory

directory = 'C:\Datasets\NOAA\myfile';

%Do stuff
</code>```

Body:
I want to read in data from the GFS weather forecasting model. The NOAA has some URL links from which the data can be downloaded, e.g.:

https://nomads.ncep.noaa.gov/cgi-bin/filter_gfs_0p25_1hr.pl?file=gfs.t06z.pgrb2.0p25.f005&lev_surface=on&var_CAPE=on&leftlon=0&rightlon=360&toplat=90&bottomlat=-90&dir=%2Fgfs.2019053006

In the internet browser, this link automatically downloads a file (but which format?). In Matlab I do the following:

fullURL = ['https://nomads.ncep.noaa.gov/cgi-bin/filter_gfs_0p25_1hr.pl?file=gfs.t06z.pgrb2.0p25.f011&lev_surface=on&var_CAPE=on&leftlon=0&rightlon=360&toplat=90&bottomlat=-90&dir=%2Fgfs.2019053006'];

filename = 'cape_test.anl';

urlwrite(fullURL,filename);

These files open well in GIS software such as QGIS or ArcGIS. But how can I now read in these files automatically in MatLab so I can display them with the imagesc() command? Trying NCToolbox didn't work.

Body:
Why don't you download the file first. Then build a script to look up directories inside a folder.

Could even source from the browser download folder.

% Directory

directory = 'C:\Datasets\NOAA\myfile';

%Do stuff


问:
Trying to save value to redux store - getting dispatch is not a function
I am trying to save a value to a redux store upon a user entering text for a search.

Edited to include my full import list

```<code>import React, { Component } from 'react';
import axios from 'axios';
import API from './API';
import { connect } from "react-redux";
import searchSave from '../actions/search'
import {bindActionCreators} from 'redux'
const format = require('string-format')

class Search extends Component {
...

   searchForText = (text) => {
    console.log("user stopped typing");
    console.log(text);
    this.props.searchSave(text);
  }

...
}

const mapStateToProps = (state) => {
  return {
    oidc: state.oidc,
    search: state.searchtext,
  };
};

function mapDispatchToProps(dispatch) {
  let actions = bindActionCreators({ searchSave });
  return { ...actions, dispatch };
}

export default connect(mapStateToProps, mapDispatchToProps)(Search)
</code>```

My reducer looks like this and is in my combineReducers function elsewhere:

```<code>import Actions from '../actions/search.js'

export default (state = "", action) => {
      switch (action.type) {
        case Actions.SEARCH:
        return {searchtext: action.payload}
      }
      return state;
    };
</code>```

I am getting the error, "TypeError: Dispatch is not a function" - but theoretically dispatch should be bound by bindActionCreators?

I have searched for this exact error, but none of it seems related to my specific conditions.

I am assuming I am doing something wrong in my mapStateToProps or my reducer?

I am pretty new to redux and still find it somewhat confusing.

答:
You need to pass the dispatch function as the second parameter to bindActionCreators:

```<code>function mapDispatchToProps(dispatch) {
  return bindActionCreators({ searchSave }, dispatch);
}
</code>```

You can see the docs for this here: https://react-redux.js.org/using-react-redux/connect-mapdispatch

If your intention was to also include dispatch in the returned props (which seems like an antipattern to me, but I'm not an expert), your original code works with the addition of the second parameter to bindActionCreators:

```<code>function mapDispatchToProps(dispatch) {
  const actions = bindActionCreators({ searchSave }, dispatch);
  return { ...actions, dispatch };
}
</code>```

Body:
I am trying to save a value to a redux store upon a user entering text for a search.

Edited to include my full import list

import React, { Component } from 'react';
import axios from 'axios';
import API from './API';
import { connect } from "react-redux";
import searchSave from '../actions/search'
import {bindActionCreators} from 'redux'
const format = require('string-format')

class Search extends Component {
...

   searchForText = (text) => {
    console.log("user stopped typing");
    console.log(text);
    this.props.searchSave(text);
  }

...
}

const mapStateToProps = (state) => {
  return {
    oidc: state.oidc,
    search: state.searchtext,
  };
};

function mapDispatchToProps(dispatch) {
  let actions = bindActionCreators({ searchSave });
  return { ...actions, dispatch };
}

export default connect(mapStateToProps, mapDispatchToProps)(Search)

My reducer looks like this and is in my combineReducers function elsewhere:

import Actions from '../actions/search.js'

export default (state = "", action) => {
      switch (action.type) {
        case Actions.SEARCH:
        return {searchtext: action.payload}
      }
      return state;
    };

I am getting the error, "TypeError: Dispatch is not a function" - but theoretically dispatch should be bound by bindActionCreators?

I have searched for this exact error, but none of it seems related to my specific conditions.

I am assuming I am doing something wrong in my mapStateToProps or my reducer?

I am pretty new to redux and still find it somewhat confusing.

Body:
You need to pass the dispatch function as the second parameter to bindActionCreators:

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ searchSave }, dispatch);
}

You can see the docs for this here: https://react-redux.js.org/using-react-redux/connect-mapdispatch

If your intention was to also include dispatch in the returned props (which seems like an antipattern to me, but I'm not an expert), your original code works with the addition of the second parameter to bindActionCreators:

function mapDispatchToProps(dispatch) {
  const actions = bindActionCreators({ searchSave }, dispatch);
  return { ...actions, dispatch };
}


答:
Get-ChildItem takes a -Filter parameter, which for files is the simple wildcard pattern. This will allow you to restrict your cmdlet to CSV files only:

```<code>Get-ChildItem -Filter *.csv
</code>```

To process subdirectories, you may also use the -Recurse switch

```<code>Get-ChildItem -Filter *.csv -Recurse
</code>```

Now, I'm never quite sure how $_ changes as you pass different objects through the pipe, so I'm probably not doing the next steps the most efficient way - but it will be clear what I'm trying to do:

Each file object that we find needs to be processed as follows:

Dissect it into a path and a filename: $filepath = $_.PSParentPath; $filename = $_.PSChildName

Load up the CSV: Import-CSV -Path $_

Output the new CSV with the proper encoding: Export-CSV -Path ("{0}\UTF8{1}" -f $filepath,$filename) -Encoding UTF8

So, we put it all together:

```<code>Get-ChildItem -Filter *.csv -Recurse -exclude UTF8* | ForEach-Object {
    $filepath = $_.PSParentPath
    $filename = $_.PSChildName
    Import-CSV -Path $_ |
       Export-CSV -Encoding UTF8 -Path ("{0}\UTF8{1}" -f $filepath,$filename) -NoTypeInformation
}
</code>```

The -Exclude UTF8* in the Get-ChildItem ensures that when you create a file, it doesn't get picked up later and re-processed. The -NoTypeInformation on the Export-CSV compensates for a stupidity built in to the cmdlet that causes an extra line with a meaningless object type name at the beginning of the file.

Title: Powershell Get -ChildItem: filtering csv files and -Recurse not working

Body:
Get-ChildItem takes a -Filter parameter, which for files is the simple wildcard pattern. This will allow you to restrict your cmdlet to CSV files only:

Get-ChildItem -Filter *.csv

To process subdirectories, you may also use the -Recurse switch

Get-ChildItem -Filter *.csv -Recurse

Now, I'm never quite sure how $_ changes as you pass different objects through the pipe, so I'm probably not doing the next steps the most efficient way - but it will be clear what I'm trying to do:

Each file object that we find needs to be processed as follows:

Dissect it into a path and a filename: $filepath = $_.PSParentPath; $filename = $_.PSChildName

Load up the CSV: Import-CSV -Path $_

Output the new CSV with the proper encoding: Export-CSV -Path ("{0}\UTF8{1}" -f $filepath,$filename) -Encoding UTF8

So, we put it all together:

Get-ChildItem -Filter *.csv -Recurse -exclude UTF8* | ForEach-Object {
    $filepath = $_.PSParentPath
    $filename = $_.PSChildName
    Import-CSV -Path $_ |
       Export-CSV -Encoding UTF8 -Path ("{0}\UTF8{1}" -f $filepath,$filename) -NoTypeInformation
}

The -Exclude UTF8* in the Get-ChildItem ensures that when you create a file, it doesn't get picked up later and re-processed. The -NoTypeInformation on the Export-CSV compensates for a stupidity built in to the cmdlet that causes an extra line with a meaningless object type name at the beginning of the file.


问:
Identifying if a string ONLY has specific text
I have a column with a string that sometimes has one name, two, names or several names separated by semi-colons. I want to identify if a row matches all the specified names, but not if a row contains only some of the specified names.

SME

Row 1 - John;Ralph;Susan;Joe

Row 2 - Ralph

Row 3 - Susan;Ralph;Robert;Margaret

Row 4 - Ralph;Susan

```<code>df1['SME'] = df1.SMES.str.ONLY contains('Ralph', na=False, case=True)
df2['SME'] = df1.SMES.str.ONLY contains('Ralph;Susan', na=False, case=True)
</code>```

Expecting df1

Row 1 - False

Row 2 - True

Row 3 - False

Row 4 - False

Expecting df2

Row 1 - False

Row 2 - False

Row 3 - False

Row 4 - True

答:
To check for an exact value you can put a condition inside your df like so :

```<code>df1[df1['SME'] == 'Ralph']
</code>```

If you only want to have the true/false values, you can create a mask just with the condition :

```<code>mask = df1['SME'] == 'Ralph'
</code>```

Body:
I have a column with a string that sometimes has one name, two, names or several names separated by semi-colons. I want to identify if a row matches all the specified names, but not if a row contains only some of the specified names.

SME

Row 1 - John;Ralph;Susan;Joe

Row 2 - Ralph

Row 3 - Susan;Ralph;Robert;Margaret

Row 4 - Ralph;Susan

df1['SME'] = df1.SMES.str.ONLY contains('Ralph', na=False, case=True)
df2['SME'] = df1.SMES.str.ONLY contains('Ralph;Susan', na=False, case=True)

Expecting df1

Row 1 - False

Row 2 - True

Row 3 - False

Row 4 - False

Expecting df2

Row 1 - False

Row 2 - False

Row 3 - False

Row 4 - True

Body:
To check for an exact value you can put a condition inside your df like so :

df1[df1['SME'] == 'Ralph']

If you only want to have the true/false values, you can create a mask just with the condition :

mask = df1['SME'] == 'Ralph'


问:
Is there a way to use a variable to name a data frame in R?
Basically I want to be able to do this.

```<code>a <- 1
data_frame_1 <- "some data"
a <- a+1
data_frame_2 <- "some data"
</code>```

Where the 1 and 2 at the end of the data frame names are coming from the values of a. Is there a way to do this?

答:
As a simple example:</p>

```<code>my_list <- list(data_frame_1,data_frame_2)
my_list <- setNames(my_list,paste0("data_frame_",1:2))
</code>```

Body:
Basically I want to be able to do this.

a <- 1
data_frame_1 <- "some data"
a <- a+1
data_frame_2 <- "some data"

Where the 1 and 2 at the end of the data frame names are coming from the values of a. Is there a way to do this?

Body:
As a simple example:

my_list <- list(data_frame_1,data_frame_2)
my_list <- setNames(my_list,paste0("data_frame_",1:2))


问:
Add textbox when button is pressed
I know this can be accomplished in Javascript (I hope!) I have a couple of forms on my page, but I cannot guess how many the user will need, so is there some magic which can be done in javascript which when a button is pressed this:

```<code> <input name="userfile[]" type="file" /><br />
    <input type="text" value="Description goes here." name="imagedescription2" maxlength="20" onfocus="this.value = '';" /><br />
</code>```

Is added to a designated area? Keeping in mind adding a number onto the name if the  button is pressed eg name="imagedescription3" next name="imagedescription4" and so forth
This may be posted around the internet, I know it would be, I just don't know how to thorougly phrase my question

答:
If possible, I recommend adding jQuery to your project.  It makes DOM manipulation easy.

http://api.jquery.com/category/manipulation/

An example might look like this

```<code><a href="#" id="myButton">Add Item</a>
<div id="#wrapper">
        <input type="text" value="Description goes here." name="imagedescription1" maxlength="20" onfocus="this.value = '';" /><br />
        <input type="text" value="Description goes here." name="imagedescription2" maxlength="20" onfocus="this.value = '';" /><br />
</div>
        <script>
        $(function(){
            var i = 3; // i would be incremented with each add.
            $("#myButton").click(function(){
                $('<input type="text" value="Description goes here." name="imagedescription' + i + '" maxlength="20" onfocus="this.value = '';" /><br />').appendTo('#wrapper');
            });
            return false;
        });

</script>
</code>```

Title: Add textbox when button is pressed

Body:
I know this can be accomplished in Javascript (I hope!) I have a couple of forms on my page, but I cannot guess how many the user will need, so is there some magic which can be done in javascript which when a button is pressed this:

 <input name="userfile[]" type="file" />

    <input type="text" value="Description goes here." name="imagedescription2" maxlength="20" onfocus="this.value = '';" />

Is added to a designated area? Keeping in mind adding a number onto the name if the  button is pressed eg name="imagedescription3" next name="imagedescription4" and so forth
This may be posted around the internet, I know it would be, I just don't know how to thorougly phrase my question

Body:
If possible, I recommend adding jQuery to your project.  It makes DOM manipulation easy.

http://api.jquery.com/category/manipulation/

An example might look like this

<a href="#" id="myButton">Add Item</a>
<div id="#wrapper">
        <input type="text" value="Description goes here." name="imagedescription1" maxlength="20" onfocus="this.value = '';" /><br />
        <input type="text" value="Description goes here." name="imagedescription2" maxlength="20" onfocus="this.value = '';" /><br />
</div>
        <script>
        $(function(){
            var i = 3; // i would be incremented with each add.
            $("#myButton").click(function(){
                $('<input type="text" value="Description goes here." name="imagedescription' + i + '" maxlength="20" onfocus="this.value = '';" /><br />').appendTo('#wrapper');
            });
            return false;
        });

</script>


答:
Looks like you're missing the import for connect, and some stuff in mapDispatchToProps. I also don't believe you need bindActionCreators in this scenario: </p>

```<code>import searchSave from '../actions/search'
//Missing import connect
import { connect } from 'react-redux'

class Search extends Component {
...

   searchForText = (text) => {
    console.log("user stopped typing");
    console.log(text);
    this.props.searchSave(text);
  }

...
}

const mapStateToProps = (state) => {
  return {
    oidc: state.oidc,
    search: state.searchtext,
  };
};

function mapDispatchToProps(dispatch) {
    searchSave: (inputs) => dispatch(searchSave(inputs)
}

export default connect(mapStateToProps, mapDispatchToProps)(Search)
</code>```

Title: Trying to save value to redux store - getting dispatch is not a function

Body:
Looks like you're missing the import for connect, and some stuff in mapDispatchToProps. I also don't believe you need bindActionCreators in this scenario:

import searchSave from '../actions/search'
//Missing import connect
import { connect } from 'react-redux'

class Search extends Component {
...

   searchForText = (text) => {
    console.log("user stopped typing");
    console.log(text);
    this.props.searchSave(text);
  }

...
}

const mapStateToProps = (state) => {
  return {
    oidc: state.oidc,
    search: state.searchtext,
  };
};

function mapDispatchToProps(dispatch) {
    searchSave: (inputs) => dispatch(searchSave(inputs)
}

export default connect(mapStateToProps, mapDispatchToProps)(Search)


问:
How to get a file from laravel folder storage for a treatment
I saved an image in storage / app / public and I created a symbolic link to public / storage and the link works well but when I try to get the image with the method Storage :: get ($path) I am being sent a FileNotFoundException. I would like to know how to get my image in my code

```<code> $fichier=Storage::get('storage/avatarDebutFemme.png');
</code>```

Illuminate \ Contracts \ Filesystem \ FileNotFoundException
  storage/avatarDebutFemme.png

Previous exceptions

File not found at path: storage/avatarDebutFemme.png (0)

答:
To access your storage path you should use the storage helper for getting the path:

$fichier = Storage::get(storage_path('app/public/avatarDebutFemme.png'));
```

Would get a file called avatarDebutFemme.png located in the folder storage/app/public of your Laravel project.

Body:
I saved an image in storage / app / public and I created a symbolic link to public / storage and the link works well but when I try to get the image with the method Storage :: get ($path) I am being sent a FileNotFoundException. I would like to know how to get my image in my code

 $fichier=Storage::get('storage/avatarDebutFemme.png');

Illuminate \ Contracts \ Filesystem \ FileNotFoundException
  storage/avatarDebutFemme.png

Previous exceptions

File not found at path: storage/avatarDebutFemme.png (0)

Body:
To access your storage path you should use the storage helper for getting the path:

$fichier = Storage::get(storage_path('app/public/avatarDebutFemme.png'));

Would get a file called avatarDebutFemme.png located in the folder storage/app/public of your Laravel project.


问:
Form elements not clickable html css
The button and text fields on my login page are unresponsive / I am unable to click or interact with them. It worked fine yesterday and is linked to a PHP database. I have no idea what code I changed but it was possibly CSS that has stopped it working. Any advice would be great as I am lost. </p>

<p>I have tried editing CSS but to avail. </p>

```<code><!DOCTYPE HTML>
<html lang="en">
<head>
  <title>Maoine in Eirinn (MIE) Wild Atlantic Gaeltacht Properties</title>
  <meta charset="utf-8">
 <link rel="stylesheet" href="css/styles.css">
 </head>
<body>
<div id="container">
<?php include("includes/header.html");?>
<?php include("includes/nav.html");?>
<div id="content">
<?php
if (empty($_SESSION))
session_start();
if (isset($_SESSION['errors'])) {
echo "<div class='form-errors'>";
foreach($_SESSION['errors'] as $error)
{
 echo "<p>";
 echo $error;
 echo "</p>";
}
echo "</div>";
}
unset($_SESSION['errors']);
?>
<div id="login">
<h3> Login </h3>
<form action="login_action.php" method="POST">
<p>
Username: <input type="text" name="adminname" required="required">
</p><p>
Password: <input type="password" name="password" required="required">
</p><p>
<input type="submit" value="Login">
</p>
</form>
</div>
</div>
<?php include("includes/footer.html");?>
</div>
</body>
</html>

body{background-color: #EEEEEE; }

#container{margin: auto;
    width: 100%;
    background-color: #EEEEEE;
    border: 10px solid #EEEEEE;
    }

#header{
    background-color: #449966;
    height: 110px;
    margin-top: 38px;
    }

#nav{background-color: #000000;
    clear: left;
      }
#moira{
  float:right;
  padding-right: 50px;
  position: relative;
  margin-left: 50px;
}
#martin{
  float:right;
  padding-right: 50px;
  position: relative;
  margin-left: 50px;
}
#openinghours{`
  width: 30%;
  float:left;
  margin-left: 100px;}
#contactus{width: 50%;
  float:left;
  margin-bottom: 200px;}
#content{background-color: #EEEEEE;
    padding: 50px;
    min-height: 500px;
    text-align: center;
    }

#content a {background-color: #449966; color: white; text-decoration:none; padding:5px;}
#content a:hover {background-color: #878787; color: white;}

#footer{background-color: #449966;
    height: 50px;
    padding: 10px;
    display: flex;
    margin-top: 200px;
    bottom: 0;
    width: 100%;
    position: fixed;
}
#comments {width: 70%; float: left;}
.container{
    position: relative;
    border-radius: 8px;
    width: 90%;
    height: 500px;
    overflow: hidden;
}
#login{z-index: 100;}
#logo {float:left;}
#copyright {float:left;}
#footer ul{    text-align: center;
     width: 50%;
     margin: auto;}
#footer a{ color:#449966; }
#socialMedia{float:right; width: 150px; display: flex;}
#sitename{text-align: center;
       width: 100%;}
#languageimage img{
  border: 1px solid #ddd;
  border-radius: 50%;
  float:right;
  display: flex;
  vertical-align: top;}
table td {padding: 10px;}
table {width: 100%}

table tr:nth-child(1) {
    background-color: #449966;
    }
table tr {
    background-color:#FFFFFF;
    }
#displayproperties{width: 75%;}
#addtestimonial{width: 25%; margin-left: 50px; float: right;}
#addtestimonial table {border: 0px;}
#addtestimonial table tr td {padding: 0px; border: 0px;}
#addtestimonial table tr {background-color: #c6e1e0; border: 0px;}

.show {display:block;}

#commentform {
           font-family: Arial;
                 width: auto;
         }
label { float:left;
    width: 50px;
    clear: left;
    text-align: left;
    padding-right: 15px;
    margin-top: 10px;
    }
input, textarea {margin-top: 10px; }
#mysubmit { margin-left:65px;
        padding-bottom: 10px;
          }

body {margin:0;font-family:Arial}

.topnav {
  overflow: hidden;
  background-color: #333;
  position: fixed;
  top: 0;
  width: 100%;
}

.topnav a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.active {
  background-color: #449966;
  color: white;
}

.topnav .icon {
  display: none;
}

.dropdown {
  float: left;
  overflow: hidden;
}

.dropdown .dropbtn {
  font-size: 17px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

.dropdown-content {
  display: none;
  position: fixed;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

.dropdown-content a {
  float: none;
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}
#youtubewaw{margin-bottom: 200px;}

.topnav a:hover, .dropdown:hover .dropbtn {
  background-color: #449966;
  color: white;
}

.dropdown-content a:hover {
  background-color: #449966;
  color: black;
}

.dropdown:hover .dropdown-content {
  display: block;
}
@media only screen and (max-width: 1200px) {
    #openinghours{float:none;}
    #addtestimonial{float:none;}

@media only screen and (max-width: 768px) {
    body{font-size:90%;}
    #displayproducts td:nth-child(1){display:none;}
    #commentform{width: auto; font-size: 80%;}
    #mysubmit{margin-left: 0;}
    #openinghours{float:none;}
    td:nth-of-type(4){display:none;}
    #content{ padding: 0px;}}

@media screen and (max-width: 768px) {
    #sitename{display:none;}
  .topnav a:not(:first-child), .dropdown .dropbtn {
    display: none;
  }
  .topnav a.icon {
    float: right;
    display: block;
  }

}

@media screen and (max-width: 768px) {
    #sitename{display:none;}
  .topnav.responsive {position: relative;}
  .topnav.responsive .icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  .topnav.responsive a {
    float: none;
    display: block;
    text-align: left;
  }
  .topnav.responsive .dropdown {float: none;}
  .topnav.responsive .dropdown-content {position: relative;}
  .topnav.responsive .dropdown .dropbtn {
    display: block;
    width: 100%;
    text-align: left;
  }
}
</code>```

答:
I removed the below and everything works again. I don't understand why but I am fairly new to this

.container{
    position: relative;

Title: Form elements not clickable html css

Body:
The button and text fields on my login page are unresponsive / I am unable to click or interact with them. It worked fine yesterday and is linked to a PHP database. I have no idea what code I changed but it was possibly CSS that has stopped it working. Any advice would be great as I am lost.

I have tried editing CSS but to avail.

<!DOCTYPE HTML>

  <title>Maoine in Eirinn (MIE) Wild Atlantic Gaeltacht Properties</title>
  <meta charset="utf-8">
 <link rel="stylesheet" href="css/styles.css">

<?php include("includes/header.html");?>
<?php include("includes/nav.html");?>

<?php
if (empty($_SESSION))
session_start();
if (isset($_SESSION['errors'])) {
echo "
";
foreach($_SESSION['errors'] as $error)
{
 echo "
";
 echo $error;
 echo "
";
}
echo "
";
}
unset($_SESSION['errors']);
?>

 Login

<form action="login_action.php" method="POST">

Username: <input type="text" name="adminname" required="required">

Password: <input type="password" name="password" required="required">

<input type="submit" value="Login">

</form>

<?php include("includes/footer.html");?>

body{background-color: #EEEEEE; }

#container{margin: auto;
    width: 100%;
    background-color: #EEEEEE;
    border: 10px solid #EEEEEE;
    }

#header{
    background-color: #449966;
    height: 110px;
    margin-top: 38px;
    }

#nav{background-color: #000000;
    clear: left;
      }
#moira{
  float:right;
  padding-right: 50px;
  position: relative;
  margin-left: 50px;
}
#martin{
  float:right;
  padding-right: 50px;
  position: relative;
  margin-left: 50px;
}
#openinghours{`
  width: 30%;
  float:left;
  margin-left: 100px;}
#contactus{width: 50%;
  float:left;
  margin-bottom: 200px;}
#content{background-color: #EEEEEE;
    padding: 50px;
    min-height: 500px;
    text-align: center;
    }

#content a {background-color: #449966; color: white; text-decoration:none; padding:5px;}
#content a:hover {background-color: #878787; color: white;}

#footer{background-color: #449966;
    height: 50px;
    padding: 10px;
    display: flex;
    margin-top: 200px;
    bottom: 0;
    width: 100%;
    position: fixed;
}
#comments {width: 70%; float: left;}
.container{
    position: relative;
    border-radius: 8px;
    width: 90%;
    height: 500px;
    overflow: hidden;
}
#login{z-index: 100;}
#logo {float:left;}
#copyright {float:left;}
#footer ul{    text-align: center;
     width: 50%;
     margin: auto;}
#footer a{ color:#449966; }
#socialMedia{float:right; width: 150px; display: flex;}
#sitename{text-align: center;
       width: 100%;}
#languageimage img{
  border: 1px solid #ddd;
  border-radius: 50%;
  float:right;
  display: flex;
  vertical-align: top;}
table td {padding: 10px;}
table {width: 100%}

table tr:nth-child(1) {
    background-color: #449966;
    }
table tr {
    background-color:#FFFFFF;
    }
#displayproperties{width: 75%;}
#addtestimonial{width: 25%; margin-left: 50px; float: right;}
#addtestimonial table {border: 0px;}
#addtestimonial table tr td {padding: 0px; border: 0px;}
#addtestimonial table tr {background-color: #c6e1e0; border: 0px;}

.show {display:block;}

#commentform {
           font-family: Arial;
                 width: auto;
         }
label { float:left;
    width: 50px;
    clear: left;
    text-align: left;
    padding-right: 15px;
    margin-top: 10px;
    }
input, textarea {margin-top: 10px; }
#mysubmit { margin-left:65px;
        padding-bottom: 10px;
          }

body {margin:0;font-family:Arial}

.topnav {
  overflow: hidden;
  background-color: #333;
  position: fixed;
  top: 0;
  width: 100%;
}

.topnav a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.active {
  background-color: #449966;
  color: white;
}

.topnav .icon {
  display: none;
}

.dropdown {
  float: left;
  overflow: hidden;
}

.dropdown .dropbtn {
  font-size: 17px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

.dropdown-content {
  display: none;
  position: fixed;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

.dropdown-content a {
  float: none;
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}
#youtubewaw{margin-bottom: 200px;}

.topnav a:hover, .dropdown:hover .dropbtn {
  background-color: #449966;
  color: white;
}

.dropdown-content a:hover {
  background-color: #449966;
  color: black;
}

.dropdown:hover .dropdown-content {
  display: block;
}
@media only screen and (max-width: 1200px) {
    #openinghours{float:none;}
    #addtestimonial{float:none;}

@media only screen and (max-width: 768px) {
    body{font-size:90%;}
    #displayproducts td:nth-child(1){display:none;}
    #commentform{width: auto; font-size: 80%;}
    #mysubmit{margin-left: 0;}
    #openinghours{float:none;}
    td:nth-of-type(4){display:none;}
    #content{ padding: 0px;}}

@media screen and (max-width: 768px) {
    #sitename{display:none;}
  .topnav a:not(:first-child), .dropdown .dropbtn {
    display: none;
  }
  .topnav a.icon {
    float: right;
    display: block;
  }

}

@media screen and (max-width: 768px) {
    #sitename{display:none;}
  .topnav.responsive {position: relative;}
  .topnav.responsive .icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  .topnav.responsive a {
    float: none;
    display: block;
    text-align: left;
  }
  .topnav.responsive .dropdown {float: none;}
  .topnav.responsive .dropdown-content {position: relative;}
  .topnav.responsive .dropdown .dropbtn {
    display: block;
    width: 100%;
    text-align: left;
  }
}


问:
Unable to get the response of mongoose query inside Vuejs but works with postman request
server side
first here is how my Api works

```<code>  searchPosts(params) {
    return Api().get('search', params);
  },
</code>```

```<code>var postRouter = express.Router();

postRouter.get('/search', (req, res) => {
  var db = req.db;
  Post.find({ capacity: { $lte : req.body.capacity } }, function (error, q) {
    if (error) { console.error(error); }
    res.send({q})
  })
})
</code>```

with this, in my express route im able to do GET request on /search with the body

```<code>{
    "capacity":60
}
</code>```

for exemple, and have a working-as-intended response

```<code>{
    "q": [
        {
         "obj":"obj"
        },
     ]
}
</code>```

Website side
in my .Vue file i call this function after a clic on a button

```<code><v-btn
:disabled="!formIsValid"
flat
color="primary"
type="submit"
@click="searchPost">Search</v-btn>
</code>```

```<code>  methods: {
    async searchPost() {
      const response = await PostsService.searchPosts({
        capacity: this.form.capacity,
        equipments: this.createObjectFromArray(this.form.equipments),
        date: this.form.date,
        time: this.form.time,
      });
      console.log(response);
      this.availableList = response.q;
    },
</code>```

in postman i'm correctly getting a q[] array with all my filtered object inside but on chrome request have no q inside

for my Api logs, i'm getting no error with Postman but

```<code>message:
   'Cast to number failed for value "undefined" at path "capacity" for model "Post"',
  name: 'CastError',
...
</code>```

on the real test on the web

for information, this.availableList is defined inside Data()

```<code> data() {
    const defaultForm = Object.freeze({
      capacity: 0,
      date: new Date().toISOString().substr(0, 10),
      time: null,
      equipments: [],
    });
    return {
      form: Object.assign({}, defaultForm),
      datePicker: false,
      hourMenu: false,
      availableList: [],
      allList: [],
      defaultForm,
    };
  },
</code>```

答:
Make sure your capacity field in your Post model includes type: number. It probably assumes by default that you're submitting a string value if you do not declare the type as number explicitly in the model.

Also, because you are awaiting the response, you also have to ensure your data assignment waits for the response to return. Try this:

```<code>methods: {
    async searchPost() {
      const response = await PostsService.searchPosts({
        capacity: this.form.capacity,
        equipments: this.createObjectFromArray(this.form.equipments),
        date: this.form.date,
        time: this.form.time,
      })
      .then( response => {
         console.log(response);
         this.availableList = response.data.q;
       }
    )}
</code>```

Notice that instead of response.q I used response.data.q. I can't test this at the moment, so if it doesn't work try switching back to response.q.

Body:
server side
first here is how my Api works

  searchPosts(params) {
    return Api().get('search', params);
  },

var postRouter = express.Router();

postRouter.get('/search', (req, res) => {
  var db = req.db;
  Post.find({ capacity: { $lte : req.body.capacity } }, function (error, q) {
    if (error) { console.error(error); }
    res.send({q})
  })
})

with this, in my express route im able to do GET request on /search with the body

{
    "capacity":60
}

for exemple, and have a working-as-intended response

{
    "q": [
        {
         "obj":"obj"
        },
     ]
}

Website side
in my .Vue file i call this function after a clic on a button

<v-btn
:disabled="!formIsValid"
flat
color="primary"
type="submit"
@click="searchPost">Search</v-btn>

  methods: {
    async searchPost() {
      const response = await PostsService.searchPosts({
        capacity: this.form.capacity,
        equipments: this.createObjectFromArray(this.form.equipments),
        date: this.form.date,
        time: this.form.time,
      });
      console.log(response);
      this.availableList = response.q;
    },

in postman i'm correctly getting a q[] array with all my filtered object inside but on chrome request have no q inside

for my Api logs, i'm getting no error with Postman but

message:
   'Cast to number failed for value "undefined" at path "capacity" for model "Post"',
  name: 'CastError',
...

on the real test on the web

for information, this.availableList is defined inside Data()

 data() {
    const defaultForm = Object.freeze({
      capacity: 0,
      date: new Date().toISOString().substr(0, 10),
      time: null,
      equipments: [],
    });
    return {
      form: Object.assign({}, defaultForm),
      datePicker: false,
      hourMenu: false,
      availableList: [],
      allList: [],
      defaultForm,
    };
  },

Body:
Make sure your capacity field in your Post model includes type: number. It probably assumes by default that you're submitting a string value if you do not declare the type as number explicitly in the model.

Also, because you are awaiting the response, you also have to ensure your data assignment waits for the response to return. Try this:

methods: {
    async searchPost() {
      const response = await PostsService.searchPosts({
        capacity: this.form.capacity,
        equipments: this.createObjectFromArray(this.form.equipments),
        date: this.form.date,
        time: this.form.time,
      })
      .then( response => {
         console.log(response);
         this.availableList = response.data.q;
       }
    )}

Notice that instead of response.q I used response.data.q. I can't test this at the moment, so if it doesn't work try switching back to response.q.