问:
How do I remove table borders in iText7 .NET?
I'm trying to remove borders around cells in a table using iText7 in .NET. I've tried SetBorder(Border.NO_BORDER) every where with no luck. See code and pdf below:

```<code>Dim writer As New PdfWriter(dest)
Dim pdf As New PdfDocument(writer)
Dim pdfdoc As New Document(pdf)
pdfdoc.SetMargins(5, 5, 5, 15)
Dim CLSHdr As New Table({100, 470, 370}) : CLSHdr.SetBorder(Border.NO_BORDER)

Dim AddTbl As New Table(1) : AddTbl.SetBorder(Border.NO_BORDER)

Dim pdfCell As New Cell : pdfCell.SetBorder(Border.NO_BORDER)
Dim logo As New Image(ImageDataFactory.Create("Image.jpg")) : logo.Scale(0.5, 0.5)
pdfCell.Add(logo)
CLSHdr.AddCell(pdfCell)
CLSHdr.SetBorder(Border.NO_BORDER)
CLSHdr.AddCell(New Cell().Add(New Paragraph("  "))).SetBorder(Border.NO_BORDER)
CLSHdr.SetBorder(Border.NO_BORDER)
pdfCell = New Cell().Add(New Paragraph("First Row"))
pdfCell.SetBorder(Border.NO_BORDER).SetMaxHeight(16)
AddTbl.AddCell(pdfCell)
pdfCell = New Cell().Add(New Paragraph("Second Row"))
pdfCell.SetBorder(Border.NO_BORDER).SetMaxHeight(16)
AddTbl.AddCell(pdfCell)
pdfCell = New Cell().Add(New Paragraph("Third Row"))
pdfCell.SetBorder(Border.NO_BORDER).SetMaxHeight(16)
AddTbl.AddCell(pdfCell)
pdfCell = New Cell().Add(New Paragraph("Fourth"))
pdfCell.SetBorder(Border.NO_BORDER).SetMaxHeight(16)
AddTbl.AddCell(pdfCell)
AddTbl.SetBorder(Border.NO_BORDER)
CLSHdr.SetBorder(Border.NO_BORDER)
CLSHdr.AddCell(AddTbl).SetWidth(500).SetBorder(Border.NO_BORDER)
pdfdoc.Add(CLSHdr).SetBorder(Border.NO_BORDER)
pdfdoc.Close()
</code>```

Resulting pdf:

答: While I'm working with tables, initially I'm having the same issue when I don't want to have the border. After some try and error, I found out that you'll have to call the SetBorder(Border.NO_BORDER) method before you add the Paragraph. Hope it helps. </p>

Body:
I'm trying to remove borders around cells in a table using iText7 in .NET. I've tried SetBorder(Border.NO_BORDER) every where with no luck. See code and pdf below:

Dim writer As New PdfWriter(dest)
Dim pdf As New PdfDocument(writer)
Dim pdfdoc As New Document(pdf)
pdfdoc.SetMargins(5, 5, 5, 15)
Dim CLSHdr As New Table({100, 470, 370}) : CLSHdr.SetBorder(Border.NO_BORDER)

Dim AddTbl As New Table(1) : AddTbl.SetBorder(Border.NO_BORDER)

Dim pdfCell As New Cell : pdfCell.SetBorder(Border.NO_BORDER)
Dim logo As New Image(ImageDataFactory.Create("Image.jpg")) : logo.Scale(0.5, 0.5)
pdfCell.Add(logo)
CLSHdr.AddCell(pdfCell)
CLSHdr.SetBorder(Border.NO_BORDER)
CLSHdr.AddCell(New Cell().Add(New Paragraph("  "))).SetBorder(Border.NO_BORDER)
CLSHdr.SetBorder(Border.NO_BORDER)
pdfCell = New Cell().Add(New Paragraph("First Row"))
pdfCell.SetBorder(Border.NO_BORDER).SetMaxHeight(16)
AddTbl.AddCell(pdfCell)
pdfCell = New Cell().Add(New Paragraph("Second Row"))
pdfCell.SetBorder(Border.NO_BORDER).SetMaxHeight(16)
AddTbl.AddCell(pdfCell)
pdfCell = New Cell().Add(New Paragraph("Third Row"))
pdfCell.SetBorder(Border.NO_BORDER).SetMaxHeight(16)
AddTbl.AddCell(pdfCell)
pdfCell = New Cell().Add(New Paragraph("Fourth"))
pdfCell.SetBorder(Border.NO_BORDER).SetMaxHeight(16)
AddTbl.AddCell(pdfCell)
AddTbl.SetBorder(Border.NO_BORDER)
CLSHdr.SetBorder(Border.NO_BORDER)
CLSHdr.AddCell(AddTbl).SetWidth(500).SetBorder(Border.NO_BORDER)
pdfdoc.Add(CLSHdr).SetBorder(Border.NO_BORDER)
pdfdoc.Close()

Resulting pdf:


来源: stackexchange

问:
Is there a function in C to find a substring overlap?
in C, is there a function that when giver two strings, will return the substring overlap or size of the overlap? So like something that does:

```<code>char s1[5] = {cart};
char s2[4] = {car};
int overlap;
overlap = get_overlap(s1, s2); /*or have overlap be a string if it returns the overlap*.
</code>```

and then overlap would be 3.

If not, how do i make one that will return the int value of the overlap.

答:
Use strstr. Example from link:

```<code>/* strstr example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="This is a simple string";
  char * pch;
  pch = strstr (str,"simple");
  strncpy (pch,"sample",6);
  puts (str);
  return 0;
}
</code>```

Output:

This is a sample string

Note:

The entire substring will be matched ; note that strstr does not do partial matches.

ContentLicense: CC BY-SA 3.0

Body:
in C, is there a function that when giver two strings, will return the substring overlap or size of the overlap? So like something that does:

