问:
The function tries to reference a deleted function, but the function is set to delete already
I am trying to check if all of my functions in the errormessage class are working in the main function, but the problem is that I get an error message at "T" and "e" located beside cout << in the Main.cpp

Saying I am trying to reference a deleted function sict::ErrorMessage::ErrorMessage(const sict::ErrorMessage&).

However, I already set this function to delete in the header. Any idea as to why this error occurs?

Header file

```<code>#ifndef SICT_ERROR_H_
#define SICT_ERROR_H_
namespace sict {
    class ErrorMessage {
        char* m_message;
    public:

        ErrorMessage(const char* errorMessage = nullptr);
        ErrorMessage(const ErrorMessage& em) = delete;
        ErrorMessage& operator=(const ErrorMessage& em) = delete;
        virtual ~ErrorMessage();
        void clear();
        bool isClear() const;
        void message(const char* str);
        const char* message() const;
    };
    std::ostream& operator<<(std::ostream& ostr, ErrorMessage);
}
#endif
</code>```

Cpp file

```<code>#include "ErrorMessage.h"
#include <iostream>
namespace sict {

    ErrorMessage::ErrorMessage(const char* errorMessage) {
        m_message = nullptr;
        message(errorMessage);
    }
    void ErrorMessage::clear() {
        delete[] m_message;
        m_message = nullptr;
    }
    void ErrorMessage::message(const char* str) {
        delete[] m_message;
        m_message = new char[strlen(str) + 1];
        strcpy(m_message, str);
    }
    const char* ErrorMessage::message() const {
        return m_message;
    }
    ErrorMessage::~ErrorMessage() {
        clear();
    }
    bool ErrorMessage::isClear() const {
        if (m_message == nullptr) {
            return true;
        }
        return false;
    }
    std::ostream& operator<<(std::ostream& ostr, ErrorMessage error) {
        if (!(error.isClear())) {
            ostr << error.message();
        }
        return ostr;
    }

}
</code>```

Main.cpp

```<code>#include <iostream>
#include "ErrorMessage.h"

using namespace std;
using namespace sict;

int main() {
    ErrorMessage T("Testing Error Message Module");
    ErrorMessage e;
    int ret = 0;
    bool ok = true;
    cout << T << endl << e << endl << "isClear(): " << (e.isClear() ? "Passed!" : "Failed!") << endl;
    if (!e.isClear()) ok = false;
    cout << endl;
    cout << "===========| Long Message\r";
    for (int i = 0; i < 10000000; i++) {
        if (i % 1000000 == 0) {
            cout << "*";
            cout.flush();
        }
        e.message("Some error message that is really long long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long");
    }
    cout << '*' << endl;
    cout << e << endl << "isClear(): " << (e.isClear() ? "Failed!" : "Passed!") << endl;
    if (e.isClear()) ok = false;
    cout << endl;

    e.message("Short Message");
    cout << e << endl << e.message() << endl << "isClear(): " << (e.isClear() ? "Failed!" : "Passed!") << endl;
    if (e.isClear()) ok = false;

    e.clear();
    cout << e << endl << "isClear(): " << (e.isClear() ? "Passed!" : "Failed!") << endl;
    if (!e.isClear()) ok = false;
    cout << endl;

    if (ok) {
        cout << "You passed all the tests!" << endl;
    }
    else {
        cout << "You did not pass all the tests" << endl;
        ret = 1;
    }

    return ret;
}
</code>```

答:
Your problem is here:

```<code>std::ostream& operator<<(std::ostream& ostr, ErrorMessage error)
</code>```

Your << is accepting an ErrorMessage by value so it must copy T and e in order to be passed to the function (and therefore attempting to use the deleted copy constructor)

Try passing by const reference:

```<code>std::ostream& operator<<(std::ostream& ostr, const ErrorMessage& error)
</code>```

Body:
I am trying to check if all of my functions in the errormessage class are working in the main function, but the problem is that I get an error message at "T" and "e" located beside cout << in the Main.cpp

Saying I am trying to reference a deleted function sict::ErrorMessage::ErrorMessage(const sict::ErrorMessage&).

However, I already set this function to delete in the header. Any idea as to why this error occurs?

Header file

#ifndef SICT_ERROR_H_
#define SICT_ERROR_H_
namespace sict {
    class ErrorMessage {
        char* m_message;
    public:

        ErrorMessage(const char* errorMessage = nullptr);
        ErrorMessage(const ErrorMessage& em) = delete;
        ErrorMessage& operator=(const ErrorMessage& em) = delete;
        virtual ~ErrorMessage();
        void clear();
        bool isClear() const;
        void message(const char* str);
        const char* message() const;
    };
    std::ostream& operator<<(std::ostream& ostr, ErrorMessage);
}
#endif

Cpp file

#include "ErrorMessage.h"
#include <iostream>
namespace sict {

    ErrorMessage::ErrorMessage(const char* errorMessage) {
        m_message = nullptr;
        message(errorMessage);
    }
    void ErrorMessage::clear() {
        delete[] m_message;
        m_message = nullptr;
    }
    void ErrorMessage::message(const char* str) {
        delete[] m_message;
        m_message = new char[strlen(str) + 1];
        strcpy(m_message, str);
    }
    const char* ErrorMessage::message() const {
        return m_message;
    }
    ErrorMessage::~ErrorMessage() {
        clear();
    }
    bool ErrorMessage::isClear() const {
        if (m_message == nullptr) {
            return true;
        }
        return false;
    }
    std::ostream& operator<<(std::ostream& ostr, ErrorMessage error) {
        if (!(error.isClear())) {
            ostr << error.message();
        }
        return ostr;
    }

}

Main.cpp

#include <iostream>
#include "ErrorMessage.h"

using namespace std;
using namespace sict;

int main() {
    ErrorMessage T("Testing Error Message Module");
    ErrorMessage e;
    int ret = 0;
    bool ok = true;
    cout << T << endl << e << endl << "isClear(): " << (e.isClear() ? "Passed!" : "Failed!") << endl;
    if (!e.isClear()) ok = false;
    cout << endl;
    cout << "===========| Long Message\r";
    for (int i = 0; i < 10000000; i++) {
        if (i % 1000000 == 0) {
            cout << "*";
            cout.flush();
        }
        e.message("Some error message that is really long long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long"
            " long  long  long  long  long  long  long  long  long  long  long  long  long");
    }
    cout << '*' << endl;
    cout << e << endl << "isClear(): " << (e.isClear() ? "Failed!" : "Passed!") << endl;
    if (e.isClear()) ok = false;
    cout << endl;

    e.message("Short Message");
    cout << e << endl << e.message() << endl << "isClear(): " << (e.isClear() ? "Failed!" : "Passed!") << endl;
    if (e.isClear()) ok = false;

    e.clear();
    cout << e << endl << "isClear(): " << (e.isClear() ? "Passed!" : "Failed!") << endl;
    if (!e.isClear()) ok = false;
    cout << endl;

    if (ok) {
        cout << "You passed all the tests!" << endl;
    }
    else {
        cout << "You did not pass all the tests" << endl;
        ret = 1;
    }

    return ret;
}

Body:
Your problem is here:

std::ostream& operator<<(std::ostream& ostr, ErrorMessage error)

Your << is accepting an ErrorMessage by value so it must copy T and e in order to be passed to the function (and therefore attempting to use the deleted copy constructor)

Try passing by const reference:

std::ostream& operator<<(std::ostream& ostr, const ErrorMessage& error)


来源: stackexchange

问:
Converting massive binary input string into character string C

I'm not familiar with C at all so this might be a simple problem to solve. I'm trying to take an input char* array of binary character sequences, ex. "0100100001101001", and output its relative string ("Hi"). The problem I'm having is coming up with a way to split the input into seperate strings of length 8 and then convert them individually to ulimately get the full output string.

```<code>char* binaryToString(char* b){
    char binary[8];
    for(int i=0; i<8; ++i){
    binary[i] = b[i];
}
printf("%s", binary);
}
</code>```

I'm aware of how to convert 8-bit into its character, I just need a way to split the input string in a way that will allow me to convert massive inputs of 8-bit binary characters.

Any help is appreciated... thanks!

答:
I just need a way to split the input string in a way that will allow me to convert massive inputs of 8-bit binary characters.

You can use strncpy() to copy the sequence of '0' and '1' in a chunk of 8 characters at a time from the input string, something like this:

