问:
Python Not Running Shell Commands After Reboot Using Launch Agent
So, I'm starting a Python (2.7) script via a launch agent, on macOS 10.13.  The script runs, and during execution, it triggers a restart of the computer.  When the computer turns back on and logs in, the launch agent runs the script again.  The script reads the logs, and does a switch:case to pick up where it left off.

The problem is, after the restart, the python script is unable to execute some shell commands. ls -l works fine.  However, when I try to run something that isn't in /bin, it seems to just... skip over it.  No errors, it simply doesn't do it.

Here's the related code. I've removed most of the specifics, as well as the switch control, because I've verified they are working, independently.

```<code>#!/usr/bin/python

import logging
import os
import subprocess
import time

#globals
path_to_plist = 'User/Me/Library/Preferences/PathTo.plist'

def spot_check():
    #determine where we are in the test, verified it works
    return loop_number

def func_that_checks_stuff():
    results = subprocess.check_output(['System/Library/Path/To/tool','-toolarg'])
    ###process results
    logging.info(results)

def restarts(power_on, power off):
    #sets plist key values for the restart app
    subprocess.Popen('defaults write {} plist_key1 {}'.format(path_to_plist, power_on), shell=True
    subprocess.Popen('defaults write {} plist_key2 {}'.format(path_to_plist, power_off), shell=True

    #run the restart app, which is a GUI application in /Applications
    logging.info('Starting restart app')
    subprocess.Popen('open -a RestartApp.app', shell=True)
    time.sleep(power_on + 5)

def main():
    ###setup and config stuff, verified its working

    #switch control stuff, verified its working
    loop = spot_check()

    if loop == 0:
        #tool that shows text on the screen
        subprocess.Popen('User/Me/Library/Scripts/Path/To/Text/tool -a -args', shell=True)
        logging.info('I just ran that tool')
        subprocess.check_output('ls -l', shell=True)
        restarts(10, 0)
    if loop == 1:
        func_that_checks_stuff()
        subprocess.Popen('User/Me/Library/Scripts/Path/To/Text/tool -a args', shell=True)
        logging.info('Hey I ran that tool again, see?')
        restarts(10, 0)
    else:
        func_that_checks_stuff()
        subprocess.Popen('User/Me/Library/Scripts/Path/To/Text/tool -a args', shell=True)

    print 'You finished!'

if __name__ == '__main__':
    main()
</code>```

So, if I start this using my launch agent, it will run through every sequence just fine.

On the first loop (prior to the restart), EVERYTHING works.  All logging, all tools, everything.

After the restart, all the logging works, so I know it's following the switch control.  The func_that_checks_stuff() works, and logs it's output correctly.  The ls -l' call shows me exactly what I should see. But,Path/To/Text/tooldoesn't run, and when I callrestarts()`, it never opens the app.

No errors are produced, at least that I can find

What am I doing wrong? Is it something to do with the tool paths?

答:
Update:

As it turns out, the solution was to add a ~20 second delay at the start of the script.  It seems like it was trying to run the commands in question before Window Server had finished loading, and that freaked everything out.  Not a particularly elegant solution, but it works for what I need in this project.

Body:
So, I'm starting a Python (2.7) script via a launch agent, on macOS 10.13.  The script runs, and during execution, it triggers a restart of the computer.  When the computer turns back on and logs in, the launch agent runs the script again.  The script reads the logs, and does a switch:case to pick up where it left off.

The problem is, after the restart, the python script is unable to execute some shell commands. ls -l works fine.  However, when I try to run something that isn't in /bin, it seems to just... skip over it.  No errors, it simply doesn't do it.

Here's the related code. I've removed most of the specifics, as well as the switch control, because I've verified they are working, independently.

#!/usr/bin/python

import logging
import os
import subprocess
import time

#globals
path_to_plist = 'User/Me/Library/Preferences/PathTo.plist'

def spot_check():
    #determine where we are in the test, verified it works
    return loop_number

def func_that_checks_stuff():
    results = subprocess.check_output(['System/Library/Path/To/tool','-toolarg'])
    ###process results
    logging.info(results)

def restarts(power_on, power off):
    #sets plist key values for the restart app
    subprocess.Popen('defaults write {} plist_key1 {}'.format(path_to_plist, power_on), shell=True
    subprocess.Popen('defaults write {} plist_key2 {}'.format(path_to_plist, power_off), shell=True

    #run the restart app, which is a GUI application in /Applications
    logging.info('Starting restart app')
    subprocess.Popen('open -a RestartApp.app', shell=True)
    time.sleep(power_on + 5)

def main():
    ###setup and config stuff, verified its working

    #switch control stuff, verified its working
    loop = spot_check()

    if loop == 0:
        #tool that shows text on the screen
        subprocess.Popen('User/Me/Library/Scripts/Path/To/Text/tool -a -args', shell=True)
        logging.info('I just ran that tool')
        subprocess.check_output('ls -l', shell=True)
        restarts(10, 0)
    if loop == 1:
        func_that_checks_stuff()
        subprocess.Popen('User/Me/Library/Scripts/Path/To/Text/tool -a args', shell=True)
        logging.info('Hey I ran that tool again, see?')
        restarts(10, 0)
    else:
        func_that_checks_stuff()
        subprocess.Popen('User/Me/Library/Scripts/Path/To/Text/tool -a args', shell=True)

    print 'You finished!'

if __name__ == '__main__':
    main()

So, if I start this using my launch agent, it will run through every sequence just fine.

On the first loop (prior to the restart), EVERYTHING works.  All logging, all tools, everything.

After the restart, all the logging works, so I know it's following the switch control.  The func_that_checks_stuff() works, and logs it's output correctly.  The ls -l' call shows me exactly what I should see. But,Path/To/Text/tooldoesn't run, and when I callrestarts()`, it never opens the app.

No errors are produced, at least that I can find

What am I doing wrong? Is it something to do with the tool paths?


来源: stackexchange

问:
Trying to convert base class to a class template
So, I'm trying to convert an array class to a template class, so far I have combined the header and main file code into one, resulting in just the header file with all the .cpp code. Though trying to compile the code into the main file results in countless errors. Now, please go easy on me here, I am still coming to grasp with C++ here, and some of the higher functions and abilities go over my head, so I apologize in advance that I am not super familiar with all the functions. The code is below.</p>

```<code>#ifndef ARRAY_H
#define ARRAY_H

 #include <iostream>
 #include <iomanip>
#include <stdexcept>

 using namespace std;

template <typename GArray>
class Array
{
friend std::ostream &operator<<(std::ostream &, const Array &);
friend std::istream &operator>>(std::istream &, Array &);

 public:
// default constructor for class Array (default size 3)
template <typename GArray> Array::Array(int arraySize)
    : size(arraySize > 0 ? arraySize :
        throw invalid_argument("Array size must be greater than 0")),
    ptr(new int[size])
{
    for (size_t i = 0; i < size; ++i)

        ptr[i] = 0; // set pointer-based array element
} // end Array default constructor

template <typename GArray> Array::~Array()
{
    delete[] ptr; // release pointer-based array space
}  // destructor

size_t Array::getSize() const
{
    return size; // number of elements in Array
} // end function getSize

  // overloaded assignment operator;
  // const return avoids: ( a1 = a2 ) = a3
template <typename GArray>  const Array &Array::operator=(const Array &right)
{
    if (&right != this) // avoid self-assignment
    {
        // for Arrays of different sizes, deallocate original
        // left-side Array, then allocate new left-side Array
        if (size != right.size)
        {
            delete[] ptr; // release space
            size = right.size; // resize this object
            ptr = new int[size]; // create space for Array copy
        } // end inner if

        for (size_t i = 0; i < size; ++i)
            ptr[i] = right.ptr[i]; // copy array into object
    } // end outer if

    return *this; // enables x = y = z, for example
} // end function operator=

template <typename GArray>  bool operator==(const Array &) const; // equality operator

                                      // subscript operator for const objects returns rvalue
int operator[](int) const;
  private:
size_t size;
int *ptr;
};

template <typename GArray> bool Array::operator==(const Array &right) const
     {
          if (size != right.size)
       return false; // arrays of different number of elements

for (size_t i = 0; i < size; ++i)
    if (ptr[i] != right.ptr[i])
        return false; // Array contents are not equal

return true;
       }

 template <typename GArray> int Array::operator[](int subscript) const
{

if (subscript < 0 || subscript >= size)
    throw out_of_range("Subscript out of range");

return ptr[subscript];
 }

  template <typename GArray> istream &operator>>(istream &input, Array &a)
  {
for (size_t i = 0; i < a.size; ++i)
    input >> a.ptr[i];

return input; // enables cin >> x >> y;
 }

   template <typename GArray> ostream &operator<<(ostream &output, const Array &a)
{
// output private ptr-based array
for (size_t i = 0; i < a.size; ++i)
{
    output << setw(12) << a.ptr[i];

    if ((i + 1) % 4 == 0) // 4 numbers per row of output
        output << endl;
}

if (a.size % 4 != 0) // end last line of output
    output << endl;

return output; // enables cout << x << y;
   }

#endif
</code>```

答:
Firstly

If you define a class as a template, you do not need to tell the member functions declaration to be template. Just make them template in the definition and use them in your class template argument if they are defined outside the class. For example,

```<code>template <class T> class Test {
    void func1(T arg1);
};
template <class T> Test<T>::func1(T arg1) {
    // Your definition here
}
</code>```

Or inside the class,

```<code>template <class T> class Test {
    void func1(T arg1) {
        //Your definition here
    }
};
</code>```

So you need to remove those from your code.

Secondly

Your class has two friend functions. In my opinion, they should also be template functions to work properly with your class. You can see here for a good knowledge in friend function in template classes.

Some good resources to know how to convert regular class to template

Converting regular class to template

I learned from here

Best place for c++ template tutorial

Finally

Although what I understand what you want, there should be added a lot more functionality to the class to work properly, after some modification, here is the code that is compilable and can be used as a starting point to know about your errors.

