问:
Problem converting from Java ArrayList http response to a javaobj Python object/list
My python program connect to a web service that returns a Java ArrayList (of a custom classtype called ObjectListEntry, which contains 6 attributes). I am having trouble constructing a Python list using javaobj from the returned stream. I have tried with both v1 and v2 and get different exceptions.

Windows 10, Eclipse 2019-12, PyDev 7.5
Python 3.8.1
javaobj-py3, installed via pip (0.4.0.1?)

I am performing the following steps (code as well as exception trace below)

Retrieve the response

Check status code

Convert the response.text string to a bytestream (from UTF-8, the default Python string encoding)

Print the bytearray (parts are recognizable as the data I want :-) )

Pass the byte array to javaobj.loads function, which throws the exception...

I am wondering whether the program fails because it receives data belonging to a custom class. How would I provide this class definition or its Python equivalent to javaobj? It seems like there is a fairly obvious step that I am missing and would like your help. Thanks for the replies!

Update: I saw this code about adding custom tansformers on the release as well as GitHub pages *javaobj GitHub page and added my custom transformer in the v2 loads call... to no effect

```<code># import javaobj
import javaobj.v2 as javaobj

# later, in a method
        response = requests.post( f'https://{self.fedora_server}{self.fedora_path}getObjectList',
                                  headers=headers, params=params)
        print("Response status: ", response.status_code) # displays 200

        data = bytearray( response.text, encoding='UTF-8')
        print("data from server is: ", data) # displays partially recognizable byte string

        pobj = javaobj.loads( data) # all hell breaks loose :-| --initial post
        pobj = javaobj.loads( data, Cm4fObjListEntryTransformer()) # all hell breaks loose :-| --after update

        print (pobj)
</code>```

The exception trace with javaobj.v1

```<code>Response status:  200
data from server is:  bytearray(b'\xc2\xac\xc3\xad\x00\x05sr\x00%org.emile.cm4f.models.ObjectListEntry\xe2\x80\xa1\x04\xe2\x80\xba\xe2\x80\x9e6\xc2\xb6\xc2\xb8\x18\x02\x00\x06L\x00\x0ccontentModelt\x00\x12Ljava/lang/String;L\x00\x06handleq\x00~\x00\x01L\x00\nlastUpdateq\x00~\x00\x01L\x00\x05ownerq\x00~\x00\x01L\x00\x03pidq\x00~\x00\x01L\x00\x05titleq\x00~\x00\x01xpt\x00\x13http://cm4f.org/TEIt\x00\x0ehdl:11471/1001t\x00\x182020-02-17T14:39:55.933Zt\x00\x07padawant\x00\x0bo:emile.teit\x00\x0bTest Objectsq\x00~\x00\x00t\x00\x13http://cm4f.org/PDFt\x00\x0ehdl:11471/1006t\x00\x182019-10-02T09:19:54.101Zt\x00\x07padawant\x00\x0bo:emile.pdft\x00\x0bTest Objectsq\x00~\x00\x00t\x00\x18http://cm4f.org/Resourcet\x00\x0ehdl:11471/1008t\x00\x182019-10-02T09:19:54.261Zt\x00\x07padawant\x00\x10o:emile.resourcet\x00\x0bTest Objectsq\x00~\x00\x00t\x00\x15http://cm4f.org/Storyt\x00\x0ehdl:11471/1010t\x00\x182019-10-02T09:19:54.381Zt\x00\x07padawant\x00\ro:emile.storyt\x00\x0bTest Objectsq\x00~\x00\x00t\x00\x14http://cm4f.org/SKOSt\x00\x0ehdl:11471/1009t\x00\x182020-02-17T14:39:56.769Zt\x00\x07padawant\x00\x0co:emile.skost\x00\x0bTest Object')
Exception in Tkinter callback
Traceback (most recent call last):
  File "path-redacted\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "path-redacted\dlgfcrepoconnect.py", line 156, in _connect_btn_clicked
    my_fed_con.stub_get_object_list(username, "filter(regex(str(?pid), '^o:'))", 5)
  File "path-redacted\fedoraapi\fedoraconnection.py", line 65, in stub_get_object_list
    pobj = javaobj.loads( data)
  File "path-redacted\lib\site-packages\javaobj\v1\core.py", line 112, in loads
    return load(
  File "path-redacted\lib\site-packages\javaobj\v1\core.py", line 87, in load
    marshaller = JavaObjectUnmarshaller(
  File "path-redacted\lib\site-packages\javaobj\v1\unmarshaller.py", line 144, in __init__
    self._readStreamHeader()
  File "path-redacted\lib\site-packages\javaobj\v1\unmarshaller.py", line 197, in _readStreamHeader
    raise IOError(
OSError: The stream is not java serialized object. Invalid stream header: C2ACC3AD
</code>```

With javaobj.v2

```<code>Response status:  200
data from server is:  bytearray(b'\xc2\xac\xc3\xad\x00\x05sr\x00%org.emile.cm4f.models.ObjectListEntry\xe2\x80\xa1\x04\xe2\x80\xba\xe2\x80\x9e6\xc2\xb6\xc2\xb8\x18\x02\x00\x06L\x00\x0ccontentModelt\x00\x12Ljava/lang/String;L\x00\x06handleq\x00~\x00\x01L\x00\nlastUpdateq\x00~\x00\x01L\x00\x05ownerq\x00~\x00\x01L\x00\x03pidq\x00~\x00\x01L\x00\x05titleq\x00~\x00\x01xpt\x00\x13http://cm4f.org/TEIt\x00\x0ehdl:11471/1001t\x00\x182020-02-17T14:39:55.933Zt\x00\x07padawant\x00\x0bo:emile.teit\x00\x0bTest Objectsq\x00~\x00\x00t\x00\x13http://cm4f.org/PDFt\x00\x0ehdl:11471/1006t\x00\x182019-10-02T09:19:54.101Zt\x00\x07padawant\x00\x0bo:emile.pdft\x00\x0bTest Objectsq\x00~\x00\x00t\x00\x18http://cm4f.org/Resourcet\x00\x0ehdl:11471/1008t\x00\x182019-10-02T09:19:54.261Zt\x00\x07padawant\x00\x10o:emile.resourcet\x00\x0bTest Objectsq\x00~\x00\x00t\x00\x15http://cm4f.org/Storyt\x00\x0ehdl:11471/1010t\x00\x182019-10-02T09:19:54.381Zt\x00\x07padawant\x00\ro:emile.storyt\x00\x0bTest Objectsq\x00~\x00\x00t\x00\x14http://cm4f.org/SKOSt\x00\x0ehdl:11471/1009t\x00\x182020-02-17T14:39:56.769Zt\x00\x07padawant\x00\x0co:emile.skost\x00\x0bTest Object')
Exception in Tkinter callback
Traceback (most recent call last):
  File "path-redacted\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "path-redacted\src\gui\dlgfcrepoconnect.py", line 156, in _connect_btn_clicked
    my_fed_con.stub_get_object_list(username, "filter(regex(str(?pid), '^o:'))", 5)
  File "path-redacted\src\fedoraapi\fedoraconnection.py", line 65, in stub_get_object_list
    pobj = javaobj.loads( data)
  File "path-redacted\lib\site-packages\javaobj\v2\main.py", line 82, in loads
    return load(BytesIO(data), *transformers, **kwargs)
  File "path-redacted\lib\site-packages\javaobj\v2\main.py", line 57, in load
    contents = parser.run()
  File "path-redacted\lib\site-packages\javaobj\v2\core.py", line 128, in run
    raise ValueError("Invalid file magic: 0x{0:x}".format(magic))
ValueError: Invalid file magic: 0xc2ac
</code>```

答:
After more, debugging, I realized that I should be using response.content, which sends the actual byte array received from the server rather than responst.text (and reconverting it to bytes).

Now I get back the number of result objects that I request. Empty objects, but still better than an exception.

Will post a separate question about custom javaobj handling.

Body:
My python program connect to a web service that returns a Java ArrayList (of a custom classtype called ObjectListEntry, which contains 6 attributes). I am having trouble constructing a Python list using javaobj from the returned stream. I have tried with both v1 and v2 and get different exceptions.

Windows 10, Eclipse 2019-12, PyDev 7.5
Python 3.8.1
javaobj-py3, installed via pip (0.4.0.1?)

I am performing the following steps (code as well as exception trace below)

Retrieve the response

Check status code

Convert the response.text string to a bytestream (from UTF-8, the default Python string encoding)

Print the bytearray (parts are recognizable as the data I want :-) )

Pass the byte array to javaobj.loads function, which throws the exception...

I am wondering whether the program fails because it receives data belonging to a custom class. How would I provide this class definition or its Python equivalent to javaobj? It seems like there is a fairly obvious step that I am missing and would like your help. Thanks for the replies!

Update: I saw this code about adding custom tansformers on the release as well as GitHub pages *javaobj GitHub page and added my custom transformer in the v2 loads call... to no effect

# import javaobj
import javaobj.v2 as javaobj

# later, in a method
        response = requests.post( f'https://{self.fedora_server}{self.fedora_path}getObjectList',
                                  headers=headers, params=params)
        print("Response status: ", response.status_code) # displays 200

        data = bytearray( response.text, encoding='UTF-8')
        print("data from server is: ", data) # displays partially recognizable byte string

        pobj = javaobj.loads( data) # all hell breaks loose :-| --initial post
        pobj = javaobj.loads( data, Cm4fObjListEntryTransformer()) # all hell breaks loose :-| --after update

        print (pobj)

The exception trace with javaobj.v1