```<code>//get the size of input string
size_t len = strlen(b);

//Your input array of '0' and '1' and every sequence of 8 bytes represents a character
unsigned int num_chars = len/8;

//Take a temporary pointer and point it to input string
const char *tmp = b;

//Now copy the 8 chars from input string to buffer "binary"
for(int i=0; i<num_chars; ++i){
    strncpy(binary, tmp+(i*8), 8);

    //do your stuff with the 8 chars copied from input string to "binary" buffer

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm not familiar with C at all so this might be a simple problem to solve. I'm trying to take an input char* array of binary character sequences, ex. "0100100001101001", and output its relative string ("Hi"). The problem I'm having is coming up with a way to split the input into seperate strings of length 8 and then convert them individually to ulimately get the full output string.

char* binaryToString(char* b){
    char binary[8];
    for(int i=0; i<8; ++i){
    binary[i] = b[i];
}
printf("%s", binary);
}

I'm aware of how to convert 8-bit into its character, I just need a way to split the input string in a way that will allow me to convert massive inputs of 8-bit binary characters.

Any help is appreciated... thanks!

Body:
I just need a way to split the input string in a way that will allow me to convert massive inputs of 8-bit binary characters.

You can use strncpy() to copy the sequence of '0' and '1' in a chunk of 8 characters at a time from the input string, something like this:

//get the size of input string
size_t len = strlen(b);

//Your input array of '0' and '1' and every sequence of 8 bytes represents a character
unsigned int num_chars = len/8;

//Take a temporary pointer and point it to input string
const char *tmp = b;

//Now copy the 8 chars from input string to buffer "binary"
for(int i=0; i<num_chars; ++i){
    strncpy(binary, tmp+(i*8), 8);

    //do your stuff with the 8 chars copied from input string to "binary" buffer

}


问:
How to sort json bottom to top
I want to sort json bottom to top, I can parse json top to bottom but I need bottom to top.

Is it possible? How can I do that?

I can parse json with this codes:

MainActivity file:

```<code>public class MainActivity extends AppCompatActivity {

    private ListView lv;
    private static String url = "https://api.androidhive.info/contacts/";

    ArrayList<HashMap<String, String>> contactList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        contactList = new ArrayList<>();

        lv = (ListView) findViewById(R.id.list);

        new GetContacts().execute();
    }

    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            String jsonStr = sh.makeServiceCall(url);
            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    JSONArray contacts = jsonObj.getJSONArray("contacts");
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);

                        String name = c.getString("name");
                        String email = c.getString("email");

                        HashMap<String, String> contact = new HashMap<>();

                        contact.put("name", name);
                        contact.put("email", email);
                        contactList.add(contact);
                    }
                } catch (final JSONException e) {
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, contactList,
                    R.layout.list_item, new String[]{"name", "email"}, new int[]{R.id.name,
                    R.id.email});

            lv.setAdapter(adapter);
        }
    }
}
</code>```

HttpHandler file:

```<code>public class HttpHandler {

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (Exception e) {
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}
</code>```

json file:

```<code>{
    "contacts": [
        {
                "name": "leonardo",
                "email": "leonardo@gmail.com"
                }
        },
        {
                "name": "Johnny",
                "email": "johnny@gmail.com"
                }
        },
        {
                "name": "jack",
                "email": "jack@gmail.com"
                }
        }
        {
                "name": "paul",
                "email": "paul@gmail.com"
                }
        }
  ]
}
</code>```

output:

```<code>leonardo - leonardo@gmail.com
-----------------------------
johnny - johnny@gmail.com
-----------------------------
jack - jack@gmail.com
-----------------------------
paul - paul@gmail.com
</code>```

but firstly I want to show the last item like this:

```<code>paul - paul@gmail.com
-----------------------------
jack - jack@gmail.com
-----------------------------
johnny - johnny@gmail.com
-----------------------------
leonardo - leonardo@gmail.com
</code>```

答:
Simple make loop reverse:</p>

```<code> for (int i = contacts.length()-1; i>=0; i--)
 {
      JSONObject c = contacts.getJSONObject(i);
      String name = c.getString("name");
      String email = c.getString("email");
      HashMap<String, String> contact = new HashMap<>();
      contact.put("name", name);
      contact.put("email", email);
      contactList.add(contact);
 }
</code>```

Title: How to sort json bottom to top

Body:
I want to sort json bottom to top, I can parse json top to bottom but I need bottom to top.

Is it possible? How can I do that?

I can parse json with this codes:

MainActivity file:

public class MainActivity extends AppCompatActivity {

    private ListView lv;
    private static String url = "https://api.androidhive.info/contacts/";

    ArrayList<HashMap<String, String>> contactList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        contactList = new ArrayList<>();

        lv = (ListView) findViewById(R.id.list);

        new GetContacts().execute();
    }

    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            String jsonStr = sh.makeServiceCall(url);
            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    JSONArray contacts = jsonObj.getJSONArray("contacts");
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);

                        String name = c.getString("name");
                        String email = c.getString("email");

                        HashMap<String, String> contact = new HashMap<>();

                        contact.put("name", name);
                        contact.put("email", email);
                        contactList.add(contact);
                    }
                } catch (final JSONException e) {
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, contactList,
                    R.layout.list_item, new String[]{"name", "email"}, new int[]{R.id.name,
                    R.id.email});

            lv.setAdapter(adapter);
        }
    }
}

HttpHandler file:

public class HttpHandler {

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (Exception e) {
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

json file:

{
    "contacts": [
        {
                "name": "leonardo",
                "email": "leonardo@gmail.com"
                }
        },
        {
                "name": "Johnny",
                "email": "johnny@gmail.com"
                }
        },
        {
                "name": "jack",
                "email": "jack@gmail.com"
                }
        }
        {
                "name": "paul",
                "email": "paul@gmail.com"
                }
        }
  ]
}

output:

leonardo - leonardo@gmail.com
-----------------------------
johnny - johnny@gmail.com
-----------------------------
jack - jack@gmail.com
-----------------------------
paul - paul@gmail.com

but firstly I want to show the last item like this:

paul - paul@gmail.com
-----------------------------
jack - jack@gmail.com
-----------------------------
johnny - johnny@gmail.com
-----------------------------
leonardo - leonardo@gmail.com

Body:
Simple make loop reverse:

 for (int i = contacts.length()-1; i>=0; i--)
 {
      JSONObject c = contacts.getJSONObject(i);
      String name = c.getString("name");
      String email = c.getString("email");
      HashMap<String, String> contact = new HashMap<>();
      contact.put("name", name);
      contact.put("email", email);
      contactList.add(contact);
 }


问:
Using Mockito for API Stubbing Load Test
I have a Spring Boot application with a REST API. Behind the scenes it uses a vended SDK to call the vendors service. I need to run load tests on my application, but don’t want to call the vendor API and accidentally crash their system during testing.

Is it possible to use Mockito outside of a JUnit test to create a mock for the vendor SDK objects during the normal application runtime?

I figured I would use a profile based configuration beam to enable the mocked object when profile is “performance-test”. But I can find no article/discussion/mention of anyone using Mockito this way and it is making me second guess my approach. Thoughts?

答:
You probably should look for using wiremock or similar software to mock the vendor service, like here: Integration Testing with a fake server

Wiremock is a stub server that you can conveniently start/stop from within JUnit tests. It acts like the remote server when you set up responses. The documentation is really good, I do not want to copy&paste all of it here.

Just a sample:

```<code>public class MyTest {
    @Rule
    public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort().dynamicHttpsPort());

    @Test
    public void exampleTest() {
        stubFor(get(urlEqualTo("/my/resource"))
                .willReturn(aResponse()
                    .withStatus(200)
                    .withBody("<response>Some content</response>")));

        ...
        verify(postRequestedFor(urlMatching("/my/resource/[a-z0-9]+"))
                .withRequestBody(matching(".*<message>1234</message>.*")));
    }
}
</code>```

For loadtest, you would rather run the stub standalone somewhere, and have some script set up the responses.

You probably don't find mention of Mockito because embedding mocks with stub responses into your application is a bad idea and will not help you getting realistic results for load tests (because your responses will be much faster and not pass through serialization/deserialization).

Else also look here:
How to mock remote REST API in unit test with Spring?

Body:
You probably should look for using wiremock or similar software to mock the vendor service, like here: Integration Testing with a fake server

Wiremock is a stub server that you can conveniently start/stop from within JUnit tests. It acts like the remote server when you set up responses. The documentation is really good, I do not want to copy&paste all of it here.

Just a sample:

public class MyTest {
    @Rule
    public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort().dynamicHttpsPort());

    @Test
    public void exampleTest() {
        stubFor(get(urlEqualTo("/my/resource"))
                .willReturn(aResponse()
                    .withStatus(200)
                    .withBody("<response>Some content</response>")));

        ...
        verify(postRequestedFor(urlMatching("/my/resource/[a-z0-9]+"))
                .withRequestBody(matching(".*<message>1234</message>.*")));
    }
}

For loadtest, you would rather run the stub standalone somewhere, and have some script set up the responses.

You probably don't find mention of Mockito because embedding mocks with stub responses into your application is a bad idea and will not help you getting realistic results for load tests (because your responses will be much faster and not pass through serialization/deserialization).

Else also look here:
How to mock remote REST API in unit test with Spring?


问:
UICollectionView Set number of columns
I just started learning about UICollectionViews. I'm wondering if anyone knows how to specify the number of columns in a collectionview. The default is set to 3 (iPhone/portrait). I've looked at the documentation and can't seem to find a concise answer.</p>

答:
I made a collection layout.

To make the separator visible, Set the background color of the collection view to gray.
One row per section.

Useage:

```<code>let layout = GridCollectionViewLayout()
layout.cellHeight = 50 // if not set, cellHeight = Collection.height/numberOfSections
layout.cellWidth = 50  // if not set, cellWidth = Collection.width/numberOfItems(inSection)
collectionView.collectionViewLayout = layout
</code>```

Layout:

```<code>import UIKit

