问:
Modern C++: initialize constexpr tables
Suppose I have a class X, which functionality requires a lot of constant table values, say an array A[1024]. I have a recurrent function f that computes its values, smth like

```<code>A[x] = f(A[x - 1]);
</code>```

Suppose that A[0] is a known constant, therefore the rest of the array is constant too. What is the best way to calculate these values beforehand, using features of modern C++, and without storaging file with hardcoded values of this array? My workaround was a const static dummy variable:

```<code>const bool X::dummy = X::SetupTables();

bool X::SetupTables() {
    A[0] = 1;
    for (size_t i = 1; i <= A.size(); ++i)
        A[i] = f(A[i - 1]);
}
</code>```

But I believe, it’s not the most beautiful way to go.
Note: I emphasize that array is rather big and I want to avoid monstrosity of the code.

答:
I think this way is more readable:

```<code>#include <array>

constexpr int f(int a) { return a + 1; }

constexpr void init(auto &A)
{
  A[0] = 1;
  for (int i = 1; i < A.size(); i++) {
    A[i] = f(A[i - 1]);
  }
}

int main() {
  std::array<int, 1024> A;
  A[0] = 1;
  init(A);
}
</code>```

I need to make a disclaimer, that for big array sizes it is not guaranteed to generate array in constant time. And the accepted answer is more likely to generate the full array during template expansion.

But the way I propose has number of advantages:

It is quite safe that the compiler will not eat up all your memory and fails to expand the template.

The compilation speed is significantly faster

You use C++-ish interface when you use an array

The code is in general more readable

In a particular example when you need only one value, the variant with templates generated for me only a single number, while the variant with std::array generated a loop.

Update

Thanks to Navin I found a way to force compile time evaluation of the array.

You can force it to run at compile time if you return by value: std::array A = init();

So with slight modification the code looks as follows:

```<code>#include <array>

constexpr int f(int a) { return a + 1; }

constexpr auto init()
{
  // Need to initialize the array
  std::array<int, SIZE> A = {0};
  A[0] = 1;
  for (unsigned i = 1; i < A.size(); i++) {
    A[i] = f(A[i - 1]);
  }
  return A;
}

int main() {
  auto A = init();
  return A[SIZE - 1];
}
</code>```

To have this compiled one needs C++17 support, otherwise operator [] from std::array is not constexpr. I also update the measurements.

On assembly output

As I mentioned earlier the template variant is more concise. Please look here for more detail.

In the template variant, when I just pick the last value of the array, the whole assembly looks as follows:

```<code>main:
  mov eax, 1024
  ret
</code>```

While for std::array variant I have a loop:

```<code>main:
        subq    $3984, %rsp
        movl    $1, %eax
.L2:
        leal    1(%rax), %edx
        movl    %edx, -120(%rsp,%rax,4)
        addq    $1, %rax
        cmpq    $1024, %rax
        jne     .L2
        movl    3972(%rsp), %eax
        addq    $3984, %rsp
        ret
</code>```

With std::array and return by value the assemble is identical to version with templates:

```<code>main:
  mov eax, 1024
  ret
</code>```

On compilation speed

I compared these two variants:

test2.cpp:

```<code>#include <utility>

constexpr int f(int a) { return a + 1; }

template<int... Idxs>
constexpr void init(int* A, std::integer_sequence<int, Idxs...>) {
    auto discard = {A[Idxs] = f(A[Idxs - 1])...};
    static_cast<void>(discard);
}

int main() {
    int A[SIZE];
    A[0] = 1;
    init(A + 1, std::make_integer_sequence<int, sizeof A / sizeof *A - 1>{});
}
</code>```

test.cpp:

```<code>#include <array>

constexpr int f(int a) { return a + 1; }

constexpr void init(auto &A)
{
    A[0] = 1;
    for (int i = 1; i < A.size(); i++) {
        A[i] = f(A[i - 1]);
    }
}

int main() {
    std::array<int, SIZE> A;
    A[0] = 1;
    init(A);
}
</code>```

The results are:

```<code>|  Size | Templates (s) | std::array (s) | by value |
|-------+---------------+----------------+----------|
|  1024 |          0.32 |           0.23 | 0.38s    |
|  2048 |          0.52 |           0.23 | 0.37s    |
|  4096 |          0.94 |           0.23 | 0.38s    |
|  8192 |          1.87 |           0.22 | 0.46s    |
| 16384 |          3.93 |           0.22 | 0.76s    |
</code>```

How I generated:

```<code>for SIZE in 1024 2048 4096 8192 16384
do
    echo $SIZE
    time g++ -DSIZE=$SIZE test2.cpp
    time g++ -DSIZE=$SIZE test.cpp
    time g++ -std=c++17 -DSIZE=$SIZE test3.cpp
done
</code>```

And if you enable optimizations, the speed of code with template is even worse:

```<code>|  Size | Templates (s) | std::array (s) | by value |
|-------+---------------+----------------+----------|
|  1024 |          0.92 |           0.26 | 0.29s    |
|  2048 |          2.81 |           0.25 | 0.33s    |
|  4096 |         10.94 |           0.23 | 0.36s    |
|  8192 |         52.34 |           0.24 | 0.39s    |
| 16384 |        211.29 |           0.24 | 0.56s    |
</code>```

How I generated:

```<code>#include <array>

constexpr int f(int a) { return a + 1; }

constexpr auto init()
{
  // Need to initialize the array
  std::array<int, SIZE> A = {0};
  A[0] = 1;
  for (unsigned i = 1; i < A.size(); i++) {
    A[i] = f(A[i - 1]);
  }
  return A;
}

int main() {
  auto A = init();
  return A[SIZE - 1];
}
</code>```0

My gcc version:

```<code>#include <array>

constexpr int f(int a) { return a + 1; }

constexpr auto init()
{
  // Need to initialize the array
  std::array<int, SIZE> A = {0};
  A[0] = 1;
  for (unsigned i = 1; i < A.size(); i++) {
    A[i] = f(A[i - 1]);
  }
  return A;
}

int main() {
  auto A = init();
  return A[SIZE - 1];
}
</code>```1

Title: Modern C++: initialize constexpr tables

Body:
Suppose I have a class X, which functionality requires a lot of constant table values, say an array A[1024]. I have a recurrent function f that computes its values, smth like

A[x] = f(A[x - 1]);

Suppose that A[0] is a known constant, therefore the rest of the array is constant too. What is the best way to calculate these values beforehand, using features of modern C++, and without storaging file with hardcoded values of this array? My workaround was a const static dummy variable:

const bool X::dummy = X::SetupTables();

bool X::SetupTables() {
    A[0] = 1;
    for (size_t i = 1; i <= A.size(); ++i)
        A[i] = f(A[i - 1]);
}

But I believe, it’s not the most beautiful way to go.
Note: I emphasize that array is rather big and I want to avoid monstrosity of the code.

Body:
I think this way is more readable:

#include <array>

constexpr int f(int a) { return a + 1; }

constexpr void init(auto &A)
{
  A[0] = 1;
  for (int i = 1; i < A.size(); i++) {
    A[i] = f(A[i - 1]);
  }
}

int main() {
  std::array<int, 1024> A;
  A[0] = 1;
  init(A);
}

I need to make a disclaimer, that for big array sizes it is not guaranteed to generate array in constant time. And the accepted answer is more likely to generate the full array during template expansion.

But the way I propose has number of advantages:

It is quite safe that the compiler will not eat up all your memory and fails to expand the template.

The compilation speed is significantly faster

You use C++-ish interface when you use an array

The code is in general more readable

In a particular example when you need only one value, the variant with templates generated for me only a single number, while the variant with std::array generated a loop.

Update

Thanks to Navin I found a way to force compile time evaluation of the array.

You can force it to run at compile time if you return by value: std::array A = init();

So with slight modification the code looks as follows:

#include <array>

constexpr int f(int a) { return a + 1; }

constexpr auto init()
{
  // Need to initialize the array
  std::array<int, SIZE> A = {0};
  A[0] = 1;
  for (unsigned i = 1; i < A.size(); i++) {
    A[i] = f(A[i - 1]);
  }
  return A;
}

int main() {
  auto A = init();
  return A[SIZE - 1];
}

To have this compiled one needs C++17 support, otherwise operator [] from std::array is not constexpr. I also update the measurements.

On assembly output

As I mentioned earlier the template variant is more concise. Please look here for more detail.

In the template variant, when I just pick the last value of the array, the whole assembly looks as follows:

main:
  mov eax, 1024
  ret

While for std::array variant I have a loop:

main:
        subq    $3984, %rsp
        movl    $1, %eax
.L2:
        leal    1(%rax), %edx
        movl    %edx, -120(%rsp,%rax,4)
        addq    $1, %rax
        cmpq    $1024, %rax
        jne     .L2
        movl    3972(%rsp), %eax
        addq    $3984, %rsp
        ret

With std::array and return by value the assemble is identical to version with templates:

main:
  mov eax, 1024
  ret

On compilation speed

I compared these two variants:

test2.cpp:

#include <utility>

constexpr int f(int a) { return a + 1; }

template<int... Idxs>
constexpr void init(int* A, std::integer_sequence<int, Idxs...>) {
    auto discard = {A[Idxs] = f(A[Idxs - 1])...};
    static_cast<void>(discard);
}

int main() {
    int A[SIZE];
    A[0] = 1;
    init(A + 1, std::make_integer_sequence<int, sizeof A / sizeof *A - 1>{});
}

test.cpp:

#include <array>

constexpr int f(int a) { return a + 1; }

constexpr void init(auto &A)
{
    A[0] = 1;
    for (int i = 1; i < A.size(); i++) {
        A[i] = f(A[i - 1]);
    }
}

int main() {
    std::array<int, SIZE> A;
    A[0] = 1;
    init(A);
}

The results are:

|  Size | Templates (s) | std::array (s) | by value |
|-------+---------------+----------------+----------|
|  1024 |          0.32 |           0.23 | 0.38s    |
|  2048 |          0.52 |           0.23 | 0.37s    |
|  4096 |          0.94 |           0.23 | 0.38s    |
|  8192 |          1.87 |           0.22 | 0.46s    |
| 16384 |          3.93 |           0.22 | 0.76s    |

How I generated:

for SIZE in 1024 2048 4096 8192 16384
do
    echo $SIZE
    time g++ -DSIZE=$SIZE test2.cpp
    time g++ -DSIZE=$SIZE test.cpp
    time g++ -std=c++17 -DSIZE=$SIZE test3.cpp
done

And if you enable optimizations, the speed of code with template is even worse:

|  Size | Templates (s) | std::array (s) | by value |
|-------+---------------+----------------+----------|
|  1024 |          0.92 |           0.26 | 0.29s    |
|  2048 |          2.81 |           0.25 | 0.33s    |
|  4096 |         10.94 |           0.23 | 0.36s    |
|  8192 |         52.34 |           0.24 | 0.39s    |
| 16384 |        211.29 |           0.24 | 0.56s    |