```<code>#ifndef ARRAY_H
#define ARRAY_H

#include <iostream>
#include <iomanip>
#include <stdexcept>

using namespace std;

template <typename GArray>
class Array {
private:
    size_t size;
    int *ptr;

public:
    Array(int arraySize);
    ~Array();

    size_t getSize() const;

    const Array& operator=(const Array &right);
    bool operator==(const Array &) const;
    int operator[](int) const;

    friend std::ostream &operator<<(std::ostream &, const Array &);
    friend std::istream &operator>>(std::istream &, Array &);

};

template <typename GArray> bool Array<GArray>::operator==(const Array<GArray> &right) const
{
    if (size != right.size)
        return false; // arrays of different number of elements

    for (size_t i = 0; i < size; ++i)
        if (ptr[i] != right.ptr[i])
            return false; // Array contents are not equal

    return true;
}

template <typename GArray> int Array<GArray>::operator[](int subscript) const
{

    if (subscript < 0 || subscript >= size)
        throw out_of_range("Subscript out of range");

    return ptr[subscript];
}

template <typename GArray> istream &operator>>(istream &input, Array<GArray> &a)
{
    for (size_t i = 0; i < a.size; ++i)
        input >> a.ptr[i];

    return input; // enables cin >> x >> y;
}

template <typename GArray> ostream &operator<<(ostream &output, const Array<GArray> &a)
{
// output private ptr-based array
    for (size_t i = 0; i < a.size; ++i)
    {
        output << setw(12) << a.ptr[i];

        if ((i + 1) % 4 == 0) // 4 numbers per row of output
            output << endl;
    }

    if (a.size % 4 != 0) // end last line of output
        output << endl;

    return output; // enables cout << x << y;
}

template<typename GArray>
Array<GArray>::Array(int arraySize)
        : size(arraySize > 0 ? arraySize :
               throw invalid_argument("Array size must be greater than 0")),
          ptr(new int[size]) {
    for (size_t i = 0; i < size; ++i)
        ptr[i] = 0; // set pointer-based array element
}

template<typename GArray>
Array<GArray>::~Array() {

    //This should be like this
    for (int i = 0; i < size; ++i) {
        delete ptr[i];
    }
    // delete[] ptr; // release pointer-based array space
}

template <typename GArray>
size_t Array<GArray>::getSize() const {
    return size; // number of elements in Array
}

template<typename GArray>
const Array<GArray> &Array<GArray>::operator=(const Array &right) {
    if (&right != this) // avoid self-assignment
    {
        // for Arrays of different sizes, deallocate original
        // left-side Array, then allocate new left-side Array
        if (size != right.size)
        {
            delete[] ptr; // release space
            size = right.size; // resize this object
            ptr = new int[size]; // create space for Array copy
        } // end inner if

        for (size_t i = 0; i < size; ++i)
            ptr[i] = right.ptr[i]; // copy array into object
    } // end outer if

    return *this; // enables x = y = z, for example
}

#endif
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So, I'm trying to convert an array class to a template class, so far I have combined the header and main file code into one, resulting in just the header file with all the .cpp code. Though trying to compile the code into the main file results in countless errors. Now, please go easy on me here, I am still coming to grasp with C++ here, and some of the higher functions and abilities go over my head, so I apologize in advance that I am not super familiar with all the functions. The code is below.

#ifndef ARRAY_H
#define ARRAY_H

 #include <iostream>
 #include <iomanip>
#include <stdexcept>

 using namespace std;

template <typename GArray>
class Array
{
friend std::ostream &operator<<(std::ostream &, const Array &);
friend std::istream &operator>>(std::istream &, Array &);

 public:
// default constructor for class Array (default size 3)
template <typename GArray> Array::Array(int arraySize)
    : size(arraySize > 0 ? arraySize :
        throw invalid_argument("Array size must be greater than 0")),
    ptr(new int[size])
{
    for (size_t i = 0; i < size; ++i)

        ptr[i] = 0; // set pointer-based array element
} // end Array default constructor

template <typename GArray> Array::~Array()
{
    delete[] ptr; // release pointer-based array space
}  // destructor

size_t Array::getSize() const
{
    return size; // number of elements in Array
} // end function getSize

  // overloaded assignment operator;
  // const return avoids: ( a1 = a2 ) = a3
template <typename GArray>  const Array &Array::operator=(const Array &right)
{
    if (&right != this) // avoid self-assignment
    {
        // for Arrays of different sizes, deallocate original
        // left-side Array, then allocate new left-side Array
        if (size != right.size)
        {
            delete[] ptr; // release space
            size = right.size; // resize this object
            ptr = new int[size]; // create space for Array copy
        } // end inner if

        for (size_t i = 0; i < size; ++i)
            ptr[i] = right.ptr[i]; // copy array into object
    } // end outer if

    return *this; // enables x = y = z, for example
} // end function operator=

template <typename GArray>  bool operator==(const Array &) const; // equality operator

                                      // subscript operator for const objects returns rvalue
int operator[](int) const;
  private:
size_t size;
int *ptr;
};

template <typename GArray> bool Array::operator==(const Array &right) const
     {
          if (size != right.size)
       return false; // arrays of different number of elements

for (size_t i = 0; i < size; ++i)
    if (ptr[i] != right.ptr[i])
        return false; // Array contents are not equal

return true;
       }

 template <typename GArray> int Array::operator[](int subscript) const
{

if (subscript < 0 || subscript >= size)
    throw out_of_range("Subscript out of range");

return ptr[subscript];
 }

  template <typename GArray> istream &operator>>(istream &input, Array &a)
  {
for (size_t i = 0; i > a.ptr[i];

return input; // enables cin >> x >> y;
 }

   template <typename GArray> ostream &operator<<(ostream &output, const Array &a)
{
// output private ptr-based array
for (size_t i = 0; i < a.size; ++i)
{
    output << setw(12) << a.ptr[i];

    if ((i + 1) % 4 == 0) // 4 numbers per row of output
        output << endl;
}

if (a.size % 4 != 0) // end last line of output
    output << endl;

return output; // enables cout << x << y;
   }

#endif

Body:
Firstly

If you define a class as a template, you do not need to tell the member functions declaration to be template. Just make them template in the definition and use them in your class template argument if they are defined outside the class. For example,

template <class T> class Test {
    void func1(T arg1);
};
template <class T> Test<T>::func1(T arg1) {
    // Your definition here
}

Or inside the class,

template <class T> class Test {
    void func1(T arg1) {
        //Your definition here
    }
};

So you need to remove those from your code.

Secondly

Your class has two friend functions. In my opinion, they should also be template functions to work properly with your class. You can see here for a good knowledge in friend function in template classes.

Some good resources to know how to convert regular class to template

Converting regular class to template

I learned from here

Best place for c++ template tutorial

Finally

Although what I understand what you want, there should be added a lot more functionality to the class to work properly, after some modification, here is the code that is compilable and can be used as a starting point to know about your errors.

#ifndef ARRAY_H
#define ARRAY_H

#include <iostream>
#include <iomanip>
#include <stdexcept>

using namespace std;

template <typename GArray>
class Array {
private:
    size_t size;
    int *ptr;

public:
    Array(int arraySize);
    ~Array();

    size_t getSize() const;

    const Array& operator=(const Array &right);
    bool operator==(const Array &) const;
    int operator[](int) const;

    friend std::ostream &operator<<(std::ostream &, const Array &);
    friend std::istream &operator>>(std::istream &, Array &);

};

template <typename GArray> bool Array<GArray>::operator==(const Array<GArray> &right) const
{
    if (size != right.size)
        return false; // arrays of different number of elements

    for (size_t i = 0; i < size; ++i)
        if (ptr[i] != right.ptr[i])
            return false; // Array contents are not equal

    return true;
}

template <typename GArray> int Array<GArray>::operator[](int subscript) const
{

    if (subscript < 0 || subscript >= size)
        throw out_of_range("Subscript out of range");

    return ptr[subscript];
}

template <typename GArray> istream &operator>>(istream &input, Array<GArray> &a)
{
    for (size_t i = 0; i < a.size; ++i)
        input >> a.ptr[i];

    return input; // enables cin >> x >> y;
}

template <typename GArray> ostream &operator<<(ostream &output, const Array<GArray> &a)
{
// output private ptr-based array
    for (size_t i = 0; i < a.size; ++i)
    {
        output << setw(12) << a.ptr[i];

        if ((i + 1) % 4 == 0) // 4 numbers per row of output
            output << endl;
    }

    if (a.size % 4 != 0) // end last line of output
        output << endl;

    return output; // enables cout << x << y;
}

template<typename GArray>
Array<GArray>::Array(int arraySize)
        : size(arraySize > 0 ? arraySize :
               throw invalid_argument("Array size must be greater than 0")),
          ptr(new int[size]) {
    for (size_t i = 0; i < size; ++i)
        ptr[i] = 0; // set pointer-based array element
}

template<typename GArray>
Array<GArray>::~Array() {

    //This should be like this
    for (int i = 0; i < size; ++i) {
        delete ptr[i];
    }
    // delete[] ptr; // release pointer-based array space
}

template <typename GArray>
size_t Array<GArray>::getSize() const {
    return size; // number of elements in Array
}

template<typename GArray>
const Array<GArray> &Array<GArray>::operator=(const Array &right) {
    if (&right != this) // avoid self-assignment
    {
        // for Arrays of different sizes, deallocate original
        // left-side Array, then allocate new left-side Array
        if (size != right.size)
        {
            delete[] ptr; // release space
            size = right.size; // resize this object
            ptr = new int[size]; // create space for Array copy
        } // end inner if

        for (size_t i = 0; i < size; ++i)
            ptr[i] = right.ptr[i]; // copy array into object
    } // end outer if

    return *this; // enables x = y = z, for example
}

#endif


问:
Defining multiple variances of __iter__ in a class
I am writing a game of Connect 4 and have a Grid class that resembles the 2-dimensional grid that the game is played in. The underlying data structure of my Grid class is an instance variable self.grid - a 2-dimensional list.

I have overwritten the __iter__ method as such:

```<code>def __iter__(self):
    for row in range(self.numRows):
        for col in range(self.numCols):
            yield self.grid[row][col]
</code>```

which I can then call as:

```<code>for cell in grid:
    # do something with yielded cell
</code>```

At some points, I need to iterate over just a specified row or a specified column. Instead of writing

```<code>col = 0
for row in range(grid.numRows):
    # do something with grid.grid[row][col]
</code>```

is there any Pythonic, readable way to define a 2nd and 3rd __iter__ method along the lines of:

```<code>def __iter__(self, col)
    for row in range(self.numRows):
        yeild self.grid[row][col]
</code>```

which would be called as:

```<code>for row in grid(col=0):
    # do something with the yielded cell
</code>```

and then the same, but with a specified row?

答:
Sure you can do that, no need to add special methods. Just add iterators, python 3 code below:

```<code>ALL = 0
ROW = 1
COL = 2

class db:
    def __init__(self, n):
        self.n = n

    def __iter__(self):
        return db_iter_all(self.n)

    def __call__(self, what = ALL):
        if what == ALL:
            return db_iter_all(self.n)
        if what == ROW:
            return db_iter_row(self.n)
        if what == COL:
            return db_iter_col(self.n)
        raise ValueError("What what?")

class db_iter_all:
    def __init__(self, n):
        self.i = 0
        self.n = n

    def __iter__(self):
        return self

    def __next__(self):
        if self.i > self.n:
            raise StopIteration()
        r = self.i
        self.i += 1
        return r