class GridCollectionViewLayout: UICollectionViewLayout {

var cellWidth : CGFloat = 0
var cellHeight : CGFloat = 0
var seperator: CGFloat = 1

private var cache = [UICollectionViewLayoutAttributes]()

override func prepare() {

    guard let collectionView = self.collectionView else {
        return
    }

    self.cache.removeAll()

        let numberOfSections = collectionView.numberOfSections

        if cellHeight <= 0
        {
            cellHeight = (collectionView.bounds.height - seperator*CGFloat(numberOfSections-1))/CGFloat(numberOfSections)
        }

        for section in 0..<collectionView.numberOfSections {

            let numberOfItems = collectionView.numberOfItems(inSection: section)

            let cellWidth2 : CGFloat
            if cellWidth <= 0
            {
                cellWidth2 = (collectionView.bounds.width - seperator*CGFloat(numberOfItems-1))/CGFloat(numberOfItems)
            }
            else
            {
                cellWidth2 = cellWidth
            }

            for row in 0..<numberOfItems {

                let indexPath = NSIndexPath(row: row, section: section)

                let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath as IndexPath)
                attributes.frame = CGRect(x: (cellWidth2+seperator)*CGFloat(row),
                                          y: (cellHeight+seperator)*CGFloat(section),
                                          width: cellWidth2,
                                          height: cellHeight)

                //row_temp.append(attributes)

                self.cache.append(attributes)
            }
            //self.itemAttributes.append(row_temp)
        }

}

override var collectionViewContentSize: CGSize {

    guard let collectionView = collectionView else
    {
        return CGSize.zero
    }

    if (collectionView.numberOfSections <= 0)
    {
        return collectionView.bounds.size
    }

    let width:CGFloat
    if cellWidth <= 0
    {
        width = collectionView.bounds.width
    }
    else
    {
        width = cellWidth*CGFloat(collectionView.numberOfItems(inSection: 0))
    }

    let numberOfSections = CGFloat(collectionView.numberOfSections)
    var height:CGFloat = 0
    height += numberOfSections * cellHeight
    height += (numberOfSections - 1) * seperator

    return CGSize(width: width, height: height)
}

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

    var layoutAttributes = [UICollectionViewLayoutAttributes]()

    for attributes in cache {
        if attributes.frame.intersects(rect) {
            layoutAttributes.append(attributes)
        }
    }
    return layoutAttributes
}

override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
    return cache[indexPath.item]
}
}
</code>```

Title: UICollectionView Set number of columns

Body:
I made a collection layout.

To make the separator visible, Set the background color of the collection view to gray.
One row per section.

Useage:

let layout = GridCollectionViewLayout()
layout.cellHeight = 50 // if not set, cellHeight = Collection.height/numberOfSections
layout.cellWidth = 50  // if not set, cellWidth = Collection.width/numberOfItems(inSection)
collectionView.collectionViewLayout = layout

Layout:

import UIKit

class GridCollectionViewLayout: UICollectionViewLayout {

var cellWidth : CGFloat = 0
var cellHeight : CGFloat = 0
var seperator: CGFloat = 1

private var cache = [UICollectionViewLayoutAttributes]()

override func prepare() {

    guard let collectionView = self.collectionView else {
        return
    }

    self.cache.removeAll()

        let numberOfSections = collectionView.numberOfSections

        if cellHeight <= 0
        {
            cellHeight = (collectionView.bounds.height - seperator*CGFloat(numberOfSections-1))/CGFloat(numberOfSections)
        }

        for section in 0..<collectionView.numberOfSections {

            let numberOfItems = collectionView.numberOfItems(inSection: section)

            let cellWidth2 : CGFloat
            if cellWidth <= 0
            {
                cellWidth2 = (collectionView.bounds.width - seperator*CGFloat(numberOfItems-1))/CGFloat(numberOfItems)
            }
            else
            {
                cellWidth2 = cellWidth
            }

            for row in 0..<numberOfItems {

                let indexPath = NSIndexPath(row: row, section: section)

                let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath as IndexPath)
                attributes.frame = CGRect(x: (cellWidth2+seperator)*CGFloat(row),
                                          y: (cellHeight+seperator)*CGFloat(section),
                                          width: cellWidth2,
                                          height: cellHeight)

                //row_temp.append(attributes)

                self.cache.append(attributes)
            }
            //self.itemAttributes.append(row_temp)
        }

}

override var collectionViewContentSize: CGSize {

    guard let collectionView = collectionView else
    {
        return CGSize.zero
    }

    if (collectionView.numberOfSections <= 0)
    {
        return collectionView.bounds.size
    }

    let width:CGFloat
    if cellWidth <= 0
    {
        width = collectionView.bounds.width
    }
    else
    {
        width = cellWidth*CGFloat(collectionView.numberOfItems(inSection: 0))
    }

    let numberOfSections = CGFloat(collectionView.numberOfSections)
    var height:CGFloat = 0
    height += numberOfSections * cellHeight
    height += (numberOfSections - 1) * seperator

    return CGSize(width: width, height: height)
}

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

    var layoutAttributes = [UICollectionViewLayoutAttributes]()

    for attributes in cache {
        if attributes.frame.intersects(rect) {
            layoutAttributes.append(attributes)
        }
    }
    return layoutAttributes
}

override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
    return cache[indexPath.item]
}
}


问:
Good way to generate GUIDs on app engine?
I was wondering if anyone knows of a good way to generate GUIDs on python google app engine. I feel like there is a simple way that people are using, what would you suggest.</p>

答:
The uuid module should be available.

Why do you need uuids?  Usually they're necessary to make really unique primary keys, but GAE's datastore essentially ought to be taking care of that for you.

ContentLicense: CC BY-SA 2.5


问:
C# Listview - How to change the color of each new item?
I add items to a ListView control from the click event of a Button. I want each new item to be colored red and the older items colored white (so only the newest item added to the ListView is colored red).

I did something like this, but it only alternates the colors between red and white:

```<code>for (int i = 0; i <= listView1.Items.Count - 1; i++)
{
    if (listView1.Items[i].Index % 2 == 0)
    {
        listView1.Items[i].BackColor = Color.Red;
    }
    else
    {
        listView1.Items[i].BackColor = Color.White;
    }
}
</code>```

How can I have only the newest added item to be colored red?

答:
Add a new method to add items to your listView:</p>

```<code>public void AddNewItemToListBox(string text)
{
  // Make existing background white
  for (int i = 0; i <= listView1.Items.Count - 1; i++)
  {
    listView1.Items[i].BackColor = Color.White;
  }
  // New one with red background
  ListViewItem lvi = new ListViewItem();
  lvi.Text = text;
  lvi.BackColor = Color.Red;
  lv.Items.Add(lvi); // lv is your listview
}
</code>```

Body:
I add items to a ListView control from the click event of a Button. I want each new item to be colored red and the older items colored white (so only the newest item added to the ListView is colored red).

I did something like this, but it only alternates the colors between red and white:

for (int i = 0; i <= listView1.Items.Count - 1; i++)
{
    if (listView1.Items[i].Index % 2 == 0)
    {
        listView1.Items[i].BackColor = Color.Red;
    }
    else
    {
        listView1.Items[i].BackColor = Color.White;
    }
}

How can I have only the newest added item to be colored red?

Body:
Add a new method to add items to your listView:

public void AddNewItemToListBox(string text)
{
  // Make existing background white
  for (int i = 0; i <= listView1.Items.Count - 1; i++)
  {
    listView1.Items[i].BackColor = Color.White;
  }
  // New one with red background
  ListViewItem lvi = new ListViewItem();
  lvi.Text = text;
  lvi.BackColor = Color.Red;
  lv.Items.Add(lvi); // lv is your listview
}


问:
Using IConfiguration in C# Class Library
I am building a class library using C# and Core .NET. I am trying to use configuration from a config.json file. Here are the contents of that file:

config.json

```<code>{
  "emailAddress":"someone@somewhere.com"
}
</code>```

In an attempt to use config.json for my configuration, I'm referencing Microsoft.Framework.ConfigurationModel.Json in my project.json file. In my code, I have the following:

MyClass.cs

```<code>using Microsoft.Framework.ConfigurationModel;
public class MyClass
{
  public string GetEmailAddress()
  {
//    return ConfigurationManager.AppSettings["emailAddress"];  This is the approach I had been using since .NET 2.0
    return ?;  // What goes here?
  }
}
</code>```

Since .NET 2.0, I had been using ConfigurationManager.AppSettings["emailAddress"]. However, I'm now trying to learn how to do it the new way via IConfiguration. My problem is, this is a class library. For that reason, I'm not sure how, or where, or when, the configuration file gets loaded. In traditional .NET, I just needed to name a file web.config for ASP.NET projects and app.config for other projects. Now, I'm not sure. I have both an ASP.NET MVC 6 project and an XUnit project. So, I'm trying to figure out how to use config.json in both of these scenarios.

Thank you!

答:
First in your .csproj file add a target that hocks in the build process, see the link for more options if the following doesn't fit your needs, like publication

```<code><Target Name="AddConfig" AfterTargets="AfterBuild">
    <Copy SourceFiles="config.json" DestinationFolder="$(OutDir)" />
