What is the difference of "__and__" and "__rand__" in class set?

Question: I read the book "Fluent Python" by Luciano Ramalho. In the description of class set, he writes:
s & z   # s.__and__(z)   - intersection of s and z
z & s   # s.__rand__(z)   - inversion operator &

I can't understand. Why in the second case he doesn't write: z.__and__(s). The author said: "intersection of s and z" != "inversion operator &".
Is __and__ and __rand__ equal for set() or not?
Comment: If `z` does not have a `__and__` method or it returns `NotImplemented`, then and only then is `s.__rand__(z)` called (except it might not be called at all in this case, what with `set` being an internal type written in C).
Comment: Assuming the author is specifically trying to explain about methods of `s`, not of `z`, the second example uses `s.__rand__` because `s` is on the **r**ight of the `&` operator.
Answer:
I can't understand. Why in the second case he doesn't write:
  z.__rand__(s).

Because that's the very point of the reverse operators. They as well exist in the form of __radd__, __rsub__ and so on.
If, when doing a & b, calling a.__and__(b) does not exist or returns NotImplemented, it tries (as a "last resort") to call b.__rand__(a).
See the relevant part of Python's documentation for details.
In your example, probably the class of z doesn't implement __and__, so it falls back to s which supplies __rand__.


fatal error: openssl/err.h: No such file or directory - Python

Question: I try to install M2Crypto, but I can't install it, the error I have is the following:
I am in a virtual miniconda environment.
building 'M2Crypto._m2crypto' extension
gcc -pthread -B /home/lcteen/miniconda3/envs/django/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/lcteen/miniconda3/envs/django/include/python3.7m -I/home/lcteen/Downloads/M2Crypto-0.35.2/SWIG -c SWIG/_m2crypto_wrap.c -o build/temp.linux-x86_64-3.7/SWIG/_m2crypto_wrap.o -DTHREADING -Wno-deprecated-declarations
SWIG/_m2crypto_wrap.c:3561:10: fatal error: openssl/err.h: No such file or directory
 3561 | #include <openssl/err.h>
      |          ^~~~~~~~~~~~~~~
compilation terminated.
error: command 'gcc' failed with exit status 1

I am installing it with the following command: python setup.py install

When installing it by pip, the error is as follows:
Collecting M2Crypto
  Using cached https://files.pythonhosted.org/packages/74/18/3beedd4ac48b52d1a4d12f2a8c5cf0ae342ce974859fba838cbbc1580249/M2Crypto-0.35.2.tar.gz
Building wheels for collected packages: M2Crypto
  Building wheel for M2Crypto (setup.py) ... error
  ERROR: Command errored out with exit status 1:
   command: /home/lcteen/miniconda3/envs/django/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-q5bgx0sr/M2Crypto/setup.py'"'"'; __file__='"'"'/tmp/pip-install-q5bgx0sr/M2Crypto/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-kjvnl1i1 --python-tag cp37
       cwd: /tmp/pip-install-q5bgx0sr/M2Crypto/
  Complete output (52 lines):
  running bdist_wheel
  running build
  running build_py
  copying M2Crypto/Engine.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/RC4.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/BIO.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/m2.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/m2urllib2.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/BN.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/util.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/Err.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/EC.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/DSA.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/EVP.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/m2urllib.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/httpslib.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/callback.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/m2xmlrpclib.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/RSA.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/threading.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/__init__.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/m2crypto.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/X509.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/ftpslib.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/Rand.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/AuthCookie.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/ASN1.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/SMIME.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/six.py -> build/lib.linux-x86_64-3.7/M2Crypto
  copying M2Crypto/DH.py -> build/lib.linux-x86_64-3.7/M2Crypto
  creating build/lib.linux-x86_64-3.7/M2Crypto/SSL
  copying M2Crypto/SSL/Cipher.py -> build/lib.linux-x86_64-3.7/M2Crypto/SSL
  copying M2Crypto/SSL/ssl_dispatcher.py -> build/lib.linux-x86_64-3.7/M2Crypto/SSL
  copying M2Crypto/SSL/timeout.py -> build/lib.linux-x86_64-3.7/M2Crypto/SSL
  copying M2Crypto/SSL/SSLServer.py -> build/lib.linux-x86_64-3.7/M2Crypto/SSL
  copying M2Crypto/SSL/cb.py -> build/lib.linux-x86_64-3.7/M2Crypto/SSL
  copying M2Crypto/SSL/Context.py -> build/lib.linux-x86_64-3.7/M2Crypto/SSL
  copying M2Crypto/SSL/Checker.py -> build/lib.linux-x86_64-3.7/M2Crypto/SSL
  copying M2Crypto/SSL/TwistedProtocolWrapper.py -> build/lib.linux-x86_64-3.7/M2Crypto/SSL
  copying M2Crypto/SSL/__init__.py -> build/lib.linux-x86_64-3.7/M2Crypto/SSL
  copying M2Crypto/SSL/Session.py -> build/lib.linux-x86_64-3.7/M2Crypto/SSL
  copying M2Crypto/SSL/Connection.py -> build/lib.linux-x86_64-3.7/M2Crypto/SSL
  running build_ext
  building 'M2Crypto._m2crypto' extension
  creating build/temp.linux-x86_64-3.7
  creating build/temp.linux-x86_64-3.7/SWIG
  gcc -pthread -B /home/lcteen/miniconda3/envs/django/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/lcteen/miniconda3/envs/django/include/python3.7m -I/tmp/pip-install-q5bgx0sr/M2Crypto/SWIG -c SWIG/_m2crypto_wrap.c -o build/temp.linux-x86_64-3.7/SWIG/_m2crypto_wrap.o -Wno-deprecated-declarations -DTHREADING
  SWIG/_m2crypto_wrap.c:3561:10: fatal error: openssl/err.h: No such file or directory
   3561 | #include <openssl/err.h>
        |          ^~~~~~~~~~~~~~~
  compilation terminated.
  error: command 'gcc' failed with exit status 1
  ----------------------------------------
  ERROR: Failed building wheel for M2Crypto
  Running setup.py clean for M2Crypto
Failed to build M2Crypto
Installing collected packages: M2Crypto
    Running setup.py install for M2Crypto ... error
    ERROR: Command errored out with exit status 1:
     command: /home/lcteen/miniconda3/envs/django/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-q5bgx0sr/M2Crypto/setup.py'"'"'; __file__='"'"'/tmp/pip-install-q5bgx0sr/M2Crypto/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-8ojxmrjt/install-record.txt --single-version-externally-managed --compile
         cwd: /tmp/pip-install-q5bgx0sr/M2Crypto/
    Complete output (55 lines):
    running install
    running build
    running build_py
    creating build
    creating build/lib.linux-x86_64-3.7
    creating build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/Engine.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/RC4.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/BIO.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/m2.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/m2urllib2.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/BN.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/util.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/Err.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/EC.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/DSA.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/EVP.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/m2urllib.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/httpslib.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/callback.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/m2xmlrpclib.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/RSA.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/threading.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/__init__.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/m2crypto.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/X509.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/ftpslib.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/Rand.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/AuthCookie.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/ASN1.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/SMIME.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/six.py -> build/lib.linux-x86_64-3.7/M2Crypto
    copying M2Crypto/DH.py -> build/lib.linux-x86_64-3.7/M2Crypto
    creating build/lib.linux-x86_64-3.7/M2Crypto/SSL
    copying M2Crypto/SSL/Cipher.py -> build/lib.linux-x86_64-3.7/M2Crypto/SSL
    copying M2Crypto/SSL/ssl_dispatcher.py -> build/lib.linux-x86_64-3.7/M2Crypto/SSL
    copying M2Crypto/SSL/timeout.py -> build/lib.linux-x86_64-3.7/M2Crypto/SSL
    copying M2Crypto/SSL/SSLServer.py -> build/lib.linux-x86_64-3.7/M2Crypto/SSL
    copying M2Crypto/SSL/cb.py -> build/lib.linux-x86_64-3.7/M2Crypto/SSL
    copying M2Crypto/SSL/Context.py -> build/lib.linux-x86_64-3.7/M2Crypto/SSL
    copying M2Crypto/SSL/Checker.py -> build/lib.linux-x86_64-3.7/M2Crypto/SSL
    copying M2Crypto/SSL/TwistedProtocolWrapper.py -> build/lib.linux-x86_64-3.7/M2Crypto/SSL
    copying M2Crypto/SSL/__init__.py -> build/lib.linux-x86_64-3.7/M2Crypto/SSL
    copying M2Crypto/SSL/Session.py -> build/lib.linux-x86_64-3.7/M2Crypto/SSL
    copying M2Crypto/SSL/Connection.py -> build/lib.linux-x86_64-3.7/M2Crypto/SSL
    running build_ext
    building 'M2Crypto._m2crypto' extension
    creating build/temp.linux-x86_64-3.7
    creating build/temp.linux-x86_64-3.7/SWIG
    gcc -pthread -B /home/lcteen/miniconda3/envs/django/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/lcteen/miniconda3/envs/django/include/python3.7m -I/tmp/pip-install-q5bgx0sr/M2Crypto/SWIG -c SWIG/_m2crypto_wrap.c -o build/temp.linux-x86_64-3.7/SWIG/_m2crypto_wrap.o -Wno-deprecated-declarations -DTHREADING
    SWIG/_m2crypto_wrap.c:3561:10: fatal error: openssl/err.h: No such file or directory
     3561 | #include <openssl/err.h>
          |          ^~~~~~~~~~~~~~~
    compilation terminated.
    error: command 'gcc' failed with exit status 1
    ----------------------------------------
ERROR: Command errored out with exit status 1: /home/lcteen/miniconda3/envs/django/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-q5bgx0sr/M2Crypto/setup.py'"'"'; __file__='"'"'/tmp/pip-install-q5bgx0sr/M2Crypto/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-8ojxmrjt/install-record.txt --single-version-externally-managed --compile Check the logs for full command output.

I am using python 3.7
I already executed the following command and still can't install it:
sudo apt-get install python3-dev

Any solution?

UPDATE:
Investigate the error and I saw that the following command could solve it:
sudo apt-get install libssl-dev