How I generated:

for SIZE in 1024 2048 4096 8192 16384
do
    echo $SIZE
    time g++ -O3 -march=native -DSIZE=$SIZE test2.cpp
    time g++ -O3 -march=native -DSIZE=$SIZE test.cpp
    time g++ -O3 -std=c++17 -march=native -DSIZE=$SIZE test3.cpp
done

My gcc version:

$ g++ --version
g++ (Debian 7.2.0-1) 7.2.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.


来源: stackexchange

问:
HeapSort Algorythm from txt file to list of arrays doesn't Sort the numbers
So I have to make HeapSort Algorythm for University using pseudocode I was given (only for heapsort). And I have to use input and output file. But for now I have only made input file which is working fine since it loads the txt file and writes down all the numbers in Console. So the problem is that after adding sorting methods to Main nothing changes. Also I decided to make a test for every method and all of them writes down my numbers once and that is it. I am not really good with sorting so it is hard for me to find the issue. Also because it is from pseudocode I had to use and no the code I could do for myself. So Do You know what cause thats issue that the sorting doesn't occure?</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
using System.IO;
using System.Windows.Forms;
namespace Zad4
{
    class Program
    {
        void Heapify(List<int> array, int i, int n)
        {
            int largest, temp;
            int parent = i;
            int left = 2 * i + 1;
            int right = 2 * i + 2;

            if (left < n && array[left] > array[parent])
            {
                largest = left;
            }
            else
            {
                largest = parent;
            }

            if (right < n && array[right] > array[largest])
            {
                largest = right;
            }
            if (largest != i)
            {

                temp = array[i];
                array[i] = array[largest];
                array[largest] = temp;

                Heapify(array, largest, n);
            }

        }

        void BuildHeap(List<int> array, int n)
        {
            int i;
            for (i = (n - 1) / 2; i >= 0; i--)
            {
                Heapify(array, i, n);
            }

        }

        void HeapSort(List<int> array, int n)
        {
            int i, temp;
            for (i = n - 1; i >= 0; i--)
            {
                temp = array[0];
                array[0] = array[n - 1];
                array[n - 1] = temp;

                n = n - 1;

                Heapify(array, 0, n);
                Console.WriteLine(string.Join(" ", array));
            }
        }

        static void Main(string[] args)
        {
            int n = 0;
            Program A = new Program();

            StreamReader myFile =
               new StreamReader("C:\\Users\\dawid\\Desktop\\C#\\Heapsort\\dane.txt");
            string myString = myFile.ReadToEnd();

            myFile.Close();

            char rc = (char)10;
            String[] listLines = myString.Split(rc);
            List<List<int>> listArrays = new List<List<int>>();
            for (int i = 0; i < listLines.Length; i++)
            {
                List<int> array = new List<int>();
                String[] listInts = listLines[i].Split(' ');
                for (int j = 0; j < listInts.Length; j++)
                {
                    if (listInts[j] != "\r")
                    {
                        array.Add(Convert.ToInt32(listInts[j]));
                    }
                }
                listArrays.Add(array);

               A.BuildHeap(array, n);
               A.HeapSort(array, n);
            }

            foreach (List<int> array in listArrays)
            {
                foreach (int i in array)
                {
                    Console.WriteLine(string.Join(" ", array));
                }
            }
            Console.WriteLine();
            Console.ReadLine();
        }
    }
}
</code>```

答:
So the solution I found is just changing the way I read my txt file and the most important one was bad use of my methods. So that is how it looks now and it sorting well. Maybe I shouldn't ask a question since I got an answer on my own. But well. There You go:</p>

```<code> static void Main(string[] args)
    {

        Program A = new Program();
        string[] array = System.IO.File.ReadAllLines(@"C:\Users\dawid\Desktop\C#\Heapsort\dane.txt");
        int[] arrayInt = Array.ConvertAll(array, int.Parse);
        A.BuildHeap(arrayInt, arrayInt.Length);
        A.HeapSort(arrayInt, arrayInt.Length);
        Console.WriteLine(string.Join(" ", arrayInt));
        Console.ReadLine();
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So I have to make HeapSort Algorythm for University using pseudocode I was given (only for heapsort). And I have to use input and output file. But for now I have only made input file which is working fine since it loads the txt file and writes down all the numbers in Console. So the problem is that after adding sorting methods to Main nothing changes. Also I decided to make a test for every method and all of them writes down my numbers once and that is it. I am not really good with sorting so it is hard for me to find the issue. Also because it is from pseudocode I had to use and no the code I could do for myself. So Do You know what cause thats issue that the sorting doesn't occure?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
using System.IO;
using System.Windows.Forms;
namespace Zad4
{
    class Program
    {
        void Heapify(List<int> array, int i, int n)
        {
            int largest, temp;
            int parent = i;
            int left = 2 * i + 1;
            int right = 2 * i + 2;

            if (left < n && array[left] > array[parent])
            {
                largest = left;
            }
            else
            {
                largest = parent;
            }

            if (right < n && array[right] > array[largest])
            {
                largest = right;
            }
            if (largest != i)
            {

                temp = array[i];
                array[i] = array[largest];
                array[largest] = temp;

                Heapify(array, largest, n);
            }

        }

        void BuildHeap(List<int> array, int n)
        {
            int i;
            for (i = (n - 1) / 2; i >= 0; i--)
            {
                Heapify(array, i, n);
            }

        }

        void HeapSort(List<int> array, int n)
        {
            int i, temp;
            for (i = n - 1; i >= 0; i--)
            {
                temp = array[0];
                array[0] = array[n - 1];
                array[n - 1] = temp;

                n = n - 1;

                Heapify(array, 0, n);
                Console.WriteLine(string.Join(" ", array));
            }
        }

        static void Main(string[] args)
        {
            int n = 0;
            Program A = new Program();

            StreamReader myFile =
               new StreamReader("C:\\Users\\dawid\\Desktop\\C#\\Heapsort\\dane.txt");
            string myString = myFile.ReadToEnd();

            myFile.Close();

            char rc = (char)10;
            String[] listLines = myString.Split(rc);
            List<List<int>> listArrays = new List<List<int>>();
            for (int i = 0; i < listLines.Length; i++)
            {
                List<int> array = new List<int>();
                String[] listInts = listLines[i].Split(' ');
                for (int j = 0; j < listInts.Length; j++)
                {
                    if (listInts[j] != "\r")
                    {
                        array.Add(Convert.ToInt32(listInts[j]));
                    }
                }
                listArrays.Add(array);

               A.BuildHeap(array, n);
               A.HeapSort(array, n);
            }

            foreach (List<int> array in listArrays)
            {
                foreach (int i in array)
                {
                    Console.WriteLine(string.Join(" ", array));
                }
            }
            Console.WriteLine();
            Console.ReadLine();
        }
    }
}

Body:
So the solution I found is just changing the way I read my txt file and the most important one was bad use of my methods. So that is how it looks now and it sorting well. Maybe I shouldn't ask a question since I got an answer on my own. But well. There You go:

 static void Main(string[] args)
    {

        Program A = new Program();
        string[] array = System.IO.File.ReadAllLines(@"C:\Users\dawid\Desktop\C#\Heapsort\dane.txt");
        int[] arrayInt = Array.ConvertAll(array, int.Parse);
        A.BuildHeap(arrayInt, arrayInt.Length);
        A.HeapSort(arrayInt, arrayInt.Length);
        Console.WriteLine(string.Join(" ", arrayInt));
        Console.ReadLine();
    }


问:
Convert string of hex to char array c++
I have a string that represents an hexadecimal number:

```<code>std::string hex = "3371";
</code>```

I want to convert it to a char array:

```<code>char hex[2] {0x33, 0x71};
</code>```

Is there any convenient way to do it? I can use c++11 features, if it may help.

Motivation:
I need to save an integer (4 bytes), using 2 bytes char array.
The way how I thought it can be done is to convert it to string using std::hex, and then convert the string to the char array, but this is the point where I cannot continue..
If there is another simple way - I would like to hear :)

Important: I can assume that the hex number is less than 0xFFFF, and a positive number.

答:
I found out a better way to convert a number to char array, as I needed. This solution works only for unsigned types!

```<code>template <typename T> bool ToByteArray(T num, unsigned char* ret, size_t size) {
  if (ret == nullptr) {
      std::cout << "Error in: " << __func__ << ": nullptr" << std::endl;
      return false;
  }
  // drop the right-most bytes and convert to new right most byte.
  for (int i = 0; i < size; i++) {
      ret[i] = (int)((num >> (24 - 8*i)) & 0xFF);
  }
  return true;
}
</code>```

This is more elegant way to do it.

If you want to convert it back - you might use:

```<code>long FormatBlock(const unsigned char* arr, size_t size) {
  long num = 0;
  for (int i = 0; i < size; i++) {
      num += ((long)arr[i] << (24 - i*8));
  }
  return num;
}
</code>```

Title: Convert string of hex to char array c++

Body:
I have a string that represents an hexadecimal number:

std::string hex = "3371";

I want to convert it to a char array:

char hex[2] {0x33, 0x71};

Is there any convenient way to do it? I can use c++11 features, if it may help.

Motivation:
I need to save an integer (4 bytes), using 2 bytes char array.
The way how I thought it can be done is to convert it to string using std::hex, and then convert the string to the char array, but this is the point where I cannot continue..
If there is another simple way - I would like to hear :)

Important: I can assume that the hex number is less than 0xFFFF, and a positive number.

Body:
I found out a better way to convert a number to char array, as I needed. This solution works only for unsigned types!

template <typename T> bool ToByteArray(T num, unsigned char* ret, size_t size) {
  if (ret == nullptr) {
      std::cout << "Error in: " << __func__ << ": nullptr" << std::endl;
      return false;
  }
  // drop the right-most bytes and convert to new right most byte.
  for (int i = 0; i < size; i++) {
      ret[i] = (int)((num >> (24 - 8*i)) & 0xFF);
  }
  return true;
}

This is more elegant way to do it.

If you want to convert it back - you might use:

long FormatBlock(const unsigned char* arr, size_t size) {
  long num = 0;
  for (int i = 0; i < size; i++) {
      num += ((long)arr[i] << (24 - i*8));
  }
  return num;
}


问:
Numerically sorting the String Arrays
I already know that we can sort string arrays numerically, by converting them to integer array then using Arrays.sort() or using any comparator.

So my question is if those strings are beyond the limit of integer or long int then how can we sort them. For example consider the following string array:

```<code>14829435897932384626433832795
4159265358979323846264338327
1937286535897932384626433832795296523
23746289
</code>```

in those cases traditional comparator or any sorting method won't work because in turn they use integer (or any other datatype).