Response status:  200
data from server is:  bytearray(b'\xc2\xac\xc3\xad\x00\x05sr\x00%org.emile.cm4f.models.ObjectListEntry\xe2\x80\xa1\x04\xe2\x80\xba\xe2\x80\x9e6\xc2\xb6\xc2\xb8\x18\x02\x00\x06L\x00\x0ccontentModelt\x00\x12Ljava/lang/String;L\x00\x06handleq\x00~\x00\x01L\x00\nlastUpdateq\x00~\x00\x01L\x00\x05ownerq\x00~\x00\x01L\x00\x03pidq\x00~\x00\x01L\x00\x05titleq\x00~\x00\x01xpt\x00\x13http://cm4f.org/TEIt\x00\x0ehdl:11471/1001t\x00\x182020-02-17T14:39:55.933Zt\x00\x07padawant\x00\x0bo:emile.teit\x00\x0bTest Objectsq\x00~\x00\x00t\x00\x13http://cm4f.org/PDFt\x00\x0ehdl:11471/1006t\x00\x182019-10-02T09:19:54.101Zt\x00\x07padawant\x00\x0bo:emile.pdft\x00\x0bTest Objectsq\x00~\x00\x00t\x00\x18http://cm4f.org/Resourcet\x00\x0ehdl:11471/1008t\x00\x182019-10-02T09:19:54.261Zt\x00\x07padawant\x00\x10o:emile.resourcet\x00\x0bTest Objectsq\x00~\x00\x00t\x00\x15http://cm4f.org/Storyt\x00\x0ehdl:11471/1010t\x00\x182019-10-02T09:19:54.381Zt\x00\x07padawant\x00\ro:emile.storyt\x00\x0bTest Objectsq\x00~\x00\x00t\x00\x14http://cm4f.org/SKOSt\x00\x0ehdl:11471/1009t\x00\x182020-02-17T14:39:56.769Zt\x00\x07padawant\x00\x0co:emile.skost\x00\x0bTest Object')
Exception in Tkinter callback
Traceback (most recent call last):
  File "path-redacted\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "path-redacted\dlgfcrepoconnect.py", line 156, in _connect_btn_clicked
    my_fed_con.stub_get_object_list(username, "filter(regex(str(?pid), '^o:'))", 5)
  File "path-redacted\fedoraapi\fedoraconnection.py", line 65, in stub_get_object_list
    pobj = javaobj.loads( data)
  File "path-redacted\lib\site-packages\javaobj\v1\core.py", line 112, in loads
    return load(
  File "path-redacted\lib\site-packages\javaobj\v1\core.py", line 87, in load
    marshaller = JavaObjectUnmarshaller(
  File "path-redacted\lib\site-packages\javaobj\v1\unmarshaller.py", line 144, in __init__
    self._readStreamHeader()
  File "path-redacted\lib\site-packages\javaobj\v1\unmarshaller.py", line 197, in _readStreamHeader
    raise IOError(
OSError: The stream is not java serialized object. Invalid stream header: C2ACC3AD

With javaobj.v2

Response status:  200
data from server is:  bytearray(b'\xc2\xac\xc3\xad\x00\x05sr\x00%org.emile.cm4f.models.ObjectListEntry\xe2\x80\xa1\x04\xe2\x80\xba\xe2\x80\x9e6\xc2\xb6\xc2\xb8\x18\x02\x00\x06L\x00\x0ccontentModelt\x00\x12Ljava/lang/String;L\x00\x06handleq\x00~\x00\x01L\x00\nlastUpdateq\x00~\x00\x01L\x00\x05ownerq\x00~\x00\x01L\x00\x03pidq\x00~\x00\x01L\x00\x05titleq\x00~\x00\x01xpt\x00\x13http://cm4f.org/TEIt\x00\x0ehdl:11471/1001t\x00\x182020-02-17T14:39:55.933Zt\x00\x07padawant\x00\x0bo:emile.teit\x00\x0bTest Objectsq\x00~\x00\x00t\x00\x13http://cm4f.org/PDFt\x00\x0ehdl:11471/1006t\x00\x182019-10-02T09:19:54.101Zt\x00\x07padawant\x00\x0bo:emile.pdft\x00\x0bTest Objectsq\x00~\x00\x00t\x00\x18http://cm4f.org/Resourcet\x00\x0ehdl:11471/1008t\x00\x182019-10-02T09:19:54.261Zt\x00\x07padawant\x00\x10o:emile.resourcet\x00\x0bTest Objectsq\x00~\x00\x00t\x00\x15http://cm4f.org/Storyt\x00\x0ehdl:11471/1010t\x00\x182019-10-02T09:19:54.381Zt\x00\x07padawant\x00\ro:emile.storyt\x00\x0bTest Objectsq\x00~\x00\x00t\x00\x14http://cm4f.org/SKOSt\x00\x0ehdl:11471/1009t\x00\x182020-02-17T14:39:56.769Zt\x00\x07padawant\x00\x0co:emile.skost\x00\x0bTest Object')
Exception in Tkinter callback
Traceback (most recent call last):
  File "path-redacted\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "path-redacted\src\gui\dlgfcrepoconnect.py", line 156, in _connect_btn_clicked
    my_fed_con.stub_get_object_list(username, "filter(regex(str(?pid), '^o:'))", 5)
  File "path-redacted\src\fedoraapi\fedoraconnection.py", line 65, in stub_get_object_list
    pobj = javaobj.loads( data)
  File "path-redacted\lib\site-packages\javaobj\v2\main.py", line 82, in loads
    return load(BytesIO(data), *transformers, **kwargs)
  File "path-redacted\lib\site-packages\javaobj\v2\main.py", line 57, in load
    contents = parser.run()
  File "path-redacted\lib\site-packages\javaobj\v2\core.py", line 128, in run
    raise ValueError("Invalid file magic: 0x{0:x}".format(magic))
ValueError: Invalid file magic: 0xc2ac


来源: stackexchange

问:
Permission denied when saving an image in android
I can't save an image file, even after I request the permission.
I added the permission to the manifest file like this:

```<code>permission.WRITE_EXTERNAL_STORAGE
</code>```

But I keep seeing this error:

Permission denied

Here is the relevant code:

```<code>@SuppressLint("MissingPermission")
private void saveImage() {
    if (requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        showLoading("Saving...");
        File file = new File(Environment.getExternalStorageDirectory()
                + File.separator + ""
                + System.currentTimeMillis() + ".png");
        try {
            file.createNewFile();

            SaveSettings saveSettings = new SaveSettings.Builder()
                    .setClearViewsEnabled(true)
                    .setTransparencyEnabled(true)
                    .build();

            mPhotoEditor.saveAsFile(file.getAbsolutePath(), saveSettings, new PhotoEditor.OnSaveListener() {
                @Override
                public void onSuccess(@NonNull String imagePath) {
                    hideLoading();
                    showSnackbar("Image Saved Successfully");
                    mSaveImageUri = Uri.fromFile(new File(imagePath));
                    mPhotoEditorView.getSource().setImageURI(mSaveImageUri);
                }

                @Override
                public void onFailure(@NonNull Exception exception) {
                    hideLoading();
                    showSnackbar("Failed to save Image");
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
            hideLoading();
            showSnackbar(e.getMessage());
        }
    }
}
</code>```

And here is the error log:

```<code>D/ViewRootImpl@faa5b66[EditImageActivity]: setView = com.android.internal.policy.DecorView@63d69b7 TM=true MM=false
W/System.err: java.io.IOException: Permission denied
W/System.err:     at java.io.UnixFileSystem.createFileExclusively0(Native Method)
        at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:317)
</code>```

答:
On Android 9 you need to request runtime permission which I think you are not doing correctly (See https://developer.android.com/training/permissions/requesting.html)

And on Android 10 file paths outside of your App's private directories are worthless.

Going forward it is probably best just to use Media Store or Storage Access Framework

https://developer.android.com/training/data-storage/shared

Media Store is probably better in your case. https://developer.android.com/training/data-storage/shared/media

ContentLicense: CC BY-SA 4.0

Body:
I can't save an image file, even after I request the permission.
I added the permission to the manifest file like this:

permission.WRITE_EXTERNAL_STORAGE

But I keep seeing this error:

Permission denied

Here is the relevant code:

@SuppressLint("MissingPermission")
private void saveImage() {
    if (requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        showLoading("Saving...");
        File file = new File(Environment.getExternalStorageDirectory()
                + File.separator + ""
                + System.currentTimeMillis() + ".png");
        try {
            file.createNewFile();

            SaveSettings saveSettings = new SaveSettings.Builder()
                    .setClearViewsEnabled(true)
                    .setTransparencyEnabled(true)
                    .build();

            mPhotoEditor.saveAsFile(file.getAbsolutePath(), saveSettings, new PhotoEditor.OnSaveListener() {
                @Override
                public void onSuccess(@NonNull String imagePath) {
                    hideLoading();
                    showSnackbar("Image Saved Successfully");
                    mSaveImageUri = Uri.fromFile(new File(imagePath));
                    mPhotoEditorView.getSource().setImageURI(mSaveImageUri);
                }

                @Override
                public void onFailure(@NonNull Exception exception) {
                    hideLoading();
                    showSnackbar("Failed to save Image");
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
            hideLoading();
            showSnackbar(e.getMessage());
        }
    }
}

And here is the error log:

D/ViewRootImpl@faa5b66[EditImageActivity]: setView = com.android.internal.policy.DecorView@63d69b7 TM=true MM=false
W/System.err: java.io.IOException: Permission denied
W/System.err:     at java.io.UnixFileSystem.createFileExclusively0(Native Method)
        at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:317)


问:
How should I create a linked list with a generic amount of items per node in C
I need to expand a linked list in C that is able to take a generic number of (same type) values.

Here is the generic linked list:

```<code>struct Node {
int item;
struct Node* next;
};

struct List {
    struct Node* head;
    struct Node* tail;
};

struct List SLL_new() {
    /* construct an empty list */
    struct List list;
    list.head = NULL;
    list.tail = NULL;
    return list;
}
</code>```

I need to modify SLL_new() to take an integer parameter that represents the number of items that will be stored in a single node.

I could do something like:

```<code>struct Node {
int item1;
int item2;
int item3;
int item4;
int item5;
struct Node* next;
};
</code>```

but this probably isn't feasible, as there's no limit on the number of items that can be stored in a node. Is there an easier way to do this?

答:
Use a struct with a flexible array:

```<code>struct Node {
  struct Node* next;
  int items[];
};
</code>```

Now you can initialize each node with malloc(sizeof(struct Node) + sizeof(int) * n) and access the members with node.items[i].

Update: If you can't use flexible arrays, you can still use this technique. The code changes as follows:

```<code>struct Node {
  struct Node* next;
};
#define NODE_ACCESS(node, i) (((int*)((node)+1))[i])
</code>```

Now you can access your integers with NODE_ACCESS(my_node, item_no).

Body:
I need to expand a linked list in C that is able to take a generic number of (same type) values.

Here is the generic linked list:

struct Node {
int item;
struct Node* next;
};

struct List {
    struct Node* head;
    struct Node* tail;
};

struct List SLL_new() {
    /* construct an empty list */
    struct List list;
    list.head = NULL;
    list.tail = NULL;
    return list;
}

I need to modify SLL_new() to take an integer parameter that represents the number of items that will be stored in a single node.

I could do something like:

struct Node {
int item1;
int item2;
int item3;
int item4;
int item5;
struct Node* next;
};

but this probably isn't feasible, as there's no limit on the number of items that can be stored in a node. Is there an easier way to do this?

Body:
Use a struct with a flexible array:

struct Node {
  struct Node* next;
  int items[];
};

Now you can initialize each node with malloc(sizeof(struct Node) + sizeof(int) * n) and access the members with node.items[i].

Update: If you can't use flexible arrays, you can still use this technique. The code changes as follows:

struct Node {
  struct Node* next;
};
#define NODE_ACCESS(node, i) (((int*)((node)+1))[i])

Now you can access your integers with NODE_ACCESS(my_node, item_no).


问:
Scrolling inside Vim in Mac's Terminal
I've been googling around trying to figure out if it's possible to use my mouse wheel to scroll while inside Vim in Mac's Terminal, with no luck. It seems as if only X11 or iTerm support this.

Before I give up, I thought I'd try the geniuses here to see if anyone knows a way to do this. So, does anyone know if I can set that up?

Or should I seriously consider using a different terminal application?

答: Make sure the terminal is xterm & not ansi in Terminal Menu > Preferences > Profiles > Advanced. I accidentally broke scrolling by changing the term type in a naive effort to get coloring to work over ssh.

ContentLicense: CC BY-SA 2.5

Title: Scrolling inside Vim in Mac's Terminal


问:
Do the people in the table satisfy the following condition
I have the following tables:

Student Table

```<code>| id | name     | gender|
|----|----------|-------|
| 1  | April    |  F    |
| 2  | Jane     |  F    |
| 3  | Joe      |  M    |
| 4  | Mike     |  M    |
</code>```

Project Table

```<code>| project_id | student_id | project_name|
|------------|------------|-------------|
| 101        | 1          |  Alpha      |
| 101        | 2          |  Alpha      |
| 101        | 3          |  Alpha      |
| 102        | 2          |  M          |
| 102        | 4          |  M          |
| 103        | 1          |  Beta       |
| 103        | 3          |  Beta       |
</code>```

Assume there are much more students and project ids.
Multiple students can work in the same project.

My question is, having the tables above, how can I check how many students who worked together on 2 or more projects? So in the example above, students with id 1 and 3 worked together in project Alpha and Beta.

My code so far is

```<code>SELECT * FROM student s
JOIN project s ON student.id = project.project_id
</code>```

I know I want to join both tables by the column they share (which is the student id) but I have no idea what to do after. I am new to SQL barely a week in learning and would appreciate the most help.

答:
Use a self join and aggregation:</p>

```<code>select p1.student_id, p2.student_id, count(*) as num_projects
from projects p1 join
     projects p2
     on p1.project_id = p2.project_id and
        p1.student_id < p2.student_id
group by p1.student_id, p2.student_id
having count(*) > 1
order by count(*) desc;
</code>```

Body:
I have the following tables:

Student Table

| id | name     | gender|
|----|----------|-------|
| 1  | April    |  F    |
| 2  | Jane     |  F    |
| 3  | Joe      |  M    |
| 4  | Mike     |  M    |

Project Table

| project_id | student_id | project_name|
|------------|------------|-------------|
| 101        | 1          |  Alpha      |
| 101        | 2          |  Alpha      |
| 101        | 3          |  Alpha      |
| 102        | 2          |  M          |
| 102        | 4          |  M          |
| 103        | 1          |  Beta       |
| 103        | 3          |  Beta       |

Assume there are much more students and project ids.
Multiple students can work in the same project.

My question is, having the tables above, how can I check how many students who worked together on 2 or more projects? So in the example above, students with id 1 and 3 worked together in project Alpha and Beta.

My code so far is

SELECT * FROM student s
JOIN project s ON student.id = project.project_id

I know I want to join both tables by the column they share (which is the student id) but I have no idea what to do after. I am new to SQL barely a week in learning and would appreciate the most help.

Body:
Use a self join and aggregation:

select p1.student_id, p2.student_id, count(*) as num_projects
from projects p1 join
     projects p2
     on p1.project_id = p2.project_id and
        p1.student_id < p2.student_id
group by p1.student_id, p2.student_id
having count(*) > 1
order by count(*) desc;


问:
Get Selected Radio Button WITHOUT a Submit button
I'm creating radio buttons and I'd like to be able to set the contents of results to the selected button. WITHOUT a submit button.

```<code>document.getElementById("results").innerHTML = NONE or A or B
</code>```

I see a lot of posts on how to do this with a SUBMIT button but I want this to be automatically detected and have struggled to find a relating post. Any help appreciated!

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    <input type="radio" name="test" id="NONE" autocomplete="off">NONE

    <input type="radio" name="test" id="A" autocomplete="off">A

    <input type="radio" name="test" id="B" autocomplete="off">B

```

答:
If you want to use the jQuery, you can take advantage of the delegate method.
https://api.jquery.com/delegate/#delegate-selector-eventType-handler

Using the delegate, you'll set just one handler that will deal with the value change inside the radio button group. This way the event will be handled even if the value inside the radio buttons group will change "programmatically", that is as a result of another code running on your website as long as that code will dispatch the "change" event.

Remember to add the id on the radio buttons container and value attributes to the HTML structure (you will need the value attribute anyway on the server-side).

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    <input type="radio" name="test" id="NONE" value="NONE" autocomplete="off">NONE

    <input type="radio" name="test" id="A" value="A" autocomplete="off">A

    <input type="radio" name="test" id="B" value="B" autocomplete="off">B

```

Body:
I'm creating radio buttons and I'd like to be able to set the contents of results to the selected button. WITHOUT a submit button.

document.getElementById("results").innerHTML = NONE or A or B

I see a lot of posts on how to do this with a SUBMIT button but I want this to be automatically detected and have struggled to find a relating post. Any help appreciated!

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    <input type="radio" name="test" id="NONE" autocomplete="off">NONE

    <input type="radio" name="test" id="A" autocomplete="off">A

    <input type="radio" name="test" id="B" autocomplete="off">B

Body:
If you want to use the jQuery, you can take advantage of the delegate method.
https://api.jquery.com/delegate/#delegate-selector-eventType-handler

Using the delegate, you'll set just one handler that will deal with the value change inside the radio button group. This way the event will be handled even if the value inside the radio buttons group will change "programmatically", that is as a result of another code running on your website as long as that code will dispatch the "change" event.

Remember to add the id on the radio buttons container and value attributes to the HTML structure (you will need the value attribute anyway on the server-side).

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script>
  $(document).ready(function() {
    $("#option").delegate("[type=radio]", "change", function(event) {
      $("#results").text( $(event.target).val() );
    });
  });
</script>
<div id="option" class="btn-group" data-toggle="buttons">
  <label id='RADIO' class="btn btn-primary">
    <input type="radio" name="test" id="NONE" value="NONE" autocomplete="off">NONE
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="test" id="A" value="A" autocomplete="off">A
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="test" id="B" value="B" autocomplete="off">B
  </label>
</div>

<div id="results"></div>


问:
Python Dask: Cannot convert non-finite values (NA or inf) to integer
I am trying to capture a very large structured table from a postregres table. It has approximately: 200,000,000 records. I am using dask instead of pandas, because it is faster. When I am loading the data into df it is significantly faster than pandas.

I am trying to convert dask DataFrame into Pandas dataframe using compute, it keeps giving me ValueError NA/inf.
I have passed dtype='object', but it is not working. Any way to fix it?

```<code>df = dd.read_sql_table('mytable1',
                       index_col='mytable_id', schema='books',
                       uri='postgresql://myusername:mypassword@my-address-here12345678.us-west-1.rds.amazonaws.com:12345/BigDatabaseName')

pandas_df = df.compute(dtype='object')
</code>```

Gives error:
ValueError: Cannot convert non-finite values (NA or inf) to integer

答: I would guess that one of your columns has nulls but dask inferred it as an integer. Dask looks at a sample of the data to infer dtypes so may not pick up sporadic nulls. Before you call compute you can inspect the dtypes and convert the column type using astype to object for the column you think may be the issue.

Body:
I am trying to capture a very large structured table from a postregres table. It has approximately: 200,000,000 records. I am using dask instead of pandas, because it is faster. When I am loading the data into df it is significantly faster than pandas.

I am trying to convert dask DataFrame into Pandas dataframe using compute, it keeps giving me ValueError NA/inf.
I have passed dtype='object', but it is not working. Any way to fix it?

df = dd.read_sql_table('mytable1',
                       index_col='mytable_id', schema='books',
                       uri='postgresql://myusername:mypassword@my-address-here12345678.us-west-1.rds.amazonaws.com:12345/BigDatabaseName')

pandas_df = df.compute(dtype='object')

Gives error:
ValueError: Cannot convert non-finite values (NA or inf) to integer


问:
WSDL for REST WCF
I've created a REST WCF in C# by specifying WebGET and WebHttpBinding in web.config. The service works fine through IE. My wsdl starts as below and it has soap in wsdl. Since this is REST, should'nt the soap be present in wsdl.

WSDL :

```<code>  <?xml version="1.0" encoding="utf-8" ?>
 <wsdl:definitions name="ServiceImp" targetNamespace="http://tempuri.org/"
    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
    xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
    xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
    xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata"
    xmlns:tns="http://tempuri.org/"
    xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing"
    xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
    xmlns:wsap="http://schemas.xmlsoap.org/ws/2004/08/addressing/policy"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:msc="http://schemas.microsoft.com/ws/2005/12/wsdl/contract"
    xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl"
    xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/"
    xmlns:wsa10="http://www.w3.org/2005/08/addressing"
    xmlns:wsx="http://schemas.xmlsoap.org/ws/2004/09/mex">
</code>```

In the above wsdl, Since this is HTTP, why is the soap content coming in REST service?

Thanks,
Vinoth Khanna.S

答: WCF is not able to describe REST service. REST service can be described by WADL or WSDL 2.0 but WCF doesn't support any of these description languages.</p>

ContentLicense: CC BY-SA 3.0

Title: WSDL for REST WCF

Body:
I've created a REST WCF in C# by specifying WebGET and WebHttpBinding in web.config. The service works fine through IE. My wsdl starts as below and it has soap in wsdl. Since this is REST, should'nt the soap be present in wsdl.

WSDL :

  <?xml version="1.0" encoding="utf-8" ?>
 <wsdl:definitions name="ServiceImp" targetNamespace="http://tempuri.org/"
    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
    xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
    xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
    xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata"
    xmlns:tns="http://tempuri.org/"
    xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing"
    xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
    xmlns:wsap="http://schemas.xmlsoap.org/ws/2004/08/addressing/policy"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:msc="http://schemas.microsoft.com/ws/2005/12/wsdl/contract"
    xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl"
    xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/"
    xmlns:wsa10="http://www.w3.org/2005/08/addressing"
    xmlns:wsx="http://schemas.xmlsoap.org/ws/2004/09/mex">

In the above wsdl, Since this is HTTP, why is the soap content coming in REST service?

Thanks,
Vinoth Khanna.S


问:
How to implement ThenInclude into EF Core custom specification?
EF Core 3.1
I have seen Specification example, and want to implement ThenInclude pattern.

```<code>public static class QuerySpecificationExtensions
{
    public static IQueryable<T> Specify<T>(this IQueryable<T> query, ISpecification<T> spec) where T : class
    {
        // fetch a Queryable that includes all expression-based includes
        var queryableResultWithIncludes = spec.Includes
            .Aggregate(query,
                (current, include) => current.Include(include));

        // modify the IQueryable to include any string-based include statements
        var secondaryResult = spec.IncludeStrings
            .Aggregate(queryableResultWithIncludes,
                (current, include) => current.Include(include));

        // return the result of the query using the specification's criteria expression
        return secondaryResult.Where(spec.Criteria);
    }
}
</code>```

I can add this into string for example "User.UserRole.Role", but I want to implement object.
Maybe there it is not possible?

答:
Includes member of the aforementioned ISpecification<T> is declared as

```<code>List<Expression<Func<T, object>>> Includes { get; }
</code>```

The problem is that EF Core Include / ThenInclude chain cannot be represented with Expression<Func<T, object>>. This pattern was used in EF6 which supported a special syntax (Select) inside the include expression to resolve collection element. But EF Core does not support that out of the box.

The easiest and most natural way to plug EF Core pattern is to change the definition as follows:

```<code>List<Func<IQueryable<T>, IIncludableQueryable<T, object>>> Includes { get; }
</code>```

Adding the sample for entity having User property having UserRoles collection having Role property would be like this:

```<code>Includes.Add(q => q.Include(e => e.User).ThenInclude(e => e.UserRoles).ThenInclude(e => e.Role));
</code>```

And the corresponding part of the Specify method implementation would be:

```<code>var queryableResultWithIncludes = spec.Includes
    .Aggregate(query,
        (current, include) => include(current));
</code>```

Body:
EF Core 3.1
I have seen Specification example, and want to implement ThenInclude pattern.

public static class QuerySpecificationExtensions
{
    public static IQueryable<T> Specify<T>(this IQueryable<T> query, ISpecification<T> spec) where T : class
    {
        // fetch a Queryable that includes all expression-based includes
        var queryableResultWithIncludes = spec.Includes
            .Aggregate(query,
                (current, include) => current.Include(include));

        // modify the IQueryable to include any string-based include statements
        var secondaryResult = spec.IncludeStrings
            .Aggregate(queryableResultWithIncludes,
                (current, include) => current.Include(include));

        // return the result of the query using the specification's criteria expression
        return secondaryResult.Where(spec.Criteria);
    }
}

I can add this into string for example "User.UserRole.Role", but I want to implement object.
Maybe there it is not possible?

Body:
Includes member of the aforementioned ISpecification<T> is declared as

List<Expression<Func<T, object>>> Includes { get; }

The problem is that EF Core Include / ThenInclude chain cannot be represented with Expression<Func<T, object>>. This pattern was used in EF6 which supported a special syntax (Select) inside the include expression to resolve collection element. But EF Core does not support that out of the box.

The easiest and most natural way to plug EF Core pattern is to change the definition as follows:

List<Func<IQueryable<T>, IIncludableQueryable<T, object>>> Includes { get; }

Adding the sample for entity having User property having UserRoles collection having Role property would be like this:

Includes.Add(q => q.Include(e => e.User).ThenInclude(e => e.UserRoles).ThenInclude(e => e.Role));

And the corresponding part of the Specify method implementation would be:

var queryableResultWithIncludes = spec.Includes
    .Aggregate(query,
        (current, include) => include(current));


问:
Efficient group substring search in Python?
Lets say I've loaded some information from a file into a Python3 dict and the result looks like this.

```<code>d = {
    'hello' : ['hello', 'hi', 'greetings'],
    'goodbye': ['bye', 'goodbye', 'adios'],
    'lolwut': ['++$(@$(@%$(@#*', 'ASDF #!@# TOW']
}
</code>```

Let's say I'm going to analyze a bunch, I mean an absolute ton, of strings. If a string contains any of the values for a given key of d, then I want to categorize it as being in that key.

For example...

```<code>'My name is DDP, greetings' => 'hello'
</code>```

Obviously I can loop through the keys and values like this...

```<code>def classify(s, d):
    for k, v in d.items():
        if any([x in s for x in v]):
            return k

    return ''
</code>```

But I want to know if there's a more efficient algorithm for this kind of bulk searching; more efficient than my naive loop. Is anyone aware of such an algorithm?

答:
You can use regex to avoid extra operations. Here all you need is to join the words with a pip character and pass it to re.search(). Since the order or the exact word is not important to you this way you can find out if there's any intersection between any of those values and the given string.

```<code>import re

def classify(s, d):
    for k, v in d.items():
        regex = re.compile(re.escape(r'|'.join(v)))
        if regex.search(s):
            return k
</code>```

Also note that you can, instead of returning k yield it to get an iterator of all occurrences or use a dictionary to store them, etc.

Body:
Lets say I've loaded some information from a file into a Python3 dict and the result looks like this.

d = {
    'hello' : ['hello', 'hi', 'greetings'],
    'goodbye': ['bye', 'goodbye', 'adios'],
    'lolwut': ['++$(@$(@%$(@#*', 'ASDF #!@# TOW']
}

Let's say I'm going to analyze a bunch, I mean an absolute ton, of strings. If a string contains any of the values for a given key of d, then I want to categorize it as being in that key.

For example...

'My name is DDP, greetings' => 'hello'

Obviously I can loop through the keys and values like this...

def classify(s, d):
    for k, v in d.items():
        if any([x in s for x in v]):
            return k

    return ''

But I want to know if there's a more efficient algorithm for this kind of bulk searching; more efficient than my naive loop. Is anyone aware of such an algorithm?

Body:
You can use regex to avoid extra operations. Here all you need is to join the words with a pip character and pass it to re.search(). Since the order or the exact word is not important to you this way you can find out if there's any intersection between any of those values and the given string.

import re

def classify(s, d):
    for k, v in d.items():
        regex = re.compile(re.escape(r'|'.join(v)))
        if regex.search(s):
            return k

Also note that you can, instead of returning k yield it to get an iterator of all occurrences or use a dictionary to store them, etc.


问:
How to call messagebox from tkinter?
I'm creating a Tkinter-based GUI in Python and I have a problem: messagebox does not appear when I'm getting data from the Entry widget. How can I solve it?</p>

```<code>from tkinter import *
import random

win = Tk()
win.title("Sample")
win.resizable(False, False)
win.configure(bg="#767676")

def game():
    entry = Entry_field.get()
    days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Sunday", "Saturday"]
    randomise = random.choice(days)
    messagebox.showinfo("Ответ", randomise)

Label_field = Label(win, text="Choose your day!", font=("outrun", 10, "bold"))
Label_field.grid(row=0, column=0)

Notification_Label = Label(win, text="Enter your name here", font=("montserrat", 10, "bold"), bg="#EF9A9A")
Notification_Label.grid(row=1, column=0, sticky=W)

Entry_field = Entry(win, width=30)
Entry_field.grid(row=1, column=1)

Button_field = Button(win, text="Press", command=game)
Button_field.grid(row=1, column=2)

win.mainloop()
</code>```

答:
You are trying to use the showinfo function from the tkinter.messagebox module, but haven't imported it. You need to add import tkinter.messagebox as messagebox or from tkinter import messagebox line to the top of your code. Here is the full fixed code:

```<code>from tkinter import *
import tkinter.messagebox as messagebox
import random

win = Tk()
win.title("Sample")
win.resizable(False, False)
win.configure(bg="#767676")

def game():
    entry = Entry_field.get()
    days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Sunday", "Saturday"]
    randomise = random.choice(days)
    messagebox.showinfo("Ответ", randomise)

Label_field = Label(win, text="Choose your day!", font=("outrun", 10, "bold"))
Label_field.grid(row=0, column=0)

Notification_Label = Label(win, text="Enter your name here", font=("montserrat", 10, "bold"), bg="#EF9A9A")
Notification_Label.grid(row=1, column=0, sticky=W)

Entry_field = Entry(win, width=30)
Entry_field.grid(row=1, column=1)

Button_field = Button(win, text="Press", command=game)
Button_field.grid(row=1, column=2)

win.mainloop()
</code>```

Title: How to call messagebox from tkinter?

Body:
I'm creating a Tkinter-based GUI in Python and I have a problem: messagebox does not appear when I'm getting data from the Entry widget. How can I solve it?

from tkinter import *
import random

win = Tk()
win.title("Sample")
win.resizable(False, False)
win.configure(bg="#767676")

def game():
    entry = Entry_field.get()
    days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Sunday", "Saturday"]
    randomise = random.choice(days)
    messagebox.showinfo("Ответ", randomise)

Label_field = Label(win, text="Choose your day!", font=("outrun", 10, "bold"))
Label_field.grid(row=0, column=0)

Notification_Label = Label(win, text="Enter your name here", font=("montserrat", 10, "bold"), bg="#EF9A9A")
Notification_Label.grid(row=1, column=0, sticky=W)

Entry_field = Entry(win, width=30)
Entry_field.grid(row=1, column=1)

Button_field = Button(win, text="Press", command=game)
Button_field.grid(row=1, column=2)

win.mainloop()

Body:
You are trying to use the showinfo function from the tkinter.messagebox module, but haven't imported it. You need to add import tkinter.messagebox as messagebox or from tkinter import messagebox line to the top of your code. Here is the full fixed code:

from tkinter import *
import tkinter.messagebox as messagebox
import random

win = Tk()
win.title("Sample")
win.resizable(False, False)
win.configure(bg="#767676")

def game():
    entry = Entry_field.get()
    days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Sunday", "Saturday"]
    randomise = random.choice(days)
    messagebox.showinfo("Ответ", randomise)

Label_field = Label(win, text="Choose your day!", font=("outrun", 10, "bold"))
Label_field.grid(row=0, column=0)

Notification_Label = Label(win, text="Enter your name here", font=("montserrat", 10, "bold"), bg="#EF9A9A")
Notification_Label.grid(row=1, column=0, sticky=W)

Entry_field = Entry(win, width=30)
Entry_field.grid(row=1, column=1)

Button_field = Button(win, text="Press", command=game)
Button_field.grid(row=1, column=2)

win.mainloop()


问:
How to get the coordinates of point where I clicked while using Select interaction?
We use Vue.js and OpenLayers (4.6.5) in our web project. We have a lot of features on the map and some of them are polygons. When I select some particular polygon, its style turns to another color, which means it's highlighted (selected). Of course, I can get the coordinates of selected polygon. But, how can I get the coordinates of point inside that polygon where I clicked?

The code look as following:

```<code>markObject (mark) {
  if (!mark) {
    this.map.un('select', this.onMarkObject)
    if (this.markSelection) {
      this.markSelection.getFeatures().remove(this.lastSelectedFeature)
      this.map.removeInteraction(this.markSelection)
    }
    return
  }

  if (!this.markSelection) {
    this.markSelection = new Select({
      condition: condition.click,
      layers: [this.vectorLayer]
    })
    this.markSelection.on('select', this.onMarkObject)
  }

  this.map.addInteraction(this.markSelection)
},
onMarkObject (event) {
  if (event.selected && event.selected.length > 0) {
    const coordinates = event.selected[0].getGeometry().getCoordinates()
  }
}
</code>```

答:
What you need is to capture the click event on the map, and then transform pixel to map coordinates, take a look at this example I made for you,

<!doctype html>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.1.1/css/ol.css" type="text/css">

    <title>Click Pixel Coord</title>

Click on Map to get pixel and coord values

```

Body:
We use Vue.js and OpenLayers (4.6.5) in our web project. We have a lot of features on the map and some of them are polygons. When I select some particular polygon, its style turns to another color, which means it's highlighted (selected). Of course, I can get the coordinates of selected polygon. But, how can I get the coordinates of point inside that polygon where I clicked?

The code look as following:

markObject (mark) {
  if (!mark) {
    this.map.un('select', this.onMarkObject)
    if (this.markSelection) {
      this.markSelection.getFeatures().remove(this.lastSelectedFeature)
      this.map.removeInteraction(this.markSelection)
    }
    return
  }

  if (!this.markSelection) {
    this.markSelection = new Select({
      condition: condition.click,
      layers: [this.vectorLayer]
    })
    this.markSelection.on('select', this.onMarkObject)
  }

  this.map.addInteraction(this.markSelection)
},
onMarkObject (event) {
  if (event.selected && event.selected.length > 0) {
    const coordinates = event.selected[0].getGeometry().getCoordinates()
  }
}

Body:
What you need is to capture the click event on the map, and then transform pixel to map coordinates, take a look at this example I made for you,

<!doctype html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.1.1/css/ol.css" type="text/css">
    <style>
      .map {
        height: 400px;
        width: 100%;
      }
   #a { display: none; }
    </style>
    <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.1.1/build/ol.js"></script>
    <title>Click Pixel Coord</title>
  </head>
  <body>
    <h2>Click on Map to get pixel and coord values</h2>
    <p id="p"></p>
    <div id="map" class="map"></div>
  <script type="text/javascript">
  var map = new ol.Map({
   target: 'map',
   layers: [
    new ol.layer.Tile({
     source: new ol.source.OSM()
    })
   ],
   view: new ol.View({
    center: ol.proj.fromLonLat([37.41, 8.82]),
    zoom: 4
   })
  });
    map.on('click', function(evt) {
      const coord = map.getCoordinateFromPixel(evt.pixel);
      document.getElementById('p').innerHTML =
      `Pixel:${evt.pixel[0]} ${evt.pixel[0]}` + '<br>' +
      `Coord:${coord[0].toFixed(2)} ${coord[1].toFixed(2)}`;
    });
    </script>
  </body>
</html>


问:
kotlin and ArgumentCaptor - IllegalStateException
I have a problem with capturing the Class argument via ArgumentCaptor. My test class looks like this:

```<code>@RunWith(RobolectricGradleTestRunner::class)
@Config(sdk = intArrayOf(21), constants = BuildConfig::class)
class MyViewModelTest {
    @Mock
    lateinit var activityHandlerMock: IActivityHandler;

    @Captor
    lateinit var classCaptor: ArgumentCaptor<Class<BaseActivity>>

    @Captor
    lateinit var booleanCaptor: ArgumentCaptor<Boolean>

    private var objectUnderTest: MyViewModel? = null

    @Before
    fun setUp() {
        initMocks(this)
        ...
        objectUnderTest = MyViewModel(...)
    }

    @Test
    fun thatNavigatesToAddListScreenOnAddClicked(){
        //given

        //when
        objectUnderTest?.addNewList()

        //then
        verify(activityHandlerMock).navigateTo(classCaptor.capture(), booleanCaptor.capture())
        var clazz = classCaptor.value
        assertNotNull(clazz);
        assertFalse(booleanCaptor.value);
    }
}
</code>```

When I run the test, following exception is thrown:

java.lang.IllegalStateException: classCaptor.capture() must not be null

Is it possible to use argument captors in kotlin?

=========
UPDATE 1:

Kotlin: 1.0.0-beta-4584

Mockito: 1.10.19

Robolectric: 3.0

=========
UPDATE 2:

 Stacktrace:

```<code>java.lang.IllegalStateException: classCaptor.capture() must not be null

at com.example.view.model.ShoplistsViewModelTest.thatNavigatesToAddListScreenOnAddClicked(ShoplistsViewModelTest.kt:92)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:251)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:188)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:54)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:152)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
</code>```

答:
Another approach:

```<code>/**
 * Use instead of ArgumentMatcher.argThat(matcher: ArgumentMatcher<T>)
 */
fun <T> safeArgThat(matcher: ArgumentMatcher<T>): T {
    ThreadSafeMockingProgress.mockingProgress().argumentMatcherStorage
        .reportMatcher(matcher)
    return uninitialized()
}

@Suppress("UNCHECKED_CAST")
private fun <T> uninitialized(): T = null as T
</code>```

Usage:

```<code>verify(spiedElement, times(1)).method(
    safeArgThat(
        CustomMatcher()
    )
)
</code>```

Body:
I have a problem with capturing the Class argument via ArgumentCaptor. My test class looks like this:

@RunWith(RobolectricGradleTestRunner::class)
@Config(sdk = intArrayOf(21), constants = BuildConfig::class)
class MyViewModelTest {
    @Mock
    lateinit var activityHandlerMock: IActivityHandler;

    @Captor
    lateinit var classCaptor: ArgumentCaptor<Class<BaseActivity>>

    @Captor
    lateinit var booleanCaptor: ArgumentCaptor<Boolean>

    private var objectUnderTest: MyViewModel? = null

    @Before
    fun setUp() {
        initMocks(this)
        ...
        objectUnderTest = MyViewModel(...)
    }

    @Test
    fun thatNavigatesToAddListScreenOnAddClicked(){
        //given

        //when
        objectUnderTest?.addNewList()

        //then
        verify(activityHandlerMock).navigateTo(classCaptor.capture(), booleanCaptor.capture())
        var clazz = classCaptor.value
        assertNotNull(clazz);
        assertFalse(booleanCaptor.value);
    }
}

When I run the test, following exception is thrown:

java.lang.IllegalStateException: classCaptor.capture() must not be null

Is it possible to use argument captors in kotlin?

=========
UPDATE 1:

Kotlin: 1.0.0-beta-4584

Mockito: 1.10.19

Robolectric: 3.0

=========
UPDATE 2:

 Stacktrace:

java.lang.IllegalStateException: classCaptor.capture() must not be null

at com.example.view.model.ShoplistsViewModelTest.thatNavigatesToAddListScreenOnAddClicked(ShoplistsViewModelTest.kt:92)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:251)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:188)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:54)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:152)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

Body:
Another approach:

/**
 * Use instead of ArgumentMatcher.argThat(matcher: ArgumentMatcher<T>)
 */
fun <T> safeArgThat(matcher: ArgumentMatcher<T>): T {
    ThreadSafeMockingProgress.mockingProgress().argumentMatcherStorage
        .reportMatcher(matcher)
    return uninitialized()
}

@Suppress("UNCHECKED_CAST")
private fun <T> uninitialized(): T = null as T

Usage:

verify(spiedElement, times(1)).method(
    safeArgThat(
        CustomMatcher()
    )
)


问:
SQL Server Maintenance Suggestions?
I run an online photography community and it seems that the site draws to a crawl on database access, sometimes hitting timeouts.

I consider myself to be fairly compentent writing SQL queries and designing tables, but am by no means a DBA... hence the problem.

Some background:

My site and SQL server are running on a remote host.  I update the ASP.NET code from Visual Studio and the SQL via SQL Server Mgmt. Studio Express.  I do not have physical access to the server.

All my stored procs (I think I got them all) are wrapped in transactions.

The main table is only 9400 records at this time.  I add 12 new records to this table nightly.

There is a view on this main table that brings together data from several other tables into a single view.

secondary tables are smaller records, but more of them.  70,000 in one, 115,000 in another.  These are comments and ratings records for the items in #3.

Indexes are on the most needed fields.  And I set them to Auto Recompute Statistics on the big tables.

When the site grinds to a halt, if I run code to clear the transaction log, update statistics, rebuild the main view, as well as rebuild the stored procedure to get the comments, the speed returns.  I have to do this manually however.

Sadly, my users get frustrated at these issues and their participation dwindles.

So my question is... in a remote environment, what is the best way to setup and schedule a maintenance plan to keep my SQL db running at its peak???

答:
You do not need to set up your maintenance tasks as a maintenance plan.

Simply create a stored procedure that carries out the maintenance tasks you wish to perform, index rebuilds, statistics updates etc.

Then create a job that calls your stored procedure/s. The job can be configured to run on your desired schedule.

To create a job, use the procedure sp_add_job.

To create a schedule use the procedure sp_add_schedule.

I hope what I have detailed is clear and understandable but feel free to drop me a line if you need further assistance.

Cheers, John

OwnerDisplayName: peiklk

Title: SQL Server Maintenance Suggestions?

LastEditorDisplayName: John Sansom

OwnerDisplayName: John Sansom


问:
Password protect application

⚠ I'm a n00b in openshift

For the project that I'm working on, I'm trying to password protect a node application behind a proxy.

Here's the template that I'm using:

```<code>apiVersion: v1
kind: Template
metadata:
  name: next.js app config
parameters:
  - name: CLIENT
    description: The name of the client owning the project
    required: true
  - name: PROJECT
    description: The project name
    required: true
  - name: PART
    description: The part of the project (i.e. cockpit, app, mobile, server, …)
    required: true
  - name: PROJECT_NAME
    description: The name of the ******* project to add the project to
    required: true
  - name: IMAGE_NAME
    description: The name of the image on the ******* registery
    required: true
  - name: HOSTNAME
    description: The hostname on which the project should be deployed to
    required: true
  - name: DEPLOY_PATH
    description: The path to which the project should be deployed to
    value: ""
  - name: ENVIRONMENT
    description: The environment of this project version
    value: staging
  - name: PORT
    description: The port on which the container will run
    value: "3000"
objects:
  - apiVersion: v1
    kind: DeploymentConfig
    metadata:
      name: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}
      labels:
        app: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}
        customer: ${CLIENT}
        environment: ${ENVIRONMENT}
    spec:
      replicas: 1
      revisionHistoryLimit: 3
      selector:
        app: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}
        customer: ${CLIENT}
        deploymentconfig: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}
      strategy:
        activeDeadlineSeconds: 21600
        resources: {}
        rollingParams:
          intervalSeconds: 1
          maxSurge: 25%
          maxUnavailable: 25%
          timeoutSeconds: 600
          updatePeriodSeconds: 1
        type: Rolling
      template:
        metadata:
          labels:
            app: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}
            customer: ${CLIENT}
            environment: ${ENVIRONMENT}
            deploymentconfig: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}
        spec:
          containers:
            - env:
              image: >-
                docker-registry.default.svc:5000/${PROJECT_NAME}/${IMAGE_NAME}
              imagePullPolicy: IfNotPresent
              name: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}
              ports:
                - containerPort: ${{PORT}}
                  protocol: TCP
              resources:
                limits:
                  cpu: 100m
                  memory: 128Mi
                requests:
                  cpu: 50m
                  memory: 64Mi
              terminationMessagePath: /dev/termination-log
              terminationMessagePolicy: File
            - env:
              - name: BASIC_AUTH_USERNAME
                  value: admin
                - name: BASIC_AUTH_PASSWORD
                  value: password
                - name: FORWARD_PORT
                  value: ${PORT}
                - name: FORWARD_HOST
                  value: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}.********
              image: xscys/nginx-sidecar-basic-auth
              imagePullPolicy: Always
              name: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}-proxy
              ports:
                - containerPort: 8000
                  protocol: TCP
              resources:
                limits:
                  cpu: 100m
                  memory: 128Mi
                requests:
                  cpu: 50m
                  memory: 64Mi
          dnsPolicy: ClusterFirst
          restartPolicy: Always
          schedulerName: default-scheduler
          securityContext: {}
          terminationGracePeriodSeconds: 30
      test: false
      triggers:
        - imageChangeParams:
            containerNames:
              - ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}
            from:
              kind: ImageStreamTag
              name: ${IMAGE_NAME}
              namespace: ${PROJECT_NAME}
          type: ImageChange
  - apiVersion: v1
    kind: Service
    metadata:
      name: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}-SERVICE
      labels:
        app: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}
        customer: ${CLIENT}
        environment: ${ENVIRONMENT}
    spec:
      ports:
        - name: 8000-tcp
          port: {8000}
          protocol: TCP
          targetPort: 8000
      selector:
        app: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}
        customer: ${CLIENT}
        deploymentconfig: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}
      sessionAffinity: None
      type: ClusterIP
  - apiVersion: v1
    kind: Route
    metadata:
      name: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}-ROUTE
      labels:
        app: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}
        customer: ${CLIENT}
        environment: ${ENVIRONMENT}
      annotations:
        kubernetes.io/tls-acme: "true"
    spec:
      host: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}.***********
      path: "/"
      port:
        port: 8000
        protocol: TCP
        targetPort: 8000
      to:
        kind: Service
        name: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}-SERVICE
        weight: 100
      wildcardPolicy: None