I ran it and I still can't install it, but the error is different. Error:
SWIG/_m2crypto_wrap.c:31130:5: note: (near initialization for 'SwigPyBuiltin___cbd_t_type.as_mapping')
    SWIG/_m2crypto_wrap.c:31134:5: warning: excess elements in struct initializer
    31134 |     (objobjproc) 0,                           /* sq_contains */
          |     ^
    SWIG/_m2crypto_wrap.c:31134:5: note: (near initialization for 'SwigPyBuiltin___cbd_t_type.as_mapping')
    SWIG/_m2crypto_wrap.c:31135:5: warning: excess elements in struct initializer
    31135 |     (binaryfunc) 0,                           /* sq_inplace_concat */
          |     ^
    SWIG/_m2crypto_wrap.c:31135:5: note: (near initialization for 'SwigPyBuiltin___cbd_t_type.as_mapping')
    SWIG/_m2crypto_wrap.c:31136:5: warning: excess elements in struct initializer
    31136 |     (ssizeargfunc) 0,                         /* sq_inplace_repeat */
          |     ^
    SWIG/_m2crypto_wrap.c:31136:5: note: (near initialization for 'SwigPyBuiltin___cbd_t_type.as_mapping')
    SWIG/_m2crypto_wrap.c:31146:5: warning: initialization of 'Py_ssize_t (*)(PyObject *)' {aka 'long int (*)(struct _object *)'} from incompatible pointer type 'int (*)(PyObject *, Py_buffer *, int)' {aka 'int (*)(struct _object *, struct bufferinfo *, int)'} [-Wincompatible-pointer-types]
    31146 |     (getbufferproc) 0,                        /* bf_getbuffer */
          |     ^
    SWIG/_m2crypto_wrap.c:31146:5: note: (near initialization for 'SwigPyBuiltin___cbd_t_type.as_sequence.sq_length')
    SWIG/_m2crypto_wrap.c:31147:5: warning: initialization of 'PyObject * (*)(PyObject *, PyObject *)' {aka 'struct _object * (*)(struct _object *, struct _object *)'} from incompatible pointer type 'void (*)(PyObject *, Py_buffer *)' {aka 'void (*)(struct _object *, struct bufferinfo *)'} [-Wincompatible-pointer-types]
    31147 |     (releasebufferproc) 0,                    /* bf_releasebuffer */
          |     ^
    SWIG/_m2crypto_wrap.c:31147:5: note: (near initialization for 'SwigPyBuiltin___cbd_t_type.as_sequence.sq_concat')
    SWIG/_m2crypto_wrap.c:31150:5: warning: initialization of 'int (*)(PyObject *, Py_buffer *, int)' {aka 'int (*)(struct _object *, struct bufferinfo *, int)'} from incompatible pointer type 'PyObject *' {aka 'struct _object *'} [-Wincompatible-pointer-types]
    31150 |     (PyObject*) 0,                            /* ht_name */
          |     ^
    SWIG/_m2crypto_wrap.c:31150:5: note: (near initialization for 'SwigPyBuiltin___cbd_t_type.as_buffer.bf_getbuffer')
    SWIG/_m2crypto_wrap.c:31151:5: warning: initialization of 'void (*)(PyObject *, Py_buffer *)' {aka 'void (*)(struct _object *, struct bufferinfo *)'} from incompatible pointer type 'PyObject *' {aka 'struct _object *'} [-Wincompatible-pointer-types]
    31151 |     (PyObject*) 0,                            /* ht_slots */
          |     ^
    SWIG/_m2crypto_wrap.c:31151:5: note: (near initialization for 'SwigPyBuiltin___cbd_t_type.as_buffer.bf_releasebuffer')
    SWIG/_m2crypto_wrap.c:30993:54: warning: missing braces around initializer [-Wmissing-braces]
    30993 | static PyHeapTypeObject SwigPyBuiltin___cbd_t_type = {
          |                                                      ^
    ......
    31150 |     (PyObject*) 0,                            /* ht_name */
          |     {
    31151 |     (PyObject*) 0,                            /* ht_slots */
    31152 | };
          | }
    error: command 'gcc' failed with exit status 1
    ----------------------------------------
ERROR: Command errored out with exit status 1: /home/lcteen/miniconda3/envs/django/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-o4e0dlzd/M2Crypto/setup.py'"'"'; __file__='"'"'/tmp/pip-install-o4e0dlzd/M2Crypto/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-lntmgt5e/install-record.txt --single-version-externally-managed --compile Check the logs for full command output.

(I did not put all the error since it is very long)
Comment: Read ``INSTALL.rst``, you need to install development files for OpenSSL (among others).
Comment: install the following: openssl, libssl, python-dev, libssl-dev, etc.
and it didn't work, I get the same error.
Comment: What version of ``swig``?
Comment: What is `swig`?
Comment: Program which is absolutely necessary for building M2Crypto. Did you read that ``INSTALL.rst`` or do you try to make to rewrite it here in comments?
Comment: I needed `M2Crypto` to be able to work with the `PayPalEncryptedPaymentsForm`, from `django-paypal`, just for that, I just needed to install it since `django-paypal` takes care of the rest.
Comment: Then why in the world you just don't install it with ``apt-get install python-m2crypto`` (or ``python3-m2crypto``)? https://packages.ubuntu.com/search?keywords=m2crypto
Comment: yes but I am in a virtual environment..
Comment: ``--system-site-packages`` ? Or you just have to reread that ``INSTALL.rst``:
```
For example on a Debian-based system the following packages are needed:
…
swig 2.0.4 or newer
```
Comment: `sudo apt-get install libssl-dev` did it for me
Answer: The solution to the problem was to run the following command:
conda install -c conda-forge m2crypto


Getting URL alias of a term

Question: I am writing a module, and am confused about the term's URLs. because, if pathauto moduel is installed, then the alias of that module should be provided. How to achieve this?
Default drupal's URL: taxonomy/term/30
Pathauto's probable pattern:
category/30
category/[title]
category/[title]/[id]
...and millions of other possible patte

Using drupal_get_path_alias() returns drupal's default path.
How should I get the path used by pathauto? I have seen pathauto's module,
but it does not provide an API for this purpose as it seems.
Answer: Just use the url() function. It will return aliased path if you have pathauto installed.
Example:
$link = url('taxonomy/term/1');

Comment: drupal_get_path_alias('taxonomy/term/[id]') will also work.
Answer: You can either use url() or drupal_get_path_alias() but make sure that your path argument doesn't have leading slash.
Example:
drupal_get_path_alias('/taxonomy/term/1');
url('/taxonomy/term/1');

Returns path '/taxonomy/term/1'
drupal_get_path_alias('taxonomy/term/1');

Returns 'tags/some-tag'
url('taxonomy/term/1');

Returns '/tags/some-tag'
Comment: Useful knowing about the leading slash! Thank you!

Getting URL alias of a term


running several background threads in succession on iphone / ipad

Question: I have to download a ton of images and I am doing it on a background thread, problem is all of the downloaded data is not released until I go back to the main thread which is fine a for couple hundred images but when I get into thousands the app runs out of memory and crashes.
So I need to run several background threads in succession so I can batch the download of the images in groups of say 200 so my autorelease pools can clear and memory gets released.
I cannot wrap my head around how to do this. I need some sort of recursive function on the main thread to call the background threads with and keep track of the batches so it knows which to call next. I know that passing values back and forth between threads will cause me some problems so I am not sure how to approach this?
Anyone tackle a problem like this before?
Comment: Something that may help is to create your own autorelease pool in the thread and then release whenever you get to a certain limit.  This way, you have some control over how much is being processed.
Answer: NSOperationQueues solve this problem for you.  You create a class that descends from NSOperation that does the download for you.  You then create an NSOperationQueue and add the downloads to the queue. You can control the max concurrency of the queue, etc.
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSOperationQueue_class/index.html
Comment: I used hotpaw2's answer with great success but I think I need to re-think it using NSOperationQueue
Answer: You don't need to wait for everything to download before releasing memory.  You could just pass each image or small batch of images to the main thread using performSelectorOnMainThread, and let the main thread release memory as it caches the data in storage or uses the data.  Then continue on in the background thread until done and pass a "done" message, again using performSelectorOnMainThread.
Comment: how do you pass arguments in the @selector for going to the main thread?  Can you do that?
Comment: Yes, you can do that using withObject:
Answer: Use NSInvocationOperation. tht wuld fix the issue instead of splitting the code in chunks. here is the sample i used
<code>NSOperationQueue *downloadQueue = [NSOperationQueue new]; for (Product *cProduct in productsMasterArray) {
NSInvocationOperation *downloadOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(downloadImages:) object:cProduct.ITEM_CODE]; [downloadQueue addOperation:downloadOperation]; [downloadOperation release]; }
</code>


Determining HTML element visibility server side