答:
You can use Arrays.sort(array, comparator)

```<code>Arrays.sort(array, Comparator.comparing(BigInteger::new));
</code>```

The comparator can take as parameter a function that maps an object into another one (here String into BigInteger)

With details (from shorter to longer, Intellij will propose you to use 1st one) :  :

```<code>= Comparator.comparing(BigInteger::new)
= Comparator.comparing(val -> new BigInteger(val))
= Comparator.comparing((o1, o2) -> new BigInteger(o1).compareTo(new BigInteger(o2)))
</code>```

```<code>String[] array = new String[]{"14829435897932384626433832795",
                              "4159265358979323846264338327",
                              "1937286535897932384626433832795296523", "23746289"};
Arrays.sort(array, Comparator.comparing(BigInteger::new));
System.out.println(Arrays.toString(array));

//Will result in
[23746289, 4159265358979323846264338327, 14829435897932384626433832795, 1937286535897932384626433832795296523]
</code>```

Title: Numerically sorting the String Arrays

Body:
I already know that we can sort string arrays numerically, by converting them to integer array then using Arrays.sort() or using any comparator.

So my question is if those strings are beyond the limit of integer or long int then how can we sort them. For example consider the following string array:

14829435897932384626433832795
4159265358979323846264338327
1937286535897932384626433832795296523
23746289

in those cases traditional comparator or any sorting method won't work because in turn they use integer (or any other datatype).

Body:
You can use Arrays.sort(array, comparator)

Arrays.sort(array, Comparator.comparing(BigInteger::new));

The comparator can take as parameter a function that maps an object into another one (here String into BigInteger)

With details (from shorter to longer, Intellij will propose you to use 1st one) :  :

= Comparator.comparing(BigInteger::new)
= Comparator.comparing(val -> new BigInteger(val))
= Comparator.comparing((o1, o2) -> new BigInteger(o1).compareTo(new BigInteger(o2)))

String[] array = new String[]{"14829435897932384626433832795",
                              "4159265358979323846264338327",
                              "1937286535897932384626433832795296523", "23746289"};
Arrays.sort(array, Comparator.comparing(BigInteger::new));
System.out.println(Arrays.toString(array));

//Will result in
[23746289, 4159265358979323846264338327, 14829435897932384626433832795, 1937286535897932384626433832795296523]


问:
Python concurrent.futures: handling exceptions in child processes
I have a pretty plain vanilla implementation of concurrent.futures.ProcessPoolExecutor -- something like (using Python 3.6):

```<code>files = get_files()
processor = get_processor_instance()
with concurrent.futures.ProcessPoolExecutor() as executor:
    list(executor.map(processor.process, files))
</code>```

While the processor is an instance of any of a number of available processor classes, they all share the process method, which looks roughly like this:

```<code>def process(self, file):
    log.debug(f"Processing source file {file.name}.")
    with DBConnection(self.db_url) as session:
        file = session.merge(file)
        session.refresh(file)
        self._set_file(file)
        timer = perf_counter()
        try:
            self.records = self._get_records()
            self._save_output()
        except Exception as ex:
            log.warning(f"Failed to process source file {file.ORIGINAL_NAME}: {ex}")
            self.error_time = time.time()
            self.records = None
        else:
            process_duration = perf_counter() - timer
            log.info(f'File {file.name} processed in {process_duration:.6f} seconds.')
            file.process_duration = process_duration
        session.commit()
</code>```

Implementation of the _get_records and _save_output methods vary per class, but my problem is with handling of errors. I'm deliberately testing it so that one of those two methods runs out of memory, but I would expect the except block above to catch it and move the the next file -- and this is precisely what happens when I run the code in a single process.

If I use ProcessPoolExecutor as described above, it raises the BrokenProcessPool exception and kills all execution:

```<code>Traceback (most recent call last):
  File "/vagrant/myapp/myapp.py", line 94, in _process
    list(executor.map(processor.process, files))
  File "/home/ubuntu/.pyenv/versions/3.6.3/lib/python3.6/concurrent/futures/process.py", line 366, in _chain_from_iterable_of_lists
    for element in iterable:
  File "/home/ubuntu/.pyenv/versions/3.6.3/lib/python3.6/concurrent/futures/_base.py", line 586, in result_iterator
    yield fs.pop().result()
  File "/home/ubuntu/.pyenv/versions/3.6.3/lib/python3.6/concurrent/futures/_base.py", line 432, in result
    return self.__get_result()
  File "/home/ubuntu/.pyenv/versions/3.6.3/lib/python3.6/concurrent/futures/_base.py", line 384, in __get_result
    raise self._exception
concurrent.futures.process.BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending.
</code>```

I can of course catch the BrokenProcessPool in the calling code, but I'd prefer to handle the error internally and proceed to the next file.

I also tried using the standard multiprocessing.Pool object, like this:

```<code>with multiprocessing.Pool() as pool:
    pool.map(processor.process, files)
</code>```

In this case, the behaviour is even weirder: after starting to process the first two files, which raise the out of memory error, it moves on to processing the later files, which are smaller so get processed completely. However, the except block apparently never gets triggered (no log messages, no error_time), and the application just hangs, neither finishing nor doing anything, until killed manually.

I was hoping that the try..except block would make each process self-contained, handling its own errors without affecting the main application. Any ideas how to achieve that?