</Target>
</code>```

you can use it like follows

```<code>using Microsoft.Framework.ConfigurationModel;
using Microsoft.Extensions.Configuration;
using System;

public class MyClass {
    public string GetEmailAddress() {
        //For example purpose only, try to move this to a right place like configuration manager class
        string basePath= System.AppContext.BaseDirectory;
        IConfigurationRoot configuration= new ConfigurationBuilder()
            .SetBasePath(basePath)
            .AddJsonFile("config.json")
            .Build();

        return configuration.Get("emailAddress");
    }
}
</code>```

Body:
I am building a class library using C# and Core .NET. I am trying to use configuration from a config.json file. Here are the contents of that file:

config.json

{
  "emailAddress":"someone@somewhere.com"
}

In an attempt to use config.json for my configuration, I'm referencing Microsoft.Framework.ConfigurationModel.Json in my project.json file. In my code, I have the following:

MyClass.cs

using Microsoft.Framework.ConfigurationModel;
public class MyClass
{
  public string GetEmailAddress()
  {
//    return ConfigurationManager.AppSettings["emailAddress"];  This is the approach I had been using since .NET 2.0
    return ?;  // What goes here?
  }
}

Since .NET 2.0, I had been using ConfigurationManager.AppSettings["emailAddress"]. However, I'm now trying to learn how to do it the new way via IConfiguration. My problem is, this is a class library. For that reason, I'm not sure how, or where, or when, the configuration file gets loaded. In traditional .NET, I just needed to name a file web.config for ASP.NET projects and app.config for other projects. Now, I'm not sure. I have both an ASP.NET MVC 6 project and an XUnit project. So, I'm trying to figure out how to use config.json in both of these scenarios.

Thank you!

Body:
First in your .csproj file add a target that hocks in the build process, see the link for more options if the following doesn't fit your needs, like publication

<Target Name="AddConfig" AfterTargets="AfterBuild">
    <Copy SourceFiles="config.json" DestinationFolder="$(OutDir)" />
</Target>

you can use it like follows

using Microsoft.Framework.ConfigurationModel;
using Microsoft.Extensions.Configuration;
using System;

public class MyClass {
    public string GetEmailAddress() {
        //For example purpose only, try to move this to a right place like configuration manager class
        string basePath= System.AppContext.BaseDirectory;
        IConfigurationRoot configuration= new ConfigurationBuilder()
            .SetBasePath(basePath)
            .AddJsonFile("config.json")
            .Build();

        return configuration.Get("emailAddress");
    }
}


问:
Different output from scrapy spider than from scrapy shell
I am new to scrapy and am attempting to figure out why I am able to extract the elements I need from the scrapy shell but not from the scrapy spider I created from command line.

In scrapy shell I did the following:

```<code>pipenv run scrapy shell http://quotes.toscrape.com/
</code>```

Then

```<code>response.css('small.author::text').extract()
</code>```

Which returns the following:

['Albert Einstein', 'J.K. Rowling', 'Albert Einstein', 'Jane Austen', 'Marilyn Monroe', 'Albert Einstein', 'André Gide', 'Thomas A. Edison', 'Eleanor Roosevelt', 'Steve Martin']

This is all as intended. But I start to have some issues when I create a scrapy spider and run it afterwards. My code is below:

```<code># -*- coding: utf-8 -*-
import scrapy

class Yolo1Spider(scrapy.Spider):
    name = 'yolo1'
    allowed_domains = ['toscrape.com']
    start_urls = ['http://http://quotes.toscrape.com/']

    def parse(self, response):
        self.log('Just visited' + response.url)
        yield {
            'author': response.css('small.author::text').extract()
            }
</code>```

I run the spider from the command line with:

```<code>pipenv run scrapy crawl yolo1
</code>```

The errors I get are as follows:

2017-12-04 20:03:56 [yolo1] DEBUG: Just visitedhttp://www.dnsrsearch.com/index.php?origURL=http://http/quotes.toscrape.com/&bc=
  2017-12-04 20:03:56 [scrapy.core.scraper] ERROR: Error processing {'author': []}
  Traceback (most recent call last):
    File "c:\users\alice.virtualenvs\all-the-places-c44chfla\lib\site-packages\twisted\internet\defer.py", line 653, in _runCallbacks
      current.result = callback(current.result, *args, **kw)
    File "C:\Users\alice\all-the-places\locations\pipelines.py", line 16, in process_item
      ref = item['ref']
  KeyError: 'ref'

I get the feeling I am just missing something simple but for the life of me I cannot figure it out and have been checking all over the place.

You can see in the output of the spider crawl that the debug line I wrote printed out, but after that I get an error. Really thought I should be getting the same output from both the spider and the command line work I did.

答:
You made mistake in start url - you have http:// twice.

See http://http://quotes.toscrape.com/

Body:
I am new to scrapy and am attempting to figure out why I am able to extract the elements I need from the scrapy shell but not from the scrapy spider I created from command line.

In scrapy shell I did the following:

pipenv run scrapy shell http://quotes.toscrape.com/

Then

response.css('small.author::text').extract()

Which returns the following:

['Albert Einstein', 'J.K. Rowling', 'Albert Einstein', 'Jane Austen', 'Marilyn Monroe', 'Albert Einstein', 'André Gide', 'Thomas A. Edison', 'Eleanor Roosevelt', 'Steve Martin']

This is all as intended. But I start to have some issues when I create a scrapy spider and run it afterwards. My code is below:

# -*- coding: utf-8 -*-
import scrapy

class Yolo1Spider(scrapy.Spider):
    name = 'yolo1'
    allowed_domains = ['toscrape.com']
    start_urls = ['http://http://quotes.toscrape.com/']

    def parse(self, response):
        self.log('Just visited' + response.url)
        yield {
            'author': response.css('small.author::text').extract()
            }

I run the spider from the command line with:

pipenv run scrapy crawl yolo1

The errors I get are as follows:

2017-12-04 20:03:56 [yolo1] DEBUG: Just visitedhttp://www.dnsrsearch.com/index.php?origURL=http://http/quotes.toscrape.com/&bc=
  2017-12-04 20:03:56 [scrapy.core.scraper] ERROR: Error processing {'author': []}
  Traceback (most recent call last):
    File "c:\users\alice.virtualenvs\all-the-places-c44chfla\lib\site-packages\twisted\internet\defer.py", line 653, in _runCallbacks
      current.result = callback(current.result, *args, **kw)
    File "C:\Users\alice\all-the-places\locations\pipelines.py", line 16, in process_item
      ref = item['ref']
  KeyError: 'ref'

I get the feeling I am just missing something simple but for the life of me I cannot figure it out and have been checking all over the place.

You can see in the output of the spider crawl that the debug line I wrote printed out, but after that I get an error. Really thought I should be getting the same output from both the spider and the command line work I did.


答: In your convertStremToString method. Try storing the lines into a stack and then print them out after the while loop.</p>

Title: How to sort json bottom to top


问:
Google Sign In error 12500
I am trying to integrate Google Sign In into my app. I don't have a back-end server, I am just getting the details of the logged on Google Account to my app.

I first tried it by using Google Sign In Example but I got an error (No code changes made except for printing the stacktrace below). I just used the example SignInActivity as I don't have a back-end server.

```<code> Exception com.google.android.gms.common.api.ApiException: 12500:
 at com.google.android.gms.common.internal.zzb.zzz(Unknown Source)
 at com.google.android.gms.auth.api.signin.GoogleSignIn.getSignedInAccountFromIntent(Unknown Source)
 at com.ewise.android.api.MainActivity.onActivityResult(SignInActivity.java:89)     at android.app.Activity.dispatchActivityResult(Activity.java:7010)
 at android.app.ActivityThread.deliverResults(ActivityThread.java:4187)
 at android.app.ActivityThread.handleSendResult(ActivityThread.java:4234)
 at android.app.ActivityThread.-wrap20(ActivityThread.java)
 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1584)
 at android.os.Handler.dispatchMessage(Handler.java:102)
 at android.os.Looper.loop(Looper.java:154)
 at android.app.ActivityThread.main(ActivityThread.java:6316)
 at java.lang.reflect.Method.invoke(Native Method)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
