text:
Q: Build and install of cffi fails (venv) ~/P/PickleballMaps ❯❯❯ pip install cffi==1.11.0                                                                                ✘ 1
Collecting cffi==1.11.0
  Downloading cffi-1.11.0.tar.gz (434 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 434.3/434.3 KB 5.6 MB/s eta 0:00:00
  Preparing metadata (setup.py) ... done
Requirement already satisfied: pycparser in ./venv/lib/python3.8/site-packages (from cffi==1.11.0) (2.18)
Building wheels for collected packages: cffi
  Building wheel for cffi (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> [134 lines of output]
      running bdist_wheel
      running build
      running build_py
      creating build
      creating build/lib.macosx-10.9-x86_64-3.8
      creating build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/backend_ctypes.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/error.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/setuptools_ext.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/__init__.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/cffi_opcode.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/vengine_gen.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/model.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/ffiplatform.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/api.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/vengine_cpy.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/commontypes.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/lock.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/recompiler.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/cparser.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/verifier.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/_cffi_include.h -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/parse_c_type.h -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/_embedding.h -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/_cffi_errors.h -> build/lib.macosx-10.9-x86_64-3.8/cffi
      running build_ext
      building '_cffi_backend' extension
      creating build/temp.macosx-10.9-x86_64-3.8
      creating build/temp.macosx-10.9-x86_64-3.8/c
      gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -DUSE__THREAD -DHAVE_SYNC_SYNCHRONIZE -I/usr/include/ffi -I/usr/include/libffi -I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/ffi -I/Users/johnvergo/PycharmProjects/PickleballMaps/venv/include -I/Library/Frameworks/Python.framework/Versions/3.8/include/python3.8 -c c/_cffi_backend.c -o build/temp.macosx-10.9-x86_64-3.8/c/_cffi_backend.o
      In file included from c/_cffi_backend.c:319:
      c/minibuffer.h:66:9: warning: 'PyObject_AsReadBuffer' is deprecated [-Wdeprecated-declarations]
          if (PyObject_AsReadBuffer(other, &buffer, &buffer_len) < 0)
              ^
      /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/abstract.h:336:1: note: 'PyObject_AsReadBuffer' has been explicitly marked deprecated here
      Py_DEPRECATED(3.0)
      ^
      /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/pyport.h:515:54: note: expanded from macro 'Py_DEPRECATED'
      #define Py_DEPRECATED(VERSION_UNUSED) __attribute__((__deprecated__))
                                                           ^
      In file included from c/_cffi_backend.c:322:
      c/file_emulator.h:54:14: warning: assigning to 'char *' from 'const char *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers]
              mode = PyText_AsUTF8(ob_mode);
                   ^ ~~~~~~~~~~~~~~~~~~~~~~
      c/_cffi_backend.c:2678:10: warning: assigning to 'char *' from 'const char *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers]
          text = PyText_AsUTF8(attr);
               ^ ~~~~~~~~~~~~~~~~~~~
      c/_cffi_backend.c:4748:28: warning: 'PyUnicode_GetSize' is deprecated [-Wdeprecated-declarations]
                      do_align = PyText_GetSize(fname) > 0;
                                 ^
      c/_cffi_backend.c:104:25: note: expanded from macro 'PyText_GetSize'
      # define PyText_GetSize PyUnicode_GetSize
                              ^
      /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/unicodeobject.h:177:1: note: 'PyUnicode_GetSize' has been explicitly marked deprecated here
      Py_DEPRECATED(3.3) PyAPI_FUNC(Py_ssize_t) PyUnicode_GetSize(
      ^
      /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/pyport.h:515:54: note: expanded from macro 'Py_DEPRECATED'
      #define Py_DEPRECATED(VERSION_UNUSED) __attribute__((__deprecated__))
                                                           ^
      c/_cffi_backend.c:4786:17: warning: 'PyUnicode_GetSize' is deprecated [-Wdeprecated-declarations]
                  if (PyText_GetSize(fname) == 0 &&
                      ^
      c/_cffi_backend.c:104:25: note: expanded from macro 'PyText_GetSize'
      # define PyText_GetSize PyUnicode_GetSize
                              ^
      /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/unicodeobject.h:177:1: note: 'PyUnicode_GetSize' has been explicitly marked deprecated here
      Py_DEPRECATED(3.3) PyAPI_FUNC(Py_ssize_t) PyUnicode_GetSize(
      ^
      /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/pyport.h:515:54: note: expanded from macro 'Py_DEPRECATED'
      #define Py_DEPRECATED(VERSION_UNUSED) __attribute__((__deprecated__))
                                                           ^
      c/_cffi_backend.c:4858:21: warning: 'PyUnicode_GetSize' is deprecated [-Wdeprecated-declarations]
                      if (PyText_GetSize(fname) > 0) {
                          ^
      c/_cffi_backend.c:104:25: note: expanded from macro 'PyText_GetSize'
      # define PyText_GetSize PyUnicode_GetSize
                              ^
      /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/unicodeobject.h:177:1: note: 'PyUnicode_GetSize' has been explicitly marked deprecated here
      Py_DEPRECATED(3.3) PyAPI_FUNC(Py_ssize_t) PyUnicode_GetSize(
      ^
      /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/pyport.h:515:54: note: expanded from macro 'Py_DEPRECATED'
      #define Py_DEPRECATED(VERSION_UNUSED) __attribute__((__deprecated__))
                                                           ^
      c/_cffi_backend.c:5817:9: warning: 'ffi_prep_closure' is deprecated [-Wdeprecated-declarations]
          if (ffi_prep_closure(closure, &cif_descr->cif,
              ^
      /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/ffi/ffi.h:348:18: note: 'ffi_prep_closure' has been explicitly marked deprecated here
        __attribute__((deprecated))
                       ^
      In file included from c/_cffi_backend.c:7276:
      In file included from c/cffi1_module.c:15:
      c/ffi_obj.c:191:19: warning: initializing 'char *' with an expression of type 'const char *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers]
                  char *input_text = PyText_AS_UTF8(arg);
                        ^            ~~~~~~~~~~~~~~~~~~~
      In file included from c/_cffi_backend.c:7276:
      In file included from c/cffi1_module.c:17:
      c/lib_obj.c:130:11: warning: initializing 'char *' with an expression of type 'const char *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers]
          char *libname = PyText_AS_UTF8(lib->l_libname);
                ^         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      c/lib_obj.c:209:11: warning: initializing 'char *' with an expression of type 'const char *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers]
          char *s = PyText_AsUTF8(name);
                ^   ~~~~~~~~~~~~~~~~~~~
      c/lib_obj.c:507:7: warning: assigning to 'char *' from 'const char *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers]
          p = PyText_AsUTF8(name);
            ^ ~~~~~~~~~~~~~~~~~~~
      In file included from c/_cffi_backend.c:7276:
      In file included from c/cffi1_module.c:20:
      c/call_python.c:20:30: error: incomplete definition of type 'struct _is'
          builtins = tstate->interp->builtins;
                     ~~~~~~~~~~~~~~^
      /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/pystate.h:20:8: note: forward declaration of 'struct _is'
      struct _is;
             ^
      In file included from c/_cffi_backend.c:7276:
      In file included from c/cffi1_module.c:20:
      c/call_python.c:73:11: warning: assigning to 'char *' from 'const char *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers]
              s = PyText_AsUTF8(name);
                ^ ~~~~~~~~~~~~~~~~~~~
      c/call_python.c:160:39: error: incomplete definition of type 'struct _is'
          new1 = PyThreadState_GET()->interp->modules;
                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~^
      /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/pystate.h:20:8: note: forward declaration of 'struct _is'
      struct _is;
             ^
      In file included from c/_cffi_backend.c:7276:
      In file included from c/cffi1_module.c:20:
      c/call_python.c:249:63: error: incomplete definition of type 'struct _is'
              if (externpy->reserved1 != PyThreadState_GET()->interp->modules) {
                                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~^
      /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/pystate.h:20:8: note: forward declaration of 'struct _is'
      struct _is;
             ^
      12 warnings and 3 errors generated.
      error: command 'gcc' failed with exit status 1
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for cffi
  Running setup.py clean for cffi
Failed to build cffi
Installing collected packages: cffi
  Attempting uninstall: cffi
    Found existing installation: cffi 1.15.0
    Not uninstalling cffi at /Users/johnvergo/Library/Python/3.8/lib/python/site-packages, outside environment /Users/johnvergo/PycharmProjects/PickleballMaps/venv
    Can't uninstall 'cffi'. No files were found to uninstall.
  Running setup.py install for cffi ... error
  error: subprocess-exited-with-error

  × Running setup.py install for cffi did not run successfully.
  │ exit code: 1
  ╰─> [134 lines of output]
      running install
      running build
      running build_py
      creating build
      creating build/lib.macosx-10.9-x86_64-3.8
      creating build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/backend_ctypes.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/error.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/setuptools_ext.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/__init__.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/cffi_opcode.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/vengine_gen.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/model.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/ffiplatform.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/api.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/vengine_cpy.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/commontypes.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/lock.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/recompiler.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/cparser.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/verifier.py -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/_cffi_include.h -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/parse_c_type.h -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/_embedding.h -> build/lib.macosx-10.9-x86_64-3.8/cffi
      copying cffi/_cffi_errors.h -> build/lib.macosx-10.9-x86_64-3.8/cffi
      running build_ext
      building '_cffi_backend' extension
      creating build/temp.macosx-10.9-x86_64-3.8
      creating build/temp.macosx-10.9-x86_64-3.8/c
      gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -DUSE__THREAD -DHAVE_SYNC_SYNCHRONIZE -I/usr/include/ffi -I/usr/include/libffi -I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/ffi -I/Users/johnvergo/PycharmProjects/PickleballMaps/venv/include -I/Library/Frameworks/Python.framework/Versions/3.8/include/python3.8 -c c/_cffi_backend.c -o build/temp.macosx-10.9-x86_64-3.8/c/_cffi_backend.o
      In file included from c/_cffi_backend.c:319:
      c/minibuffer.h:66:9: warning: 'PyObject_AsReadBuffer' is deprecated [-Wdeprecated-declarations]
          if (PyObject_AsReadBuffer(other, &buffer, &buffer_len) < 0)
              ^
      /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/abstract.h:336:1: note: 'PyObject_AsReadBuffer' has been explicitly marked deprecated here
      Py_DEPRECATED(3.0)
      ^
      /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/pyport.h:515:54: note: expanded from macro 'Py_DEPRECATED'
      #define Py_DEPRECATED(VERSION_UNUSED) __attribute__((__deprecated__))
                                                           ^
      In file included from c/_cffi_backend.c:322:
      c/file_emulator.h:54:14: warning: assigning to 'char *' from 'const char *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers]
              mode = PyText_AsUTF8(ob_mode);
                   ^ ~~~~~~~~~~~~~~~~~~~~~~
      c/_cffi_backend.c:2678:10: warning: assigning to 'char *' from 'const char *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers]
          text = PyText_AsUTF8(attr);
               ^ ~~~~~~~~~~~~~~~~~~~
      c/_cffi_backend.c:4748:28: warning: 'PyUnicode_GetSize' is deprecated [-Wdeprecated-declarations]
                      do_align = PyText_GetSize(fname) > 0;
                                 ^
      c/_cffi_backend.c:104:25: note: expanded from macro 'PyText_GetSize'
      # define PyText_GetSize PyUnicode_GetSize
                              ^
      /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/unicodeobject.h:177:1: note: 'PyUnicode_GetSize' has been explicitly marked deprecated here
      Py_DEPRECATED(3.3) PyAPI_FUNC(Py_ssize_t) PyUnicode_GetSize(
      ^
      /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/pyport.h:515:54: note: expanded from macro 'Py_DEPRECATED'
      #define Py_DEPRECATED(VERSION_UNUSED) __attribute__((__deprecated__))
                                                           ^
      c/_cffi_backend.c:4786:17: warning: 'PyUnicode_GetSize' is deprecated [-Wdeprecated-declarations]
                  if (PyText_GetSize(fname) == 0 &&
                      ^
      c/_cffi_backend.c:104:25: note: expanded from macro 'PyText_GetSize'
      # define PyText_GetSize PyUnicode_GetSize
                              ^
      /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/unicodeobject.h:177:1: note: 'PyUnicode_GetSize' has been explicitly marked deprecated here
      Py_DEPRECATED(3.3) PyAPI_FUNC(Py_ssize_t) PyUnicode_GetSize(
      ^
      /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/pyport.h:515:54: note: expanded from macro 'Py_DEPRECATED'
      #define Py_DEPRECATED(VERSION_UNUSED) __attribute__((__deprecated__))
                                                           ^
      c/_cffi_backend.c:4858:21: warning: 'PyUnicode_GetSize' is deprecated [-Wdeprecated-declarations]
                      if (PyText_GetSize(fname) > 0) {
                          ^
      c/_cffi_backend.c:104:25: note: expanded from macro 'PyText_GetSize'
      # define PyText_GetSize PyUnicode_GetSize
                              ^
      /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/unicodeobject.h:177:1: note: 'PyUnicode_GetSize' has been explicitly marked deprecated here
      Py_DEPRECATED(3.3) PyAPI_FUNC(Py_ssize_t) PyUnicode_GetSize(
      ^
      /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/pyport.h:515:54: note: expanded from macro 'Py_DEPRECATED'
      #define Py_DEPRECATED(VERSION_UNUSED) __attribute__((__deprecated__))
                                                           ^
      c/_cffi_backend.c:5817:9: warning: 'ffi_prep_closure' is deprecated [-Wdeprecated-declarations]
          if (ffi_prep_closure(closure, &cif_descr->cif,
              ^
      /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/ffi/ffi.h:348:18: note: 'ffi_prep_closure' has been explicitly marked deprecated here
        __attribute__((deprecated))
                       ^
      In file included from c/_cffi_backend.c:7276:
      In file included from c/cffi1_module.c:15:
      c/ffi_obj.c:191:19: warning: initializing 'char *' with an expression of type 'const char *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers]
                  char *input_text = PyText_AS_UTF8(arg);
                        ^            ~~~~~~~~~~~~~~~~~~~
      In file included from c/_cffi_backend.c:7276:
      In file included from c/cffi1_module.c:17:
      c/lib_obj.c:130:11: warning: initializing 'char *' with an expression of type 'const char *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers]
          char *libname = PyText_AS_UTF8(lib->l_libname);
                ^         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      c/lib_obj.c:209:11: warning: initializing 'char *' with an expression of type 'const char *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers]
          char *s = PyText_AsUTF8(name);
                ^   ~~~~~~~~~~~~~~~~~~~
      c/lib_obj.c:507:7: warning: assigning to 'char *' from 'const char *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers]
          p = PyText_AsUTF8(name);
            ^ ~~~~~~~~~~~~~~~~~~~
      In file included from c/_cffi_backend.c:7276:
      In file included from c/cffi1_module.c:20:
      c/call_python.c:20:30: error: incomplete definition of type 'struct _is'
          builtins = tstate->interp->builtins;
                     ~~~~~~~~~~~~~~^
      /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/pystate.h:20:8: note: forward declaration of 'struct _is'
      struct _is;
             ^
      In file included from c/_cffi_backend.c:7276:
      In file included from c/cffi1_module.c:20:
      c/call_python.c:73:11: warning: assigning to 'char *' from 'const char *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers]
              s = PyText_AsUTF8(name);
                ^ ~~~~~~~~~~~~~~~~~~~
      c/call_python.c:160:39: error: incomplete definition of type 'struct _is'
          new1 = PyThreadState_GET()->interp->modules;
                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~^
      /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/pystate.h:20:8: note: forward declaration of 'struct _is'
      struct _is;
             ^
      In file included from c/_cffi_backend.c:7276:
      In file included from c/cffi1_module.c:20:
      c/call_python.c:249:63: error: incomplete definition of type 'struct _is'
              if (externpy->reserved1 != PyThreadState_GET()->interp->modules) {
                                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~^
      /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/pystate.h:20:8: note: forward declaration of 'struct _is'
      struct _is;
             ^
      12 warnings and 3 errors generated.
      error: command 'gcc' failed with exit status 1
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Can't roll back cffi; was not uninstalled
error: legacy-install-failure

× Encountered error while trying to install package.
╰─> cffi

note: This is an issue with the package mentioned above, not pip.
hint: See above for output from the failure.

I also tried to uninstall cffi and got this message:

pip uninstall cffi
✘ 1
Found existing installation: cffi 1.15.0
Not uninstalling cffi at /Users/johnvergo/Library/Python/3.8/lib/python/site-packages, outside
environment /Users/johnvergo/PycharmProjects/PickleballMaps/venv
Can't uninstall 'cffi'. No files were found to uninstall.

A: Seeing that there are a lot of mentions of deprecated in the output and that cffi==1.11 only had official support up to python 3.6, I would bet that the sole issue is that cffi==1.11 is not compatible with python 3.8.
I would try to use python 3.6 in this case. There should be no compilation neccessary then as there are also whl files on pypi for that version

A: I had a similar issue where cffi was needing to be installed for pdfservices-sdk by Adobe.
The solution it turned out was 2 fold

*

*Make sure the full C++/C Development tools and make sure those are on the PATH environment variable.

*Have python 3.7.9 be the instance of python used as, like an above commenter said, cffi has incompatibilities with the newer versions of python.


text:
Q: Kafka Streams: How to stop stream application when exception Version 1.0
Let's say in the punctuate method of lowlevel processor, creation of a dummy file fails with an exception.  How to stop the stream application when an exception is encountered?
I was wondering if there is a way to throw an exception, but could not add throw clause on the init method.  The following requires to be surrounded by a try-catch OR an exception to be thrown and can't use either one.  Please suggest.
Files.createFile(Paths.get(dummyFile));

A: you could wrap IOException into any unchecked exception like RuntimeException, or would be better to create your own that will extend from RuntimeException, and throw it. if your method throw exception for any incoming message, stream will be in a dead state, so stop consuming messages until you restart application

redpajama_set_name: RedPajamaStackExchange


text:
Q: pdfshuffler not avaliable on Ubuntu 22.04 After an install of 22.04, I am attempting to install pdfshuffler but it appears to not be available.
I'm running this command to install it:
sudo apt-get install pdfshuffler

and the result is:
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
E: Unable to locate package pdfshuffler

Will this be available in the future or did I try to install incorrectly?

A: Packages may be removed from the Ubuntu repositories if they are not updated, and rely on outdated libraries that are not anymore shipped with Ubuntu. That may be the case with Pdf-Shuffler.
Instead consider PDF Arranger. This is functionally equivalent (it actually is a fork of PDF-Shuffler) and is better maintained.

A: You can install PDF Arranger on Ubuntu 22.04 - it has the same functionality and a similar interface to PDF Shuffler.
Install PDF Arranger on Ubuntu:

*

*Launch a Terminal window with Ctrl + T.

*Install the latest Pike PDF:
sudo apt-get install python3-pip python3-distutils-extra python3-wheel python3-gi python3-gi-cairo gir1.2-gtk-3.0 gir1.2-poppler-0.18 gir1.2-handy-1 python3-setuptools

*Install PDF Arranger:

pip3 install --user --upgrade https://github.com/pdfarranger/pdfarranger/zipball/main


text:
Q: Missing method get_WebRootFileSystem in mvc 6? I am trying to upload a file to MVC 6 application using following code.
public void UploadFile(IEnumerable<IFormFile> files)
{
    foreach (var file in files)
    {
        var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
        using (var reader = new StreamReader(file.OpenReadStream()))
        {
            var fileContent = reader.ReadToEnd();
            var Filename = parsedContentDisposition.FileName;

        }
    }
}

I am getting following error. Any help please? I am not sure how to resolve this. i have tried all latest versions of Microsoft.AspNet.StaticFiles as well.
System.TypeLoadException
Method 'get_WebRootFileSystem' in type 'Microsoft.AspNet.Hosting.HostingEnvironment' from assembly 'Microsoft.AspNet.Hosting, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.
at Microsoft.Framework.DependencyInjection.HostingServicesExtensions.AddHosting(IServiceCollection services, IConfiguration configuration)
at Microsoft.AspNet.Hosting.HostingServices.Create(IServiceProvider fallbackServices, IConfiguration configuration)
at Microsoft.AspNet.Loader.IIS.KlrHttpApplication.ApplicationStart(IHttpApplication application)
at Microsoft.AspNet.Loader.IIS.HttpApplicationBase.InvokeApplicationStart(IHttpApplication application)

A: This is mostly sure because of a mismatch between the package versions, or package versions and runtime version. I would bet on the former.
Check the following:

*

*The application uses the same versions for all packages (e.g all of them end with Beta2). You can see this in the project's references node in VS.

*The runtime is from the same release (e.g Beta2). You can check this by right clicking the project -> Properties and look at the runtime version.

If none of these work, please post here the project.json file of your project and the output of the RuntimeInfo middleware which will show exactly what packages are loaded.

A: Be sure all your packages and KRE runtime targets the same beta version and kill all your running Application Server.


text:
Q: SmartGit authentication to bare repository fails, while push from commandline works I've added a remote bare repository using commandline:
git add remote production ssh://username@domain.com/path/to/repo.git

I'm able to push to the repository using:
git push production master

Now I'd like to push from SmartGit:

*

*I right click my local master-branch and choose Push To ....

*In the window I select the production repository and click Push.

*A dialog is shown asking me for private SSH key and passphrase. I point to the private key and type the passphrase then click Login.

*The dialog is shown again and I click Login once again.

*SmartGit display an error in the Output-window:
Push: Could not read from remote repository.
/var/www/website> git push --porcelain --progress --recurse-submodules-check production refs/heads/master
Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
Could not read from remote repository.

I've checked that I have the correct access rights and that the repository exists. Also private key has only read/write permissions for the onwer (chmod 600 ~/.ssh/id_rsa).
What am I missing?

A: *

*Enable Use system SSH client in the Preferences, section Authentication

*Install ssh-askpass: sudo apt-get install ssh-askpass

*Then push again ...


text:
Q: Captivate 7 SCORM Bookmarking I need some help in understanding how Captivate 7 bookmarking works in SCORM 2004 courses. By default, Captivate seems to bookmark your location as the last slide you visited, whether it be the first one in the course or the last one. Restarting a course on Slide 50, moving backwards 20 slides and then exiting will cause you to start again on Slide 30 NOT Slide 50. This is NOT the default functionality we want. We are looking to have Captivate remember your highest slide number visited and then restart from there if you exit and resume at a later time. From what I can tell, there is not an option anywhere to allow this type of behavior so I am working on an HTML5 Widget that will hopefully solve this issue.  To accomplish this, I have done the following:

*

*Created a maxSlide variable in JavaScript that tracks the highest slide visited;

*Overwrote the following functions found in scormdriver.js in my local widget.js file thus replacing the cmi.location variable with my maxSlide variable:

*SCORM2004_SetBookmark(strBookmark)

*SCORM2004_CallSetValue(strElement,strValue)

*setBookmark(strBookmark)

So, testing this out on cloud.scorm.com, using both the console window and debug logger, on the surface it appears that the steps I have taken above are working. However, as the images below show, I navigated to Slide 11, then went back to Slide 1, and exit the course. Upon restarting the course, Captivate grabs the initial bookmark location of 11, but then overwrites it with Slide_1 and then almost immediately after calls setValue with 1. On the prior attempt's log, NO WHERE do I see any cmi.location value being set other than my highest location of 11. Therefore, the $64,000 question is where/how is Captivate getting my last slide location of 1? Is it using a cookie to pull this value of 1? Also,why is it overwriting the first cmi.location getValue of 11 with Slide_1?
Relevant Debug logs from cloud.scorm.com:

First attempt at the course and all locations (cmi.location) are 11, despite navigating backwards to Slide 1 and exiting on Slide 1.

Subsequent attempt with the course shows the initial cmi.location value of 11 being returned. However, Captivate then decides to overwrite it with Slide_1 and then later just "1". Thus, I started the course again on Slide 1 - not Slide 11.
How can I stop the incorrect bookmark value from being loaded/saved? Any and all insight is appreciated. Thanks!

A: I haven't used Captivate 7, but Captivate has previously used cmi.suspend_data to track almost everything. In previous versions of Captivate, the development team decided not to use SCORM's CMI fields the way they were intended to be used, preferring to shoehorn almost everything they need into cmi.suspend_data. This provided flexibility for them because they supported other tracking systems as well, and were not married to SCORM's CMI model.
They certainly changed things up a bit in CP7, but I wouldn't be surprised if they still use some custom logic that melds cmi.suspend_data with cmi.location (if they even use cmi.location at all... it may be populated, but that doesn't mean they use it in their logic).


text:
Q: server side rendering in React : Is this for all the Route URLs? I am going to implement server side rendering through react application. As for as I understand the index.html will be served fast from server. I have a question. if I have a SEO url's named which is stated below, Is all the 3 URL's are rendered from the server Or It render index.html once always and then the client side take care of the URL Route ( basic | advance | test ) . what happens if I have a 3 different meta tags each. How it handled in that case ?
https://website.com/basic
https://website.com/advance
https://website.com/test

A: A typical server-side rendering setup will generate the HTML server-side when the URL is requested directly by the browser.
Then, if JavaScript is supported (and doesn't fail for any reason), navigation within the app will be handled client-side by JS and not retrigger server-side rendering.


text:
Q: Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'reduce') I am working on yup validation. Whenever it comes to FileList validation, if I left the input blank, I got the following error:
enter image description here
Here is my code:
import React, { useEffect, useMemo, useState } from 'react';
import { useLocation } from 'react-router';
import { useDispatch, useSelector } from '@app/hooks';
import { Button, Dimmer, Dropdown, DropdownItemProps, DropdownProps, Form, Header, Loader, Modal } from 'semantic-ui-react';
import { NewBook, TestBook, UpdateParam } from '@app/reducers/master-data/book/book.model';
import * as yup from "yup";
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import { useHistory } from 'react-router-dom';
import { _getAllGenres } from '@app/reducers/master-data/genre/genre.slice';
import { _getAllPublisher } from '@app/reducers/master-data/publisher/publisher.slice';
import { _getAllAuthors } from '@app/reducers/master-data/author/author.slice';
import { _getAllDepartment } from '@app/reducers/master-data/department/department.slice';
import { _updateBook, _getAllBooks, _getBookDetail, _uploadBookFile } from '@app/reducers/master-data/book/book.slice';
import { Wrapper } from '@app/components/data-table/StyledComponent';
import { IBookParam } from '@app/reducers/master-data/book/book.service';
interface IProps {

}

interface ErrMessage {
    type: string,
    message: string
}

const schema = yup.object().shape({
    title: yup.string().required('Title cannot blank'),
    publishYear: yup.number(),
    isPublic: yup.boolean(),
    language: yup.string(),
    authorIDs: yup.array(),
    genreIDs: yup.array(),
    description: yup.string(),
    // departmentIDs: yup.array(),
    publisherID: yup.number(),
    file: yup
        .mixed()
        .required("A random message")
        .nullable(false)
        .test("Empty file", "You need to provide a file", (value: FileList) => {

            let x = value.length !== 0
            debugger
            return  value.length !== 0;
        })
        .test("type", "Only support PDF file", (value: FileList) => {
            return  value[0].type === "application/pdf"
        })

});

const UpdateBookPage: React.FC<IProps> = (props) => {

    const dispath = useDispatch()
    const history = useHistory();
    useEffect(() => {
        dispath(_getAllGenres());
        dispath(_getAllPublisher());
        dispath(_getAllAuthors());
        dispath(_getAllDepartment());
        // dispath(_getAllBooks());
        dispath(_getBookDetail(id));
    }, [])

    const search = useLocation().search;
    const query = new URLSearchParams(search);
    const id = query.get('id') || '';

    const genres = useSelector(state => state.genre).genres;
    const publishers = useSelector(state => state.publisher).publishers;
    const authors = useSelector(state => state.author).authors;
    const departments = useSelector(state => state.department).departments;
    const book = useSelector(state => state.book.selectedBook);
    const isLoading = useSelector(state => state.book.isLoading);
    const statusCode = useSelector(state => state.book.statusCode);
    // console.log(book)

    const defaultDepartments = useMemo<number[]>(() => {
        let temp: number[] = []
        for (let x of book.departments) {

            temp.push(x.id)
        };
        return temp;
    }, [book.departments])

    const defaultAuthors = useMemo<number[]>(() => {
        let temp: number[] = []
        for (let x of book.authors) {

            temp.push(Number(x.id))
        };
        return temp;
    }, [book.authors])

    const defaultGenres = useMemo<number[]>(() => {
        let temp: number[] = []
        for (let x of book.genres) {

            temp.push(Number(x.id))
        };
        return temp;
    }, [book.genres])

    const departmentOptions = useMemo<DropdownItemProps[]>(() => {
        let temp: DropdownItemProps[] = []
        for (let x of departments) {

            temp.push({
                key: x.id,
                text: x.name,
                value: x.id
            })
        };
        return temp;
    }, [departments])

    const genreOptions = useMemo<DropdownItemProps[]>(() => {
        let temp: DropdownItemProps[] = []
        for (let x of genres) {

            temp.push({
                key: x.id,
                text: x.name,
                value: x.id
            })
        };
        return temp;
    }, [genres])

    const authorOptions = useMemo<DropdownItemProps[]>(() => {
        let temp: DropdownItemProps[] = []
        for (let x of authors) {

            temp.push({
                key: x.id,
                text: x.fullName,
                value: x.id
            })
        };
        return temp;
    }, [authors])

    const [openForm, setOpenForm] = useState<boolean>(false)
    const [authorSelected, setAuthorSelected] = useState<Number[]>([...defaultAuthors]);
    const [genreSelected, setGenreSelected] = useState<Number[]>([...defaultGenres]);
    const [departmentSelected, setDepartmentSelected] = useState<Number[]>([...defaultDepartments]);
    const [selectedFile, setSelectedFile] = useState<File | null>(null);
    const [fileErrorText, setFileErrorText] = useState<string>('');
    // const [selectedFile, setSelectedFile] = useState<File|null>(null);
    const [isOpen, setIsOpen] = useState<boolean>(false);
    const [alertText, setAlertText] = useState<string>('');
    const [isFailed, setIsFailed] = useState<boolean>(false);
    const [errMessage, setErrMessage] = useState<ErrMessage>({
        type: '',
        message: ''
    })

    const { register, handleSubmit, formState: { errors }, setValue, trigger } = useForm<TestBook>({
        resolver: yupResolver(schema),
        //   defaultValues: defaultBook
    });

    useEffect(() => {
        if (book) {
            setInitValue()
        }
    }, [book])

    const setInitValue = () => {
        setValue('title', book.title)
        setValue('publishYear', book.publishYear)
        setValue('authorIDs', [...defaultAuthors])
        setValue('language', 'vi')
        setValue('departmentIDs', [...defaultDepartments])
        setValue('description', book.description)
        setValue('genreIDs', [...defaultGenres])
        setValue('isPublic', book.isPublic)
        setValue('publisherID', Number(book.publisher.id))
    }

    // console.log(defaultAuthors, defaultDepartments, defaultGenres)

    const handleSubmitBtn = async (data: NewBook) => {
        debugger
        console.log(data);

        const valid = validateData();
        debugger
        if (valid) {
            data.authorIDs = authorSelected.concat(defaultAuthors);
            data.genreIDs = genreSelected.concat(defaultGenres)
            data.departmentIDs = departmentSelected.concat(defaultDepartments)
            const updateParam: UpdateParam = {
                id: id,
                newBook: data
            }
            console.log(data);
            console.log(selectedFile);
            try {
                debugger
                await dispath(_updateBook(updateParam)).then(() => {
                    if (statusCode == 200) {
                        if (selectedFile != null) {
                            let formData = new FormData();
                            formData.append("FILE", selectedFile);
                            formData.append("NAME", selectedFile.name);
                            const param: IBookParam = {
                                id: localStorage.getItem("BOOKID") || '',
                                file: formData
                            }
                            console.log(param.file);
                            console.log(param.id);
                            dispath(_uploadBookFile(param)).then(() => {
                                if (statusCode == 200) {
                                    setIsOpen(true);
                                    console.log(isOpen);
                                    setAlertText("Update successfully")
                                } else {
                                    setIsOpen(true)
                                    setAlertText("An error has occured. Please try again later");
                                    setIsFailed(true);
                                }
                            })
                        } else {
                            return;
                        }

                    }
                    console.log(data);
                })
            }
            catch {
                setIsOpen(true)
                setAlertText("An error has occured. Please try again later");
                setIsFailed(true);
            }
        }

    }

    const validateData =  (): boolean => {

        let x = authorSelected.concat(defaultAuthors)
        let y = genreSelected.concat(defaultGenres)
        let z = departmentSelected.concat(defaultDepartments)
        debugger
        if (authorSelected.concat(defaultAuthors).includes(0)) {
            setErrMessage({
                type: "AUTHOR",
                message: "At least one author must be selected"
            });
            return false;

        } else if (genreSelected.concat(defaultGenres).includes(0)) {
            setErrMessage({
                type: "GENRE",
                message: "At least one genre must be selected",
            });
            return false;
        } else if (departmentSelected.concat(defaultDepartments).includes(0)) {
            setErrMessage({
                type: "DEPARTMENT",
                message: "At least one department must be selected",
            });
            return false;
        }
        return true;
    }

    const handleAddItem = (data: DropdownProps, type: string) => {
        let val = JSON.stringify(data.value)
        let numArr: Number[] = []
        val = val.substring(1, val.length - 1)
        let valArr = val.split(',');
        // console.log(valArr);
        for (let x of valArr) {
            numArr.push(Number(x))
            // console.log(numArr)
        }
        console.log(numArr)
        // const y: Number[] = numArr
        switch (type) {
            case "AUTHOR":
                setValue("authorIDs", numArr)
                setAuthorSelected(numArr)
                break;
            case "GENRE":
                setValue("genreIDs", numArr)
                setGenreSelected(numArr);
                break;
            case "DEPARTMENT":
                // if(numArr.length > 5){
                //     setErrMessage({
                //         type: "Department",
                //         message: "You can only select maximum of 5 departments"
                //     })
                //     break;
                // }
                setValue("departmentIDs", numArr)
                setDepartmentSelected(numArr);
                break;
        }

    }

    const handleSelectFile = (event: any) => {
        console.log(event.target.files[0]);
        setSelectedFile(event.target.files[0]);
    }

    const handleCancelAction = () => {
        history.push('/master-data/manage-book')
    }

    useEffect(() => {
        console.log(authorSelected)
        console.log(genreSelected)
        console.log(departmentSelected)
    }, [authorSelected, genreSelected, departmentSelected])

    return (

            Update book
            {
                isLoading && (
                    <Wrapper style={{ padding: '40px 0' }}>
                        <Dimmer inverted active={true}>
                            <Loader>Loading</Loader>
                        </Dimmer>
                    </Wrapper>)
            }
            {
                !isLoading && (

                        <Modal
                            size={"tiny"}
                            open={isOpen}
                        >

                            <Modal.Content>

{alertText}

                            </Modal.Content>
                            <Modal.Actions>
                                {!isFailed &&
                                    <Button negative onClick={() => setIsOpen(false)}>
                                        Close
                                    </Button>
                                }
                                <Button positive onClick={() => history.push("/librarian/master-data/manage-book")}>
                                    Ok
                                </Button>
                            </Modal.Actions>
                        </Modal>
                        <Form className="create-book-form" onSubmit={handleSubmit(handleSubmitBtn)}>
                            <Form.Field>
                                Title
                                <input {...register('title')} className="text-field" />

{errors.title?.message}

                            </Form.Field>
                            <Form.Field>
                                Description
                                <textarea {...register('description')} className="textarea-field" />

{errors.description?.message}

                            </Form.Field>
                            <Form.Field>
                                Publish Year
                                <input className="text-field" {...register('publishYear')} />

{errors.publishYear?.message}

                            </Form.Field>
                            <Form.Field>
                                PDF File
                                <input {...register('file')} className="text-field" accept="application/pdf" type="file" name="file" onChange={handleSelectFile} />

{errors.file?.message}

                            </Form.Field>
                            <Form.Field>
                                Access Permission
                                <select defaultValue={book.isPublic ? 1 : 0} className="text-field" {...register('isPublic')}>
                                    <option value={1}>Public</option>
                                    <option value={0}>Restricted</option>
                                </select>

{errors.isPublic?.message}

                            </Form.Field>
                            <Form.Field>
                                Publisher
                                <select className="text-field" {...register('publisherID')} >
                                    {
                                        publishers.map((e) => {
                                            if (e.id === book.publisher.id)
                                                return (<option selected value={e.id}>{e.name}</option>)
                                            else
                                                return (<option value={e.id}>{e.name}</option>)
                                        }
                                        )
                                    }
                                </select>

{errors.publisherID?.message}

                            </Form.Field>
                            <Form.Field>
                                Authors
                                <Dropdown className="text-field" onChange={(e, data) => handleAddItem(data, "AUTHOR")} placeholder='Authors' fluid multiple selection options={authorOptions} defaultValue={defaultAuthors} />

{errMessage.type == "AUTHOR" ? errMessage.message : ''}

                            </Form.Field>
                            <Form.Field>
                                Genre
                                <Dropdown className="text-field" onChange={(e, data) => handleAddItem(data, "GENRE")} placeholder='Genres' fluid multiple selection options={genreOptions} defaultValue={defaultGenres} />

{errMessage.type == "GENRE" ? errMessage.message : ''}

                            </Form.Field>
                            <Form.Field>
                                Department
                                <Dropdown className="text-field" onChange={(e, data) => handleAddItem(data, "DEPARTMENT")} placeholder='Genres' fluid multiple selection options={departmentOptions} defaultValue={defaultDepartments} />

{errMessage.type == "DEPARTMENT" ? errMessage.message : ''}

                            </Form.Field>
                            <Button
                                content="Submit"
                                // onClick={handleSubmit(handleSubmitBtn)}
                                className="ui inverted green button"
                            />
                            <Button
                                color="black"
                                content="Cancel"
                                onClick={() => handleCancelAction()}
                                className="negative ui button"
                            />
                        </Form>

                )
            }

    );
};

export default UpdateBookPage;

When I check the source tab, I find out that the problem comes from here:

But I don't know how to solve it.

A: replace
.required("A random message")
.nullable(false)

to
.test("fileLength", "A random message", (value) => {
        return !!value.length
})


text:
Q: How can I recover overwritten labels, pointer blocks and ueberblocks in a ZFS pool? I caused a stupid accident in a single-disk ZFS pool, seemingly in the same way as the person in this mailing list thread, i. e., I seem to have overwritten important metadata. Can this be restored from the actual payload, or is there a way to retrieve the payload without the metadata?
Here's what I did, exactly:

*

*had a ZFS pool running with a single disk on one machine

*wanted to migrate it to a new ZFS pool on another machine

*forgot to zpool export it on the first machine

*when zpool create complained that the device was in use, I thought "No problem, I just took down the host, it's not in use anymore" and did zpool create -f
What I should have done (as I realised after RTFM) is import  instead of create on the new host. Now I have a working zfspool, but the filesystems are gone / invisible.
I tried to reimport the device on the old host, and later tried import -D, but, quite obviously, both didn't work.

A: Well first things first I'd get a bit stream copy of the disk before trying anything.
Does a zpool import -D do anything?
If I'm honest I don't think it because the new pool has overwritten all labels, blocks and pointer blocks of the original pool.

A: The top and bottom 512 kilobytes of the disk/partition contain the labels, which include a listing of the last few uberblocks (for recovery and rollback) and the RAID geometry of the pool (more specifically the vdev the disk was part of). By making a new pool you've almost certainly wiped out the old labels. This means you need to know the exact geometry of the pool (RAID-Z configuration with disk order) and go looking for the uberblocks the hard way.
A zpool create overwrites all labels on a device (that's why you had to add "-f", which essentially means "blame me if all goes wrong"). Since the vdev labels contain the root block pointer (which points to the root block of the entire pool object tree) and the value in this block pointer moves around as new data is added (due to COW semantics), your data was gone


text:
Q: Construct crispy forms layouts iteratively? I'm currently trying to render a form that will allow our users to edit products, currently the form is being displayed all as one long column.
It has been requested that I split it into two columns but am having issues due to the ModelForm being generated using modelform_factory()
Is there any way in which I can generate a Crispy layout object that can insert new div's every two form objects?
Note: the length of the form is not known beforehand.
View Code:
def layout_from_form(form, columns=2):
    field_count = sum(1 for i in form)  # form specified it's iterable but is not len() friendly
    for field_number, _ in enumerate(form):

        if field_number % columns == 0:

            max_length_field = field_number + 2
            if field_number + 2 > field_count:
                max_length_field = field_count
            try:
                selected_forms = form.helper[field_number:max_length_field]
                selected_forms.wrap(Div, css_class="span6")
                selected_forms.wrap_together(Div, css_class="row-fluid")
            except:
                assert False, (field_count, field_number, max_length_field)

def edit_product(request, bought_in_control_panel_id, item_uuid):

    boughtin_model = get_model_for_bought_in_control_panel(bought_in_control_panel_id)
    item = boughtin_model.objects.get(pk=item_uuid)
    BoughtinForm = modelform_factory(boughtin_model, exclude=("uuid", "date_time_updated", "date_time_created",
                                                              "manufacturer"))
    if request.method == "POST":
        boughtin_form = BoughtinForm(request.POST, instance=item)
        if boughtin_form.is_valid():
            boughtin_form.save()
            return redirect(reverse('view_product', kwargs={'bought_in_control_panel_id': bought_in_control_panel_id,
                                                            'item_uuid': item_uuid}))
    else:
        boughtin_form = BoughtinForm(instance=item)

        boughtin_form.helper = FormHelper(boughtin_form)
        boughtin_form.helper.form_action = reverse('edit_product', kwargs={'bought_in_control_panel_id': bought_in_control_panel_id,
                                                                           'item_uuid': item_uuid})
        boughtin_form.helper.add_input(Submit('submit', 'Submit'))
        layout_from_form(boughtin_form)
    return render_to_response('suppliers/products/edit_product.html', {'item': item,
                                                                       'boughtin_form': boughtin_form,
                                                                       'bought_in_control_panel_id': bought_in_control_panel_id})

Example Layout Object:
Layout(
    Div(
        Field('name'),
        Field('type'),
        css_class="row-fluid"
    ),
    Div(
        Field('uuid'),
        Field('dave'),
        css_class="row-fluid"
    ),
    .... Etc ad infinitum ....
)

A:
In your question: "Note: the length of the form is not known beforehand."

We can indeed find the length of a form beforehand:
>>> import apps.students.models as models
>>> from django.forms.models import modelform_factory
>>> form = modelform_factory(models.StudentProfileBasics)
>>> len(form.base_fields.keys())
5

From there, the combination of a) Crispy's ability to modify layouts on the go by grabbing slices of a layout, b) the wrap method that Crispy provides, and c) the list provided by forms.Form.base_fields.keys() should get you where you need to be!


text:
Q: Error in function "leveneTest" in shinyapp I have a shiny app that is using levene's test in one part of the app. It works on Rstudio without any error, but I faced a problem when I transfered it on the web (using shinyapp.io). The app is runing but I can't see the result of levene's test.
Error:
An error has occurred. Check your logs or contact the app author for clarification.

I found the error from Logs :
Error in leveneTest: could not find function "leveneTest"

Why does it happened only on the web?


text:
Q: how to check an instance variable I am new to rails and am stuck: I have a model for Articles, Topics and Links. On the page, where the whole article is displayed, I show in div-boxes all @topics and all @links, which are connected to this article (@topics.each ...).
Sometimes there is/are no topic/topics or link/links connected to this one article and I don't want to show the div-box.
How do I test if the instance variable @topics is empty and therefore must not be displayed? Do I check this in the view or do I check it in the controller? Since I have no real clue I don't know where to start looking for.

A: In the view, put your each loop under unless @topics.empty?.
Edit: But this does not cover the case when the @topics instance variable is not set at all. For a better pattern see tadman's response.

A: The usual pattern is this:
if (@topics.present?)
  @topics.each do |topic|
    # ... Show each row
  end
else
  # .. Show a "no entires" row.
end

A: I probably misunderstood your question.
Assuming:

*

*You're doing this in erb,

*You have a @article variable, and

*Your associations are set up correctly so you can do @article.topics
Then I would think you could do something like:
<%- if @article.topics.any? %>

    <%- @article.topics.each do |topic| %>

        ... do some stuff

    <% end %>

<% end %>

Similar, naturally, for @article.links.
My erb is very rusty, so I might have gotten something wrong in there.


text:
Q: Cannot Read Write NFC C# using library i have a coursework about nfc read and write, but i'm still new using C# and i found some libraries about nfc c#. one of them from h4kbas which I'm currenly using righ now.
the first thing i try is how to read UID, but it seem work fine
        private void button1_Click(object sender, EventArgs e)
        {
            if (NFC.Connect())
            {
                textBox1.Text = NFC.GetCardUID();
            }
        }

and then i try making read and write :
Read
        private void button2_Click(object sender, EventArgs e)
        {
            if (NFC.Connect())
            {
                NFC.WriteBlock(textBox2.Text, "5");
                //Close();
            }

        }

Write
        private void button3_Click(object sender, EventArgs e)
        {
            if (NFC.Connect())
            {
                NFC.ReadBlock("5");

                //Close();
            }
        }

but after i try making a read and write function above, i don't found any error massage but if i try read or write some string data on running process, forced to close and give massage "The program '[10192] WFANFCReadWriteExecute.exe' has exited with code -1 (0xffffffff)." still..., i don't know the problem is on my code or i have to use "AuthBlock" first.


text:
Q: What's a word for "a thoroughly enjoyable experience"? What's a word for "a thoroughly enjoyable experience"? Something like the opposite of a "trial"?

A: "Slang" terms that I've come across for "pleasurable" are "lark," and "lulu."'
That was a lark. or
That was a lulu.

A: A pleasure?

The condition or sensation induced by the experience or anticipation of what is felt to be good or desirable; a feeling of happy satisfaction or enjoyment; delight, gratification. Opposed to pain.

A treat?

Something highly enjoyable; a great pleasure, delight, or gratification.

A delight?

Anything in which one takes delight, or which affords delight; an object of delight; a source of great pleasure or joy.

(All from the OED.)

A: If you mean something that gives pleasure:
Delight

a high degree of gratification : joy; also : extreme satisfaction
something that gives great pleasure

If you're talking about the state of mind:
Bliss

complete happiness

There are also joy (which can be used in both contexts), pleasure, and felicity.

A: A good opposite of trial would be lark or breeze, if you are interested in the testing or "putting to the proof" aspect of the word trial.

How was the job interview? It was a breeze.

A: You could have a ball  (sense 2).

A: How about 'I'm having a blast!'?

A: When you're having a really hard time it can feel like a trial. When you're having a really good time it can feel like a festival.


text:
Q: JQuery Cookie.js Save cokkie Hi there i am using jquery cookie.js to store cookie.
I have search the code and with the cookie.js plugin it's working fine,
But i am having an issue that when i refresh the page the cookie automatically save and the popup does not display. When any user enter on the site a popup appear and the user must have to click the continue button to enter on the site,
I am basically not allowing user to enter on the site before clicking the continue button.
Here is my html code

Are You Over 18? Click Continue if you are or return to previous
      page

  Continue

And this is the js code i am using

A: When you have number of cookies visits cookie may not be the first cookie in the cookie array so you have to try to get that cookie by using following both ways
jQuery.cookie('visits')

jQuery.cookie(' visits')


text:
Q: Integrate Cognitive Speech in Directline 4.0 Webchat Previously in V3.0 I was using this code and passing it to Bot.App as parameter, but I don't know how to achieve this in Directline V4.0 using Webchat-E5.js
const speechOptions = {
        speechRecognizer: new CognitiveServices.SpeechRecognizer({ locale: 'de-DE', subscriptionKey: '1add78901d9d' }),
        speechSynthesizer: new CognitiveServices.SpeechSynthesizer({
            gender: CognitiveServices.SynthesisGender.Female,
            subscriptionKey: '1add78125a901d9d',
            voiceName: 'Microsoft Server Speech Text to Speech Voice (de-DE, Stefan, Apollo)'
        })
    };

Many Thanks in Advance.
Text to Speech not working with Cognitive Bing API.
 window.fetch('https://sfbotspeech.cognitiveservices.azure.com/sts/v1.0/issuetoken', { method: 'POST', headers: {
                            'Ocp-Apim-Subscription-Key' : 'f9d649bf33bf2427c', 'Content-type': 'application/x-www-form-urlencoded' , 'Content-Length': '0'} })
         .then(function (res) {
          return res.text();
        })
        .then(function (authtok) {
              SpeechToken =  authtok;

        console.log(SpeechToken)    ;
        const webSpeechPonyfillFactory =  WebChat.createCognitiveServicesSpeechServicesPonyfillFactory({
           authorizationToken: SpeechToken
         });

        ///
        WebChat.renderWebChat(
            {
                bot: bot,
                directLine: WebChat.createDirectLine({token}),
                user: user,
                //speechOptions: speechOptions,
                resize: 'detect',
                styleOptions: styleOptions,
                selectVoice: (activity) =>
                    activity.locale === 'de-DE',
                webSpeechPonyfillFactory : webSpeechPonyfillFactory
            },
            document.getElementById('BotChatGoesHere')
        );

A: Check out sample 06.g.select-voice located on the BotFramework-WebChat repo. The attached index.html shows the complete code.
The above sample expands on sample 06.c.cognitive-services-speech-services-js. If you need additional guidance, consider looking this one over.
Hope of help!


text:
Q: speeding up cvs pserver over WAN I have a remote location with 5 developers that are using a CVS (pserver) repository in main office via WAN, but the bandwidth i have is only a couple of hundred kbps so CVS operations are fairly slow.
Is there any way to speed this up? I can rsync over a local copy of the CVS root(s) every couple of minutes, so this can handle the updates, but obviously not the commits. Is there any way to say to CVS to update from one server, but push to another one?
Any other ideas?

A: You could try enabling Gzip compression on your SSH tunnel.  That usually improves speed on things like that.


text:
Q: Blade conditional statements I have several models.  Each model has a create and edit page.  If the model has not been created yet, I need to display its create page.  If it has been created, I need to show its edit page.
So far I have this which works

    @if (is_null($project->projectType))
        @include ('projects.partials.projectTypesCreate')
    @else
        @include ('projects.partials.projectTypesEdit')
    @endif

    @if (is_null($project->projectData))
        @include ('projects.partials.projectDataCreate')
    @else
        @include ('projects.partials.projectDataEdit')
    @endif

    @if (is_null($project->projectTesting))
        @include ('projects.partials.projectTestingCreate')
    @else
        @include ('projects.partials.projectTestingEdit')
    @endif

Now, the above is not the prettiest, to many conditional statements in my opinion.  What makes this worse is the fact that I need to display things in order.  By this I mean that if projectType is null,
only projectTypesCreate should be displayed.  If it is not null. projectTypesEdit and  projectDataCreate should be displayed, and so on.
To accomplish this I could potentially do something like so
@if (is_null($project->projectType))
    @include ('projects.partials.campaignTypes')
@else
    @include ('projects.partials.campaignTypesEdit')
@endif

@if (!is_null($project->projectType) && is_null($project->projectData))
    @include ('projects.partials.projectDataCreate')
@else
    @include ('projects.partials.projectDataEdit')
@endif

@if (!is_null($project->projectData) && is_null($project->projectTesting))
    @include ('projects.partials.projectTestingCreate')
@else
    @include ('projects.partials.projectTestingEdit')
@endif

Once again though, it is getting a bit clunky and it is not accurate as to what I need because the edit page will display when the condition fails.
So really I am just after some advice as to how to best handle this situation.  I need to determine what view to display for each model, whilst at the same time displaying views sequentially.
Thanks

A: Create a single $action variable that holds the action you want to do, then use that in your @include statements:

    @php($action = is_null($project->projectType) ? 'Create' : 'Edit')

    @include('projects.partials.projectTypes'.$action)
    @include('projects.partials.projectData'.$action)
    @include('projects.partials.projectTesting'.$action)

A: I'd have a look at RESTful routing in laravel. For one line in your routes file, several routes will be generated to allow you to perform CRUD operations on a model.
https://laravel.com/docs/5.1/controllers#restful-resource-controllers
Then if you need to reuse form elements you could create partials that are included on multiple views. Its a bit more work to set up but is easy to edit later on.


text:
Q: Solving system of equations using Chinese remainder theorem I have a system of equations on that I would like to solve programatically:
$(x + a_1) \bmod b_1 = 0$
$(x + a_2) \bmod b_2 = 0$
$...$
$(x + a_i) \bmod b_i = 0$
$a$ and $b$ are given, and I would like to find the smallest positive solution for $x$. The numbers are too big to iterate through all possible solutions. I think it should be possible to solve it using the Chinese  remainder theorem, but I haven't been able to get from one to the other. How can I translate this problem into a problem that can be solved using the CRT?

A: Your system of equations is the same as solving $x\equiv -a_i \pmod{b_i}$.


text:
Q: List IDs That Aren't in An Inner Join I have a SELECT statement that provides me with a list of relevant IDs and company names that match the criteria.  Here is the statement:
$result = mysqli_query($con,"SELECT a.OWNER_ID,b.ID, b.TITLE AS companyname FROM b_crm_act a INNER JOIN b_crm_company b ON a.OWNER_ID = b.ID");

while($row = mysqli_fetch_array($result))
{
echo "
";
echo "" . $row['ID'] . "	";
echo "" . $row['companyname'] . "	";
echo "
";
}
echo "
";

This lists all the IDs and company names. What I actually need is a list of IDs from b_crm_company that aren't in b_crm_act.  I'm thinking I use NOT IN function but I've tried this and it's not listing anything.
Your help would be appreciated.

A: you can use LEFT JOIN on this
SELECT  a.ID,
        a.TITLE AS companyname
FROM    b_crm_company a
        LEFT JOIN b_crm_act b
            ON a.ID = b.OWNER_ID // <== specify how the tables are linked
WHERE   b.OWNER_ID IS NULL       // <== a value of NULL when it doesn't exists

Not sure about your column names but this is how it looks like.

A: I don't know how efficient this is but have you tried using a NOT IN subquery?
SELECT ID,title FROM b_crm_company WHERE ID NOT IN( SELECT ID FROM b_crm_company INNER JOIN b_crm_act ON b_crm_act.OWNER_ID = b_crm_company.ID )


text:
Q: Beaumont - Pierce Principal theorem In book R. Göbel, P. Hill, Wolfgang "Abelian Group Theory and Related Topics", I found next Beaumont -Pierce Principal theorem: Any torsion-free ring $R$ of finite rank is quasi-equal to $S\oplus N$, where $N$ is nilradical, and $S$ is subring of $R$.
My question is: is $R$ need to be commutative in this theorem. If "No", what nilradical mean for noncimmutative rings?

A: No, every endomorphism ring of a torsion-free group falls into this class of rings and they are usually non-commutative.


text:
Q: What is the broadest definition of conditional probability? The usual definition of conditional probability on a probability space $(\Omega, \sigma, P)$ is~:
$$P(A|B) = \frac{P(A \cap B)}{P(B)}$$
which obviously implies that $B$ must not be a negligible set. However this definition appears too restrictive as we sometimes need to compute probabilities conditioned by negligible sets (a usual case is for example an event of the form $B = \{X = x\}$ where $X$ is a continuous random variable and $x$ a real number). Informally speaking we would like to define~:
$$P(A|B) = \underset{P(B') > 0}{\lim_{B'\rightarrow B}} \frac{P(A \cap B')}{P(B')}$$
Now the meaning of the limit should be made precise. I'm neither aware of a topology defined on $\sigma$ itself nor convinced it is the way to go. It might also be possible to work with sequences of decreasing events which in some sense "convergence" toward $B$:
$$B_1 \supset B_2 \supset \cdots \supset B$$
such that:
$$\forall x \in \Omega \setminus B, \exists n \in \mathbb N,  x \not\in B_n$$
But I'd like to know if some formal definition already exist.

A: The conditional probabilities used in modern mathematical probability theory are defined with respect to a $\sigma$-algebra.
Let $(\Omega, \mathcal{F}, P)$ be a probability space and let $\mathcal{G}$ be a sub-$\sigma$-algebra of $\mathcal{G}$. Then the conditional probability $P(\cdot \mid \mathcal{G})$ is a $\mathcal{G}$-measurable random variable that satisfies
$$P(\cdot \cap G) = \int_G P(\cdot \mid \mathcal{G})dP$$
for all $G \in \mathcal{G}$. The existence and almost sure uniqueness of $P(\cdot \mid \mathcal{G})$ is guaranteed by the Radon-Nikodym theorem. If you're familiar with conditional expectations, you'll notice that, for $A \in \mathcal{F}$, we have $P(A \mid \mathcal{G}) = E(\mathbf{1}_A \mid \mathcal{G})$.
This generalizes the definition of conditional probability that you mention as follows. Let $\mathcal{G}$ be generated by a partition $\{E,E^c \}$ with $P(E)>0$. Then, since $P(\cdot \mid \mathcal{G})$ is $\mathcal{G}$-measurable, it is constant on $E$ (this being an atom of $\mathcal{G}$). Therefore, by the equation above we have, for almost all $\omega \in E$,
$$P(\cdot \mid \mathcal{G}) = \frac{P(\cdot \cap E)}{P(E)} = P(\cdot \mid E).$$
We can use this theory of conditional probability to condition on probability $0$ events by first embedding such events in a $\sigma$-algebra. For examples, see any of the standard textbooks on measure-theoretic probability, e.g. Billingsley.
There are other theories of conditional probability in which conditional probabilities are primitive, and not defined in terms of unconditional probabilities as we've done above. For example, Alfred Renyi developed such a theory and it is explained reasonably clearly in chapter 4 of Rao's Conditional Measures and Applications. As far as I can tell, Renyi's theory hasn't been nearly as influential as the theory explained above.


text:
Q: JavaScript Cloned Table Rows - reset value I have a form/table set up that's cloning rows with specific valued names so that they can be processed separately once the form submits. All seems to be well unless you fill out information on the 5th row (the row being cloned) and then it copies all of the data over into the cloned row.
Is there an easy way to reset the values to NULL and 0 during the cloning process?
(I have two rows on bottom that are tallying/totalling each column, hence the tr:nth-last-child(2))
var totalRows = 5;

function addrow() {
  totalRows++;
  var clonedRow = $("table#maintable tr:nth-child(5)").clone(); //this will grab the 5th table row.

  //get the textfield
  var tfName = $("input.name",clonedRow);
  var tfproA = $("input.proA",clonedRow);
  var tfproB = $("input.proB",clonedRow);
  var tfproC = $("input.proC",clonedRow);
  var tfproD = $("input.proD",clonedRow);
  var tfproE = $("input.proE",clonedRow);
  var tfproF = $("input.proF",clonedRow);
  var tfproG = $("input.proG",clonedRow);
  var tfproH = $("input.proH",clonedRow);
  var tfproI = $("input.proI",clonedRow);
  var tfproJ = $("input.proJ",clonedRow);
  var tfproK = $("input.proK",clonedRow);
  var tfproL = $("input.proL",clonedRow);
  var tfproM = $("input.proM",clonedRow);
  var tfproN = $("input.proN",clonedRow);

  //change their names
  tfName.attr("name","name"+totalRows);
  tfproA.attr("name","proA"+totalRows);
  tfproB.attr("name","proB"+totalRows);
  tfproC.attr("name","proC"+totalRows);
  tfproD.attr("name","proD"+totalRows);
  tfproE.attr("name","proE"+totalRows);
  tfproF.attr("name","proF"+totalRows);
  tfproG.attr("name","proG"+totalRows);
  tfproH.attr("name","proH"+totalRows);
  tfproI.attr("name","proI"+totalRows);
  tfproJ.attr("name","proJ"+totalRows);
  tfproK.attr("name","proK"+totalRows);
  tfproL.attr("name","proL"+totalRows);
  tfproM.attr("name","proM"+totalRows);
  tfproN.attr("name","proN"+totalRows);

  $("table#maintable tr:nth-last-child(2)").before(clonedRow); //add the row back to the table before the last 2nd to last row
  console.log('done')
}

A: You can chain together a call to val()
tfName.attr("name","name"+totalRows).val(0) or
tfName.attr("name","name"+totalRows).val('')


text:
Q: Add ajax return value to selectbox? I am trying to insert a value from my database to select box using it's ID. this my code for that
<select id="branch_name">
    <option value="0">Select branch Name</option>
</select>

$.ajax({
    url : 'get_savac_member_data.php',
    method : "POST",
    data : data,
    success : function(response){
        // window.location.replace("items_insert_form.php");
        var res = response;
        var segments = response.split(",");

        $("#brnch_name").val(segments[17].trim());

    }
});

My value has returned successfully. But, it shows nothing to my select box. Can anyone help me please?

A: You need to add proper html to select. Something like
 for(var key in obj) {
        html += "<option value=" + key  + ">" +obj[key] + "</option>"
    }

And then $("#brnch_name").html(html).
For this example, I assume you are getting response in json format

A: Use $.each like below:
$.ajax({
    url : 'get_savac_member_data.php',
    method : "POST",
    data : data,
    success : function(response){
    // window.location.replace("items_insert_form.php");
    var res = response;
    var segments = response.split(",");
    $.each(res, function (key, value) {
        $("#brnch_name").append($("<option></option>").val(segments[key].trim());
        });
   }
});

A: Here is my solution:
  $("#brnch_name").empty(); //clear the drop down box
  for (var i=0;i<segments.length;i++)
  {
     html="<option value=\""+segments[i]+"\">"+segments[i]+"</option>";
     $("#brnch_name").append(html);
  }

A: You can loop the response and append to select with $('#branch_name').append($('<option>', { value: item.value, text : item.text })); here value is the value of option and text is text to be displayed on dorpdown.

$.ajax({
    url : 'get_savac_member_data.php',
    method : "POST",
    data : data,
    success : function(response){
    // window.location.replace("items_insert_form.php");
    var res = response;
    var segments = response.split(",");
    $.each(res, function (i, item) {
        $('#branch_name').append($('<option>', {
            value: item.value,
            text : item.text
         }));
    });
});
<select id="branch_name">
  <option value="0">Select branch Name</option>
</select>

A: You need to iterate through each branch names from response and append the same as individual <option> tags. However you have already got several solutions for the same, while mine uses simple string replace.

/* this is only relevant script */
var response = 'Branch 1,Branch 2,Branch 3,Branch 4';
$('<option>' + response.replace(/\,/g, '</option><option>') + '</option>').appendTo('#branch_name');
/*in-case you wish to show a default selection */
$('#branch_name').prop('selectedIndex', 3);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="branch_name"><option value="0">Select branch Name</option></select>


text:
Q: auto select an option by matching div data attribute and option value? Please take a look at this auto slider (fiddle). The select box is there to allow users to jump to a specific slide. When the slider is on auto-rotate mode, I want the select option to change based on the current slide. Do you think it's possible by getting the data attribute (e.g title1 of the present slide and matching it with the option value title1? Right now the select box is fixed at default option.

Title1

text

Title2

Text

<button id="left">left</button>
<button id="right">right</button>

<select class="select_title">
 <option value="title1">Select</option>
 <option value="title1">Title_1</option>
 <option value="title2">Title_2</option>
</select>

AutoRotate Function:
 function autoRotate(){
  intv = setInterval(function(){
      $('#right').click();
  },10000); //Pause Time
     $('.select_title').prop('selectedIndex',0);
 }

 autoRotate(); // start auto rotate

A: use this code $('.select_title').prop('selectedIndex',C+1); instead of $('.select_title').prop('selectedIndex',0);
$( document ).ready(function() {

var intv;
var autoRotate;

var sliderplace = $('#searchslider .eventslide');
var W = sliderplace.width();
var N = sliderplace.length;
var C = 0;

$('#searchslider').width( W*N );

$('#left, #right,#auto').click(function(){

  if(this.id=='right'){

    C++;
    C = C % N;     // reset to '0' if end reached

  }else{ // left was clicked

    C--;
    if(C===-1){   // IF C turns -1 scroll to last one (N-1)
      C = N-1;
    }

  }
  $('.select_title').prop('selectedIndex',C+1); // this line added for auto select
  $('#searchslider').stop().animate({left: -C*W }, 500 );
});

 function autoRotate(){
  intv = setInterval(function(){
      $('#right').click();
  },10000); //Pause Time
     $('.select_title').prop('selectedIndex',C+1);
}
autoRotate(); // start auto rotate

// pause hover

$('#event_rotator').on('mouseenter mouseleave', function( e ){
   var mEnt = e.type=='mouseenter';
  if(mEnt){
     clearInterval(intv);
  }else{
     autoRotate();
  }
});
$('.select_title').change(function(){

    var optionSelected = $("option:selected", this);
    var selIndex = $(this).prop("selectedIndex");
    if (selIndex == 0) return false;
    C = selIndex - 1;

     clearInterval(intv);
    if(optionSelected){
        autoRotate(); }

   $('#searchslider').stop().animate({left: -C*W }, 500 );
});

});

Here http://jsfiddle.net/K3bWS/

A: Try checking the offset of each frame to get the current frame. Then read out that title attribute and change the option value accordingly
$( "#searchslider" ).promise().done(function() {
   $('#searchslider').find('.eventslide').each(function(){
    var parentLeft = $('#searchslider').offset().left;
    var offsetX = $(this).offset().left;
    if (offsetX == 22){
        var dataAttribute = $(this).attr('data-title');
        $('.select_title').val(dataAttribute);
        console.log(dataAttribute);
    }
    });
});

http://jsfiddle.net/cYFLe/62/

A: To make it work I suggest this select field to be generated after the page is loaded.
jQuery should count the titles and create a options for this select field.
Once this one is done - it's all simple.
JS

Here is the fiddle: http://jsfiddle.net/cYFLe/61/


text:
Q: Proper way to unit test beforeFilter() and beforeRender() in AppController I'm writing unit tests for a new site I'm working on that uses CakePHP 2.3. Everything's going smoothly, except for one thing. I want to test the beforeFilter() and beforeRender() functions. beforeFilter() I can test easily enough by creating a mock object
$app_controller_mock = $this->generate(
    'App',
    array(
        'components' => array(
            'Session'
        )
    )
);
$app_controller_mock->beforeFilter();

That will run the function, but it won't give me the useful stuff like $this->vars, $this->content, etc. On this particular function that's ok, but in my beforeRender() I'm manually setting a viewVar that I want to check for in my test case.
$app_controller_mock->beforeRender();
$this->assertNotNull($this->vars['controller_name'], "'controller_name' viewVar is null");

When I do the above, I get the following error:
'controller_name' viewVar is null
Failed asserting that null is not null.

What's the "proper" way to do this?

A: Something I usually do is dispatch a full request, which ensures all integrated components exist for beforeFilter and beforeRender.
Sometimes, a dummy controller is helpful:
App::uses('ControllerTestCase', 'TestSuite');
App::uses('AppController', 'Controller');
class MockFiltersController extends AppController {
    public $controllerVar = 'something';

    public function action($var1 = null) {
        // can be helpful to set other vars, or
        // set something on the controller
        $this->controllerVar = $var1;
        $this->set(compact($var1));
    }
}

class AppControllerTest extends ControllerTestCase {

    public function testBeforeRender() {
        $this->testAction('/mock_filters/action/test', array(
            'method' => 'GET'
        ));
        // ensure view vars are set
        $this->assertEquals('test', $this->vars['var1']);
        // other assertions for beforeRender items
    }

}

Then repeat for beforeFilter, mocking using generate() as necessary.
The $this->vars, content, view, etc. variables are only set when using ControllerTestCase::testAction to run an integration test.
Using this methods seems to be effective for me, as I can check for variables that are changed on the controller itself, integration with various components, and of course view variables being set.


text:
Q: Looking for a verb formed from a plural noun Almost any singular noun can be verbed, transformed into a verb means to remove (skin), apply (paint), use (bus), or otherwise interact with the noun.
I'm looking for a plural noun that can be verbed.  I have only two, frankly terrible, examples:

*

*times, which has a very childish sound to my ears

*mules, which refers to a surgical procedure performed on sheep, and is named for a Dr. Mules, and not the sturdy equine, although I assume the name of the eponymous vet originally derives from that animal.

Is there a true example?  Tell me that to cats someone is a thing.

A: Yes, there are a few words that are like this, even more if both slang and obscure/obsolete words are included (that's actually most of the list). I found these with an advanced search on OED:

*

*balls/bollocks (slang)

*(de-)pants (slang)

*discommons (historical & rare)

*guts (colloquial)

*quicksticks (slang, rare, & possibly formed from adj not noun)

*sessions (slang)

*suds

*times (there is another, non-colloquial meaning in Building & Surveying)

*twos (colloquial)

If you include irregular plurals, there is:

*

*dice

*people

A: I can think of a number off the top of my head:

*

*cups

*groups

*heads

*faces

*numbers

*plates

*forks

*spoons

A: Numerals:
(the golfer) bogey-fived the eighth
(batsman) centuried with an off-drive.
collectives:
to regiment a collection of pencils;
to convoy a group of students;
to team up with a casual acquaintance;


text:
Q: Woocommerce Webshop on bitnami stack (ec2): SSL operation failed with code 1. OpenSSL Error messages: error:14090086 I simply can't find a solution to this. I migrated a Wordpress site with a woocommerce shop and payment gateway "Payunity" to a new EC2 machine with a bitnami wordpress stack.
I generated a Let's Encrypt SSL certificate and the entire site works as expected.
Only problem I have is that for some reason on the woocommerce checkout page I suddenly get this error message:

SSL operation failed with code 1. OpenSSL Error messages:
  error:14090086:SSL routines:ssl3_get_server_certificate:certificate
  verify failed

I googled extensively and tried figuring this out but no chance.
Any idea what I have to set on the server to have this go away? I tried modifying the php.ini with the capath and cafile like some threads pointed out but no luck.
Any ideas?
Update: I now moved to Cloudflare as DNS Manager and have the "Full (strict) setting so that the Cloudflare SSL is the one in use. However still the same error, so I figure this has nothing todo with the original Let's Encrypt or now Cloudflare SSL Certificate.

A: I believe this error message is caused by CURL. According to the CURL FAQ (https://github.com/curl/curl/blob/master/docs/FAQ) section 4.12 (where exactly this error message is mentioned), "it means that curl couldn't verify that the server's certificate was good. Curl verifies the certificate using the CA cert bundle that comes with the curl installation." (vsince CURL 7.10).
As your CURL version is quite old (released on Oct 7, 2015), I would assume that one of the CA/root certificates it is using is too old. I would recommend updating CURL separately (e.g. using this guide: http://pavelpolyakov.com/2014/11/17/updating-php-curl-on-ubuntu/, depending on your OS).
Furthermore, you can check the openssl.cafile option in php.ini that should point to an absolute path containing a more or less recent CA bundle (e.g. "C:\xampp7.3\apache\bin\curl-ca-bundle.crt" for my XAMPP installation). You can try to extract the bundle from the XAMPP .zip (https://www.apachefriends.org/download.html) and replace the path in your php.ini and then restart the server.
In addition, you can check your php.ini if extension=php_openssl.* (extension e.g. dll for Windows) is uncommented, i.e. activated.
Maybe (and this is why I asked what should be shown normally at this place) a script inside the Payunity plugin is trying to fetch something from an URL with a broken certificate or something similar.
EDIT: As pointed out by Sebastian B., you can check the error.log (in case of Apache) for failed file_get_contents() (or similar) calls because the actual URL of the "file" the site PHP tried to fetch is mentioned there.
EDIT: CURL Perl script to create a fresh ca-bundle.crt file based on Mozilla's chain: https://github.com/curl/curl/blob/master/lib/mk-ca-bundle.pl You can try this (or extract one from a fresh CURL installation) and set this as a path in php.ini. Or you can use this from the Nextcloud project (https://github.com/nextcloud/server/blob/master/resources/config/ca-bundle.crt) or another one (just for testing purposes, of course).


text:
Q: Privilege page, tracker, and notifications still indicate that 1,000 reputation is required to see vote counts here, even though it was lowered to 100 Just today, the system was changed so that only 100 reputation is required to view vote counts here on Meta Stack Exchange.
However, the privilege pages here and here still continue to indicate that 1,000 reputation is required to gain the privilege.
As far as I can tell, the privilege tracker in the user profile as well as the privilege notification system also use the same system to show how far a user is from earning a privilege. The former also still likely indicates that the user needs 1,000 reputation: it will show as progress to 1,000, but once the user completes it, it won't affect anything as the user already had the ability. The latter is effectively a meaningless notification.
Can this please be fixed?

A: While we can make changes to what reputation is required for specific privileges, the components of each privilege can't be broken up or edited in a custom/per-site way and we don't have any plans to allow for this. As animuson commented, there are also other internal things attached to this privilege that are not mentioned in the help center and the privilege tracker.
We made the decision to allow everyone with 100 reputation here to see vote splits because those people often have that ability on their primary sites and they benefit from being able to see them here without us requiring them to have actually participated here.
So, our options here are to roll back that change (and force everyone to have 1,000 reputation to see vote splits again) or to leave it as-is and consider this a "secret" perk for people. We do not want the other internal things attached to that privilege to be given out at only 100 reputation, and we feel the value of seeing the vote splits is outweighed by the slight confusion that some might experience at the help center pages and privilege tracker on the user profile being incorrect.

A: Agreed, in my profile it is showing my next privilege is "view vote counts" at 1k reputation even though it is at 100 reputation.
I recommend the following as well, but it might not be accepted well:

*

*Combine the established user achievement with Create gallery chat rooms. So now the title is "Established user", with the description of "Create gallery rooms".

*Remove the View vote counts and put it at the 100 reputation. It should also have the "View vote counts" as the title.


text:
Q: Proof of least squares approximation formulas? I'm trying to study from this pdf: http://math.mit.edu/~gs/linearalgebra/ila0403.pdf
I was just wondering if there were any established proofs for the following formulas:

$\hat{y} = Zw$, where $\hat{y}, w$ are column vectors and $Z$ is a data matrix that is $N * M + 1$

$l(w) = ||Zw - t||^2$, $t$ being a column vector and where $||v||^2 = \sum_{n}{v_{n}^2}$

While searching for answers, I came across this post: Proof of least squares approximation lemma
Would it be fair to say that this proves the second formula? How is the first formula proven?
Edit: Here is a screenshot of the question

A: These two results are actually definitions. Imagine you have a dataset of the form $\{y_i,(x_1,x_2,\cdots,x_M)_i\}_{i=1}^N$. That is, you have $N$ observations $y_i$ of a variable that depends on $M$ independent features ${\bf x}_i = (x_1,x_2\cdots,x_M)_i$. Imagine there exists $M+1$ numbers $(w_0,w_1,w_2,\cdots w_M)$ such that each observation can be explained as the linear combination of the features with these weights, that is
\begin{eqnarray}
y_1 &=& w_0 + w_1 x_{1,1} + \cdots w_Mx_{M,1} +\epsilon_1\\
y_2 &=& w_0 + w_1 x_{1,2} + \cdots w_Mx_{M,2} +\epsilon_2\\
&\vdots& \\
y_N &=& w_0 + w_1 x_{1,N} + \cdots w_Mx_{M,N} +\epsilon_N\\
\end{eqnarray}
which can be represented in matrix form as
$$
\left(\begin{array}{c}
y_1 \\ \vdots \\ y_N
\end{array}\right) = \left(\begin{array}{cccc}
1 & x_{1,1} & \cdots & x_{M,1} \\
1 & x_{1,2} & \cdots & x_{M,2} \\
 &  & \vdots &  \\
1 & x_{1,N} & \cdots & x_{M,N} \\
\end{array}\right)
\left(\begin{array}{c}
w_0 \\ w_1 \\ \vdots \\ w_M
\end{array}\right) +
\left(\begin{array}{c}
\epsilon_1 \\ \vdots \\ \epsilon_N
\end{array}\right)
$$
or equivalently
$$
{\bf y} = {\bf Z}{\bf w} + {\bf \epsilon} = \hat{\bf y} + {\bf \epsilon}
$$
with $\hat{\bf y}={\bf Z}{\bf w}$, with ${\bf W}\in \mathbb{R}^{N\times(M+1)}$, ${\bf y}, {\bf \epsilon}\in \mathbb{R}^N$ and ${\bf w} \in \mathbb{R}^{M+1}$.
As for the second part, the idea is to find find the weights ${\bf w}$ such that the prediction $\hat{\bf y}$ is as close as possible to the real observation ${\bf y}$. That is why you define the distance between these two vectors as
$$
l({\bf w}) = ||{\bf Z}{\bf w} - {\bf y}||^2
$$
and try to minimize it


text:
Q: Where is the ClickOnce "Show Desktop Icon" option? (VS2008 SP1) Apparently in VS2008 SP1 there's an option under Publish | Options to have a desktop shortcut for ClickOnce, but I've got VS2008 with SP1 and there's no such option!
My Publish Options page
Any ideas? Thx!

A: Are you certain you're running VS2008? My "Publish Options" dialog looks nothing like that. It's a tabbed affair nowadays with a "Manifests" tab (which is where you'll find the "Create desktop shortcut" checkbox).


text:
Q: Joining two tables based on their dates without primary keys(SQL Server 2014) I am lost here
I have two tables
This is the Period Table

And the Days Table

Days table counts the days of an employee when he went on a vacation
Period table is a temporary table created from a lot of if else statements
What I want to do is to join Days table with the Period table grouped by their years (and possibly use aggregate functions)
----EDIT----
Here is the query for Days Table
Select COUNT(isMandatory) + COUNT(isVacation) as 'Mandatory/Sick', COUNT(isSick) as Sick,
YEAR (date) as 'Year' from datesInclusiveTable where leaveID in
(select leaveID from leaveTable where acctNo = 'M29076')
Group by YEAR (date)

You see it has aggregate functions
I would like to post the query for Period Table but it's too long and might be
too complicated to look at

A: If DateStarted (or DateEnded) are of data type date:
SELECT * FROM Days D
INNER JOIN Period P ON YEAR(P.DateStarted) = D.Year

A: Try this:
SELECT * FROM Days D
JOIN Period P ON YEAR(CONVERT(date, P.DateStarted)) = D.Year;