class db_iter_row:
    def __init__(self, n):
        self.i = 0
        self.n = n

    def __iter__(self):
        return self

    def __next__(self):
        if self.i > self.n:
            raise StopIteration()
        r = self.i
        self.i += 3
        return r

class db_iter_col:
    def __init__(self, n):
        self.i = 0
        self.n = n

    def __iter__(self):
        return self

    def __next__(self):
        if self.i > self.n:
            raise StopIteration()
        r = self.i
        self.i += 5
        return r
</code>```

And simple example how to use it

```<code>grid = db(15)
for k in grid:
    print(k)

for k in grid(ROW):
    print(k)

for k in grid(COL):
    print(k)
</code>```

Body:
I am writing a game of Connect 4 and have a Grid class that resembles the 2-dimensional grid that the game is played in. The underlying data structure of my Grid class is an instance variable self.grid - a 2-dimensional list.

I have overwritten the __iter__ method as such:

def __iter__(self):
    for row in range(self.numRows):
        for col in range(self.numCols):
            yield self.grid[row][col]

which I can then call as:

for cell in grid:
    # do something with yielded cell

At some points, I need to iterate over just a specified row or a specified column. Instead of writing

col = 0
for row in range(grid.numRows):
    # do something with grid.grid[row][col]

is there any Pythonic, readable way to define a 2nd and 3rd __iter__ method along the lines of:

def __iter__(self, col)
    for row in range(self.numRows):
        yeild self.grid[row][col]

which would be called as:

for row in grid(col=0):
    # do something with the yielded cell

and then the same, but with a specified row?

Body:
Sure you can do that, no need to add special methods. Just add iterators, python 3 code below:

ALL = 0
ROW = 1
COL = 2

class db:
    def __init__(self, n):
        self.n = n

    def __iter__(self):
        return db_iter_all(self.n)

    def __call__(self, what = ALL):
        if what == ALL:
            return db_iter_all(self.n)
        if what == ROW:
            return db_iter_row(self.n)
        if what == COL:
            return db_iter_col(self.n)
        raise ValueError("What what?")

class db_iter_all:
    def __init__(self, n):
        self.i = 0
        self.n = n

    def __iter__(self):
        return self

    def __next__(self):
        if self.i > self.n:
            raise StopIteration()
        r = self.i
        self.i += 1
        return r

class db_iter_row:
    def __init__(self, n):
        self.i = 0
        self.n = n

    def __iter__(self):
        return self

    def __next__(self):
        if self.i > self.n:
            raise StopIteration()
        r = self.i
        self.i += 3
        return r

class db_iter_col:
    def __init__(self, n):
        self.i = 0
        self.n = n

    def __iter__(self):
        return self

    def __next__(self):
        if self.i > self.n:
            raise StopIteration()
        r = self.i
        self.i += 5
        return r

And simple example how to use it

grid = db(15)
for k in grid:
    print(k)

for k in grid(ROW):
    print(k)

for k in grid(COL):
    print(k)


问:
How to change the color of text in a TextView generated by an ArrayAdapter
I am using a ListView with an ArrayAdapter, and I want to change the color of text inside of a TextView when the user clicks on it. This works fine except when one TextView changes color another one further down the list changes color too.

Does this have something to do with ArrayAdapter reusing views?

```<code>ArrayAdapter<String> adapter = new ArrayAdapter<> (thisContext, R.layout.textview_1, arrayList);
listView.setAdapter (adapter);

listView.setOnItemClickListener (new AdapterView.OnItemClickListener ()
{
    @Override
    public void onItemClick (AdapterView<?> parent, View view, int   position, long id)
    {
        TextView textToChange = (TextView) view;
        textToChange.setTextColor (Color.RED);
    }
});
</code>```

答:
Does this have something to do with ArrayAdapter reusing views?

Yes.

You can solve this by overriding getView() when you create your ArrayAdapter, by doing something like this:

```<code>ArrayAdapter<String> adapter = new ArrayAdapter<String>(thisContext, R.layout.textview_1, arrayList) {

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        // TODO
    }
};
</code>```

How you actually go about solving it will depend on what behavior you want. It seems like your item views are TextViews really, so you could replace the TODO with something like this:

```<code>TextView tv = (TextView) super.getView(position, convertView, parent);
tv.setTextColor(Color.BLACK);
return tv;
</code>```

That will make sure that any recycled view has black text, but it will also mean that if you click on a row (so it turns red), scroll that row out of view, and then scroll it back into view, it will go back to being black.

Perhaps you could update a variable that stores your last clicked position from within your OnItemClickListener, and then reference that in getView():

```<code>TextView tv = (TextView) super.getView(position, convertView, parent);
tv.setTextColor(position == lastClickedPosition ? Color.RED : Color.BLACK);
return tv;
</code>```

Body:
I am using a ListView with an ArrayAdapter, and I want to change the color of text inside of a TextView when the user clicks on it. This works fine except when one TextView changes color another one further down the list changes color too.

Does this have something to do with ArrayAdapter reusing views?

ArrayAdapter<String> adapter = new ArrayAdapter<> (thisContext, R.layout.textview_1, arrayList);
listView.setAdapter (adapter);

listView.setOnItemClickListener (new AdapterView.OnItemClickListener ()
{
    @Override
    public void onItemClick (AdapterView<?> parent, View view, int   position, long id)
    {
        TextView textToChange = (TextView) view;
        textToChange.setTextColor (Color.RED);
    }
});

Body:
Does this have something to do with ArrayAdapter reusing views?

Yes.

You can solve this by overriding getView() when you create your ArrayAdapter, by doing something like this:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(thisContext, R.layout.textview_1, arrayList) {

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        // TODO
    }
};

How you actually go about solving it will depend on what behavior you want. It seems like your item views are TextViews really, so you could replace the TODO with something like this:

TextView tv = (TextView) super.getView(position, convertView, parent);
tv.setTextColor(Color.BLACK);
return tv;

That will make sure that any recycled view has black text, but it will also mean that if you click on a row (so it turns red), scroll that row out of view, and then scroll it back into view, it will go back to being black.

Perhaps you could update a variable that stores your last clicked position from within your OnItemClickListener, and then reference that in getView():

TextView tv = (TextView) super.getView(position, convertView, parent);
tv.setTextColor(position == lastClickedPosition ? Color.RED : Color.BLACK);
return tv;


问:
Google maps api REQUEST_DENIED when using API restrictions & key
I have been happily using the Geocoding API from Maps for some years, with no problem.  Recently I've made more keys, for different environments, and decided it would be a good idea to add API restrictions to them.

When I add these API restrictions, I suddenly start getting REQUEST_DENIED.

```<code>https://maps.googleapis.com/maps/api/geocode/json?latlng=={lt},{ln}&key={key}