</code>```

Code

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

     private static final String TAG = "SignInActivity";
     private static final int RC_SIGN_IN = 9001;

     private GoogleSignInClient mGoogleSignInClient;
     private TextView mStatusTextView;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);

         // Views
         mStatusTextView = findViewById(R.id.status);

         // Button listeners
         findViewById(R.id.sign_in_button).setOnClickListener(this);
         findViewById(R.id.sign_out_button).setOnClickListener(this);
         findViewById(R.id.disconnect_button).setOnClickListener(this);

         // [START configure_signin]
         // Configure sign-in to request the user's ID, email address, and basic
         // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
         GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                 .requestEmail()
                 .build();
         // [END configure_signin]

         // [START build_client]
         // Build a GoogleSignInClient with the options specified by gso.
         mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
         // [END build_client]

         // [START customize_button]
         // Set the dimensions of the sign-in button.
         SignInButton signInButton = findViewById(R.id.sign_in_button);
         signInButton.setSize(SignInButton.SIZE_STANDARD);
         signInButton.setColorScheme(SignInButton.COLOR_LIGHT);
         // [END customize_button]
     }

     @Override
     public void onStart() {
         super.onStart();

         // [START on_start_sign_in]
         // Check for existing Google Sign In account, if the user is already signed in
         // the GoogleSignInAccount will be non-null.
         GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
         updateUI(account);
         // [END on_start_sign_in]
     }

     // [START onActivityResult]
     @Override
     public void onActivityResult(int requestCode, int resultCode, Intent data) {
         super.onActivityResult(requestCode, resultCode, data);

         // Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
         if (requestCode == RC_SIGN_IN) {
             // The Task returned from this call is always completed, no need to attach
             // a listener.
             Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
             handleSignInResult(task);
         }
     }
     // [END onActivityResult]

     // [START handleSignInResult]
     private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
         try {
             GoogleSignInAccount account = completedTask.getResult(ApiException.class);

             // Signed in successfully, show authenticated UI.
             updateUI(account);
         } catch (ApiException e) {
             // The ApiException status code indicates the detailed failure reason.
             // Please refer to the GoogleSignInStatusCodes class reference for more information.
             Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
             e.printStackTrace();
             updateUI(null);
         }
     }
     // [END handleSignInResult]

     // [START signIn]
     private void signIn() {
         Intent signInIntent = mGoogleSignInClient.getSignInIntent();
         startActivityForResult(signInIntent, RC_SIGN_IN);
     }
     // [END signIn]

     // [START signOut]
     private void signOut() {
         mGoogleSignInClient.signOut()
                 .addOnCompleteListener(this, new OnCompleteListener<Void>() {
                     @Override
                     public void onComplete(@NonNull Task<Void> task) {
                         // [START_EXCLUDE]
                         updateUI(null);
                         // [END_EXCLUDE]
                     }
                 });
     }
     // [END signOut]

     // [START revokeAccess]
     private void revokeAccess() {
         mGoogleSignInClient.revokeAccess()
                 .addOnCompleteListener(this, new OnCompleteListener<Void>() {
                     @Override
                     public void onComplete(@NonNull Task<Void> task) {
                         // [START_EXCLUDE]
                         updateUI(null);
                         // [END_EXCLUDE]
                     }
                 });
     }
     // [END revokeAccess]

     private void updateUI(@Nullable GoogleSignInAccount account) {
         if (account != null) {
             mStatusTextView.setText(getString(R.string.signed_in_fmt, account.getDisplayName()));

             findViewById(R.id.sign_in_button).setVisibility(View.GONE);
             findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
         } else {
             mStatusTextView.setText(R.string.signed_out);

             findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
             findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
         }
     }

     @Override
     public void onClick(View v) {
         switch (v.getId()) {
             case R.id.sign_in_button:
                 signIn();
                 break;
             case R.id.sign_out_button:
                 signOut();
                 break;
             case R.id.disconnect_button:
                 revokeAccess();
                 break;
         }
     }
  }
</code>```

From what I read, the issue could be caused by SHA1 Generation.

I followed the complete guide but apparently it's not working.

I copied the SHA1 from gradle signingReport

```<code>Variant: debug
Config: debug
Store: /Users/user/.android/debug.keystore
Alias: AndroidDebugKey
MD5: A3:16:3F:43:75:FE:07:62:6D:8D:CC:DD:21:9F:FA:1A
SHA1: 7B:21:26:7F:D8:18:BB:0E:36:1C:82:DD:B7:28:5F:C1:2F:5C:E4:EA
Valid until: Saturday, August 31, 2047
----------
Variant: release
Config: none
----------
Variant: debugAndroidTest
Config: debug
Store: /Users/user/.android/debug.keystore
Alias: AndroidDebugKey
MD5: A3:16:3F:43:75:FE:07:62:6D:8D:CC:DD:21:9F:FA:1A
SHA1: 7B:21:26:7F:D8:18:BB:0E:36:1C:82:DD:B7:28:5F:C1:2F:5C:E4:EA
Valid until: Saturday, August 31, 2047
----------
Variant: debugUnitTest
Config: debug
Store: /Users/user/.android/debug.keystore
Alias: AndroidDebugKey
MD5: A3:16:3F:43:75:FE:07:62:6D:8D:CC:DD:21:9F:FA:1A
SHA1: 7B:21:26:7F:D8:18:BB:0E:36:1C:82:DD:B7:28:5F:C1:2F:5C:E4:EA
Valid until: Saturday, August 31, 2047
</code>```

what could be the possible cause of this?

Thanks

P.S. Could this be a possible cause?

```<code>Google Play services out of date.  Requires 11720000 but found 10932470
</code>```

答: Simply update your Google Play Services to the latest version (or 11720000 in this case). If you are using AVD, Nexus 5 and 5X images support Google Play. Once the emulator is up and running, go to the Extended Controls Menu >  Google Play then update.</p>

Title: Google Sign In error 12500

Body:
I am trying to integrate Google Sign In into my app. I don't have a back-end server, I am just getting the details of the logged on Google Account to my app.

I first tried it by using Google Sign In Example but I got an error (No code changes made except for printing the stacktrace below). I just used the example SignInActivity as I don't have a back-end server.

 Exception com.google.android.gms.common.api.ApiException: 12500:
 at com.google.android.gms.common.internal.zzb.zzz(Unknown Source)
 at com.google.android.gms.auth.api.signin.GoogleSignIn.getSignedInAccountFromIntent(Unknown Source)
 at com.ewise.android.api.MainActivity.onActivityResult(SignInActivity.java:89)     at android.app.Activity.dispatchActivityResult(Activity.java:7010)
 at android.app.ActivityThread.deliverResults(ActivityThread.java:4187)
 at android.app.ActivityThread.handleSendResult(ActivityThread.java:4234)
 at android.app.ActivityThread.-wrap20(ActivityThread.java)
 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1584)
 at android.os.Handler.dispatchMessage(Handler.java:102)
 at android.os.Looper.loop(Looper.java:154)
 at android.app.ActivityThread.main(ActivityThread.java:6316)
 at java.lang.reflect.Method.invoke(Native Method)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)

Code

 public class SignInActivity extends AppCompatActivity implements
         View.OnClickListener {

     private static final String TAG = "SignInActivity";
     private static final int RC_SIGN_IN = 9001;

     private GoogleSignInClient mGoogleSignInClient;
     private TextView mStatusTextView;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);

         // Views
         mStatusTextView = findViewById(R.id.status);

         // Button listeners
         findViewById(R.id.sign_in_button).setOnClickListener(this);
         findViewById(R.id.sign_out_button).setOnClickListener(this);
         findViewById(R.id.disconnect_button).setOnClickListener(this);

         // [START configure_signin]
         // Configure sign-in to request the user's ID, email address, and basic
         // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
         GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                 .requestEmail()
                 .build();
         // [END configure_signin]

         // [START build_client]
         // Build a GoogleSignInClient with the options specified by gso.
         mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
         // [END build_client]

         // [START customize_button]
         // Set the dimensions of the sign-in button.
         SignInButton signInButton = findViewById(R.id.sign_in_button);
         signInButton.setSize(SignInButton.SIZE_STANDARD);
         signInButton.setColorScheme(SignInButton.COLOR_LIGHT);
         // [END customize_button]
     }

     @Override
     public void onStart() {
         super.onStart();

         // [START on_start_sign_in]
         // Check for existing Google Sign In account, if the user is already signed in
         // the GoogleSignInAccount will be non-null.
         GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
         updateUI(account);
         // [END on_start_sign_in]
     }

     // [START onActivityResult]
     @Override
     public void onActivityResult(int requestCode, int resultCode, Intent data) {
         super.onActivityResult(requestCode, resultCode, data);

         // Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
         if (requestCode == RC_SIGN_IN) {
             // The Task returned from this call is always completed, no need to attach
             // a listener.
             Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
             handleSignInResult(task);
         }
     }
     // [END onActivityResult]

     // [START handleSignInResult]
     private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
         try {
             GoogleSignInAccount account = completedTask.getResult(ApiException.class);

             // Signed in successfully, show authenticated UI.
             updateUI(account);
         } catch (ApiException e) {
             // The ApiException status code indicates the detailed failure reason.
             // Please refer to the GoogleSignInStatusCodes class reference for more information.
             Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
             e.printStackTrace();
             updateUI(null);
         }
     }
     // [END handleSignInResult]

     // [START signIn]
     private void signIn() {
         Intent signInIntent = mGoogleSignInClient.getSignInIntent();
         startActivityForResult(signInIntent, RC_SIGN_IN);
     }
     // [END signIn]

     // [START signOut]
     private void signOut() {
         mGoogleSignInClient.signOut()
                 .addOnCompleteListener(this, new OnCompleteListener<Void>() {
                     @Override
                     public void onComplete(@NonNull Task<Void> task) {
                         // [START_EXCLUDE]
                         updateUI(null);
                         // [END_EXCLUDE]
                     }
                 });
     }
     // [END signOut]

     // [START revokeAccess]
     private void revokeAccess() {
         mGoogleSignInClient.revokeAccess()
                 .addOnCompleteListener(this, new OnCompleteListener<Void>() {
                     @Override
                     public void onComplete(@NonNull Task<Void> task) {
                         // [START_EXCLUDE]
                         updateUI(null);
                         // [END_EXCLUDE]
                     }
                 });
     }
     // [END revokeAccess]

     private void updateUI(@Nullable GoogleSignInAccount account) {
         if (account != null) {
             mStatusTextView.setText(getString(R.string.signed_in_fmt, account.getDisplayName()));

             findViewById(R.id.sign_in_button).setVisibility(View.GONE);
             findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
         } else {
             mStatusTextView.setText(R.string.signed_out);

             findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
             findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
         }
     }

     @Override
     public void onClick(View v) {
         switch (v.getId()) {
             case R.id.sign_in_button:
                 signIn();
                 break;
             case R.id.sign_out_button:
                 signOut();
                 break;
             case R.id.disconnect_button:
                 revokeAccess();
                 break;
         }
     }
  }