答:
So, after a lot of debugging (and with a due credit to @RomanPerekhrest's suggestion to check the executor object), I've figured the cause. As described in the question, the test data consisted of a number of files, two of which were quite large (over 1 million lines of CSV, each). Those two each caused my test machine (a 2GB VM) to choke, but in different ways -- while the first, which was larger, caused a regular out of memory error which would be handled by the except, the second simply caused a sigkill. Without exploring too much, I suspect that the larger file simply couldn't fit in the memory on read (done in the _get_records method), while the smaller one could, but then manipulation on it (done in _save_output) caused the overflow and killed the process.

My solution was to simply catch the BrokenProcessPool exception and inform the user of the issue; I also added an option which runs the processing tasks in one process, in which case any too-large files are simply marked as having an error:

```<code>files = get_files()
processor = get_processor_instance()
results = []
if args.nonconcurrent:
    results = list(map(processor.process, files))
else:
    with concurrent.futures.ProcessPoolExecutor() as executor:
        try:
            results = list(executor.map(processor.process, files))
        except concurrent.futures.process.BrokenProcessPool as ex:
            raise MyCustomProcessingError(
                f"{ex} This might be caused by limited system resources. "
                "Try increasing system memory or disable concurrent processing "
                "using the --nonconcurrent option."
            )
</code>```

Body:
I have a pretty plain vanilla implementation of concurrent.futures.ProcessPoolExecutor -- something like (using Python 3.6):

files = get_files()
processor = get_processor_instance()
with concurrent.futures.ProcessPoolExecutor() as executor:
    list(executor.map(processor.process, files))

While the processor is an instance of any of a number of available processor classes, they all share the process method, which looks roughly like this:

def process(self, file):
    log.debug(f"Processing source file {file.name}.")
    with DBConnection(self.db_url) as session:
        file = session.merge(file)
        session.refresh(file)
        self._set_file(file)
        timer = perf_counter()
        try:
            self.records = self._get_records()
            self._save_output()
        except Exception as ex:
            log.warning(f"Failed to process source file {file.ORIGINAL_NAME}: {ex}")
            self.error_time = time.time()
            self.records = None
        else:
            process_duration = perf_counter() - timer
            log.info(f'File {file.name} processed in {process_duration:.6f} seconds.')
            file.process_duration = process_duration
        session.commit()

Implementation of the _get_records and _save_output methods vary per class, but my problem is with handling of errors. I'm deliberately testing it so that one of those two methods runs out of memory, but I would expect the except block above to catch it and move the the next file -- and this is precisely what happens when I run the code in a single process.

If I use ProcessPoolExecutor as described above, it raises the BrokenProcessPool exception and kills all execution:

Traceback (most recent call last):
  File "/vagrant/myapp/myapp.py", line 94, in _process
    list(executor.map(processor.process, files))
  File "/home/ubuntu/.pyenv/versions/3.6.3/lib/python3.6/concurrent/futures/process.py", line 366, in _chain_from_iterable_of_lists
    for element in iterable:
  File "/home/ubuntu/.pyenv/versions/3.6.3/lib/python3.6/concurrent/futures/_base.py", line 586, in result_iterator
    yield fs.pop().result()
  File "/home/ubuntu/.pyenv/versions/3.6.3/lib/python3.6/concurrent/futures/_base.py", line 432, in result
    return self.__get_result()
  File "/home/ubuntu/.pyenv/versions/3.6.3/lib/python3.6/concurrent/futures/_base.py", line 384, in __get_result
    raise self._exception
concurrent.futures.process.BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending.

I can of course catch the BrokenProcessPool in the calling code, but I'd prefer to handle the error internally and proceed to the next file.

I also tried using the standard multiprocessing.Pool object, like this:

with multiprocessing.Pool() as pool:
    pool.map(processor.process, files)

In this case, the behaviour is even weirder: after starting to process the first two files, which raise the out of memory error, it moves on to processing the later files, which are smaller so get processed completely. However, the except block apparently never gets triggered (no log messages, no error_time), and the application just hangs, neither finishing nor doing anything, until killed manually.

I was hoping that the try..except block would make each process self-contained, handling its own errors without affecting the main application. Any ideas how to achieve that?

Body:
So, after a lot of debugging (and with a due credit to @RomanPerekhrest's suggestion to check the executor object), I've figured the cause. As described in the question, the test data consisted of a number of files, two of which were quite large (over 1 million lines of CSV, each). Those two each caused my test machine (a 2GB VM) to choke, but in different ways -- while the first, which was larger, caused a regular out of memory error which would be handled by the except, the second simply caused a sigkill. Without exploring too much, I suspect that the larger file simply couldn't fit in the memory on read (done in the _get_records method), while the smaller one could, but then manipulation on it (done in _save_output) caused the overflow and killed the process.

My solution was to simply catch the BrokenProcessPool exception and inform the user of the issue; I also added an option which runs the processing tasks in one process, in which case any too-large files are simply marked as having an error:

files = get_files()
processor = get_processor_instance()
results = []
if args.nonconcurrent:
    results = list(map(processor.process, files))
else:
    with concurrent.futures.ProcessPoolExecutor() as executor:
        try:
            results = list(executor.map(processor.process, files))
        except concurrent.futures.process.BrokenProcessPool as ex:
            raise MyCustomProcessingError(
                f"{ex} This might be caused by limited system resources. "
                "Try increasing system memory or disable concurrent processing "
                "using the --nonconcurrent option."
            )

ContentLicense: CC BY-SA 4.0


问:
C - I'm having trouble coding a "rotate right" function
I'm having a little trouble writing my code to rotate my hexadecimal digits right. Below is a function I wrote, where, if you call on it, passing it like so: rotr(0x12345678, 4), it should return 0x81234567. Instead, it's only returning 7 digits (as opposed to eight, like in the original value = 0x12345678).

Can someone please help me understand what is going on in the bit level? I'm having trouble understanding why my current code is returning 0x123456f, instead of 0x81234567. Thanks in advance!

Edit: is it because I'm shifting 0x12345678 too early? I'm mainly trying to figure out why only seven digits return back, as opposed to eight.

```<code>unsigned int rotr(unsigned int x, int n) {
    int i; //iterate for loop
    unsigned int y; //masked last bit
    unsigned int z; //final result

    for (i=1; i<=n; i++) {
        y = x & 0x1; //isolates last bit
        x = x >> 1; //shift right 1
        z = x | (y << (sizeof(x)-1)); //shifts mask back to first slot; OR
                                      //it with x
    }

    return z;
}
</code>```

答:
instead of sizeof(x) you should write 8*sizeof(x), it's looks generic because your input may be short int, long int or anything.

For Right Rotation instead of rotating loops you can try below logic.

```<code>#include<stdio.h>
unsigned int rotr(unsigned int x, int n) {
        unsigned int z;
        z = (x >> n) | (x << (8*sizeof(int) - n)) ;
        return z;
}
int main()
{
        unsigned  int num= 0x12345678, n = 4, ret;

        printf("before : %x\n",num);
        ret= rotr(num,n);
        printf("before : %x\n",ret);
}
</code>```

Body:
I'm having a little trouble writing my code to rotate my hexadecimal digits right. Below is a function I wrote, where, if you call on it, passing it like so: rotr(0x12345678, 4), it should return 0x81234567. Instead, it's only returning 7 digits (as opposed to eight, like in the original value = 0x12345678).

Can someone please help me understand what is going on in the bit level? I'm having trouble understanding why my current code is returning 0x123456f, instead of 0x81234567. Thanks in advance!

Edit: is it because I'm shifting 0x12345678 too early? I'm mainly trying to figure out why only seven digits return back, as opposed to eight.

unsigned int rotr(unsigned int x, int n) {
    int i; //iterate for loop
    unsigned int y; //masked last bit
    unsigned int z; //final result

    for (i=1; i<=n; i++) {
        y = x & 0x1; //isolates last bit
        x = x >> 1; //shift right 1
        z = x | (y << (sizeof(x)-1)); //shifts mask back to first slot; OR
                                      //it with x
    }

    return z;
}

Body:
instead of sizeof(x) you should write 8*sizeof(x), it's looks generic because your input may be short int, long int or anything.

For Right Rotation instead of rotating loops you can try below logic.

#include<stdio.h>
unsigned int rotr(unsigned int x, int n) {
        unsigned int z;
        z = (x >> n) | (x << (8*sizeof(int) - n)) ;
        return z;
}
int main()
{
        unsigned  int num= 0x12345678, n = 4, ret;

        printf("before : %x\n",num);
        ret= rotr(num,n);
        printf("before : %x\n",ret);
}


问:
how to style a particular wordpress sidebar widget
I have sidebar widgets visible when I open a post in my website. But since the website is bilingual, some of them are supposed to be right aligned while others left aligned.

Is this possible? If I knew which function is generating the content for sidebar HTML, perhaps I could achieve this but I don't know where that function is, if it existed.

答:
umm... kinda got it working.

I made the following changes to the file:
wp-includes\widgets\class-wp-widget-recent-posts.php

It had the following code:

```<code><ul>
        <?php while ( $r->have_posts() ) : $r->the_post(); ?>
            <li>
                <a href="<?php the_permalink(); ?>"><?php get_the_title() ? the_title() : the_ID(); ?></a>
            <?php if ( $show_date ) : ?>
                <span class="post-date"><?php echo get_the_date(); ?></span>
            <?php endif; ?>
            </li>
        <?php endwhile; ?>
        </ul>
</code>```

I then changed it to:

```<code><ul>
        <?php while ( $r->have_posts() ) : $r->the_post(); ?>

            <?php
            if (strpos(get_the_title(), 'a') !== false) {
                echo '<li class="engwidget">';
            }else{
                echo '<li class="localwidget">';
            }
            ?>

                <a href="<?php the_permalink(); ?>"><?php get_the_title() ? the_title() : the_ID(); ?></a>
            <?php if ( $show_date ) : ?>
                <span class="post-date"><?php echo get_the_date(); ?></span>
            <?php endif; ?>
            </li>
        <?php endwhile; ?>
        </ul>
</code>```

I've achieved what I wanted but no idea if this is by any means a right way to do so.

Body:
umm... kinda got it working.

I made the following changes to the file:
wp-includes\widgets\class-wp-widget-recent-posts.php

It had the following code:

<ul>
        <?php while ( $r->have_posts() ) : $r->the_post(); ?>
            <li>
                <a href="<?php the_permalink(); ?>"><?php get_the_title() ? the_title() : the_ID(); ?></a>
            <?php if ( $show_date ) : ?>
                <span class="post-date"><?php echo get_the_date(); ?></span>
            <?php endif; ?>
            </li>
        <?php endwhile; ?>
        </ul>

I then changed it to:

<ul>
        <?php while ( $r->have_posts() ) : $r->the_post(); ?>

            <?php
            if (strpos(get_the_title(), 'a') !== false) {
                echo '<li class="engwidget">';
            }else{
                echo '<li class="localwidget">';
            }
            ?>

                <a href="<?php the_permalink(); ?>"><?php get_the_title() ? the_title() : the_ID(); ?></a>
            <?php if ( $show_date ) : ?>
                <span class="post-date"><?php echo get_the_date(); ?></span>
            <?php endif; ?>
            </li>
        <?php endwhile; ?>
        </ul>

I've achieved what I wanted but no idea if this is by any means a right way to do so.


问:
Error: Status{statusCode=DEVELOPER_ERROR, resolution=null}
I am usign gplus sign in, and getting this error at time I am in onActivityResult....

```<code>@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode, resultCode, data);
    client.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 0) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        if (result.isSuccess()) {

            GoogleSignInAccount acct = result.getSignInAccount();
//                Log.d("Result","details"+ acct.getDisplayName() + acct.getEmail());

            mEmail = acct.getEmail();
            String mFullName = acct.getDisplayName();
            String mGoogleplusId = acct.getId();

            SocialUser user = new SocialUser();
            user.setType("googleplus");

            user.setEmail(mEmail);
            user.setFullname(mFullName);
            user.setId(mGoogleplusId + "");
            loginParams.put("email_id", mEmail);
            loginParams.put("googlePlusId", mGoogleplusId);
            loginParams.put("full_name", mFullName);
            loginParams.put("registrationType", "googleplus");
            SignUpService(user);

        } else {
            Toast.makeText(CustomerLogIn.this, "Unable to fetch data, Proceed manually", Toast.LENGTH_SHORT).show();
        }
    }
}
</code>```

And I am calling for gplus login on button click. On clcking button following code is executed....

```<code> GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();
    mGoogleApiClient = new GoogleApiClient.Builder(CustomerLogIn.this)

            .addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
            .build();

    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, 0);
</code>```

And I am geetng this error...

```<code>Status{statusCode=DEVELOPER_ERROR, resolution=null}
</code>```

on this line....

```<code>GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
</code>```

Please suggest the solution.

答:
Alternatively to the answers provided here, you can use Android Studio's Firebase Assistant to automatically add your SHA-1 to your project with the click of some buttons.

In Android Studio, go to Tools > Firebase > Select 'Authentication' and click the link that says 'Email and password authentication'.

This will bring you a little tutorial on how to integrate Authentication to your project, but since you've probably done all that, just click 'Connect to Firebase' and you're done.

Body:
I am usign gplus sign in, and getting this error at time I am in onActivityResult....

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode, resultCode, data);
    client.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 0) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        if (result.isSuccess()) {

            GoogleSignInAccount acct = result.getSignInAccount();
//                Log.d("Result","details"+ acct.getDisplayName() + acct.getEmail());

            mEmail = acct.getEmail();
            String mFullName = acct.getDisplayName();
            String mGoogleplusId = acct.getId();

            SocialUser user = new SocialUser();
            user.setType("googleplus");

            user.setEmail(mEmail);
            user.setFullname(mFullName);
            user.setId(mGoogleplusId + "");
            loginParams.put("email_id", mEmail);
            loginParams.put("googlePlusId", mGoogleplusId);
            loginParams.put("full_name", mFullName);
            loginParams.put("registrationType", "googleplus");
            SignUpService(user);

        } else {
            Toast.makeText(CustomerLogIn.this, "Unable to fetch data, Proceed manually", Toast.LENGTH_SHORT).show();
        }
    }
}

And I am calling for gplus login on button click. On clcking button following code is executed....

 GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();
    mGoogleApiClient = new GoogleApiClient.Builder(CustomerLogIn.this)

            .addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
            .build();

    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, 0);

And I am geetng this error...

Status{statusCode=DEVELOPER_ERROR, resolution=null}

on this line....

GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);

Please suggest the solution.


问:
uwp conditional xaml giving property not found error
I am creating a uwp app using windows template studio and using hamburger menu originally made by uwp community toolkit. And I want to add some fluent design features to my app. because my min version is creators update which lacks fluent design features so I wanna add these features with conditional xaml

min target : creators update
target : fall creators update

code

```<code><controls:HamburgerMenu
    x:Name="NavigationMenu"
    IsAcrylicBrushPresent:PaneBackground="{ThemeResource SystemControlAltHighAcrylicWindowBrush}"
......
</code>```

i also have added the following namespace in the page.

xmlns:IsAcrylicBrushPresent="http://schemas.microsoft.com/winfx/2006/xaml/presentation?IsTypePresent(Windows.UI.Xaml.Media.AcrylicBrush)"

ERROR

The property "PaneBackground" does not exist in the "http://schemas.microsoft.com/winfx/2006/xaml/presentation"

答:
That's because "http://schemas.microsoft.com/winfx/2006/xaml/presentation" is for the native controls, not for the UWP Community Toolkit controls!

You should use the same namespace you currently have for controls and just add the ?IsTypePresent(Windows.UI.Xaml.Media.AcrylicBrush) query bit.

It should look something like this:

```<code>xmlns:IsAcrylicBrushPresent="using:Microsoft.Toolkit.Uwp.UI.Controls?IsTypePresent(Windows.UI.Xaml.Media.AcrylicBrush)"
</code>```

Body:
I am creating a uwp app using windows template studio and using hamburger menu originally made by uwp community toolkit. And I want to add some fluent design features to my app. because my min version is creators update which lacks fluent design features so I wanna add these features with conditional xaml

min target : creators update
target : fall creators update

code