This IP, site or mobile application is not authorized to use this API key, ...
REQUEST_DENIED
</code>```

Removing them allows the APIs to be called again.

This is the setup for the keys.  We only have 2 APIs enabled, and they are both added to this key.  In this configuration I can't call the Geocoding API.  When I delete the restrictions the Key works again, no problem.  I've not set up any other app restrictions.

答: I ran into this issue as well. I think the API Restrictions settings actually prevents the key being used for the listed APIs. In other words, it's opt-out rather than opt-in. However, that's very counterintuitive and not at all clear from the documentation. </p>

Body:
I have been happily using the Geocoding API from Maps for some years, with no problem.  Recently I've made more keys, for different environments, and decided it would be a good idea to add API restrictions to them.

When I add these API restrictions, I suddenly start getting REQUEST_DENIED.

https://maps.googleapis.com/maps/api/geocode/json?latlng=={lt},{ln}&key={key}

This IP, site or mobile application is not authorized to use this API key, ...
REQUEST_DENIED

Removing them allows the APIs to be called again.

This is the setup for the keys.  We only have 2 APIs enabled, and they are both added to this key.  In this configuration I can't call the Geocoding API.  When I delete the restrictions the Key works again, no problem.  I've not set up any other app restrictions.


问:
How to map a derived class to a base class property with Automapper
Firstly, if my above question is confusing, I am both new to the use of Automapper and don't know the lingo all that well and rarely ask questions like this so I might be trying to articulate my thoughts into an absurd sounding question.

I have created a few classes that inherit from a base class because I intend to re-use the base classes for more entities than the ones shown below. For simplicity sake, I am going to keep the classes void of the properties.

My issue is with the mapping for the PersonBusiness properties. When I load the data from SQL with EF 6 I see it loads the Person and Business properties of the PersonBusiness object as an Employee object and a Branch object because that is what I am pulling back for the query, but when I attempt to map the Employee Object and the Branch object from the PersonBusiness object to the PersonBusinessDto object it loads them as the Person and Business class types; obviously leaving off all the properties that are included in the derived classes.

It's obvious given the data loaded into the PersonBusiness object that the Person and Business properties are object reference variables that can be loaded with the derived types Employee and Branch but for some reason, Automapper sees the Employee and Branch objects and only maps them to the base type of Person and Business.

This is an example of the data loaded from the database:

And this is an example of the data mapped to the PersonBusinessDto:

Below are the basic class structure and the mappings I used to map the Entities to the DTOs which work fine for everything except the PersonBusiness mappings.

Entity.cs

```<code>public abstract class Entity : IEntity
{

}
</code>```

EntityDto.cs

```<code>public abstract class EntityDto : IEntityDto
{

}
</code>```

Person.cs

```<code>public abstract class Person : Entity
{
    public List<PersonBusiness> PersonBusinesses { get; set; };
}
</code>```

PersonDto.cs

```<code>public abstract class PersonDto : EntityDto
{
    public List<PersonBusinessDto> PersonBusinesses { get; set; };
}
</code>```

Employee.cs

```<code>public class Employee : Person
{

}
</code>```

EmployeeDto.cs

```<code>public class EmployeeDto : PersonDto
{

}
</code>```

Business.cs

```<code>public abstract class Business : Entity
{
    public List<PersonBusiness> PersonBusinesses { get; set; };
}
</code>```

BusinessDto.cs

```<code>public abstract class BusinessDto : EntityDto
{
    public List<PersonBusinessDto> PersonBusinesses { get; set; };
}
</code>```

Branch.cs

```<code>public class Branch : Business
{

}
</code>```

BranchDto.cs

```<code>public class BranchDto : BusinessDto
{

}
</code>```

PersonBusiness.cs

```<code>public abstract class EntityDto : IEntityDto
{

}
</code>```0

PersonBusinessDto.cs

```<code>public abstract class EntityDto : IEntityDto
{

}
</code>```1

AutoMapperConfig.cs

```<code>public abstract class EntityDto : IEntityDto
{

}
</code>```2

答:
What's happening here is that Employee and Branch are being upcasted to Person and Business, respectively since those are the actual types in the PersonBusiness class. Then, when AutoMapper does the mapping, it sees Person and Business types and therefore maps them to PersonDto and BusinessDto as the configuration dictates.

The objects are still instances of Employee and Branch, even after they've been upcasted; you could cast back to Employee and Branch. However, AutoMapper is creating actual instances of PersonDto and BusinessDto, so you can't cast those to EmployeDto and BranchDto.

Short of having a class with the actual correct property types, you'll have to cast them back to the right types during the mapping, which is going to be a real  pain. Principally, you're going to run into the issue that MapFrom is not going to be able to return varying derived types, because the lambda can only return one type.

AutoMapper provides some guidance for how to make this sort of thing work. However, you'll notice that it's dealing with the instances directly, and not properties on those instances. I'm not sure how to actually, do what you need to do, other than to simply ignore mapping those properties when mapping from PersonBusiness to PersonBusinessDto, and then explicitly map over the properties using the method the AutoMapper docs detail, i.e.

```<code>personBusinessDto.Person = Mapper.Map(personBusiness.Person, personBusiness.Person.GetType(), typeof(PersonDto));
</code>```

Like I said: real pain.

Body:
Firstly, if my above question is confusing, I am both new to the use of Automapper and don't know the lingo all that well and rarely ask questions like this so I might be trying to articulate my thoughts into an absurd sounding question.

I have created a few classes that inherit from a base class because I intend to re-use the base classes for more entities than the ones shown below. For simplicity sake, I am going to keep the classes void of the properties.

My issue is with the mapping for the PersonBusiness properties. When I load the data from SQL with EF 6 I see it loads the Person and Business properties of the PersonBusiness object as an Employee object and a Branch object because that is what I am pulling back for the query, but when I attempt to map the Employee Object and the Branch object from the PersonBusiness object to the PersonBusinessDto object it loads them as the Person and Business class types; obviously leaving off all the properties that are included in the derived classes.

It's obvious given the data loaded into the PersonBusiness object that the Person and Business properties are object reference variables that can be loaded with the derived types Employee and Branch but for some reason, Automapper sees the Employee and Branch objects and only maps them to the base type of Person and Business.

This is an example of the data loaded from the database:

And this is an example of the data mapped to the PersonBusinessDto:

Below are the basic class structure and the mappings I used to map the Entities to the DTOs which work fine for everything except the PersonBusiness mappings.

Entity.cs

public abstract class Entity : IEntity
{

}

EntityDto.cs

public abstract class EntityDto : IEntityDto
{

}

Person.cs

public abstract class Person : Entity
{
    public List<PersonBusiness> PersonBusinesses { get; set; };
}

PersonDto.cs

public abstract class PersonDto : EntityDto
{
    public List<PersonBusinessDto> PersonBusinesses { get; set; };
}

Employee.cs

public class Employee : Person
{

}

EmployeeDto.cs

public class EmployeeDto : PersonDto
{

}

Business.cs

public abstract class Business : Entity
{
    public List<PersonBusiness> PersonBusinesses { get; set; };
}

BusinessDto.cs

public abstract class BusinessDto : EntityDto
{
    public List<PersonBusinessDto> PersonBusinesses { get; set; };
}

Branch.cs

public class Branch : Business
{

}

BranchDto.cs

public class BranchDto : BusinessDto
{

}

PersonBusiness.cs

public class PersonBusiness
{
    public int PersonId { get; set; }
    public int BusinessId { get; set; }
    public Enums.RoleType RoleType { get; set; }

    public Person Person { get; set; }
    public Business Business { get; set; }
}

PersonBusinessDto.cs

public class PersonBusinessDto
{
    public int PersonId { get; set; }
    public int BusinessId { get; set; }
    public Enums.RoleType RoleType { get; set; }

    public PersonDto Person { get; set; }
    public BusinessDto Business { get; set; }
}

AutoMapperConfig.cs

public class ProfileMapping
        : Profile
    {
        private readonly IMapperConfiguration _mappingConfiguration;

        public ProfileMapping(IMapperConfiguration config)
        {
            _mappingConfiguration = config;
        }

        protected override void Configure()
        {
            _mappingConfiguration.AllowNullDestinationValues = true;

            _mappingConfiguration
                .CreateMap<Person, PersonDto>()
                .ForMember(dto => dto.PersonBusinesses, opt => opt.MapFrom(src => src.PresonBusinesses));

            _mappingConfiguration
                .CreateMap<Employee, EmployeeDto>()

            _mappingConfiguration
                .CreateMap<Business, BusinessDto>()
                .ForMember(dto => dto.PersonBusinesses, opt => opt.MapFrom(src => src.PresonBusinesses));

            _mappingConfiguration
                .CreateMap<Branch, BranchDto>();

            _mappingConfiguration
                .CreateMap<PersonBusiness, PersonBusinessDto>()
                .ForMember(dto => dto.Business, opt => opt.MapFrom(src => src.Business))
                .ForMember(dto => dto.Person, opt => opt.MapFrom(src => src.Person));
        }
    }

Body:
What's happening here is that Employee and Branch are being upcasted to Person and Business, respectively since those are the actual types in the PersonBusiness class. Then, when AutoMapper does the mapping, it sees Person and Business types and therefore maps them to PersonDto and BusinessDto as the configuration dictates.

The objects are still instances of Employee and Branch, even after they've been upcasted; you could cast back to Employee and Branch. However, AutoMapper is creating actual instances of PersonDto and BusinessDto, so you can't cast those to EmployeDto and BranchDto.

Short of having a class with the actual correct property types, you'll have to cast them back to the right types during the mapping, which is going to be a real  pain. Principally, you're going to run into the issue that MapFrom is not going to be able to return varying derived types, because the lambda can only return one type.

AutoMapper provides some guidance for how to make this sort of thing work. However, you'll notice that it's dealing with the instances directly, and not properties on those instances. I'm not sure how to actually, do what you need to do, other than to simply ignore mapping those properties when mapping from PersonBusiness to PersonBusinessDto, and then explicitly map over the properties using the method the AutoMapper docs detail, i.e.

personBusinessDto.Person = Mapper.Map(personBusiness.Person, personBusiness.Person.GetType(), typeof(PersonDto));

Like I said: real pain.


问:
How to sort ip address in ascending order
Is there any method to sort this? Or do I just need to split it and use a loop to compare?
Input

```<code>123.4.245.23
104.244.253.29
1.198.3.93
32.183.93.40
104.30.244.2
104.244.4.1
</code>```

Output

```<code>1.198.3.93
32.183.93.40
104.30.244.2
104.244.4.1
104.244.253.29
123.4.245.23
</code>```

So far I use HashMap to stored my data. I want sort the value by the  Ip address in ascending order. Seems TreeMap is better choice?

答:
In Java8

```<code>import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;

class Test {
    private static final Comparator<InetAddress> COMPARATOR = Comparator
            .comparing(InetAddress::getAddress,
                    Comparator.comparingInt((byte[] b) -> b.length)
                    .thenComparing(b -> new BigInteger(1, b)));

    public static void main(String[] args) {
        final String[] addresses = {
                "123.4.245.23",
                "104.244.253.29",
                "1.198.3.93",
                "32.183.93.40",
                "104.30.244.2",
                "104.244.4.1"
        };

        for (final String address : sort(addresses)) {
            System.out.println(address);
        }
    }

    public static String[] sort(final String[] addresses) {
        return Arrays.stream(addresses)
                .map(s -> new AbstractMap.SimpleImmutableEntry<>(toInetAddress(s), s))
                .sorted(Comparator.comparing(Map.Entry::getKey, Comparator.nullsLast(COMPARATOR)))
                .map(Map.Entry::getValue)
                .toArray(String[]::new);
    }

    private static InetAddress toInetAddress(final String address) {
        try {
            return InetAddress.getByName(address);
        } catch (final UnknownHostException | SecurityException e) {
            e.printStackTrace();
            return null;
        }
    }
}
</code>```

Output:

```
1.198.3.93
32.183.93.40
104.30.244.2
104.244.4.1
104.244.253.29
123.4.245.23

```

Body:
Is there any method to sort this? Or do I just need to split it and use a loop to compare?
Input

123.4.245.23
104.244.253.29
1.198.3.93
32.183.93.40
104.30.244.2
104.244.4.1

Output

1.198.3.93
32.183.93.40
104.30.244.2
104.244.4.1
104.244.253.29
123.4.245.23

So far I use HashMap to stored my data. I want sort the value by the  Ip address in ascending order. Seems TreeMap is better choice?

Body:
In Java8

import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;

class Test {
    private static final Comparator<InetAddress> COMPARATOR = Comparator
            .comparing(InetAddress::getAddress,
                    Comparator.comparingInt((byte[] b) -> b.length)
                    .thenComparing(b -> new BigInteger(1, b)));

    public static void main(String[] args) {
        final String[] addresses = {
                "123.4.245.23",
                "104.244.253.29",
                "1.198.3.93",
                "32.183.93.40",
                "104.30.244.2",
                "104.244.4.1"
        };

        for (final String address : sort(addresses)) {
            System.out.println(address);
        }
    }

    public static String[] sort(final String[] addresses) {
        return Arrays.stream(addresses)
                .map(s -> new AbstractMap.SimpleImmutableEntry<>(toInetAddress(s), s))
                .sorted(Comparator.comparing(Map.Entry::getKey, Comparator.nullsLast(COMPARATOR)))
                .map(Map.Entry::getValue)
                .toArray(String[]::new);
    }

    private static InetAddress toInetAddress(final String address) {
        try {
            return InetAddress.getByName(address);
        } catch (final UnknownHostException | SecurityException e) {
            e.printStackTrace();
            return null;
        }
    }
}

Output:

1.198.3.93
32.183.93.40
104.30.244.2
104.244.4.1
104.244.253.29
123.4.245.23


问:
How to order a list of objects using a list of object attributes
I have a list of objects with ids (object.id) and a list of ids. What is the most efficient way to use the list of ids to order the object list? I have the following solution... just wondering whether there is a faster one?

Input:

result = list of user objects with user ids (user.id)

list_of_ids = list of user ids e.g. [3, 2, 5, 8, 9]

Output:

list of user objects ordered according to list_of_ids

Code:

```<code>ordered_result = []
for user_id in list_of_ids:
    for user in result:
        if user_id == user.id:
            ordered_result.append(user)
            break
</code>```

答:
Here is an O(n log(n)) solution. It requires the ids in both lists to be exactly the same. It sorts the object list by id and does an indirect sort of the id list yielding an index list containing the positions of ids in order. This is then used to move the sorted objects to the right positions.

```<code>import operator

class know_who_you_are:
    def __init__(self, id_):
        self.id = id_

def argsort(L):
    "returns sorted, order"
    return zip(*sorted(zip(L, range(len(L)))))