From what I read, the issue could be caused by SHA1 Generation.

I followed the complete guide but apparently it's not working.

I copied the SHA1 from gradle signingReport

Variant: debug
Config: debug
Store: /Users/user/.android/debug.keystore
Alias: AndroidDebugKey
MD5: A3:16:3F:43:75:FE:07:62:6D:8D:CC:DD:21:9F:FA:1A
SHA1: 7B:21:26:7F:D8:18:BB:0E:36:1C:82:DD:B7:28:5F:C1:2F:5C:E4:EA
Valid until: Saturday, August 31, 2047
----------
Variant: release
Config: none
----------
Variant: debugAndroidTest
Config: debug
Store: /Users/user/.android/debug.keystore
Alias: AndroidDebugKey
MD5: A3:16:3F:43:75:FE:07:62:6D:8D:CC:DD:21:9F:FA:1A
SHA1: 7B:21:26:7F:D8:18:BB:0E:36:1C:82:DD:B7:28:5F:C1:2F:5C:E4:EA
Valid until: Saturday, August 31, 2047
----------
Variant: debugUnitTest
Config: debug
Store: /Users/user/.android/debug.keystore
Alias: AndroidDebugKey
MD5: A3:16:3F:43:75:FE:07:62:6D:8D:CC:DD:21:9F:FA:1A
SHA1: 7B:21:26:7F:D8:18:BB:0E:36:1C:82:DD:B7:28:5F:C1:2F:5C:E4:EA
Valid until: Saturday, August 31, 2047

what could be the possible cause of this?

Thanks

P.S. Could this be a possible cause?

Google Play services out of date.  Requires 11720000 but found 10932470


问:
How to extend a JS class in fable
Given a class defined in an external JS library (let's call it Foo) then I'd like to extend in F#

```<code>type bar() =
   inherits Foo
   ...
</code>```

However I can' only find examples of how to integrate with functions

and

```<code>[<Import("Foo", from="my-module")>]
let Foo = JsNative
</code>```

will of course not let me derive Bar from Foo. So how Do I do that

答:
The Import attribute can be used on a type declaration. e.g.

```<code>[<Import("Foo", from="my-module")>]
type Foo() =
    class
    end

type Bar() =
    inherit Foo()
</code>```

You can then also include signatures for the members of the class. It's instructive to look at examples of imports like the Fable React declarations: https://github.com/fable-compiler/fable-react/blob/master/src/Fable.React/Fable.Import.React.fs

Title: How to extend a JS class in fable

Body:
Given a class defined in an external JS library (let's call it Foo) then I'd like to extend in F#

type bar() =
   inherits Foo
   ...

However I can' only find examples of how to integrate with functions

and

[<Import("Foo", from="my-module")>]
let Foo = JsNative

will of course not let me derive Bar from Foo. So how Do I do that

Body:
The Import attribute can be used on a type declaration. e.g.

[<Import("Foo", from="my-module")>]
type Foo() =
    class
    end

type Bar() =
    inherit Foo()

You can then also include signatures for the members of the class. It's instructive to look at examples of imports like the Fable React declarations: https://github.com/fable-compiler/fable-react/blob/master/src/Fable.React/Fable.Import.React.fs


问:
Best IoT Database?
I have many IoT devices sending data currently to MySQL Database.

I want to port it to some other Database, which will be Open Source and provide me with:

JSON support

Scalability

Flexibility to add multiple columns automatically as per payload

Python and PHP Support

Extremely Fast Read, Write

Ability to export at least 6 months of data in CSV format

Please revert back soon.
Any help will be appreciated.

Thanks

答:
Shaping your database based on input data is a mistake. Think of tomorrow your data will be CSV or XML, in a slight different format. Design your database based on your abstract data model, normalize it and apply existing data to your model. Shape your structure based on what input you have and what output you plan to get. If you retrieve the same content as the input, storing data in files will be sufficient, you don't need a database.

Also, you don't want to store "raw" records the database. Even if your database can compose a data record out of the raw element at run time, you cannot run a selection based on a certain extracted element, without visiting all the records.

Most of the databases allow you to connect from anywhere (there is not such thing as better support of PostgreSQL in Java as compared to Python, but the quality and level of standardization for drivers may vary). The question is what features shall your driver support. For example, you may require support for bulk import (don't issue large INSERT sets to the database).

What you actually look for is:

scalability: can your database grow with your data? Would the DB benefit of adding additional CPUs (MySQL particularly doesn't for large queries). Can you shard your database on multiple instances? (MySQL again fails to handle that).

does your model looks like a snowflake? If yes, you may consider NoSQL, otherwise stay away of it. If you manage to model as a snowflake (and this means you are open for compromises) you may use anything like Lucene based search products, Mongo, Cassandra, etc. The fact you have timeseries doesn't qualify you for NoSQL. For example, you may have 10K devices issuing 5k message types. Specific data is redundantly recorded at device level and at message type level. In that case, because of the n:m relation, you don't have the snowflake anymore.

why do you store the data? What queries are you going to issue?

Title: Best IoT Database?


问:
HTML5 video, fallback to flash if no .ogv file
How can I fallback to a flash video player if the necessary file type is not present.

For example this code:

```<code><video controls width="500">
    <source src="<?= $mov ?>" type="video/mp4" />
    <embed src="http://blip.tv/play/gcMVgcmBAgA%2Em4v" type="application/x-shockwave-flash" width="1024" height="798" allowscriptaccess="always" allowfullscreen="true"></embed>
</video>
</code>```

Does not include an .ogv file, so in Firefox, an empty video player is displayed.

How can I fall back to a Flash player even if the html5 video tag is supported in the browswer?

答:
You should really include an .ogv file, that's not so much effort, there are so much video converter software, and you can also find online converters.

If you don't want to do that anyway

Use Modernizr.

What is Modernizr?

Modernizr adds classes to the  element which allow you to target specific browser functionality in your stylesheet. You don't actually need to write any Javascript to use it.

Have you ever wanted to do if-statements in your CSS for the availability of cool features like border-radius? Well, with Modernizr you can accomplish just that! The syntax is very intuitive, too:

```<code>.multiplebgs div p {
  /* properties for browsers that
     support multiple backgrounds */
}
.no-multiplebgs div p {
  /* optional fallback properties
     for browsers that don't */
}
</code>```

Modernizr is a small and simple JavaScript library that helps you take advantage of emerging web technologies (CSS3, HTML 5) while still maintaining a fine level of control over older browsers that may not yet support these new technologies.

Modernizr uses feature detection to test the current browser against upcoming features like rgba(), border-radius, CSS Transitions and many more. These are currently being implemented across browsers and with Modernizr you can start using them right now, with an easy way to control the fallbacks for browsers that don’t yet support them.

Additionally, Modernizr creates a self-titled global JavaScript object which contains properties for each feature; if a browser supports it, the property will evaluate true and if not, it will be false.

Lastly, Modernizr also adds support for styling and printing HTML5 elements. This allows you to use more semantic, forward-looking elements such as
,  and <dialog> without having to worry about them not working in Internet Explorer.

What Modernizr doesn't do

Modernizr does not add missing functionality to browsers; instead, it detects native availability of features and offers you a way to maintain a fine level of control over your site regardless of a browser’s capabilities.

However if you're interested in that, you'll probably want to look here: HTML5 Cross browser Polyfills.

Body:
How can I fallback to a flash video player if the necessary file type is not present.

For example this code:

<video controls width="500">
    <source src="<?= $mov ?>" type="video/mp4" />
    <embed src="http://blip.tv/play/gcMVgcmBAgA%2Em4v" type="application/x-shockwave-flash" width="1024" height="798" allowscriptaccess="always" allowfullscreen="true"></embed>
</video>

Does not include an .ogv file, so in Firefox, an empty video player is displayed.

How can I fall back to a Flash player even if the html5 video tag is supported in the browswer?

Body:
You should really include an .ogv file, that's not so much effort, there are so much video converter software, and you can also find online converters.

If you don't want to do that anyway

Use Modernizr.

What is Modernizr?

Modernizr adds classes to the <html> element which allow you to target specific browser functionality in your stylesheet. You don't actually need to write any Javascript to use it.

Have you ever wanted to do if-statements in your CSS for the availability of cool features like border-radius? Well, with Modernizr you can accomplish just that! The syntax is very intuitive, too:

.multiplebgs div p {
  /* properties for browsers that
     support multiple backgrounds */
}
.no-multiplebgs div p {
  /* optional fallback properties
     for browsers that don't */
}

Modernizr is a small and simple JavaScript library that helps you take advantage of emerging web technologies (CSS3, HTML 5) while still maintaining a fine level of control over older browsers that may not yet support these new technologies.

Modernizr uses feature detection to test the current browser against upcoming features like rgba(), border-radius, CSS Transitions and many more. These are currently being implemented across browsers and with Modernizr you can start using them right now, with an easy way to control the fallbacks for browsers that don’t yet support them.

Additionally, Modernizr creates a self-titled global JavaScript object which contains properties for each feature; if a browser supports it, the property will evaluate true and if not, it will be false.

Lastly, Modernizr also adds support for styling and printing HTML5 elements. This allows you to use more semantic, forward-looking elements such as <section>, <header> and <dialog> without having to worry about them not working in Internet Explorer.

What Modernizr doesn't do

Modernizr does not add missing functionality to browsers; instead, it detects native availability of features and offers you a way to maintain a fine level of control over your site regardless of a browser’s capabilities.

However if you're interested in that, you'll probably want to look here: HTML5 Cross browser Polyfills.


问:
data consistency check : TypeError: argument of type 'NoneType' is not iterable
so basically i am writing a some codes to cross check if my data is consistent.
I have written the below code but it has been showing TypeError: argument of type 'NoneType' is not iterable, i have tried changing the code quite a few times but still the same error comes out. Many thanks.</p>

```<code>def checkdata(sex,school):
    if (sex == 'F') and ('boys school' in school) :
        return 'inconsistent'
    if (sex == 'M') and ('girls school' in school):
        return 'inconsistent'
    return

def Dif() :
    with arcpy.da.UpdateCursor(DATA_SET,
        [sex, school]) as Cursor :
    for Cols in Cursor :

            Data = checkdata(Cols[0], Cols[1])
            if Data is not None:
                print (Data, " ",Cols)
</code>```

答:
Ah. For one of your data records, you must be getting a None as the value of school. The TypeError is being thrown by the in operator, which expects a sequence type as the second operand. None isn't a sequence type - it's None ;-)

Try adding print(sex, school) as the first line of checkdata() to confirm the parameters are what you expect.

Body:
so basically i am writing a some codes to cross check if my data is consistent.
I have written the below code but it has been showing TypeError: argument of type 'NoneType' is not iterable, i have tried changing the code quite a few times but still the same error comes out. Many thanks.

def checkdata(sex,school):
    if (sex == 'F') and ('boys school' in school) :
        return 'inconsistent'
    if (sex == 'M') and ('girls school' in school):
        return 'inconsistent'
    return

def Dif() :
    with arcpy.da.UpdateCursor(DATA_SET,
        [sex, school]) as Cursor :
    for Cols in Cursor :

            Data = checkdata(Cols[0], Cols[1])
            if Data is not None:
                print (Data, " ",Cols)


问:
REST endpoint with @QuerydslPredicate Predicate mocking test
I have a rest controller which has parameter com.querydsl.core.types.Predicate that is annotated with @QuerydslPredicate

```<code>ResponseEntity<List<Employee>> listEmployees(@QuerydslPredicate(root = Employee.class) Predicate predicate) {
    List<Employee> employees = employeeService.listEmployees(predicate);
    return new ResponseEntity<>(employees , HttpStatus.OK);
}
</code>```

I have my unit test using spring runner. My unit test looks like

```<code>@Test
public void test_listEmployees() throws Exception {
    List<Employee> employees = singletonList(employee);

   given(employeeService.listEmployees(any(Predicate.class))).willReturn(employees);

    mockMvc.perform(get(EMPLOYEE_PATH)
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$", hasSize(1)))
            .andExpect(jsonPath("$[0].employeeId", is(employee.getEmployeeId())))
            .andExpect(jsonPath("$[0].employeeName", is(employee.getEmployeeName())));
}
</code>```

On unit test execution, I get following exception.

```<code>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.querydsl.core.types.Predicate]: Specified class is an interface

at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:160)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:127)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:127)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:127)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:127)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.querydsl.core.types.Predicate]: Specified class is an interface
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:99)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.createAttribute(ModelAttributeMethodProcessor.java:141)
at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttribute(ServletModelAttributeMethodProcessor.java:81)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:101)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:158)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
... 47 more
</code>```

Any help will be appreciated.

Edit

My controller class is annotated with

```<code>@RestController
@RequestMapping(value = "employees")
</code>```

And my controller method is annotated with

```<code>@RequestMapping(
        method = RequestMethod.GET
)
</code>```

答:
After taking a break for few days and trying to understand the issue, I found out that it is not an issue with mockito given function. Rather, it is an issue with mockmvc.perform operation. I got it resolved by adding @EnableSpringDataWebSupport annotation from spring-data-commons package in my test class.

Hurrrayyyyy

Body:
I have a rest controller which has parameter com.querydsl.core.types.Predicate that is annotated with @QuerydslPredicate

ResponseEntity<List<Employee>> listEmployees(@QuerydslPredicate(root = Employee.class) Predicate predicate) {
    List<Employee> employees = employeeService.listEmployees(predicate);
    return new ResponseEntity<>(employees , HttpStatus.OK);
}

I have my unit test using spring runner. My unit test looks like

@Test
public void test_listEmployees() throws Exception {
    List<Employee> employees = singletonList(employee);

   given(employeeService.listEmployees(any(Predicate.class))).willReturn(employees);

    mockMvc.perform(get(EMPLOYEE_PATH)
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$", hasSize(1)))
            .andExpect(jsonPath("$[0].employeeId", is(employee.getEmployeeId())))
            .andExpect(jsonPath("$[0].employeeName", is(employee.getEmployeeName())));
}

On unit test execution, I get following exception.

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.querydsl.core.types.Predicate]: Specified class is an interface

at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:160)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:127)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:127)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:127)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:127)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.querydsl.core.types.Predicate]: Specified class is an interface
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:99)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.createAttribute(ModelAttributeMethodProcessor.java:141)
at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttribute(ServletModelAttributeMethodProcessor.java:81)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:101)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:158)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
... 47 more