<controls:HamburgerMenu
    x:Name="NavigationMenu"
    IsAcrylicBrushPresent:PaneBackground="{ThemeResource SystemControlAltHighAcrylicWindowBrush}"
......

i also have added the following namespace in the page.

xmlns:IsAcrylicBrushPresent="http://schemas.microsoft.com/winfx/2006/xaml/presentation?IsTypePresent(Windows.UI.Xaml.Media.AcrylicBrush)"

ERROR

The property "PaneBackground" does not exist in the "http://schemas.microsoft.com/winfx/2006/xaml/presentation"

Body:
That's because "http://schemas.microsoft.com/winfx/2006/xaml/presentation" is for the native controls, not for the UWP Community Toolkit controls!

You should use the same namespace you currently have for controls and just add the ?IsTypePresent(Windows.UI.Xaml.Media.AcrylicBrush) query bit.

It should look something like this:

xmlns:IsAcrylicBrushPresent="using:Microsoft.Toolkit.Uwp.UI.Controls?IsTypePresent(Windows.UI.Xaml.Media.AcrylicBrush)"


问:
Bizagi create dynamic combobox
Guys!
I'm working on a project with Bizagi Suite - Version 11.1. I'm new to it and I will really appreciate your help, because I'm having a hard time creating a dynamic combobox control.
So my case is the following:
Data Model: 3 master tables: Program, Order and Order-Program (m-m relationship). In table Program users fill out year, positions and amounts for each position. In table Order, they fill out info about the order and they have to specify from which program they want to take the money out for the order. The Program itself has a lot of records with different positions and amount. And I want when the users fill out the order to select the year, the position and the amount they want to take out of the program. So I need to have a dynamic combobox for the field 'position'  which loads when user select year.

In other words I need to load combobox with filtered records of master table.
Do you have any ideas how I can do that?

Thank you in advance!

Best regards,
A.Mincheva

答:
You must define your combobox with the full content of the master table.

Then ,you can define a Filter expression to dynamically filter the combobox content.

In the filter expression, you need to retreive the value of selected Year with XPath and use this value to filter the records.

In the form designer, you go to "Actions & Validations" to define the following action :

When "Year" changes <=The display name of the input field

Then Refresh "Program" <=The display name of your dynamic combobox

Title: Bizagi create dynamic combobox


问:
How to readInput regardless of type in scala?
Hi im fairly new to scala and I want to do a type check on a number a user enters. Is there a way in scala to read from the user and let scala determine which type it thinks it is.</p>

答:
I think you can do like the following:
Suppose a is the number entered</p>

```<code>     a match {
      case a: Byte => println("It is byte")
      case a: Short => //do something
      case a: Int => //do something
      case a: Long => //do something
      case a: Float => //do something
      case a: Double => //do something
      case _ => println("It is not a number")
    }
</code>```

Body:
I think you can do like the following:
Suppose a is the number entered

     a match {
      case a: Byte => println("It is byte")
      case a: Short => //do something
      case a: Int => //do something
      case a: Long => //do something
      case a: Float => //do something
      case a: Double => //do something
      case _ => println("It is not a number")
    }


问:
Changing div background image refreshes page
I have a section that overlaps another section.  When i change the background image using setinterval, the background image appears on top and then the other section eventually appears.  It looks like the entire page is refreshed.  I need to refresh a background image on a section on an interval without refreshing the remainder of the page.
Thanks in advance for any help.</p>

答:
Look at this code, the picture.jpg does not disappear:</p>

```<code><!doctype html>
<html>
<head>
</head>
<body>

<div id="bg" height="400" style="background-image:url(red.jpg);">
<div>
<img src="picture.jpg">
</div>
</div>

<script>
setInterval(function(){
   document.getElementById("bg").style.backgroundImage = (document.getElementById("bg").currentStyle.backgroundImage.search('red.jpg') < 0)
                                                       ? "url(red.jpg)"
                                                       : "url(blue.jpg)";
   }, 3000);
</script>

</body>
</html>
</code>```

Body:
Look at this code, the picture.jpg does not disappear:

<!doctype html>
<html>
<head>
</head>
<body>

<div id="bg" height="400" style="background-image:url(red.jpg);">
<div>
<img src="picture.jpg">
</div>
</div>

<script>
setInterval(function(){
   document.getElementById("bg").style.backgroundImage = (document.getElementById("bg").currentStyle.backgroundImage.search('red.jpg') < 0)
                                                       ? "url(red.jpg)"
                                                       : "url(blue.jpg)";
   }, 3000);
</script>

</body>
</html>


问:
Comparing date field in a form with current date
I am trying to check with an if statement if the date entered in a form is before the current date. If so write to an object in the model. I am also not sure if there are a better way of doing this.

I get this error

```<code>'<' not supported between instances of 'DateField' and 'datetime.date'
</code>```

My view:

```<code>class ActionCreateView(LoginRequiredMixin, generic.CreateView):
    login_url = '/scrty/login/'
    template_name = "nodiso/actioncreate.html"
    form_class = forms.LeadActionCreateForm
    # success_url = reverse_lazy('nodisoapp:leaddetail', kwargs['pk'] )

  def get_success_url(self, **kwargs):
    return reverse("nodisoapp:leaddetail", kwargs={'pk':
    self.kwargs['pk']})

  def form_valid(self, form):
     if form.fields['Duedate'] < datetime.date.today():
        self.object.overdue = 1
    else:
        pass
    self.object = form.save(commit=False)
    self.object.lead_id = self.kwargs['pk']
    self.object.creator = self.request.user.firstname
    self.object.save()
    return super(ActionCreateView, self).form_valid(form)
</code>```

The Model:

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

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

The form:

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

答:
Since you already pull out the unsaved model from the form here:

```<code>self.object = form.save(commit=False)
</code>```

Why not read the Duedate directly from the model instance, and set the overdue flag accordingly ?

```<code>is_overdue = self.object.Duedate > datetime.date.today()
self.object.overdue = 1 if is_overdue else None
</code>```

Complete code:

```<code>class ActionCreateView(LoginRequiredMixin, generic.CreateView):
     login_url = '/scrty/login/'
     template_name = "nodiso/actioncreate.html"
     form_class = forms.LeadActionCreateForm
     # success_url = reverse_lazy('nodisoapp:leaddetail', kwargs['pk'] )

     def get_success_url(self, **kwargs):
          return reverse("nodisoapp:leaddetail", kwargs={'pk': self.kwargs['pk']})

     def form_valid(self, form):
         self.object = form.save(commit=False)
         is_overdue = self.object.Duedate > datetime.date.today()
         self.object.overdue = 1 if is_overdue else None

         self.object.lead_id = self.kwargs['pk']
         self.object.creator = self.request.user.firstname
         self.object.save()
         return super(ActionCreateView, self).form_valid(form)
</code>```

Body:
I am trying to check with an if statement if the date entered in a form is before the current date. If so write to an object in the model. I am also not sure if there are a better way of doing this.

I get this error

'<' not supported between instances of 'DateField' and 'datetime.date'

My view:

class ActionCreateView(LoginRequiredMixin, generic.CreateView):
    login_url = '/scrty/login/'
    template_name = "nodiso/actioncreate.html"
    form_class = forms.LeadActionCreateForm
    # success_url = reverse_lazy('nodisoapp:leaddetail', kwargs['pk'] )

  def get_success_url(self, **kwargs):
    return reverse("nodisoapp:leaddetail", kwargs={'pk':
    self.kwargs['pk']})

  def form_valid(self, form):
     if form.fields['Duedate'] < datetime.date.today():
        self.object.overdue = 1
    else:
        pass
    self.object = form.save(commit=False)
    self.object.lead_id = self.kwargs['pk']
    self.object.creator = self.request.user.firstname
    self.object.save()
    return super(ActionCreateView, self).form_valid(form)

The Model:

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

  def __str__(self):
    return self.name

The form:

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

Body:
Since you already pull out the unsaved model from the form here:

self.object = form.save(commit=False)

Why not read the Duedate directly from the model instance, and set the overdue flag accordingly ?

is_overdue = self.object.Duedate > datetime.date.today()
self.object.overdue = 1 if is_overdue else None

Complete code:

class ActionCreateView(LoginRequiredMixin, generic.CreateView):
     login_url = '/scrty/login/'
     template_name = "nodiso/actioncreate.html"
     form_class = forms.LeadActionCreateForm
     # success_url = reverse_lazy('nodisoapp:leaddetail', kwargs['pk'] )

     def get_success_url(self, **kwargs):
          return reverse("nodisoapp:leaddetail", kwargs={'pk': self.kwargs['pk']})

     def form_valid(self, form):
         self.object = form.save(commit=False)
         is_overdue = self.object.Duedate > datetime.date.today()
         self.object.overdue = 1 if is_overdue else None

         self.object.lead_id = self.kwargs['pk']
         self.object.creator = self.request.user.firstname
         self.object.save()
         return super(ActionCreateView, self).form_valid(form)


问:
SSRS: How to return last day of a Custom/Financial Month (Not Calendar) through expression
This is a real hair puller so any help, much appreciated!

I want to be able to determine the:

First day of the current custom/financial month

Last day of the current custom/financial month

And use these new columns Start_Date and end_Date as between Filters in the Matrix.

Note: I understand that if this was calendar Month, then that will be "quite" straightforward.

But in this case its quite different.

Please see image which might help with the context i am trying to work with:

答:
I'm sure this is possible using expressions in SSRS but I don;t have time to investigate. In case it's useful, here's how I would do it in SQL.

Again there is probably a more elegant solution but this was what came to me.

I'll reproduced your data plus a few more dates either end for testing which I guessed based on your sample.

```<code>DECLARE @t TABLE(Custom_Date date, Custom_Day int)

INSERT INTO @t VALUES
('2017-10-26', 28),
('2017-10-27', 29),
('2017-10-28', 30),
('2017-10-29', 1),
('2017-10-30', 2),
('2017-10-31', 3),
('2017-11-01', 4),
('2017-11-02', 5),
('2017-11-03', 6),
('2017-11-04', 7),
('2017-11-05', 8),
('2017-11-06', 9),
('2017-11-07', 10),
('2017-11-08', 11),
('2017-11-09', 12),
('2017-11-10', 13),
('2017-11-11', 14),
('2017-11-12', 15),
('2017-11-13', 16),
('2017-11-14', 17),
('2017-11-15', 18),
('2017-11-16', 19),
('2017-11-17', 20),
('2017-11-18', 21),
('2017-11-19', 22),
('2017-11-20', 23),
('2017-11-21', 24),
('2017-11-22', 25),
('2017-11-23', 26),
('2017-11-24', 27),
('2017-11-25', 28),
('2017-11-26', 1),
('2017-11-27', 2),
('2017-11-28', 3)
</code>```