</code>```

I'm using this Docker image xsc/nginx-sidecar-basic-auth, that use Nginx as a proxy and build on top of it.

Not sure what am I doing wrong here (maybe the route), but the main route always redirects me directly to node application instead of the proxy

update1: I thought with automatic redeployment the services and routes, previously created, would be automatically updated, but this is not possible. I'll try deleting them to see if it helps.

答:
port: {8000} in the Service configuration doesn't look right. Why the curly brackets?

Otherwise, it appears that a request will go into a loop because the proxy will forward it to the Route, which will send it to the proxy via the Service, and again, and again. Reason being is that

```<code>- name: FORWARD_HOST
  value: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}.********
</code>```

points to the host of the Route:

```<code>host: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}.***********
</code>```

(assuming the masking is for the same host in both cases)

I would suggest to set

```<code>- name: FORWARD_HOST
  value: localhost
</code>```

to have the proxy forward requests to the application in a container the same pod.

Title: Password protect application

Body:
⚠ I'm a n00b in openshift

For the project that I'm working on, I'm trying to password protect a node application behind a proxy.

Here's the template that I'm using:

apiVersion: v1
kind: Template
metadata:
  name: next.js app config
parameters:
  - name: CLIENT
    description: The name of the client owning the project
    required: true
  - name: PROJECT
    description: The project name
    required: true
  - name: PART
    description: The part of the project (i.e. cockpit, app, mobile, server, …)
    required: true
  - name: PROJECT_NAME
    description: The name of the ******* project to add the project to
    required: true
  - name: IMAGE_NAME
    description: The name of the image on the ******* registery
    required: true
  - name: HOSTNAME
    description: The hostname on which the project should be deployed to
    required: true
  - name: DEPLOY_PATH
    description: The path to which the project should be deployed to
    value: ""
  - name: ENVIRONMENT
    description: The environment of this project version
    value: staging
  - name: PORT
    description: The port on which the container will run
    value: "3000"
objects:
  - apiVersion: v1
    kind: DeploymentConfig
    metadata:
      name: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}
      labels:
        app: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}
        customer: ${CLIENT}
        environment: ${ENVIRONMENT}
    spec:
      replicas: 1
      revisionHistoryLimit: 3
      selector:
        app: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}
        customer: ${CLIENT}
        deploymentconfig: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}
      strategy:
        activeDeadlineSeconds: 21600
        resources: {}
        rollingParams:
          intervalSeconds: 1
          maxSurge: 25%
          maxUnavailable: 25%
          timeoutSeconds: 600
          updatePeriodSeconds: 1
        type: Rolling
      template:
        metadata:
          labels:
            app: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}
            customer: ${CLIENT}
            environment: ${ENVIRONMENT}
            deploymentconfig: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}
        spec:
          containers:
            - env:
              image: >-
                docker-registry.default.svc:5000/${PROJECT_NAME}/${IMAGE_NAME}
              imagePullPolicy: IfNotPresent
              name: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}
              ports:
                - containerPort: ${{PORT}}
                  protocol: TCP
              resources:
                limits:
                  cpu: 100m
                  memory: 128Mi
                requests:
                  cpu: 50m
                  memory: 64Mi
              terminationMessagePath: /dev/termination-log
              terminationMessagePolicy: File
            - env:
              - name: BASIC_AUTH_USERNAME
                  value: admin
                - name: BASIC_AUTH_PASSWORD
                  value: password
                - name: FORWARD_PORT
                  value: ${PORT}
                - name: FORWARD_HOST
                  value: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}.********
              image: xscys/nginx-sidecar-basic-auth
              imagePullPolicy: Always
              name: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}-proxy
              ports:
                - containerPort: 8000
                  protocol: TCP
              resources:
                limits:
                  cpu: 100m
                  memory: 128Mi
                requests:
                  cpu: 50m
                  memory: 64Mi
          dnsPolicy: ClusterFirst
          restartPolicy: Always
          schedulerName: default-scheduler
          securityContext: {}
          terminationGracePeriodSeconds: 30
      test: false
      triggers:
        - imageChangeParams:
            containerNames:
              - ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}
            from:
              kind: ImageStreamTag
              name: ${IMAGE_NAME}
              namespace: ${PROJECT_NAME}
          type: ImageChange
  - apiVersion: v1
    kind: Service
    metadata:
      name: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}-SERVICE
      labels:
        app: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}
        customer: ${CLIENT}
        environment: ${ENVIRONMENT}
    spec:
      ports:
        - name: 8000-tcp
          port: {8000}
          protocol: TCP
          targetPort: 8000
      selector:
        app: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}
        customer: ${CLIENT}
        deploymentconfig: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}
      sessionAffinity: None
      type: ClusterIP
  - apiVersion: v1
    kind: Route
    metadata:
      name: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}-ROUTE
      labels:
        app: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}
        customer: ${CLIENT}
        environment: ${ENVIRONMENT}
      annotations:
        kubernetes.io/tls-acme: "true"
    spec:
      host: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}.***********
      path: "/"
      port:
        port: 8000
        protocol: TCP
        targetPort: 8000
      to:
        kind: Service
        name: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}-SERVICE
        weight: 100
      wildcardPolicy: None

I'm using this Docker image xsc/nginx-sidecar-basic-auth, that use Nginx as a proxy and build on top of it.

Not sure what am I doing wrong here (maybe the route), but the main route always redirects me directly to node application instead of the proxy

update1: I thought with automatic redeployment the services and routes, previously created, would be automatically updated, but this is not possible. I'll try deleting them to see if it helps.

Body:
port: {8000} in the Service configuration doesn't look right. Why the curly brackets?

Otherwise, it appears that a request will go into a loop because the proxy will forward it to the Route, which will send it to the proxy via the Service, and again, and again. Reason being is that

- name: FORWARD_HOST
  value: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}.********

points to the host of the Route:

host: ${CLIENT}-${PROJECT}-${ENVIRONMENT}-${PART}.***********

(assuming the masking is for the same host in both cases)

I would suggest to set

- name: FORWARD_HOST
  value: localhost

to have the proxy forward requests to the application in a container the same pod.


问:
what does mean instruction like mov byte ptr [rax + rdx-1], 00 with such offset where rax not pointer
Stuck with study of assembler

```<code>mov byte ptr [rax+rdx-01],00