Any help will be appreciated.

Edit

My controller class is annotated with

@RestController
@RequestMapping(value = "employees")

And my controller method is annotated with

@RequestMapping(
        method = RequestMethod.GET
)


问:
Picture shrinks down in size, but doesn't grow back?
I'm trying to make an image shrink down in width, change the image source, and grow back out. It shrinks, but it doesn't grow back. Any ideas what's wrong?</p>

```<code>while (pictureBox2.Size.Width > 0)
{
    int width = pictureBox2.Size.Width;
    width -= 2;
    pictureBox2.Size = new Size(width, pictureBox2.Size.Height);
    pictureBox2.Location = new Point(pictureBox2.Location.X + 1, pictureBox2.Location.Y);
    System.Threading.Thread.Sleep(1);
}
pictureBox1.Image = currentImage;
while (pictureBox2.Size.Width < 191)
{
    int width = pictureBox2.Size.Width;
    width += 2;
    pictureBox2.Size = new Size(width, pictureBox2.Size.Height);
    pictureBox2.Location = new Point(pictureBox2.Location.X - 1, pictureBox2.Location.Y);
    System.Threading.Thread.Sleep(1);
}
</code>```

答:
I suspect your drawing problems are due to not allowing Windows to paint your controls properly.  Typically Windows controls receive a WM_PAINT or equivalent when processing the message pump.  If apps don't process this pump (because say they are busy in a while loop sleeping) then generally no updates occur.

If you want to do it in a while loop then you arguably should use pictureBox2.Refresh() instead of calling Thread.Sleep().   The former will block the current thread (the UI thread) and allow the picture box to repaint itself.  The latter only serves to block the current thread which is probably why you are not seeing updates.

MSDN

Forces the control to invalidate its client area and immediately redraw itself and any child controls.  Tell me more...

In practice, you may want to investigate into using a timer instead of a tight loop and sleeping.

Body:
I'm trying to make an image shrink down in width, change the image source, and grow back out. It shrinks, but it doesn't grow back. Any ideas what's wrong?

while (pictureBox2.Size.Width > 0)
{
    int width = pictureBox2.Size.Width;
    width -= 2;
    pictureBox2.Size = new Size(width, pictureBox2.Size.Height);
    pictureBox2.Location = new Point(pictureBox2.Location.X + 1, pictureBox2.Location.Y);
    System.Threading.Thread.Sleep(1);
}
pictureBox1.Image = currentImage;
while (pictureBox2.Size.Width < 191)
{
    int width = pictureBox2.Size.Width;
    width += 2;
    pictureBox2.Size = new Size(width, pictureBox2.Size.Height);
    pictureBox2.Location = new Point(pictureBox2.Location.X - 1, pictureBox2.Location.Y);
    System.Threading.Thread.Sleep(1);
}