ids = [3, 2, 4, 5, 1]
objs = [know_who_you_are(id_) for id_ in [1, 5, 3, 2, 4]]

sid, oid = argsort(ids)
sobj = sorted(objs, key=operator.attrgetter('id'))
result = len(objs) * [None]
for dest, src in zip(oid, sobj):
    result[dest] = src

# check
print(all(id_==obj.id for id_, obj in zip(ids, result)))
</code>```

Prints:

```<code>True
</code>```

Body:
I have a list of objects with ids (object.id) and a list of ids. What is the most efficient way to use the list of ids to order the object list? I have the following solution... just wondering whether there is a faster one?

Input:

result = list of user objects with user ids (user.id)

list_of_ids = list of user ids e.g. [3, 2, 5, 8, 9]

Output:

list of user objects ordered according to list_of_ids

Code:

ordered_result = []
for user_id in list_of_ids:
    for user in result:
        if user_id == user.id:
            ordered_result.append(user)
            break

Body:
Here is an O(n log(n)) solution. It requires the ids in both lists to be exactly the same. It sorts the object list by id and does an indirect sort of the id list yielding an index list containing the positions of ids in order. This is then used to move the sorted objects to the right positions.

import operator

class know_who_you_are:
    def __init__(self, id_):
        self.id = id_

def argsort(L):
    "returns sorted, order"
    return zip(*sorted(zip(L, range(len(L)))))

ids = [3, 2, 4, 5, 1]
objs = [know_who_you_are(id_) for id_ in [1, 5, 3, 2, 4]]

sid, oid = argsort(ids)
sobj = sorted(objs, key=operator.attrgetter('id'))
result = len(objs) * [None]
for dest, src in zip(oid, sobj):
    result[dest] = src

# check
print(all(id_==obj.id for id_, obj in zip(ids, result)))

Prints:

True


问:
How to publish specific branch to azure app service?
I have code in VSTS. I have azure app service.

I can manually deploy from Visual Studio to azure via Publish Config Profile.

I setup continue integration deploy, now I somebody push to master branch it will be deployed on azure.

How to publish specific branch to azure app service? Main goal what QA can deploy any branch without VS.

I can't find any whay, except make a lot of CMD command like, login to VSTS, get files, upload to server, run server.

答:
and if you got here trying to google how to get it working for local git deployment option, here is the answer: https://github.com/projectkudu/kudu/wiki/Deployment-branch

you can set the branch by setting an Azure App Setting called
  deployment_branch.


问:
Wrapping multiple elements with one tag in DOMdocument
I'm kind of stuck with wrapping elements to one tag in php DOMdocument.
This is what I have:

```<code><figure>
    <a href="">
    <img class=""></a>
</figure>
<figure>
    <a href="">
    <img class=""></a>
</figure>
</code>```

And result should be:

```<code><div class="new">
    <figure>
        <a href="">
        <img class=""></a>
    </figure>
    <figure>
        <a href="">
        <img class=""></a>
    </figure>
</div>
</code>```

I allready did all work with figures inside loop, but I can't figure out how to wrap all theese tags in one parent.
I know that I have to use appendChild(), but my selection is DOMNodeList and it cannot be appened. Maybe I'm missing something.
My code:

```<code>$dom = new DOMdocument();
$dom->loadHTML($content);
$NewDiv = $dom->createElement('div');
$NewDiv->setAttribute('class','new');
$figures = $dom->getElementsByTagName('figure');
$NewDiv ->appendChild($figures);
$dom->appendChild($NewDiv);
</code>```

答:
something like this? I do not clearly understand your problem..</p>

```<code>echo'<div>'
include (yourphp.php);
echo'</div>'
</code>```

Body:
I'm kind of stuck with wrapping elements to one tag in php DOMdocument.
This is what I have:

And result should be:

I allready did all work with figures inside loop, but I can't figure out how to wrap all theese tags in one parent.
I know that I have to use appendChild(), but my selection is DOMNodeList and it cannot be appened. Maybe I'm missing something.
My code:

$dom = new DOMdocument();
$dom->loadHTML($content);
$NewDiv = $dom->createElement('div');
$NewDiv->setAttribute('class','new');
$figures = $dom->getElementsByTagName('figure');
$NewDiv ->appendChild($figures);
$dom->appendChild($NewDiv);

Body:
something like this? I do not clearly understand your problem..

echo'<div>'
include (yourphp.php);
echo'</div>'


问:
Can't get listed of selected items from multiselect ListBox in Excel userform
New to VBA and having some difficulty getting selected items from a ListBox. I keep getting an error on the For line.  The name of the ListBox is correct and I think .ListCount should work.</p>

```<code>Sub GetListBox1()
Dim SelectedItems As String

For i = 0 To ListBox1.ListCount - 1
    If ListBox1.Selected = True Then
    SelectedItems = SelectedItems & ListBox1.List(i)
    End If
Next i

Debug.Print SelectedItems

End Sub
</code>```

答:
To Add commas in your output, try this...

```<code>Dim SelectedItems As String

With UserForm1 ' replace with the name of your form
    For i = 0 To .ListBox1.ListCount - 1
        If .ListBox1.Selected(i) = True Then  ' <-- you need to add the index of the selected item (according to the loop)
            SelectedItems = SelectedItems & .ListBox1.List(i) & ", " ' <-- THE COMMA goes here
        End If
    Next i
End With
</code>```

The way you did it in a ELSE clause would only add a comma if the listbox item was NOT selected, and WOULD add a comma for every listbox item that wasn't selected.

So If a user selected Alabama, and Montana from the states listbox choices, the output would show the two state names, plus 48 commas.

Body:
New to VBA and having some difficulty getting selected items from a ListBox. I keep getting an error on the For line.  The name of the ListBox is correct and I think .ListCount should work.

Sub GetListBox1()
Dim SelectedItems As String

For i = 0 To ListBox1.ListCount - 1
    If ListBox1.Selected = True Then
    SelectedItems = SelectedItems & ListBox1.List(i)
    End If
Next i

Debug.Print SelectedItems

End Sub

Body:
To Add commas in your output, try this...

Dim SelectedItems As String

With UserForm1 ' replace with the name of your form
    For i = 0 To .ListBox1.ListCount - 1
        If .ListBox1.Selected(i) = True Then  ' <-- you need to add the index of the selected item (according to the loop)
            SelectedItems = SelectedItems & .ListBox1.List(i) & ", " ' <-- THE COMMA goes here
        End If
    Next i
End With

The way you did it in a ELSE clause would only add a comma if the listbox item was NOT selected, and WOULD add a comma for every listbox item that wasn't selected.

So If a user selected Alabama, and Montana from the states listbox choices, the output would show the two state names, plus 48 commas.


问:
Azure App Service - deployment from a specific branch in GitHub
I wonder - is there a way to pick up the code from a specific branch only? If I am right, if I follow the following tutorial Deploying-from-GitHub push to any branch gets picked up?</p>

答:
to get it working for local git deployment option, here is the answer: https://github.com/projectkudu/kudu/wiki/Deployment-branch

you can set the branch by setting an Azure App Setting called
  deployment_branch.


问:
Android Toast message doesn't show
I know there are some other issues regard this problem, however, mine is surprisingly different (at least I think so).

I guess my code is right but I don't have idea why toast message doesn't display. Firstly, I couldn't see toast message in my Fragments. Then I decided to put it in my activity and amazingly it doesn't display here too.

This is code of my Activity which has been extended from FragmentActivity.

```<code>@Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        Log.d(TAG, "***************************");
        Log.d(TAG, "*** Application started ***");
        Log.d(TAG, "***************************");

        // assign layout to activity
        setContentView(R.layout.activity_main);

        mContext = MainActivity.this;
        Toast.makeText(mContext, "Hello World", Toast.LENGTH_SHORT).show();

.
.
.
}
</code>```

Application works fine without error and just this f.toast message doesn't display!
I even replaced mContext with getApplicationContext() and I had same result, toast does not display.

Any suggestion would be appreciated. Thanks

===============

Update: When I open Toast class there are some red lines. please look at image below

答:
something may be hiding your toast...so I use this when that appears to be the case:

```<code>    Toast toast = Toast.makeText(TaskEdit.this, "Task Saved", Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.CENTER_HORIZONTAL,0,0);
    toast.show();
</code>```

You can change the position of the toast location using the various setGravity options available.  Happy Coding.

Title: Android Toast message doesn't show

Body:
I know there are some other issues regard this problem, however, mine is surprisingly different (at least I think so).

I guess my code is right but I don't have idea why toast message doesn't display. Firstly, I couldn't see toast message in my Fragments. Then I decided to put it in my activity and amazingly it doesn't display here too.

This is code of my Activity which has been extended from FragmentActivity.

@Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        Log.d(TAG, "***************************");
        Log.d(TAG, "*** Application started ***");
        Log.d(TAG, "***************************");

        // assign layout to activity
        setContentView(R.layout.activity_main);

        mContext = MainActivity.this;
        Toast.makeText(mContext, "Hello World", Toast.LENGTH_SHORT).show();

.
.
.
}

Application works fine without error and just this f.toast message doesn't display!
I even replaced mContext with getApplicationContext() and I had same result, toast does not display.

Any suggestion would be appreciated. Thanks

===============

Update: When I open Toast class there are some red lines. please look at image below

Body:
something may be hiding your toast...so I use this when that appears to be the case:

    Toast toast = Toast.makeText(TaskEdit.this, "Task Saved", Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.CENTER_HORIZONTAL,0,0);
    toast.show();

You can change the position of the toast location using the various setGravity options available.  Happy Coding.


问:
How do "invisible" function parameters in Haskell work?
An example of what I am talking about is takeWhile

```<code>takeWhile :: (a -> Bool) -> [a] -> [a]
</code>```

Example usage

```<code>takeWhile (< 3) [1,2,3,4,1,2,3,4] == [1,2]
</code>```

From what I can tell (< 3) becomes (a < 3) where a is the current item in the list being checked.

How is this done in Haskell and how would I be able to move where a goes so I could do something like

```<code>takeWhile ((length a) < 4) ["aaa", "aaaaa"]
</code>```

答:
(< 3) is called a "section" and works only with infix operators. It's a syntactic sugar to write abbreviated functions. (< 3) is equivalent to \x -> x < 3 and (3 <) is equivalent to \x -> 3 < x.

Thus, (< 3) is a function of one argument that returns a Bool. Which is exactly what takeWhile expects.

With length, you have to write a function in full:

```<code>takeWhile (\x -> length x < 4) ["aaa", "aaaaa"]
</code>```

or define your own function you can curry:

```<code>shorterThan n x = length x < n

takeWhile (shorterThan 4) ["aaa", "aaaaa"]
</code>```

If you are feeling adventurous, you can write

```<code>takeWhile ((< 4) . length) ["aaa", "aaaaa"]
</code>```

or perhaps in a more readable fashion

```<code>(??) = flip (.)