Question: If a HTML element such as an input box is hidden under a CSS visibility e.g. Display:None.  Can I determine server-side whether this element is hidden of not.  And if so, how?
Comment: for some reason I am thinking this could be used to counter the spam bot checks using css hidden inputs? Hmmm...  is that the intent?
Comment: No, the intent is as follows.  Given a form with a repeating group of information, e.g. An address.  I control the visibility of the repeating group with another control (e.g a yes/no radio button). If the repeating group is visible I want to be able to determine this to determine whether or not to persist any data entered. If the user hides the repeating group. I want to ignore any data entered.  I dont want to inspect the radio button  status as I dont have any knowledge of the relationship between the radio button and repeating group server side (rules are all emitted in JSON/Jquery)...
Answer: The short answer is "no, you cannot".
The long answer is: if you are absolutely sure that this element visibility can only be altered via CSS you could parse all applicable CSS files. It's rather hard but possible.
However, in real life you also need to know the exact browser version (due to possible CSS hacks and thus difference in behavior) plus quite often element visibility is toggled via javascript.
Update (based on OP's clarification):
I would strongly suggest using a hidden field (<input type="hidden">) in order to determine visibility as you've described. Hidden field value can be changed via javascript as radio group value changes.
Comment: Coincidentally, mooted this with a few other peeps. Without going into too much detail this is probably the only way I can achieve what I am looking for WITHOUT caring about the relationship between the radio button and repeating group server side (would require a tweak to the framework I am currently working with). Thanks for your time..


how to custom sort in spark SQL?

Question: for a column like
col
a
b
c

how do I get the output
col
c
a
b

is there an equivalent of order by field() in sqark sql?
Comment: `select col from table order by col desc`?
Comment: @mck "custom" order
Comment: Oh sorry, I thought I saw col, c, b, a...
Answer: There is no logic behind your sort order from my perspective. If you have one then you need to write a function where you can provide an "order mechanism". For example create an ordered list of all your possible values and then map this list to a key value. c=1, a=2, b=3. Then add a column with the key values to the Dataframe and order on the new column.

how to custom sort in spark SQL?


Java / Android - Calculate difference between timestamps

Question: I have a problem figuring out how to calculate the elapsed time between two timestamps (hours, minutes, seconds). This is the result:
String starttime = beginElement.getTimestamp();
String endtime = element.getTimestamp();

I/Start time: 1496258892612
I/End time: 1496258928999
long diffTime = Long.parseLong(endtime) - Long.parseLong(starttime);

I/Diff time: 36387
String elapsedtime = new SimpleDateFormat("hh:mm:ss").format(Long.parseLong(String.valueOf(diffTime)));

I/Elapsed time: 01:00:36
In fact, the elapsed time is just 36 seconds. It's always one hour less than the result.
How do I fix this strange issue?
Comment: Read https://stackoverflow.com/questions/21285161/android-difference-between-two-dates
Answer: you are using the API incorrectly, parse is not what you need since that time is not related to a date but to a duration period instead....
do something like:
String periodAsHH_MM_SS = String.format("%02d:%02d:%02d",
        TimeUnit.MILLISECONDS.toHours(diffTime),
        TimeUnit.MILLISECONDS.toMinutes(diffTime) % TimeUnit.HOURS.toMinutes(1),
        TimeUnit.MILLISECONDS.toSeconds(diffTime) % TimeUnit.MINUTES.toSeconds(1));

System.out.println("Duration in hh:mm:ss is: "+periodAsHH_MM_SS);

Comment: Thank you! This did the trick.
Comment: You are welcome
Answer: You need to set GMT timezone, try this:
    SimpleDateFormat sd = new SimpleDateFormat("HH:mm:ss");
    sd.setTimeZone(TimeZone.getTimeZone("GMT"));
    String elapsedtime = sd.format(diff);


Typescript Chain Async Call

Question: I need to:
localStorage.setItem('user', user);
router.navigate(['/profile']);
The problem is that navigation may occur before storage is set.
Please tell me I don't need to route parameters, create asynchronous classes, callbacks, promisses, or timers for this to work.
Comment: localStorage is synchronous...
Comment: Could you provide a self-contained [mre] that demonstrates your issue when pasted into a standalone IDE?  Right now my IDE doesn't know what `user` and `router` are, nor does it seem possible that anything `router.navigate()` does can take effect before `localStorage.setItem()` does, so it would be nice to see that in action.  Without more info it's hard to advise.  Good luck!
Answer: You may set localstorage value in useEffect hook like this:
<code> React.useEffect(()=>{
   setStorage()
   router.navigate(['/profile'])
 },[])

 const setStorage = ()=>{
    localStorage.setItem("user", user)
 }
</code>
It'll set the value in localstorage before router.naviagte
Comment: Not quite. You need an external package and parameter exchange for the lack of a .then() -- JS was always asynchrounlously causing trouble. There has to be a better way in Typescript or, back to JS!
Comment: @AleksanderSpacca TypeScript is primarily just a static type system on top of JavaScript, and this gets erased on transpilation and therefore has no runtime effect; if you don't like how something works in JavaScript, you probably won't like how it works in TypeScript either.
Comment: Yeah, jcalz! I know how it works. I want to follow Angular's choices because to them everything is a component. People hate when I put MaintenancePlans() and PartsTTL() in a car.cs but love car.parts.sparks.ttl without 20 injectable classes that never sees a user, cart, or anything else. parts.spark.ttl is just expected! So I want to stick to Typescript's not thinking like JS. There has got to be a way to wait for a result before proceeding. http.get has it. I need what it uses to port a mess. Or anything.. I'm now trying to check storage before redirect.
Comment: I will wait a couple of days to see if anyone can help any further. I will not forget to mark you kuuhak-u because it helps who can use react!
Answer: Best way I found (using callback):
<code>this.save(user, response => {
  router.navigate(['/profile']);
})

save(user, callback: (error: any) => void ){
  localStorage.setItem("user", user);
  callback('done');
}
</code>

Typescript Chain Async Call


App Script for saving a sheet as PDF to a specific folder

Question: I am looking for an app script that lets me save a sheet as PDF from my Google Workbook to a specific folder in Google Drive based on a condition.
In my Google Drive I have a Google Sheet Workbook file and an employee folder.
The employee folder Id is 1Jy2Yr7u0qrgy90Gvtb6p8V27baS7T_eP
My google workbook has a sheet called 'Sheet2' whose Id is 1DmDBmEijUkolVp7aVgGNK4cTRu5y4uLdzbCrDYO5XRA.
This sheet has a cell C3 that has an employee name. The value in this cell needs to be checked, i.e. if the employee name matches then the script should convert the sheet to a PDF format and place the PDF in employee folder.
I am not a programmer or a coder but doing my best to get this working. I went through many scripts that I found here in stackoverflow and in Youtube and came up with this. I am not sure if it is correct. Need some expert help. Hoping someone can help.

function checkSheet() {
var sheetName = "1DmDBmEijUkolVp7aVgGNK4cTRu5y4uLdzbCrDYO5XRA";
var folderID = "1Jy2Yr7u0qrgy90Gvtb6p8V27baS7T_eP";

var sourceSpreadsheet = SpreadsheetApp.getActive();
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
var folder = DriveApp.getFolderById(folderID);

var checkForNews = spreadsheetApp.getActiveSpreadsheet().getSheetByName("Tracking").getRange("c6").getValue();
if (checkForNews='Yes') {
var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(sourceSpreadsheet.getId()).makeCopy("tmp_convert_to_pdf", folder));
var theBlob = destSpreadsheet.getBlob().getAs('application/pdf').setName(pdfName);
var newFile = folder.createFile(theBlob);
}
}

Here are the resource that I found,
Using Google Apps Script to save a single sheet from a spreadsheet as pdf in a specific folder
How to check for cell value?
How can I modify this to save a spreadsheet into a new folder
As mentioned above I came up with that script which I think is not right. Please help.
Comment: I have to apologize for my poor English skill. Unfortunately, I cannot understand `if the employee name matches then the script should convert the sheet to a PDF format and place the PDF in employee folder.`. Can I ask you about the detail of your expected result?
Answer: Try it this way:
function checkSheet() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Tracking");
  var fldr = DriveApp.getFolderById("folder id");
  if(sh.getRange("C6").getValue() == "Yes") {
    var theBlob = ss.getBlob().getAs('application/pdf').setName("mypdf");
    fldr.createFile(theBlob);
  }
}

Comment: Thank you so much Cooper. This did the trick. However, it is saving the entire workbook as a PDF file and not that specific sheet. Also, if I want to give the PDF file a specific name how do I do that? For example, the PDF name format should be 'Employee Name_Case#' (where Employee Name is the value in cell C6 and Case# is the value in cell D6)
Comment: I got the file renaming to work. I used the Concatenate formula to join the values in the two cells and then used the following in the script, var fileName = ss.getSheetByName("Sheet2").getRange("G1").getValue(); and changed .setName("mypdf") to .setName(fileName). I am still stuck with first issue where the entire workbook is getting saved and not that specific sheet.
Comment: The new file is stored in fldr and you provide the folder id


Show $\pi_1(SU(2)/H_8)$

Question: Say $H_8$ is a quaternion group of order 8,
How should one think of the space $SU(2)/H_8$ even if $H_8$ is not a normal subgroup?
How do we show
$$\pi_1(SU(2)/H_8)=H_8?$$
Comment: $H_8$ doesn't need to be normal to define $SU(2)/H_8$: it's simply the set of left cosets of $H_8$. Normality is only required to define an appropriate group structure.
Comment: $SU(2)$ is a lie group, hence a manifold (or is a manifold, hence a Lie group, depends your perspective :) ).The action of quaternions produces an orbit space hence with induced topology by the natural projection you have a new topological space. So naturally you come up with the question of the fundamental group. If I recall correctly, in Hatcher's book you may find something useful about it (or something similar anyway).
Answer: If a discrete group $G$ acts properly discontinuously on a path-connected space $X$, then the projection
$$p:X\to X/G$$
is a covering map. For a reference, check Switzer's algebric topology text page 62, or in Hatcher, page 72. From here, applying the long exact sequence of a fibration to the covering map $p$ gives:
$$\cdots\xrightarrow{\ \ \ }\pi_1(G)\xrightarrow{\ \ \ }\pi_1(X)\xrightarrow{\ \ \ }\pi_1(X/G)\xrightarrow{\ \ \ }\pi_0(G)\xrightarrow{\ \ \ }\pi_0(X)\xrightarrow{\ \ \ }\cdots$$
which gives us the short exact sequence:
$$0\xrightarrow{\ \ \ }\pi_1(X)\xrightarrow{\ p_* \ }\pi_1(X/G)\xrightarrow{\ \ \partial }\pi_0(G)\cong G\xrightarrow{\ \ \ }0,$$
since $\pi_1(G)=0$ and $\pi_0(X)=0$. One can show that $\partial$ is a homomorphism in this case, and therefore by the first isomorphism theorem,
$$G\cong \frac{\pi_1(X/G)}{p_*(\pi_1(X))}.$$
In your case, we have:
$$H_8\cong\frac{\pi_1(SU(2)/H_8)}{p_*(\pi_1(SU(2)))}.$$
As explained by Max in this answer, $SU(2)\cong S^3$, so $\pi_1(SU(2))\cong \pi_1(S^3)$ which is trivial, and therefore
$$H_8\cong \pi_1(SU(2)/H_8).$$
Comment: @annieheart Happy to help, and no problem at all.
Comment: One thing I guess I should mention, thinking of $SU(2)$ as $S^3$, the group $H_8$ acts on $S^3$ by 90-degree rotations, so at least intuitively, this action should be properly discontinuous.
Comment: thanks I ask another new basic question you may know.

Show $\pi_1(SU(2)/H_8)$


Upgrading Python 2.X on CentOS or RHEL

Question: I hate to play the annoying dull person who doesn't have a clue what he is talking about. But, unfortunately, that's me as far as linux is concerned...
I'm doing some file manipulations in python that use the zipfile module.  The version of python currently installed is 2.4.3, but the zipfile module utilizes 'with' statements, which I think came out in version 2.5 (I'm also going to need to use the tarfile module; although I haven't tested it, I imagine I'll run into the same problem).
My current plan of action is to figure out how to upgrade the python installation.  But, knowing absolutely nothing about linux and very little about python, I don't even know where to start.  I look at some similar posts, which mentioned installing it in another directory.  I didn't install it in the first place though.  I don't even know how to install stuff in linux...
Any help would be greatly appreciated!  Also, if there's a better way than trying to update python, I'm totally open to suggestions. Just remember: my linux intelligence is about equivalent to that of a four-year-old. Thanks!
Comment: I am not sure this is the right place for this question, but in any case, your question should probably include what Linux distribution/version you are using. Most distributions these days will provide a GUI to upgrade your software without the need for command line commands .. (that sounds redundant :)
Comment: `zipfile`, `tarfile` are in stdlib. So the version that comes with Python 2.4 must work as is i.e., it doesn't use `with` statement. If you need a newer version of Python for some other reason then you could use your distribution packages to install it (as an addition, not a replacement) e.g., `sudo apt-get install python3.2`. Don't touch your default Python installation it might break things.
Answer: THE EASY WAY:
just work with zip commands directly, instead of using the old zip module:
import subprocess
subprocess.call('unzip <path to your file>')