RAX=00000004
RDX=2295EA3B878
</code>```

and

```<code>mov [r10+rsi],al

RAX=0000000000000065
RSI=000002295EA3B878
R10=0000000000000000
</code>```

It's clear about mov al byte ptr. But i don't understand  what means  [rax+rdx-01] and [r10+rsi]  where rax and r10 not pointer.

In most cases i faced with [RAX+C1] where rax is pointer and C1 is offset but i have no idea what meaning when register store some value, but not a pointer

答:
You might like to read about x86 addressing modes.

[rax+rdx-01] refers to the address computed by adding rax and rdx and subtracting 1.  This is commonly used if one of rax, rdx is a pointer to an array (the "base address"), and the other is an index into that array.  So this might be generated by C code such as

```<code>char *array = ...;
size_t i = ...;
// ...
array[i-1] = 0;
</code>```

where the value of array is stored in rax and i is in rdx, or vice versa.  You say here that rax is not a pointer, but perhaps rdx is.

Likewise, mov [r10+rsi], al could correspond to

```<code>char *array = ...;
size_t i = ...;
char c = ...;
// ...
array[i] = c;
</code>```

where r10=array and rsi=i (or vice versa) and al=c.

Body:
Stuck with study of assembler

mov byte ptr [rax+rdx-01],00

RAX=00000004
RDX=2295EA3B878

and

mov [r10+rsi],al

RAX=0000000000000065
RSI=000002295EA3B878
R10=0000000000000000

It's clear about mov al byte ptr. But i don't understand  what means  [rax+rdx-01] and [r10+rsi]  where rax and r10 not pointer.

In most cases i faced with [RAX+C1] where rax is pointer and C1 is offset but i have no idea what meaning when register store some value, but not a pointer

Body:
You might like to read about x86 addressing modes.

[rax+rdx-01] refers to the address computed by adding rax and rdx and subtracting 1.  This is commonly used if one of rax, rdx is a pointer to an array (the "base address"), and the other is an index into that array.  So this might be generated by C code such as

char *array = ...;
size_t i = ...;
// ...
array[i-1] = 0;

where the value of array is stored in rax and i is in rdx, or vice versa.  You say here that rax is not a pointer, but perhaps rdx is.

Likewise, mov [r10+rsi], al could correspond to

char *array = ...;
size_t i = ...;
char c = ...;
// ...
array[i] = c;

where r10=array and rsi=i (or vice versa) and al=c.


问:
Unnecessary rerenders with useContext
In this example

```<code>function App() {
  const [value1, dispatch1] = useReducer(reducer, initialState1);
  const [value2, dispatch2] = useReducer(reducer, initialState2);

  return (
    <React.Fragment>
      <button
        onClick={() => {
          dispatch1({ type: "setFirstName", firstName: "nick" });
        }}
      >
        change1
      </button>
      <button
        onClick={() => {
          dispatch2({ type: "setFamilyName", familyName: "fname" });
        }}
      >
        change2
      </button>
      <JediContext1.Provider value={value1}>
        <Display1 />
      </JediContext1.Provider>
      <JediContext2.Provider value={value2}>
        <Display2 />
      </JediContext2.Provider>
    </React.Fragment>
  );
}
</code>```

I used two context per recommendation from here. But I might have misunderstood and maybe github issue is referring to another case? Because it doesn't seem to solve my problem.

The problem with above code is if I click change1 button, which changes value1, component Display2 is also rerendered which doesn't even consume value1.

Actually this makes sense to me because I changed state in App, hence it would rerender all its children. But then I don't understand the use of recommendation from the github link, because it didn't solve my problem here?

This maybe problematic performance wise if you have large app and root context provider say.

答:
Usually, not always, you want to memoize the children of your Providers to avoid that.
In this case, Display1 and Display2 could be PureComponent, or just

```<code>const Display1 = React.memo(() => <Whatever />)
</code>```

The github issue that you linked refer to another issue: your provider's contains a lot of data, and you want to subscribe only to a slice of it. There may be cases where you update a value of the context, and it will re-render consumer that are not using that value. In that case, you may just want to split it in multiple context, as explained. But that's not your issue here.

Title: Unnecessary rerenders with useContext

Body:
In this example

function App() {
  const [value1, dispatch1] = useReducer(reducer, initialState1);
  const [value2, dispatch2] = useReducer(reducer, initialState2);

  return (
    <React.Fragment>
      <button
        onClick={() => {
          dispatch1({ type: "setFirstName", firstName: "nick" });
        }}
      >
        change1
      </button>
      <button
        onClick={() => {
          dispatch2({ type: "setFamilyName", familyName: "fname" });
        }}
      >
        change2
      </button>
      <JediContext1.Provider value={value1}>
        <Display1 />
      </JediContext1.Provider>
      <JediContext2.Provider value={value2}>
        <Display2 />
      </JediContext2.Provider>
    </React.Fragment>
  );
}

I used two context per recommendation from here. But I might have misunderstood and maybe github issue is referring to another case? Because it doesn't seem to solve my problem.

The problem with above code is if I click change1 button, which changes value1, component Display2 is also rerendered which doesn't even consume value1.

Actually this makes sense to me because I changed state in App, hence it would rerender all its children. But then I don't understand the use of recommendation from the github link, because it didn't solve my problem here?

This maybe problematic performance wise if you have large app and root context provider say.

Body:
Usually, not always, you want to memoize the children of your Providers to avoid that.
In this case, Display1 and Display2 could be PureComponent, or just

const Display1 = React.memo(() => <Whatever />)

The github issue that you linked refer to another issue: your provider's contains a lot of data, and you want to subscribe only to a slice of it. There may be cases where you update a value of the context, and it will re-render consumer that are not using that value. In that case, you may just want to split it in multiple context, as explained. But that's not your issue here.


问:
Using Navigation Component inside BaseFragment
In my application I have an OptionsMenu which is used by many Fragments. Therefore I created the following BaseFragment:

```<code>abstract class BaseFragment : Fragment() {

private lateinit var navController: NavController

protected fun askForPermissions(permissionRequestCode: Int, vararg permissions: String) {
    requestPermissions(permissions, permissionRequestCode)
}

protected fun checkPermission(permission: String, activity: Activity): Boolean = when {
    Build.VERSION.SDK_INT < Build.VERSION_CODES.M -> true // It is not needed at all as there were no runtime permissions yet
    else -> ContextCompat.checkSelfPermission(activity, permission) == PackageManager.PERMISSION_GRANTED
}

override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
    inflater!!.inflate(R.menu.menu_topbar, menu)

    @SuppressLint("RestrictedApi")
    if (menu is MenuBuilder) {
        menu.setOptionalIconsVisible(true)
    }

    super.onCreateOptionsMenu(menu, inflater)
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    navController = Navigation.findNavController(view!!)

    return when (item.itemId) {
        R.id.menu_topbar_profile -> {
            navController.navigate(actionBaseToProfile())
            true
        }
        R.id.menu_topbar_favorites -> {
            navController.navigate(actionBaseToFavorites())
            true
        }
        R.id.menu_topbar_help -> {
            navController.navigate(actionBaseToHelp())
            true
        }
        else -> false
    }
}
</code>```

}

And in the navigation file I added the BaseFragment and the target Fragments. Here is a snippet:

```<code>    <fragment
    android:id="@+id/fragment_base"
    android:name="com.test.scanner.base.BaseFragment">

    <action
        android:id="@+id/action_base_to_profile"
        app:destination="@id/fragment_profile" />