takeWhile (length ?? (< 4)) ["aaa", "aaaaa"]
</code>```

Body:
An example of what I am talking about is takeWhile

takeWhile :: (a -> Bool) -> [a] -> [a]

Example usage

takeWhile (< 3) [1,2,3,4,1,2,3,4] == [1,2]

From what I can tell (< 3) becomes (a < 3) where a is the current item in the list being checked.

How is this done in Haskell and how would I be able to move where a goes so I could do something like

takeWhile ((length a) < 4) ["aaa", "aaaaa"]

Body:
(< 3) is called a "section" and works only with infix operators. It's a syntactic sugar to write abbreviated functions. (< 3) is equivalent to \x -> x < 3 and (3 <) is equivalent to \x -> 3 < x.

Thus, (< 3) is a function of one argument that returns a Bool. Which is exactly what takeWhile expects.

With length, you have to write a function in full:

takeWhile (\x -> length x < 4) ["aaa", "aaaaa"]

or define your own function you can curry:

shorterThan n x = length x < n

takeWhile (shorterThan 4) ["aaa", "aaaaa"]

If you are feeling adventurous, you can write

takeWhile ((< 4) . length) ["aaa", "aaaaa"]

or perhaps in a more readable fashion

(??) = flip (.)

takeWhile (length ?? (< 4)) ["aaa", "aaaaa"]


问:
ImageView not changing with setImageResource()?
Here's the code:

```<code>public class MainActivity extends AppCompatActivity implements View.OnClickListener{

  ImageView button;

 @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (ImageView)findViewById(R.id.startButton);
    button.setOnClickListener(this);
    button.setImageResource(R.drawable.play);
}
    public void onClick(View v) {
        button.setImageResource(R.drawable.pause);
    }
}
</code>```

Apparently if I put the button.setImageResource(R.drawable.pause);in the onCreate it works and changes images but not in the onClick? I tried debugging it and it ran the onClick code but didn't change the button image. I'm probably making a very stupid mistake but I can't figure it out.

xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.larry.app.MainActivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
   <ImageView
        android:id="@+id/startButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true" />
</LinearLayout>
</code>```

答:
Could you try this code and tell me the result then : </p>

```<code>public class MainActivity extends AppCompatActivity implements View.OnClickListener{

      ImageView button;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            button = (ImageView)findViewById(R.id.startButton);
            button.setOnClickListener(this);
            button.setImageResource(R.drawable.play);

        }
        public void onClick(View v) {
            button.setImageResource(R.drawable.pause);
        }
    }
</code>```

<p>and in the xml : </p>

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.larry.app.MainActivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
   <ImageView
        android:id="@+id/startButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true" />
</LinearLayout>
</code>```

Body:
Here's the code:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

  ImageView button;

 @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (ImageView)findViewById(R.id.startButton);
    button.setOnClickListener(this);
    button.setImageResource(R.drawable.play);
}
    public void onClick(View v) {
        button.setImageResource(R.drawable.pause);
    }
}

Apparently if I put the button.setImageResource(R.drawable.pause);in the onCreate it works and changes images but not in the onClick? I tried debugging it and it ran the onClick code but didn't change the button image. I'm probably making a very stupid mistake but I can't figure it out.

xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.larry.app.MainActivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
   <ImageView
        android:id="@+id/startButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true" />
</LinearLayout>

Body:
Could you try this code and tell me the result then :

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

      ImageView button;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            button = (ImageView)findViewById(R.id.startButton);
            button.setOnClickListener(this);
            button.setImageResource(R.drawable.play);

        }
        public void onClick(View v) {
            button.setImageResource(R.drawable.pause);
        }
    }

and in the xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.larry.app.MainActivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
   <ImageView
        android:id="@+id/startButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true" />
</LinearLayout>


问:
void pointer in function parameter
Consider following program:

```<code>#include <iostream>
void f(void* a)
{
    std::cout<<"(void*)fun is called\n";
    std::cout<<*(int*)a<<'\n';
}
int main()
{
    int a=9;
    void* b=(int*)&a;
    f(b);
    return 0;
}
</code>```

If I change the function call statement like this:

f(&b);

It still compiles fine & crashes at runtime. Why? What is the reason? Should I not get the compile time error? Because the correct way to call the function is f(b). right? Also, why it is allowed to pass NULL to a function whose parameter is of type (void*)?

Please correct me If I am missing something or understanding something incorrectly.

答:
I found myself here because I am working on a homework assignment that requests the same functionality. After combining each comment, this is what I came up with. </p>

```<code>// A function that accepts a void pointer
void f(void* a)
{
    std::cout<<"(void*)fun is called\n";
    std::cout<< "value for a: " << *(int*)a << '\n';
}

int main() {
    int a = 9;
    void* c = static_cast<int*>(&a);

    int b = 3;
    f(&b);
    f(c);
}
</code>```

Title: void pointer in function parameter

Body:
Consider following program:

#include <iostream>
void f(void* a)
{
    std::cout<<"(void*)fun is called\n";
    std::cout<<*(int*)a<<'\n';
}
int main()
{
    int a=9;
    void* b=(int*)&a;
    f(b);
    return 0;
}

If I change the function call statement like this:

f(&b);

It still compiles fine & crashes at runtime. Why? What is the reason? Should I not get the compile time error? Because the correct way to call the function is f(b). right? Also, why it is allowed to pass NULL to a function whose parameter is of type (void*)?

Please correct me If I am missing something or understanding something incorrectly.

Body:
I found myself here because I am working on a homework assignment that requests the same functionality. After combining each comment, this is what I came up with.

// A function that accepts a void pointer
void f(void* a)
{
    std::cout<<"(void*)fun is called\n";
    std::cout<< "value for a: " << *(int*)a << '\n';
}

int main() {
    int a = 9;
    void* c = static_cast<int*>(&a);

    int b = 3;
    f(&b);
    f(c);
}

ContentLicense: CC BY-SA 4.0


问:
Cannot store object of type _SwiftValue at name. Can only store objects of type NSNumber, NSString, NSDictionary, and NSArray.'
All, I am having some trouble with a Firebase driven app I am working on. The issue came about after upgrading my xCode to version 8. I have done some extensive research on this and gone through a few Stackoverflow topics trying to solve this, as it seems to be a very common error. I've gathered it is probably something super obvious that I am missing, excuse my stupidity.

This is the error I am receiving.

Cannot store object of type _SwiftValue at name. Can only store objects of type NSNumber, NSString, NSDictionary, and NSArray.'

This is my section of code it's occuring in I believe.

```<code>    func saveUser(withUID uid: String, username: String, value: [String:   String?], completion: @escaping (Error?) -> Void) {
         let values = ["/users/\(uid)": value, "/usernames/\(username)": uid] as [String: Any]
         root.updateChildValues(values) { (error, _) in
            completion(error)
        }
    }

    func updateUser(_ newValue: [String: String?]) {
        currentUser.updateChildValues(newValue)
    }

    // MARK: - Posts

    func createPost(_ _post: [String: String]) {

        let userUID = Auth.shared.currentUserUID
        let key = posts.childByAutoId().key

        var post = _post
        post["userUID"] = userUID

        // get current user's username
        currentUser.child("username").observeSingleEvent(of: .value, with: {     snapshot in
            if let username = snapshot.value as? String {
                post["username"] = username
                let values = [
                    "/posts/\(key)": post,
                    "/user-posts/\(userUID)/\(key)": post
                ]
                self.root.updateChildValues(values)
            }
        })

    }
</code>```

答: I got the same error in my code as well, just figured that out.  Make sure values is type of [String : String] instead of [String : String?].

Body:
All, I am having some trouble with a Firebase driven app I am working on. The issue came about after upgrading my xCode to version 8. I have done some extensive research on this and gone through a few Stackoverflow topics trying to solve this, as it seems to be a very common error. I've gathered it is probably something super obvious that I am missing, excuse my stupidity.

This is the error I am receiving.

Cannot store object of type _SwiftValue at name. Can only store objects of type NSNumber, NSString, NSDictionary, and NSArray.'

This is my section of code it's occuring in I believe.

    func saveUser(withUID uid: String, username: String, value: [String:   String?], completion: @escaping (Error?) -> Void) {
         let values = ["/users/\(uid)": value, "/usernames/\(username)": uid] as [String: Any]
         root.updateChildValues(values) { (error, _) in
            completion(error)
        }
    }

    func updateUser(_ newValue: [String: String?]) {
        currentUser.updateChildValues(newValue)
    }

    // MARK: - Posts

    func createPost(_ _post: [String: String]) {

        let userUID = Auth.shared.currentUserUID
        let key = posts.childByAutoId().key

        var post = _post
        post["userUID"] = userUID

        // get current user's username
        currentUser.child("username").observeSingleEvent(of: .value, with: {     snapshot in
            if let username = snapshot.value as? String {
                post["username"] = username
                let values = [
                    "/posts/\(key)": post,
                    "/user-posts/\(userUID)/\(key)": post
                ]
                self.root.updateChildValues(values)
            }
        })

    }


问:
How to get embedded video to be responsive in a shrunk browser
So I have the embedded video the way I like it in the full width browser, but when it is shrunk to the small size browser and below, I can't figure out a way to get to be responsive, so it stays centered in the browser.

I am using Bootstrap's grid system for the text next to it to be responsive. I would like for the video to be stacked underneath the text when the browser hits medium size and below, and I have successfully made the video centered with media query when it's in the medium  size browser, but can't get it centered in the small and extra small browser size. Does this make sense?

.section1Text {
  padding-top: 35px;
}

.section1Text h2 {
  font-weight: 100;
  font-size: 2.9em;
  letter-spacing: 1px;
}

.section1Btn {
  background-color: #2e3233;
  border-style: solid;
  border-width: 0px 0px 3px 0px;
  border-color: #121313;
  border-radius: 50px;
  padding-top: 15px;
  padding-bottom: 15px;
  margin-top: 30px;
  font-size: 1.45em;
  color: #ffffff;
  font-weight: 700;
  transition: all 0.3s ease-in-out 0s;
}

.video-responsive {
  padding-top: 45px;
  padding-bottom: 45px;
  float: right;
}

.video-responsive iframe {
  width: 560px;
  height: 315px;
}

/*section1 media queries*/

@media (max-width: 992px) {
  .video-responsive {
    padding-top: 45px;
    padding-bottom: 45px;
    margin-right: 35px;
  }
  .video-responsive iframe {
    width: 672px;
    height: 378px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="section1">
  <div class="container">
    <div class="row">
      <div class="section1Text col-md-4">
        <h2 class="text-center">What We Have to Offer</h2>
        <p class="text-center">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vel massa iaculis, posuere augue et, pharetra ipsum. Suspendisse metus ex, pellentesque id dolor in, vehicula varius tortor. Nam auctor ante nisi.</p>
        <div class="col-xs-8 col-xs-offset-2">
          Learn More
        </div>
      </div>
      <div class="video-responsive">
        <iframe width="560px" height="315px" src="https://www.youtube.com/embed/bsY2GdBEvSA?rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
      </div>
    </div>
  </div>
</section></code>```