or alternatively, use subprocess.Popen.
And After submitting my answer, I would like to title this part:
THE HARD WAY:
Guessing from the Python version you are using a Red Hat 5 or CentOS 5.
Here is how it is looking on my Red Hat 5.8 at work:
oz@server ~ $ /usr/bin/python
Python 2.4.3 (#1, Dec 22 2011, 12:12:01)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('/etc/redhat-release')
>>> f.readlines()
['Red Hat Enterprise Linux Server release 5.8 (Tikanga)\n']

Most other Ubuntu version and Debian have newer Python version.
Anyway, upgrading Python should work like this:

First you need to know the admin password (root in Linux world).
type 'su' to change to root - WATCH OUT HERE, this is a dangerous situations. Being ROOT is dangerous.
type:

yum groupinstall "development tools" -y
yum install readline-devel openssl-devel gmp-devel ncurses-devel gdbm-devel \
glib-devel expat-devel libGL-devel tk tix gcc-c++ \
libX11-devel glibc-devel bzip2 tar tcl-devel tk-devel pkgconfig \
tix-devel bzip2-devel sqlite-devel autoconf db4-devel libffi-devel \
valgrind-devel -y
mkdir tmp
cd tmp
wget http://python.org/ftp/python/2.7.5/Python-2.7.5.tgz
tar xvfz Python-2.7.5.tgz
cd Python-2.7.5

THIS is important otherwise you will erase your system PYTHON !!! you don't want to do that is, because many system components depend on Python.
./configure --prefix=/opt/python2.7 --enable-shared

Noe, compile the software itself:
make

Then install it:
make altinstall

Don't miss the --prefix=/opt
./configure --prefix=/opt/python2.7
Finally, you need to set your PATH variable to include the python where Python was installed.
export PATH=$PATH:/opt/python2.7/bin/

To make that permanent, edit your .bashrc, and add the above line!
Good luck and welcome to Linux :-)
Answer: The easiest way to upgrade Python on Linux is to have someone else do it for you; your distribution often has many people who package upgrades specifically for that distribution.  Before you roll up your sleeves and get into it, see if they have already done the work.
Basically, this means learning what type of package manager your distribution uses, and then seeing if the next release is available.  Weaknesses to this technique exist:

Your distribution release might be old and updates are no longer available.
Your distribution might value stability over cutting-edge, and has not yet decided the next release is stable enough (or adequately tested).
Your distribution might not have packaged the needed modules, so you must install them yourself.

For my distribution, rpm is the package manager, and yum is the command line front-end.  To check if an update exists for a package with yum, I type
yum check-updates <package name>

and to update something I type
yum update <package name>

Whatever your outcome is with respect to your Python module, you should learn a bit about your package manager and how to use it to avoid the rush of needing to learn it at a critical juncture.
In the event that you do not find the right version packaged for you, sometimes a search on Google will yield a person who packaged the right version for your distribution, even though your distribution hasn't done so yet.  If so, and if you trust the other person to not be doing something malicious, then you can typically install their package.
If no prepackaged version exists, then you are stuck and need to read the "how to install" pages of the particular item, and for Python, it closely reflects Maxime's "the hard way", which might sound intimidating, but after you do it a few times, you realize it isn't really that hard.
Keep in mind that software installed outside of the package manager's knowledge probably will never be known to the package manager, so future use of the package manager with respect to that software will probably need to be handled specially, to prevent the package manager from doing something that makes sense if your version of Python isn't installed.
Answer: Not sure why there's so much resistance to just building Python from source, because it's really quite simple:
$ tar jxf Python-2.7.3.tar.bz2   # unpack the source tarball
$ cd Python-2.7.3                # cd into the source directory
$ ./configure --prefix=$HOME     # configure for your system
$ make                           # build everything
$ make install                   # install (in $HOME/bin, $HOME/share, etc )

If you are nervous about doing the install step, first do make DESTDIR=/tmp/foo install and install everything in /tmp/foo.  Inspect that directory tree, then rm -rf /tmp/foo  (Unless you had important files in /tmp/foo before you started the procedure, of course!)
If you get errors, then there will be some work to do, but chances are very good that the build will work without errors.
Once you've done this, you should be able to run $HOME/bin/python

Upgrading Python 2.X on CentOS or RHEL


Unable to delete thousands of files within a folder in terminal

