问:
ModuleNotFoundError: No module named 'numpy.random._pickle'
I have a doc2vec model which drives my recommendation app. I have built the doc2vec model and saved into s3 bucket. Now when i open the webapp the model should be loaded back from s3 but this not happenning. I used AWS Elasticbean stalk to deploy my webapplication. So, i then checked the logs of Elasticbean stalk for errors. This is the error it shows me when i try to deploy

```<code>-------------------------------------
/var/log/httpd/error_log
-------------------------------------
[Fri May 22 12:53:57.768095 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]   File "/usr/lib64/python3.6/pickle.py", line 1338, in load_global
[Fri May 22 12:53:57.768098 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]     klass = self.find_class(module, name)
[Fri May 22 12:53:57.768104 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]   File "/usr/lib64/python3.6/pickle.py", line 1388, in find_class
[Fri May 22 12:53:57.768107 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]     __import__(module, level=0)
[Fri May 22 12:53:57.768127 2020] [:error] [pid 8177] [remote 172.31.23.26:48093] ModuleNotFoundError: No module named 'numpy.random._pickle'
[Fri May 22 12:53:57.768138 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]
[Fri May 22 12:53:57.768141 2020] [:error] [pid 8177] [remote 172.31.23.26:48093] During handling of the above exception, another exception occurred:
[Fri May 22 12:53:57.768144 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]
[Fri May 22 12:53:57.768150 2020] [:error] [pid 8177] [remote 172.31.23.26:48093] Traceback (most recent call last):
[Fri May 22 12:53:57.768177 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]   File "/opt/python/current/app/application.py", line 81, in <module>
[Fri May 22 12:53:57.768181 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]     model_d2v = d2v.load_d2v('doc2vec_model', ENV)
[Fri May 22 12:53:57.768187 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]   File "/opt/python/current/app/microservices/d2v_services.py", line 21, in load_d2v
[Fri May 22 12:53:57.768190 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]     model=joblib.load(model_name)
[Fri May 22 12:53:57.768196 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]   File "/opt/python/run/venv/local/lib/python3.6/site-packages/joblib/numpy_pickle.py", line 605, in load
[Fri May 22 12:53:57.768199 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]     obj = _unpickle(fobj, filename, mmap_mode)
[Fri May 22 12:53:57.768204 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]   File "/opt/python/run/venv/local/lib/python3.6/site-packages/joblib/numpy_pickle.py", line 529, in _unpickle
[Fri May 22 12:53:57.768208 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]     obj = unpickler.load()
[Fri May 22 12:53:57.768213 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]   File "/usr/lib64/python3.6/pickle.py", line 1050, in load
[Fri May 22 12:53:57.768216 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]     dispatch[key[0]](self)
[Fri May 22 12:53:57.768222 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]   File "/usr/lib64/python3.6/pickle.py", line 1338, in load_global
[Fri May 22 12:53:57.768230 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]     klass = self.find_class(module, name)
[Fri May 22 12:53:57.768237 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]   File "/usr/lib64/python3.6/pickle.py", line 1388, in find_class
[Fri May 22 12:53:57.768240 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]     __import__(module, level=0)
[Fri May 22 12:53:57.768250 2020] [:error] [pid 8177] [remote 172.31.23.26:48093] ModuleNotFoundError: No module named 'numpy.random._pickle'
[Fri May 22 12:54:07.192783 2020] [:error] [pid 8177] loading...doc2vec_model
[Fri May 22 12:54:12.237091 2020] [:error] [pid 8177] [remote 172.31.15.191:48093] mod_wsgi (pid=8177): Target WSGI script '/opt/python/current/app/application.py' cannot be loaded as Python module.
[Fri May 22 12:54:12.237334 2020] [:error] [pid 8177] [remote 172.31.15.191:48093] mod_wsgi (pid=8177): Exception occurred processing WSGI script '/opt/python/current/app/application.py'.
[Fri May 22 12:54:12.238604 2020] [:error] [pid 8177] [remote 172.31.15.191:48093] Traceback (most recent call last):
[Fri May 22 12:54:12.238658 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/opt/python/current/app/microservices/d2v_services.py", line 14, in load_d2v
[Fri May 22 12:54:12.238664 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     model=joblib.load(model_name)
[Fri May 22 12:54:12.238675 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/opt/python/run/venv/local/lib/python3.6/site-packages/joblib/numpy_pickle.py", line 605, in load
[Fri May 22 12:54:12.238679 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     obj = _unpickle(fobj, filename, mmap_mode)
[Fri May 22 12:54:12.238686 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/opt/python/run/venv/local/lib/python3.6/site-packages/joblib/numpy_pickle.py", line 529, in _unpickle
[Fri May 22 12:54:12.238690 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     obj = unpickler.load()
[Fri May 22 12:54:12.238695 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/usr/lib64/python3.6/pickle.py", line 1050, in load
[Fri May 22 12:54:12.238699 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     dispatch[key[0]](self)
[Fri May 22 12:54:12.238705 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/usr/lib64/python3.6/pickle.py", line 1338, in load_global
[Fri May 22 12:54:12.238709 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     klass = self.find_class(module, name)
[Fri May 22 12:54:12.238714 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/usr/lib64/python3.6/pickle.py", line 1388, in find_class
[Fri May 22 12:54:12.238718 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     __import__(module, level=0)
[Fri May 22 12:54:12.238737 2020] [:error] [pid 8177] [remote 172.31.15.191:48093] ModuleNotFoundError: No module named 'numpy.random._pickle'
[Fri May 22 12:54:12.238793 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]
[Fri May 22 12:54:12.238800 2020] [:error] [pid 8177] [remote 172.31.15.191:48093] During handling of the above exception, another exception occurred:
[Fri May 22 12:54:12.238803 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]
[Fri May 22 12:54:12.238810 2020] [:error] [pid 8177] [remote 172.31.15.191:48093] Traceback (most recent call last):
[Fri May 22 12:54:12.238840 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/opt/python/current/app/application.py", line 81, in <module>
[Fri May 22 12:54:12.238845 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     model_d2v = d2v.load_d2v('doc2vec_model', ENV)
[Fri May 22 12:54:12.238851 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/opt/python/current/app/microservices/d2v_services.py", line 21, in load_d2v
[Fri May 22 12:54:12.238855 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     model=joblib.load(model_name)
[Fri May 22 12:54:12.238872 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/opt/python/run/venv/local/lib/python3.6/site-packages/joblib/numpy_pickle.py", line 605, in load
[Fri May 22 12:54:12.238883 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     obj = _unpickle(fobj, filename, mmap_mode)
[Fri May 22 12:54:12.238889 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/opt/python/run/venv/local/lib/python3.6/site-packages/joblib/numpy_pickle.py", line 529, in _unpickle
[Fri May 22 12:54:12.238892 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     obj = unpickler.load()
[Fri May 22 12:54:12.238897 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/usr/lib64/python3.6/pickle.py", line 1050, in load
[Fri May 22 12:54:12.238901 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     dispatch[key[0]](self)
[Fri May 22 12:54:12.238906 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/usr/lib64/python3.6/pickle.py", line 1338, in load_global
[Fri May 22 12:54:12.238909 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     klass = self.find_class(module, name)
[Fri May 22 12:54:12.238914 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/usr/lib64/python3.6/pickle.py", line 1388, in find_class
[Fri May 22 12:54:12.238917 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     __import__(module, level=0)
[Fri May 22 12:54:12.238928 2020] [:error] [pid 8177] [remote 172.31.15.191:48093] ModuleNotFoundError: No module named 'numpy.random._pickle'
[Fri May 22 12:56:22.918445 2020] [mpm_prefork:notice] [pid 8172] AH00169: caught SIGTERM, shutting down
</code>```

I tried importing 'numpy.random._pickle' but it didn't work.

The code I used for loading the model:

```<code>import subprocess
from sklearn.externals import joblib
import gensim

model = load_d2v("doc2vec_model")

def load_d2v(fname):
    model_name = fname
    s3_base_path='s3://sd-flikku/datalake/current_doc2vec_model'
    path = s3_base_path+'/'+model_name
    command = "aws s3 cp {} {}".format(path,model_name).split()
    print('loading...'+model_name)
    subprocess.call(command)
    model=joblib.load(model_name)
    return model
</code>```

Can you please help me with this? Thanks in advance.

答:
Upgrade the numpy library using:

```<code>pip install numpy --upgrade
</code>```

Occurs when the model was built with a specific version of the library and tested with other versions.

Body:
I have a doc2vec model which drives my recommendation app. I have built the doc2vec model and saved into s3 bucket. Now when i open the webapp the model should be loaded back from s3 but this not happenning. I used AWS Elasticbean stalk to deploy my webapplication. So, i then checked the logs of Elasticbean stalk for errors. This is the error it shows me when i try to deploy