答:
For the videos responsiveness, use percents (example below). Mess around with the percents until it works the way you would like it. You may also need a container to put the video in.</p>

```<code>.video-responsive iframe {
        width: 100%;
        height: 50%;
    }
</code>```

Body:
So I have the embedded video the way I like it in the full width browser, but when it is shrunk to the small size browser and below, I can't figure out a way to get to be responsive, so it stays centered in the browser.

I am using Bootstrap's grid system for the text next to it to be responsive. I would like for the video to be stacked underneath the text when the browser hits medium size and below, and I have successfully made the video centered with media query when it's in the medium  size browser, but can't get it centered in the small and extra small browser size. Does this make sense?

.section1Text {
  padding-top: 35px;
}

.section1Text h2 {
  font-weight: 100;
  font-size: 2.9em;
  letter-spacing: 1px;
}

.section1Btn {
  background-color: #2e3233;
  border-style: solid;
  border-width: 0px 0px 3px 0px;
  border-color: #121313;
  border-radius: 50px;
  padding-top: 15px;
  padding-bottom: 15px;
  margin-top: 30px;
  font-size: 1.45em;
  color: #ffffff;
  font-weight: 700;
  transition: all 0.3s ease-in-out 0s;
}

.video-responsive {
  padding-top: 45px;
  padding-bottom: 45px;
  float: right;
}

.video-responsive iframe {
  width: 560px;
  height: 315px;
}

/*section1 media queries*/

@media (max-width: 992px) {
  .video-responsive {
    padding-top: 45px;
    padding-bottom: 45px;
    margin-right: 35px;
  }
  .video-responsive iframe {
    width: 672px;
    height: 378px;
  }
}

What We Have to Offer

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vel massa iaculis, posuere augue et, pharetra ipsum. Suspendisse metus ex, pellentesque id dolor in, vehicula varius tortor. Nam auctor ante nisi.

          Learn More

Body:
For the videos responsiveness, use percents (example below). Mess around with the percents until it works the way you would like it. You may also need a container to put the video in.

.video-responsive iframe {
        width: 100%;
        height: 50%;
    }


问:
Javascript: function not defined with button onclick event?
Learning JS, trying to get this little survey to work, but I get a "function not defined" error at HTML element onclick.  Can't figure out why, it seems like the function is defined and I can't find any syntax errors.  I also get an error saying that "soda is not defined," but it seems like that variable is defined as an object in the array.

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

<h3>What cats are in the room?</h3>

Sophie: <input type="checkbox" id="sophieCheck">
<br></br>
Soda: <input type="checkbox" id="sodaCheck">
<br></br>
Mr.: <input type="checkbox" id="mrCheck">
<br></br>

<button onclick="catsInTheRoom()">Try it</button>
<br></br>

<p id="cats"></p>

<script>
function catsInTheRoom() {

    var myCats = [ soda, mr, sophie ];

    if (getElementById("sodaCheck").checked) {
        myCats[0] = 1;
    } else {
        myCats[0] = 0;
    }
    if (getElementById("sophieCheck").checked) {
        myCats[2] = 10;
    } else {
        myCats[2] = 0;
    }
    if (getElementById("mrCheck").checked) {
        myCats[1] = 20;
    } else {
        myCats[1] = 0;
    }

    getElementById("cats").innerHTML = myCats[0] + myCats[1]  + myCats[2];
}

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

I created the array so I can use the numerical values for a switch statement to produce different text based on which checkboxes are checked.

This simpler version worked:

```<code>Sophie: <input type="checkbox" id="sohpieCheck">
<br></br>
Soda: <input type="checkbox" id="sodaCheck">
<br></br>
Mr.: <input type="checkbox" id="mrCheck">
<br></br>

<button onclick="myFunction()">Try it</button>

<p id="cats"></p>

<script>

function myFunction() {
    var soda = document.getElementById("sodaCheck").checked;

    if (soda) {
        catBehavior = "Cats are being rascals.";
    } else {
        catBehavior = "Cats are behaving nicely.";
    }

    document.getElementById("cats").innerHTML = catBehavior;
}

</script>
</code>```

Why does the second example work, but not the first one?

答:
Your code has some errors. Please, check the fixes:

 tags are self closed.

soda, mr and sophie must be strings.

getElementById belongs to the document object (or any other DOM node).

What cats are in the room?

Sophie: <input type="checkbox" id="sophieCheck">

Soda: <input type="checkbox" id="sodaCheck">

Mr.: <input type="checkbox" id="mrCheck">

<button onclick="catsInTheRoom()">Try it</button>

```

Body:
Learning JS, trying to get this little survey to work, but I get a "function not defined" error at HTML element onclick.  Can't figure out why, it seems like the function is defined and I can't find any syntax errors.  I also get an error saying that "soda is not defined," but it seems like that variable is defined as an object in the array.

What cats are in the room?

Sophie: <input type="checkbox" id="sophieCheck">

Soda: <input type="checkbox" id="sodaCheck">

Mr.: <input type="checkbox" id="mrCheck">

<button onclick="catsInTheRoom()">Try it</button>

I created the array so I can use the numerical values for a switch statement to produce different text based on which checkboxes are checked.

This simpler version worked:

Sophie: <input type="checkbox" id="sohpieCheck">

Soda: <input type="checkbox" id="sodaCheck">

Mr.: <input type="checkbox" id="mrCheck">

<button onclick="myFunction()">Try it</button>

Why does the second example work, but not the first one?

Body:
Your code has some errors. Please, check the fixes:

<br> tags are self closed.

soda, mr and sophie must be strings.

getElementById belongs to the document object (or any other DOM node).

<h3>What cats are in the room?</h3>

Sophie: <input type="checkbox" id="sophieCheck">
<br>
Soda: <input type="checkbox" id="sodaCheck">
<br>
Mr.: <input type="checkbox" id="mrCheck">
<br>

<button onclick="catsInTheRoom()">Try it</button>
<br>

<p id="cats"></p>
<script>
function catsInTheRoom() {

var myCats = [ 'soda', 'mr', 'sophie' ];

if (document.getElementById("sodaCheck").checked) {
myCats[0] = 1;
} else {
myCats[0] = 0;
}
if (document.getElementById("sophieCheck").checked) {
myCats[2] = 10;
} else {
myCats[2] = 0;
}
if (document.getElementById("mrCheck").checked) {
myCats[1] = 20;
} else {
myCats[1] = 0;
}

document.getElementById("cats").innerHTML = myCats[0] + myCats[1]  + myCats[2];
}
</script>


问:
colMeans of successive lines in a matrix in R
I have a matrix of 30 rows:

```<code>set.seed(1234)
m = matrix(rnorm(300), 0)
</code>```

I want to calculate the colMeans of each five successive lines.
For example:

colMeans of rows 1,2,3,4,5

colMeans of rows 2,3,4,5,6

colMeans of rows 3,4,5,6,7

...

colMeans of rows 16,17,18,19,20

How I can do it?

答:
Functions from the package zoo can be useful here. Try

```<code>set.seed(1234)
m = matrix(rnorm(300), nrow = 30)
zoo::rollmean(m, 5) # option 1
zoo::rollapply(m, 5, mean) # option 2
</code>```

Body:
I have a matrix of 30 rows:

set.seed(1234)
m = matrix(rnorm(300), 0)

I want to calculate the colMeans of each five successive lines.
For example:

colMeans of rows 1,2,3,4,5

colMeans of rows 2,3,4,5,6

colMeans of rows 3,4,5,6,7

...

colMeans of rows 16,17,18,19,20

How I can do it?

Body:
Functions from the package zoo can be useful here. Try

set.seed(1234)
m = matrix(rnorm(300), nrow = 30)
zoo::rollmean(m, 5) # option 1
zoo::rollapply(m, 5, mean) # option 2


问:
How long since last time app was opened in iOS?
How can I tell the time from the last time my app was open?  Can this still be monitored even my app is not running in the background?

Thanks.

答: In your application delegates - (void)applicationDidEnterBackground:(UIApplication *)application method, just write the current time to a file. Then, in either applicationWillEnterForeground: or applicationDidFinishLaunching, read this file and compare with the current time. The difference will tell you how long since your application was last foremost.

ContentLicense: CC BY-SA 2.5


问:
how to separated One column to two with cases
I have a table and I would want to separate the data to multiple columns, how i can do it ?

I tried this:

```<code> select a.[batch],a.[Doc_Type],
    Soaking Out =
      CASE a.[Doc_Type]
         WHEN 'BB' THEN 'Soaking Out'
      END,

        Soaking In =
      CASE a.[Doc_Type]
         WHEN 'AA' THEN 'Soaking In'
      END,

     FROM Transaction_Hdr a JOIN Transaction_dtl b
on a.Doc_Number=b.Doc_Number
</code>```

答:
Use CASE() and Modulus as below, assuming that Batch is always inceremnted by 1 and Doc_Type has always those two values AA and BB in the same order:

```<code>CREATE TABLE Data (
    Doc_Type VARCHAR(10),
    Batch INT,
    Qty DECIMAL(4,2)
    );
INSERT INTO Data VALUES
('AA', 1, 20.5),
('BB', 2, 10  ),
('AA', 3, 6   ),
('BB', 4, 7   ),
('AA', 5, 8   );

SELECT D.Doc_Type, D.Batch,
       CASE WHEN D.Batch % 2 = 0 Then 0 ELSE D.Qty END AS Soaking_In,
       CASE WHEN D.Batch % 2 = 1 Then 0 ELSE D.Qty END AS Soaking_Out