Question: I'm trying to delete files inside a certain folder but it's throwing an error:
rm -rf /usr/html/sched/downloads/*

-bash: /bin/rm: Argument list too long

I searched online and found this solution but I'm afraid to try it being a production server and I don't know how to put the path correctly:
find . -name '*' | xargs rm -v

How can I delete thousands of files within the /downloads director? FYI, there's no sub-directory.
Comment: Does this answer your question? [Argument list too long error for rm, cp, mv commands](https://stackoverflow.com/questions/11289551/argument-list-too-long-error-for-rm-cp-mv-commands)
Comment: Will this command work? `find . -name "/usr/html/sched/downloads/*" -delete`
Comment: You would probably rather do `find /usr/html/sched/downloads -type f -delete`; you can replace `-delete` with `-print` first so see if the files are the right ones. Notice that `-delete` is a) a GNU find extension and b) can only delete files, not directories.
Comment: Could you post this as an answer? I got it working. Thank you :)
Comment: It's an exact duplicate of what I posted, can you accept the duplicate instead?
Answer: I think here you can check how you can handle it because for a large scale of files you will need to do it by a specific quantity by milliseconds.
find ./cache -mtime +0.5 -print0 | xargs -0 rm -f

Faster way to delete a large number of files [duplicate]
Comment: Will this work: `find rm -rf /usr/html/sched/downloads/* -mtime +0.5 -print0 | xargs -0 rm -f`
Comment: Link only answers are not allowed on SO. [answer] Either form your own answer or delete this altogether.


Why are there positive and negative values of $\omega$ for which resonance occurs?

Question: The question I'm having trouble with is 'determine the value(s) $\omega$ for which resonance occurs for the differential equation $q''+20q=100\sin(\omega t)$'.
So I know the first step is to consider the homogeneous part first ($q''+20q=0$). Next, considering the Characteristic Equation, $\lambda^2$ + $20$ = $0$, $\lambda = \pm 2\sqrt{5}i$. This means the real general solution for the homogeneous part is $$q_H(t)=A\cos(2\sqrt{5}t)+B\sin(2\sqrt{5}t)$$
The next step is to solve the inhomogeneous part. So if I were to choose $\omega=2\sqrt{5}$, resonance would occur, and so I rejected the negative $\lambda$ solution. However, the answers to my question state that the solution I rejected is also a value of $\omega$ that causes resonance. I rejected the negative solution as it would change the original differential equation as $100\sin(-2\sqrt{5}t) = -100\sin(2\sqrt{5}t)$.
My question is, why is the negative $\lambda$ value viable even if the original differential equation changes?
Comment: (FWIW, the characteristic equation is $\lambda^{2} + 20 = 0$, not $\lambda^{2} + 20\lambda = 0$. ;) Not sure I understand what you're asking. Is it that when $\omega = -2\sqrt{5}$ the ODE appears to become $q'' + q = -\sin(\omega t)$, which differs from  what was given...? If so, the resolution is that equation _doesn't_ pick up a minus sign on the right; it reads $q'' + 20q = \sin(\omega t)$, with $\omega = -2\sqrt{5}$.
Comment: Is that really it? Thank you! My lecturer wasn't very clear when he taught this.
Comment: That's just trigonometry. :) (If you like, signs in an expression can"hide" in unexpected places.)
Answer: The solution of $\lambda^2$ + $20$ = $0$ is $\lambda = \pm j 2\sqrt{5}$ (purely imaginary). You can easily verify (by substituting) that both $Ae^{j 2\sqrt{5}t}$ and $Be^{-j 2\sqrt{5}t}$ solve the equation.
In general, since the coefficients of the differential equation are real constants, the imaginary solutions are always complex conjugate pairs.


XmlTextReader and embedded resource DTD

Question: I'm trying to create a single EXE with no dependencies (spare the .NET Framework :-). The program involves parsing a bunch of XML docs (using XmlTextReader) that share the same DTD. The DTD is referred to by its name alone in the doc, so till now I've had it as "Copy if Newer" so it's in the same folder as the EXE itself.
Now I'd like to embed this DTD as an embedded resource in my project. I assume I'll need a custom XmlResolver to make my XmlTextReader happy, but I wasn't sure what that looked like.  What's the secret sauce?
Comment: In general, you shouldn't use `XmlTextReader`. You should use `XmlReader.Create()`.
Answer: There is no secret sauce. Just Google for "XmlResolver", and you'll find the "System.Xml.XmlResolver class" article. At the bottom, you'll find a link to "Customizing the XmlUrlResolver class".
Use an instance of your custom resolver as the XmlResolver property of the XmlReaderSettings instance that you use in your XmlReader.Create call.
Comment: Thanks, now I get it. But you must admit the sauce was closer to worcestershire than ketchup. :-)
Comment: Helpful, but an example would have been better since there are none on MSDN.
Comment: @night I assume a certain level of competence in the audience.

XmlTextReader and embedded resource DTD


Set Input to read Only

Question: I have this input which I need to set to readonly using jquery. Below is what I've done so far, but the code is not working. What is my mistake here?
HTML:
<input type="text" placeholder="" data-field-id="field26" name="field26[]" data-min-char="" data-max-char="" data-val-type="url" data-regexp="" data-is-required="false" data-allow-spaces="" class="validation-lenient" data-placement="right" data-toggle="tooltip" tooltip="" data-trigger="focus" data-html="true" data-input-mask="" data-mask-placeholder="">

js:
$( document ).ready(function() {
    input('[data-field-id="field26"]').setAttribute("readonly", true);
    $('[data-field-id="field26"]').setAttribute("readonly", true);
});

Comment: Use `.prop()` for this
Comment: use `document.querySelector` https://jsfiddle.net/yv1roo2y/
Answer: $(document).ready(function() {
    $('[data-field-id="field26"]').attr("readonly", true);
});

Answer: try
$("#fieldName").prop("readonly", true);

or
add atributed
disabled="disabled"
Comment: Disabled and readonly are not the same thing (disabled won't POST with the form for a start).

Set Input to read Only


No sound from bass guitar unless strings are hit very hard: dead preamplifier?

Question: My electric bass guitar (Yamaha RBX374, active pickup) suddenly stopped producing any sound. Only if I play the strings very hard, I do get some noisy tone.
Here's what I tried:

I suspected it was a dead battery so I replaced it with a new one, still no sound. I also checked that the voltage from the battery can be measured at the preamplifier.
I checked with two different amplifiers and doublechecked the cable.
Knobs (volume, balance, bass, treble) are all in middle position. In the meanwhile, I took out the balance pot and verified that it shows the correct resistance. I haven't put it back in yet but instead clamped the signal of one of the pickups directly to the preamp input (I tried both pickups).
I checked that all pots, all Gnd pins on the preamp, the cable, the bridge and the strings are all grounded.

I doubt that the problem is in the pickups because I see no reason why they should die at the same time.
My best guess currently is that the preamp is somehow broken but I don't know how to check this.
How can I further debug this?
Answer: I would say your best guess is probably correct: dead preamp. Which is strange because a properly made solid-state preamp should easily work without flaw for many decades, but that doesn't mean they all do. Be prepared that you'll have to replace it.
However since this has both active PUs and a preamp, it's definitely worth making sure the PUs aren't actually the problem. As you say it's highly unlikely that both PUs failed simultaneously, but what isn't so implausible is that they both don't get the correct operation voltage anymore. Have you checked that?
Regardless, I would also try tapping out the signal of one of the PUs directly to your amp. This sort of test can be best done by connecting the cable only for grounding, and taking the actual signal with a crocodile-clamp probe at various points in the circuit. I tend to put a ~470 nF capacitor in the probe to avoid biasing issues, though that actually shouldn't be necessary because the amp already has one.
Speaking of biasing – your description actually sounds like that might be the underlying issue: some connection is supposed to be at 4.5 V, but is actually at 0 V or 9 V instead and thus in the saturation region of the OP-amp it's feeding, unless you hit the strings hard enough to get some peaks into the linear region. If you want to go really nitty-gritty, you could use that knowledge to figure out what's wrong with the preamp circuit (assuming it's not encased in epoxy).
Comment: > Regardless, I would also try tapping out the signal of one of the PUs directly to your amp.  Good point, that works for both pickups! I have at least a usable instrument again :)
Comment: Interesting comment about the saturation region. I will check the preamp circuit for that, luckily it's not encased.
Comment: "...but what isn't so implausible is that they both don't get the correct operation voltage anymore." I think I had a misconception of the term active pickup. According to [this](https://www.talkbass.com/wiki/active-pickup/) I "misused" the term "in reference to a bass with an onboard preamp and passive pickups". The pickups have two connections only, the only "active" thing is the preamp, outside of the pickups.
Comment: Right, it's an active bass with passive PUs then.


How to center figure caption in R markdown

Question: I am using knitR to import my image into my rmarkdown and I wrote captions using fig.cap. My image is already centered but my caption is always left-aligned. Is there anyway to also align my caption under my image?
<code>```{r, echo=FALSE, fig.align='center', fig.cap="tmap with multiple data classification methods and classes"}
knitr::include_graphics("tmap01.png")
</code>
Comment: What type of document are you rendering to? How you can style a document depends in part on that e.g. if you're rendering to HTML, you can set up CSS styling for stuff like this pretty easily. If it's Word, set a reference doc.
Comment: @camille I am rendering to a HTML. I am thinking without adjusting the CSS styling, from rmarkdown are there any options to do it
Comment: There's a bunch of ideas [here](https://stackoverflow.com/q/3912694/5325862) that are markdown in general, not rmarkdown specifically
Comment: You could also have a glance at [`quarto`](https://quarto.org/docs/authoring/figures.html#caption-locations).
Answer: Inspecting the document shows that the caption is in a <code>p</code> tag with class <code>caption</code>, and there's no CSS associated to this class. So you can set some CSS properties to the <code>caption</code> class, by adding this CSS chunk (e.g. at the beginning of the document):
<code>```{css}
.caption {
  margin: auto;
  text-align: center;
}
```
</code>


Perform a select and expand in the same query with breeze is not supported

Question: I develop an asp.net solution with Durandal/breeze.
Here is my code to get all my shippers:
var query = EntityQuery.from('Shippers')
               .select('id, name, street, city');

return manager.executeQuery(query)
        .then(querySucceeded)
        .fail(queryFailed);

Here is the related model:
public class Shipper
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Street { get; set; }
    public string Number { get; set; }
    public City City { get; set; }
}

public class City
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string PostCode { get; set; }
    public Country Country { get; set; }
}

Now I need to also include countries
public class Country
{
    [Key]
    public int Id { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
}

But with the actual query I don't get countries with it.
I try:
var query = EntityQuery.from('Shippers')
               .select('id, name, street, city')
               .expand('City.Country');

but i get the error:
use of both 'expand' and 'select' in the same query is not currently supported
My question: how to get countries?

UPDATE
As Jay suggested, we can do:
var query = EntityQuery.from('Shippers')
       .select('id, name, street, city, city.country')

Now, I got a city_Country object:

I don't understand why we got this city_Country because country data are already available in the city \ country object:

Furthermore it gives me problem because my next statement try to map my dto into my entity and this city_Country object don't exist in my entity and an error occured when mapping.
Below we see my entity object and there are no city_Country object:

Do I have to do something special on my mapping to avoid it?
Below is my function for the mapping operation:
function mapToEntity(entity, dto) {
     // entity is an object with observables
     // dto is from json
     for (var prop in dto) {
          if (dto.hasOwnProperty(prop)) {
             entity[prop](dto[prop]);
          }
     }
     return entity;
}

Answer: I'm not sure it's good practice to use a projection to 'partially' fill an entity, which is what it looks like you are doing.  Breeze will automatically map any true 'entities' it finds in your result set.  So why not simply use
var query = EntityQuery.from('Shippers')
    .where(...)
    .expand('city.country');

The immediate results will be a collection of shippers, but each shipper will have its city and nested country properties fully resolved as entities as well.  They will be available via navigation from the returned shippers but they will also be available within the entityManager cache if you wanted to query them directly.
A second note: Breeze 'expand' semantics have the same restrictions that the Entity Framework does.  This means that we cannot expand the properties of a projection.
So you can either skip the projection (as above)
var query = EntityQuery.from('Shippers')
   .where(...)
   .expand('city.country')

and get full "Shipper" entities with the 'city" and the 'country' property on the city both populated. ... Or you can do a projection, in which case you perform the equivalant of the expansion yourself. i.e.
In this case you will
var query = EntityQuery.from('Shippers')
  .select('id, name, street, city, city.country')

in which case each item in your result set will consist of 5 properties. Note that in this case only the 'city' and 'city.country' properties will be added to the entityManager's cache becasue these are the only 'true' entities in the result set. i.e. no shipper's
The idea to be clear on is that the 'results' of a query and the 'side effects' of a query are distinct.  The top level results of a query will be exactly the shape you expect. The 'side effects' of the query are the result of any 'expand' you perform.  These do not change the shape of the query, they simply change the resolution of any nested 'entity' properties within the results.
Hope this helps.
Comment: Thank you for this explanation. Why I used projection in my querries is because some entities may contain a lot of 'heavy' properties like images, ... so in case of querying for a simple list is it better to get only necessary properties or all the properties of an entity?
Comment: One option is simply to map the "heavy" properties to their own EntityType with a one to one correspondence to the 'parentType' which would exclude them.  The other is to actually measure the perf/memory footprint of using the "full" entities and see if they are as expensive as you suspect.  I'd start with the simplest architecture and only complicate/optimize it once you prove to yourself that it is non-performant. i.e. don't optimize too early.
Answer: We do allow this:
var query = EntityQuery.from('Shippers')
           .select('id, name, street, city, city.country')

Comment: Doing this to a one-to-many property doesn't work

    ExceptionMessage: "Unable to locate property 'UserName' on type 'System.Collections.Generic.ICollection`1[Domain.Entities.UserProfile]'.",
Comment: I updated my question to show the result. Can you take a look? Thanks.


Howdo I use MATPOWER only for power flow?

Question: Here is my question. I´m developing a genetic algorithm to optmize a distribution net by reducing it´s power losses, I´ve been trying to use Matpower since this "matlab´s plugin" already calculate the power flow, but my problem is that matpower tries to optimize it. I´d like to know if it is possible to use it only for power flow calculation and how could I do it.
Thank you.
Answer: I´ve just find the answer. It is quite simple, instead of using runopf() you can use runpf() for power flow analyses.


Basic Trig problem

Question: This is a very basic question but that I need to know to solve a harder calculus question.  How do I solve for $x$, for the problem $\tan(x) = \sqrt{3}$?
Comment: You can observe that it is $\pi/3$ radians ($60$ degrees). Just draw the usual $30$-$60$-$90$ triangle. If the htpotenuse is $1$, the sides are easy to write down.  There are other solutions, one in the third quadrant, and you can then always change by a multiple of $2\pi$.
Comment: I forgot the 30-60-90 trick what is it again?
Comment: It's half an equilateral triangle, which tells you something about the relative lengths involved.
Comment: From the hypotenus, draw a line making a $60$ degree angle with the shorter of the two legs. By chasing angles, you can see this divides the original triangle into $2$ triangles, one equiateral and the other isosceles with base angles $30$. From this you can conclude that the line you just drew bisects the hypotenuse. so if hypotenuse is $1$, the short side is $1/2$, and by Pythagorean Theorem the other side is $\sqrt{3}/2$.
Comment: @Sean: Gerry Myerson is right, it is much cleaner to cut an equilateral into two halves.
Answer: You either use the $\arctan(y)$ function and plug in $\sqrt{3}$; or if you happen to know some of the basic values of the trigonometric functions, you might know that
$$\sin(60^{\circ}) = \frac{\sqrt{3}}{2},\qquad\text{and}\qquad\cos(60^{\circ})=\frac{1}{2}$$
and therefore
$$\tan(60^{\circ}) = \frac{\sqrt{3}/2}{1/2} = \sqrt{3}.$$
In radians, $x=\frac{\pi}{3}$ is one solution.
Since the tangent function is periodic with period $180^{\circ}=\pi\ \text{radians}$, the solutions are
$$x = \frac{\pi}{3}+n\pi,\qquad n\text{ any integer.}$$

Basic Trig problem


Does capo quality make any difference?

Question: I feel I was fooled by a music store. They made me buy a really expensive capo saying that it gives a better tone than normal cheap one. However, I recently bought a cheap wooden capo and I could not hear much of a difference.
Does capo quality really make a difference to the tone?
I feel that as long as the capo holds the strings tightly, it doesn't matter.
Comment: Try Before You Buy.
Comment: @CarlWitthoft: Fair enough, but sometimes easier said than done, if you are shy of playing in a store, or think you may take some time to (learn to) appreciate the difference. Of course it helps if you have acquaintances to give you advice or let you try out their equipment.
Comment: I have seen instructional videos talk about capos that where made out of nothing more than a bunch of rubber bands and a pencil.
Comment: the only thing that I think makes a difference is whether it matches, or can adapt to, your fingerboard radius. If its too rigid, or pulls too hard without any adjustment then it could pull some of your stings slightly out of tune. Ive used one quite successfully on a Precision Bass before.@NeilMeyer is right, a rubber band and a pencil might work too, though with a fairly flat radius board as pencils are not noted for their flexibility
Answer: Capo quality matters, but not for tone. A better capo may give you more even tension on the strings, it may be more convenient to use, or maybe it's made of more durable materials or components that can be services or replaced as they wear.
The guitar's tone will only become affected if the capo throws the strings out of tune differently across the neck, or doesn't hold the strings tightly enough and causes buzzing or muting.
Capos can also throw guitars out of tune when used; better capos will do this less than simple ones. (It's worth mentioning that a capo doesn't need to clamp on the strings tightly; it only needs to hold them firmly enough so the strings ring freely. A capo that clamps the strings too tightly will often throw the guitar out of tune.)

Capos that use a spring to hold the neck are harder to adjust than one that uses an a mechanism with adjustable tension, but for guitars with a fairly average-sized neck this may not matter.
The style of capo that has a stretchy elastic band to clip onto the neck can sometimes work on steel-string guitars but it works very well on classical guitars, that have nylon strings with low tension.
Comment: There are many trigger-type models which tout one-handed operation, but as others have said, the spring will eventually lose tension. I have one of these. An alternative adjustable mechanism seems like a better deal. If you examine photographs of professional musicians playing with capos, I suspect that you may frequently see a common model -- the Shubb capo. I just added one of these to my bag, and initial tests  sound good.
Comment: @KirkA I use Shubbs a lot, even on stage. I use a D'Addario capo for 12-string work that's quite similar but allows for even finer adjustment. Would never use it on stage, though, it takes far too long to use. Shubb is a good compromise between that and the easy-to-use Kyser spring capos.
Answer: There are many different styles and types of capo, all with the same end product in mind. However, they do differ a lot. Some are dead straight, to work with flat fingerboards. Others have a radius which approximately matches the fingerboard radius on cambered fingerboards.
The way they attach to the neck varies too, and some are very easy to move up and down, while others need adjustment. Those with a spring for tension cannot be adjusted, so may, on some guitars, squeeze too hard and put the guitar out of tune, necessitating retuning for each position change. But they store easily on the head of the guitar when not being used.
I don't use capos often, but prefer G7,(not the cheapest!) which can be attached with as much or little pressure as needed.
There are many different designs, so it's worth trying several out. Take guitar to shop. Until you've tried them out, you really won't know whether it was hard sell or good sell. The cheapest is a pencil and rubber band - yes, it works - right through to a 'Spider', which takes things to a different level.
Answer: A cheap capo might seem just as good at first...
Give it a year or so of regular use and you'll realise why you pay extra for a good quality capo, they're more durable and maintain their tension so the strings will be held tightly.
Cheap capos lose tension and need replacing.
I bought a cheap capo and replaced it within a year with a good one that cost twice as much and hasn't needed replacing in 7 years.
Comment: I respectfully disagree, I bought a basic one 20+ years ago and it still works fine.
Answer: I have used the "K" brand quick change on my Martin 000X ae , Taylor 414ce, Ovation 12 string and Gibson J150 for 10 years and it works great. Pressure on the strings is even and enough so they ring like an open chord.
I see capos for $60 USD and I think that's over the top. The "K" brand (not sure I am allowed to name them) are about $14.00 USD. I use the 12 string capo (the black "quick change" one) on all the guitars (6 and 12 string) and my capo has lasted 10 years, no wear or tear or issues. I find them easy to use at gigs and I leave it on the headstock for quick changes.
Also - there is no dan=mage to the neck from the rubber like some say.....aside from keeping the strings suppressed properly and evenly and staying in tune - a capo does not affect the sound tone - just the pitch
Answer: Yes. It's mainly the strength of the metal spring to consider and how many strings it frets. Partial capos are great. I have to use two capos on one fret because my expensive capo is nice metal cast but the spring needs to be pulled apart with needle-nose pliers.
Here is a YouTube video of a homemade "snare" capo that sounds terrible.
Answer: One thing to consider when getting a capo is how much it gets in the way of your hand up there on the 7th fret (I have big hands). Fingering notes right next to the capo may be a bit cumbersome with a clunky device.
BTW some capos are capable of barring just a few strings. Most others are all or nothing.
Answer: Frankly, I don't think it makes any difference at all.
I use a few capos on my classical guitar, I'd be lying if I said one sounds better than the other.
Comment: Since the tension on the strings is much lower for classical guitars, there is likely a big difference in how classical guitars respond to capos versus steel string acoustic and electric guitars.
Comment: If you use 'a few' is there one you prefer? For any particular reason? On this site, we try to be as helpful as we can, by adding other relevant information in answers.
Answer: A capo might make a slight difference in tone. (I disagree with some of the earlier posts).
I did a comparison among three capos, on a higher end, all solid wood acoustic guitar:

Planet Waves NS Pro (from the pre-D'Addario days)
D'Addario Planes Waves NS Pro Plus
G7th Performance 3

The PW Pro and the G7th have a firm rubber band. They result in brighter, crisiper sound.
The D'Addario Pro Plus, by design, has a thicker and softer pad that aims to emulate the barring finger's flesh. This results in a somewhat more dampened sound.
The difference is subtle, but is there.
I have also found other folks on YouTube come to the same conclusion, and also one video where G7th's representative claims that the rubber's firmness has the said effect on the tone.
It's not the capo quality per se—as you asked in your question—that affects the tone (all these three are great quality products), but the deliberate design choices made by the manufacturer. One tone is not necessarily better than the other, it's up to you to decide which one you prefer, among many other properties of the capo.

Does capo quality make any difference?


Uniform distribution versus a Poisson homogeneous process with Ripley's K

Question: I'm testing astropy's RipleysKEstimator. I create a 2-dimensional uniform distribution in [0, 1), and obtain its K value for a radius $r=0.5$.
It was my understanding that this should be equivalent to evaluating the Ripley K function on a homogeneous Poisson process, whose result is $\pi r^2\approx0.785$ (for $r=0.5$). This is not what I get tough:
import numpy as np
from astropy.stats import RipleysKEstimator

# Define Kest
Kest = RipleysKEstimator(area=1)
# Generate random 2D data
xy = np.random.uniform(0, 1., (1000, 2))
# Evaluate with r=0.5
res = Kest(xy, (.5,))

This gives $res\approx0.49$.
What am I missing here?
Comment: I've edited the question. You were right, this is apparently caused by edge effects. Thank you!
Comment: Could you tell us how `Kest` deals with the edge effects?  That alone could explain the difference, because $r=0.5$ is such a large fraction of the diameter of this region.
Answer: Following whuber's advice I checked the methods for edge effects correction:

none:
this method does not take into account any edge effects whatsoever.
translation:
computes the intersection of rectangular areas centered at the given points provided the upper bounds of the dimensions of the rectangular area of study. It assumes that all the points lie in a bounded rectangular region satisfying x_min < x_i < x_max; y_min < y_i < y_max. A detailed description of this method can be found on ref [4].
ohser:
this method uses the isotropized set covariance function of the window of study as a weight to correct for edge-effects. A detailed description of this method can be found on ref [4].
var-width:
this method considers the distance of each observed point to the nearest boundary of the study window as a factor to account for edge-effects. See [3] for a brief description of this method.
ripley:
this method is known as Ripley's edge-corrected estimator. The weight for edge-correction is a function of the proportions of circumferences centered at each data point which crosses another data point of interest. See [3] for a detailed description of this method.

His intuition was right, apparently the problem is with the default none method which does not take into account edge effects. All the other (except var-width where I'm not sure what's going on) give results much closer to what I was expecting:
>>> Kest = RipleysKEstimator(area=1, x_max=1, y_max=1, x_min=0, y_min=0)
>>> xy=np.random.uniform(0., 1., (1000, 2))
>>> Kest(data=xy, radii=(.5,), mode='none')
array([0.48910911])
>>> Kest(data=xy, radii=(.5,), mode='translation')
array([0.79486786])
>>> Kest(data=xy, radii=(.5,), mode='ohser')
array([0.79475738])
>>> Kest(data=xy, radii=(.5,), mode='var-width')
array([0.])
>>> Kest(data=xy, radii=(.5,), mode='ripley')
array([0.79369159])


Which hook will allow me to change links in a page?

Question: Which hook would allow me to change each link (given in  tags) in content pages and menus and change their attributes?
I need to implement this in a theme that uses Olivero as parent theme and the obvious MYTHEME_preprocess_links() results in a blank white screen (WSOD).
The only hook I've been able to use to change the page content is this one.
function MYTHEME_preprocess_field(&$variables): void {
    $content = $variables['items'][0]['content'] ?? false;
    $type = $content['#type'] ?? '';

    if ($content && $type === 'processed_text') {
        $dom = new DomDocument();

        libxml_use_internal_errors(true);
        $dom->loadHTML($variables['items'][0]['content']['#text']);
        $errors = libxml_get_errors();
        libxml_clear_errors();

        if (count($errors) === 0) {
            $edited = 0;

            foreach ($dom->getElementsByTagName('a') as $link) {
            }
        }
    }
}

Comment: There is no single "preprocesses all links everywhere" hook. Links in content are mostly field templates (use hook_preprocess_field) or editorial text (use a text filter). If not covered by those two, you have to look for module-specific hooks (like hook_preprocess_menu from menu module). Those are usually documented in MODULE_NAME.api.php of the module
Comment: We need to see your code to have the possibility to understand what's wrong with it.
Comment: Thank you for reading my question. :) In this case I'm not certain I have code to share. I've simply been trying a bunch of theme hooks to see which get triggered and which actually give me access to the  tags within page contents. I must have tried 50 variations of hooks. I won't be able to remember them all.
Comment: Depending on what you are doing, it might be better to create an input filter.  This will affect the content wherever it is displayed in that filter, but it might be a more robust solution than using a hook in your theme.
Answer: With thanks to the commenters I was able to figure out how to edit the DOM in content pages and menus.
Regarding version: Drupal 10.
Replace "MYTHEME" with the machine name of your theme. Open your MYTHEME.info.yml file to see the name of your theme. It is case-sensitive.
Within your /themes/MYTHEME/ directory you may have a MYTHEME.theme file wherein you are able to declare hook functions. These hooks include those that allow you to preprocess data before it gets build into a template. It is here that you are able to adjust the HTML strings to your needs.
These hooks include a $variables parameter that will eat up all of your available memory if you try to print it via var_dump.
Editing content
Content includes those that you build in /admin/content and those you build in /admin/structure/block/block-content.
The hook used to adjust the HTML of content pages is MYTHEME_preprocess_field(&$variables).
Inspect $variables['entity_type'] to determine if you are editing content or block-content.
The HTML string that will be used to build your content is in $variables['items'][0]['content']['#text']. Adjust that string via string manipulation or DOM manipulation with DOMDocument then overwrite $variables['items'][0]['content']['#text'] with your edited string.
If using DOMDocument you may need to ignore all errors generated by loadHTML() because this feature does not understand HTML5 elements, but it can still work with them.
function MYTHEME_preprocess_field(&$variables): void {
    $content = $variables['items'][0]['content'] ?? false;
    $type = $content['#type'] ?? '';
    // Blocks are the pieces that are not content. These include the sidebar, search, header, and footer.
    $block = $variables['entity_type'] === 'block_content';

    if ($content && $type === 'processed_text') {
        $dom = new DomDocument();

        libxml_use_internal_errors(true);
        $options = LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD | LIBXML_NOERROR;
        $dom->loadHTML('
' . $content['#text'] . '
', $options);
        // Use this variable to inspect the errors when troubleshooting.
        // $errors = libxml_get_errors();
        libxml_clear_errors();

        $parsedHTML = $dom->saveHTML();

        // Errors are fine as long as the HTML string was successfully parsed by DOMDocument.
        if ($parsedHTML) {
            // Your code here to manipulate DOM.
        }
    }
}

Editing menus
The hook used to adjust the HTML of menus is MYTHEME_preprocess_menu(&$variables).
There are various menus in a Drupal page. These include admin, main, and account.
The menu items to adjust are within $variables['items']. The structure of each element within that array is:
items(array)
 - menu_link_content:{unique_id}(array)
 -  - is_expanded(boolean)
 -  - is_collapsed(boolean)
 -  - in_active_trail(boolean)
 -  - attributes(object)
 -  - title(string) Sample menu item
 -  - url(object)
 -  - below(array)
 -  -  - menu_link_content:{unique_id}(array)
 -  -  -  - is_expanded(boolean)
 -  -  -  - is_collapsed(boolean)
 -  -  -  - in_active_trail(boolean)
 -  -  -  - attributes(object)
 -  -  -  - title(string) Sample sub-menu item
 -  -  -  - url(object)
 -  -  -  - below(array)
 -  -  -  - original_link(object)

Each menu item may have sub-items. These are saved in the ['below'] key as an array.
If you want to adjust the url the ['url'] element holds a Drupal URL object. Refer to the documentation on how to adjust a Drupal URL object.
Here is an example to get you started:
function adjustMenuItem($item) {
    // Your code to adjust the elements of the $item array.

    // Handle recursive array elements.
    if (isset($item['below']) && is_array($item['below']) && count($item['below']) > 0) {
        foreach ($item['below'] as $key => $value) {
            $item['below'][$key] = adjustMenuItem($value);
        }
    }

    return $item;
}

function MYTHEME_preprocess_menu(&$variables): void {
    $name = $variables['menu_name'] ?? '';

    if ($name === 'main' && is_array($variables['items'])) {
        foreach ($variables['items'] as $key => $value) {
            $variables['items'][$key] = adjustMenuItem($value);
        }
    }
}


What Is The Best Keystore to use?

Question: I want to use Keystore in my upcoming project. I saw that there is an Keystore API in Java. But that seems to be very complicated.
Are there any other good keystore available that work well with Java/Groovy?
Answer: Not that I know of.  From my perspective, the API is relatively as minimal as possible give the things that it needs to supply.
<code>KeyStore keyStore = keyStore.getInstance(KeyStore.getDefaultType());
keyStore.load( inputStream, storePassword.getBytes() );

// Get a key
if ( keyStore.isKeyEntry(alias) ) {
   Key key = keyStore.getKey(alias, keyPassword.getBytes());
}

// Store a new key
KeyFactory keyFactory = KeyFactory.getInstance(KeyStore.getDefaultType());
KeySpec keySpec ...; // depends on what kind of key you want to create (ie. rsa, etc..)
Key key = keyFactory.generatePrivate(keySpec);
// sign the key here
Certificate certChain[] = ...; // get the cert chain
keyStore.setKeyEntry(newAlias, newKey, newKeyPassword.getBytes(), certChain);
keyStore.store(outputStream, storePassword.getBytes());
</code>
This is relatively minimal code to handle what a keystore needs to do.

What Is The Best Keystore to use?


Solving simultaneous linear equations with R

Question: Am trying to solve a system of linear equations involving three variables using R. However, I get an error as shown below:
> A = matrix(data=c(-0.4, 0.4, 0.15, 0.3, -0.55, 0.6, 0.1, 0.15, -0.75), nrow=3, ncol=3, byrow=TRUE)
> A
     [,1]  [,2]  [,3]
[1,] -0.4  0.40  0.15
[2,]  0.3 -0.55  0.60
[3,]  0.1  0.15 -0.75
>
> b = matrix(data=c(0, 0, 0), nrow=3, ncol=1, byrow=TRUE)
> b
     [,1]
[1,]    0
[2,]    0
[3,]    0
>
> solve(A, b)
Error in solve.default(A, b) :
  system is computationally singular: reciprocal condition number = 1.04615e-17

When I work them out using substitution method, I get the variable values as: 0.456, 0.4027, 0.1413 respectively (not exactly precise values). The sum of all the variables should be 1.
How could I solve such a system?
Background: These equations come from solving a Discrete Time Markov Chain. In reality, there could be around 20 such simultaneous equations on 20 variables.
Comment: There are infinitely many solutions in this case.  Check out `A %*% c(1, .8837, .31)` and `A %*% c(3.225, 2.85, 1)` for two examples.
Comment: Ah, I missed out the constraint! Updating the post.
Answer: A1 = matrix(data=c(-0.4, 0.4, 0.15, 0.3, -0.55, 0.6, 0.1, 0.15, -0.75), nrow=3, ncol=3, byrow=TRUE)
A2<-eigen(A)$vector
A%*%A2[,3]
              [,1]
[1,]  2.461139e-17
[2,] -1.083796e-16
[3,]  3.932943e-17
1> A2[,3]
[1] 0.7298860 0.6450156 0.2263212

I suppose you mean the norm of the variables should be 1.
Otherwise:
1> A2[,3]/sum(A2[,3])
[1] 0.4558304 0.4028269 0.1413428

Comment: +1 `MASS::Null` should also get this answer.
Comment: This looks brilliant, although I'm not sure about the theory involved here. Actually, all the variables indicate certain probabilities (of being in a state) -- so their sum should be 1.
Comment: @Barun: yes and, geometrically, this constraint implies that your LHS matrix is rank deficient and therefore that it's last eigenvalue is 0 and that the corresponding eigenvector gives (a basis for) the vector you are looking for (up to a rescaling/change of signs).


How to identify properties of conic $12x+y^2-6y+45=0$

Question: I need to find out the type of conic, the coordinates of the center, focus (foci), vertex (vertices), directrix for the conic given by:
$$12x+y^2-6y+45=0$$
I completed the square to get
$$(y-3)^2+36=-12x$$
This is a parabola I believe since it is of the form $y^2=4px$ which is a parabola rotated by $\frac{\pi}{2}$ clockwise if I'm not mistaken.
I am now struggling on how to get the rest of this information so any help is appreciated.
Answer: Hints and References :

Look up the detailed guide here.
The parabola is shifted and it is rotated by 180 degrees . ( The -ve sign of p indicates that it has been flipped)
This might also help.
Answer: Yes, this is a parabola. You can factor out like this:
$$(y-3)^2 = -12(x+3)$$
This means, the vertex is located at $(-3,3)$. The parabola is opening towards the left.
In this case, $-4p = -12$, $p=3$. This means the distance from focus to vertex is 3. If you draw the parabola, the focus should be located at $(-6,3)$. The directrix should be a vertical line with the nearest point to the vertex also having a distance of 3. Hence, directrix is $x=0$.
Comment: Very useful thanks it was mainly the first step you provided that helped me most.


Laravel attribute with default value is set, still gives an error Integrity constraint violation 'priority' cannot be null

Question: Migration:
$table->tinyInteger('priority')->default(1);

Controller Method:
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    //
    $this->validate($request, [
      'asset_type' => 'required',
      'scan_time' => 'required|numeric',
      'priority' => 'nullable|numeric',
    ]);

    $data = $request->except('_token');

    try {
      ScanProfile::add($data);
      return back()->with('success', 'Scan Profile has been added');
    } catch (\Throwable $th) {
      throw $th;
      return back()->withErrors([$th->getMessage()]);
    }
  }

Model:
protected $fillable = [
    'system_name', 'key', 'scan_time', 'priority'
  ];

  /**
   * Create new scan profile
   *
   * @param array $data
   * @param UploadedFile $photo
   * @return void
   */
  public static function add($data, $photo)
  {
    $sp = new ScanProfile();
    $sp->fill($data);

    try {
      $sp->save();
    } catch (\Throwable $th) {
      throw new Exception("Error in save : " . $th->getMessage(), 1);
    }
  }