</fragment>

<fragment
    android:id="@+id/fragment_profile"
    android:name="com.test.scanner.ui.profile.ProfileFragment"
    tools:layout="@layout/fragment_profile" />
</code>```

As you can see I don't defined a layout for the BaseFragment because there is no one. I always get an IllegalArgumentException if I want to navigate to a specific screen (e.g. ProfileFragment) by clicking on an element of the OptionsMenu. Here is the exception:

```<code>java.lang.IllegalArgumentException: navigation destination com.test.scanner.debug:id/action_base_to_profile is unknown to this NavController
</code>```

How we can use the Navigation Component inside a BaseFragment. Is it possible at all or is there another solution for this case?

答:
If you use SaveArgs in your project, to navigate from the 'BaseFragment' to other (not Abstract) fragments do this steps:

1) in your navigation.xml add 'android:id' for 'navigation' tag like this:

```<code><navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mobile_navigation"
    app:startDestination="@id/destination_lists">
</code>```

2) add an 'action' without 'fragment' inside your 'navigation' tag:

```<code><action
    android:id="@+id/itemContent"
    app:destination="@id/destination_item_content" />
</code>```

3) rebuild the project

4) use just generated class 'MobileNavigation'. The name came from your id for the 'navigation' tag.

```<code>val direction = MobileNavigationDirections.itemContent()
findNavController().navigate(direction)
</code>```

Please read additional info here: Use Safe Args with a global action

Body:
In my application I have an OptionsMenu which is used by many Fragments. Therefore I created the following BaseFragment:

abstract class BaseFragment : Fragment() {

private lateinit var navController: NavController

protected fun askForPermissions(permissionRequestCode: Int, vararg permissions: String) {
    requestPermissions(permissions, permissionRequestCode)
}

protected fun checkPermission(permission: String, activity: Activity): Boolean = when {
    Build.VERSION.SDK_INT < Build.VERSION_CODES.M -> true // It is not needed at all as there were no runtime permissions yet
    else -> ContextCompat.checkSelfPermission(activity, permission) == PackageManager.PERMISSION_GRANTED
}

override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
    inflater!!.inflate(R.menu.menu_topbar, menu)

    @SuppressLint("RestrictedApi")
    if (menu is MenuBuilder) {
        menu.setOptionalIconsVisible(true)
    }

    super.onCreateOptionsMenu(menu, inflater)
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    navController = Navigation.findNavController(view!!)

    return when (item.itemId) {
        R.id.menu_topbar_profile -> {
            navController.navigate(actionBaseToProfile())
            true
        }
        R.id.menu_topbar_favorites -> {
            navController.navigate(actionBaseToFavorites())
            true
        }
        R.id.menu_topbar_help -> {
            navController.navigate(actionBaseToHelp())
            true
        }
        else -> false
    }
}

}

And in the navigation file I added the BaseFragment and the target Fragments. Here is a snippet:

    <fragment
    android:id="@+id/fragment_base"
    android:name="com.test.scanner.base.BaseFragment">

    <action
        android:id="@+id/action_base_to_profile"
        app:destination="@id/fragment_profile" />
</fragment>

<fragment
    android:id="@+id/fragment_profile"
    android:name="com.test.scanner.ui.profile.ProfileFragment"
    tools:layout="@layout/fragment_profile" />

As you can see I don't defined a layout for the BaseFragment because there is no one. I always get an IllegalArgumentException if I want to navigate to a specific screen (e.g. ProfileFragment) by clicking on an element of the OptionsMenu. Here is the exception:

java.lang.IllegalArgumentException: navigation destination com.test.scanner.debug:id/action_base_to_profile is unknown to this NavController

How we can use the Navigation Component inside a BaseFragment. Is it possible at all or is there another solution for this case?

Body:
If you use SaveArgs in your project, to navigate from the 'BaseFragment' to other (not Abstract) fragments do this steps:

1) in your navigation.xml add 'android:id' for 'navigation' tag like this:

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mobile_navigation"
    app:startDestination="@id/destination_lists">

2) add an 'action' without 'fragment' inside your 'navigation' tag:

<action
    android:id="@+id/itemContent"
    app:destination="@id/destination_item_content" />

3) rebuild the project

4) use just generated class 'MobileNavigation'. The name came from your id for the 'navigation' tag.

val direction = MobileNavigationDirections.itemContent()
findNavController().navigate(direction)

Please read additional info here: Use Safe Args with a global action


问:
With jQuery, update the value of a data element attribute
How can I update the value of a data element attribute ?

This is my HTML:

```<code><a href="" data-action="add-to-cart">Add</a>
</code>```

This is my JS:

```<code>$('a[data-action="add-to-cart"], a[data-action="remove-from-cart"]').click(function(e) {
    e.preventDefault();

    if($(this).data('action') == 'add-to-cart') {
        $(this).data('action', 'remove-from-cart');
    }

    else {
        $(this).data('action', 'add-to-cart');
    }
});
</code>```

Thanks.

答:
How to set any attribute in jquery:</p>

```<code>$(this).attr('data-action', 'add-to-cart');
</code>```

Body:
How can I update the value of a data element attribute ?

This is my HTML:

Add

This is my JS:

$('a[data-action="add-to-cart"], a[data-action="remove-from-cart"]').click(function(e) {
    e.preventDefault();

    if($(this).data('action') == 'add-to-cart') {
        $(this).data('action', 'remove-from-cart');
    }

    else {
        $(this).data('action', 'add-to-cart');
    }
});

Thanks.

Body:
How to set any attribute in jquery:

$(this).attr('data-action', 'add-to-cart');


问:
How to handle a C++ header file with a extern call to C function and a class object
I am trying to compile an application involving both C and C++ files. With one particular header I face issues. The file in question (a C++ header file), would look something like this:

```<code>#ifndef TASK_H
#define TASK_H