-------------------------------------
/var/log/httpd/error_log
-------------------------------------
[Fri May 22 12:53:57.768095 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]   File "/usr/lib64/python3.6/pickle.py", line 1338, in load_global
[Fri May 22 12:53:57.768098 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]     klass = self.find_class(module, name)
[Fri May 22 12:53:57.768104 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]   File "/usr/lib64/python3.6/pickle.py", line 1388, in find_class
[Fri May 22 12:53:57.768107 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]     __import__(module, level=0)
[Fri May 22 12:53:57.768127 2020] [:error] [pid 8177] [remote 172.31.23.26:48093] ModuleNotFoundError: No module named 'numpy.random._pickle'
[Fri May 22 12:53:57.768138 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]
[Fri May 22 12:53:57.768141 2020] [:error] [pid 8177] [remote 172.31.23.26:48093] During handling of the above exception, another exception occurred:
[Fri May 22 12:53:57.768144 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]
[Fri May 22 12:53:57.768150 2020] [:error] [pid 8177] [remote 172.31.23.26:48093] Traceback (most recent call last):
[Fri May 22 12:53:57.768177 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]   File "/opt/python/current/app/application.py", line 81, in <module>
[Fri May 22 12:53:57.768181 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]     model_d2v = d2v.load_d2v('doc2vec_model', ENV)
[Fri May 22 12:53:57.768187 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]   File "/opt/python/current/app/microservices/d2v_services.py", line 21, in load_d2v
[Fri May 22 12:53:57.768190 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]     model=joblib.load(model_name)
[Fri May 22 12:53:57.768196 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]   File "/opt/python/run/venv/local/lib/python3.6/site-packages/joblib/numpy_pickle.py", line 605, in load
[Fri May 22 12:53:57.768199 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]     obj = _unpickle(fobj, filename, mmap_mode)
[Fri May 22 12:53:57.768204 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]   File "/opt/python/run/venv/local/lib/python3.6/site-packages/joblib/numpy_pickle.py", line 529, in _unpickle
[Fri May 22 12:53:57.768208 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]     obj = unpickler.load()
[Fri May 22 12:53:57.768213 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]   File "/usr/lib64/python3.6/pickle.py", line 1050, in load
[Fri May 22 12:53:57.768216 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]     dispatch[key[0]](self)
[Fri May 22 12:53:57.768222 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]   File "/usr/lib64/python3.6/pickle.py", line 1338, in load_global
[Fri May 22 12:53:57.768230 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]     klass = self.find_class(module, name)
[Fri May 22 12:53:57.768237 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]   File "/usr/lib64/python3.6/pickle.py", line 1388, in find_class
[Fri May 22 12:53:57.768240 2020] [:error] [pid 8177] [remote 172.31.23.26:48093]     __import__(module, level=0)
[Fri May 22 12:53:57.768250 2020] [:error] [pid 8177] [remote 172.31.23.26:48093] ModuleNotFoundError: No module named 'numpy.random._pickle'
[Fri May 22 12:54:07.192783 2020] [:error] [pid 8177] loading...doc2vec_model
[Fri May 22 12:54:12.237091 2020] [:error] [pid 8177] [remote 172.31.15.191:48093] mod_wsgi (pid=8177): Target WSGI script '/opt/python/current/app/application.py' cannot be loaded as Python module.
[Fri May 22 12:54:12.237334 2020] [:error] [pid 8177] [remote 172.31.15.191:48093] mod_wsgi (pid=8177): Exception occurred processing WSGI script '/opt/python/current/app/application.py'.
[Fri May 22 12:54:12.238604 2020] [:error] [pid 8177] [remote 172.31.15.191:48093] Traceback (most recent call last):
[Fri May 22 12:54:12.238658 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/opt/python/current/app/microservices/d2v_services.py", line 14, in load_d2v
[Fri May 22 12:54:12.238664 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     model=joblib.load(model_name)
[Fri May 22 12:54:12.238675 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/opt/python/run/venv/local/lib/python3.6/site-packages/joblib/numpy_pickle.py", line 605, in load
[Fri May 22 12:54:12.238679 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     obj = _unpickle(fobj, filename, mmap_mode)
[Fri May 22 12:54:12.238686 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/opt/python/run/venv/local/lib/python3.6/site-packages/joblib/numpy_pickle.py", line 529, in _unpickle
[Fri May 22 12:54:12.238690 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     obj = unpickler.load()
[Fri May 22 12:54:12.238695 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/usr/lib64/python3.6/pickle.py", line 1050, in load
[Fri May 22 12:54:12.238699 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     dispatch[key[0]](self)
[Fri May 22 12:54:12.238705 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/usr/lib64/python3.6/pickle.py", line 1338, in load_global
[Fri May 22 12:54:12.238709 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     klass = self.find_class(module, name)
[Fri May 22 12:54:12.238714 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/usr/lib64/python3.6/pickle.py", line 1388, in find_class
[Fri May 22 12:54:12.238718 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     __import__(module, level=0)
[Fri May 22 12:54:12.238737 2020] [:error] [pid 8177] [remote 172.31.15.191:48093] ModuleNotFoundError: No module named 'numpy.random._pickle'
[Fri May 22 12:54:12.238793 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]
[Fri May 22 12:54:12.238800 2020] [:error] [pid 8177] [remote 172.31.15.191:48093] During handling of the above exception, another exception occurred:
[Fri May 22 12:54:12.238803 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]
[Fri May 22 12:54:12.238810 2020] [:error] [pid 8177] [remote 172.31.15.191:48093] Traceback (most recent call last):
[Fri May 22 12:54:12.238840 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/opt/python/current/app/application.py", line 81, in <module>
[Fri May 22 12:54:12.238845 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     model_d2v = d2v.load_d2v('doc2vec_model', ENV)
[Fri May 22 12:54:12.238851 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/opt/python/current/app/microservices/d2v_services.py", line 21, in load_d2v
[Fri May 22 12:54:12.238855 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     model=joblib.load(model_name)
[Fri May 22 12:54:12.238872 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/opt/python/run/venv/local/lib/python3.6/site-packages/joblib/numpy_pickle.py", line 605, in load
[Fri May 22 12:54:12.238883 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     obj = _unpickle(fobj, filename, mmap_mode)
[Fri May 22 12:54:12.238889 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/opt/python/run/venv/local/lib/python3.6/site-packages/joblib/numpy_pickle.py", line 529, in _unpickle
[Fri May 22 12:54:12.238892 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     obj = unpickler.load()
[Fri May 22 12:54:12.238897 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/usr/lib64/python3.6/pickle.py", line 1050, in load
[Fri May 22 12:54:12.238901 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     dispatch[key[0]](self)
[Fri May 22 12:54:12.238906 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/usr/lib64/python3.6/pickle.py", line 1338, in load_global
[Fri May 22 12:54:12.238909 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     klass = self.find_class(module, name)
[Fri May 22 12:54:12.238914 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]   File "/usr/lib64/python3.6/pickle.py", line 1388, in find_class
[Fri May 22 12:54:12.238917 2020] [:error] [pid 8177] [remote 172.31.15.191:48093]     __import__(module, level=0)
[Fri May 22 12:54:12.238928 2020] [:error] [pid 8177] [remote 172.31.15.191:48093] ModuleNotFoundError: No module named 'numpy.random._pickle'
[Fri May 22 12:56:22.918445 2020] [mpm_prefork:notice] [pid 8172] AH00169: caught SIGTERM, shutting down

I tried importing 'numpy.random._pickle' but it didn't work.

The code I used for loading the model:

import subprocess
from sklearn.externals import joblib
import gensim

model = load_d2v("doc2vec_model")

def load_d2v(fname):
    model_name = fname
    s3_base_path='s3://sd-flikku/datalake/current_doc2vec_model'
    path = s3_base_path+'/'+model_name
    command = "aws s3 cp {} {}".format(path,model_name).split()
    print('loading...'+model_name)
    subprocess.call(command)
    model=joblib.load(model_name)
    return model

Can you please help me with this? Thanks in advance.

Body:
Upgrade the numpy library using:

pip install numpy --upgrade

Occurs when the model was built with a specific version of the library and tested with other versions.


来源: stackexchange

问:
Post Action method overload with same route name in ASP.Net Web API Controller
Is it possible to have two actions with same route name and same method but different parameter?
I have tried this:

```<code>[HttpPost]
[Route("gstr4")]
public HttpResponseMessage SubmitGSTR4([FromBody] RequestPayloadWithoutSign requestPayload)
{ }

[HttpPost]
[Route("gstr4")]
public HttpResponseMessage FileGSTR4([FromBody] RequestPayloadWithSign requestPayload)
{ }
</code>```

I received a Status Code of 500 (InternalServerError) and here is raw response:

```<code>{"Message":"An error has occurred.","ExceptionMessage":"Multiple actions were found that match the request: \r\nFileGSTR4 on type APIPortal.Controllers.GSTR4Controller\r\nSubmitGSTR4 on type APIPortal.Controllers.GSTR4Controller","ExceptionType":"System.InvalidOperationException","StackTrace":"   at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext)\r\n   at System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext)\r\n   at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"}
</code>```

答:
It is only possible with different HTTP verbs. Otherwise, you have to define different routes.

https://learn.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

ContentLicense: CC BY-SA 4.0

Body:
Is it possible to have two actions with same route name and same method but different parameter?
I have tried this:

[HttpPost]
[Route("gstr4")]
public HttpResponseMessage SubmitGSTR4([FromBody] RequestPayloadWithoutSign requestPayload)
{ }

[HttpPost]
[Route("gstr4")]
public HttpResponseMessage FileGSTR4([FromBody] RequestPayloadWithSign requestPayload)
{ }

I received a Status Code of 500 (InternalServerError) and here is raw response:

{"Message":"An error has occurred.","ExceptionMessage":"Multiple actions were found that match the request: \r\nFileGSTR4 on type APIPortal.Controllers.GSTR4Controller\r\nSubmitGSTR4 on type APIPortal.Controllers.GSTR4Controller","ExceptionType":"System.InvalidOperationException","StackTrace":"   at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext)\r\n   at System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext)\r\n   at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"}


问:
Format Spring CommandObject variable on the front end
How do I format a value that is fetched from a command object on front end.

Its an SSN value which comes from the DB without any "-" (Hyphens). How do I convert this?

example: Convert 123456789 into 123-45-6789. Also the in the backing bean this field is an Int.

答:
How about creating a custom property editor?
Spring uses custom property editors to format special data, like SSN.

An IntegerPropertyEditor looks like this:

```<code>package com.pnt.common.propertyeditor;

import java.beans.PropertyEditorSupport;
import com.pnt.util.number.NumUtils;

public class IntegerPropertyEditor extends PropertyEditorSupport {

//private static final Log logger = LogFactory.getLog(IntegerPropertyEditor.class);

public void setValue(Object value) {

    if (value==null) {
        super.setValue(null);
    }

    else if (value instanceof Integer) {
        super.setValue(value);
    }

    else if (value instanceof String) {
        setValue(NumUtils.stringToInteger((String)value));
    }

    else {
        super.setValue(NumUtils.stringToInteger(value.toString()));
    }
}

public void setAsText(String text) {
    setValue(NumUtils.stringToInteger(text.replaceAll(" ", "")));
}

public String getAsText() {
    Integer value = (Integer)getValue();
    if (value != null){
        String t = value.toString();
        int k = 1;
        for (int i = t.length() - 1; i >= 0; i--) {
            if (k % 3 == 0 && i != 0)
                t = t.substring(0, i) + " " + t.substring(i);
            k++;
        }
        return t;

    }
    else
        return "";
}
}
</code>```

And you have to register it in the controller's initBinder() method:

```<code>protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder ){
    try {
        binder.registerCustomEditor(Integer.class, "ssnField", new IntegerPropertyEditor());
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
</code>```

Where "ssnField" is the name of the field.

Now all you have to do is tweak the PropertyEditor to match your format.

ContentLicense: CC BY-SA 3.0

Body:
How about creating a custom property editor?
Spring uses custom property editors to format special data, like SSN.

An IntegerPropertyEditor looks like this:

package com.pnt.common.propertyeditor;

import java.beans.PropertyEditorSupport;
import com.pnt.util.number.NumUtils;

public class IntegerPropertyEditor extends PropertyEditorSupport {

//private static final Log logger = LogFactory.getLog(IntegerPropertyEditor.class);

public void setValue(Object value) {

    if (value==null) {
        super.setValue(null);
    }

    else if (value instanceof Integer) {
        super.setValue(value);
    }

    else if (value instanceof String) {
        setValue(NumUtils.stringToInteger((String)value));
    }

    else {
        super.setValue(NumUtils.stringToInteger(value.toString()));
    }
}

public void setAsText(String text) {
    setValue(NumUtils.stringToInteger(text.replaceAll(" ", "")));
}

public String getAsText() {
    Integer value = (Integer)getValue();
    if (value != null){
        String t = value.toString();
        int k = 1;
        for (int i = t.length() - 1; i >= 0; i--) {
            if (k % 3 == 0 && i != 0)
                t = t.substring(0, i) + " " + t.substring(i);
            k++;
        }
        return t;

    }
    else
        return "";
}
}

And you have to register it in the controller's initBinder() method:

protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder ){
    try {
        binder.registerCustomEditor(Integer.class, "ssnField", new IntegerPropertyEditor());
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

Where "ssnField" is the name of the field.

Now all you have to do is tweak the PropertyEditor to match your format.


问:
R time series from day to month
I'm new to R and i need help with an R time series. I have daily data that I want to sum up to one month.
How can I sum up the days to a month?
In the end I want to use the TS as monthly frequency.

```<code>library(data.table)

#read csv "ProductList-B1-134564"
coffeedata = fread("https://raw.githubusercontent.com/Skruff80/FFHS/master/KantineWII/ProductList-B1-134564_w3_original.csv")

#Formating date
coffeedata$Date = as.Date(coffeedata$Date, "%d.%m.%Y")

#dailycounter
countcoffee = function(timeStamps) {
Dates = as.Date(strftime(coffeedata$Date, "%Y-%m-%d"))
allDates = seq(from = min(Dates), to = max(Dates), by = "day")
coffee.count = sapply(allDates, FUN = function(X) sum(Dates == X))
data.frame(day = allDates, coffee.count = coffee.count)}
dailycounter = countcoffee(df$coffee.date)

#time series
demand <- ts(dailycounter$coffee.count, start = c(2018, 1), frequency = 365)
plot(demand, type="l", xlab = "Year", col = "orange", lwd = "1", ylab = "Products a day")
</code>```

I appreciate your help.

Title: R time series from day to month

Body:
I'm new to R and i need help with an R time series. I have daily data that I want to sum up to one month.
How can I sum up the days to a month?
In the end I want to use the TS as monthly frequency.

library(data.table)

#read csv "ProductList-B1-134564"
coffeedata = fread("https://raw.githubusercontent.com/Skruff80/FFHS/master/KantineWII/ProductList-B1-134564_w3_original.csv")

#Formating date
coffeedata$Date = as.Date(coffeedata$Date, "%d.%m.%Y")

#dailycounter
countcoffee = function(timeStamps) {
Dates = as.Date(strftime(coffeedata$Date, "%Y-%m-%d"))
allDates = seq(from = min(Dates), to = max(Dates), by = "day")
coffee.count = sapply(allDates, FUN = function(X) sum(Dates == X))
data.frame(day = allDates, coffee.count = coffee.count)}
dailycounter = countcoffee(df$coffee.date)

#time series
demand <- ts(dailycounter$coffee.count, start = c(2018, 1), frequency = 365)
plot(demand, type="l", xlab = "Year", col = "orange", lwd = "1", ylab = "Products a day")

I appreciate your help.

Body:
Since you already are reading your data in a data.table-format, using fread(), why not stick with data.table?

code

#set Date as posixCT
coffeedata[, Date := as.POSIXct( Date, format = "%d.%m.%Y %H:%M" ) ]
#summarise to monthly total of lines
coffeedata[, .( total = .N ), by = .( format( Date, "%Y-%m" ) )]

output

#     format total
# 1: 2020-05  1223
# 2: 2020-04  1666
# 3: 2020-03  2174
# 4: 2020-02  2660
# 5: 2020-01  2948
# 6: 2019-12  2127
# 7: 2019-11  2921
# 8: 2019-10  2954
# 9: 2019-09  2827
# 10: 2019-08  2310
# 11: 2019-07  2940
# 12: 2019-06  2544
# 13: 2019-05  2984
# 14: 2019-04  2676
# 15: 2019-03  2810
# 16: 2019-02  2660
# 17: 2019-01  2948
# 18: 2018-12  2127
# 19: 2018-11  2921
# 20: 2018-10  3291
# 21: 2018-09  2020
# 22: 2018-08  1771
# 23: 2018-07  2576
# 24: 2018-06  2569
# 25: 2018-05  2553
# 26: 2018-04  1990
# 27: 2018-03  2472
# 28: 2018-02  2091
# 29: 2018-01   892
#      format total


问:
Send jQuery range slider min/max value to PHP
I want get value range slider each min/max value to PHP. I don't know how and don't know why. I am using the jQueryUI range slider: https://jqueryui.com/slider/#range

  <form method="POST" action="value.php">
    <input type="text" id="amount" name="slide-value" />

    <input type="submit" name="submit" />
  </form>
  <?php
    value = (float)$_POST['slide-value'];
    echo $value;
  ?>

```

<pre class="lang-js prettyprint-override"><code>$(function() {
  $("#slider-range").slider({
    range: true,
    min: 0,
    max: 500,
    values: [0, 300],
    slide: function(event, ui) {
      var value1 = $("#slider-range").slider("values", 0);
      var value2 = $("#slider-range").slider("values", 1);
      $("#amount").val("$" + ui.values[0] + " - $" + ui.values[1]);
    }
  });

  $("#amount").val("$" + $("#slider-range").slider("values", 0) + " - $" + $("#slider-range").slider("values", 1));
});
</code>```

答:
To separate the min/max values create two new fields in your form and update them separately when the slider moves. Note that I made the fields visible in this example for clarity, but they can be changed to hidden if required. Also note that I made a couple of changes to improve performance of the code, such as caching the jQuery objects. Try this:

jQuery($ => {
  let $amount = $('#amount'),
    $min = $('#min'),
    $max = $('#max');

  let $slider = $("#slider-range").slider({
    range: true,
    min: 0,
    max: 500,
    values: [0, 300],
    slide: function(event, ui) {
      $amount.val(`값${ui.values[0]} - $${ui.values[1]}`);
      $min.val(ui.values[0]);
      $max.val(ui.values[1]);
    }
  });

  $amount.val("값" + $slider.slider("values", 0) + " - $" + $slider.slider("values", 1));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />
<form method="POST" action="value.php">
  <input type="text" id="amount" name="slide-value" /><br/>
  <input type="text" id="min" value="0" />
  <input type="text" id="max" value="300" />
  <div id="slider-range" style="width: 500px;"></div>
  <input type="submit" name="submit" />
</form></code>```

Body:
I want get value range slider each min/max value to PHP. I don't know how and don't know why. I am using the jQueryUI range slider: https://jqueryui.com/slider/#range

  <form method="POST" action="value.php">
    <input type="text" id="amount" name="slide-value" />

    <input type="submit" name="submit" />
  </form>
  <?php
    value = (float)$_POST['slide-value'];
    echo $value;
  ?>

$(function() {
  $("#slider-range").slider({
    range: true,
    min: 0,
    max: 500,
    values: [0, 300],
    slide: function(event, ui) {
      var value1 = $("#slider-range").slider("values", 0);
      var value2 = $("#slider-range").slider("values", 1);
      $("#amount").val("$" + ui.values[0] + " - $" + ui.values[1]);
    }
  });

  $("#amount").val("$" + $("#slider-range").slider("values", 0) + " - $" + $("#slider-range").slider("values", 1));
});

Body:
To separate the min/max values create two new fields in your form and update them separately when the slider moves. Note that I made the fields visible in this example for clarity, but they can be changed to hidden if required. Also note that I made a couple of changes to improve performance of the code, such as caching the jQuery objects. Try this:

jQuery($ => {
  let $amount = $('#amount'),
    $min = $('#min'),
    $max = $('#max');

  let $slider = $("#slider-range").slider({
    range: true,
    min: 0,
    max: 500,
    values: [0, 300],
    slide: function(event, ui) {
      $amount.val(`값${ui.values[0]} - $${ui.values[1]}`);
      $min.val(ui.values[0]);
      $max.val(ui.values[1]);
    }
  });

  $amount.val("값" + $slider.slider("values", 0) + " - $" + $slider.slider("values", 1));
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />
<form method="POST" action="value.php">
  <input type="text" id="amount" name="slide-value" /><br/>
  <input type="text" id="min" value="0" />
  <input type="text" id="max" value="300" />
  <div id="slider-range" style="width: 500px;"></div>
  <input type="submit" name="submit" />
</form>


问:
Music discord.js bot : The "url" argument must be of type string
I am trying to make a working music Discord bot with discord.js and ffmpeg but I keep getting the error TypeError [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string. Received type undefined. The error occurs when I try the command play, after the bot joins the voice channel and send   |  En cours de lecture : ${song.title}. The command is suppose to work either with an URL or with a search string. It produces the error in the 2 cases.

Here is the code of the command and the two functions used :

if (command === "play" || command === "p") {

    const args = args[1] ? args[1].replace(/<(.+)>/g, "$1") : "";
    const searchString = args.slice(1).join(" ");
    if (!args[1]) {
      return message.channel.send('Il faut spécifier une URL !')
        .catch(console.error);
    }
    const url = args[1].toString();
    const serverQueue = queue.get(message.guild.id);
    var voiceChannel = message.member.voice.channel;
    if (!voiceChannel) return message.channel.send("Tu dois être dans un salon vocal pour utiliser cette commande !");
    const permissions = voiceChannel.permissionsFor(message.client.user);
    if (!permissions.has("CONNECT")) {
      return message.channel.send("J'ai besoin de la permission **`CONNECT`** pour cette commande");
    }
    if (!permissions.has("SPEAK")) {
      return message.channel.send("J'ai besoin de la permission **`SPEAK`** pour parler");
    }

    if (url.match(/^https?:\/\/(www.youtube.com|youtube.com)\/playlist(.*)$/)) {
      const playlist = await youtube.getPlaylist(url);
      const videos = await playlist.getVideos();
      for (const video of Object.values(videos)) {
        const video2 = await youtube.getVideoByID(video.id); // eslint-disable-line no-await-in-loop
        await handleVideo(video2, message, voiceChannel, true); // eslint-disable-line no-await-in-loop
      }
      return message.channel.send(`:white_check_mark:  **|**  Playlist: **\`${playlist.title}\`** a été ajouté à la playlist !`);
    } else {
      try {
        var video = await youtube.getVideo(url);
      } catch (error) {
        try {
          var videos = await youtube.searchVideos(searchString, 10);
          let index = 0;
          // eslint-disable-next-line max-depth
          try {

          } catch (err) {
            console.error(err);
            return message.channel.send("Annulation de la commande...");
          }
          const videoIndex = parseInt(1);
          var video = await youtube.getVideoByID(videos[videoIndex - 1].id);
        } catch (err) {
          console.error(err);
          return message.channel.send("  **|**  Je n'obtiens aucun résultat :pensive:");
        }
      }
      return handleVideo(video, message, voiceChannel);
    }
}

async function handleVideo(video, message, voiceChannel, playlist = false) {
  const serverQueue = queue.get(message.guild.id);
  const song = {
    id: video.id,
    title: Util.escapeMarkdown(video.title),
    url: `https://www.youtube.com/watch?v=${video.id}`
  };
  console.log(song.url)
  if (!serverQueue) {
    const queueConstruct = {
      textChannel: message.channel,
      voiceChannel: voiceChannel,
      connection: null,
      songs: [],
      volume: 5,
      playing: true
    };
    queue.set(message.guild.id, queueConstruct);

    queueConstruct.songs.push(song);

    try {
      var connection = await voiceChannel.join();
      queueConstruct.connection = connection;
      play(message.guild, queueConstruct.songs[0]);
    } catch (error) {
      console.error(`Je ne peux pas rejoindre le salon vocal : ${error}`);
      queue.delete(message.guild.id);
      return message.channel.send(`Je ne peux pas rejoindre le salon vocal : **\`${error}\`**`);
    }
  } else {
    serverQueue.songs.push(song);
    console.log(serverQueue.songs);
    if (playlist) return undefined;
    else return message.channel.send(`:white_check_mark:  **|** **\`${song.title}\`** a été ajouté à la playlist !`);
  }
  return undefined;
}

function play(guild, song) {
  const serverQueue = queue.get(guild.id);

  if (!song) {
    serverQueue.voiceChannel.leave();
    queue.delete(guild.id);
    return;
  }

  const dispatcher = serverQueue.connection.play(ytdl(song.url))
    .on("end", reason => {
      if (reason === "Stream is not generating quickly enough.") console.log("Musique terminée.");
      else console.log(reason);
      serverQueue.songs.shift();
      play(guild, serverQueue.songs[0]);
    })
    .on("error", error => console.error(error));
  dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);

  serverQueue.textChannel.send(`  **|**  En cours de lecture : **\`${song.title}\`**`);
};
```

答:
Try this :

Type npm list ytdl-core into your console and if the the version is not ytdl-core@2.1.5 or newer type npm i ytdl-core@latest.

That fixed my issue with this.


问:
What is the difference between signed and unsigned variables?
I have seen these mentioned in the context of C and C++, but what is the difference between signed and unsigned variables? </p>

答:
Signed variables, such as signed integers will allow you to represent numbers both in the positive and negative ranges.

Unsigned variables, such as unsigned integers, will only allow you to represent numbers in the positive and zero.

Unsigned and signed variables of the same type (such as int and byte) both have the same range (range of 65,536 and 256 numbers, respectively), but unsigned can represent a larger magnitude number than the corresponding signed variable.

For example, an unsigned byte can represent values from 0 to 255, while signed byte can represent -128 to 127.

Wikipedia page on Signed number representations explains the difference in the representation at the bit level, and the Integer (computer science) page provides a table of ranges for each signed/unsigned integer type.

OwnerDisplayName: coobird

LastEditorDisplayName: Diomidis Spinellis


问:
Removal of 30-40 millions record without affecting performance
I have a SQL Server database running in Full recovery.  I need to remove data (around 30-40 million records) but I cannot take the database offline as it's in constant use.  I also cannot switch it to Simple recovery mode incase anything happens and we lose live data.  When I try to remove the data in small chunks (around 2 million rows), the transaction log becomes extremely large and causes the process to become extremely slow.  Due to back-up jobs running at night, I only have a small timeframe.

Does anyone have any thoughts on how I can do this?  I thought about copying the table into another database (in Simple recovery mode) and then remove the data.  Is this a good idea?

There are 3 tables in question.  Campaign, Events and Targets.  Its the Events table that has the millions of records in and this is what takes the time to delete.  The all have the necessary relations via Id columns.

答:
What criteria do you use to select the 30-40 millions rows for deletion? If it is something fairly straightforward (such as 'older than 10 days') then you may be able to use SQL Server's table partitioning mechanism. There are some well-documented techniques (see link below) on partition switching to deal with use-cases similar to yours.

pjjH

http://msdn.microsoft.com/en-us/library/ms191160%28v=sql.100%29.aspx


问:
Cannot remove firestore listener
I call remove(), but listener is still working.
I want to call result(true) just onece.

var listener: ListenerRegistration!

func setListener(result:@escaping(Bool)-> Void){
    listener = ref.addSnapshotListener { (querySnapshot, err) in
        if ...
            result(true)
            self.removeListener
    }
}

func removeListener() {
    if listener != nil {
        listener.remove()
    }
}
```

答: I was setting mutable listener to the same variable. That was the reason.</p>

Title: Cannot remove firestore listener


问:
Visual Studio - Windows UI Library - set TargetPlatformMinVersion and TargetPlatformVersion (C#)
I would like to try the Windows UI Library in Visual Studio. I have followed the installation instructions from Microsoft (Link: https://learn.microsoft.com/en-us/windows/apps/winui/winui2/getting-started). Unfortunately I can't find the place where I can set the "TargetPlatformMinVersion" and the "TargetPlatformVersion".

I found this picture, but I cannot find these settings.

If I skip this step, I unfortunately get an error message.

Thanks a lot

答:
First Approach:

Please follow the instruction of how to change TargetplatformVersion:

1) Right-click on your project in Visual Studio

2) Select “Unload Project“, it will now appear as ProjectName (unavailable)

3) Right-click on the unloaded project and select “Edit projectName.csproj”

4) Locate the <TargetPlatformVersion> and <TargetPlatformMinVersion> items in the first <PropertyGroup>.

5) Change the TargetPlatformMinVersion to the version that you want.

6) Now Save and Close the file

7) Select the “Load Project“ to Launch the project again.

Second Approach:

1) Close Your project in visual studio

2) Open Your projectName.csproj with Notepad or Notepad++

4) Locate the <TargetPlatformVersion> and <TargetPlatformMinVersion> items in the first <PropertyGroup>.

5) Change the TargetPlatformMinVersion to the version that you want.

6) Now Save and Close the file


问:
How do I determine if my mouse is over randomly spawning objects
I'm trying to implement a game which allows for the clicking of randomly spawning circles, which give you points everytime u click on it.

import pygame
import time
import random

pygame.init()
window = pygame.display.set_mode((800,600))

class Circle():

    def __init__(self, color, x, y, radius, width):
        self.color = color
        self.x = x
        self.y = y
        self.radius = radius
        self.width = width

    def draw(self, win, outline=None):
        pygame.draw.circle(win, self.color, (self.x, self.y), self.radius, self.width)

    def isOver(self, mouse):

        mouse = pygame.mouse.get_pos()
        # Pos is the mouse position or a tuple of (x,y) coordinates
        if mouse[0] > self.x and mouse[0] < self.x + self.radius:
            if mouse[1] > self.y and mouse[1] < self.y + self.width:
                return True

        return False

circles = []

clock = pygame.time.Clock()
FPS = 60

current_time = 0
next_circle_time = 0

run=True
while run:
    delta_ms = clock.tick()

    current_time += delta_ms
    if  current_time > next_circle_time:
        next_circle_time = current_time + 1000 # 1000 milliseconds (1 second)
        r = 20
        new_circle = Circle((255, 255, 255), random.randint(r, 800-r), random.randint(r, 600-r), r, r)
        circles.append(new_circle)
        print()

    window.fill((0, 0, 0))
    for c in circles:
        c.draw(window)
    pygame.display.update()

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            run=False
            pygame.quit()
            quit()

        if event.type == pygame.MOUSEBUTTONDOWN:
            if Circle.isOver(mouse):
                print('Clicked the circle')
```

<p>However, when I try to implement the last condition, if Circle.isOver(mouse):...
I get this error</p>

```TypeError: isOver() missing 1 required positional argument: 'mouse'
```

Anyone knows a solution to this? Any help is much appreciated!

答:
You have to iterate though the circle objects, which are contained in the list circles. Similar as you do when you draw the circle. You have to evaluate whether the mouse is on for each instance of the class Circle, rather than for the Class itself. Note, isOver is a Method Object and has to be invoked by Instance Objects.

Since the method is called when the MOUSEBUTTONDOWN event occurs, the current mouse position is provided in the event.pos attribute (See pygame.event):

```<code>run=True
while run:
    # [...]

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            run=False
            pygame.quit()
            quit()

        if event.type == pygame.MOUSEBUTTONDOWN:
            for c in circles:
                if c.isOver(event.pos):
                    print('Clicked the circle')
</code>```

Getting the mouse position by pygame.mouse.get_pos() in isOver, is superfluous, because the current mouse position is argument to the method.

I recommend to evaluate if the circle is clicked, by evaluating if the square of the Euclidean distance to the center  of the circle is less or equal the the square of the radius of the circle:

class Circle():

    # [...]

    def isOver(self, mouse):
        dx, dy = mouse[0] - self.x, mouse[1] - self.y
        return (dx*dx + dy*dy) <= self.radius*self.radius
```

Body:
I'm trying to implement a game which allows for the clicking of randomly spawning circles, which give you points everytime u click on it.

import pygame
import time
import random

pygame.init()
window = pygame.display.set_mode((800,600))

class Circle():

    def __init__(self, color, x, y, radius, width):
        self.color = color
        self.x = x
        self.y = y
        self.radius = radius
        self.width = width

    def draw(self, win, outline=None):
        pygame.draw.circle(win, self.color, (self.x, self.y), self.radius, self.width)

    def isOver(self, mouse):

        mouse = pygame.mouse.get_pos()
        # Pos is the mouse position or a tuple of (x,y) coordinates
        if mouse[0] > self.x and mouse[0] < self.x + self.radius:
            if mouse[1] > self.y and mouse[1] < self.y + self.width:
                return True

        return False

circles = []

clock = pygame.time.Clock()
FPS = 60

current_time = 0
next_circle_time = 0

run=True
while run:
    delta_ms = clock.tick()

    current_time += delta_ms
    if  current_time > next_circle_time:
        next_circle_time = current_time + 1000 # 1000 milliseconds (1 second)
        r = 20
        new_circle = Circle((255, 255, 255), random.randint(r, 800-r), random.randint(r, 600-r), r, r)
        circles.append(new_circle)
        print()

    window.fill((0, 0, 0))
    for c in circles:
        c.draw(window)
    pygame.display.update()

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            run=False
            pygame.quit()
            quit()

        if event.type == pygame.MOUSEBUTTONDOWN:
            if Circle.isOver(mouse):
                print('Clicked the circle')

However, when I try to implement the last condition, if Circle.isOver(mouse):...
I get this error

TypeError: isOver() missing 1 required positional argument: 'mouse'

Anyone knows a solution to this? Any help is much appreciated!

Body:
You have to iterate though the circle objects, which are contained in the list circles. Similar as you do when you draw the circle. You have to evaluate whether the mouse is on for each instance of the class Circle, rather than for the Class itself. Note, isOver is a Method Object and has to be invoked by Instance Objects.

Since the method is called when the MOUSEBUTTONDOWN event occurs, the current mouse position is provided in the event.pos attribute (See pygame.event):

run=True
while run:
    # [...]

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            run=False
            pygame.quit()
            quit()

        if event.type == pygame.MOUSEBUTTONDOWN:
            for c in circles:
                if c.isOver(event.pos):
                    print('Clicked the circle')

Getting the mouse position by pygame.mouse.get_pos() in isOver, is superfluous, because the current mouse position is argument to the method.

I recommend to evaluate if the circle is clicked, by evaluating if the square of the Euclidean distance to the center  of the circle is less or equal the the square of the radius of the circle:

class Circle():

    # [...]

    def isOver(self, mouse):
        dx, dy = mouse[0] - self.x, mouse[1] - self.y
        return (dx*dx + dy*dy) <= self.radius*self.radius


问:
How to log all files inside a folder
I want to navigate into a specific folder and then print all the files inside that specified folder using Google Apps Script:

function listFilesinSpecFolder(){
    var files = DriveApp.getFolderById("specific folder id placed here");
    while (files.hasNext()) {
      var file = files.next();
      Logger.log(file.getName());
    }
}
```
<p>When I tried to log this it gives me an error saying that hasNext() function is not a function.
But when I run the below code it gives me no errors...</p>
<pre class="lang-js prettyprint-override"><code>function folder(){
    var folders = DriveApp.getFolders();
    while (folders.hasNext()) {
      var folder = folders.next();
      Logger.log(folder.getName());
    }
}
</code>```

答:
var files = DriveApp.getFolderById("specific folder id placed here");
this does not return files, it will return a folder

instead try something like:

```<code>var folder = DriveApp.getFolderById("specific folder id placed here");

var files = folder.getFiles()
</code>```

Title: How to log all files inside a folder

Body:
I want to navigate into a specific folder and then print all the files inside that specified folder using Google Apps Script:

function listFilesinSpecFolder(){
    var files = DriveApp.getFolderById("specific folder id placed here");
    while (files.hasNext()) {
      var file = files.next();
      Logger.log(file.getName());
    }
}

When I tried to log this it gives me an error saying that hasNext() function is not a function.
But when I run the below code it gives me no errors...

function folder(){
    var folders = DriveApp.getFolders();
    while (folders.hasNext()) {
      var folder = folders.next();
      Logger.log(folder.getName());
    }
}

Body:
var files = DriveApp.getFolderById("specific folder id placed here");
this does not return files, it will return a folder

instead try something like:

var folder = DriveApp.getFolderById("specific folder id placed here");

var files = folder.getFiles()


答:
mouse is not defined when passing it to your function. There are other problems too but these are separate.

```<code>if event.type == pygame.MOUSEBUTTONDOWN:
        mouse = pygame.mouse.get_pos()
        for circle in circles:
            if circle.isOver(mouse):
                print('Clicked the circle')
</code>```

Title: How do I determine if my mouse is over randomly spawning objects

Body:
mouse is not defined when passing it to your function. There are other problems too but these are separate.

if event.type == pygame.MOUSEBUTTONDOWN:
        mouse = pygame.mouse.get_pos()
        for circle in circles:
            if circle.isOver(mouse):
                print('Clicked the circle')


问:
when i run my flutter app ,there emerge a unexpected problem , error :

What went wrong:
Could not determine the dependencies of task ':app:preDebugBuild'.

Could not resolve all task dependencies for configuration ':app:debugRuntimeClasspath'.
  Could not resolve project :path_provider_macos.
   Required by:
       project :app > project :path_provider
  Unable to find a matching configuration of project :path_provider_macos: None of the consumable configurations have attributes.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 2s
Finished with error: Gradle task assembleDebug failed with exit code 1

答: Some imports are missing. Try flutter pub get to update packages, or flutter pub cache repair, which will re-import all dependencies.


问:
mv: cannot stat ‘2001010000\r’: No such file or directory
I have a file abc.out and I need to read it and export the content to the named pipe. My shell script as below:

```<code>#!/bin/ksh -x

cd /home/robert/

if [[ -s abc.out ]]; then
  sleep 2
  for i in `cat abc.out`
  do
    mv -f $i ./abc_archive/x$i
    print `pwd`/abc_archive/x$i > /home/robert/pipe_abc
    sleep 1
  done
fi
</code>```

The content of abc.out file as below:

```<code>2001010000
2001010001
2001010002
</code>```

But when I run the script with the command sh abc.spt, error prompted as below:

```<code>mv: cannot stat ‘2001010000\r’: No such file or directory
</code>```

How can I fix this issue, many thanks!

答:
One option would be to pipe output through either sed or tr, to remove carriage returns:
sed -e 's/[\r\n]//g'
or
tr -d '\r' if you only want to remove \r

Body:
I have a file abc.out and I need to read it and export the content to the named pipe. My shell script as below:

#!/bin/ksh -x

cd /home/robert/

if [[ -s abc.out ]]; then
  sleep 2
  for i in `cat abc.out`
  do
    mv -f $i ./abc_archive/x$i
    print `pwd`/abc_archive/x$i > /home/robert/pipe_abc
    sleep 1
  done
fi

The content of abc.out file as below:

2001010000
2001010001
2001010002

But when I run the script with the command sh abc.spt, error prompted as below:

mv: cannot stat ‘2001010000\r’: No such file or directory

How can I fix this issue, many thanks!


问:
Apply CSS for all buttons except a specific ID
I have a code:

```<code>button {
  background: rgb(1, 81, 227);
  background: linear-gradient(
    90deg,
    rgba(1, 81, 227, 1) 35%,
    rgba(0, 90, 255, 1) 100%
  );
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 20px;
  margin: 4px 2px;
  cursor: pointer;
  border-radius: 6px;
}
</code>```

And a ton of buttons. I want to apply that css code for all buttons except two, with the IDs startAction & endAction.

How do I do that?

答:
button:not(#startAction):not(#endAction)

by @underscore_d

Body:
I have a code:

button {
  background: rgb(1, 81, 227);
  background: linear-gradient(
    90deg,
    rgba(1, 81, 227, 1) 35%,
    rgba(0, 90, 255, 1) 100%
  );
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 20px;
  margin: 4px 2px;
  cursor: pointer;
  border-radius: 6px;
}

And a ton of buttons. I want to apply that css code for all buttons except two, with the IDs startAction & endAction.

How do I do that?


问:
NGINX: Connect to backend with service name over Docker Compose's network from frontend
I have a simple dockerized flask backend that listens on 0.0.0.0:8080 and simple dockerized react frontend that sends a request to localhost:8080/api/v1.0/resource.
Now i want to run those containers in docker compose and issue the request to the service's name backend
The compose file looks like this:

```<code>version: '3'
services:
  backend:
    ports:
      - "8080:8080"
    image: "tobiaslocker/simple-dockerized-flask-backend:v0.1"
  frontend:
    ports:
      - "80:80"
    image: "tobiaslocker/simple-dockerized-react-frontend:v0.1"
</code>```

The NGINX configuration that works for requests to localhost:

```<code>server {
  listen 80;
  location / {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
  }
}
</code>```

The frontend sends the request axios.get('http://localhost:8080/api/v1.0/resource')

My questions:

How do i have to configure NGINX to be able to use the service name (e.g. backend)

How do i have to issue the request to match the configuration.

I am not sure how the proxy_pass will take effect when sending the request from the frontend and found it hard to debug.

Regards

答:
My Answers:

How do i have to configure NGINX to be able to use the service name (e.g. backend)

```<code>server {
    listen 80;
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
    location /api {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://backend:8080;
        proxy_ssl_session_reuse off;
        proxy_set_header Host $http_host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
    }
}
</code>```

Taken from here. Not sure if all settings are relevant but only setting proxy_pass didn't work for me.

How do i have to issue the request to match the configuration.

Same as before: axios.get('http://localhost:8080/api/v1.0/resource'), which makes sense, since it works locally and proxied with NGINX.

Body:
I have a simple dockerized flask backend that listens on 0.0.0.0:8080 and simple dockerized react frontend that sends a request to localhost:8080/api/v1.0/resource.
Now i want to run those containers in docker compose and issue the request to the service's name backend
The compose file looks like this:

version: '3'
services:
  backend:
    ports:
      - "8080:8080"
    image: "tobiaslocker/simple-dockerized-flask-backend:v0.1"
  frontend:
    ports:
      - "80:80"
    image: "tobiaslocker/simple-dockerized-react-frontend:v0.1"

The NGINX configuration that works for requests to localhost:

server {
  listen 80;
  location / {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
  }
}

The frontend sends the request axios.get('http://localhost:8080/api/v1.0/resource')

My questions:

How do i have to configure NGINX to be able to use the service name (e.g. backend)

How do i have to issue the request to match the configuration.

I am not sure how the proxy_pass will take effect when sending the request from the frontend and found it hard to debug.

Regards

Body:
My Answers:

How do i have to configure NGINX to be able to use the service name (e.g. backend)

server {
    listen 80;
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
    location /api {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://backend:8080;
        proxy_ssl_session_reuse off;
        proxy_set_header Host $http_host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
    }
}

Taken from here. Not sure if all settings are relevant but only setting proxy_pass didn't work for me.

How do i have to issue the request to match the configuration.

Same as before: axios.get('http://localhost:8080/api/v1.0/resource'), which makes sense, since it works locally and proxied with NGINX.


问:
Z-index issue in mozila firefox, in a css only page
I know this has been asked many times, and I have been searching for the answer in a lot of places but I can't seem to fix my code. Thank you for reading this because I'm going crazy here! First I had a different z-index problem with safari, than another with explorer, but now the z-index problem I'm having with mozila I can't fix in any way. I code in chrome, where it seems to work perfectly (for me it seems at least!)

I believe now it works more or less fine in most browsers but not on mozila. The idea of the page is to make (only with CSS because that's the only language supported by the website) a flipping book of several pages. I see some examples around of CSS only flipping cards (only one page), but not a book of more than one page. So I essentially overlap several "cards", in order to give this effect. You can see the demo from codepen here: pkrein/pen/qBOewem

Btw I do know this code is not as clean as it could be, but that's the way I figured to make a fuction like that works only with CSS, and I hope it will make sense for you.

Ok, so the matter is, the content inside the book pages is not "scrollable" on firefox. I guess this is indeed a z-index problem, because when I move any page outside the book, that is, from behind the rest of the content, it scrolls fine.

Let me know if I can give any more info that could help you understand my issue!

答:
I figured a possible solution for this. It's not quite the solution for the problem itself but it's something that can make what I want to do work.

The problem was: (what I had to remove in order to make it work):

(1) The div #content-holder holding all the text inside the flap

(2) The div .preparation-text inside the .preparation (that's the text I want to scroll). That was a scrolling div (.preparation) inside a non-scrolling div (.preparation-text). I always add a scrolling div inside a non-scrolling div in order to hide the scrollbar, by adding a high padding-right to the inside div. I know I can use code to hide the scrollbar but it do not work in all browsers.

How I fixed:

(1) I just removed the #content-holedr divs, since it was not strictly necessary.

(2) I removed the .preparation-text and transformed .preparation into a scrolling div. Then I just covered the scrollbar with an image of the same size and colors as the background (a print of the layout).


问:
I have accidentally deleted a page from Azure DevOps Wiki. How can I recover it?
I have accidentally deleted a Wiki-page from our repository in Azure DevOps.
(How) can I recover it?</p>

答:
That is not an option for us, since we will loose many changes that
  were made after the last version no. up until the date I accidentally
  deleted the wiki page.

You can choose Clone wiki to download the wiki repo to local machine.

Then use git commands(git revert or what) locally to get the deleted page, once you find the deleted page, publish it and add it back to Wiki page as a new commit.


问:
best practice to pass object between a grid and edit page in Angular 8+
so i have a data grid with a typical edit button. a very typical scenario where this a create-edit-account component that will also be used to edit and existing component.

so when i click edit on a grid i navigate to create-edit-account component to use it for edit purposes as well.

upon clicking edit i navigate like this

```<code> edit(account: BankAccount) {
this.router.navigateByUrl('/create-edit-account/' + account.id);
 }
</code>```

but at the time i clicked edit i have a populated account object i want to pass it to the create-edit-account component.

Question 1 what is the best practice in passing object while using parameterized routes in Angular 8+

Question 2 how we tell a component that it is being used for edit or add. i learned that if i pass "0" in the route's id param we can consider it is being used as "new" . but is there a better approach ?

i also have an ngrx store implemented . so  Question 3 would you recommend using an action dispatch with something called "account-updating" and passing in the object as an action param and subscribing it in the create-edit-account component and later dispatching "account-updated" action?

答:
Q1: you can use resolvers, they can fetch the data and pass it together with ActivatedRoute.

Q2: You should have an independent url for the edit mode, then the component can detect its state and switch between show / edit, also users can share desired page to show or to edit the component.

As an option you can have internal state in the component and a button that switches it to be show / edit. But in this case users always have to click the button.

Q3: For the thing you describe you should use ngrx effects. Then an effects listens to update request and performs it. Once the request has been finished it dispatches an action to set the updated entity in the store.

Body:
so i have a data grid with a typical edit button. a very typical scenario where this a create-edit-account component that will also be used to edit and existing component.

so when i click edit on a grid i navigate to create-edit-account component to use it for edit purposes as well.

upon clicking edit i navigate like this

 edit(account: BankAccount) {
this.router.navigateByUrl('/create-edit-account/' + account.id);
 }

but at the time i clicked edit i have a populated account object i want to pass it to the create-edit-account component.

Question 1 what is the best practice in passing object while using parameterized routes in Angular 8+

Question 2 how we tell a component that it is being used for edit or add. i learned that if i pass "0" in the route's id param we can consider it is being used as "new" . but is there a better approach ?

i also have an ngrx store implemented . so  Question 3 would you recommend using an action dispatch with something called "account-updating" and passing in the object as an action param and subscribing it in the create-edit-account component and later dispatching "account-updated" action?


问:
Converting Google Cloud Video intelligence json to newline delimited json to upload to Big Query
I have created a function which outputs the json below from using the Google Video Intelligence API. I am trying to get the json into newline delimited format so that I can upload the json file to Big Query.

I have tried the following JQ code however it does not convert it into a format accepted by BiG Query.

Any help greatly appreciated.

$ cat a.json | jq -c '.[]'

Full json output from video intelligence

```<code>{
  "annotation_results": [ {
    "input_uri": "/mastersproject-252719.appspot.com/AEnB2UoTKtyPJd1X88yUBKC60dn3kp6qrnnE91Q5PylS9RqotQWrt2TzFPE7kG1UHtxoBYyWX5mo7zoXU1jzwnNe_WRD-t0QeFSoHU4g-WJZTfeQV4cpFNY.4-FicKZIT3vtFBd2",
    "segment": {
      "start_time_offset": {

      },
      "end_time_offset": {
        "seconds": 126,
        "nanos": 160000000
      }
    },
    "shot_annotations": [ {
      "start_time_offset": {

      },
      "end_time_offset": {
        "seconds": 3,
        "nanos": 960000000
      }
    }, {
      "start_time_offset": {
        "seconds": 4
      },
      "end_time_offset": {
        "seconds": 5,
        "nanos": 840000000
      }
    }, {
      "start_time_offset": {
        "seconds": 5,
        "nanos": 880000000
      },
      "end_time_offset": {
        "seconds": 11,
        "nanos": 40000000
      }
    }, {
      "start_time_offset": {
        "seconds": 11,
        "nanos": 80000000
      },
      "end_time_offset": {
        "seconds": 14,
        "nanos": 640000000
      }
    }, {
      "start_time_offset": {
        "seconds": 14,
        "nanos": 680000000
      },
      "end_time_offset": {
        "seconds": 15,
        "nanos": 400000000
      }
    }, {
      "start_time_offset": {
        "seconds": 15,
        "nanos": 440000000
      },
      "end_time_offset": {
        "seconds": 19,
        "nanos": 840000000
      }
    }, {
      "start_time_offset": {
        "seconds": 19,
        "nanos": 880000000
      },
      "end_time_offset": {
        "seconds": 21,
        "nanos": 880000000
      }
    }, {
      "start_time_offset": {
        "seconds": 21,
        "nanos": 920000000
      },
      "end_time_offset": {
        "seconds": 25,
        "nanos": 120000000
      }
    }, {
      "start_time_offset": {
        "seconds": 25,
        "nanos": 160000000
      },
      "end_time_offset": {
        "seconds": 30,
        "nanos": 880000000
      }
    }, {
      "start_time_offset": {
        "seconds": 30,
        "nanos": 920000000
      },
      "end_time_offset": {
        "seconds": 32,
        "nanos": 960000000
      }
    }, {
      "start_time_offset": {
        "seconds": 33
      },
      "end_time_offset": {
        "seconds": 38,
        "nanos": 80000000
      }
    }, {
      "start_time_offset": {
        "seconds": 38,
        "nanos": 120000000
      },
      "end_time_offset": {
        "seconds": 44,
        "nanos": 80000000
      }
    }, {
      "start_time_offset": {
        "seconds": 44,
        "nanos": 120000000
      },
      "end_time_offset": {
        "seconds": 47,
        "nanos": 680000000
      }
    }, {
      "start_time_offset": {
        "seconds": 47,
        "nanos": 720000000
      },
      "end_time_offset": {
        "seconds": 51,
        "nanos": 120000000
      }
    }, {
      "start_time_offset": {
        "seconds": 51,
        "nanos": 160000000
      },
      "end_time_offset": {
        "seconds": 56,
        "nanos": 640000000
      }
    }, {
      "start_time_offset": {
        "seconds": 56,
        "nanos": 680000000
      },
      "end_time_offset": {
        "seconds": 59,
        "nanos": 40000000
      }
    }, {
      "start_time_offset": {
        "seconds": 59,
        "nanos": 80000000
      },
      "end_time_offset": {
        "seconds": 62,
        "nanos": 880000000
      }
    }, {
      "start_time_offset": {
        "seconds": 62,
        "nanos": 920000000
      },
      "end_time_offset": {
        "seconds": 70,
        "nanos": 640000000
      }
    }, {
      "start_time_offset": {
        "seconds": 70,
        "nanos": 680000000
      },
      "end_time_offset": {
        "seconds": 74,
        "nanos": 240000000
      }
    }, {
      "start_time_offset": {
        "seconds": 74,
        "nanos": 280000000
      },
      "end_time_offset": {
        "seconds": 76,
        "nanos": 40000000
      }
    }, {
      "start_time_offset": {
        "seconds": 76,
        "nanos": 80000000
      },
      "end_time_offset": {
        "seconds": 82,
        "nanos": 240000000
      }
    }, {
      "start_time_offset": {
        "seconds": 82,
        "nanos": 280000000
      },
      "end_time_offset": {
        "seconds": 86
      }
    }, {
      "start_time_offset": {
        "seconds": 86,
        "nanos": 40000000
      },
      "end_time_offset": {
        "seconds": 89,
        "nanos": 720000000
      }
    }, {
      "start_time_offset": {
        "seconds": 89,
        "nanos": 760000000
      },
      "end_time_offset": {
        "seconds": 99,
        "nanos": 680000000
      }
    }, {
      "start_time_offset": {
        "seconds": 99,
        "nanos": 720000000
      },
      "end_time_offset": {
        "seconds": 104,
        "nanos": 360000000
      }
    }, {
      "start_time_offset": {
        "seconds": 104,
        "nanos": 400000000
      },
      "end_time_offset": {
        "seconds": 107,
        "nanos": 440000000
      }
    }, {
      "start_time_offset": {
        "seconds": 107,
        "nanos": 480000000
      },
      "end_time_offset": {
        "seconds": 108,
        "nanos": 640000000
      }
    }, {
      "start_time_offset": {
        "seconds": 108,
        "nanos": 680000000
      },
      "end_time_offset": {
        "seconds": 112,
        "nanos": 160000000
      }
    }, {
      "start_time_offset": {
        "seconds": 112,
        "nanos": 200000000
      },
      "end_time_offset": {
        "seconds": 114,
        "nanos": 640000000
      }
    }, {
      "start_time_offset": {
        "seconds": 114,
        "nanos": 680000000
      },
      "end_time_offset": {
        "seconds": 117,
        "nanos": 520000000
      }
    }, {
      "start_time_offset": {
        "seconds": 117,
        "nanos": 560000000
      },
      "end_time_offset": {
        "seconds": 118,
        "nanos": 760000000
      }
    }, {
      "start_time_offset": {
        "seconds": 118,
        "nanos": 800000000
      },
      "end_time_offset": {
        "seconds": 121,
        "nanos": 80000000
      }
    }, {
      "start_time_offset": {
        "seconds": 121,
        "nanos": 120000000
      },
      "end_time_offset": {
        "seconds": 122,
        "nanos": 320000000
      }
    }, {
      "start_time_offset": {
        "seconds": 122,
        "nanos": 360000000
      },
      "end_time_offset": {
        "seconds": 124,
        "nanos": 200000000
      }
    }, {
      "start_time_offset": {
        "seconds": 124,
        "nanos": 240000000
      },
      "end_time_offset": {
        "seconds": 126,
        "nanos": 160000000
      }
    } ]
  } ]
}

</code>```

答:
I see you tried the suggested JQ command in this stack overflow post. You need to use a different JQ command suited to your case.

I personally tried:

```<code>cat <filename>.json | jq -c '.'
</code>```

and it works. Meaning, the end result is a valid newline delimited json.

However, it may need more tweaks depending on your end table schema.

Include your end table schema on the description if it does not work so we can understand better what is the goal.

Body:
I have created a function which outputs the json below from using the Google Video Intelligence API. I am trying to get the json into newline delimited format so that I can upload the json file to Big Query.

I have tried the following JQ code however it does not convert it into a format accepted by BiG Query.

Any help greatly appreciated.

$ cat a.json | jq -c '.[]'

Full json output from video intelligence

{
  "annotation_results": [ {
    "input_uri": "/mastersproject-252719.appspot.com/AEnB2UoTKtyPJd1X88yUBKC60dn3kp6qrnnE91Q5PylS9RqotQWrt2TzFPE7kG1UHtxoBYyWX5mo7zoXU1jzwnNe_WRD-t0QeFSoHU4g-WJZTfeQV4cpFNY.4-FicKZIT3vtFBd2",
    "segment": {
      "start_time_offset": {

      },
      "end_time_offset": {
        "seconds": 126,
        "nanos": 160000000
      }
    },
    "shot_annotations": [ {
      "start_time_offset": {

      },
      "end_time_offset": {
        "seconds": 3,
        "nanos": 960000000
      }
    }, {
      "start_time_offset": {
        "seconds": 4
      },
      "end_time_offset": {
        "seconds": 5,
        "nanos": 840000000
      }
    }, {
      "start_time_offset": {
        "seconds": 5,
        "nanos": 880000000
      },
      "end_time_offset": {
        "seconds": 11,
        "nanos": 40000000
      }
    }, {
      "start_time_offset": {
        "seconds": 11,
        "nanos": 80000000
      },
      "end_time_offset": {
        "seconds": 14,
        "nanos": 640000000
      }
    }, {
      "start_time_offset": {
        "seconds": 14,
        "nanos": 680000000
      },
      "end_time_offset": {
        "seconds": 15,
        "nanos": 400000000
      }
    }, {
      "start_time_offset": {
        "seconds": 15,
        "nanos": 440000000
      },
      "end_time_offset": {
        "seconds": 19,
        "nanos": 840000000
      }
    }, {
      "start_time_offset": {
        "seconds": 19,
        "nanos": 880000000
      },
      "end_time_offset": {
        "seconds": 21,
        "nanos": 880000000
      }
    }, {
      "start_time_offset": {
        "seconds": 21,
        "nanos": 920000000
      },
      "end_time_offset": {
        "seconds": 25,
        "nanos": 120000000
      }
    }, {
      "start_time_offset": {
        "seconds": 25,
        "nanos": 160000000
      },
      "end_time_offset": {
        "seconds": 30,
        "nanos": 880000000
      }
    }, {
      "start_time_offset": {
        "seconds": 30,
        "nanos": 920000000
      },
      "end_time_offset": {
        "seconds": 32,
        "nanos": 960000000
      }
    }, {
      "start_time_offset": {
        "seconds": 33
      },
      "end_time_offset": {
        "seconds": 38,
        "nanos": 80000000
      }
    }, {
      "start_time_offset": {
        "seconds": 38,
        "nanos": 120000000
      },
      "end_time_offset": {
        "seconds": 44,
        "nanos": 80000000
      }
    }, {
      "start_time_offset": {
        "seconds": 44,
        "nanos": 120000000
      },
      "end_time_offset": {
        "seconds": 47,
        "nanos": 680000000
      }
    }, {
      "start_time_offset": {
        "seconds": 47,
        "nanos": 720000000
      },
      "end_time_offset": {
        "seconds": 51,
        "nanos": 120000000
      }
    }, {
      "start_time_offset": {
        "seconds": 51,
        "nanos": 160000000
      },
      "end_time_offset": {
        "seconds": 56,
        "nanos": 640000000
      }
    }, {
      "start_time_offset": {
        "seconds": 56,
        "nanos": 680000000
      },
      "end_time_offset": {
        "seconds": 59,
        "nanos": 40000000
      }
    }, {
      "start_time_offset": {
        "seconds": 59,
        "nanos": 80000000
      },
      "end_time_offset": {
        "seconds": 62,
        "nanos": 880000000
      }
    }, {
      "start_time_offset": {
        "seconds": 62,
        "nanos": 920000000
      },
      "end_time_offset": {
        "seconds": 70,
        "nanos": 640000000
      }
    }, {
      "start_time_offset": {
        "seconds": 70,
        "nanos": 680000000
      },
      "end_time_offset": {
        "seconds": 74,
        "nanos": 240000000
      }
    }, {
      "start_time_offset": {
        "seconds": 74,
        "nanos": 280000000
      },
      "end_time_offset": {
        "seconds": 76,
        "nanos": 40000000
      }
    }, {
      "start_time_offset": {
        "seconds": 76,
        "nanos": 80000000
      },
      "end_time_offset": {
        "seconds": 82,
        "nanos": 240000000
      }
    }, {
      "start_time_offset": {
        "seconds": 82,
        "nanos": 280000000
      },
      "end_time_offset": {
        "seconds": 86
      }
    }, {
      "start_time_offset": {
        "seconds": 86,
        "nanos": 40000000
      },
      "end_time_offset": {
        "seconds": 89,
        "nanos": 720000000
      }
    }, {
      "start_time_offset": {
        "seconds": 89,
        "nanos": 760000000
      },
      "end_time_offset": {
        "seconds": 99,
        "nanos": 680000000
      }
    }, {
      "start_time_offset": {
        "seconds": 99,
        "nanos": 720000000
      },
      "end_time_offset": {
        "seconds": 104,
        "nanos": 360000000
      }
    }, {
      "start_time_offset": {
        "seconds": 104,
        "nanos": 400000000
      },
      "end_time_offset": {
        "seconds": 107,
        "nanos": 440000000
      }
    }, {
      "start_time_offset": {
        "seconds": 107,
        "nanos": 480000000
      },
      "end_time_offset": {
        "seconds": 108,
        "nanos": 640000000
      }
    }, {
      "start_time_offset": {
        "seconds": 108,
        "nanos": 680000000
      },
      "end_time_offset": {
        "seconds": 112,
        "nanos": 160000000
      }
    }, {
      "start_time_offset": {
        "seconds": 112,
        "nanos": 200000000
      },
      "end_time_offset": {
        "seconds": 114,
        "nanos": 640000000
      }
    }, {
      "start_time_offset": {
        "seconds": 114,
        "nanos": 680000000
      },
      "end_time_offset": {
        "seconds": 117,
        "nanos": 520000000
      }
    }, {
      "start_time_offset": {
        "seconds": 117,
        "nanos": 560000000
      },
      "end_time_offset": {
        "seconds": 118,
        "nanos": 760000000
      }
    }, {
      "start_time_offset": {
        "seconds": 118,
        "nanos": 800000000
      },
      "end_time_offset": {
        "seconds": 121,
        "nanos": 80000000
      }
    }, {
      "start_time_offset": {
        "seconds": 121,
        "nanos": 120000000
      },
      "end_time_offset": {
        "seconds": 122,
        "nanos": 320000000
      }
    }, {
      "start_time_offset": {
        "seconds": 122,
        "nanos": 360000000
      },
      "end_time_offset": {
        "seconds": 124,
        "nanos": 200000000
      }
    }, {
      "start_time_offset": {
        "seconds": 124,
        "nanos": 240000000
      },
      "end_time_offset": {
        "seconds": 126,
        "nanos": 160000000
      }
    } ]
  } ]
}

Body:
I see you tried the suggested JQ command in this stack overflow post. You need to use a different JQ command suited to your case.

I personally tried:

cat <filename>.json | jq -c '.'

and it works. Meaning, the end result is a valid newline delimited json.

However, it may need more tweaks depending on your end table schema.

Include your end table schema on the description if it does not work so we can understand better what is the goal.


问:
How can I import Elastic-Net, Lasso and Ridge regression in Pyspark?
Could you please tell me how can I use Elastic-Net, Lasso and Ridge regression in Pyspark? Actually I chose Linear, Elastic-Net, Lasso and Ridge regression these 4 algorithms according to machine learning cheatsheet. However, I don't know how to import Elastic-Net, Lasso and Ridge regression in Pyspark and cannot google the right answers. I just know using the Linear Regression in Pyspark.

答:
Have a look at https://spark.apache.org/docs/1.5.2/ml-linear-methods.html

You can use something like:

```<code>from pyspark.ml.regression import LinearRegression
from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.util import MLUtils

# Load training data
training = MLUtils.loadLibSVMFile(sc, "data/mllib/sample_libsvm_data.txt").toDF()

lr = LinearRegression(maxIter=10, regParam=0.3, elasticNetParam=0.8)

# Fit the model
lrModel = lr.fit(training)

# Print the weights and intercept for linear regression
print("Weights: " + str(lrModel.weights))
print("Intercept: " + str(lrModel.intercept))

</code>```

If you read into the setup, you'll find that:

By setting α properly, elastic net contains both L1 and L2 regularization as special cases. For example, if a linear regression model is trained with the elastic net parameter α set to 1, it is equivalent to a Lasso model. On the other hand, if α is set to 0, the trained model reduces to a ridge regression model.

Where:

elasticNetParam corresponds to α and regParam corresponds to λ.

Body:
Have a look at https://spark.apache.org/docs/1.5.2/ml-linear-methods.html

You can use something like:

from pyspark.ml.regression import LinearRegression
from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.util import MLUtils

# Load training data
training = MLUtils.loadLibSVMFile(sc, "data/mllib/sample_libsvm_data.txt").toDF()

lr = LinearRegression(maxIter=10, regParam=0.3, elasticNetParam=0.8)

# Fit the model
lrModel = lr.fit(training)

# Print the weights and intercept for linear regression
print("Weights: " + str(lrModel.weights))
print("Intercept: " + str(lrModel.intercept))

If you read into the setup, you'll find that:

By setting α properly, elastic net contains both L1 and L2 regularization as special cases. For example, if a linear regression model is trained with the elastic net parameter α set to 1, it is equivalent to a Lasso model. On the other hand, if α is set to 0, the trained model reduces to a ridge regression model.

Where:

elasticNetParam corresponds to α and regParam corresponds to λ.


问:
How to return content of a nested indexed field with some top level fields using Mongodb?
Consider these documents:

```<code>{
  "chapterNumber": "1",
  "contents": [
    {
      "paragraphNumber": "1 ",
      "paragraphCleanText": "cleaned content 1",
      "contents": [
        "not clean content",
        {
          "p": null
        }
      ]
    },
    {
      "paragraphNumber": "1 ",
      "paragraphCleanText": "cleaned content 2",
      "contents": [
        "not clean content",
        {
          "p": null
        }
      ]
    },
  ]
}
{
  "chapterNumber": "2",
  "contents": [
    {
      "paragraphNumber": "1 ",
      "paragraphCleanText": "cleaned content 3",
      "contents": [
        "not clean content",
        {
          "p": null
        }
      ]
    },
    {
      "paragraphNumber": "1 ",
      "paragraphCleanText": "cleaned content 4",
      "contents": [
        "not clean content",
        {
          "p": null
        }
      ]
    },
  ]
}
</code>```

If I do an index on the field paragraphCleanText and then issue a query to search for this string cleaned content 3, is there a way to return the following structure from a single or optimized query?

```<code>{
  "chapterNumber": "2",
  "paragraphNumber": "1 ",
  "paragraphCleanText": "cleaned content 3"
}
</code>```

答:
Found a pretty simple solution for my use case:

add an index on paragraphCleanText field, plus chapterNumber and paragraphNumber as additional fields

make the following query db.yourCollection.find({"contents.paragraphCleanText" : { $regex: /^ some text that is present in the field .*/ } })._addSpecial( "$returnKey", true )
`

Body:
Consider these documents:

{
  "chapterNumber": "1",
  "contents": [
    {
      "paragraphNumber": "1 ",
      "paragraphCleanText": "cleaned content 1",
      "contents": [
        "not clean content",
        {
          "p": null
        }
      ]
    },
    {
      "paragraphNumber": "1 ",
      "paragraphCleanText": "cleaned content 2",
      "contents": [
        "not clean content",
        {
          "p": null
        }
      ]
    },
  ]
}
{
  "chapterNumber": "2",
  "contents": [
    {
      "paragraphNumber": "1 ",
      "paragraphCleanText": "cleaned content 3",
      "contents": [
        "not clean content",
        {
          "p": null
        }
      ]
    },
    {
      "paragraphNumber": "1 ",
      "paragraphCleanText": "cleaned content 4",
      "contents": [
        "not clean content",
        {
          "p": null
        }
      ]
    },
  ]
}

If I do an index on the field paragraphCleanText and then issue a query to search for this string cleaned content 3, is there a way to return the following structure from a single or optimized query?

{
  "chapterNumber": "2",
  "paragraphNumber": "1 ",
  "paragraphCleanText": "cleaned content 3"
}


问:
How to highlight SQL keywords using a regular expression?
I would like to highlight SQL keywords that occur within a string in a syntax highlighter. Here are the rules I would like to have:

Match the keywords SELECT and FROM (others will be added, but we'll start here). Must be all-caps

Must be contained in a string -- either starting with ' or "

The first word in that string (ignoring whitespace preceding it) should be one of the keywords.

This of course is not comprehensive (can ignore escapes within a string), but I'd like to start here.

Here are a few examples:

SELECT * FROM main -- will not match (not in a string)

"SELECT name FROM main" -- will match

"

      SELECT name FROM main" -- will match

"""Here is a SQL statement:

SELECT * FROM main""" -- no, string does not start with a keyword (SELECT...).

The only way I thought to do it in a single regex would be with a negative lookbehind...but then it would not be fixed width, as we don't know when the string starts. Something like:

(?<=["']\s*(SELECT)\s*)(SELECT|FROM)

But this of course won't work:

Would something like this be possible to do in a single regex?

答:
If I understand your requirements well I suggest that:

```<code>/^'\s*(SELECT)[^']*(FROM)[^']*'|^"\s*(SELECT)[^"]*(FROM)[^"]*"/m
</code>```

[Regex Fiddle Demo]

Explanation:

When you need to check start of a string; use ^.

When you need to accept 0-n spaces; use \s*.

When you need to accept new-line or multi-line strings; use m flag over your regex.

When you need to use Case-Sensitive mode; Don't use i flag over your regex.

When you need to block a string between a specific character like "; use [^"]* instead of .* that will protects first end of block.

When you need to have a block with similar start and end characters like ' & "; use ' '|" " instead of ['"] ['"].

Update:

If you need to capture any special keyword after verifying existence of SELECT keyword after start of your string, I can update my solution to this:

```<code>/^'\s*(SELECT)([^']*(SELECT|FROM))+|^"\s*(SELECT)([^"]*(SELECT|FROM))+/m
</code>```

Body:
If I understand your requirements well I suggest that:

/^'\s*(SELECT)[^']*(FROM)[^']*'|^"\s*(SELECT)[^"]*(FROM)[^"]*"/m

[Regex Fiddle Demo]

Explanation:

When you need to check start of a string; use ^.

When you need to accept 0-n spaces; use \s*.

When you need to accept new-line or multi-line strings; use m flag over your regex.

When you need to use Case-Sensitive mode; Don't use i flag over your regex.

When you need to block a string between a specific character like "; use [^"]* instead of .* that will protects first end of block.

When you need to have a block with similar start and end characters like ' & "; use ' '|" " instead of ['"] ['"].

Update:

If you need to capture any special keyword after verifying existence of SELECT keyword after start of your string, I can update my solution to this:

/^'\s*(SELECT)([^']*(SELECT|FROM))+|^"\s*(SELECT)([^"]*(SELECT|FROM))+/m


问:
LocalStorage data appearing in console but not in the DOM
I am currently building a to-do list app and I have already saved the data using the localStorage API.

The desired data, however, appears in the console whenever I console.log it but it still doesn't save in the DOM.

I also added the getItem() function and logged it into the console and I can still view it in the console, find here:
getItem content in the console

But it just doesn't store in the browser

Seeing this, it is in your inclination that it should have stored in the DOM and the content still remains after reloading but that just isn't the case here.

This function below adds a new item to the list, it also deletes and crosses out completed items too:

```<code>let id = 0;
function addTaskFunc() {

    const aTask = `
    <div class="task" id="task-${id}">
        <button class="done__btn">
            <i class="far fa-check-square"></i>
        </button>
        <p>${box.value}</p>
        <button class="priority">Make priority</button>
        <button class="cancel__btn">
            <i class="far fa-times-circle"></i>
        </button>
    </div>
`;

    const x = box.value;
    if (x) {
        taskList.insertAdjacentHTML('afterbegin', aTask);
        box.value = '';
        ;

        let cid = id;

        const cancelBtn = document.querySelector(`#task-${id} .cancel__btn`);
        cancelBtn.addEventListener('click', () => {
        deleteItem(cid);
        });

        let cid2 = id;

        // code for marking out an item as done

        let cid3 = id;

        // code for appending an item to the top of DOM

        let cid4 = id;
        persistData(cid4);
        readData(cid4);
        id++;
    }
}

newTask.addEventListener('click', addTaskFunc); // Button to activate the function

persistData = id => {
    const el = document.querySelector(`#task-${id}`);
    localStorage.setItem('addedTasks222', el.innerHTML);

};

readData = id => {
    const el = document.querySelector(`#task-${id}`);
    const saved = localStorage.getItem('addedTasks222');
    if (saved) el.innerHTML = saved;
    console.log(el.innerHTML); // This line of code appears in the console
}
</code>```

I also tried doing it this way inside of the addTaskFunc:

```<code>const r = document.querySelector(`#task-${id} .task`);
r.addEventListener('load', () => {
          persistData(cid4);
          readData(cid4);
 });
</code>```

When I try it with the method above I get the error code in the console:
Cannot read property of addEventListener of null.

I feel there is something wrong somewhere but I just cannot seem to find out where I am missing it.

One last thing, the localStorage only seems to store only one item into the key. Do I need a loop to sort that out?

答:
sorry for the time..
So I was looking in to your code, and appears that you have some problems..
1- The first one I saw, was in the persistData() function. Accidentally you are just selecting one task to store with document.querySelector(.task);
to select all you need to use document.querySelectorAll(.task), this will return you an array. Because of that you only store one task.
2- Secondly is that you are trying to store html. with .innerHtml, and the innerHtml of your (".class") is buttons and etc.. You should store values.
3- At the end, when you are trying to print the data, you do document.querySelector(.task), and as you can see its returning you undefined, that's because you haven't a .task div yet.

So How you can appropriately make your app work.

1- The first thing you need to do is creating an array variable up on your js file.

let tasks = [];

2-That array will be used to store the values of your tasks with something like this

```<code>    function addItem(){
      let value = item.value; //you need to define the item some way
      tasks.push(value);
      print() //a function to print the values;
      persistData() // store the array
    }
</code>```

3-To print the tasks

```<code>    function print(){
      tasks.forEach(task => {
       let div = document.createElement("div");
       div.innerHTML = `copy your html task to here, use ${task} to print the task value`
      })
    }
</code>```

4-Store the tasks

```<code>function persistData(){
   localStorage.setItem('addedTasks', tasks); //store the array
};

function readData(){
   if (typeof(Storage) !== "undefined") { //check if the browser has localStorage
    tasks = localStorage.getItem('addedTasks'); //update your array
    print();
   } else {
    //No Web Storage message
   }
};
</code>```

5- Just run readData() when you load your document with

```<code> document.addEventListener("DOMContentLoaded", function(event) {
      readData();
  });
</code>```

I hope that I can help

Body:
I am currently building a to-do list app and I have already saved the data using the localStorage API.

The desired data, however, appears in the console whenever I console.log it but it still doesn't save in the DOM.

I also added the getItem() function and logged it into the console and I can still view it in the console, find here:
getItem content in the console

But it just doesn't store in the browser

Seeing this, it is in your inclination that it should have stored in the DOM and the content still remains after reloading but that just isn't the case here.

This function below adds a new item to the list, it also deletes and crosses out completed items too:

let id = 0;
function addTaskFunc() {

    const aTask = `

        <button class="done__btn">

        </button>

${box.value}

        <button class="priority">Make priority</button>
        <button class="cancel__btn">

        </button>

`;

    const x = box.value;
    if (x) {
        taskList.insertAdjacentHTML('afterbegin', aTask);
        box.value = '';
        ;

        let cid = id;

        const cancelBtn = document.querySelector(`#task-${id} .cancel__btn`);
        cancelBtn.addEventListener('click', () => {
        deleteItem(cid);
        });

        let cid2 = id;

        // code for marking out an item as done

        let cid3 = id;

        // code for appending an item to the top of DOM

        let cid4 = id;
        persistData(cid4);
        readData(cid4);
        id++;
    }
}

newTask.addEventListener('click', addTaskFunc); // Button to activate the function

persistData = id => {
    const el = document.querySelector(`#task-${id}`);
    localStorage.setItem('addedTasks222', el.innerHTML);

};

readData = id => {
    const el = document.querySelector(`#task-${id}`);
    const saved = localStorage.getItem('addedTasks222');
    if (saved) el.innerHTML = saved;
    console.log(el.innerHTML); // This line of code appears in the console
}

I also tried doing it this way inside of the addTaskFunc:

const r = document.querySelector(`#task-${id} .task`);
r.addEventListener('load', () => {
          persistData(cid4);
          readData(cid4);
 });

When I try it with the method above I get the error code in the console:
Cannot read property of addEventListener of null.

I feel there is something wrong somewhere but I just cannot seem to find out where I am missing it.

One last thing, the localStorage only seems to store only one item into the key. Do I need a loop to sort that out?

Body:
sorry for the time..
So I was looking in to your code, and appears that you have some problems..
1- The first one I saw, was in the persistData() function. Accidentally you are just selecting one task to store with document.querySelector(.task);
to select all you need to use document.querySelectorAll(.task), this will return you an array. Because of that you only store one task.
2- Secondly is that you are trying to store html. with .innerHtml, and the innerHtml of your (".class") is buttons and etc.. You should store values.
3- At the end, when you are trying to print the data, you do document.querySelector(.task), and as you can see its returning you undefined, that's because you haven't a .task div yet.

So How you can appropriately make your app work.

1- The first thing you need to do is creating an array variable up on your js file.

let tasks = [];

2-That array will be used to store the values of your tasks with something like this

    function addItem(){
      let value = item.value; //you need to define the item some way
      tasks.push(value);
      print() //a function to print the values;
      persistData() // store the array
    }

3-To print the tasks

    function print(){
      tasks.forEach(task => {
       let div = document.createElement("div");
       div.innerHTML = `copy your html task to here, use ${task} to print the task value`
      })
    }

4-Store the tasks

function persistData(){
   localStorage.setItem('addedTasks', tasks); //store the array
};

function readData(){
   if (typeof(Storage) !== "undefined") { //check if the browser has localStorage
    tasks = localStorage.getItem('addedTasks'); //update your array
    print();
   } else {
    //No Web Storage message
   }
};

5- Just run readData() when you load your document with

 document.addEventListener("DOMContentLoaded", function(event) {
      readData();
  });

I hope that I can help