Data:
$data = [
  "priority" => null
  "system_name" => "Ultra Scan"
  "asset_type" => "D"
  "scan_time" => "3"
]

Error:
Error in save : SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'priority' cannot be null (SQL: insert into master_scan_profiles (priority, system_name, asset_type, scan_time, id, updated_at, created_at) values (?, Ultra Scan, D, 3, 843a3073-d087-4e49-9280-5c3d6be025d6, 2021-11-25 07:31:06, 2021-11-25 07:31:06))
Answer: because in your validation rules you say:
'priority' => 'nullable|numeric',

so, a priority with null value would pass ...
to avoid this , you can use filled validation
$this->validate($request, [
      'asset_type' => 'required',
      'scan_time' => 'required|numeric',
      'priority' => 'filled|numeric',
    ]);

Comment: Changed 'priority' => 'nullable|numeric', to 'priority' => 'filled|numeric', Now getting validation error says: The priority field must have a value.
Comment: yes, because you pass it as null, the validation validate the if the priority  present is should not be null, so you either pass it with a value, or you should not pass it at all
Comment: Yes, I get to know that and the issue was solved. thanks btw. @OMR


How do i display my code with jQuery?

Question: I wanted to try something simple today with jQuery, but it doesn't seem to display anything on the page, whatever i try.
<!DOCTYPE html>

