text:
Q: Benchmarking Sorting Algorithms Java; Average Run Times are incorrect While I understand the following method for benchmarking isn't ideal, I am working on benchmarking sorting algorithms to help better understand algorithms and data structures.
I want to list the average run times of a "large" n 500000 and small "n" size array 50, but my averages are always increasing.
I am unsure of where I went wrong:
    public class BenchmarkingAlgorithms
    {
        public static void main(String[] args)
        {
            int[] largeUnsortedArray = largeArrayWithRandomInts(500000);

        bubbleSort(largeUnsortedArray);

        selectionSort(largeUnsortedArray);
        insertionSort(largeUnsortedArray);
        benchmarkQuickSort(largeUnsortedArray);
        benchmarkMergeSort(largeUnsortedArray);

        int[] smallUnsortedArray = smallArrayWithRandomInts(50);

        bubbleSort(smallUnsortedArray);
        selectionSort(smallUnsortedArray);
        insertionSort(smallUnsortedArray);
        benchmarkQuickSort(smallUnsortedArray);
        benchmarkMergeSort(smallUnsortedArray);
    }

    /**
     * Sorting an array of ints in ascending order using bubbleSort
     * Best-Case Complexity: O(n), Average Complexity: O(n^2), Worst-Case Complexity: O(n^2)
     * O(n) is achieved in Best-Case (already sorted array) using the alreadySorted flag
     * @param array
     * @return
     */
    static int[] bubbleSort(int[] array)
    {
         int bubbleSortTime[] = new int[500];
          int x, y;
          for (x = 0; x< 500; x++) {

        int temp;
        boolean alreadySorted = true;
        long start = System.nanoTime();

        {
            for (int i = 0; i < array.length; i++)
        {

            for (int j = 0; j < array.length - 1; j++)
            {

                if (array[j] > array[j + 1])
                {
                    alreadySorted = false;
                    temp = array[j + 1];
                    array[j + 1] = array[j];
                    array[j] = temp;
                }

            }
            if (alreadySorted == true)
            {
                break;
            }

        }
            long end = System.nanoTime();

            long bubbleSortRunTime = end - start;

            bubbleSortTime[x] = (int) bubbleSortRunTime;
            x++;

        }
        // getting array length
        int length = bubbleSortTime.length;

        // default sum value.
        int sum = 0;

        // sum of all values in array using for loop
        for (int i = 0; i < bubbleSortTime.length; i++) {
            sum += bubbleSortTime[i];
        }

        double average = sum / length;

        System.out.println("Average of array : "+average + " nano seconds.");

    }

        return array;

    }

    /**
     * Sorting an array of ints in ascending order using selectionSort
     * Best-Case Complexity: O(n^2), Average Complexity: O(n^2), Worst-Case Complexity: O(n^2)
     * @param array
     * @return
     */
    static int[] selectionSort(int[] array)
    {

         int selectionSortTime[] = new int[500];
         int x, y;
         for (x = 0; x< 500; x++) {

        int min;
        int pos = 0;
        long start = System.nanoTime();

        {
            for (int i = 0; i < array.length - 1; i++)
            {

                min = array[i];
                for (int j = i + 1; j < array.length; j++)
                {
                    if (array[j] < min)
                    {
                        min = array[j];
                        pos = j;
                    }
                }
                array[pos] = array[i];
                array[i] = min;
            }

        }
        long end = System.nanoTime();

        long selectionSortRunTime = end - start;

        selectionSortTime[x] = (int) selectionSortRunTime;
        x++;

    // getting array length
    int length = selectionSortTime.length;

    // default sum value.
    int sum = 0;

    // sum of all values in array using for loop
    for (int i = 0; i < selectionSortTime.length; i++) {
        sum += selectionSortTime[i];
    }

    double average = sum / length;

    System.out.println("Average of array : "+average + " nano seconds.");

}

        return array;
    }

    /**
     * Sorting an array of ints in ascending order using insertionSort
     * Best-Case Complexity: O(n), Average Complexity: O(n^2), Worst-Case Complexity: O(n^2)
     * @param array
     * @return
     */
    static int[] insertionSort(int[] array)
    {

        int insertionSortTime[] = new int[500];
      int x, y;
        for (x = 0; x< 500; x++) {
        long start = System.nanoTime();
        int j;

        {
            for (int i = 1; i < array.length; i++)
            {

                int key = array[i];

                for (j = i - 1; (j >= 0) && (key < array[j]); j--)
                {
                    array[j + 1] = array[j];
                }
                array[j + 1] = key;
            }

        }
        long end = System.nanoTime();
    long insertionSortRunTime = end - start;

        insertionSortTime[x] = (int) insertionSortRunTime;
        x++;

    // getting array length
    int length = insertionSortTime.length;

    // default sum value.
    int sum = 0;

    // sum of all values in array using for loop
    for (int i = 0; i < insertionSortTime.length; i++) {
        sum += insertionSortTime[i];
    }

    double average = sum / length;

    System.out.println("Average of array : "+average + " nano seconds.");

}

        return array;
    }

    /**
     * Sorting an array of ints in ascending order using quickSort
     * Best-Case Complexity: O(n log(n)), Average Complexity: O(n log(n)), Worst-Case Complexity: O(n^2))
     * @param array
     * @return
     */
    static void quickSort(int[] array, int low, int high)
    {

        int pivot = array[low + ((high - low) / 2)];
        int i = low;
        int j = high;

            while (i <= j)
            {

                while (array[i] < pivot)
                {
                    i++;
                }
                while (array[j] > pivot)
                {
                    j--;
                }
                if (i <= j)
                {
                    int temp = array[i];
                    array[i] = array[j];
                    array[j] = temp;
                    i++;
                    j--;
                }
            }

            if (low < j)
            {
                quickSort(array, low, j);
            }

            if (i < high)
            {
                quickSort(array, i, high);
            }
        }

    /**
     * Helping method to benchmark quick sort's execution time
     * @param array
     */
    static void benchmarkQuickSort(int[] array)
    {
        int quickSortTime[] = new int[500];
          int x, y;
          for (x = 0; x< 500; x++) {
        long start = System.nanoTime();
        quickSort(array, 0, array.length - 1);
        long end = System.nanoTime();
        long quickSortRunTime = end - start;

        quickSortTime[x] = (int) quickSortRunTime;
        x++;

    // getting array length
    int length = quickSortTime.length;

    // default sum value.
    int sum = 0;

    // sum of all values in array using for loop
    for (int i = 0; i < quickSortTime.length; i++) {
        sum += quickSortTime[i];
    }

    double average = sum / length;

    System.out.println("Average of array : "+average + " nano seconds.");

}

    }

    /**
     * Sorting an array of ints in ascending order using mergeSort
     * Best-Case Complexity: O(n log(n)), Average Complexity: O(n log(n)), Worst-Case Complexity: O(n log(n)))
     * @param array
     * @return
     */
    public static int[] mergeSort(int[] array)
    {
        if (array.length == 1)
        {
            return array;
        }

        int[] array1 = new int[(array.length/2)];
        int[] array2 = new int[(array.length-array1.length)];

        System.arraycopy(array, 0, array1, 0, array1.length);
        System.arraycopy(array, array1.length, array2, 0, array2.length);

        mergeSort(array1);
        mergeSort(array2);

        merge(array1, array2, array);
        return array;
    }

    /**
     * Merges 2 sorted arrays of ints
     * @param array1
     * @param array2
     * @param mergedArray
     * @return
     */
    static void merge(int[] array1, int[] array2, int[] mergedArray)
    {
        int array1Index = 0;
        int array2Index = 0;
        int pos = 0;
        while ((array1Index < array1.length) && (array2Index < array2.length))
        {
            if (array1[array1Index] < array2[array2Index])
            {
                mergedArray[pos] = array1[array1Index];
                array1Index++;
                pos++;
            } else
            {
                mergedArray[pos] = array2[array2Index];
                array2Index++;
                pos++;
            }
        }

        if (array1Index < array2Index)
        {
            System.arraycopy(array1, array1Index, mergedArray, pos, array1.length - array1Index);
        }
        else if (array2Index < array1Index) ;
        {
            System.arraycopy(array2, array2Index, mergedArray, pos, array2.length - array2Index);
        }
    }

    /**
     * Helping method to benchmark merge sort's execution time
     * @param array
     */
    static void benchmarkMergeSort(int[] array)
    {
        int mergeSortTime[] = new int[500];
      int x, y;
        for (x = 0; x< 500; x++) {
        long start = System.nanoTime();
        mergeSort(array);
        long end = System.nanoTime();
  long quickSortRunTime = end - start;

        mergeSortTime[x] = (int) quickSortRunTime;
        x++;

    // getting array length
    int length = mergeSortTime.length;

    // default sum value.
    int sum = 0;

    // sum of all values in array using for loop
    for (int i = 0; i < mergeSortTime.length; i++) {
        sum += mergeSortTime[i];
    }

    double average = sum / length;

    System.out.println("Average of array : "+average + " nano seconds.");
        }

}

    /**
     * Creates and returns an array with random ints
     * @param size the size of the array to be created
     * @return
     */
    static int[] largeArrayWithRandomInts(int size)
    {
        int[] largeArray = new int[size];

        for (int i = 0; i < size; i++)
        {
            largeArray[i] = (int) (Math.random() * Math.random() * 500000);
        }
        return largeArray;
    }

    static int[] smallArrayWithRandomInts(int size)
    {
        int[] smallArray = new int[size];

        for (int i = 0; i < size; i++)
        {
            smallArray[i] = (int) (Math.random() * Math.random() * 50);
        }
        return smallArray;
    }

    /**
     * Prints the elements of  one dimensional array of type int
     * @param array
     */
    static void printArray(int[] array)
    {
        for (int i = 0; i < array.length; i++)
        {
            System.out.print(array[i] + " ");
        }
        System.out.println();
    }

}

I appreciate any insight.  Always ready to learn something new.

A: There are multiple things going wrong in your method.

*

*You are calculating and printing the in-between times by taking the average of 500 elements in bubbleSortTime. For the first run, instead of dividing by bubbleSortTime.length (which is 500), you should be dividing by x + 1 to get the average of the runs that you have done so far.

*You are timing each run separately, rounding to roughly 50 nanoseconds due to how System.nanoTime() works (see javadocs). What you should do is store the start time to a variable, then run the code that you want to time X times within a loop (100-1000 times is often sufficient, more runs will give a more precise result), then record the end time and finally divide the time elapsed by X to get the average runtime of the timed code.

*Before starting to time your code, you should run the timed code at least once. This will cause all classes and required system libraries to be loaded, which can be a one-time slightly slower operation.


text:
Q: Can I zip a list of numbers with a list of lists? I have two python lists:
The first list contains 8 numbers:
['4554176', '4554178', '4555289', '4555522', '4555661', '4555693', '4555695', '4556068']

The second list is a list of 8 lists:
[['dune', 'pro', 'pc', 'case'] ['apple', 'typische', 'kaesereiben', 'muster'] ['orientiert', 'profi', 'mac', 'mac'] ['handel', 'hersteller', 'pc', 'gehaeusen'] ['optik', 'kaesereibe', 'nutzer', 'ueberarbeitete', 'apple'] ['design', 'geklont', 'nennt', 'dune', 'pc'] ['oktober', 'form', 'kickstarter', 'projekts', 'realitaet'] ['annehmen', 'preise', 'genannt', 'signifikant']]