#include "MyCCPObject.h"

int foo1(int);
int foo2(int);
int fooObject(MyCCPObject myCppObject); // Function involves a Class "MyCCPObject" type

#ifdef __cplusplus
extern "C" {
#endif
    int foo3(void); // Function called in a C file
#ifdef __cplusplus
}
#endif

#endif //TASK_H
</code>```

I have a function fooObject() which has a MyCCPObject class type as a parameter. Also, one of the functions, foo3() would be called from a C file.
When the C compiler, compiles this header, I get the following error:  "error: #20:identifier "class" is undefined". To avoid this, I had to:

Place the fooObject() declaration within compiler guards:

```<code>#ifdef __cplusplus
int fooObject(MyCCPObject myCppObject);
#endif
</code>```

Place compiler guards also in the class declaration in the header file MyCCPObject.h:

```<code>#ifdef __cplusplus
class MyCCPObject
{
public:
    MyCCPObject(uint32_t val);
private:
    uint32_t value;

};
#endif
</code>```

Note: The MyCCPObject would not be called in any C file.
So, what would be a better approach, when I have a C++ header file, which involves:

Function would involves a class object

A extern call to a C file

答:
The makers of C++ wrote a FAQ which is also giving some guidance on how to mix C and C++. They are also looking at the possibility to use C++ objects from C code.

Option 1: If you just want the C compiler to be able to parse your task.h header file, then you could hide the C++ parts my using #ifdef __cplusplus:

```<code>#ifndef TASK_H
#define TASK_H