Fixed it. I just forgot to put the jQuery script in it.
Comment: Your div is empty put something there. And missing jquery reference
Comment: you did not included jquery.js file in  tag
Comment: missing references to jquery maybe ?
Comment: yes, if you put something in the div you will see that fade out as you have requested in your code. Once you add the jquery lib as well.
Comment: Why ppl still answer this kind qustion ? earn more rep. ?
Answer: You don't seem to be including jquery. Try adding this:

Answer: Your code looks correct, but its result isn't visible.
Your jQuery code makes your div slowly disappear. But the said div is empty, so it is invisible.
Put something into your div and you'll see some results !
Also, don't forget to include the jQuery source.
Comment: Thanks, but everything works. It was indeed the jQuery source that was missing.

How do i display my code with jQuery?


Chord shown in brackets above music score

Question: In the image below, what do the brackets around the chord Em mean?
Looking at the piano part, the notes played are G Bb D and F. Which I believe is a Gm7.
The guitar tab at the top shows an Gm:

Shouldn't this be a Gm7 to include the high F?
What is the relevance of the Em in brackets?
The guitar chord shown is an Em (I believe). Why is this? There are no E notes in the piano score.
Comment: would you post the head of the sheet or tell us the title, please? I wonder if there isn't more information, like Tim says in his answer ....
Answer: It's not 100% clear, but I'd say that you either use a capo at 3rd fret, and play an Em chord shape, which results in a Gm, or you play Gm with a barre at the 3rd fret. Indeed it could have been explained better...
Comment: Thank you, I think you are correct. I've just had a look at the rest of the score and it all lines up with your suggestion. Do you have any idea why it would be Gm and not Gm7? Can I also just confirm that I have that right. It is actually Gm7 in the piano part?
Comment: It is a Gm7 in the piano part, yes. Why Gm and not Gm7? It could be they're just simplified the guitar part. The F that makes it a Gm7 is in the 'broken chord' (a kind of figure), from the second beat onward. The music is arranged for guitar and piano, so it's not *necessary* for the guitar to play Gm7. It will sound fine if you do. If you're playing it without a piano then you probably should play Gm7. But bear in mind that the piano's F is quite high and tinkly, so if you play a Gm7 with a *low* F it might not sound right for the song. But I don't know what the song is.
Comment: Why plain Gm? Two reasons off the top of my head, but I'm sure there can be more. Reason 1: (as suggested elsewhere) it's simpler and it's good enough. Reason 2: that's exactly what the composer wanted - only because the piano plays Gm7, it doesn't necessarily follow that the guitar must play the same. The ultimate goal is to have something that sounds good, and whatever achieves that, that's what the composer wants.
Answer: There may well be an instruction at the top saying capo the 3rd fret. Then you can play the (simple) open chords to accompany the song. Actually Em7 would be even more simple!
The other explanation may be that there is a part for a transposing instrument, which would play to provide a key a m3 away, and the bracketed chord would be in tune with that.