Then two queries to pull out the correct dates which you could combine if required.

```<code>SELECT MAX(Custom_Date) FROM @t WHERE Custom_Date < getdate() AND custom_day = 1

SELECT MAX(Custom_Date)
    FROM @t
    WHERE
        Custom_Date > getdate()
        AND DATEDIFF(d, getdate(), Custom_Date)<=31
        AND Custom_Day = (
                            SELECT MAX(custom_day)
                                FROM @t
                                WHERE
                                    Custom_Date > getdate()
                                    AND datediff(d, getdate(), Custom_Date)<=31
                        )
</code>```

FYI: This would be a lot easier if you had a custom month/period and year in your dates table as then you could just look custom_day 1 and max(custom_day) where the custom month and year are the same as the current date.

Body:
I'm sure this is possible using expressions in SSRS but I don;t have time to investigate. In case it's useful, here's how I would do it in SQL.

Again there is probably a more elegant solution but this was what came to me.

I'll reproduced your data plus a few more dates either end for testing which I guessed based on your sample.

DECLARE @t TABLE(Custom_Date date, Custom_Day int)

INSERT INTO @t VALUES
('2017-10-26', 28),
('2017-10-27', 29),
('2017-10-28', 30),
('2017-10-29', 1),
('2017-10-30', 2),
('2017-10-31', 3),
('2017-11-01', 4),
('2017-11-02', 5),
('2017-11-03', 6),
('2017-11-04', 7),
('2017-11-05', 8),
('2017-11-06', 9),
('2017-11-07', 10),
('2017-11-08', 11),
('2017-11-09', 12),
('2017-11-10', 13),
('2017-11-11', 14),
('2017-11-12', 15),
('2017-11-13', 16),
('2017-11-14', 17),
('2017-11-15', 18),
('2017-11-16', 19),
('2017-11-17', 20),
('2017-11-18', 21),
('2017-11-19', 22),
('2017-11-20', 23),
('2017-11-21', 24),
('2017-11-22', 25),
('2017-11-23', 26),
('2017-11-24', 27),
('2017-11-25', 28),
('2017-11-26', 1),
('2017-11-27', 2),
('2017-11-28', 3)

Then two queries to pull out the correct dates which you could combine if required.

SELECT MAX(Custom_Date) FROM @t WHERE Custom_Date < getdate() AND custom_day = 1

SELECT MAX(Custom_Date)
    FROM @t
    WHERE
        Custom_Date > getdate()
        AND DATEDIFF(d, getdate(), Custom_Date)<=31
        AND Custom_Day = (
                            SELECT MAX(custom_day)
                                FROM @t
                                WHERE
                                    Custom_Date > getdate()
                                    AND datediff(d, getdate(), Custom_Date)<=31
                        )

FYI: This would be a lot easier if you had a custom month/period and year in your dates table as then you could just look custom_day 1 and max(custom_day) where the custom month and year are the same as the current date.


问:
How to find the App ID of android application
I'm learning android application. I've build simple app by the help of one's project . Now I want to upload in playstore for testing purpose, but I'm confused regarding following 2 terms : Startapp Developer and App ID

strings.xml

```<code><!-- Change Startapp Developer and App ID -->
<string name="startapp_dev_id">102358176</string>
<string name="startapp_app_id">203718681</string>
</code>```

Screenshot of code

Where to find Startapp Developer and App ID ? I've found https://portal.startapp.com for App ID. Is this is associated with playstore or google account.

答:
You may find the applicationId of your Android app in your module's build.gradle file, as shown here:

```<code>android {
    defaultConfig {
        applicationId "com.example.myapp"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    ...
}
</code>```

See this documentation to learn more and this SO post for additional insights.

Body:
I'm learning android application. I've build simple app by the help of one's project . Now I want to upload in playstore for testing purpose, but I'm confused regarding following 2 terms : Startapp Developer and App ID

strings.xml

<string name="startapp_dev_id">102358176</string>
<string name="startapp_app_id">203718681</string>

Screenshot of code

Where to find Startapp Developer and App ID ? I've found https://portal.startapp.com for App ID. Is this is associated with playstore or google account.

Body:
You may find the applicationId of your Android app in your module's build.gradle file, as shown here:

android {
    defaultConfig {
        applicationId "com.example.myapp"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    ...
}

See this documentation to learn more and this SO post for additional insights.


问:
Querying a database again and again or storing all the data in a file at once and querying the files?
I am making a set of Talend jobs where I am going to query same set of tables differently depending on the need of the jobs. These tables are huge. Will it be good if before running the jobs I query all the tables and take all the data from the DB and store them in a file and then using the files for the various queries in Talend jobs. Those files will be stored in the same location where jobs would be running while DB server would be somewhere else. If I am not wrong then DBs themselves have some sort of caching and indexing implemented to make querying faster and optimized. So, is it worthwhile to store them in a file and then query them in Talend Jobs? I am using Oracle DataBase.</p>

答:
I wouldn't do this.

Depending on your license, you might be able to use in-memory tables. Despite of that, depending of the size of the query there might be some caching, as you said.

I would avoid it because it could lead to all kinds of problems:

Filesystem could become unavailable

No caching in local filesystem, calling this might be a lot slower - even slower than processing

All database performance helpers - like indices, caching, query analyzer - will not be available

Need to implement some kind of database system - which is silly b/c there is already a database there

What could be an idea, though, would be a temp table within this or another database.

So the heavy load would only happen once, which I find a good idea. Then the further processing will happen on the temp table. Afterwards, after all processes went through, this temp table will be dropped.


问:
How to initialize a List<T> to a given size (as opposed to capacity)?
.NET offers a generic list container whose performance is almost identical (see Performance of Arrays vs. Lists question). However they are quite different in initialization.

Arrays are very easy to initialize with a default value, and by definition they already have certain size:

```<code>string[] Ar = new string[10];
</code>```

Which allows one to safely assign random items, say:

```<code>Ar[5]="hello";
</code>```

with list things are more tricky. I can see two ways of doing the same initialization, neither of which is what you would call elegant:

```<code>List<string> L = new List<string>(10);
for (int i=0;i<10;i++) L.Add(null);
</code>```

or

```<code>string[] Ar = new string[10];
List<string> L = new List<string>(Ar);
</code>```

What would be a cleaner way?

EDIT: The answers so far refer to capacity, which is something else than pre-populating a list. For example, on a list just created with a capacity of 10, one cannot do L[2]="somevalue"

EDIT 2: People wonder why I want to use lists this way, as it is not the way they are intended to be used. I can see two reasons:

One could quite convincingly argue that lists are the "next generation" arrays, adding flexibility with almost no penalty. Therefore one should use them by default. I'm pointing out they might not be as easy to initialize.

What I'm currently writing is a base class offering default functionality as part of a bigger framework. In the default functionality I offer, the size of the List is known in advanced and therefore I could have used an array. However, I want to offer any base class the chance to dynamically extend it and therefore I opt for a list.

答:
You seem to be emphasizing the need for a positional association with your data, so wouldn't an associative array be more fitting?</p>

```<code>Dictionary<int, string> foo = new Dictionary<int, string>();
foo[2] = "string";
</code>```

OwnerDisplayName: Boaz

Body:
.NET offers a generic list container whose performance is almost identical (see Performance of Arrays vs. Lists question). However they are quite different in initialization.

Arrays are very easy to initialize with a default value, and by definition they already have certain size:

string[] Ar = new string[10];

Which allows one to safely assign random items, say:

Ar[5]="hello";

with list things are more tricky. I can see two ways of doing the same initialization, neither of which is what you would call elegant:

List<string> L = new List<string>(10);
for (int i=0;i<10;i++) L.Add(null);

or

string[] Ar = new string[10];
List<string> L = new List<string>(Ar);

What would be a cleaner way?

EDIT: The answers so far refer to capacity, which is something else than pre-populating a list. For example, on a list just created with a capacity of 10, one cannot do L[2]="somevalue"

EDIT 2: People wonder why I want to use lists this way, as it is not the way they are intended to be used. I can see two reasons:

One could quite convincingly argue that lists are the "next generation" arrays, adding flexibility with almost no penalty. Therefore one should use them by default. I'm pointing out they might not be as easy to initialize.

What I'm currently writing is a base class offering default functionality as part of a bigger framework. In the default functionality I offer, the size of the List is known in advanced and therefore I could have used an array. However, I want to offer any base class the chance to dynamically extend it and therefore I opt for a list.

LastEditorDisplayName: Boaz

Body:
You seem to be emphasizing the need for a positional association with your data, so wouldn't an associative array be more fitting?

Dictionary<int, string> foo = new Dictionary<int, string>();
foo[2] = "string";

OwnerDisplayName: Greg D

ContentLicense: CC BY-SA 2.5


问:
Getting the name of a child class in the parent class (static context)
I'm building an ORM library with reuse and simplicity in mind; everything goes fine except that I got stuck by a stupid inheritance limitation. Please consider the code below:

```<code>class BaseModel {
    /*
     * Return an instance of a Model from the database.
     */
    static public function get (/* varargs */) {
        // 1. Notice we want an instance of User
        $class = get_class(parent); // value: bool(false)
        $class = get_class(self);   // value: bool(false)
        $class = get_class();       // value: string(9) "BaseModel"
        $class =  __CLASS__;        // value: string(9) "BaseModel"

        // 2. Query the database with id
        $row = get_row_from_db_as_array(func_get_args());

        // 3. Return the filled instance
        $obj = new $class();
        $obj->data = $row;
        return $obj;
    }
}

class User extends BaseModel {
    protected $table = 'users';
    protected $fields = array('id', 'name');
    protected $primary_keys = array('id');
}
class Section extends BaseModel {
    // [...]
}

$my_user = User::get(3);
$my_user->name = 'Jean';

$other_user = User::get(24);
$other_user->name = 'Paul';

$my_user->save();
$other_user->save();

$my_section = Section::get('apropos');
$my_section->delete();
</code>```

Obviously, this is not the behavior I was expecting (although the actual behavior also makes sense).. So my question is if you guys know of a mean to get, in the parent class, the name of child class.

答:
Two variations on Preston's answer:

1)

```<code>class Base
{
    public static function find($id)
    {
        $table = static::$_table;
        $class = static::$_class;
        $data = array('table' => $table, 'id' => $id);
        return new $class($data);
    }
}

class User extends Base
{
    public static $_class = 'User';
}
</code>```

2)

```<code>class Base
{
    public static function _find($class, $id)
    {
        $table = static::$_table;
        $data = array('table' => $table, 'id' => $id);
        return new $class($data);
    }
}

class User extends Base
{
    public static function find($id)
    {
        return self::_find(get_class($this), $id);
    }
}
</code>```

Note: starting a property name with _ is a convention that basically means "i know i made this public, but it really should have been protected, but i couldn't do that and achieve my goal"