问:
How can I do time/hours arithmetic in Google Spreadsheet?
How do I do time/hour arithmetic in a Google spreadsheet?

I have a value that is time (e.g., 36:00:00) and I want to divide it by another time (e.g., 3:00:00) and get 12.  If I divide just one by the other, I get 288:00:00 when what I want is 12 (or 12:00:00).

Note that using the hours() function doesn't work, because 36:00:00 becomes 12.

答: I used the TO_PURE_NUMBER() function and it worked.


问:
Missing Hive Execution Jar: /usr/local/hadoop/hive/lib/hive-exec-*.jar
I have Hadoop 1.0.4 running on a single node cluster set up on my Ubuntu machine.

I did the following steps to download and install the hive release

```<code>> svn co http://svn.apache.org/repos/asf/hive/trunk hive
> cd hive
</code>```

My hadoop install folder is $HADOOP_HOME/hive and $HADOOP_HOME=/usr/local/hadoop. I set both the environment variables in .bashrc under /home/hduser which is my Hadoop user and the $JAVA_HOME as well.

```<code>export HADOOP_HOME=/usr/local/hadoop

export HIVE_HOME=$HADOOP_HOME/hive

export JAVA_HOME=/usr/lib/jvm/java-6-openjdk
</code>```

I have also added the bin folder of both hadoop and hive in my $PATH variable as follows

```<code>export PATH=$PATH:$HADOOP_HOME/bin
export PATH=$HIVE_HOME/bin:$PATH
</code>```

But while running hive from CLI, I am getting the below error.

```<code>hduser@somnath-laptop:/usr/local/hadoop/hive$ bin/hive
Missing Hive Execution Jar: /usr/local/hadoop/hive/lib/hive-exec-*.jar
</code>```

Should I download this jar and add it to the /lib/ or is there some hive-specific environment variables that I need to configure. Any suggestion would be very helpful.

答:
I did below in Dec 2017 and it worked.

Copied hive in to hadoop_home directory

Did below in cygwin:

```<code>export HIVE_HOME=$HADOOP_HOME/hive
export PATH=$HIVE_HOME/bin:$PATH
</code>```

Body:
I have Hadoop 1.0.4 running on a single node cluster set up on my Ubuntu machine.

I did the following steps to download and install the hive release

> svn co http://svn.apache.org/repos/asf/hive/trunk hive
> cd hive

My hadoop install folder is $HADOOP_HOME/hive and $HADOOP_HOME=/usr/local/hadoop. I set both the environment variables in .bashrc under /home/hduser which is my Hadoop user and the $JAVA_HOME as well.

export HADOOP_HOME=/usr/local/hadoop

export HIVE_HOME=$HADOOP_HOME/hive

export JAVA_HOME=/usr/lib/jvm/java-6-openjdk

I have also added the bin folder of both hadoop and hive in my $PATH variable as follows

export PATH=$PATH:$HADOOP_HOME/bin
export PATH=$HIVE_HOME/bin:$PATH

But while running hive from CLI, I am getting the below error.

hduser@somnath-laptop:/usr/local/hadoop/hive$ bin/hive
Missing Hive Execution Jar: /usr/local/hadoop/hive/lib/hive-exec-*.jar

Should I download this jar and add it to the /lib/ or is there some hive-specific environment variables that I need to configure. Any suggestion would be very helpful.

Body:
I did below in Dec 2017 and it worked.

Copied hive in to hadoop_home directory

Did below in cygwin:

export HIVE_HOME=$HADOOP_HOME/hive
export PATH=$HIVE_HOME/bin:$PATH


问:
How to keep React component state between mount/unmount?
I have a simple component <StatefulView> that maintains an internal state. I have another component <App> that toggles whether or not <StatefulView> is rendered.

However, I want to keep <StatefulView>'s internal state between mounting/unmouting.

I figured I could instantiate the component in <App> and then control whether its rendered/mounted.

```<code>var StatefulView = React.createClass({
  getInitialState: function() {
    return {
      count: 0
    }
  },
  inc: function() {
    this.setState({count: this.state.count+1})
  },
  render: function() {
    return (
        <div>
          <button onClick={this.inc}>inc</button>
          <div>count:{this.state.count}</div>
        </div>
    )
  }
});

var App = React.createClass({
  getInitialState: function() {
    return {
      show: true,
      component: <StatefulView/>
    }
  },
  toggle: function() {
    this.setState({show: !this.state.show})
  },
  render: function() {
    var content = this.state.show ? this.state.component : false
    return (
      <div>
        <button onClick={this.toggle}>toggle</button>
        {content}
      </div>
    )
  }
});
</code>```

This apparently doesnt work and a new <StatefulView> is created on each toggle.

Here's a JSFiddle.

Is there a way to hang on to the same component after it is unmounted so it can be re-mounted?

答: I'm late to the party but if you're using Redux. You'll get that behaviour almost out of the box with redux-persist. Just add its autoRehydrate to the store then it will be listening to REHYDRATE actions that will automatically restore previous state of the component (from web storage).

Body:
I have a simple component <StatefulView> that maintains an internal state. I have another component <App> that toggles whether or not <StatefulView> is rendered.

However, I want to keep <StatefulView>'s internal state between mounting/unmouting.

I figured I could instantiate the component in <App> and then control whether its rendered/mounted.

var StatefulView = React.createClass({
  getInitialState: function() {
    return {
      count: 0
    }
  },
  inc: function() {
    this.setState({count: this.state.count+1})
  },
  render: function() {
    return (

          <button onClick={this.inc}>inc</button>

count:{this.state.count}

    )
  }
});

var App = React.createClass({
  getInitialState: function() {
    return {
      show: true,
      component: <StatefulView/>
    }
  },
  toggle: function() {
    this.setState({show: !this.state.show})
  },
  render: function() {
    var content = this.state.show ? this.state.component : false
    return (

        <button onClick={this.toggle}>toggle</button>
        {content}

    )
  }
});

This apparently doesnt work and a new <StatefulView> is created on each toggle.

Here's a JSFiddle.

Is there a way to hang on to the same component after it is unmounted so it can be re-mounted?


问:
Material Design vs Bootstrap
I just heard something like " Material design is already becoming a little bit out of fashion and how will it look like in 5 years" and "Lot of company stop using this and moving to Bootstrap". </p>

<p>Need some community feedback on this saying. </p>

答:
You can use material design and bootstrap separately or together, because they are not rival, each of them help complete the other. I think you look at the problem from the wrong angle.

Material Design provides the design of graphic layouts for great UI/UX.

Bootstrap are front-end frameworks to create responsive pages from the design. It can speed up your development by saving you from writing tons of code and that's it, nothing more!

Btw, material design is more than designs of web pages, it's using for mobile apps, posters,..

Title: Material Design vs Bootstrap

Body:
I just heard something like " Material design is already becoming a little bit out of fashion and how will it look like in 5 years" and "Lot of company stop using this and moving to Bootstrap".

Need some community feedback on this saying.


问:
How to export Estimator model with export_savedmodel function
are there any tutorials available about export_savedmodel ?

I have gone through this article on tensorflow.org and unittest code on github.com, and still have no idea about how to construct the parameter serving_input_fn of function export_savedmodel

答:
You need to have tf.train.Example and tf.train.Feature and pass the input to input receiver function and invoke the model.
 You can take a look at this example
https://github.com/tettusud/tensorflow-examples/tree/master/estimators</p>


问:
Put text into a textbox from a website in VB.NET
I want to know how to put text to a website's textbox with VB.NET.
Like when you complete a textbox and press enter.
Something like this:

Dim web as webbrowser

web.document.textbox(1).insert("text")

答:
This will help 100%:</p>

```<code>webbrowser1.document.getElementById("yourtextboxidinwebsite").innertext = textbox1.text
</code>```

Body:
This will help 100%:

webbrowser1.document.getElementById("yourtextboxidinwebsite").innertext = textbox1.text


问:
How to load react component dynamically using require with babel-register
I am using babel-register to use ES6 classes in node environment and want to load and render React component dynamically using require(file_path) with ReactDomServer, but its showing me following error:

"Invariant Violation: renderToStaticMarkup(): You must pass a valid ReactElement."

```<code>// enable es6
require('babel-register')({
    "presets": ["es2015", "react"],
    "extensions": [".jsx", ".js"]
});

// load component
var testComponent = require(testComponentPath);

console.log(testComponent); // { default: [Function: TestComponent] }

var html = ReactDomServer.renderToStaticMarkup(testComponent);
</code>```

答: Change your require statement to var testComponent = require(testComponentPath).default;, assuming the component is exported as default.

Body:
I am using babel-register to use ES6 classes in node environment and want to load and render React component dynamically using require(file_path) with ReactDomServer, but its showing me following error:

"Invariant Violation: renderToStaticMarkup(): You must pass a valid ReactElement."

// enable es6
require('babel-register')({
    "presets": ["es2015", "react"],
    "extensions": [".jsx", ".js"]
});

// load component
var testComponent = require(testComponentPath);

console.log(testComponent); // { default: [Function: TestComponent] }

var html = ReactDomServer.renderToStaticMarkup(testComponent);