FROM Data D;
</code>```

Results:

```<code>+----------+-------+------------+-------------+
| Doc_Type | Batch | Soaking_In | Soaking_Out |
+----------+-------+------------+-------------+
| AA       |     1 |      20,50 |        0,00 |
| BB       |     2 |       0,00 |       10,00 |
| AA       |     3 |       6,00 |        0,00 |
| BB       |     4 |       0,00 |        7,00 |
| AA       |     5 |       8,00 |        0,00 |
+----------+-------+------------+-------------+
</code>```

Demo

Body:
I have a table and I would want to separate the data to multiple columns, how i can do it ?

I tried this:

 select a.[batch],a.[Doc_Type],
    Soaking Out =
      CASE a.[Doc_Type]
         WHEN 'BB' THEN 'Soaking Out'
      END,

        Soaking In =
      CASE a.[Doc_Type]
         WHEN 'AA' THEN 'Soaking In'
      END,

     FROM Transaction_Hdr a JOIN Transaction_dtl b
on a.Doc_Number=b.Doc_Number

Body:
Use CASE() and Modulus as below, assuming that Batch is always inceremnted by 1 and Doc_Type has always those two values AA and BB in the same order:

CREATE TABLE Data (
    Doc_Type VARCHAR(10),
    Batch INT,
    Qty DECIMAL(4,2)
    );
INSERT INTO Data VALUES
('AA', 1, 20.5),
('BB', 2, 10  ),
('AA', 3, 6   ),
('BB', 4, 7   ),
('AA', 5, 8   );

SELECT D.Doc_Type, D.Batch,
       CASE WHEN D.Batch % 2 = 0 Then 0 ELSE D.Qty END AS Soaking_In,
       CASE WHEN D.Batch % 2 = 1 Then 0 ELSE D.Qty END AS Soaking_Out
FROM Data D;

Results:

+----------+-------+------------+-------------+
| Doc_Type | Batch | Soaking_In | Soaking_Out |
+----------+-------+------------+-------------+
| AA       |     1 |      20,50 |        0,00 |
| BB       |     2 |       0,00 |       10,00 |
| AA       |     3 |       6,00 |        0,00 |
| BB       |     4 |       0,00 |        7,00 |
| AA       |     5 |       8,00 |        0,00 |
+----------+-------+------------+-------------+

Demo


问:
PHP - How do I access specific array values in nested array?
I have an array like this:

```<code>    Array (
    [0] => Array (
        [0] => 510
        [1] => 984
        [2] => 1045
        [3] => 2068
        [4] => 1054
        [5] => 673
        )
    [1] => Array (
        [0] => 1163
        [1] => 1982
        [2] => 2067
        [3] => 3989
        [4] => 1940
        [5] => 1242
        )
    [2] => Array (
        [0] => june
        [1] => july
        [2] => august
        [3] => september
        [4] => october
        [5] => november
        )
    )
</code>```

I want to access only one of the arrays within the array at a time and echo them out.

For example, I would get: 510, 984, 1045, 2068, 1054, and 673 as one result.

I've looked at multiple threads and answers but nothing that quite solves my issue, I've been able to print out all the values but I just want some specifically.

I'd store it in the variable: $array_item

My most recent attempt was:

```<code>foreach ($array_item as $inner) {
if (is_array($inner)) {
    foreach ($inner[0] as $value) {
        echo "$value \n";
    }
}
}
</code>```

Which gives me: Warning: Invalid argument supplied for foreach().

I thought for sure that would work, what am I doing wrong?

答:
You never can tell what could solve a problem

```<code>$array_group = array();

if (isset($array_item[0]) and is_array($array_item[0])) {
foreach ($array_item[0] as $value) {
    $array_group[] = $value;
}
</code>```

$array_group should output

```<code>Array
(
    [0] => 510
    [1] => 984
    [2] => 1045
    [3] => 2068
    [4] => 1054
    [5] => 673
)
</code>```

Body:
I have an array like this:

    Array (
    [0] => Array (
        [0] => 510
        [1] => 984
        [2] => 1045
        [3] => 2068
        [4] => 1054
        [5] => 673
        )
    [1] => Array (
        [0] => 1163
        [1] => 1982
        [2] => 2067
        [3] => 3989
        [4] => 1940
        [5] => 1242
        )
    [2] => Array (
        [0] => june
        [1] => july
        [2] => august
        [3] => september
        [4] => october
        [5] => november
        )
    )

I want to access only one of the arrays within the array at a time and echo them out.

For example, I would get: 510, 984, 1045, 2068, 1054, and 673 as one result.

I've looked at multiple threads and answers but nothing that quite solves my issue, I've been able to print out all the values but I just want some specifically.

I'd store it in the variable: $array_item

My most recent attempt was:

foreach ($array_item as $inner) {
if (is_array($inner)) {
    foreach ($inner[0] as $value) {
        echo "$value \n";
    }
}
}

Which gives me: Warning: Invalid argument supplied for foreach().

I thought for sure that would work, what am I doing wrong?

Body:
You never can tell what could solve a problem

$array_group = array();

if (isset($array_item[0]) and is_array($array_item[0])) {
foreach ($array_item[0] as $value) {
    $array_group[] = $value;
}

$array_group should output

Array
(
    [0] => 510
    [1] => 984
    [2] => 1045
    [3] => 2068
    [4] => 1054
    [5] => 673
)


问:
PyQt5 loading spinner halts on post request
I'm using the QtWaitingSpinner found here: https://github.com/snowwlex/QtWaitingSpinner. You can create and start a spinner like so: spinner = QtWaitingSpinner(self); spinner.start(). Unfortunately when I try to make a POST request from my GUI, the spinner halts until a response has been returned. Consequently I don't see the spinner at all, or if I start the spinner prematurely it stops spinning while it waits for the response. I think I'll have to use some sort of asynchronous method like QThread or asyncio but it's unclear what the best way of getting around this is. If anyone can show me the best way to handle it I'd be grateful. Here is a simplified version of what I'm doing:

```<code>class Obj(QDialog):
    # some button calls this function when pressed
    def submit(self):
        #start spinner
        spinner = QtWaitingSpinner(self)
        spinner.start()

        # post some data to some url, spinner should spin
        r = requests.post('some_url.com', json=some_data)

        # stop spinner
        spinner.stop()
</code>```

答:
The problem you are requests is blocking the Qt loop, so elements like QTimer do not work. One solution is to run that task on another thread, a simple way to do it is using QRunnable and QThreadPool.

```<code>class RequestRunnable(QRunnable):
    def __init__(self, url, json, dialog):
        QRunnable.__init__(self)
        self.mUrl = url
        self.mJson = json
        self.w = dialog

    def run(self):
        r = requests.post(self.mUrl, json=self.mJson)
        QMetaObject.invokeMethod(self.w, "setData",
                                 Qt.QueuedConnection,
                                 Q_ARG(str, r.text))

class Dialog(QDialog):
    def __init__(self, *args, **kwargs):
        QDialog.__init__(self, *args, **kwargs)
        self.setLayout(QVBoxLayout())
        btn = QPushButton("Submit", self)
        btn.clicked.connect(self.submit)
        self.spinner = QtWaitingSpinner(self)

        self.layout().addWidget(btn)
        self.layout().addWidget(self.spinner)

    def submit(self):
        self.spinner.start()
        runnable = RequestRunnable("https://api.github.com/some/endpoint",
                                   {'some': 'data'},
                                   self)
        QThreadPool.globalInstance().start(runnable)

    @pyqtSlot(str)
    def setData(self, data):
        print(data)
        self.spinner.stop()
        self.adjustSize()
</code>```

A complete example can be found in the following link

Body:
I'm using the QtWaitingSpinner found here: https://github.com/snowwlex/QtWaitingSpinner. You can create and start a spinner like so: spinner = QtWaitingSpinner(self); spinner.start(). Unfortunately when I try to make a POST request from my GUI, the spinner halts until a response has been returned. Consequently I don't see the spinner at all, or if I start the spinner prematurely it stops spinning while it waits for the response. I think I'll have to use some sort of asynchronous method like QThread or asyncio but it's unclear what the best way of getting around this is. If anyone can show me the best way to handle it I'd be grateful. Here is a simplified version of what I'm doing:

class Obj(QDialog):
    # some button calls this function when pressed
    def submit(self):
        #start spinner
        spinner = QtWaitingSpinner(self)
        spinner.start()

        # post some data to some url, spinner should spin
        r = requests.post('some_url.com', json=some_data)

        # stop spinner
        spinner.stop()

Body:
The problem you are requests is blocking the Qt loop, so elements like QTimer do not work. One solution is to run that task on another thread, a simple way to do it is using QRunnable and QThreadPool.

class RequestRunnable(QRunnable):
    def __init__(self, url, json, dialog):
        QRunnable.__init__(self)
        self.mUrl = url
        self.mJson = json
        self.w = dialog

    def run(self):
        r = requests.post(self.mUrl, json=self.mJson)
        QMetaObject.invokeMethod(self.w, "setData",
                                 Qt.QueuedConnection,
                                 Q_ARG(str, r.text))

class Dialog(QDialog):
    def __init__(self, *args, **kwargs):
        QDialog.__init__(self, *args, **kwargs)
        self.setLayout(QVBoxLayout())
        btn = QPushButton("Submit", self)
        btn.clicked.connect(self.submit)
        self.spinner = QtWaitingSpinner(self)

        self.layout().addWidget(btn)
        self.layout().addWidget(self.spinner)

    def submit(self):
        self.spinner.start()
        runnable = RequestRunnable("https://api.github.com/some/endpoint",
                                   {'some': 'data'},
                                   self)
        QThreadPool.globalInstance().start(runnable)

    @pyqtSlot(str)
    def setData(self, data):
        print(data)
        self.spinner.stop()
        self.adjustSize()

A complete example can be found in the following link


问:
Swift 3 Firebase - (setValue:) Cannot store object of type _SwiftValue at content
I've seen this question asked multiple times, but can't seem to figure out how to use those answers to solve the problem in my code. This is the current code I'm using:

```<code>if let postContent = postAlert.textFields?.first?.text {
    let post = Post(content: postContent, addedByUser: "Max Kortge")

    let postRef = self.dbRef.child(postContent.lowercased())

    postRef.setValue(post.toAnyObject()) //error here
}
</code>```

I presume that the error in the console means the line where I've commented 'error here'.

The method toAnyObject is below:

```<code>func toAnyObject() -> Any {
    return ["content":content, "addedByUser":addedByUser] as Any
}
</code>```

The full console error is below:

Terminating app due to uncaught exception 'InvalidFirebaseData', reason: '(setValue:) Cannot store object of type _SwiftValue at content. Can only store objects of type NSNumber, NSString, NSDictionary, and NSArray.'

答: make sure 'post' in your code is [String : String] instead of [String : String?]</p>

Body:
I've seen this question asked multiple times, but can't seem to figure out how to use those answers to solve the problem in my code. This is the current code I'm using:

if let postContent = postAlert.textFields?.first?.text {
    let post = Post(content: postContent, addedByUser: "Max Kortge")

    let postRef = self.dbRef.child(postContent.lowercased())

    postRef.setValue(post.toAnyObject()) //error here
}

I presume that the error in the console means the line where I've commented 'error here'.

The method toAnyObject is below:

func toAnyObject() -> Any {
    return ["content":content, "addedByUser":addedByUser] as Any
}

The full console error is below:

Terminating app due to uncaught exception 'InvalidFirebaseData', reason: '(setValue:) Cannot store object of type _SwiftValue at content. Can only store objects of type NSNumber, NSString, NSDictionary, and NSArray.'