I want to zip the numbers of the first list with every element of the corresponding list in the list of lists.
Example:
[['4554176':'dune', '4554176':'pro', '4554176':'pc', '4554176':'case'],...

The example I provided is a dictionary. I know dictionaries dont support duplicate keys, but I want to show you what I am tyring to do.
Maybe a list of tuples is better?

A: Given
numbers = ['4554176', '4554178', '4555289', '4555522', '4555661', '4555693', '4555695', '4556068']
lists   = [
    ['dune', 'pro', 'pc', 'case'],
    ['apple', 'typische', 'kaesereiben', 'muster'],
    ['orientiert', 'profi', 'mac', 'mac'],
    ['handel', 'hersteller', 'pc', 'gehaeusen'],
    ['optik', 'kaesereibe', 'nutzer', 'ueberarbeitete', 'apple'],
    ['design', 'geklont', 'nennt', 'dune', 'pc'],
    ['oktober', 'form', 'kickstarter', 'projekts', 'realitaet'],
    ['annehmen', 'preise', 'genannt', 'signifikant']
]

A list comprehension would work:
result = [(n,word) for (n,l) in zip(numbers, lists) for word in l]

Output

[
  ('4554176', 'dune'),
  ('4554176', 'pro'),
  ('4554176', 'pc'),
  ('4554176', 'case'),
  ('4554178', 'apple'),
  ('4554178', 'typische'),
  ('4554178', 'kaesereiben'),
  ('4554178', 'muster'),
  ('4555289', 'orientiert'),
  ('4555289', 'profi'),
  ('4555289', 'mac'),
  ('4555289', 'mac'),
  ('4555522', 'handel'),
  ('4555522', 'hersteller'),
  ('4555522', 'pc'),
  ('4555522', 'gehaeusen'),
  ('4555661', 'optik'),
  ('4555661', 'kaesereibe'),
  ('4555661', 'nutzer'),
  ('4555661', 'ueberarbeitete'),
  ('4555661', 'apple'),
  ('4555693', 'design'),
  ('4555693', 'geklont'),
  ('4555693', 'nennt'),
  ('4555693', 'dune'),
  ('4555693', 'pc'),
  ('4555695', 'oktober'),
  ('4555695', 'form'),
  ('4555695', 'kickstarter'),
  ('4555695', 'projekts'),
  ('4555695', 'realitaet'),
  ('4556068', 'annehmen'),
  ('4556068', 'preise'),
  ('4556068', 'genannt'),
  ('4556068', 'signifikant'),
]

Edit: or, if you want the output nested:
result = [[(n,word) for word in l] for (n,l) in zip(numbers, lists)]

Output:

[
  [('4554176', 'dune'), ('4554176', 'pro'), ('4554176', 'pc'), ('4554176', 'case')],
  [('4554178', 'apple'), ('4554178', 'typische'), ('4554178', 'kaesereiben'), ('4554178', 'muster')],
  [('4555289', 'orientiert'), ('4555289', 'profi'), ('4555289', 'mac'), ('4555289', 'mac')],
  [('4555522', 'handel'), ('4555522', 'hersteller'), ('4555522', 'pc'), ('4555522', 'gehaeusen')],
  [('4555661', 'optik'), ('4555661', 'kaesereibe'), ('4555661', 'nutzer'), ('4555661', 'ueberarbeitete'), ('4555661', 'apple')],
  [('4555693', 'design'), ('4555693', 'geklont'), ('4555693', 'nennt'), ('4555693', 'dune'), ('4555693', 'pc')],
  [('4555695', 'oktober'), ('4555695', 'form'), ('4555695', 'kickstarter'), ('4555695', 'projekts'), ('4555695', 'realitaet')],
  [('4556068', 'annehmen'), ('4556068', 'preise'), ('4556068', 'genannt'), ('4556068', 'signifikant')],
]

A: Your expected results seem like you're looking for a list but you're using colons like it were a dict. By the data I assume you need a list of lists of tuples. In that case zip and itertools.repeat are your friend.
list1 = ['4554176', '4554178', '4555289', '4555522', '4555661', '4555693', '4555695', '4556068']
list2 = [['dune', 'pro', 'pc', 'case'], ['apple', 'typische', 'kaesereiben', 'muster'], ['orientiert', 'profi', 'mac', 'mac'], ['handel', 'hersteller', 'pc', 'gehaeusen'], ['optik', 'kaesereibe', 'nutzer', 'ueberarbeitete', 'apple'], ['design', 'geklont', 'nennt', 'dune', 'pc'], ['oktober', 'form', 'kickstarter', 'projekts', 'realitaet'], ['annehmen', 'preise', 'genannt', 'signifikant']]

result = [list(zip(repeat(s), l)) for s, l in zip(list1, list2)]

Result:
[[('4554176', 'dune'), ('4554176', 'pro'), ('4554176', 'pc'), ('4554176', 'case')], [('4554178', 'apple'), ('4554178', 'typische'), ('4554178', 'kaesereiben'), ('4554178', 'muster')], [('4555289', 'orientiert'), ('4555289', 'profi'), ('4555289','mac'), ('4555289', 'mac')], [('4555522', 'handel'), ('4555522', 'hersteller'), ('4555522', 'pc'), ('4555522', 'gehaeusen')], [('4555661', 'optik'), ('4555661', 'kaesereibe'), ('4555661', 'nutzer'), ('4555661', 'ueberarbeitete'), ('4555661', 'apple')], [('4555693', 'design'), ('4555693', 'geklont'), ('4555693', 'nennt'), ('4555693', 'dune'), ('4555693', 'pc')], [('4555695', 'oktober'), ('4555695', 'form'),('4555695', 'kickstarter'), ('4555695', 'projekts'), ('4555695', 'realitaet')], [('4556068', 'annehmen'), ('4556068', 'preise'), ('4556068', 'genannt'), ('4556068', 'signifikant')]]

P.S: list2 was missing commas between each sub-list I resolved that above.

Maybe a list of tuples is better?

IMHO: You may honestly want to use a dict for this data as the above is overkill for the data represented. Also it'd be MUCH more simple to convert.
result = dict(zip(list1, list2))

Result:
{'4554176': ['dune', 'pro', 'pc', 'case'], '4554178': ['apple', 'typische', 'kaesereiben', 'muster'], '4555289': ['orientiert', 'profi', 'mac', 'mac'], '4555522': ['handel', 'hersteller', 'pc', 'gehaeusen'], '4555661': ['optik', 'kaesereibe', 'nutzer', 'ueberarbeitete', 'apple'], '4555693': ['design', 'geklont', 'nennt', 'dune', 'pc'], '4555695': ['oktober', 'form', 'kickstarter', 'projekts', 'realitaet'], '4556068': ['annehmen', 'preise', 'genannt', 'signifikant']}

Although If you want a list of tuples, then simply use my first approach and wrap it in itertools.chain:
result = list(chain(*(list(zip(repeat(s), l)) for s, l in zip(list1, list2))))

Result:
[('4554176', 'dune'), ('4554176', 'pro'), ('4554176', 'pc'), ('4554176', 'case'), ('4554178', 'apple'), ('4554178', 'typische'), ('4554178', 'kaesereiben'), ('4554178', 'muster'), ('4555289', 'orientiert'), ('4555289', 'profi'), ('4555289', 'mac'), ('4555289', 'mac'), ('4555522', 'handel'), ('4555522', 'hersteller'), ('4555522', 'pc'), ('4555522', 'gehaeusen'), ('4555661', 'optik'), ('4555661', 'kaesereibe'), ('4555661', 'nutzer'), ('4555661', 'ueberarbeitete'), ('4555661', 'apple'), ('4555693', 'design'), ('4555693', 'geklont'), ('4555693', 'nennt'), ('4555693', 'dune'), ('4555693', 'pc'), ('4555695', 'oktober'), ('4555695', 'form'), ('4555695', 'kickstarter'), ('4555695', 'projekts'), ('4555695', 'realitaet'), ('4556068', 'annehmen'), ('4556068', 'preise'), ('4556068', 'genannt'), ('4556068', 'signifikant')]

Extra, here's functional approaches to both ways other than the dict result. (they require itertools.starmap FYI)
list of lists
list(map(list, starmap(zip, zip(map(repeat, list1), list2))))

list of tuples
list(chain(*starmap(zip, zip(map(repeat, list1), list2))))

A: Create temp list for every item(with repeatation 4 times) of frist list and then zip with first list of 2nd list.
[list(zip([l1[i]]*len(l2[i]), l2[i])) for i in range(len(l2))]

A: Python does not support duplicate keys. But maybe you can make them into a key-array dict?
a = ['4554176', '4554178', '4555289', '4555522', '4555661', '4555693', '4555695', '4556068']
b = [['dune', 'pro', 'pc', 'case'], ['apple', 'typische', 'kaesereiben', 'muster'], ['orientiert', 'profi', 'mac', 'mac'], ['handel', 'hersteller', 'pc', 'gehaeusen'], ['optik', 'kaesereibe', 'nutzer', 'ueberarbeitete', 'apple'], ['design', 'geklont', 'nennt', 'dune', 'pc'], ['oktober', 'form', 'kickstarter', 'projekts', 'realitaet'], ['annehmen', 'preise', 'genannt', 'signifikant']]
c = {}

for i in range(len(a)):
    c[a[i]] = b[i]

print(c)

Output: {'4555289': ['orientiert', 'profi', 'mac', 'mac'], '4555693': ['design', 'geklont', 'nennt', 'dune', 'pc'], '4555522': ['handel', 'hersteller', 'pc', 'gehaeusen'], '4556068': ['annehmen', 'preise', 'genannt', 'signifikant'], '4554176': ['dune', 'pro', 'pc', 'case'], '4555695': ['oktober', 'form', 'kickstarter', 'projekts', 'realitaet'], '4555661': ['optik', 'kaesereibe', 'nutzer', 'ueberarbeitete', 'apple'], '4554178': ['apple', 'typische', 'kaesereiben', 'muster']}
Or, maybe an array of tiny dicts:
a = ['4554176', '4554178', '4555289', '4555522', '4555661', '4555693', '4555695', '4556068']
b = [['dune', 'pro', 'pc', 'case'], ['apple', 'typische', 'kaesereiben', 'muster'], ['orientiert', 'profi', 'mac', 'mac'], ['handel', 'hersteller', 'pc', 'gehaeusen'], ['optik', 'kaesereibe', 'nutzer', 'ueberarbeitete', 'apple'], ['design', 'geklont', 'nennt', 'dune', 'pc'], ['oktober', 'form', 'kickstarter', 'projekts', 'realitaet'], ['annehmen', 'preise', 'genannt', 'signifikant']]
c = []

for i in range(len(a)):
    key = a[i]
    for j in range(len(b[i])):
        c.append({ a[i]: b[i][j] })

print(c)

Output: [{'4554176': 'dune'}, {'4554176': 'pro'}, {'4554176': 'pc'}, {'4554176': 'case'}, {'4554178': 'apple'}, {'4554178': 'typische'}, {'4554178': 'kaesereiben'}, {'4554178': 'muster'}, {'4555289': 'orientiert'}, {'4555289': 'profi'}, {'4555289': 'mac'}, {'4555289': 'mac'}, {'4555522': 'handel'}, {'4555522': 'hersteller'}, {'4555522': 'pc'}, {'4555522': 'gehaeusen'}, {'4555661': 'optik'}, {'4555661': 'kaesereibe'}, {'4555661': 'nutzer'}, {'4555661': 'ueberarbeitete'}, {'4555661': 'apple'}, {'4555693': 'design'}, {'4555693': 'geklont'}, {'4555693': 'nennt'}, {'4555693': 'dune'}, {'4555693': 'pc'}, {'4555695': 'oktober'}, {'4555695': 'form'}, {'4555695': 'kickstarter'}, {'4555695': 'projekts'}, {'4555695': 'realitaet'}, {'4556068': 'annehmen'}, {'4556068': 'preise'}, {'4556068': 'genannt'}, {'4556068': 'signifikant'}]

A: You can use the function product() in a list comprehension:
from itertools import product

lst1 = list('123')
lst2 = [list('ab'), list('cd'), list('ef')]

[list(product(*i)) for i in zip(lst1, lst2)]
# [[('1', 'a'), ('1', 'b')], [('2', 'c'), ('2', 'd')], [('3', 'e'), ('3', 'f')]]

A: I like this combination of itertools.product with an inner zip.
import itertools

v1 =['4554176', '4554178', '4555289']
v2 = [
    ['dune', 'pro', 'pc', 'case'],
    ['apple', 'typische', 'kaesereiben', 'muster'],
    ['orientiert', 'profi', 'mac', 'mac'],
]

result = [list(itertools.product([x], y)) for (x, y) in zip(v1, v2)]
print(result)

This is similar to @beer44's answer, except that product replaces the multiplication by 4

redpajama_set_name: RedPajamaStackExchange


text:
Q: the size of each parent in json file I need to build a json file like this https://gist.github.com/mbostock/1283663  in order to obtain an animeted graph like this http://bl.ocks.org/mbostock/1283663. But i didn't understand how the size of each parent is determined if only children's size are mentioned in the json file ?
Is it the sum of children's size? and if it 's true how to change the parent size?  because i want  the parent's size to be the average of children's size.
I need your helps please. Thanks :)