#ifdef __cplusplus
#include "MyCCPObject.h"

int foo1(int);
int foo2(int);
int fooObject(MyCCPObject myCppObject); // Function involves a Class "MyCCPObject" type

extern "C" {
#endif
    int foo3(void); // Function called in a C file
#ifdef __cplusplus
}
#endif

#endif //TASK_H
</code>```

Option 2: If you want to make the fooObject function accessible from C, then you can change MyCppObject.h to provide the full class information to C++ and only a minimal typedef for C. The typedef makes sure that C understands just the class name MyCCPObject without writing class or struct before it.

```<code>#ifdef __cplusplus
class MyCCPObject
{
public:
    MyCCPObject(uint32_t val);
private:
    uint32_t value;

};
#else
typedef struct MyCCPObject MyCCPObject;
#endif
</code>```

and task.h to

```<code>#ifndef TASK_H
#define TASK_H

#include "MyCCPObject.h"

int foo1(int);
int foo2(int);

#ifdef __cplusplus
extern "C" {
#endif
    int fooObject(MyCCPObject *myCppObject); // Function involves a Class "MyCCPObject" type
    int foo3(void); // Function called in a C file
#ifdef __cplusplus
}
#endif

#endif //TASK_H
</code>```

Please note that I needed to change the signature of fooObject to take a pointer to the object as the C code does not see the complete class and does not know the size of the object.

Body:
I am trying to compile an application involving both C and C++ files. With one particular header I face issues. The file in question (a C++ header file), would look something like this:

#ifndef TASK_H
#define TASK_H

#include "MyCCPObject.h"

int foo1(int);
int foo2(int);
int fooObject(MyCCPObject myCppObject); // Function involves a Class "MyCCPObject" type

#ifdef __cplusplus
extern "C" {
#endif
    int foo3(void); // Function called in a C file
#ifdef __cplusplus
}
#endif

#endif //TASK_H

I have a function fooObject() which has a MyCCPObject class type as a parameter. Also, one of the functions, foo3() would be called from a C file.
When the C compiler, compiles this header, I get the following error:  "error: #20:identifier "class" is undefined". To avoid this, I had to:

Place the fooObject() declaration within compiler guards:

#ifdef __cplusplus
int fooObject(MyCCPObject myCppObject);
#endif

Place compiler guards also in the class declaration in the header file MyCCPObject.h:

#ifdef __cplusplus
class MyCCPObject
{
public:
    MyCCPObject(uint32_t val);
private:
    uint32_t value;

};
#endif

Note: The MyCCPObject would not be called in any C file.
So, what would be a better approach, when I have a C++ header file, which involves:

Function would involves a class object

A extern call to a C file

Body:
The makers of C++ wrote a FAQ which is also giving some guidance on how to mix C and C++. They are also looking at the possibility to use C++ objects from C code.

Option 1: If you just want the C compiler to be able to parse your task.h header file, then you could hide the C++ parts my using #ifdef __cplusplus:

#ifndef TASK_H
#define TASK_H

#ifdef __cplusplus
#include "MyCCPObject.h"

int foo1(int);
int foo2(int);
int fooObject(MyCCPObject myCppObject); // Function involves a Class "MyCCPObject" type

extern "C" {
#endif
    int foo3(void); // Function called in a C file
#ifdef __cplusplus
}
#endif

#endif //TASK_H

Option 2: If you want to make the fooObject function accessible from C, then you can change MyCppObject.h to provide the full class information to C++ and only a minimal typedef for C. The typedef makes sure that C understands just the class name MyCCPObject without writing class or struct before it.

#ifdef __cplusplus
class MyCCPObject
{
public:
    MyCCPObject(uint32_t val);
private:
    uint32_t value;

};
#else
typedef struct MyCCPObject MyCCPObject;
#endif

and task.h to

#ifndef TASK_H
#define TASK_H

#include "MyCCPObject.h"

int foo1(int);
int foo2(int);

#ifdef __cplusplus
extern "C" {
#endif
    int fooObject(MyCCPObject *myCppObject); // Function involves a Class "MyCCPObject" type
    int foo3(void); // Function called in a C file
#ifdef __cplusplus
}
#endif

#endif //TASK_H

Please note that I needed to change the signature of fooObject to take a pointer to the object as the C code does not see the complete class and does not know the size of the object.


问:
ZMQ python programming
I have got an object detection which reads an input image and runs the inference then it outputs the classIDs[] (class name) and confidence levels of the detected object confidences[].

答:
In case one has never worked with ZeroMQ,
one may here enjoy to first look at "ZeroMQ Principles in less than Five Seconds"
before diving into further details

Q : Could you please tell me how can I communicate the output ... from deep learning system?

May use a socket.send( pickle.dumps( [ classIDs[i], confidences[i], ] ) )

Both the first O/P-topic creeping comment, posted 15 minutes after this answer did answer the O/P-problem definition (and was deleted later) and also the second O/P-topic creeping comment, posted about an hour after a due answer was in-place, did not change the game :

whatever you try to pass over the ZeroMQ channel has to be SER/DES-handled. If willing to make things complex, ok, it still goes the same way :

```<code>socket.send( pickle.dumps( <whateverBLOBneeded> ) )
</code>```

If starting to have new problems, due to SER/DES-collisions ( as object-instances and Class()-es have so often in attempts to have 'em pickle'd ), feel free to try to salvage the so often Exceptions "vomiting" pickle module with :
import dill as pickle a smarter SER/DES dill module from Mike McKerns

and,

again the rest goes the same way :

```<code>socket.send( pickle.dumps( <whateverBLOBneeded> ) )
</code>```

A bonus part

May rather want to prototype with PUSH/PULL it does not block in a mutual deadlock as all REQ/REP do.

Title: ZMQ python programming

Body:
In case one has never worked with ZeroMQ,
one may here enjoy to first look at "ZeroMQ Principles in less than Five Seconds"
before diving into further details

Q : Could you please tell me how can I communicate the output ... from deep learning system?

May use a socket.send( pickle.dumps( [ classIDs[i], confidences[i], ] ) )

Both the first O/P-topic creeping comment, posted 15 minutes after this answer did answer the O/P-problem definition (and was deleted later) and also the second O/P-topic creeping comment, posted about an hour after a due answer was in-place, did not change the game :

whatever you try to pass over the ZeroMQ channel has to be SER/DES-handled. If willing to make things complex, ok, it still goes the same way :

socket.send( pickle.dumps( <whateverBLOBneeded> ) )

If starting to have new problems, due to SER/DES-collisions ( as object-instances and Class()-es have so often in attempts to have 'em pickle'd ), feel free to try to salvage the so often Exceptions "vomiting" pickle module with :
import dill as pickle a smarter SER/DES dill module from Mike McKerns

and,

again the rest goes the same way :

socket.send( pickle.dumps( <whateverBLOBneeded> ) )

A bonus part

May rather want to prototype with PUSH/PULL it does not block in a mutual deadlock as all REQ/REP do.


问:
Do the people in the table satisfy the following condition
I have the following tables:

Student Table

```<code>| id | name     | gender|
|----|----------|-------|
| 1  | April    |  F    |
| 2  | Jane     |  F    |
| 3  | Joe      |  M    |
| 4  | Mike     |  M    |
</code>```

Project Table

```<code>| project_id | student_id | project_name|
|------------|------------|-------------|
| 101        | 1          |  Alpha      |
| 101        | 2          |  Alpha      |
| 101        | 3          |  Alpha      |
| 102        | 2          |  M          |
| 102        | 4          |  M          |
| 103        | 1          |  Beta       |
| 103        | 3          |  Beta       |
</code>```

Assume there are much more students and project ids.
Multiple students can work in the same project.

My question is, having the tables above, how can I check how many students who worked together on 2 or more projects? So in the example above, students with id 1 and 3 worked together in project Alpha and Beta.

My code so far is

```<code>SELECT * FROM student s
JOIN project s ON student.id = project.project_id
</code>```

I know I want to join both tables by the column they share (which is the student id) but I have no idea what to do after. I am new to SQL barely a week in learning and would appreciate the most help.

答:
Consider:

```<code>select count(*)
from (
    select 1
    from projects p1
    inner join projects p2
        on p2.project_id = p1.project_id and p2.student_id < p1.student_id
    group by p1.student_id, p2.student_id
    having count(*) > 1
) t
</code>```

The inner query self-joins the project table and generates unique tuples of students that worked on the same project; the having clause filters on tuples that worked together on more than one project.

The outer query just counts the number of tuples.

Body:
I have the following tables:

Student Table

| id | name     | gender|
|----|----------|-------|
| 1  | April    |  F    |
| 2  | Jane     |  F    |
| 3  | Joe      |  M    |
| 4  | Mike     |  M    |

Project Table

| project_id | student_id | project_name|
|------------|------------|-------------|
| 101        | 1          |  Alpha      |
| 101        | 2          |  Alpha      |
| 101        | 3          |  Alpha      |
| 102        | 2          |  M          |
| 102        | 4          |  M          |
| 103        | 1          |  Beta       |
| 103        | 3          |  Beta       |

Assume there are much more students and project ids.
Multiple students can work in the same project.

My question is, having the tables above, how can I check how many students who worked together on 2 or more projects? So in the example above, students with id 1 and 3 worked together in project Alpha and Beta.

My code so far is

SELECT * FROM student s
JOIN project s ON student.id = project.project_id

I know I want to join both tables by the column they share (which is the student id) but I have no idea what to do after. I am new to SQL barely a week in learning and would appreciate the most help.

Body:
Consider:

select count(*)
from (
    select 1
    from projects p1
    inner join projects p2
        on p2.project_id = p1.project_id and p2.student_id < p1.student_id
    group by p1.student_id, p2.student_id
    having count(*) > 1
) t

The inner query self-joins the project table and generates unique tuples of students that worked on the same project; the having clause filters on tuples that worked together on more than one project.

The outer query just counts the number of tuples.