OwnerDisplayName: Benoit Myard

Body:
I'm building an ORM library with reuse and simplicity in mind; everything goes fine except that I got stuck by a stupid inheritance limitation. Please consider the code below:

class BaseModel {
    /*
     * Return an instance of a Model from the database.
     */
    static public function get (/* varargs */) {
        // 1. Notice we want an instance of User
        $class = get_class(parent); // value: bool(false)
        $class = get_class(self);   // value: bool(false)
        $class = get_class();       // value: string(9) "BaseModel"
        $class =  __CLASS__;        // value: string(9) "BaseModel"

        // 2. Query the database with id
        $row = get_row_from_db_as_array(func_get_args());

        // 3. Return the filled instance
        $obj = new $class();
        $obj->data = $row;
        return $obj;
    }
}

class User extends BaseModel {
    protected $table = 'users';
    protected $fields = array('id', 'name');
    protected $primary_keys = array('id');
}
class Section extends BaseModel {
    // [...]
}

$my_user = User::get(3);
$my_user->name = 'Jean';

$other_user = User::get(24);
$other_user->name = 'Paul';

$my_user->save();
$other_user->save();

$my_section = Section::get('apropos');
$my_section->delete();

Obviously, this is not the behavior I was expecting (although the actual behavior also makes sense).. So my question is if you guys know of a mean to get, in the parent class, the name of child class.

LastEditorDisplayName: Benoit Myard

Body:
Two variations on Preston's answer:

1)

class Base
{
    public static function find($id)
    {
        $table = static::$_table;
        $class = static::$_class;
        $data = array('table' => $table, 'id' => $id);
        return new $class($data);
    }
}

class User extends Base
{
    public static $_class = 'User';
}

2)

class Base
{
    public static function _find($class, $id)
    {
        $table = static::$_table;
        $data = array('table' => $table, 'id' => $id);
        return new $class($data);
    }
}

class User extends Base
{
    public static function find($id)
    {
        return self::_find(get_class($this), $id);
    }
}

Note: starting a property name with _ is a convention that basically means "i know i made this public, but it really should have been protected, but i couldn't do that and achieve my goal"


问:
Remove free shipping method after apply coupon code
How to remove free shipping method after apply coupon code in cart page as well as onepagecheckout page?</p>

答:
I fixed this using the following approach, so posting in case anyone else is looking. Copy the following file:

/app/code/core/Mage/Shipping/Model/Carrier/Freeshipping.php

to your local folder, creating the directories, so you have:

/app/code/local/Mage/Shipping/Model/Carrier/Freeshipping.php

Then replace lines 70 to 86, which are like this:

```<code>if (($request->getFreeShipping())
        || ($request->getBaseSubtotalInclTax() >=
            $this->getConfigData('free_shipping_subtotal'))
    ) {
        $method = Mage::getModel('shipping/rate_result_method');

        $method->setCarrier('freeshipping');
        $method->setCarrierTitle($this->getConfigData('title'));

        $method->setMethod('freeshipping');
        $method->setMethodTitle($this->getConfigData('name'));

        $method->setPrice('0.00');
        $method->setCost('0.00');

        $result->append($method);
    }
</code>```

...with the following:

```<code>if (($request->getFreeShipping())
        || ($request->getBaseSubtotalInclTax() >=
            $this->getConfigData('free_shipping_subtotal'))
    ) {
        $coupon = Mage::getSingleton('checkout/session')->getQuote()->getCouponCode();
        $totals = Mage::getSingleton('checkout/session')->getQuote()->getTotals();
        if(isset($totals['discount'])) {
            $discount = abs($totals['discount']->getValue()); // Discount value if applied
        } else {
            $discount = '';
        }
        // No free shipping if coupon used, unless GRAND total is still over free-shipping limit
        if(!$coupon || $coupon && ($totals['subtotal']->getValue() - $discount) > $this->getConfigData('free_shipping_subtotal')) {
            $method = Mage::getModel('shipping/rate_result_method');

            $method->setCarrier('freeshipping');
            $method->setCarrierTitle($this->getConfigData('title'));

            $method->setMethod('freeshipping');
            $method->setMethodTitle($this->getConfigData('name'));

            $method->setPrice('0.00');
            $method->setCost('0.00');

            $result->append($method);
        }
    }
</code>```

Now, if a coupon code gets used, Magento checks whether the GRAND total is still above the free shipping threshold before applying it.

Body:
I fixed this using the following approach, so posting in case anyone else is looking. Copy the following file:

/app/code/core/Mage/Shipping/Model/Carrier/Freeshipping.php

to your local folder, creating the directories, so you have:

/app/code/local/Mage/Shipping/Model/Carrier/Freeshipping.php

Then replace lines 70 to 86, which are like this:

if (($request->getFreeShipping())
        || ($request->getBaseSubtotalInclTax() >=
            $this->getConfigData('free_shipping_subtotal'))
    ) {
        $method = Mage::getModel('shipping/rate_result_method');

        $method->setCarrier('freeshipping');
        $method->setCarrierTitle($this->getConfigData('title'));

        $method->setMethod('freeshipping');
        $method->setMethodTitle($this->getConfigData('name'));

        $method->setPrice('0.00');
        $method->setCost('0.00');

        $result->append($method);
    }

...with the following:

if (($request->getFreeShipping())
        || ($request->getBaseSubtotalInclTax() >=
            $this->getConfigData('free_shipping_subtotal'))
    ) {
        $coupon = Mage::getSingleton('checkout/session')->getQuote()->getCouponCode();
        $totals = Mage::getSingleton('checkout/session')->getQuote()->getTotals();
        if(isset($totals['discount'])) {
            $discount = abs($totals['discount']->getValue()); // Discount value if applied
        } else {
            $discount = '';
        }
        // No free shipping if coupon used, unless GRAND total is still over free-shipping limit
        if(!$coupon || $coupon && ($totals['subtotal']->getValue() - $discount) > $this->getConfigData('free_shipping_subtotal')) {
            $method = Mage::getModel('shipping/rate_result_method');

            $method->setCarrier('freeshipping');
            $method->setCarrierTitle($this->getConfigData('title'));

            $method->setMethod('freeshipping');
            $method->setMethodTitle($this->getConfigData('name'));

            $method->setPrice('0.00');
            $method->setCost('0.00');

            $result->append($method);
        }
    }

Now, if a coupon code gets used, Magento checks whether the GRAND total is still above the free shipping threshold before applying it.


问:
Redux action not present
I have set up correctly according to doc redux boilerplate.
I have a folder of various action files which contains actions.
In this folder I have created an index.js where I am exporting all these files. I import it as named export.
When I console log the function itself it is there, but when I console log out this.props its not present.
I have tried to console log out the function outside the class its undefined.

If I import the action directly from the file it is defined in it works.

actions/formActions.js

```<code>export const formInput = (key, val) => (
    {
        type: FORM_INPUT,
        payload: { key, val }
    }
);
</code>```

actions/index.js

```<code>export * from './formActions';
</code>```

FormComp.js

```<code>import { formInput } from './actions'; //  <-- this.props.formInput = undefined
</code>```

or

```<code>import { formInput } from './actions/formActions'; //  <-- this.props.formInput = func
</code>```

connect:

```<code>class InputField extends Component { ... }

const FormComp = connect(({ forms }) => ({ forms }), { formInput })(InputField);

export { FormComp };
</code>```

edit1: If I inside componentWillMount() console.log(formInput) //without this.props its there.

edit2 (solution?):
I was able to map actions to props with bindActionCreators. How ever I don't understand why I need to use bindActionCreators and why I can't just export connect as it is with actions as second param.

```<code>const FormComp = connect(
  ({ forms }) => ({ forms }),
  dispatch => bindActionCreators({ formInput }, dispatch)
)(InputField);
</code>```

答:
You need to return a function which has dispatch and getState as parameter.

```<code>export const formInput = (key, val) => (dispatch, getState) => {
    // maybe additional stuff
    dispatch({
        type: FORM_INPUT,
        payload: { key, val }
    });
};
</code>```

See title Action Creators from the documents: https://redux.js.org/docs/basics/Actions.html

Title: Redux action not present

Body:
I have set up correctly according to doc redux boilerplate.
I have a folder of various action files which contains actions.
In this folder I have created an index.js where I am exporting all these files. I import it as named export.
When I console log the function itself it is there, but when I console log out this.props its not present.
I have tried to console log out the function outside the class its undefined.

If I import the action directly from the file it is defined in it works.

actions/formActions.js

export const formInput = (key, val) => (
    {
        type: FORM_INPUT,
        payload: { key, val }
    }
);

actions/index.js

export * from './formActions';

FormComp.js

import { formInput } from './actions'; //  <-- this.props.formInput = undefined

or

import { formInput } from './actions/formActions'; //  <-- this.props.formInput = func

connect:

class InputField extends Component { ... }

const FormComp = connect(({ forms }) => ({ forms }), { formInput })(InputField);

export { FormComp };

edit1: If I inside componentWillMount() console.log(formInput) //without this.props its there.

edit2 (solution?):
I was able to map actions to props with bindActionCreators. How ever I don't understand why I need to use bindActionCreators and why I can't just export connect as it is with actions as second param.

const FormComp = connect(
  ({ forms }) => ({ forms }),
  dispatch => bindActionCreators({ formInput }, dispatch)
)(InputField);

Body:
You need to return a function which has dispatch and getState as parameter.

export const formInput = (key, val) => (dispatch, getState) => {
    // maybe additional stuff
    dispatch({
        type: FORM_INPUT,
        payload: { key, val }
    });
};

See title Action Creators from the documents: https://redux.js.org/docs/basics/Actions.html


问:
How to Print Unicode (Bangla Font) to Thermal Printer?
I want to Print Bangla text Like "আপনি কি ডাটা সংরক্ষন করতে চান" from my android app.But i got wrong result every time. Here is my Output:

My Code is Here:

```<code>   String memo = "আপনি কি ডাটা সংরক্ষন করতে চান" + "\n" +
            "\n" +
            "\n" +
            "\n" +
            "\n" +
            "\n";

    byte[] buffer = memo.getBytes(Charset.forName("UTF-8"));

    try {
        Toast.makeText(getApplicationContext(), "Starting...", Toast.LENGTH_LONG).show();

        Thread.sleep(1000);
        byte[] printformat = {27, 33, 01};
        mmOutputStream.write(printformat);
        mmOutputStream.write(buffer);
        mmOutputStream.write(0x0B);
        mmOutputStream.write(0x0B);
        mmOutputStream.write(0x0B);
        mmOutputStream.flush();

        mmOutputStream.close();
        mmSocket.close();
        Toast.makeText(getApplicationContext(), "Completed", Toast.LENGTH_LONG).show();
        mmOutputStream.close();
        mmSocket.close();
    } catch (Exception ex) {
        Toast.makeText(getApplicationContext(),
                "Excep IntentPrint", Toast.LENGTH_SHORT).show();
  }
</code>```