element.classList.contains() eaquals to undefined. Why?

Question: Code below displays undefined:
function search(){
    let clas = document.querySelector('input#search').value;
    if(clas=="Speed"){
        clas="v";
    }else if(clas=="Dro"){
        clas="s";
    }else if(clas=="Cza"){
        clas="t";
    }else if(clas=="Przys"){
        clas="a";
    }
    find(clas);
}
function find(clas="*"){
        const elements = document.querySelector("main").childNodes;
        if(clas!="*"){
            console.log(elements[0].classList.contains("v"));
        }
}

I wanted to check if elements of main contain class "v" but my every attempt concludes with an error:

script.js:17 Uncaught TypeError: Cannot read properties of undefined
(reading 'contains')
at find (script.js:17)
at search (script.js:12)
at HTMLButtonElement.onclick (calculator.html:18) find @ script.js:17 search @ script.js:12 onclick @ calculator.html:18

Main contains elements! I do not understand what I've done wrong and how to fix it. Could someone explain and help?
Comment: the element probably has no classes at all - could be just a text, not a dom element
Comment: _"Cannot read properties of undefined (reading 'contains')"_ - You try to read/access the property `contains` from something that is `undefined` (it's not that `.contains()` is `undefined` as mentioned in the title)
Answer: The error tells you that you're trying to use contains on the value undefined. That tells us that the first child node of the main element is not an element (perhaps it's a text or comment node; often it's a text node with whitespace). Only element nodes have classList. So elements[0].classList is undefined.
You may have wanted children rather than childNodes, if you wanted only element children.
Here's an example of the difference:

const main = document.querySelector("main");
console.log("childNodes[0].nodeName:", main.childNodes[0].nodeName);
console.log("children[0].nodeName:", main.children[0].nodeName);

Hi there

Or if you're only going to use the first one, you could use firstElementChild instead of children[0].
Comment: You were right, I did use comments and as it appears that was the problem. The ultimate solution is:  function find(clas='*'){
    const elements = document.querySelector("main").children;
    if(clas!="*"){
        for (let i = 0; i < elements.length; i++) {
            if(elements[i].classList==undefined){
                console.log("un!");
            }
            if(elements[i].classList.contains("v")){
                elements[i].style.display="flex";
            }else{
                elements[i].style.display="none";
            }
        }
    }else{

    }
}


if (String.IsNullOrEmpty(myString)) and if (String.IsNullOrWhitespace(myString)) still working for empty strings

Question: my goal is to get a message from an other client over a server and work on with that message. Server and other client are in visual basic and if i try to communicate between two vb clients everything is fine, but i need the client in c# for my Unityproject.
My Problem is that there are still empty Messages at the Console, so i think the if() doesn't work correct.
Here is the relevant part of the Code:
try
            {
                theStream = mySocket.GetStream();
                Byte[] inStream = new Byte[mySocket.SendBufferSize];
                theStream.Read(inStream, 0, inStream.Length);
                serverMsg += Encoding.ASCII.GetString(inStream);
                serverMsg = serverMsg.Trim();

                //if ((serverMsg == null || serverMsg == "")) doesn't work
                //if (String.IsNullOrWhiteSpace(serverMsg)) doesn't work
                //if (String.IsNullOrEmpty(serverMsg) || serverMsg.Length <1) doesn't work
                INOWS = false;
                INOWS = IsNullOrWhiteSpace(serverMsg);

                if (INOWS)
                {
                    // do nothing
                }
                else
                {
                    Debug.Log("[SERVER] -> " + serverMsg);

                }
            }
            catch (Exception e)
            {
                Debug.Log("[Fehler]" + e);
            }
        } while (socketReady == true);
public static bool IsNullOrWhiteSpace(string value)
{
    if (value != null)
    {
        for (int i = 0; i < value.Length; i++)
        {
            if (!char.IsWhiteSpace(value[i]))
            {
                return false;
            }
        }
    }
    return true;
}

Thanks to your hints i tried using IsNullOrWhiteSpace, but this gave me an error "'string' does not contain a definition for IsNullOrWhiteSpace"
So i used this IsNullOrWhitespace but i still get at least one empty string at the console for every korrekt string. console view Do you have any other hints for me?
Comment: Note that Trim does not edit the string. It returns a new string that has been trimmed.
Comment: Also, you could just use `String.IsNullOrWhiteSpace`.
Comment: Using SendBufferSize to *read* makes no sense whatsoever.  4096 is a nice round value.  Trim() does not remove the zeros from the buffer, nor is it used correctly.  Pay attention to the return value of Read(), it tells you how many bytes are actually in the buffer and what you need to pass to GetString().
Comment: You should really avoid writing `catch (Exception e)` - it leads to swallowing errors and giving you the false sense of security that your code is bug-free.
Comment: the marked "duplicates" didn't bring the solution, it's still not working. Thanks for trying to help me.
Comment: What is the exact value of `value`? `value.Length`? `value.Trim().Length`?
Comment: serverMsg.Trim() is the value
Comment: I asked three questions. You answered none of them. The latter two questions, for example, would have a **number** as the answer.
Comment: so i missunderstood your question, sorry.
value is like:  Quelle-95-94-true
length: different but always Name-XPos-YPos-boolean
Trim.Length should be the same as length, but if there were Spaces, it should remove them
Answer: if (String.IsNullOrWhitespace(serverMsg))
                {
                    // do nothing
                }

IsNullOrWhitespace() checks null, whitespace("   ") and empty("")
Comment: I tried it with IsNullOrWhitespace() and edited my Question, because it poorly didn't work for me
Comment: @mjwills You're right, I just copied and pasted it and added the NullOrWhitesapce. I will update now
Answer: Try trimming the string:  if the string has any whitespace characters in it, it will still fail the IsNullOrEmpty() test.
In such cases (particularly with user or web service input), I generally use something like
if ((s ?? "").Trim() != "")
{
  //  do whatever processing you need to do here...
  ...
)

Comment: I guess that's what `IsNullOrWhiteSpace` is for! Why reinvent the wheel?


What if my seasonal decompose is completely coloured?

Question: I have a dataset for solar output, at day the values are positive but at night the values are 0. When i try the seasonal_decompose() function It gives me the following result:

Im pretty sure the difference between day and night is a seasonality (right?).
This is my code:
result = seasonal_decompose(df1, model='additive',freq=96)
result.plot()
plt.show()

freq = 96 because my data is per 15 minutes.
What does this graphs tell me?
Comment: What solar output variable did you measure? Units of measurement?
Comment: @kjetilbhalvorsen I measured the Solar output in MW
Comment: And why does it have such an increasing (modulo sesonality) trend over time? Something with the measurement conditions? It looks suspicious!
Answer: I got a similar graph as yours for a seasonal sale data and after I increased my freq variable to 365 I got the seasonal pattern, before it was all colored. It could be something similar for you. Your freq is not suitable for your data.
Answer: The plot from your question shows "overplotting": to many dots or lines in small graph and one cannot see too much.
You can zoom in to see details, i.e., reduce the time span, say pick only 3 month to plot.
In addition, the freq setting may be wrong, data is per 15 min does not mean the freq is 96 because "solar data" may not have freq of 1 day.


How to match php variable but not inside single quoted string

Question: I need to match php variable but not method call, not inside single quote and not if $ is escaped.
is should match:
$foo
"$bar"

but not when used like this:
$foo->bar
'foo $bar baz'
"\$foo"

So far I have this regex: "/(?<!\\\\)\$(\w*+(?!->))/" that don't match method call and escaped dolar demo
Comment: Need to parse php? A big ask for regex. You'd have to exclude quotes/comments, and anything else that can hide stuff. I don't see how a $ could be escaped outside a quote/comment, do you?
Comment: Also, the check that something is _not escaped `(?<!\\)(?:\\\\)*something`_ and something that _is escaped `(?<!\\)(?:\\\\)*\\something`_
Answer: You can use this regex in PCRE with verbs (*SKIP) and (*FAIL):
'[^'\\]*(?:\\.[^'\\]*)*'(*SKIP)(*F)|(?<!\\)\$([a-zA-Z_]\w*)\b(?!->)

RegEx Breakup:
'[^'\\]*(?:\\.[^'\\]*)*' # will match text between single quotes skipping escaped quotes
(*SKIP)(*F)              # skips above single quoted text
(?<!\\)                  # negative lookbehind to fail the match is $ is preceded by \
[a-zA-Z_]\w*             # will match a variable starting with $, \b is for word boundary
(?!->)                   # negative lookahead to fail the match if -> is at next position

RegEx Demo
Comment: How about escaped quotes `'$foo \'$bar\' '`?
Comment: But he said not between single quotes. Didn't he? I think it will go to get more and more complex.
Comment: Good. But we don't have such variables `$999` either. It should be considered as a dollar signed amount and get ignored.


Equivalence of the sum of random variables and their expectation

Question: Given that $X$ is a random variable I define
$$
\psi = \sum_i^{n} X_i
$$
so $\psi$ is the sum of $n$ variables with the same distribution. Given that
$$
\bar{X} = \frac{\sum_{i}^{n} X_i}{n}
$$
I can write:
$$
\sum_{i}^{n} X_i = n \bar{X} = \psi
$$
At the same time if I take the expectation of $\psi$ I get:
$$
E[\psi] = E\left[\sum_{i}^{n} X_i\right] = n E[X_i] = n \bar{X}
$$
thus it seems that $\psi = E[\psi]$ which seems impossible. Where is the error in this reasoning?
Answer: I have a problem with this

$$E[\psi] = E\left[\sum_{i}^{n} X_i\right] = n E[X_i] = n \bar{X}$$

because
$$E[X_i]  \neq \bar{X}$$
simply because $\bar{X}$ is random whereas $E[X_i]$ is not.
Comment: So as I understand it the population mean $\bar{X}$ is not the same as the expectation of the random variable $E[X_i]$. Can we say that they converge when the population size ($n$) is very large?
Comment: What you say is true and is an application of the law of large numbers @Tom
Comment: Thanks, In that case $\psi=[\psi]$ in the limit where N is large right?
Comment: you can say $ \frac{\psi}{n} \rightarrow E(X_i)$ as $n$ goes to infinity given iid observations.
Answer: You are confusing the 'average X', which is the average over an actual sample, and the 'average X' which is the expectation value, the ideal limit you would get from many samplings.  The first is usually denoted $\overline X$ and the latter$E(X)$.  $<X>$ is used for both by various authors. So the notation can be confusing, but the concepts are entirely different.