text:
Q: com.microsoft.sqlserver.jdbc.SQLServerException: Error when reading Azure SQLDB from Apache Spark Databricks I answered one of my previous questions, however, having fixed the issue, I am faced with an another issue regarding SQLServerException.
I am trying to read in data on an Azure SQLDB.
I have successfully authenticated to the server however when I try to apply the function to read in data I get the following error:

com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near
'5'

The following is more details on the error:
Py4JJavaError                             Traceback (most recent call last)
<command-3741352302548628> in readFromDb(processId, query)
      3   try:
----> 4     jdbcDF = (spark.read
      5       .format("jdbc")

/databricks/spark/python/pyspark/sql/readwriter.py in load(self, path, format, schema, **options)
    209         else:
--> 210             return self._df(self._jreader.load())
    211

/databricks/spark/python/lib/py4j-0.10.9-src.zip/py4j/java_gateway.py in __call__(self, *args)
   1303         answer = self.gateway_client.send_command(command)
-> 1304         return_value = get_return_value(
   1305             answer, self.gateway_client, self.target_id, self.name

The code is as follows:
def readFromDb(processId, query):
  try:
    jdbcDF = (spark.read
      .format("jdbc")
      .option("driver", "com.microsoft.sqlserver.jdbc.SQLServerDriver")
      .option("url", f"jdbc:sqlserver://{DBServer}.database.windows.net;database={DBDatabase}")
      .option("user", DBUser)
      .option("query", query)
      .option("password", DBPword)
      .load()
     )
    return jdbcDF
  except Exception as e:
    writeToLogs(processId,LogType.Error, EventType.FailReadFromDb, LogMessage.FailReadFromDb, errorType = ErrorType.FailReadFromDb)
    raise Error(f"{LogMessage.FailReadFromDb.value} ERROR: {e}")
  except:
    writeToLogs(processId,LogType.FailReadFromDb, EventType.FailReadFromDb, LogMessage.FailReadFromDb, errorType = ErrorType.FailReadFromDb)
    raise Error(f"{LogMessage.FailReadFromDb.value}")

Can someone let me know what the code generally means and best approach to fix it?

A: Like @mac and Alex Ott said, the error is mostly caused by the query statements.
And we are glad to hear the error is resolved bye modify the query.


text:
Q: Iterate v.export on GRASS 7.8.5 through Python 3 using a list and SQL I would like to iterate an analysis on a vector for each unique value present on his attribute table. The first step is to extract different vector according to the unique identifier, but the SQL formula doesn't work. It should be Site_ID='site', instead is  Site_ID=site. I am using GRASS 7.8.5 and python 3, launched from the GRASS shell.
Desired behavior: extract groups of features from a vector by a unique identifier using a list
Error: The formula is not able to insert the correct SQL expression. It should be Site_ID='site', instead is  Site_ID=site.
import os
import grass.script as script

area_allsites = 'input vector'

# Create a list with site names from the column Site_ID
sitelist1 = gscript.read_command('v.db.select',
    map=area_allsites,
    columns='Site_ID',
    flags='c',
    overwrite = overwrite)

sitelist2 = sitelist1.split(os.linesep)
sitelist=list(set(sitelist2)) # remove duplicates

# Reiterate trough area_allsites using the list names
for site in sitelist:
    formula = 'Site_ID =' + site
    gscript.run_command('v.extract',
        input=area_allsites,
        where=formula,
        output=('area' + site),
        overwrite = overwrite)


text:
Q: file association in Windows 8 Associating a file to a program should be easy in Windows. However, i find it rather difficult when I'm working on Windows 8. associating a file to a desktop application that I install on my computer is easy because the whole operation is entirely the same with that in the previous Windows releases. What I find rather difficult is associating a file to a Metro apps that I download from the store. So far, I have been using Multimedia 8 (a metro app) to open my video files. However, this app cannot handle particular files-like *.dat-that can be associated easily to desktop video applications, such as media player classic and the like. When I try to associate my DAT files to Multimedia 8, there is indeed a "look for another app on this PC" option at the bottom of the "open with" pop up. But alas, I cannot figure out how to locate my Multimedia 8 app to which I want to associate my DAT file (as well as other video files that are not yet associated to this metro app). If anyone of you knows how to locate those metro apps, please tell me. many thanks

A: They are at C:\Program Files\WindowsApps (the directory is hidden; you don't have read permissions by default).

A: Use the Application DefaultProgramEditor to change the associations:

Default Programs Editor makes it easy to fix file association settings in Windows, including context menu items, icons, and descriptions. Also: autoplay settings and default programs settings ...all without fiddling around in the registry.


text:
Q: Finding the minimum value in an array (What's wrong with my code?) This is for my intro to C++ course. We are currently doing arrays and I'm trying to find the min value for each column of the array. here is what I have:
#include <iostream>
using namespace std;

int main(){
int grade[4][30] = {{76, 70, 80, 90, 100, 83, 61, 63, 64, 65, 97, 69, 70, 79,60, 70, 80, 90, 100, 83, 61, 63, 99, 98, 66, 69, 70, 79},
                    {74, 70, 80, 90,60, 61, 93, 88, 73, 65, 91, 69, 70, 79, 60, 70, 80, 90, 60, 83, 61, 63, 64, 65, 66, 69, 67, 74},
                    {72, 70, 80, 90, 99, 84, 62, 63, 99, 65, 66, 69, 70, 79, 60, 70, 80, 90, 99, 83, 61, 63, 64, 65, 66, 69, 70, 77},
                    {69, 70, 80, 90, 60, 61, 86, 63, 97, 97, 66, 69, 70, 79, 97, 70, 80, 90, 88, 83, 88, 63, 64, 65, 66, 69, 70, 79}};

int a;
for(int x = 0; x < 4; ++x){
    a = grade[x][0];
    for(int y = 0; y < 30; ++y){
        if( a > grade[x][y])
            a = grade[x][y];
            cout << "a is " << a << " for the " << y << "time" << endl;}
    cout << a << endl;}

return 0;

}

My problem is I don't understand why in the last two loops the value turns to 0? The real answer should be 60 for each row.
P.S I used this to find the maximum and it worked, but don't get why it won't work here?

A:
for(int y = 0; y < 30; ++y){

It is because for example your first array contains only 28 explicitly initialized elements and you iterate till 30 (see above). The elements which you didn't initialize yourself are initialized to 0.

A: Your array initializers have less than 30 numbers.  Since your array is declared to take 30 elements, the remaining entries are set to 0.
Since you don't appear to have 0s in your data, you could use 0 as a sentinel to know to stop the loop.


text:
Q: Develop Coldfusion Web Service I need to develop/design Coldfusion Web Service which uses few object calls and functions.

*

*What is good source of samples to develop in terms of OOP?

*What is best way to secure the web service?

*how to authenticate external/internal users, any sample?

FYI, This web service is going to be used by multiple department.
thanks
A

A: OOP examples are all over the web.  I don't have any handy, so I'll skip that part, and go straight to authentication and security.
First, authentication.  There are several possible answers depending on what kind of users you are authenticating.  For example, if you are authenticating users connnecting via a 3rd parth tool -- like a desktop or phone app posting to Twitter -- I would say that OAuth is a good solution.  There is a good library for both publishing and consuming OAuth integrations at oauth.riaforge.com.  If you are looking for someting lighter weight, we used a simple token creation scheme for a webservice that was only consumed by partner services.  Basically, the partner service sends what amounts to a username and password pair, a token is created with a "last used" timestamp, and every time the webservice interacts after that, we do a check against the token store.
Security is, similarly, very dependent on your end goals.  However, there are a few basic principles I've always tried to follow.  First, build your basic CFCs as you normally would for constructing your objects.  Entry points should be public, helper functions private, etc.  This includes building an object to handle whatever authntication model you choose.  On top of that, build your public API.  These should all simply be access functions.  They are called by outside applications, call the security object, then call the appropriate objects and methods to achieve the goal of the call. This way, you never have to bake the security layer into your base functionality calls, but you also have an easy way to include security.  Remember, a single API call does not have to reflect a single base call -- you can build more complex routines if needed.
So, to recap.
Authentication

*

*OAuth

*Temporary Token Generation

Security

*

*private/public (not remote) base layer

*private/public (not remote) authentication layer

*remote API layer


text:
Q: Great Expectations: expect_values_to_match_regex rule gives out error for all regex NOTE: Running on Snowflake
I actually need the regex to check for SSN. The one I'm using is -
Regex used: '^(?!666|000|9\\d{2})\\d{3}-(?!00)\\d{2}-(?!0{4})\\d{4}$'
Error message:
Invalid regular expression: '^(?!666|000|9\d{2})\d{3}-(?!00)\d{2}-(?!0{4})\d{4}$', no argument for repetition operator: ?\n[SQL: SELECT sum(CASE WHEN (ssn IS NOT NULL AND NOT (ssn RLIKE %(param_1)s)) THEN %(param_2)s ELSE %(param_3)s END) AS "column_values.match_regex.unexpected_count", sum(CASE WHEN (ssn IS NULL) THEN %(param_4)s ELSE %(param_5)s END) AS "column_values.nonnull.unexpected_count" \nFROM ge_temp_4b471582]\n[parameters: {'param_1': '^(?!666|000|9\\d{2})\\d{3}-(?!00)\\d{2}-(?!0{4})\\d{4}$', 'param_2': 1, 'param_3': 0, 'param_4': 1, 'param_5': 0}]
Rule used:
{"expectation_type": "expect_column_values_to_match_regex", "kwargs": {"column": "ssn", "regex": "^(?!666|000|9\d{2})\d{3}-(?!00)\d{2}-(?!0{4})\d{4}$"}, "meta": {}}
A couple months ago, when I ran this, it was running perfectly. Is there something I'm doing wrong here? Or is it a problem from Great Expectation's side?
So, I figured there must be a problem with the regex. But, using a basic regex like the one mentioned below, I'm getting a similar error.
regex used: '[Aa-Zz]'
Error message:
Invalid regular expression: '[Aa-Zz]', invalid character class range: a-Z\n[SQL: SELECT first AS unexpected_values \nFROM ge_temp_de90d2b5 \nWHERE first IS NOT NULL AND NOT (first RLIKE %(param_1)s)\n LIMIT %(param_2)s]\n[parameters: {'param_1': '[Aa-Zz]', 'param_2': 20}]\n(Background on this error at: https://sqlalche.me/e/14/f405)\n"/n%22),
Thanks in advance! :)


text:
Q: Read a text file to a matrix and then multiply them  I have some .txt files looks like this:
1050.00 68.13

1048.00 67.89

1046.00 67.62

1044.00 67.30

1042.00 66.91

[ ... ]

I want to multiply this to another matrix.
My problem is that I don't know how to read and store this data in a matrix.
Do anyone have any idea that can help me?

A: I'd store the data in a vector<vector<double>>, and I'd read it in using std::getline, std::istringstream, and operator>>.
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iterator>
#include <algorithm>
struct Matrix {
  std::vector<std::vector<double> > data;
  Matrix(const std::string& filename) {
    std::ifstream inFile(filename.c_str());
    std::string inLine;
    while(std::getline(inFile, inLine)) {
      std::istringstream inLineStream(inLine);
      std::vector<double> inLineData(
        (std::istream_iterator<double>(inLineStream)),
        std::istream_iterator<double>());
      data.push_back(inLineData);
    }
  }
  Matrix operator*(const Matrix& rhs) { ... };
};

int main () {
  Matrix a("a.txt");
  Matrix b("b.txt");
  Matrix c(a * b);
}

A: What is a "matrix"?
If you have some sort of "matrix library", simply use its functions.
If you are implementing the matrices yourself, read the textfile line-by-line (fgets()) and use sscanf() to read the items.
Hope this helps.

A: You can read it this way:
char *fname = "matrix.txt";
ifstream infile(fname);

float f;
while (infile >> f) {
   //store f to matrix
}

There are a lot of maxtrix class implementation samples in the web, there is one:  http://www.codeproject.com/Articles/3613/A-generic-reusable-and-extendable-matrix-class


text:
Q: Extracting integers from given .txt file Each column represents a different variable for a large set of data. I am trying to extract each number and place it in an array for each row.
Underscores represent spacing
2___2___2_______3___1___19
1___3___2_______3___3___19
1___3___4_______3___1___19
6___3___6_______5_______13
5___2___5_______5_______13
5___4___4___7___4_______13
spaceForNew Represents how many characters are left until the next variable will be found. This varies from the current variable.
I am using the following code:
    public static int[] remaining(String Line)throws IOException
{
    int[] data = new int[7];
    int pointer = 0;
    int spaceForNew = 0;
    for(int i = 0;i<=Line.length()-1;i++)
    {
        if(i<Line.length()-1)
        {
            if((i == spaceForNew)&&(pointer<6))
            {
                //two digit
                if((Line.charAt(i)=='1')&&(Line.charAt(i+1)=='0'))
                {
                    data[pointer] = 10;
                    spaceForNew+=3;
                    pointer++;
                //one digit
                }else if((Line.charAt(i)!= '    ')&&(Line.charAt(i+1)!='0')){
                    data[pointer] = Integer.parseInt(Character.toString(Line.charAt(i)));
                    spaceForNew+=2;
                    pointer++;
                }else if((Line.charAt(i)==' ')&&(data[pointer]==0)){
                    data[pointer]=-1;
                    spaceForNew++;
                    pointer++;
                }

            }
        }else {
            if(pointer==6)
            {
                data[pointer]=Integer.parseInt(Character.toString(Line.charAt(i)));
            }
        }
    }
    return data;
}

Following code is hideous and not very intuitive but seems to work for a lot of the data but fails in a fashion that appears to almost be random. Any suggestions at all would be much obliged

A: UPD Try this
    String line = "10   8   10           1   8";
    String[] split = line.split("   ");
    int[] array = new int[7];
    for (int i = 0; i < split.length; i++) {
        array[i] = split[i].trim().isEmpty() ? -1 : Integer.parseInt(split[i].trim());
    }

A: you can use regex to parse the lines
(\d+| )(?:   )?
this basically says give me all digits or a single space that is followed or not by 3 spaces.
you will get a list of strings that are either able to parse into numbers or is a single space and you can handle that as missing data but will be a place holder so you can keep your columns straight.
    Integer[] parsed = new Integer[7];
    String thing = "2   2   2       3   1   19";
    Pattern pattern = Pattern.compile("(\\d+| )(?:   )?");
    Matcher m = pattern.matcher(thing);
    int index = 0;
    while (m.find()) {
        if (!" ".equals(m.group(1)))
            parsed[index] = Integer.parseInt(m.group(1));
        else
            parsed[index] = -1; //or what ever your missing data value should be.
        index++;
    }
    Arrays.asList(parsed).forEach(System.out::println);

edit*** super fixed. group(0) is the whole pattern and then comes any capturing groups.  so group(1) gets the first capture group which is just the digits or a single space.

A: You need to know what exactly the pattern is for each line. I assume that each 'column' has a fixed width, otherwise, the numbers were not be aligned like this.
For example, suppose each column is three characters wide (digits and/or spaces), and the column separator is 1 space wide, your pattern could look like this:
[ \d]{3} |[ \d]{1,3}

Now with Pattern::compile, Pattern::matcher and Matcher::find you could search for all numbers present in the current line. Assuming that lines is a List<String> with each element being a line:
// Precompile pattern. This matches either a cell followed by a space, or,
// if we are at the end of the line, a variable number of spaces and/or
// digits.
Pattern pattern = Pattern.compile("[ \\d]{3} |[ \\d]{1,3}");

List<List<Integer>> matrix = lines.stream()
    .map(pattern::matcher)
    .map(matcher -> {
        List<Integer> ints = new ArrayList<>();
        while (matcher.find()) {
            String element = matcher.group().trim();
            ints.add(!element.isEmpty() ? Integer.valueOf(element) : -1);
        }
        return ints;
    })
    .collect(Collectors.toList());

Using MatcherStream provided by dimo414:
Pattern pattern = Pattern.compile("[ \\d]{3} |[ \\d]{1,3}");
List<List<Integer>> matrix = lines.stream()
    .map(line -> MatcherStream.find(pattern, line)
        .map(String::trim)
        .map(element -> !element.isEmpty() ? Integer.valueOf(element) : -1)
        .collect(Collectors.toList()))
    .collect(Collectors.toList());

A: I would imagine that theoretically a value could be missing anywhere within any given file line of space delimited data, even consecutive values. This would include

*

*at the beginning of a data line;

*at the end of a data line;

*anywhere between the start and end of a data line.

Examples might be (as in your example, underscores represent whitespaces):
2___2___2_______3___1___19

1___3___2_______3___3___19

____3___4_______3___1___19

____5___7___4___3___8____

6___3___6_______5_______13

5___2___5_______________13

5___4___4___7___4_______16

10___6___10___3___8_______1

2___10___0___8___4___0___1

2___10___0___8___4________

4___12___0___9___6

The saving grace here is the fact that the data within the file appears to be formatted in a fixed space pattern. Knowing this it is possible to replace missing values with a specific integer value that will be rather obscure from the other values actually contained within each file data line. I think "-1" (what you're using) would indeed work well for this providing there is never the fear of dealing with any other signed data value within the file or -1 would never be a value of any real concern towards further data processing since its' possible existence is taken into consideration. This of course would be something you have to decide.
Once the missing values in any given data line are replaced with -1 that line can be split based on whitespace delimitation, the array elements converted to integer, and then they are placed into a integer array.
If you want to place each row (file line) of file data into an Integer Array then allow me to suggest a Two Dimensional Integer (int[][]) Array. I think you would find it much easier to deal with since the entire file of data can be contained within that specific array. Then allow a Java method to create that array, for example:
Read the entire file line by line into a String[] Array:
List<String> list = new ArrayList<>();
try (Scanner reader = new Scanner(new File("FileExample.txt"))) {
    while (reader.hasNextLine()) {
        String line = reader.nextLine();
        if (line.equals("")) { continue; }
        list.add(line);
    }
}
catch (FileNotFoundException ex) {
    Logger.getLogger("FILE NOT FOUND!").log(Level.SEVERE, null, ex);
}

// Convert list to String Array
String[] stringData = list.toArray(new String[0]);

The FileExample.txt file contains the very same data as provided above however, within the file underscores are whitespaces. Once the code above is run the String[] Array variable named stringData will contain all file data lines. We now pass this array to our next method named stringDataTo2DIntArray() (for lack of a better name) to create a 2D integer array (data[][]):
/**
 * Creates a 2D Integer (int[][]) Array from data lines contained within the
 * supplied String Array.

 *
 * @param stringData (1D String[] Array) The String array where each element
 * contains lines of fixed space delimited numerical values, for example each
 * line would look something like:

 *
 *     "2   1   3   4   5   6   7"

 *
 * @param replaceMissingWith (String) One or more numerical values could be
 * missing from any elemental line within the supplied stringData array. What
 * you supply as an argument to this parameter will be used in place of that
 * missing value.

 *
 * @param desiredNumberOfColumns (Integer (int)) The number of columns desired
 * in each row of the returned 2D Integer Array. Make sure desiredNumberOfColumns
 * contains a value greater than 0 and less then (Integer.MAX_VALUE - 4). You
 * will most likely run out of JVM memory if you go that big! Be reasonable,
 * although almost any unsigned integer value can be supplied (and you're
 * encouraged to test this) the largest number of data columns contained within
 * the data file should suffice.

 *
 * @return (2D Integer (int[][]) Array) A two dimensional Integer Array derived
 * from the supplied String Array of fixed space delimited line data.
 */
public int[][] stringDataToIntArray(final String[] stringData,
        final String replaceMissingWith, final int desiredNumberOfColumns) {
    int requiredArrayLength = desiredNumberOfColumns;

    // Make sure the replaceMissingWith parameter actually contains something.
    if (replaceMissingWith == null || replaceMissingWith.trim().equals("")) {
        System.err.println("stringDataToIntArray() Method Error! The "
                + "replaceMissingWith parameter requires a valid argument!");
        return null;
    }

    /* Make sure desiredNumberOfColumns contains a value greater than 0 and
       less then (Integer.MAX_VALUE - 4).   */
    if (desiredNumberOfColumns < 1 || desiredNumberOfColumns > (Integer.MAX_VALUE - 4)) {
        System.err.println("stringDataToIntArray() Method Error! The "
                + "desiredNumberOfColumns parameter requires any value "
                + "from 1 to " + (Integer.MAX_VALUE - 4) + "!");
        return null;
    }

    // The 2D Array to return.
    int[][] data = new int[stringData.length][requiredArrayLength];

    /* Iterate through each elemental data line contained within
       the supplied String Array. Process each line and replace
       any missing values...   */
    for (int i = 0; i < stringData.length; i++) {
        String line = stringData[i];
        // Replace the first numerical value with replaceMissingWith if missing:
        if (line.startsWith(" ")) {
            line = replaceMissingWith + line.substring(1);
        }

        // Replace remaining missing numerical values if missing:
        line = line.replaceAll("\\s{4}", " " + replaceMissingWith);

        // Split the string of numerical values based on whitespace:
        String[] lineParts = line.split("\\s+");

        /* Ensure we have the correct Required Array Length (ie: 7):
           If we don't then at this point we were missing values at
           the end of the input string (line). Append replaceMissingWith
           to the end of line until a split satisfies the requiredArrayLength:  */
        while (lineParts.length < requiredArrayLength) {
            line+= " " + replaceMissingWith;
            lineParts = line.split("\\s+");
        }

        /* Fill the data[][] integer array. Convert each string numerical
           value to an Integer (int) value for current line:   */
        for (int  j = 0; j < requiredArrayLength; j++) {
            data[i][j] = Integer.parseInt(lineParts[j]);
        }
    }
    return data;
}

And to use this method (once you've read the data file and placed its' contents into a String Array):
int[][] data = stringDataToIntArray(stringData, "-1", 7);

// Display the 2D data Array in Console...
for (int i = 0; i < data.length; i++) {
    System.out.println(Arrays.toString(data[i]));
}

If you've processed the example file data provided above then your console output window should contain:
[2, 2, 2, -1, 3, 1, 19]
[1, 3, 2, -1, 3, 3, 19]
[-1, 3, 4, -1, 3, 1, 19]
[-1, 5, 7, 4, 3, 8, -1]
[6, 3, 6, -1, 5, -1, 13]
[5, 2, 5, -1, -1, -1, 13]
[5, 4, 4, 7, 4, -1, 16]
[10, 6, 10, 3, 8, -1, 1]
[2, 10, 0, 8, 4, 0, 1]
[2, 10, 0, 8, 4, -1, -1]
[4, 12, 0, 9, 6, -1, -1]

If you want only the first three columns from each file line then your call would be:
int[][] data = stringDataToIntArray(stringData, "-1", 3);

and the output would look like:
[2, 2, 2]
[1, 3, 2]
[-1, 3, 4]
[-1, 5, 7]
[6, 3, 6]
[5, 2, 5]
[5, 4, 4]
[10, 6, 10]
[2, 10, 0]
[2, 10, 0]
[4, 12, 0]

and if you want 12 data columns for each file line your call would be:
int[][] data = stringDataToIntArray(stringData, "-1", 12);

and the output would look like:
[2, 2, 2, -1, 3, 1, 19, -1, -1, -1, -1, -1]
[1, 3, 2, -1, 3, 3, 19, -1, -1, -1, -1, -1]
[-1, 3, 4, -1, 3, 1, 19, -1, -1, -1, -1, -1]
[-1, 5, 7, 4, 3, 8, -1, -1, -1, -1, -1, -1]
[6, 3, 6, -1, 5, -1, 13, -1, -1, -1, -1, -1]
[5, 2, 5, -1, -1, -1, 13, -1, -1, -1, -1, -1]
[5, 4, 4, 7, 4, -1, 16, -1, -1, -1, -1, -1]
[10, 6, 10, 3, 8, -1, 1, -1, -1, -1, -1, -1]
[2, 10, 0, 8, 4, 0, 1, -1, -1, -1, -1, -1]
[2, 10, 0, 8, 4, -1, -1, -1, -1, -1, -1, -1]
[4, 12, 0, 9, 6, -1, -1, -1, -1, -1, -1, -1]

The additional -1's at then end of each array is because the method detected those columns didn't exist within the data lines but because 12 was your desired columns amount the required data was appended.


text:
Q: How to prevent column overlap in Highcharts I believe this is a general question not needing to much information from my highcharts data.
I want to prevent the columns to stack over/overlap each other, how do I do this?
See image-link below on how it is now
http://highslide.com/forum/download/file.php?id=3157
jsfiddle: http://jsfiddle.net/Dzs5q/

A: Please try and reproduce the error here @ http://jsfiddle.net/jugal/bgNBG/
Highcharts by default smartly reduces width of the columns if there are way too many of them so as to avoid overlapping.
The columns will tend to overlap if you have overridden the aforementioned default behavior by specifying column.pointWidth
    column: {
        pointWidth : 10
    }

eg: @ http://jsfiddle.net/jugal/bgNBG/2/
So to avoid overlapping, I see two options you have.
Option #1.  Remove the column.pointWidth
This will make the columns thinner in order to not overlap
eg:  @ http://jsfiddle.net/jugal/bgNBG/
Option #2.  Use column.dataGrouping
This will help have a constant width of columns, but reducing (by grouping them) the number of columns instead to avoid clutter/overlap.
dataGrouping = {
    groupPixelWidth: 40, // Minimum width for each column
    units: [[            // Permissible groupings
        'day',
        [1, 2, 3,4,5,6]  // 1,2,3,4,5,6 days may be grouped into 1 column
        ]]
}

eg: @ http://jsfiddle.net/jugal/JraJW/4/
Similar Question @ https://stackoverflow.com/a/12354111/1566575

A: The best way to control the columns and make sure they don't stack/overlap over each other is by controlling the width of the chart.  you can do this within the containing <div>.

*

*CSS: min-width ~ allows the div to change size, but restrict it from going under a certain width.  You do this because you know once it is under that width stuff start to blur together and is unreadable.

*CSS: width ~ forces the width of the chart to allows be a certain value.

*CSS: no width set ~ notice if you shrink the browser window down to far it begins to make the chart unreadable.

By controlling the width of the containing div and rotating the label as c0deNinja suggested, you can prevent most stack over/overlap issues.  However, if you chart has to many series/data points, even this won't help.

A: My problem was similar and I was getting nowhere with solutions which moved items to the secondary axis etc. Then I found my x axis was being recognized as a continuum (in this case: date) and the two overlapping columns were of course sharing the same x value.
I solved the problem by selecting the x axis, found the option called "axis type" and deselected "automatically select based on data" changing it to "text axis". That got my columns side by side.
A bit overdue for your problem but maybe helpful.


text:
Q: Difficulty with reading csv file Write a function named "csv_to_kvs" that takes a string as a parameter representing the name of a CSV file with 4 columns in the format "string, float, float, float" and returns a new key-value store mapping strings to floating point numbers. The returned key-value store will have one pair for each row in the file with keys from the first column of the CSV file and values from the third column. (My code below)
import csv
def csv_to_kvs(string):
  with open(string) as f:
    my_file = csv.reader(f)
    my_dict = {}
    for row in my_file:
      my_dict[row[0]] = row[2]
    return my_dict

How can I convert the values in the dictionary into floats?

A: Use casting.

There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.
Casting in python is therefore done using constructor functions:
int() - constructs an integer number from an integer literal, a float literal (by rounding down to the previous whole number), or a string literal (providing the string represents a whole number)
float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer)
str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals

Reference: https://www.w3schools.com/python/python_casting.asp
What your code should look like:
import csv
def csv_to_kvs(string):
  with open(string) as f:
    my_file = csv.reader(f)
    my_dict = {}
    for row in my_file:
      my_dict[row[0]] = float(row[2])
    return my_dict


text:
Q: jQuery $.post() + IE8

<form action="" method="post" id="InqRespForm" name=InqRespForm>
Reply to the above Inquiry :

<textarea rows="7" name="Detail" id="InquiryResponse" cols="60" colspan=2>Type your     response in this space ...</textarea>

<input id="SendReply" name="Send" type="submit" value="Send Response" alt="Reply to  Inquiry" />

</form>

On form submit, I send an email out. Which works on FF, Chrome etc. But I've gone bald trying to make this work in IE8. I will buy you beer if you can point me to a solution.

A: I figured it out. Im going to post the solution here in case it helps someone in future. The problem was with the url i was posting to. My url was a parameterised url and I was using a wrong syntax/format all along. The IE and non IE separation is not really needed. The answer lies in extracting the various components of the current url and pass it in $.post via the "data" array. Thanks for your inputs. Working code below:

A: Why are you doing this: jQuery.browser.msie ????
There is almost never a reason to detect the browser! And I can see absolutely nothing in your code that requires knowing what the browser is.

A: Put this line within your HTML just after the  tag starts
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

It will work for IE8+

A: $.post( "", ... ) might have caused the problem. I found that it works in most browsers except IE.
Rather use $.post(window.location, ... ) to post to the same page.


text:
Q: Python-How to prevent a variable from reseting in a while-loop So I just started experimenting with python and I've learned a few commands with which Im trying to create a hangman-game. If the player finds a letter for the 1st time the program works fine and displays the missing letters as '_', showing the letter in the correct spot. However if the player finds a 2nd letter, the word will just reset and show up just the 2nd letter in its potisionand the missing letters as ' _'. Is there a command that can help me deal with this. Ive used this code for that section
word = input('Give word:\n')
word = word[0].upper()+word[1:]
wordC =word[1:-1]
wordUkn = ' _ '*len(wordC)

while '_' in wordUkn and mist < 3 :
    ans=input('Give a letter:\n')
    if ans in wordC :
          pos=wordC.index(ans)
          wordUkn=(' _ '*pos)+str(ans)+' _ '*(len(wordC)-(pos+1))
          print(word[0]+wordUkn+word[-1])

mist = mistakes
ans=answer
Also If Im new here so If there is anything I should be doing differently about posting questions please inform me.
I would also aprreciate it,If anyone could tell me how to deal with the case that the world contains the same letter 2 times.
Thanks for your time. :)

A: I understand you want to fill up wordUkn variable, as the user finds each letter.
In order to replace a character in string in Python there is a simpler way:
You can change the string to a list, change the character in the list index you already have and then transform the list back to a string, a small example is here:
pos = 5
s = 'good dye'
li = list(s)
li[pos] = 'b'
s = "".join(li)

If you replace 'b' with the current found letter you are done!


text:
Q: Cannot create permanant environment variable in Ubuntu I'm trying to create a permanent environment variable on Ubuntu.
I tried the following:
export SASS_LIBSASS_PATH=/usr/local/lib/libsass

When I opened a new terminal and used 'printenv', I found the variable disappeared!
I also tried to make it work by appending:
SASS_LIBSASS_PATH="/usr/local/lib/libsass"

to the end of the file in /etc/environment, and then used:
source /etc/enviroment

That did not work!
UPDATE:
I then tried editing my ~/.profile file:
SASS_LIBSASS_PATH="/usr/local/lib/libsass"

that did not work.
I then tried instead appending the following at the end of ~/.profile file:
export SASS_LIBSASS_PATH="/usr/local/lib/libsass"

that too did not work!
How can I make a permanent system variable?

A: export only sets the environment variable in your current shell session and any child processes started by that shell session. It is certainly not "permanent". The only way to set an environment variable for future shell sessions is to add the export command to a shell start-up file. Your best bet is probably to put it in ~/.profile (unless the file ~/.bash_profile exists).


text:
Q: Why can my local docker image see one external host and not the other?
*

*I am running a docker container on my PC as follows: docker run -it my_container /bin/bash.

*Outside of docker, my PC has network access to remote hosts machine1.sydney.network and machine2.sydney.network.

*When I run a container of my image, I can access (ping) machine1.sydney.network, but NOT machine2.sydney.network from within the container.

*Both machine1.sydney.network and machine2.sydney.network are on the same subnet

*Our network engineers have confirmed firewall settings are good for both machine1.sydney.network and machine2.sydney.network

*in response to a suggestion that I might need include a script to modify ip routing, the network team say "you should just be able to use the standard routing the gateway here will direct traffic as required"

I am new to Docker so perhaps am missing an obvious config.
Can anyone suggest what might be the issue here?
ie: is there something I can add to my "docker run" script to make both remote machines visible from within my docker container?
Cheers,
Chris

NSLOOKUP and DIG information from inside the container included below.
Note: I am now in a different office (on a different subnet) in our organisation  to when I first posted the original query.  In this office, my docker container cannot acccess either of machine1 or machine2.  However I can still access them when outside of my docker container.
MACHINE 1
=========

root@cb4b66d8ad7e:/# nslookup machine1.sydney.network
Server:         127.0.0.11
Address:        127.0.0.11#53

Non-authoritative answer:
Name:   machine1.sydney.network
Address: 172.16.32.20

----------------------------------

root@cb4b66d8ad7e:/# dig machine1.sydney.network
; <<>> DiG 9.10.3-P4-Ubuntu <<>> machine1.sydney.network
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 12578
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4000
;; QUESTION SECTION:
;machine1.sydney.network.     IN      A

;; ANSWER SECTION:
machine1.sydney.network. 1916 IN      A       172.16.32.20

;; Query time: 12 msec
;; SERVER: 127.0.0.11#53(127.0.0.11)
;; WHEN: Mon Apr 30 23:53:05 UTC 2018
;; MSG SIZE  rcvd: 70

MACHINE 2
=========

root@cb4b66d8ad7e:/# nslookup machine2.sydney.network
Server:         127.0.0.11
Address:        127.0.0.11#53

Non-authoritative answer:
Name:   machine2.sydney.network
Address: 172.17.32.115

----------------------------------

root@cb4b66d8ad7e:/# dig machine2.sydney.network
; <<>> DiG 9.10.3-P4-Ubuntu <<>> machine2.sydney.network
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 42566
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4000
;; QUESTION SECTION:
;machine2.sydney.network.     IN      A

;; ANSWER SECTION:
machine2.sydney.network. 60   IN      A       172.17.32.115

;; Query time: 11 msec
;; SERVER: 127.0.0.11#53(127.0.0.11)
;; WHEN: Mon Apr 30 23:48:45 UTC 2018
;; MSG SIZE  rcvd: 70


text:
Q: GDB prints incorrect parameter value in kernel I'm debugging Linux kernel with gdb, the breakpoint works fine.
But when gdb breaks, the passed in parameter value were incorrect.
Breakpoint 4, XXX (a=0xb008, b=1, c=1, d=0x0, e=0) at XX.c:YY

Yes, all these values are wrong. I added a few printk in the XXX kernel function, and confirmed it was wrong. (It wasn't a data format problem)
I have tested with gcc-4.6 and gcc-4.9 same result. I didn't modify CFLAGS_KERNEL either.
Perhaps a gdb problem? I'm using version 7.7.1
P.S I have also tried with multiple kernel source code, 3.12.8, 3.4.0 2.6.32 etc. No change.

A: There isn't enough information here to know what the problem is.  It might be a gdb problem, though from the description I would say it is more likely a debug info issue.  But there is no easy way to tell, one must dive into the debug info, the assembly emitted by the compiler, and the gdb source code in order to decide where the bug lies.


text:
Q: How to display day label if there is only one data point in flot? Following is my xaxis parameter for flot -
xaxis: {
    mode : "time",
    minTickSize: [1, "day"],
    color : "#999"
}

What I want is that day labels be visible on the x-axis. It works when I have more than one data point as in here -

But it doesn't work when I've only one data point.

Is there anyway to render the day label when there is only one data point? I tried using
"1 hour" as the minimum tick size and it clutters the timeline.

A: Here is an example of a single day I created. I don't think there should be any issue.


text:
Q: Both C and D drives behave as non-persistent, even though i have set C drive as "non-persistent" and D drive as "Persistent" Is it the disk, which behaves as persistent and non persistent or the VM?
I have a VM on my vsphere with two disk drives ( C and D ), Both Drives are marked as THIN PROVISIONED. this machine is being used as a CI/CV node. C drive has the OS installed on it and D drive has jenkins and gitcode.
i want to make c drive as non persistent , so that the changes happening to this drive does not stick in my VM after i restart the machine. at the same time i want my D drive to be Persistent, so that the logs and other screenshots taken should remain in the D drive.
I made the c drive as non persistent and D drive as persistent disk in Vsphere VM edit option But when i use this machine now.. Both C drive as well as D drive behave as NON Persistent, Datafiles created during execution are getting deleted from D drive as well.
Drive D

Drive C

A: This is a slightly unusual use-case for this but yes it can be done.
Just set the underlying disk for your C: drive to be 'Independent Non-Persistent Mode' and the underlying disk for your D: drive to be Persistent and I think you'll get what you want. Good luck.


text:
Q: Set python version on MacOS Big Sur does someone had situation when "python --version" says "Python 2.7.16", but installed version is 3.7
Command "pyenv versions" says "* 3.7.11 (set by /Users/dima/.python-version)"
My applications see also just version "2.7.16".
Does someone know how to set default Python version to installed "3.7.11"? Simply set entire system default python to 3.7.
Thanks a lot!

A: Python is python 2, for legacy applications. To use python 3, you must use the command python3. So python3 —-version should be what you are looking for.
Edit: I missed that you're using pyenv. Maybe it's a bug with pyenv, but python3 should still bring python 3.

A: Make sure your Python installation appears in your PATH before the system Python.
Edit ~/.bash_profile or the profile file for the shell you're using and add
export PATH=/path/to/your/python/bin/folder:$PATH

with the path to the folder containing your python.


text:
Q: How to make mobs spawn where the player is at random intervals? Hello I'm trying to make a plugin/mod where mobs(1 - 31) randomly spawn at the players coords, but I'm very new to coding in Minecraft so any help will be appreciated.
I'm playing on 1.18

A: You can use Psuedo Random, it is not entirely random but it's fast enough to be "random".
To do Pseudo Random you can add a dummy scoreboard to yourself
/scoreboard objectives add psuedoRandom dummy

Then you can create a repeating command block that increments it or changes it to a random one
/scoreboard players add @s psuedoRandom 1

Then add a repeating command block that resets it everytime it goes to the max limit
/execute if score @s pseudoRandom matches 100.. run scoreboard players reset psuedoRandom

Then you can add a repeating command block that checks if the psuedo random is at a specific number then summon depending on what mob you choose
/execute if score @s pseudoRandom matches 69 run summon tnt ~ ~1 ~


text:
Q: Ruby on Rails - destroy_all on 70k+ records with 450k associations From my understanding, destroy_all destroy all records, their associations, and does callbacks. However, it instantiates all of the records, which in my case is taking hours. It's going through about 70k records in one table, along with about 450k associated records in another table. It also just chews up through all the 16GB of memory trying to do this as well.
I'm trying to figure out the best way to handle this so that it's scalable across large number of rows.
The downfall that I see of delete_all is that it doesn't go through dependent: :destroy and destroy dependent associations. In this case, would it be best for me to just simply hard code the dependent deletes? So if Book has_many :pages, dependent: :destroy, would it be better for me to go through Pages.where(book_id: xyz).delete_all and then call Book.delete, or is there another best way for me to use delete_all to also catch its associated records?

A: Alter the database and set on delete cascade on the relevant foreign keys. Then when a record is deleted, all its associations will also be deleted. Then you can use the much more efficient SomeClass.delete_all.
Rails doesn't let you alter an existing foreign key. You need to remove it and add it back. For example, let's say you have...
class Building
  has_many :rooms, dependent: :destroy
end

class Room
  belongs_to :building
end

Then you'd write a migration like...
change_table :rooms do |t|
  t.remove_foreign_key :buildings
  t.foreign_key :buildings, on_delete: :cascade
end

This doesn't drop the column, it just drops and re-adds the foreign key constraint.
Then you can Building.where(...).delete_all. This will issue a single delete from buildings where ... statement. The database will efficiently delete all associated rooms as well.


text:
Q: Remove halo around image before segmentation (preprocessing) I'm trying to perform image segmentation using Morphological Snakes, however the input images contain something like a halo that it is messing with the output. Here you can see an example image and its corresponding segmentation should look like this. As it can be seen in the first image the object of interest is the one in the center but around it there is, what I call, a gray halo and since the difference among the pixels is not much I haven't found a way to perform the segmentation.
I've tried preprocessing methods such as morphological operations and gaussian filter, however I didn't obtain the expected results. I've also tryed to segmentate the image using adaptative threshold and otsu, but didn't work either because, as I said before, the difference among the pixels is not much (that's why I moved to morphological snakes that work better but not enough for my case).
I want to know if there's any preprocessing method that could help in my case, maybe I haven't found the correct combination of them. I need to remove or clean the halo, or to highlight the the object in the center.
Thanks in advance to any who could help me.


text:
Q: Sending an email alert when query rows are more than 50K We have a apex job in which we are fetching some records(SOQL) in execute method based on the record values retured by start method. But, there are more than 50000 records corresponding to one particular value in an object. My requirement is to send an email alert from batch apex if records returned by SOQL are more than 50K. We know that limit exceptions cannot be handled through try/catch blocks in apex.
Is there any workaround to accomplish this? Please find below mentioned code:
global class BatchUpdateOptOutPermissions implements Database.Batchable<sObject>
    {

       /* Start - Variables */
       /* End - Variables */

       /* Start - Constructor */
       global BatchUpdateOptOutPermissions()
       {
            //Do Nothing
       }
       /* End - Constructor */

       global Database.QueryLocator start(Database.BatchableContext BC)
       {
          DateTime dtLast24Hours = System.now().addHours(-24);
          return Database.getQueryLocator('SELECT Id, Channel_Value__c FROM Brand_Permission__c WHERE Permission_Value__c = \'OUT\' AND LastModifiedDate >: dtLast24Hours');
       }

       global void execute(Database.BatchableContext BC, List<sObject> scope)
       {
            List<Brand_Permission__c> lstBP = (List<Brand_Permission__c>)scope;// Casting the scope to list of Brand_Permission__c.
            List<Brand_Permission__c> lstBPToUpdate = new List<Brand_Permission__c>();// List to hold the existing channel permission records which needs to updated.
            Set<String> setPermissionValues = new Set<String>();// Set to hold the channel permission values corresponding to those permissions that are passed from the batch.

            //Iterating to hold the channel values
            for(Brand_Permission__c objBP : lstBP)
            {
                if(String.isNotEmpty(objBP.Channel_Value__c))
                    setPermissionValues.add(objBP.Channel_Value__c);
            }

            if(!setPermissionValues.isEmpty())
            {
                //Fetching the existing permissions which are not opted out in last 24 hours.
                for(Brand_Permission__c objBP : [SELECT ID FROM Brand_Permission__c WHERE Permission_Value__c != 'OUT' AND Channel_Value__c IN : setPermissionValues])
                {
                    lstBPToUpdate.add(new Brand_Permission__c(Id = objBP.Id, Source_Time_Stamp__c = System.now(), Effective_Date__c = System.now(), Permission_Value__c = 'OUT', Source_Application__c = 'SharedOptOutSource'));
                }
            }

           Database.update(lstBPToUpdate,false);
       }

       global void finish(Database.BatchableContext BC)
       {
            //Do Nothing
       }
    }


text:
Q: Query Folder name with role associated to it I'm trying to get the role names associated with the folder but I'm not getting hold of it. Here is what I have tried:
Select Id, Name, isActive, Folder.Name from EmailTemplate
where Folder.Name = 'test'

I have tried adding UserRole.Name or Profile.Name but none of this works and if this is not possible is there a way to retrieve through metadata api using workbench?
I'm trying to get the selected values that users have selected in Shared To o the right hand box in the image.
Here is the image as a ref:


text:
Q: Mono.Cecil: Log method's entry and exit point I am writing a program that can change the IL of target program to log method's entry and exit point.
I am using Mono.Cecil
I want this program to insert log statements in the beginning and end of the target method.
I tried a basic program as sample.
public class Target
{
    // My target method.
    public void Run()
    {
        Console.WriteLine("Run method body");
    }

    // This is my log method, which i want to call in begining of Run() method.
    public void LogEntry()
    {
        System.Console.WriteLine("******Entered in RUN method.***********");
    }
}

Source program.
public class Sample
{
    private readonly string _targetFileName;
    private readonly ModuleDefinition _module;

    public ModuleDefinition TargetModule { get { return _module; } }

    public Sample(string targetFileName)
    {
        _targetFileName = targetFileName;

        // Read the module with default parameters
        _module = ModuleDefinition.ReadModule(_targetFileName);
    }

    public void Run()
    {

        // Retrive the target class.
        var targetType = _module.Types.Single(t => t.Name == "Target");

        // Retrieve the target method.
        var runMethod = targetType.Methods.Single(m => m.Name == "Run");

        // Get a ILProcessor for the Run method
        var processor = runMethod.Body.GetILProcessor();

        // get log entry method ref to create instruction
        var logEntryMethodReference = targetType.Methods.Single(m => m.Name == "LogEntry");

        var newInstruction = processor.Create(OpCodes.Call, logEntryMethodReference);

        var firstInstruction = runMethod.Body.Instructions[0];

        processor.InsertBefore(firstInstruction, newInstruction);

        // Write the module with default parameters
        _module.Write(_targetFileName);
    }
}

When I run my source program to change the IL of target program,
I am getting following error message.
System.InvalidProgramException: Common Language Runtime detected an invalid program.
   at CecilDemoTarget.Target.Run()
   at CecilDemoTarget.Program.Main(String[] args).

A: I believe the issue is that you're calling instance method without specifying this.
To fix this, you have two choices:

*

*Make LogEntry static.

*Load this on the evaluation stack by adding the ldarg.0 instruction before the call.

To verify that what I'm saying is correct and to diagnose similar issues in the future, you can run Peverify on the modified assembly.


text:
Q: Perl CPAN: Can't install module dependencies - Could not find a version X or above Whenever I try installing a perl module on my system, it fails to install the dependencies. I had this working before, I'm not sure why it's not working on my fresh setup.
For example, I try to install Catalyst-Runtime-5.80032 (I downloaded from http://search.cpan.org/CPAN/authors/id/B/BO/BOBTFISH/Catalyst-Runtime-5.80032.tar.gz ).
Inside the directory, I type
perl Makefile.PL.
That comes back with
Warning: prerequisite B::Hooks::EndOfScope 0.08 not found.
Warning: prerequisite CGI::Simple::Cookie 1.109 not found.
Warning: prerequisite Class::C3::Adopt::NEXT 0.07 not found.
Warning: prerequisite Class::Data::Inheritable 0 not found.

along with other modules not found. Then I type make and all of the modules come back with errors.
*** Installing dependencies...
*** Installing Class::Data::Inheritable...
*** Could not find a version 0 or above for Class::Data::Inheritable; skipping.
*** Installing Test::Exception...
*** Could not find a version 0 or above for Test::Exception; skipping.
*** Installing namespace::autoclean...
*** Could not find a version 0.09 or above for namespace::autoclean; skipping.
*** Installing namespace::clean...
*** Could not find a version 0.13 or above for namespace::clean; skipping.
*** Installing B::Hooks::EndOfScope...
*** Could not find a version 0.08 or above for B::Hooks::EndOfScope; skipping.

and a whole bunch of others like that.
Any ideas why this is failing? I am behind a company firewall, but I have set up the http_proxy, ftp_proxy, and https_proxy environment variables in bash. I'm able to curl and wget from all these protocols.
Thanks.

A: Instead of manual building, which doesn't download dependencies (you have to do that manually to), why not use the cpan utility?
# cpan Catalyst::Runtime

That will download the package, it's dependencies, do all the compilation, and even install it all for you.


text:
Q: C++ Array Error: Access violation reading location 0xC0000005 For some reason, when I try to print out an array of strings it always has an error:

Unhandled exception at 0x0F767EA6 (msvcp120d.dll) in Project1.exe: 0xC0000005: Access violation reading location 0x73F6B6FF.

Here is the code that generates the error:
#include <iostream>
#include <string>

using namespace std;

int main()
{
    const int numItems = 6;
    string itemNames[numItems] = { "Boots", "Swords", "Helmets", "Kittens", "Poleaxes", "Leggings" };

    cout << "*** Welcome to the item shop! ***\n";

    for (int i = 0; i < numItems; i++)
    {
        cout << itemNames[numItems] << endl;
    }

    cout << "**********\n\n";
    cout << "What would you like to buy?\n";

    system("PAUSE");
    return 0;
}

I am using Visual Studio 2013, by the way.

A: for (int i = 0; i < numItems; i++)
{
    cout << itemNames[numItems] << endl;
}

You may want cout << itemNames[i] << endl;. Otherwise itemNames[numItems] is always out-of-bound.

A: The value of numItems is 6. You are trying to access itemNames[6] with itemNames[numItems] in line

cout << itemNames[numItems] << endl;

which doesn't exist. And thus you get an access violation error.


text:
Q: Are Spring Converters for the web layer (problem with @WebMvcTest)? I'm writing a test which is annotated with @WebMvcTest. Apart from the specified controller, this also loads all custom Converters.
The problem is that the application for which I'm writing the test uses these converters in the service layer, and, even worse, that these converters (unfortunately) have dependencies to the database layer and to many other beans. Therefore, starting the WebMvcTest fails due to unfulfilled dependencies of the converters. My workaround is to put all converters into the @MockBean annotation.
This makes me wonder what these converters are exactly made for. If they are designed for the web layer to implicitely convert controller arguments, it would be fine to load them in a WebMvcTest, but then they should not have any other dependencies.
But if they don't have any arguments, what would be the advantage of them to use over simple Java method calls? Why would one need beans for them?


text:
Q: How can i produce multi point linear interpolation? I have a linear interpolation methods. This is calculate interpolate value when (x1,y1) (x2,y2) and x0 known. it is calculate y0 value. But i need the do that when multi point known.
I am not talking about Bilinear or Trilinear interpolation.

A: For multi point interpolation there are 3 options:

*

*piecewise linear interpolation
choose 2 closest points to your known coordinate if you use parameter then select the points containing parameter range and change the parameter range/scale to interpolation range (usually <0,1>) and interpolate as linear interpolation.
example of linear DDA on integers and more is in here:

*

*Precise subpixel line drawing algorithm (rasterization algorithm)

*polynomial interpolation
this is not linear !!! Take all known points, compute n-th degree polynomial from it (by Lagrange polynomial or by edge conditions or by regression/curve fitting or by whatever else) and compute the point from parameter as function of this polynomial. Usually you have one polynomial per axis the more the points and or degree of polynomial the less stable the result (oscillations).

*piecewise polynomial interpolation
It is combination of #1,#2 (n is low to avoid oscillations). You need to call the point sequence properly to manage continuity between segments, the edge conditions must take into account previous and next segment...

*

*here Piecewise interpolation cubic example

*here How to construct own interpolation 3th degree polynomial

*here How to construct own interpolation 4th degree polynomial

*here point call sequence and BEZIER cubic as interpolation cubic
[notes]
SPLINE,BEZIER,... are approximation curves not interpolation (they do not necessarily cross the control points). There is a way how to convert in-between different types of curves by recomputation of control points. For example see this:

*

*Interpolation cubic vs. Bezier cubic


text:
Q: How do you make a button in android that opens a new activity and this activity is not just a default activity its a custom one I am trying a make notepad app so every time a new note is opened the layout will be the same. also, the number of activity(new note) should not be defined as many possible

A: If the activity is always the same, you should probably create an adapter that allows you to change the texts and images of your activity without the need to create several activities.


text:
Q: How would I would I turn this for loop into a forEach loop? Hello All^^  I apologize if this has been asked previously (though I was unable to find a previously posted, similar question myself...).  Also, let me apologize for the simplicity of this question, beforehand.
This is a simple browser game similar to wheel of fortune.  A random quote is generated via js script which the user is supposed to guess via the onscreen keyboard keys.  However, I am unable to compare the user click to that of the quote text content, at current; it is returning "undefined".
I understand (after reading some of the questions on here) that the reason why document.querySelectorAll('.letters') is returning "undefined" is because it is an array, and likely requires a forEach loop, rather than a for loop.
However, is there a way to augment this for loop to compare the button click event target value to that of the document.querySelectorAll('.letters') array value?  If not, how would I write this as a for each loop?  I have tried to re-write it as such for the last hour or so with no luck : /
Is it not possible to include this in a function with an event listener?
I do appreciate your time.
problem code:
qwerty.addEventListener('click', function (event) {
  if ( event.target.tagName === "BUTTON" ) {
       event.target.className = "chosen";
      for( let i = 0; i < letters.length; i++ ) {
          if( event.target.innerText === letters.textContent.toLowerCase() ) {
              letters.className = 'show';
              matched += 1;
          }
       }
    }
 });

full code:
//Keyboard and game element variables

const qwerty = document.getElementById('qwerty');
const phrase = document.getElementById('phrase');
const keyLetters = document.querySelectorAll('.keyrow button').innerText;

//hidden letters of phrase
const letters = document.querySelectorAll('.letters');

//Game score

const missed = 0;
const matched = 0;

//Start button (hides start screen overlay and begins game)
const startGame = document.querySelector('.btn_reset');

startGame.addEventListener('click', function () {
    document.querySelector('.start').style.display = 'none';
});

//Game quotes

const quotes = [
["René Descartes"        , "I think therefore I am"],
["Friedrich Nietzsche"   , "What does not kill me makes me stronger"],
["Socrates"              , "The unexamined life is not worth living"],
["Sir Winston Churchill" , "If you are going through hell keep going"],
["Winnie the Pooh"       , "Doing nothing often leads to the very best of something"],
["Aldous Huxley"         , "Never have so many been manipulated so much by so few"],
["Albert Einstein"       , "The most beautiful experience we can have is the mysterious"]
];

//Generate random quote

const getRandomPhraseAsArray = () => {
    //create random number between 1 - 7 for quote selection
    let randNum = Math.floor( Math.random() * (quotes.length) );
    //retrieve object value (quote) with random number
    let randQuote = quotes[randNum][1];
    //select the ul .phrase div
    const ul = document.querySelector('#phrase ul');
    //Append to li element created in const li
    randQuote = randQuote.toString().split("");
    //iterate though each string value in randQuote, create an li element
    //then set the innerText of the li to the string value

    for( let i = 0; i < randQuote.length; i++ ) {
        const li = document.createElement("li");
        ul.appendChild(li);
        li.innerText = randQuote[i];
            if ( randQuote[i] != " " ) {
                li.className = "letter";
            } else {
                li.className = "space";
            }
        };
};

getRandomPhraseAsArray();

//keypress function

qwerty.addEventListener('click', function (event) {
    if ( event.target.tagName === "BUTTON" ) {
         event.target.className = "chosen";
        for( let i = 0; i < letters.length; i++ ) {
             if( event.target.innerText === letters.textContent.toLowerCase() ) {
                 letters.className = 'show';
                 matched += 1;
             }
        }
    }
});

A: Fixed.  StackSlave was correct.  A for/of loop was what was required to iterate through the array.
qwerty.addEventListener('click', function (event) {
if ( event.target.tagName === "BUTTON" ) {
     event.target.className = "chosen";
    for( const letter of letters ) {
         if( event.target.innerText === letter.textContent.toLowerCase() ) {
             letter.className = 'show';
             matched += 1;
         }
    }
}

});


text:
Q: Cygwin usr/bin/perl: bad interpreter : Permission denied Hello I'm trying to run a perl script on a Windows 64 bit. I'm getting the error like this :

/usr/bin/perl : bad interpreter : Permission denied

I have my perl script on my windows 64 bit C:\test\perlscripts\testperl.pl.

A: You probably saved the Perl script with DOS style line endings. The shell is looking for a file called /usr/bin/perl<CR>.
Save your files with Unix-style line endings. My .vimrc which I use with my natively compiled vim and gvim has:
set fileformat=unix
set fileformats=unix,dos

Check your editor's settings for the appropriate options.
To fix line endings in a particular file, use $ dos2unix filename.

A: You may not install Perl in default cygwin64 package. Please ensure that you have Perl at /usr/bin/perl.exe.
If it is not there, run setup-x86_64.exe again and select Perl interpreter.


text:
Q: Proving that Set O is the smallest set satisfying these properties $O_n$ is defined as: $O_n = {1}$; $O_{n+1} = O_n \cup \{2n+1\}$. Let $O = \cup_n O_n $
Prove that $O$ is the smallest set satisfying properties O1 and O2.
O1: $1 \in O$
O2: if $x \in O$ then $x+2 \in O$

Let S be a set which satisfies properties, O1 and O2.
Now Let $y \in O$.
Then, $y \in \cup_n O_n $ and $y$ some odd integer number.
Since we know that $S$ is a set of all odd nonnegative integers by its properties (i.e. if 1 is in $S$, then 3 is, and 5, so on), it follows that $y \in S$ and this can be shown for all $y \in O$.
Thus, $O \subseteq S$ and $O$ is the smallest set satisfying properties O1 and O2.
Is this fine?

A: To be very rigorous: let $S$ satisfy O1 and O2. Then, by induction, we see that $S$ must contain all the odd natural numbers. Let $y \in \cup_n O_n$. Then there exists some $n \in \mathbb{N}$ such that $$y \in O_n = O_{n-1} \cup \{2n - 1\} = O_{n-2} \cup \{ 2n - 3 \} \cup \{2n - 1\} = \cdots = \cup_{i=1}^n \{2n - (2i-1)\}.$$
(To be very rigorous about the dots, one may use induction again.) Thus $y = 2n - (2i - 1) = 2(n-i) + 1$ for some $1 \leq i \leq n$, i.e., $y$ is some odd natural number. Hence $y \in S$ as required.


text:
Q: PHP multi-dimentional array sort I have an array that I would like to sort, that should be easy, except that I build my array in a strange manners (for different reasons) that make it hard to sort. Here is my array :
$arrayCEO =array(
'companyName' => array(0=>'name1', 1=>'name2'),
'link' => array (0=>'link1', 1=>'link2'),
'isin' => array (0=>'isin1', 1=>'isin2'),
'mktCap' => array (0=>'mktCap1', 1=>'mktCap2'),
'nbShares' => array (0=>'nbShares1', 1=>'nbShares2'),
'amount' => array (0=>'10', 1=>'20'));

Is that possible to sort by "amount" without breaking the order in the others arrays?
Do you recommend me to rewrite my code to build an array like this one :
$arrayCEO =array(
0 => array ('name' => 'name1', 'link' => 'link1', 'isin' => 'isin1', …),
1 => array ('name' => 'name2', 'link' => 'link2', 'isin' => 'isin2', …));
2 => ...

I know this one would be simple to sort but it's a lot of work to rewrite my piece of code.
Thanks,
Dorian

A: It makes a lot more sense to rewrite your arrays to store in the more conventional format you described - (It's always better to organise things in decreasing magnitude 'Root > rows > fields' instead of 'Root > fields > rows')
If you didn't want to change you could probably use the usort function and roll your own sorting method, but it might be a bit of work to make it play nicely.


text:
Q: Need to delete old SKU# and enter new SKU # onto a master sheet This project keeps throwing new and exciting things that I am having a good deal of trouble with.
I am hoping that there is an easy solution but I am starting to suspect it may be a macro problem.
What I have is...a master list of products, 10,000 of them.  It is now end of season and we are moving a range of products to a discontinued section.
So what I need to know is how can I delete all the SKU's I need to...and then as an added bonus feature...add the NEW SKU's for this season into the master list.
What I am hoping to do is create something that when we have to do this again in six months...we dont have to enter the data individually and just add a discontinued list...and a new list and it will auto update the main list.
I will have to add SKUS and the data they contain and my only knowledge of this is using Vlookup.
Thanks.

A: There are a lot of ways to tackle this, but you haven't given enough info to get a specific answer.
For example, if you have that list of discontinued product numbers somewhere, you could easily run a vlookup formula against that data source to the master data source.  Then, just sort out the stuff you want and delete it or move it or whatever.
It also begs the question of why you have a 'discontinued' section.  I loathe 'sections' in a database.  If it's a real DB table, there shouldn't be any breaks anywhere....you'd deal with 'discontinued' versus 'active' with an additional field (column) and mark things as such there.
If the table and the data is organized well, you can easily do these tasks you are talkign about.


text:
Q: AsyncLocal & CallContext - How can I achieve both async *and* remoting logical context guarantees? I'm attempting to develop a library that implements the loosely-defined Ambient Context pattern. I need to consider both a high-degree of parallelism and remoting (.NET Framework 4.6.2). It seems I have 2 options available: AsyncLocal<T> and CallContext. I don't believe either satisfies both of those considerations.
Consider the following sample that demonstrates the remoting half of my issue:
class Program
{
    static string hello = "Hello from '{0}'! \n\tAsyncID: {1} \n\tContextID: {2} ";

    static void Main(string[] args)
    {
        OperationManager.CallContextOperationID = Guid.NewGuid();
        OperationManager.AsyncLocalOperationID = Guid.NewGuid();

        AppDomain other = AppDomain.CreateDomain("remote");
        SayHello();
        other.DoCallBack(SayHello);

        Console.ReadKey();
    }

    private static void SayHello()
    {
        string statement = string.Format(hello, AppDomain.CurrentDomain.FriendlyName,
            OperationManager.AsyncLocalOperationID,
            OperationManager.CallContextOperationID);
        Console.WriteLine(statement);
    }
}

internal class OperationManager
{
    private static string _slotName = "HelloWorld";
    private static readonly AsyncLocal<Guid> _operationID = new AsyncLocal<Guid>();

    public static Guid AsyncLocalOperationID
    {
        get => _operationID.Value;
        set => _operationID.Value = value;
    }

    public static Guid CallContextOperationID
    {
        get => (Guid)CallContext.LogicalGetData(_slotName);
        set => CallContext.LogicalSetData(_slotName, value);
    }
}

This class creates two GUIDs, storing one in an async local and the other in the logical call context. Then it spins up a new AppDomain, and prints the values from the current and remote domain.
Sample output from this program shows
Hello from 'ConsoleApp1.exe'!
    AsyncID: 4c9e7c3a-fef8-4948-b0f0-896abe7dc2dd
    ContextID: 4b479195-6fe8-43ae-a753-2fb3ccc57530
Hello from 'remote'!
    AsyncID: 00000000-0000-0000-0000-000000000000
    ContextID: 4b479195-6fe8-43ae-a753-2fb3ccc57530

And we can see that the CallContext made it across the remoting boundary, while the AsyncLocal did not (not that surprising).
The problem is that I don't believe I can leverage the CallContext in a "simple parallelism" environment (as laid out by Stephen Cleary in this post), due to the way that the CallContext is shared across threads. Stephen has an excellent pseudo-code example in the linked solution that I won't duplicate here. That example outlines the async portion of my issue.
My two options then become
AsyncLocal<T>: Works in a "simple parallelism" environment, but fails across remoting boundaries.
CallContext: Works across remoting boundaries, but fails in a "simple parallelism" environment.

Is there a third option here I am missing?


text:
Q: IRR on two raters' integer scores I am writing with questions about a study I am helping with:
Two "raters" will score athletes subjectively from 0 to 3 (3>2>1>0) on each of 10 skill performances.  Scores will be summed to a maximum of 30, and the total bracketed into approximately three categories for comparison with regard to knee injury incidence.  Reliability/agreement between the two raters' scores must be determined.
How should the inter-rater reliability testing be set up?
  Kappa and/or Kendall?
  Same data for individual skills and total score?
How much data is needed for this irr testing?
The lead investigator anticipates highly consistent scores between raters and plans to divide their testing of subjects accordingly, for the main study.


text:
Q: How to return custom JSON output in Django REST Framework I am trying to return custom json with the following structure
[ {
'yesterday': [{'teams': "team a -team b", 'start_time': "0: 11", 'pick': "X2", 'score': "1:4", 'odds': 1.25, 'won_or_lost': "won", 'date': "2019-01-8"}],

'today': [{'teams': "team a -team b", 'start_time': "0: 11", 'pick': "X2", 'score': "1:4", 'odds': 1.25, 'won_or_lost': "won", 'date': "2019-01-8"}],

'tomorrow': [{'teams': "team a -team b", 'start_time': "0: 11", 'pick': "X2", 'score': "1:4", 'odds': 1.25, 'won_or_lost': "won", 'date': "2019-01-8"}]
}]

The following is my code:
serializer.py
class GamesSerializer(serializers.Serializer):
    class Meta:
        model = AllGames
        fields = ('teams', 'start_time', 'pick',
                  'score', 'odds', 'won_or_lost', 'date')

class GamesViewSet(viewsets.ModelViewSet):
    today_date = date_picker

    yesterday = AllGames.objects.filter(
        date=today_date(-1)).order_by('start_time', 'teams')
    today = AllGames.objects.filter(
        date=today_date(0)).order_by('start_time', 'teams')
    tomorrow = AllGames.objects.filter(
        date=today_date(1)).order_by('start_time', 'teams')

    queryset = [yesterday, today, tomorrow]
    serializer_class = GamesSerializer

Current Output
[
    {},
    {},
    {}
]

How can I modify my GamesSerializer to return the custom output as shown above.

A: You can convert your response class from DRF ModelViewSet to ViewSet.
Then you can further parse your data before returning response, by overriding retrieve
As mentioned here: https://www.django-rest-framework.org/api-guide/viewsets/#example

A: For anyone trying to find the answer for this I used Viewset instead of ModelViewSet as suggested by @jay-vasant and then overrode list method above to customize the output like I wanted.
This is my GamesViewSet after update.
class GamesViewSet(viewsets.ViewSet):
def list(self, request):
    today_date = date_picker

    yesterday = AllGames.objects.filter(
        date=today_date(-1)).order_by('start_time', 'teams')
    today = AllGames.objects.filter(
        date=today_date(0)).order_by('start_time', 'teams')
    tomorrow = AllGames.objects.filter(
        date=today_date(1)).order_by('start_time', 'teams')

    queryset = [yesterday, today, tomorrow]
    games = []
    for day in queryset:
        serializer = GamesSerializer(day, many=True)
        games.append(serializer.data)
    return Response(games)

Output I get there after.
[
    [{'teams': "team a -team b", 'start_time': "0: 11", 'pick': "X2", 'score': "1:4", 'odds': 1.25, 'won_or_lost': "won", 'date': "2019-01-8"}],

    [{'teams': "team a -team b", 'start_time': "0: 11", 'pick': "X2", 'score': "1:4", 'odds': 1.25, 'won_or_lost': "won", 'date': "2019-01-8"}],
    [{'teams': "team a -team b", 'start_time': "0: 11", 'pick': "X2",'score': "1:4", 'odds': 1.25, 'won_or_lost': "won", 'date': "2019-01-8"}]
 ]

Which is now close to what I wanted.