答:
This assumes that the printer can handle multi-byte sequences of UTF-8.
At the same time printer specific control bytes are written. I think the printer has only a limited and specific ASCII (8 bit) character set.

So try it out:

```<code>byte[] buffer = new byte[128];
for (int i = 0; i < 128; ++i) {
    buffer[i] = (byte)(-128 + i);
}
</code>```

If you cannot find some documentation, you need to map all by hand.

And then you need to map characters in strings like "\u098F\u09AC\u0982" to their byte values.

```<code>Map<Character, Byte> charsToByte;
charsToByte.put('\u088F', (byte)129); // Or such.
</code>```

Body:
I want to Print Bangla text Like "আপনি কি ডাটা সংরক্ষন করতে চান" from my android app.But i got wrong result every time. Here is my Output:

My Code is Here:

   String memo = "আপনি কি ডাটা সংরক্ষন করতে চান" + "\n" +
            "\n" +
            "\n" +
            "\n" +
            "\n" +
            "\n";

    byte[] buffer = memo.getBytes(Charset.forName("UTF-8"));

    try {
        Toast.makeText(getApplicationContext(), "Starting...", Toast.LENGTH_LONG).show();

        Thread.sleep(1000);
        byte[] printformat = {27, 33, 01};
        mmOutputStream.write(printformat);
        mmOutputStream.write(buffer);
        mmOutputStream.write(0x0B);
        mmOutputStream.write(0x0B);
        mmOutputStream.write(0x0B);
        mmOutputStream.flush();

        mmOutputStream.close();
        mmSocket.close();
        Toast.makeText(getApplicationContext(), "Completed", Toast.LENGTH_LONG).show();
        mmOutputStream.close();
        mmSocket.close();
    } catch (Exception ex) {
        Toast.makeText(getApplicationContext(),
                "Excep IntentPrint", Toast.LENGTH_SHORT).show();
  }

Body:
This assumes that the printer can handle multi-byte sequences of UTF-8.
At the same time printer specific control bytes are written. I think the printer has only a limited and specific ASCII (8 bit) character set.

So try it out:

byte[] buffer = new byte[128];
for (int i = 0; i < 128; ++i) {
    buffer[i] = (byte)(-128 + i);
}

If you cannot find some documentation, you need to map all by hand.

And then you need to map characters in strings like "\u098F\u09AC\u0982" to their byte values.

Map<Character, Byte> charsToByte;
charsToByte.put('\u088F', (byte)129); // Or such.


问:
Olingo and Excel
I've downloaded the Olingo server sample (Odata4), compiled and deployed on my local tomcat

browsing the url http://localhost:8080/odata-server-sample/cars.svc/ i get

```<code><?xml version="1.0" encoding="UTF-8"?>
<app:service xmlns:app="http://www.w3.org/2007/app" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:metadata="http://docs.oasis-open.org/odata/ns/metadata" metadata:context="$metadata">
   <app:workspace>
      <atom:title>olingo.odata.sample.Container</atom:title>
      <app:collection href="Cars" metadata:name="Cars">
         <atom:title>Cars</atom:title>
      </app:collection>
      <app:collection href="Manufacturers" metadata:name="Manufacturers">
         <atom:title>Manufacturers</atom:title>
      </app:collection>
   </app:workspace>
</app:service>
</code>```

I don't know the OData protocol, but it seem legit...

Now if i i feed this to Excel 2016, using PowerQuery:
Data > New Query > From Other Source > From OData Feed

i get the error Invalid URI: The hostname could not be parsed.

If i use instead this vba code:

```<code>Option Explicit

' References that need to be added:
' Microsoft XML, v6.0
' Microsoft Scripting Runtime

Const ODataErrorFirst As Long = 100
Const ODataCannotReadUrlError As Long = ODataErrorFirst + 1
Const ODataParseError As Long = ODataErrorFirst + 2

Sub test()
    ODataReadUrl ("http://localhost:8080/odata-server-sample/cars.svc/")
End Sub

' Given a URL, reads an OData feed or entry into an XML document.
Function ODataReadUrl(ByVal strUrl As String) As MSXML2.DOMDocument60
    Dim objXmlHttp As MSXML2.XMLHTTP60
    Dim objResult As MSXML2.DOMDocument60
    Dim strText As String

    ' Make a request for the URL.
    Set objXmlHttp = New MSXML2.XMLHTTP60
    objXmlHttp.Open "GET", strUrl, False
    objXmlHttp.send

    If objXmlHttp.Status <> 200 Then
        Err.Raise ODataCannotReadUrlError, "ODataReadUrl", "Unable to get '" & strUrl & "' – status code: " & objXmlHttp.Status
    End If

    ' Get the result as text.
    strText = objXmlHttp.responseText
    Set objXmlHttp = Nothing

    ' Create a document from the text.
    Set objResult = New MSXML2.DOMDocument60
    objResult.LoadXML strText
    If objResult.parseError.ErrorCode <> 0 Then
        Err.Raise ODataParseError, "ODataReadUrl", "Unable to load '" & strUrl & "' – " & objResult.parseError.reason
    End If

    Set ODataReadUrl = objResult
End Function
</code>```

i get Not valid at root level.  (in my Italian Excel: Non valido al primo livello del documento.)

What does this mean?
Olingo isn't compatible with excel?

答:
I've followed some suggestions and come up with a working sample

you can find the patched code here: https://github.com/lelmarir/olingo-odata4/commit/8a947d3b7afab88c04177bfb361e9689ea91defc

References:

https://issues.apache.org/jira/browse/OLINGO-1025

https://issues.apache.org/jira/browse/OLINGO-758

Title: Olingo and Excel

Body:
I've downloaded the Olingo server sample (Odata4), compiled and deployed on my local tomcat

browsing the url http://localhost:8080/odata-server-sample/cars.svc/ i get

<?xml version="1.0" encoding="UTF-8"?>
<app:service xmlns:app="http://www.w3.org/2007/app" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:metadata="http://docs.oasis-open.org/odata/ns/metadata" metadata:context="$metadata">
   <app:workspace>
      <atom:title>olingo.odata.sample.Container</atom:title>
      <app:collection href="Cars" metadata:name="Cars">
         <atom:title>Cars</atom:title>
      </app:collection>
      <app:collection href="Manufacturers" metadata:name="Manufacturers">
         <atom:title>Manufacturers</atom:title>
      </app:collection>
   </app:workspace>
</app:service>

I don't know the OData protocol, but it seem legit...

Now if i i feed this to Excel 2016, using PowerQuery:
Data > New Query > From Other Source > From OData Feed

i get the error Invalid URI: The hostname could not be parsed.

If i use instead this vba code:

Option Explicit

' References that need to be added:
' Microsoft XML, v6.0
' Microsoft Scripting Runtime

Const ODataErrorFirst As Long = 100
Const ODataCannotReadUrlError As Long = ODataErrorFirst + 1
Const ODataParseError As Long = ODataErrorFirst + 2

Sub test()
    ODataReadUrl ("http://localhost:8080/odata-server-sample/cars.svc/")
End Sub

' Given a URL, reads an OData feed or entry into an XML document.
Function ODataReadUrl(ByVal strUrl As String) As MSXML2.DOMDocument60
    Dim objXmlHttp As MSXML2.XMLHTTP60
    Dim objResult As MSXML2.DOMDocument60
    Dim strText As String

    ' Make a request for the URL.
    Set objXmlHttp = New MSXML2.XMLHTTP60
    objXmlHttp.Open "GET", strUrl, False
    objXmlHttp.send

    If objXmlHttp.Status <> 200 Then
        Err.Raise ODataCannotReadUrlError, "ODataReadUrl", "Unable to get '" & strUrl & "' – status code: " & objXmlHttp.Status
    End If

    ' Get the result as text.
    strText = objXmlHttp.responseText
    Set objXmlHttp = Nothing

    ' Create a document from the text.
    Set objResult = New MSXML2.DOMDocument60
    objResult.LoadXML strText
    If objResult.parseError.ErrorCode <> 0 Then
        Err.Raise ODataParseError, "ODataReadUrl", "Unable to load '" & strUrl & "' – " & objResult.parseError.reason
    End If

    Set ODataReadUrl = objResult
End Function

i get Not valid at root level.  (in my Italian Excel: Non valido al primo livello del documento.)

What does this mean?
Olingo isn't compatible with excel?


问:
Jetty: how to disable logging?
I am trying to embed Jetty 6.1 in another program. Jetty is dumping INFO-log information and I need to turn it off. Is there a simple way to disable logging programmaticaly? </p>

答: In Jetty Embedded you can try: org.mortbay.log.Log.setLog(null); Before call Server.</p>

Title: Jetty: how to disable logging?


问:
Not including field names in validation error messages
If I have the following validation:

```<code>validates_inclusion_of :dob, :in => Date.new(1900)..Time.now.years_ago(18).to_date, :message => "You must be 18 or older to register"
</code>```

The actual message on the site that shows up is:

"Dob You must be 18 or older to register"

Is there any way not to include the column name at the beginning of the message?

Thank you

Tom

答:
Full disclosure: I developed the gem.

I feel existing solutions are hacks, and I developed this gem to avoid such hacks.

https://github.com/lulalala/adequate_errors

After installing the gem, set the error message in your locale yaml file like this:

```<code>en:
  activemodel
    adequate_errors:
      models:
        user:
          attributes:
            dob:
              inclusion: "You must be 18 or older to register"
</code>```

And then accessing model.errors.adequate.messages will have the message without attribute prefix.

Body:
If I have the following validation:

validates_inclusion_of :dob, :in => Date.new(1900)..Time.now.years_ago(18).to_date, :message => "You must be 18 or older to register"

The actual message on the site that shows up is:

"Dob You must be 18 or older to register"

Is there any way not to include the column name at the beginning of the message?

Thank you

Tom

Body:
Full disclosure: I developed the gem.

I feel existing solutions are hacks, and I developed this gem to avoid such hacks.

https://github.com/lulalala/adequate_errors

After installing the gem, set the error message in your locale yaml file like this:

en:
  activemodel
    adequate_errors:
      models:
        user:
          attributes:
            dob:
              inclusion: "You must be 18 or older to register"

And then accessing model.errors.adequate.messages will have the message without attribute prefix.


问:
How do you create a custom user role in Azure AD?
Found this article on how to setup roles but it uses the legacy azure portal to accomplish this.

How do you create user roles in the latest Azure portal?

How do you assign multiple roles to a user afterwards?

答: RBAC built-in roles lists the roles available in Azure. It specifies the operations and scope that each built-in role grants to users. If you're looking to define your own roles for even more control, see how to build Custom roles in Azure RBAC.