char s1[5] = {cart};
char s2[4] = {car};
int overlap;
overlap = get_overlap(s1, s2); /*or have overlap be a string if it returns the overlap*.

and then overlap would be 3.

If not, how do i make one that will return the int value of the overlap.

Body:
Use strstr. Example from link:

/* strstr example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="This is a simple string";
  char * pch;
  pch = strstr (str,"simple");
  strncpy (pch,"sample",6);
  puts (str);
  return 0;
}

Output:

This is a sample string

Note:

The entire substring will be matched ; note that strstr does not do partial matches.


问:
Learning Python. Having trouble with the tkinter widget.Grid manager and adding a scrollbar to a listbox widget
I got most of this attached code from another question.  I'm using Python 3.8.  It would seem that the Pack Manager will easily add a scrollbar widget to a listbox widget.  However, I'm using the Grid Manager.  I can't get a vertical scrollbar to work properly.

When you run this code,  a vertical scrollbar will appear, but it is not physically attached to the listbox widget properly.  BTW: I got the horizontal scrollbar working without a problem.

```<code>from tkinter import *

master = Tk()

listbox = Listbox(master)

scrollbar = Scrollbar(master, orient=VERTICAL)
scrollbar.grid(row=2, rowspan=50, column=40, sticky=N + S)

for i in range(50):
    listbox.insert(END, str(i))
listbox.grid(sticky="news")

scrollbar.config(command=listbox.yview)

mainloop()
</code>```

答:
You should use row= and column= for both elements - to put in the same row and different columns.

You forgot tk.Listbox(..., yscrollcommand=scrollbar.set)

You don't have to use rowspan=50 for Scrollbar - Listbox uses only one row even if you insert 50 lines of text.

```<code>import tkinter as tk # `import *` is not preferred (see PEP8)

master = tk.Tk()

scrollbar = tk.Scrollbar(master, orient='vertical')
scrollbar.grid(row=2, column=1, sticky='ns')

listbox = tk.Listbox(master, yscrollcommand=scrollbar.set)
for i in range(50):
    listbox.insert('end', str(i))
listbox.grid(row=2, column=0, sticky="news")

scrollbar.config(command=listbox.yview)

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

PEP 8 -- Style Guide for Python Code

ContentLicense: CC BY-SA 4.0

Body:
I got most of this attached code from another question.  I'm using Python 3.8.  It would seem that the Pack Manager will easily add a scrollbar widget to a listbox widget.  However, I'm using the Grid Manager.  I can't get a vertical scrollbar to work properly.

When you run this code,  a vertical scrollbar will appear, but it is not physically attached to the listbox widget properly.  BTW: I got the horizontal scrollbar working without a problem.

from tkinter import *

master = Tk()

listbox = Listbox(master)

scrollbar = Scrollbar(master, orient=VERTICAL)
scrollbar.grid(row=2, rowspan=50, column=40, sticky=N + S)

for i in range(50):
    listbox.insert(END, str(i))
listbox.grid(sticky="news")

scrollbar.config(command=listbox.yview)

mainloop()

Body:
You should use row= and column= for both elements - to put in the same row and different columns.

You forgot tk.Listbox(..., yscrollcommand=scrollbar.set)

You don't have to use rowspan=50 for Scrollbar - Listbox uses only one row even if you insert 50 lines of text.

import tkinter as tk # `import *` is not preferred (see PEP8)

master = tk.Tk()

scrollbar = tk.Scrollbar(master, orient='vertical')
scrollbar.grid(row=2, column=1, sticky='ns')

listbox = tk.Listbox(master, yscrollcommand=scrollbar.set)
for i in range(50):
    listbox.insert('end', str(i))
listbox.grid(row=2, column=0, sticky="news")

scrollbar.config(command=listbox.yview)

master.mainloop()

PEP 8 -- Style Guide for Python Code


问:
CMake and Visual studio 2015 - The C compiler cl.exe is not able to compile a simple test program
I am trying to compile my programme using microsoft visual studio 2015 combine with cmake on Qt creator and I get this error that I really do not know how to solve.</p>

```<code>Running "C:\Program Files\CMake\bin\cmake.exe C:/Users/SEVLH/Documents/sodis"-GCodeBlocks - NMake Makefiles" "-DCMAKE_CXX_COMPILER:STRING=C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/amd64/cl.exe" "-DCMAKE_C_COMPILER:STRING=C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/amd64/cl.exe" "-DCMAKE_PREFIX_PATH:STRING=C:/Qt/Qt5.8.0/5.8/msvc2015_64" "-DQT_QMAKE_EXECUTABLE:STRING=C:/Qt/Qt5.8.0/5.8/msvc2015_64/bin/qmake.exe"" in C:\Users\SEVLH\AppData\Local\Temp\qtc-cmake-Yu2EZw.
-- The C compiler identification is unknown
-- The CXX compiler identification is unknown
-- Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/amd64/cl.exe
-- Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/amd64/cl.exe -- broken
CMake Error at C:/Program Files/CMake/share/cmake-3.8/Modules/CMakeTestCCompiler.cmake:51 (message):
The C compiler "C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/amd64/cl.exe" is not able to compile a simple test program.

It fails with the following output:

Change Dir: C:/Users/SEVLH/AppData/Local/Temp/qtc-cmake-Yu2EZw/CMakeFiles/CMakeTmp

Run Build Command:"nmake" "/NOLOGO" "cmTC_eda15\fast"

"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\amd64\nmake.exe" -f CMakeFiles\cmTC_eda15.dir\build.make
/nologo -L CMakeFiles\cmTC_eda15.dir\build

Building C object CMakeFiles/cmTC_eda15.dir/testCCompiler.c.obj

C:\PROGRA~2\MICROS~1.0\VC\bin\amd64\cl.exe -o
CMakeFiles\cmTC_eda15.dir\testCCompiler.c.obj -c
C:\Users\SEVLH\AppData\Local\Temp\qtc-cmake-Yu2EZw\CMakeFiles\CMakeTmp\testCCompiler.c

NMAKE : fatal error U1045: spawn failed : Invalid argument

 Stop.

NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\amd64\nmake.exe"' : return code '0x2'

 Stop.

CMake will not be able to correctly generate this project.
Call Stack (most recent call first):
CMakeLists.txt:3 (project)
</code>```

答: I solved this problem for Visual Studio 2019 and QT 5.14.1 (Qt creator 4.11.0) by changing CMake generator in Tools > Options > Kits to Ninja. </p>

Body:
I am trying to compile my programme using microsoft visual studio 2015 combine with cmake on Qt creator and I get this error that I really do not know how to solve.

Running "C:\Program Files\CMake\bin\cmake.exe C:/Users/SEVLH/Documents/sodis"-GCodeBlocks - NMake Makefiles" "-DCMAKE_CXX_COMPILER:STRING=C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/amd64/cl.exe" "-DCMAKE_C_COMPILER:STRING=C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/amd64/cl.exe" "-DCMAKE_PREFIX_PATH:STRING=C:/Qt/Qt5.8.0/5.8/msvc2015_64" "-DQT_QMAKE_EXECUTABLE:STRING=C:/Qt/Qt5.8.0/5.8/msvc2015_64/bin/qmake.exe"" in C:\Users\SEVLH\AppData\Local\Temp\qtc-cmake-Yu2EZw.
-- The C compiler identification is unknown
-- The CXX compiler identification is unknown
-- Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/amd64/cl.exe
-- Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/amd64/cl.exe -- broken
CMake Error at C:/Program Files/CMake/share/cmake-3.8/Modules/CMakeTestCCompiler.cmake:51 (message):
The C compiler "C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/amd64/cl.exe" is not able to compile a simple test program.

It fails with the following output:

Change Dir: C:/Users/SEVLH/AppData/Local/Temp/qtc-cmake-Yu2EZw/CMakeFiles/CMakeTmp

Run Build Command:"nmake" "/NOLOGO" "cmTC_eda15\fast"

"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\amd64\nmake.exe" -f CMakeFiles\cmTC_eda15.dir\build.make
/nologo -L CMakeFiles\cmTC_eda15.dir\build

Building C object CMakeFiles/cmTC_eda15.dir/testCCompiler.c.obj

C:\PROGRA~2\MICROS~1.0\VC\bin\amd64\cl.exe -o
CMakeFiles\cmTC_eda15.dir\testCCompiler.c.obj -c
C:\Users\SEVLH\AppData\Local\Temp\qtc-cmake-Yu2EZw\CMakeFiles\CMakeTmp\testCCompiler.c

NMAKE : fatal error U1045: spawn failed : Invalid argument

 Stop.

NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\amd64\nmake.exe"' : return code '0x2'

 Stop.

CMake will not be able to correctly generate this project.
Call Stack (most recent call first):
CMakeLists.txt:3 (project)


问:
Django 'SessionStore' object has no attribute '_session_cache'
I am currently getting spammed by the error:

dictionary update sequence element #0 has length 14; 2 is required that seems to be provoked by ('SessionStore' object has no attribute '_session_cache')

I read in this question: Django project looking for "attribute '_session_cache'" that the issue might be that I don't have the django_session table, but I do and it's filled with content.

Any idea what could provoke that?

I am on Python 3.6.7, django 2.1.7

Here is the full error stack:

```<code>File "/path/to/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py" in _get_session
  190.             return self._session_cache

During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred:

File "/path/to/venv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/path/to/venv/lib/python3.6/site-packages/django/utils/deprecation.py" in __call__
  90.             response = self.process_request(request)

File "/path/to/venv/lib/python3.6/site-packages/django/middleware/locale.py" in process_request
  21.         language = translation.get_language_from_request(request, check_path=i18n_patterns_used)

File "/path/to/venv/lib/python3.6/site-packages/django/utils/translation/__init__.py" in get_language_from_request
  222.     return _trans.get_language_from_request(request, check_path)

File "/path/to/venv/lib/python3.6/site-packages/django/utils/translation/trans_real.py" in get_language_from_request
  464.         lang_code = request.session.get(LANGUAGE_SESSION_KEY)

File "/path/to/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py" in get
  66.         return self._session.get(key, default)

File "/path/to/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py" in _get_session
  195.                 self._session_cache = self.load()

File "/path/to/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/db.py" in load
  43.         s = self._get_session_from_db()

File "/path/to/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/db.py" in _get_session_from_db
  34.                 expire_date__gt=timezone.now()

File "/path/to/venv/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method
  82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/path/to/venv/lib/python3.6/site-packages/django/db/models/query.py" in get
  390.         clone = self.filter(*args, **kwargs)

File "/path/to/venv/lib/python3.6/site-packages/django/db/models/query.py" in filter
  844.         return self._filter_or_exclude(False, *args, **kwargs)

File "/path/to/venv/lib/python3.6/site-packages/django/db/models/query.py" in _filter_or_exclude
  862.             clone.query.add_q(Q(*args, **kwargs))

File "/path/to/venv/lib/python3.6/site-packages/django/db/models/sql/query.py" in add_q
  1263.         clause, _ = self._add_q(q_object, self.used_aliases)

File "/path/to/venv/lib/python3.6/site-packages/django/db/models/sql/query.py" in _add_q
  1289.                 joinpromoter.add_votes(needed_inner)

File "/path/to/venv/lib/python3.6/site-packages/django/db/models/sql/query.py" in add_votes
  2171.         self.votes.update(votes)

File "/usr/lib/python3.6/collections/__init__.py" in update
  620.                     super(Counter, self).update(iterable) # fast path when counter is empty

Exception Type: ValueError
Exception Value: dictionary update sequence element #0 has length 14; 2 is required
</code>```

答:
maybe when you uninstall some packages. check if your settings file is 'django.contrib.sessions.middleware.SessionMiddleware' in your MIDDLEWARE_CLASSES.

or

sometimes just put on console : python manage.py migrate, and it lives again

Body:
I am currently getting spammed by the error:

dictionary update sequence element #0 has length 14; 2 is required that seems to be provoked by ('SessionStore' object has no attribute '_session_cache')

I read in this question: Django project looking for "attribute '_session_cache'" that the issue might be that I don't have the django_session table, but I do and it's filled with content.

Any idea what could provoke that?

I am on Python 3.6.7, django 2.1.7

Here is the full error stack:

File "/path/to/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py" in _get_session
  190.             return self._session_cache

During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred:

File "/path/to/venv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/path/to/venv/lib/python3.6/site-packages/django/utils/deprecation.py" in __call__
  90.             response = self.process_request(request)

File "/path/to/venv/lib/python3.6/site-packages/django/middleware/locale.py" in process_request
  21.         language = translation.get_language_from_request(request, check_path=i18n_patterns_used)

File "/path/to/venv/lib/python3.6/site-packages/django/utils/translation/__init__.py" in get_language_from_request
  222.     return _trans.get_language_from_request(request, check_path)

File "/path/to/venv/lib/python3.6/site-packages/django/utils/translation/trans_real.py" in get_language_from_request
  464.         lang_code = request.session.get(LANGUAGE_SESSION_KEY)

File "/path/to/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py" in get
  66.         return self._session.get(key, default)

File "/path/to/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py" in _get_session
  195.                 self._session_cache = self.load()

File "/path/to/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/db.py" in load
  43.         s = self._get_session_from_db()

File "/path/to/venv/lib/python3.6/site-packages/django/contrib/sessions/backends/db.py" in _get_session_from_db
  34.                 expire_date__gt=timezone.now()

File "/path/to/venv/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method
  82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/path/to/venv/lib/python3.6/site-packages/django/db/models/query.py" in get
  390.         clone = self.filter(*args, **kwargs)

File "/path/to/venv/lib/python3.6/site-packages/django/db/models/query.py" in filter
  844.         return self._filter_or_exclude(False, *args, **kwargs)

File "/path/to/venv/lib/python3.6/site-packages/django/db/models/query.py" in _filter_or_exclude
  862.             clone.query.add_q(Q(*args, **kwargs))

File "/path/to/venv/lib/python3.6/site-packages/django/db/models/sql/query.py" in add_q
  1263.         clause, _ = self._add_q(q_object, self.used_aliases)

File "/path/to/venv/lib/python3.6/site-packages/django/db/models/sql/query.py" in _add_q
  1289.                 joinpromoter.add_votes(needed_inner)

File "/path/to/venv/lib/python3.6/site-packages/django/db/models/sql/query.py" in add_votes
  2171.         self.votes.update(votes)

File "/usr/lib/python3.6/collections/__init__.py" in update
  620.                     super(Counter, self).update(iterable) # fast path when counter is empty

Exception Type: ValueError
Exception Value: dictionary update sequence element #0 has length 14; 2 is required


问:
Is it possible to take a trained CNN stored as a .mat file and use that file to make a classification algorithm in Python?
I have created a CNN in MATLAB 2019b and the trained CNN is stored in a file called "trainednet.mat". I was wondering how you can load the trained .mat file in Python and classify the images in Python instead of loading it on MATLAB 2019b. I have tried to convert my .mat file to .h5 file using h5py so that I can use it in keras but it does not work. I have also heard of a function in scipy called sio.loadmat docs.scipy.org/doc/scipy/reference/tutorial/io.html but I am unsure if this can be used for implementation in python. Will the methods I have stated above work if implemented correctly or is there another way to approach this problem? </p>

答:
A short answer is that it is possible, however, it's not hassle-free as you will need to recreate a part of the network (at least the part for prediction) in python code. It will work with just numpy and scipy, or can also recreate with PyTorch  / TensorFlow for utilising GPUs.

The trainednet.mat you mentioned probably stored the weights of the NN, and you will need to recreate the architecture of the NN based on the original model (the one in matlab), i.e., perform matrix calculations in python.

As you had mentioned, you will first load the .mat by scipy with

from scipy.io import loadmat

parameters = loadmat("trainednet.mat")
```

<p>and now <code>parameters</code> is a Python dictionary where it's structure is hugely dependent on your network. The following details will be different for each kind of CNN, but the basic workflow is something similar to:</p>

<pre class="lang-py prettyprint-override"><code>def predict(img, parameters):
    # the kind of saved parameters
    # your trainednet.mat should have weights for something like
    # w1,w2,w3,w4... for weights of convolutional layers
    #                    weights of dense layers
    # b3,b4...       for any bias from layers

    # convolution operation
    z = convolution(..., img, w1)
    # ReLU non-linearity
    z[z<=0] = 0

    # convolution operation
    z = convolution(..., z, w2)
    # ReLU non-linearity
    z[z<=0] = 0

    z = maxpool(z, ...).reshape(...) # maxpooling operation

    # dense layer with bias
    z = w3.dot(z) + b3
    # ReLU non-linearity
    z[z<=0] = 0

    # second dense layer with bias
    z = w4.dot(z) + b4

    # predict class probabilities
    probs = softmax(z)
    return probs

from scipy.ndimage import imread
img = imread(FILENAME, mode="RGB")

predict(img, parameters)
</code>```

Most part are easy to implement, except the convolution operation which is extremely tricky. If you do want to go on this route, you might be better off if  you use NN library for it.

In short, it's possible but required a lot of effort to re-implement the same code  (code as in the NN architecture) from matlab to python. You can refer to this guide as a starter of converting matlab pretrained network in python.

Body:
A short answer is that it is possible, however, it's not hassle-free as you will need to recreate a part of the network (at least the part for prediction) in python code. It will work with just numpy and scipy, or can also recreate with PyTorch  / TensorFlow for utilising GPUs.

The trainednet.mat you mentioned probably stored the weights of the NN, and you will need to recreate the architecture of the NN based on the original model (the one in matlab), i.e., perform matrix calculations in python.

As you had mentioned, you will first load the .mat by scipy with

from scipy.io import loadmat

parameters = loadmat("trainednet.mat")

and now parameters is a Python dictionary where it's structure is hugely dependent on your network. The following details will be different for each kind of CNN, but the basic workflow is something similar to:

def predict(img, parameters):
    # the kind of saved parameters
    # your trainednet.mat should have weights for something like
    # w1,w2,w3,w4... for weights of convolutional layers
    #                    weights of dense layers
    # b3,b4...       for any bias from layers

    # convolution operation
    z = convolution(..., img, w1)
    # ReLU non-linearity
    z[z<=0] = 0

    # convolution operation
    z = convolution(..., z, w2)
    # ReLU non-linearity
    z[z<=0] = 0

    z = maxpool(z, ...).reshape(...) # maxpooling operation

    # dense layer with bias
    z = w3.dot(z) + b3
    # ReLU non-linearity
    z[z<=0] = 0

    # second dense layer with bias
    z = w4.dot(z) + b4

    # predict class probabilities
    probs = softmax(z)
    return probs

from scipy.ndimage import imread
img = imread(FILENAME, mode="RGB")

predict(img, parameters)

Most part are easy to implement, except the convolution operation which is extremely tricky. If you do want to go on this route, you might be better off if  you use NN library for it.

In short, it's possible but required a lot of effort to re-implement the same code  (code as in the NN architecture) from matlab to python. You can refer to this guide as a starter of converting matlab pretrained network in python.


问:
Stop people uploading malicious PHP files via forms
I have an upload form created in php on my website where people are able to upload a zip file. The zip file is then extracted and all file locations are added to a database. The upload form is for people to upload pictures only, obviously, with the files being inside the zip folder I cant check what files are being uploaded until the file has been extracted. I need a piece of code which will delete all the files which aren't image formats (.png, .jpeg, etc). I'm really worried about people being able to upload malicious php files, big security risk! I also need to be aware of people changing the extensions of php files trying to get around this security feature.

This is the original script I used http://net.tutsplus.com/videos/screencasts/how-to-open-zip-files-with-php/

This is the code which actually extracts the .zip file:

```<code>function openZip($file_to_open) {
    global $target;

    $zip = new ZipArchive();
    $x = $zip->open($file_to_open);
    if($x === true) {
        $zip->extractTo($target);
        $zip->close();

        unlink($file_to_open);
    } else {
        die("There was a problem. Please try again!");
    }
}
</code>```

Thanks, Ben.

答: You should probably not rely just on the filename extension, then.  Try passing each file through an image library to validate that its really an image, also.</p>

OwnerDisplayName: Ben McRae

Body:
I have an upload form created in php on my website where people are able to upload a zip file. The zip file is then extracted and all file locations are added to a database. The upload form is for people to upload pictures only, obviously, with the files being inside the zip folder I cant check what files are being uploaded until the file has been extracted. I need a piece of code which will delete all the files which aren't image formats (.png, .jpeg, etc). I'm really worried about people being able to upload malicious php files, big security risk! I also need to be aware of people changing the extensions of php files trying to get around this security feature.

This is the original script I used http://net.tutsplus.com/videos/screencasts/how-to-open-zip-files-with-php/

This is the code which actually extracts the .zip file:

function openZip($file_to_open) {
    global $target;

    $zip = new ZipArchive();
    $x = $zip->open($file_to_open);
    if($x === true) {
        $zip->extractTo($target);
        $zip->close();

        unlink($file_to_open);
    } else {
        die("There was a problem. Please try again!");
    }
}

Thanks, Ben.

LastEditorDisplayName: gs

OwnerDisplayName: John Ellinwood

ContentLicense: CC BY-SA 2.5


问:
Cursor.execute data adds single quotes marks and breaks query that contains IN(1,2) statement with mysql in python
thanks for reading.
I have an issue trying to send a variable to cursor.execute(query,variable). Query contains IN (%s) stament and variable contains ints comma separated.
Problem occurs when pythons execute apparently adds single quote marks to variable. It breaks query. So...
How can I override this behavior to discard quotation marks?

query:
review_authors=

```<code>SELECT   autor.id, autor.escuela, autor.nombre, count(*)
FROM     autor, cita, obra
WHERE    obra.autor=autor.id
AND      cita.obra=obra.id
AND      cita.id in ( %s )
GROUP BY autor.id, autor.escuela, autor.nombre
ORDER BY autor.nombre ASC;
</code>```

data:

```<code>citaid=request.cookies.get("idNote")
</code>```

cursor.execute:

```<code>Cursor.execute(review_authors, citaid)
</code>```

informed error:

C:\Users\sebap\Web\venv\lib\site-packages\pymysql\cursors.py:170: Warning: (1292, "Truncated incorrect DOUBLE value: '5302,5303,354,501'")
    result = self._query(query)

thanks again

答:
What you need to do is put placeholder %s in your query.

Then the variables will go into their appropriate places.

```<code>citaid=request.cookies.get("idNote")
placeholders = ",".join(['%s']*len(citaid))
review_authors = """SELECT autor.id, autor.escuela, autor.nombre, COUNT(*)
                    FROM autor, cita, obra
                    WHERE obra.autor=autor.id
                        AND cita.obra=obra.id
                        AND cita.id in ({})
                    GROUP BY autor.id, autor.escuela, autor.nombre
                    ORDER BY autor.nombre ASC;""".format(placeholders)
Cursor.execute(review_authors, citaid)
</code>```

Body:
thanks for reading.
I have an issue trying to send a variable to cursor.execute(query,variable). Query contains IN (%s) stament and variable contains ints comma separated.
Problem occurs when pythons execute apparently adds single quote marks to variable. It breaks query. So...
How can I override this behavior to discard quotation marks?

query:
review_authors=

SELECT   autor.id, autor.escuela, autor.nombre, count(*)
FROM     autor, cita, obra
WHERE    obra.autor=autor.id
AND      cita.obra=obra.id
AND      cita.id in ( %s )
GROUP BY autor.id, autor.escuela, autor.nombre
ORDER BY autor.nombre ASC;

data:

citaid=request.cookies.get("idNote")

cursor.execute:

Cursor.execute(review_authors, citaid)

informed error:

C:\Users\sebap\Web\venv\lib\site-packages\pymysql\cursors.py:170: Warning: (1292, "Truncated incorrect DOUBLE value: '5302,5303,354,501'")
    result = self._query(query)

thanks again

Body:
What you need to do is put placeholder %s in your query.

Then the variables will go into their appropriate places.

citaid=request.cookies.get("idNote")
placeholders = ",".join(['%s']*len(citaid))
review_authors = """SELECT autor.id, autor.escuela, autor.nombre, COUNT(*)
                    FROM autor, cita, obra
                    WHERE obra.autor=autor.id
                        AND cita.obra=obra.id
                        AND cita.id in ({})
                    GROUP BY autor.id, autor.escuela, autor.nombre
                    ORDER BY autor.nombre ASC;""".format(placeholders)
Cursor.execute(review_authors, citaid)


问:
Dynamic task dependency based on a value of a property
I need to create a plugin which would provide an interactive task, invoked like this:

> ./gradlew analyzeSomething --configuration compileClasspath
```

<p>Here the <code>--configuration</code> argument is supposed to be the name of a configuration in the project which is used for the analysis.</p>

<p>However, this analysis requires some data computed from the configuration, which might be expensive. Therefore, I'd like to cache this data, but, naturally, in a way which would result in cache invalidation in case contents of the configuration change (e.g. a dependency is added by the user). Ideally I'd take advantage of the built-in Gradle task dependencies mechanisms, which would track task dependencies and allow not to run a computation unless its input has changed.</p>

<p>This is the solution I came up with, but it does not work. First, declare two properties in the <code>AnalyzeSomething</code> class:</p>

```abstract class AnalyzeSomethingTask : DefaultTask() {
    @get:Internal
    @get:Option(option = "configuration", description = "Configuration")
    abstract val configuration: Property<String>

    @get:Internal
    abstract val dataCacheFile: RegularFileProperty
}
```

<p>Second, create a task rule to instantiate tasks performing the expensive computation:</p>

```abstract class PrecomputeTask : DefaultTask() {
    @get:InputFiles
    abstract val classpath: ConfigurableFileCollection

    @get:OutputFile
    abstract val outputFile: RegularFileProperty
}

project.tasks.addRule("Pattern precompute<Configuration>") {
    val taskName = this
    if (taskName.startsWith("precompute")) {
        val configurationName = taskName.removePrefix("precompute").decapitalize()
        val configuration = project.configurations.getByName(configurationName)
        project.tasks.register<PrecomputeTask>(taskName) {
            classpath.from(configuration)
            outputFile.set(temporaryDir.resolve("data.txt"))
        }
    }
}
```

<p>Finally, create the <code>analyzeSomething</code> task and in the <code>project.afterEvalute</code> block (so all the properties of the task are already set, including those on the command line) set up a dependency between <code>analyzeSomething</code> and one of the rule-generated tasks:</p>

```val analyzeSomething = project.tasks.register<AnalyzeSomethingTask>("analyzeSomething")
project.afterEvaluate {
    analyzeSomething.configure {
        val precomputeTaskName = "precompute" + configuration.get().capitalize()
        dataCacheFile.set(
            project.tasks.named<PrecomputeTask>(precomputeTaskName)
                .flatMap { it.outputFile }
        )
    }
}
```

<p>This approach, however, does not work, because apparently the <code>register()</code> and any other collection configuration methods cannot be called at whatever point they are called in such setup:</p>

<pre class="lang-none prettyprint-override"><code>> ./gradlew analyzeSomething --configuration runtimeClasspath
Caused by: org.gradle.api.internal.tasks.DefaultTaskContainer$TaskCreationException: Could not create task ':analyzeSomething'.
...
Caused by: org.gradle.api.internal.AbstractMutationGuard$IllegalMutationException: DefaultTaskContainer#create(String, Class, Action) on task set cannot be executed in the current context.
</code>```

So my question is, is there a way to set up task dependencies based on a property name, and if not, what would be a better way to do what I what I want?

答:
Interestingly enough, this approach works once I get rid of project.afterEvaluate, with some moderately complex providers shuffling:

```<code>// instead of
val analyzeSomething = project.tasks.register<AnalyzeSomethingTask>("analyzeSomething")
project.afterEvaluate {
    analyzeSomething.configure {
        val precomputeTaskName = "precompute" + configuration.get().capitalize()
        dataCacheFile.set(
            project.tasks.named<PrecomputeTask>(precomputeTaskName)
                .flatMap { it.outputFile }
        )
    }
}

// do this

project.tasks.register<AnalyzeSomethingTask>("analyzeSomething") {
    dataCacheFile.set(
        configuration.flatMap { c ->
            val precomputeTaskName = "precompute" + c.capitalize()
            project.tasks.named<PrecomputeTask>(precomputeTaskName)
                .flatMap { it.outputFile }
        }
    )
}
</code>```

I'm really curious why this approach works compared to the project.afterEvaluate-based one, but it does seem to work correctly, as it results in the proper precompute* task being added to the task graph, and its output being used for the analysis.

Body:
I need to create a plugin which would provide an interactive task, invoked like this:

> ./gradlew analyzeSomething --configuration compileClasspath

Here the --configuration argument is supposed to be the name of a configuration in the project which is used for the analysis.

However, this analysis requires some data computed from the configuration, which might be expensive. Therefore, I'd like to cache this data, but, naturally, in a way which would result in cache invalidation in case contents of the configuration change (e.g. a dependency is added by the user). Ideally I'd take advantage of the built-in Gradle task dependencies mechanisms, which would track task dependencies and allow not to run a computation unless its input has changed.

This is the solution I came up with, but it does not work. First, declare two properties in the AnalyzeSomething class:

abstract class AnalyzeSomethingTask : DefaultTask() {
    @get:Internal
    @get:Option(option = "configuration", description = "Configuration")
    abstract val configuration: Property<String>

    @get:Internal
    abstract val dataCacheFile: RegularFileProperty
}

Second, create a task rule to instantiate tasks performing the expensive computation:

abstract class PrecomputeTask : DefaultTask() {
    @get:InputFiles
    abstract val classpath: ConfigurableFileCollection

    @get:OutputFile
    abstract val outputFile: RegularFileProperty
}

project.tasks.addRule("Pattern precompute<Configuration>") {
    val taskName = this
    if (taskName.startsWith("precompute")) {
        val configurationName = taskName.removePrefix("precompute").decapitalize()
        val configuration = project.configurations.getByName(configurationName)
        project.tasks.register<PrecomputeTask>(taskName) {
            classpath.from(configuration)
            outputFile.set(temporaryDir.resolve("data.txt"))
        }
    }
}

Finally, create the analyzeSomething task and in the project.afterEvalute block (so all the properties of the task are already set, including those on the command line) set up a dependency between analyzeSomething and one of the rule-generated tasks:

val analyzeSomething = project.tasks.register<AnalyzeSomethingTask>("analyzeSomething")
project.afterEvaluate {
    analyzeSomething.configure {
        val precomputeTaskName = "precompute" + configuration.get().capitalize()
        dataCacheFile.set(
            project.tasks.named<PrecomputeTask>(precomputeTaskName)
                .flatMap { it.outputFile }
        )
    }
}

This approach, however, does not work, because apparently the register() and any other collection configuration methods cannot be called at whatever point they are called in such setup:

> ./gradlew analyzeSomething --configuration runtimeClasspath
Caused by: org.gradle.api.internal.tasks.DefaultTaskContainer$TaskCreationException: Could not create task ':analyzeSomething'.
...
Caused by: org.gradle.api.internal.AbstractMutationGuard$IllegalMutationException: DefaultTaskContainer#create(String, Class, Action) on task set cannot be executed in the current context.

So my question is, is there a way to set up task dependencies based on a property name, and if not, what would be a better way to do what I what I want?

Body:
Interestingly enough, this approach works once I get rid of project.afterEvaluate, with some moderately complex providers shuffling:

// instead of
val analyzeSomething = project.tasks.register<AnalyzeSomethingTask>("analyzeSomething")
project.afterEvaluate {
    analyzeSomething.configure {
        val precomputeTaskName = "precompute" + configuration.get().capitalize()
        dataCacheFile.set(
            project.tasks.named<PrecomputeTask>(precomputeTaskName)
                .flatMap { it.outputFile }
        )
    }
}

// do this

project.tasks.register<AnalyzeSomethingTask>("analyzeSomething") {
    dataCacheFile.set(
        configuration.flatMap { c ->
            val precomputeTaskName = "precompute" + c.capitalize()
            project.tasks.named<PrecomputeTask>(precomputeTaskName)
                .flatMap { it.outputFile }
        }
    )
}

I'm really curious why this approach works compared to the project.afterEvaluate-based one, but it does seem to work correctly, as it results in the proper precompute* task being added to the task graph, and its output being used for the analysis.


问:
Create a page with child pages and have each child have it's own page template
I have some code that creates pages with child pages in WordPress. What i would like to do is have each child have its own page template.
As you see below, i am creating child pages of Script and Assets. Currently the child page is created with one page_Full.php added to everything but i would like to have Script and Assets have their own page template. Ideas would be helpful.
Thanks in advance. </p>

```<code>function CreatePage(){

    $post_title = $_POST['ProjectName'];
    $post_excerpt = $_POST['ProjectDiscript'];
    $tags = $_POST['TypeOption'];

    $pages = array(
        array(
            'name'  => $post_title,
            'title' => $post_title,
            'child' => array(
                'script' => $post_title.'_Script',
                'assets' => $post_title.'_Assets'
            )
        )

    );

    $template = array(
        'post_type'   => 'page',
        'post_status' => 'publish',
        'post_author' => $user_id,
        'post_excerpt'  => $post_excerpt,
        'tags_input'  => array($tags),
    );

    foreach( $pages as $page ) {
        $exists = get_page_by_title( $page['title'] );
        $my_page = array(
            'post_name'         => $page['name'],
            'post_title'        => $page['title'],
            'page_template'     => 'page_Full.php'

        );
        $my_page = array_merge( $my_page, $template );

        $id = ( $exists ? $exists->ID : wp_insert_post( $my_page ) );

        if( isset( $page['child'] ) ) {
            foreach( $page['child'] as $key => $value ) {
                $child_id = get_page_by_title( $value );
                $child_page = array(
                    'post_name'         => $key,
                    'post_title'        => $value,
                    'post_parent'       => $id,
                    'page_template'     => 'page_Full.php'
                );
                $child_page = array_merge( $child_page, $template );
                if( !isset( $child_id ) ) wp_insert_post( $child_page );
            }
        }
    }
    wp_die();

}

add_action( 'wp_ajax_CreatePage','CreatePage' );
</code>```

答:
Had the idea to create an array for every child page - and it seams to work. Perhaps there is still a better way but for the time being - This does the trick!

```<code> $pages = array(
    array(
        'name'  => $post_title,
        'title' => $post_title,
        'child' => array(
                'script' => array(
                                'Pname'      => $post_title.'_Script',
                                'Ptemplate'  => 'page_Full_Script.php'
                                ),
                'assets' => array(
                                'Pname'     => $post_title.'_Assets',
                                'Ptemplate' => 'page_Full_Assets.php'
                ),
                'settings' => array(
                    'Pname'     => $post_title.'_Settings',
                    'Ptemplate' => 'page_Full_Settings.php'
                 )
        )
    )

);
</code>```

Here is the child with sub arrays.

```<code>if( isset( $page['child'] ) ) {
        foreach( $page['child'] as $key[] => $value ) {
            $child_id = get_page_by_title( $value );
            $child_page = array(
                'post_name'         => $value['Pname'],
                'post_title'        => $value['Pname'],
                'post_parent'       => $id,
                'page_template'     => $value['Ptemplate'],
            );
            $child_page = array_merge( $child_page, $template );
            if( !isset( $child_id ) ) wp_insert_post( $child_page );
        }
    }
</code>```

And here is where the child array is set as var to be iterated through so that the info can be inserted into the child_page var to be merged and the post inserted.
Thanks to any who took the time to review.
Cheers

Body:
I have some code that creates pages with child pages in WordPress. What i would like to do is have each child have its own page template.
As you see below, i am creating child pages of Script and Assets. Currently the child page is created with one page_Full.php added to everything but i would like to have Script and Assets have their own page template. Ideas would be helpful.
Thanks in advance.

function CreatePage(){

    $post_title = $_POST['ProjectName'];
    $post_excerpt = $_POST['ProjectDiscript'];
    $tags = $_POST['TypeOption'];

    $pages = array(
        array(
            'name'  => $post_title,
            'title' => $post_title,
            'child' => array(
                'script' => $post_title.'_Script',
                'assets' => $post_title.'_Assets'
            )
        )

    );

    $template = array(
        'post_type'   => 'page',
        'post_status' => 'publish',
        'post_author' => $user_id,
        'post_excerpt'  => $post_excerpt,
        'tags_input'  => array($tags),
    );

    foreach( $pages as $page ) {
        $exists = get_page_by_title( $page['title'] );
        $my_page = array(
            'post_name'         => $page['name'],
            'post_title'        => $page['title'],
            'page_template'     => 'page_Full.php'

        );
        $my_page = array_merge( $my_page, $template );

        $id = ( $exists ? $exists->ID : wp_insert_post( $my_page ) );

        if( isset( $page['child'] ) ) {
            foreach( $page['child'] as $key => $value ) {
                $child_id = get_page_by_title( $value );
                $child_page = array(
                    'post_name'         => $key,
                    'post_title'        => $value,
                    'post_parent'       => $id,
                    'page_template'     => 'page_Full.php'
                );
                $child_page = array_merge( $child_page, $template );
                if( !isset( $child_id ) ) wp_insert_post( $child_page );
            }
        }
    }
    wp_die();

}

add_action( 'wp_ajax_CreatePage','CreatePage' );

Body:
Had the idea to create an array for every child page - and it seams to work. Perhaps there is still a better way but for the time being - This does the trick!

 $pages = array(
    array(
        'name'  => $post_title,
        'title' => $post_title,
        'child' => array(
                'script' => array(
                                'Pname'      => $post_title.'_Script',
                                'Ptemplate'  => 'page_Full_Script.php'
                                ),
                'assets' => array(
                                'Pname'     => $post_title.'_Assets',
                                'Ptemplate' => 'page_Full_Assets.php'
                ),
                'settings' => array(
                    'Pname'     => $post_title.'_Settings',
                    'Ptemplate' => 'page_Full_Settings.php'
                 )
        )
    )

);

Here is the child with sub arrays.

if( isset( $page['child'] ) ) {
        foreach( $page['child'] as $key[] => $value ) {
            $child_id = get_page_by_title( $value );
            $child_page = array(
                'post_name'         => $value['Pname'],
                'post_title'        => $value['Pname'],
                'post_parent'       => $id,
                'page_template'     => $value['Ptemplate'],
            );
            $child_page = array_merge( $child_page, $template );
            if( !isset( $child_id ) ) wp_insert_post( $child_page );
        }
    }

And here is where the child array is set as var to be iterated through so that the info can be inserted into the child_page var to be merged and the post inserted.
Thanks to any who took the time to review.
Cheers


问:
How to `scl enable devtoolset-8 bash` when login in?
In my centos7, I tried to put scl enable devtoolset-8 bash command to ~/.bashrc but When I login in, processes of scl enable devtoolset-8 bash are started again and again until the process number reaches the user max process number.

So what should I do?

答: Solve it by using echo "source /opt/rh/devtoolset-8/enable" >> /etc/profile


问:
Docker web app on Azure Web App for Container
I am new to both docker and azure container services. I am trying to deploy a docker web app in the Azure Web App for Containers as single container instance. I am using the azure-vote-front image provided here.  I followed the steps provided here after tagging and pushing the docker image in an Azure container register.

But after deploying the web app and navigating to the web url, all it shows is
502 Bad Gateway
with nginx/1.15.8 mentioned below. Is there addtional configuration, I need to mention in any file or configure anywhere?

答:
For your issue, you misunderstand the image azure-vote-front. You can the docker-compose.yaml file in the Github link your provide, it creates the azure-vote-front image, but it also needs the database Redis. So it's not a single container instance, it's the multiple containers.

You can need to create the image azure-vote-front and push it to the Azure Container Registry. Also does the image Redis. Then you can change the docker-compose.yaml file like this:

```<code>version: '3.7'
services:
  azure-vote-back:
    image: youracrname.azurecr.io/redis
    container_name: azure-vote-back
    ports:
        - "6379:6379"

  azure-vote-front:
    image: youracrname.azurecr.io/azure-vote-front
    container_name: azure-vote-front
    environment:
      REDIS: azure-vote-back
    ports:
        - "80:80"
</code>```

And set the ACR credential with the command here:

```<code>az webapp config container set -g group_name -n app_name --docker-registry-server-url youracrname.azurecr.io --docker-registry-server-user acr_username --docker-registry-server-password acr_password
</code>```

Finally, wait for munites and then you can access the Web App. For more details, see the example Create a multi-container (preview) app in Web App for Containers.

Body:
For your issue, you misunderstand the image azure-vote-front. You can the docker-compose.yaml file in the Github link your provide, it creates the azure-vote-front image, but it also needs the database Redis. So it's not a single container instance, it's the multiple containers.

You can need to create the image azure-vote-front and push it to the Azure Container Registry. Also does the image Redis. Then you can change the docker-compose.yaml file like this:

version: '3.7'
services:
  azure-vote-back:
    image: youracrname.azurecr.io/redis
    container_name: azure-vote-back
    ports:
        - "6379:6379"

  azure-vote-front:
    image: youracrname.azurecr.io/azure-vote-front
    container_name: azure-vote-front
    environment:
      REDIS: azure-vote-back
    ports:
        - "80:80"

And set the ACR credential with the command here:

az webapp config container set -g group_name -n app_name --docker-registry-server-url youracrname.azurecr.io --docker-registry-server-user acr_username --docker-registry-server-password acr_password

Finally, wait for munites and then you can access the Web App. For more details, see the example Create a multi-container (preview) app in Web App for Containers.


问:
IBM-MQ: Configuring mutual TLS authentication between client and queue manager
I'm trying to set up TLS mutual authentication between client and IBM-MQ queue manager (using the ibmcom/mq Docker image). The certificates are self-signed and created according to this article. As stated in the docs, it should be possible to bake in the server's private key and both certificates into the image. My Dockerfile looks like this:

```<code>FROM ibmcom/mq

USER mqm
COPY --chown=mqm:mqm 20-config.mqsc /etc/mqm/ # creation of additional queues, no problems here
COPY --chown=mqm:mqm keys_mq1/key.key /etc/mqm/pki/keys/mykey/
COPY --chown=mqm:mqm keys_mq1/key.crt /etc/mqm/pki/keys/mykey/
COPY --chown=mqm:mqm keys_client/client.crt /etc/mqm/pki/trust/0/
</code>```

The files can be found in the running container:

```<code>/etc/mqm/pki/keys/mykey
drwxr-xr-x 1 mqm mqm 4096 Feb 16 11:18 .
drwxr-xr-x 1 mqm mqm 4096 Feb 16 11:18 ..
-rwxr-xr-x 1 mqm mqm 1253 Feb 16 10:54 key.crt
-rwxr-xr-x 1 mqm mqm 1704 Feb 16 10:53 key.key

/etc/mqm/pki/trust/0
drwxr-xr-x 2 mqm mqm 4096 Feb 16 13:34 .
drwxr-xr-x 3 mqm mqm 4096 Feb 16 13:34 ..
-rwxr-xr-x 1 mqm mqm 1054 Feb 16 13:29 client.crt
</code>```

One thing to notice is that, according to the docs, the channel details should now show the following entry: CERTLABL(mykey). In my case, it's just CERTLABL( ). However, I'm not sure if that's the problem here, authentication of the server without client authentication seems to be working (see below).

```<code>DISPLAY CHANNEL(DEV.APP.SVRCONN)
     1 : DISPLAY CHANNEL(DEV.APP.SVRCONN)
AMQ8414I: Display Channel details.
   CHANNEL(DEV.APP.SVRCONN)                CHLTYPE(SVRCONN)
   ALTDATE(2020-02-16)                     ALTTIME(13.34.47)
   CERTLABL( )                             COMPHDR(NONE)
   COMPMSG(NONE)                           DESCR( )
   DISCINT(0)                              HBINT(300)
   KAINT(AUTO)                             MAXINST(999999999)
   MAXINSTC(999999999)                     MAXMSGL(4194304)
   MCAUSER(app)                            MONCHL(QMGR)
   RCVDATA( )                              RCVEXIT( )
   SCYDATA( )                              SCYEXIT( )
   SENDDATA( )                             SENDEXIT( )
   SHARECNV(10)                            SSLCAUTH(OPTIONAL)
   SSLCIPH(ANY_TLS12)                      SSLPEER( )
   TRPTYPE(TCP)
</code>```

On client side, I created two Java keystores (JKS), one with the server's certificate (truststore) and one with the client's keypair.

My connection attempts were as followed:

Connecting to the default queue manager QM1 using the provided app user (no password) and DEV.APP.SVRCONN channel. The client application is an existing tool that perfectly works with the existing MQ infrastructure, I just exchanged the keystores and connection details.

Client exception: com.ibm.mq.MQException: JMSCMQ0001: WebSphere MQ call failed with compcode '2' ('MQCC_FAILED') reason '2035' ('MQRC_NOT_AUTHORIZED').

MQ log:

```<code>AMQ5534E: User ID 'app' authentication failed
AMQ5542I: The failed authentication check was caused by the queue manager CONNAUTH CHCKCLNT(REQDADM) configuration.
</code>```

Connecting using the provided admin user and DEV.ADMIN.SVRCONN channel via IBM MQ Explorer (in this scenario, I switched to admin because app has insufficient rights to be used with MQ Explorer, regardless of the authentication method). I checked the "no password" option, since I want to authenticate with the client's certificate.

MQ Explorer error message:

```<code>Access not permitted. You are not authorized to perform this operation. (AMQ4036)
  Explanation: The queue manager security mechanism has indicated that the userid associated with this request is not authorized to access the object.
</code>```

MQ log:

```<code>AMQ5540E: Application 'MQ Explorer 8.0.0' did not supply a user ID and password
AMQ5541I: The failed authentication check was caused by the queue manager CONNAUTH CHCKCLNT(REQDADM) configuration.
AMQ9557E: Queue Manager User ID initialization failed for 'admin'.
</code>```

Same as 2., but omitting the client's keystore and providing the password instead. Works. The idea here was to verify that at least the server's certificate is configured correctly (on the other hand, I'm not sure if MQ Explorer is enforcing the check of the server's certificate against the truststore in the first place).

What am I missing?

edit: my actual goal is to use mutual authentication for the app user and DEV.APP.SVRCONN channel.

答:
CHANNEL attribute CERTLABL

This attribute does not need to be set, unless you require to present a different certificate over this SVRCONN than all the other channels on the queue manager. If you do not have this requirement, leave CHANNEL attribute CERTLABL blank and just use the overall queue manager wide certificate. This is either following the default pattern of a certificate named ibmWebSphereMQ<qm-name> or uses the certificate label that you set using the following MQSC command:

```<code>ALTER QMGR CERTLABL(my-certificate-label)
</code>```

Connection Authentication (MQ built-in Password checking)

A brand new queue manager created at V8 or above will have the Connection Authentication feature enabled, which means the queue manager will check any passwords you provide, and more importantly in your scenario, will demand that any privileged user id must supply one. The error message you report in connection attempt 1:

```<code>AMQ5542I: The failed authentication check was caused by the queue manager CONNAUTH CHCKCLNT(REQDADM) configuration.
</code>```

and connection attempt 2/3:

```<code>AMQ5540E: Application 'MQ Explorer 8.0.0' did not supply a user ID and password
AMQ5541I: The failed authentication check was caused by the queue manager CONNAUTH CHCKCLNT(REQDADM) configuration.
</code>```

... are telling you that connection authentication is mandating that your user id, which it considers privileged (i.e. member of mqm group or similar), has not supplied a password.

If you do not require password checking for any remotely connecting privileged user id, then you can turn this off with the following commands on the queue manager.

```<code>ALTER AUTHINFO(SYSTEM.DEFAULT.AUTHINFO.IDPWOS) AUTHTYPE(IDPWOS) CHCKCLNT(OPTIONAL)

REFRESH SECURITY TYPE(CONNAUTH)
</code>```

Mutually Authenticated SSL/TLS

In order to ensure mutually authenticated SSL/TLS, you will eventually need to ensure that your CHANNEL attribute SSLCAUTH is set to REQUIRED. But the easiest way to achieve this is to start with it set to OPTIONAL, and get to the point where the client is authenticating the queue manager's certificate, and then get it sending it's own, and finally set SSLCAUTH(REQUIRED) to ensure that it will only work if the client continues to do so.

You will need to ensure that you have set SSLCIPH on both ends of the channel. You don't mention that in your question, but the instructions you reference use SSLCIPH(ANY_TLS12) so I assume you have done the same.

If you successfully make a connection and are not sure whether the client has sent a certificate to the queue manager, use the following MQSC command:-

```<code>DISPLAY CHSTATUS(DEV.ADMIN.SVRCONN) SSLPEER SSLCERTI
</code>```

to see the Subject's DN and Issuer's DN of the certificate sent by the client. If blank, it did not sent a certificate.

Body:
I'm trying to set up TLS mutual authentication between client and IBM-MQ queue manager (using the ibmcom/mq Docker image). The certificates are self-signed and created according to this article. As stated in the docs, it should be possible to bake in the server's private key and both certificates into the image. My Dockerfile looks like this:

FROM ibmcom/mq

USER mqm
COPY --chown=mqm:mqm 20-config.mqsc /etc/mqm/ # creation of additional queues, no problems here
COPY --chown=mqm:mqm keys_mq1/key.key /etc/mqm/pki/keys/mykey/
COPY --chown=mqm:mqm keys_mq1/key.crt /etc/mqm/pki/keys/mykey/
COPY --chown=mqm:mqm keys_client/client.crt /etc/mqm/pki/trust/0/

The files can be found in the running container:

/etc/mqm/pki/keys/mykey
drwxr-xr-x 1 mqm mqm 4096 Feb 16 11:18 .
drwxr-xr-x 1 mqm mqm 4096 Feb 16 11:18 ..
-rwxr-xr-x 1 mqm mqm 1253 Feb 16 10:54 key.crt
-rwxr-xr-x 1 mqm mqm 1704 Feb 16 10:53 key.key

/etc/mqm/pki/trust/0
drwxr-xr-x 2 mqm mqm 4096 Feb 16 13:34 .
drwxr-xr-x 3 mqm mqm 4096 Feb 16 13:34 ..
-rwxr-xr-x 1 mqm mqm 1054 Feb 16 13:29 client.crt

One thing to notice is that, according to the docs, the channel details should now show the following entry: CERTLABL(mykey). In my case, it's just CERTLABL( ). However, I'm not sure if that's the problem here, authentication of the server without client authentication seems to be working (see below).

DISPLAY CHANNEL(DEV.APP.SVRCONN)
     1 : DISPLAY CHANNEL(DEV.APP.SVRCONN)
AMQ8414I: Display Channel details.
   CHANNEL(DEV.APP.SVRCONN)                CHLTYPE(SVRCONN)
   ALTDATE(2020-02-16)                     ALTTIME(13.34.47)
   CERTLABL( )                             COMPHDR(NONE)
   COMPMSG(NONE)                           DESCR( )
   DISCINT(0)                              HBINT(300)
   KAINT(AUTO)                             MAXINST(999999999)
   MAXINSTC(999999999)                     MAXMSGL(4194304)
   MCAUSER(app)                            MONCHL(QMGR)
   RCVDATA( )                              RCVEXIT( )
   SCYDATA( )                              SCYEXIT( )
   SENDDATA( )                             SENDEXIT( )
   SHARECNV(10)                            SSLCAUTH(OPTIONAL)
   SSLCIPH(ANY_TLS12)                      SSLPEER( )
   TRPTYPE(TCP)

On client side, I created two Java keystores (JKS), one with the server's certificate (truststore) and one with the client's keypair.

My connection attempts were as followed:

Connecting to the default queue manager QM1 using the provided app user (no password) and DEV.APP.SVRCONN channel. The client application is an existing tool that perfectly works with the existing MQ infrastructure, I just exchanged the keystores and connection details.

Client exception: com.ibm.mq.MQException: JMSCMQ0001: WebSphere MQ call failed with compcode '2' ('MQCC_FAILED') reason '2035' ('MQRC_NOT_AUTHORIZED').

MQ log:

AMQ5534E: User ID 'app' authentication failed
AMQ5542I: The failed authentication check was caused by the queue manager CONNAUTH CHCKCLNT(REQDADM) configuration.

Connecting using the provided admin user and DEV.ADMIN.SVRCONN channel via IBM MQ Explorer (in this scenario, I switched to admin because app has insufficient rights to be used with MQ Explorer, regardless of the authentication method). I checked the "no password" option, since I want to authenticate with the client's certificate.

MQ Explorer error message:

Access not permitted. You are not authorized to perform this operation. (AMQ4036)
  Explanation: The queue manager security mechanism has indicated that the userid associated with this request is not authorized to access the object.

MQ log:

AMQ5540E: Application 'MQ Explorer 8.0.0' did not supply a user ID and password
AMQ5541I: The failed authentication check was caused by the queue manager CONNAUTH CHCKCLNT(REQDADM) configuration.
AMQ9557E: Queue Manager User ID initialization failed for 'admin'.

Same as 2., but omitting the client's keystore and providing the password instead. Works. The idea here was to verify that at least the server's certificate is configured correctly (on the other hand, I'm not sure if MQ Explorer is enforcing the check of the server's certificate against the truststore in the first place).

What am I missing?

edit: my actual goal is to use mutual authentication for the app user and DEV.APP.SVRCONN channel.

Body:
CHANNEL attribute CERTLABL

This attribute does not need to be set, unless you require to present a different certificate over this SVRCONN than all the other channels on the queue manager. If you do not have this requirement, leave CHANNEL attribute CERTLABL blank and just use the overall queue manager wide certificate. This is either following the default pattern of a certificate named ibmWebSphereMQ<qm-name> or uses the certificate label that you set using the following MQSC command:

ALTER QMGR CERTLABL(my-certificate-label)

Connection Authentication (MQ built-in Password checking)

A brand new queue manager created at V8 or above will have the Connection Authentication feature enabled, which means the queue manager will check any passwords you provide, and more importantly in your scenario, will demand that any privileged user id must supply one. The error message you report in connection attempt 1:

AMQ5542I: The failed authentication check was caused by the queue manager CONNAUTH CHCKCLNT(REQDADM) configuration.

and connection attempt 2/3:

AMQ5540E: Application 'MQ Explorer 8.0.0' did not supply a user ID and password
AMQ5541I: The failed authentication check was caused by the queue manager CONNAUTH CHCKCLNT(REQDADM) configuration.

... are telling you that connection authentication is mandating that your user id, which it considers privileged (i.e. member of mqm group or similar), has not supplied a password.

If you do not require password checking for any remotely connecting privileged user id, then you can turn this off with the following commands on the queue manager.

ALTER AUTHINFO(SYSTEM.DEFAULT.AUTHINFO.IDPWOS) AUTHTYPE(IDPWOS) CHCKCLNT(OPTIONAL)

REFRESH SECURITY TYPE(CONNAUTH)

Mutually Authenticated SSL/TLS

In order to ensure mutually authenticated SSL/TLS, you will eventually need to ensure that your CHANNEL attribute SSLCAUTH is set to REQUIRED. But the easiest way to achieve this is to start with it set to OPTIONAL, and get to the point where the client is authenticating the queue manager's certificate, and then get it sending it's own, and finally set SSLCAUTH(REQUIRED) to ensure that it will only work if the client continues to do so.

You will need to ensure that you have set SSLCIPH on both ends of the channel. You don't mention that in your question, but the instructions you reference use SSLCIPH(ANY_TLS12) so I assume you have done the same.

If you successfully make a connection and are not sure whether the client has sent a certificate to the queue manager, use the following MQSC command:-

DISPLAY CHSTATUS(DEV.ADMIN.SVRCONN) SSLPEER SSLCERTI

to see the Subject's DN and Issuer's DN of the certificate sent by the client. If blank, it did not sent a certificate.


问:
How to align stack at 32 byte boundary in GCC?
I'm using MinGW64 build based on GCC 4.6.1 for Windows 64bit target. I'm playing around with the new Intel's AVX instructions. My command line arguments are -march=corei7-avx -mtune=corei7-avx -mavx.

But I started running into segmentation fault errors when allocating local variables on the stack. GCC uses the aligned moves VMOVAPS and VMOVAPD to move __m256 and __m256d around, and these instructions require 32-byte alignment. However, the stack for Windows 64bit has only 16 byte alignment.

How can I change the GCC's stack alignment to 32 bytes?

I have tried using -mstackrealign but to no avail, since that aligns only to 16 bytes.  I couldn't make __attribute__((force_align_arg_pointer)) work either, it aligns to 16 bytes anyway. I haven't been able to find any other compiler options that would address this. Any help is greatly appreciated.

EDIT:
I tried using -mpreferred-stack-boundary=5, but GCC says that 5 is not supported for this target. I'm out of ideas.

答:
I have been exploring the issue, filed a GCC bug report, and found out that this is a MinGW64 related problem. See GCC Bug#49001. Apparently, GCC doesn't support 32-byte stack alignment on Windows. This effectively prevents the use of 256-bit AVX instructions.

I investigated a couple ways how to deal with this issue. The simplest and bluntest solution is to replace of aligned memory accesses VMOVAPS/PD/DQA by unaligned alternatives VMOVUPS etc. So I learned Python last night (very nice tool, by the way) and pulled off the following script that does the job with an input assembler file produced by GCC:

```<code>import re
import fileinput
import sys

# fix aligned stack access
# replace aligned vmov* by unaligned vmov* with 32-byte aligned operands
# see Intel's AVX programming guide, page 39
vmova = re.compile(r"\s*?vmov(\w+).*?((\(%r.*?%ymm)|(%ymm.*?\(%r))")
aligndict = {"aps" : "ups", "apd" : "upd", "dqa" : "dqu"};
for line in fileinput.FileInput(sys.argv[1:],inplace=1):
    m = vmova.match(line)
    if m and m.group(1) in aligndict:
        s = m.group(1)
        print line.replace("vmov"+s, "vmov"+aligndict[s]),
    else:
        print line,
</code>```

This approach is pretty safe and foolproof. Though I observed a performance penalty on rare occasions. When the stack is unaligned, the memory access crosses the cache line boundary. Fortunately, the code performs as fast as aligned accesses most of the time. My recommendation: inline functions in critical loops!

I also attempted to fix the stack allocation in every function prolog using another Python script, trying to align it always at the 32-byte boundary. This seems to work for some code, but not for other. I have to rely on the good will of GCC that it will allocate aligned local variables (with respect to the stack pointer), which it usually does. This is not always the case, especially when there is a serious register spilling due to the necessity to save all ymm register before a function call. (All ymm registers are callee-save). I can post the script if there's an interest.

The best solution would be to fix GCC MinGW64 build. Unfortunately, I have no knowledge of its internal workings, just started using it last week.

Body:
I have been exploring the issue, filed a GCC bug report, and found out that this is a MinGW64 related problem. See GCC Bug#49001. Apparently, GCC doesn't support 32-byte stack alignment on Windows. This effectively prevents the use of 256-bit AVX instructions.

I investigated a couple ways how to deal with this issue. The simplest and bluntest solution is to replace of aligned memory accesses VMOVAPS/PD/DQA by unaligned alternatives VMOVUPS etc. So I learned Python last night (very nice tool, by the way) and pulled off the following script that does the job with an input assembler file produced by GCC:

import re
import fileinput
import sys

# fix aligned stack access
# replace aligned vmov* by unaligned vmov* with 32-byte aligned operands
# see Intel's AVX programming guide, page 39
vmova = re.compile(r"\s*?vmov(\w+).*?((\(%r.*?%ymm)|(%ymm.*?\(%r))")
aligndict = {"aps" : "ups", "apd" : "upd", "dqa" : "dqu"};
for line in fileinput.FileInput(sys.argv[1:],inplace=1):
    m = vmova.match(line)
    if m and m.group(1) in aligndict:
        s = m.group(1)
        print line.replace("vmov"+s, "vmov"+aligndict[s]),
    else:
        print line,

This approach is pretty safe and foolproof. Though I observed a performance penalty on rare occasions. When the stack is unaligned, the memory access crosses the cache line boundary. Fortunately, the code performs as fast as aligned accesses most of the time. My recommendation: inline functions in critical loops!

I also attempted to fix the stack allocation in every function prolog using another Python script, trying to align it always at the 32-byte boundary. This seems to work for some code, but not for other. I have to rely on the good will of GCC that it will allocate aligned local variables (with respect to the stack pointer), which it usually does. This is not always the case, especially when there is a serious register spilling due to the necessity to save all ymm register before a function call. (All ymm registers are callee-save). I can post the script if there's an interest.

The best solution would be to fix GCC MinGW64 build. Unfortunately, I have no knowledge of its internal workings, just started using it last week.


问:
How to define an optional parameter in path using swagger
There is a function in my REST web service working with GET method and it has two optional parameters.

I tried to define it in Swagger but I encountered an error, Not a valid parameter definition, after I set the required as false.

I found out that if I set the required value as true the error will be gone. Here is a sample of my Swagger code.

```<code>...
paths:
  '/get/{param1}/{param2}':
    get:
      ...
      parameters:
      - name: param1
        in: path
        description: 'description regarding param1'
        required: false
        type: string
      - name: param2
        in: path
        description: 'description regarding param2'
        required: false
        type: string
</code>```

I didn't experience this with parameters in body or the the ones in query. I think this problem is only related to parameters in path. I could not find any solution in swagger specification files either.

Is there any other way to define optional parameters in Swagger or do I have any mistake in my code?

Any help would be appreciated.

答:
Sad but fact there is no official support for optional parameters still in 2020 and in 3.* specification:
https://github.com/OAI/OpenAPI-Specification/issues/93

You can only apply some workaround mentioned in other answers (describe several endpoints for every set of parameters; convert your API to work with query-parameters instead of path-parameters).

Personally I decided to just leave everything as is, just add a parameter description which clearly says "This parameter is OPTIONAL!". Should be clear enough for everyone who reads the API.

Body:
There is a function in my REST web service working with GET method and it has two optional parameters.

I tried to define it in Swagger but I encountered an error, Not a valid parameter definition, after I set the required as false.

I found out that if I set the required value as true the error will be gone. Here is a sample of my Swagger code.

...
paths:
  '/get/{param1}/{param2}':
    get:
      ...
      parameters:
      - name: param1
        in: path
        description: 'description regarding param1'
        required: false
        type: string
      - name: param2
        in: path
        description: 'description regarding param2'
        required: false
        type: string

I didn't experience this with parameters in body or the the ones in query. I think this problem is only related to parameters in path. I could not find any solution in swagger specification files either.

Is there any other way to define optional parameters in Swagger or do I have any mistake in my code?

Any help would be appreciated.


问:
Is it possible to do inheritance for DTOs in NestJs?
I have a NestJs Get controller which searches for a list of employees.

```<code>@Controller('employee')
export class EmployeeController {
    private logger = new Logger('EmployeeController');
    constructor(private employeeService:EmployeeService){}

    @Get()
    @UsePipes(new ValidationPipe({ transform: true }))
    getEmployees(
        @Query() filter:GetEmployeesFilterDto
    ):Promise<Employee[]>{
        console.log(JSON.stringify(filter), filter.batch);
        return this.employeeService.getEmployees(filter);
    }
}
</code>```

In order to support pagination, the method accepts a filter DTO to accept parameters such as batch size and page number. Seeing as how this will be common parameters for other DTO classes, I thought of creating a base filter DTO:

```<code>export class BaseQueryFilterDto{

    @IsOptional()
    @IsInt()
    @UsePipes(ParseIntPipe)
    batch:number;

    @IsOptional()
    @IsInt()
    @UsePipes(ParseIntPipe)
    skip:number;

}
</code>```

And then inherit this DTO for the GetEmployeesFilterDto:

```<code>export class GetEmployeesFilterDto extends BaseQueryFilterDto{
    @IsOptional()
    @IsNotEmpty()
    search:string;

    @IsOptional()
    primarySupervisorId:string;

}
</code>```

Running the following request http://localhost:3000/employee?batch=30 would throw the following exception:

```<code>[Nest] 27920   - 02/14/2020, 6:29:54 PM   [ExceptionsHandler] Cannot assign to read only property 'batch' of object '#<GetEmployeesFilterDto>' +606974ms
TypeError: Cannot assign to read only property 'batch' of object '#<GetEmployeesFilterDto>'
    at _loop_1 (C:\ng-proj\nestjs-tutorial\node_modules\class-transformer\TransformOperationExecutor.js:242:47)
    at TransformOperationExecutor.transform (C:\ng-proj\nestjs-tutorial\node_modules\class-transformer\TransformOperationExecutor.js:260:17)
    at ClassTransformer.plainToClass (C:\ng-proj\nestjs-tutorial\node_modules\class-transformer\ClassTransformer.js:17:25)    at Object.plainToClass (C:\ng-proj\nestjs-tutorial\node_modules\class-transformer\index.js:20:29)
    at ValidationPipe.transform (C:\ng-proj\nestjs-tutorial\node_modules\@nestjs\common\pipes\validation.pipe.js:55:41)
    at transforms.reduce (C:\ng-proj\nestjs-tutorial\node_modules\@nestjs\core\pipes\pipes-consumer.js:15:33)
    at process._tickCallback (internal/process/next_tick.js:68:7)
</code>```

However, when i move all the properties from the super class to GetEmployeesFilterDto like so:

```<code>export class GetEmployeesFilterDto extends BaseQueryFilterDto{
    @IsOptional()
    @IsNotEmpty()
    search:string;

    @IsOptional()
    primarySupervisorId:string;

    //Moved from BaseQueryFilterDto
    @IsOptional()
    @IsInt()
    @UsePipes(ParseIntPipe)
    batch:number;

    @IsOptional()
    @IsInt()
    @UsePipes(ParseIntPipe)
    skip:number;

}
</code>```

The request runs successfully.
Am I missing out something here or can I not implement inheritance to controller DTOs in NestJs?

答:
Thanks to @JayMcDoniel for pointing out that I shouldn't be using @UsePipes() on properties.

Here's the solution that works fine for me.

```<code>export class BaseQueryFilterDto{

    @IsOptional()
    @Type(() => Number)
    batch:number;

    @IsOptional()
    @Type(() => Number)
    skip:number;

}
</code>```

Body:
I have a NestJs Get controller which searches for a list of employees.

@Controller('employee')
export class EmployeeController {
    private logger = new Logger('EmployeeController');
    constructor(private employeeService:EmployeeService){}

    @Get()
    @UsePipes(new ValidationPipe({ transform: true }))
    getEmployees(
        @Query() filter:GetEmployeesFilterDto
    ):Promise<Employee[]>{
        console.log(JSON.stringify(filter), filter.batch);
        return this.employeeService.getEmployees(filter);
    }
}

In order to support pagination, the method accepts a filter DTO to accept parameters such as batch size and page number. Seeing as how this will be common parameters for other DTO classes, I thought of creating a base filter DTO:

export class BaseQueryFilterDto{

    @IsOptional()
    @IsInt()
    @UsePipes(ParseIntPipe)
    batch:number;

    @IsOptional()
    @IsInt()
    @UsePipes(ParseIntPipe)
    skip:number;

}

And then inherit this DTO for the GetEmployeesFilterDto:

export class GetEmployeesFilterDto extends BaseQueryFilterDto{
    @IsOptional()
    @IsNotEmpty()
    search:string;

    @IsOptional()
    primarySupervisorId:string;

}

Running the following request http://localhost:3000/employee?batch=30 would throw the following exception:

[Nest] 27920   - 02/14/2020, 6:29:54 PM   [ExceptionsHandler] Cannot assign to read only property 'batch' of object '#<GetEmployeesFilterDto>' +606974ms
TypeError: Cannot assign to read only property 'batch' of object '#<GetEmployeesFilterDto>'
    at _loop_1 (C:\ng-proj\nestjs-tutorial\node_modules\class-transformer\TransformOperationExecutor.js:242:47)
    at TransformOperationExecutor.transform (C:\ng-proj\nestjs-tutorial\node_modules\class-transformer\TransformOperationExecutor.js:260:17)
    at ClassTransformer.plainToClass (C:\ng-proj\nestjs-tutorial\node_modules\class-transformer\ClassTransformer.js:17:25)    at Object.plainToClass (C:\ng-proj\nestjs-tutorial\node_modules\class-transformer\index.js:20:29)
    at ValidationPipe.transform (C:\ng-proj\nestjs-tutorial\node_modules\@nestjs\common\pipes\validation.pipe.js:55:41)
    at transforms.reduce (C:\ng-proj\nestjs-tutorial\node_modules\@nestjs\core\pipes\pipes-consumer.js:15:33)
    at process._tickCallback (internal/process/next_tick.js:68:7)

However, when i move all the properties from the super class to GetEmployeesFilterDto like so:

export class GetEmployeesFilterDto extends BaseQueryFilterDto{
    @IsOptional()
    @IsNotEmpty()
    search:string;

    @IsOptional()
    primarySupervisorId:string;

    //Moved from BaseQueryFilterDto
    @IsOptional()
    @IsInt()
    @UsePipes(ParseIntPipe)
    batch:number;

    @IsOptional()
    @IsInt()
    @UsePipes(ParseIntPipe)
    skip:number;

}

The request runs successfully.
Am I missing out something here or can I not implement inheritance to controller DTOs in NestJs?

Body:
Thanks to @JayMcDoniel for pointing out that I shouldn't be using @UsePipes() on properties.

Here's the solution that works fine for me.

export class BaseQueryFilterDto{

    @IsOptional()
    @Type(() => Number)
    batch:number;

    @IsOptional()
    @Type(() => Number)
    skip:number;

}


问:
Swift: Keep assignment made in closure
Trying to keep a changed value outside a closure. Assigning length from a child in a Firebase database within the observeSingleEvent() call. However, after the function, length's assignment is not kept for use in the for loop, the initial value is used.

Furthermore, I append() a bunch of GMSMarker Objects to the list markers but again the appends are not kept and the list is returned empty

How can I keep the assignments done in the closures. I know in C++ you can use & like [&varName] to pass by reference. Have not found something similar regarding Swift.

```<code>func loadMarkersFromDatabase(ref:DatabaseReference, node:String) -> [GMSMarker] {
        var markers = [GMSMarker]()
        var length:Int? = 1
        ref.child("Config").observeSingleEvent(of: .value, with: { (snapshot) in
                let value = snapshot.value as? NSDictionary
                length = (value?["AcademicBuildingsLength"] as? Int ?? 0)
            })
        print(length!)
        for i in 0...length! {
            ref.child(node).child(String(i)).observeSingleEvent(of: .value, with: { (snapshot) in
                let value = snapshot.value as? NSDictionary
                let building = value?["building"] as? String ?? ""
                let lat = value?["lat"] as? Double ?? 0.0
                let lon = value?["long"] as? Double ?? 0.0
                let marker = GMSMarker()
                marker.position = CLLocationCoordinate2D(latitude: lat, longitude: lon)
                marker.title = building
                marker.snippet = node
                markers.append(marker)
            })

        }
        return markers

    }
</code>```

I have tried adding a closure block [length] like this but then get this compile error: Cannot assign to value: 'length' is an immutable capture

```<code>ref.child("Config").observeSingleEvent(of: .value, with: { [length](snapshot) in
                let value = snapshot.value as? NSDictionary
                length = (value?["AcademicBuildingsLength"] as? Int ?? 0)
            })
</code>```

答:
However, after the function, length's assignment is not kept for use
  in the for loop, the initial value is used.

The modifications to markers are kept. The problem is you are making incorrect assumptions about the order in which things execute. You are assuming that the loadMarkersFromDatabase function returns "after" the closure executes, but that is not the case. The observeSingleEvent method does not execute the closure you give it synchronously, but keeps it around to execute later. (The fact that you need to pass a closure to it is a big hint of this; because it it were synchronous, it could just return the snapshot directly instead of passing it into your closure.)

If you put in logging statements in the two places, you can see the actual order in which they execute. When the closure runs, it will add elements to markers, and any other code that shares access to markers will see that change. But you are not making use of that because your loadMarkersFromDatabase function has already returned.

Title: Swift: Keep assignment made in closure

Body:
Trying to keep a changed value outside a closure. Assigning length from a child in a Firebase database within the observeSingleEvent() call. However, after the function, length's assignment is not kept for use in the for loop, the initial value is used.

Furthermore, I append() a bunch of GMSMarker Objects to the list markers but again the appends are not kept and the list is returned empty

How can I keep the assignments done in the closures. I know in C++ you can use & like [&varName] to pass by reference. Have not found something similar regarding Swift.

func loadMarkersFromDatabase(ref:DatabaseReference, node:String) -> [GMSMarker] {
        var markers = [GMSMarker]()
        var length:Int? = 1
        ref.child("Config").observeSingleEvent(of: .value, with: { (snapshot) in
                let value = snapshot.value as? NSDictionary
                length = (value?["AcademicBuildingsLength"] as? Int ?? 0)
            })
        print(length!)
        for i in 0...length! {
            ref.child(node).child(String(i)).observeSingleEvent(of: .value, with: { (snapshot) in
                let value = snapshot.value as? NSDictionary
                let building = value?["building"] as? String ?? ""
                let lat = value?["lat"] as? Double ?? 0.0
                let lon = value?["long"] as? Double ?? 0.0
                let marker = GMSMarker()
                marker.position = CLLocationCoordinate2D(latitude: lat, longitude: lon)
                marker.title = building
                marker.snippet = node
                markers.append(marker)
            })

        }
        return markers

    }

I have tried adding a closure block [length] like this but then get this compile error: Cannot assign to value: 'length' is an immutable capture

ref.child("Config").observeSingleEvent(of: .value, with: { [length](snapshot) in
                let value = snapshot.value as? NSDictionary
                length = (value?["AcademicBuildingsLength"] as? Int ?? 0)
            })


问:
Best Practice for laying out UI Programmatically for both iPhone and iPad
Looking for a clean solution to laying out UI programmatically and having it look right on every device.  I've tried extending CGFloat to scale numbers depending on the device

```<code>extension CGFloat {
    func scale() {
        // Modifies self by multiplies by the ratio between the initial screen size and the desired screen size
    }
}

// usage
view.widthAnchor.constraint(equalToConstant: 20.scale())
</code>```

I've also tried just creating two different sets of constraints for iPhone and iPad and activating them depending on which device the app is being run on, but this seems unnecessarily verbose.

How can I layout my UI so that it will work on all devices without hacky workarounds.  Are there certain types of constraints I should be avoiding? (for example, instead of setting width/height constants, set them to a multiple of the screen's (or some other view's) width/height?)

EDIT:  I don't want to over-explain my own situation, so let me re-ask the question.  What are some best practices for setting constraints in an application designed for both iPhone and iPad.  Is it bad practice to just check if the device is an iPad, and if it is, have constraints just for iPad, and, if not, have constraints for just iPhone.

答:
Is it bad practice to just check if the device is an iPad, and if it
  is, have constraints just for iPad, and, if not, have constraints for
  just iPhone.

If you're planning for Split-View support, that is definitely a no-go. The code for achieving and handling this is always going to be slightly verbose. There are no one-liners here to achieve what you want.

In your -[UIViewController viewDidLoad] method, you'd want to setup your views with the base trait collection available to the controller's view. This is your starting point.

As and when your App's windows are resized by the OS (imagine going for a fullscreen app in landscape mode to a split-sized app, occupying one-third of the screen): the -[UIViewController traitCollectionDidChange:] method is called on your View Controller. This is where you update your layout constraints.

You can, and should, encapsulate your layout logic in a single method and call it from -[UIViewController viewDidLoad] as well as -[UIViewController traitCollectionDidChange:].

In such a method, I do not recommend checking if the host device is an iPad. You specifically want to look at the active trait collection's horizontalSizeClass & verticalSizeClass properties to determine the values for your layout constraints.

For further information, I suggest you go through the following documentation:

 1. https://developer.apple.com/documentation/uikit/uitraitcollection?language=objc

 2. https://developer.apple.com/documentation/uikit/uitraitenvironment/1623516-traitcollectiondidchange?language=objc

The 2nd link has a simple example on how to check if you need to update your constraints.

Body:
Looking for a clean solution to laying out UI programmatically and having it look right on every device.  I've tried extending CGFloat to scale numbers depending on the device

extension CGFloat {
    func scale() {
        // Modifies self by multiplies by the ratio between the initial screen size and the desired screen size
    }
}

// usage
view.widthAnchor.constraint(equalToConstant: 20.scale())

I've also tried just creating two different sets of constraints for iPhone and iPad and activating them depending on which device the app is being run on, but this seems unnecessarily verbose.

How can I layout my UI so that it will work on all devices without hacky workarounds.  Are there certain types of constraints I should be avoiding? (for example, instead of setting width/height constants, set them to a multiple of the screen's (or some other view's) width/height?)

EDIT:  I don't want to over-explain my own situation, so let me re-ask the question.  What are some best practices for setting constraints in an application designed for both iPhone and iPad.  Is it bad practice to just check if the device is an iPad, and if it is, have constraints just for iPad, and, if not, have constraints for just iPhone.


问:
Get Prior Row of Dataframe in For Loop Python
This is what I believe to be a simple logic problem, but I have been working at this for a while and haven't figured it out, so hopefully someone can find the easy solution that I have been missing. I would like to be able to get the prior part of a dataframe using the following code, and have settle for the (row-1) solve in the fourth row, but that obviously did not work.

```<code>for row in players_at_start_of_period.iterrows():
    if(row[1]['PERIOD']):
        continue
    elif(row[1]['PERIOD'] - 2) > (row-1)[1]['PERIOD']:
        sub_map.update = {row[1]['TEAM_ID_1']: split_row(row[1]['TEAM_1_PLAYERS']), row[1]['TEAM_ID_2']: split_row(row[1]['TEAM_2_PLAYERS'])}
    else:
        continue
</code>```

What would I be able to do to access the value that exists one iteration prior to the current value of 'row'? Thanks!

答:
I am not sure how your data is, but iterrows() already returns the index, so you could do something like this:

```<code>import pandas as pd
import random
# read the data from the downloaded CSV file.
df = pd.read_csv('https://s3-eu-west-1.amazonaws.com/shanebucket/downloads/uk-500.csv')
# set a numeric id for use as an index for examples.
df['index'] = [random.randint(0,1000) for x in range(df.shape[0])]
for index, row in df.iterrows():
    previous_name = ''
    if index > 0:
        previous_name = df.loc[index - 1]['first_name']
    print(previous_name, df.loc[index]['first_name'])
</code>```

Body:
This is what I believe to be a simple logic problem, but I have been working at this for a while and haven't figured it out, so hopefully someone can find the easy solution that I have been missing. I would like to be able to get the prior part of a dataframe using the following code, and have settle for the (row-1) solve in the fourth row, but that obviously did not work.

for row in players_at_start_of_period.iterrows():
    if(row[1]['PERIOD']):
        continue
    elif(row[1]['PERIOD'] - 2) > (row-1)[1]['PERIOD']:
        sub_map.update = {row[1]['TEAM_ID_1']: split_row(row[1]['TEAM_1_PLAYERS']), row[1]['TEAM_ID_2']: split_row(row[1]['TEAM_2_PLAYERS'])}
    else:
        continue

What would I be able to do to access the value that exists one iteration prior to the current value of 'row'? Thanks!

Body:
I am not sure how your data is, but iterrows() already returns the index, so you could do something like this:

import pandas as pd
import random
# read the data from the downloaded CSV file.
df = pd.read_csv('https://s3-eu-west-1.amazonaws.com/shanebucket/downloads/uk-500.csv')
# set a numeric id for use as an index for examples.
df['index'] = [random.randint(0,1000) for x in range(df.shape[0])]
for index, row in df.iterrows():
    previous_name = ''
    if index > 0:
        previous_name = df.loc[index - 1]['first_name']
    print(previous_name, df.loc[index]['first_name'])


问:
Is there a function in C to find a substring overlap?
in C, is there a function that when giver two strings, will return the substring overlap or size of the overlap? So like something that does:

```<code>char s1[5] = {cart};
char s2[4] = {car};
int overlap;
overlap = get_overlap(s1, s2); /*or have overlap be a string if it returns the overlap*.
</code>```

and then overlap would be 3.

If not, how do i make one that will return the int value of the overlap.

答:
```<code>char *strstr(const char *str1, const char *str2);
</code>```

The function strstr() finds the
  occurrence of str2 in the str1 and
  returns the pointer to occurrence of
  str2 in str1. If no match found, then
  a null pointer is returned.

Body:
in C, is there a function that when giver two strings, will return the substring overlap or size of the overlap? So like something that does:

char s1[5] = {cart};
char s2[4] = {car};
int overlap;
overlap = get_overlap(s1, s2); /*or have overlap be a string if it returns the overlap*.

and then overlap would be 3.

If not, how do i make one that will return the int value of the overlap.

Body:
char *strstr(const char *str1, const char *str2);

The function strstr() finds the
  occurrence of str2 in the str1 and
  returns the pointer to occurrence of
  str2 in str1. If no match found, then
  a null pointer is returned.