问:
Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar
I have used geotools library, in my project I have added all the dependencies to the buildpath

Downloaded the libraries from Sourseforge. Added the same to the library, When I try to execute the application, I am getting the below error.

```<code>    SLF4J: Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflowError.
SLF4J: See also http://www.slf4j.org/codes.html#log4jDelegationLoop for more details.
Exception in thread "main" java.lang.ExceptionInInitializerError
    at org.hsqldb.DatabaseManager.filePathToKey(Unknown Source)
    at org.hsqldb.DatabaseManager.getDatabaseObject(Unknown Source)
    at org.hsqldb.DatabaseManager.getDatabase(Unknown Source)
    at org.hsqldb.DatabaseManager.newSession(Unknown Source)
    at org.hsqldb.jdbc.JDBCConnection.<init>(Unknown Source)
    at org.hsqldb.jdbc.JDBCDriver.getConnection(Unknown Source)
    at org.hsqldb.jdbc.JDBCDataSource.getConnection(Unknown Source)
    at org.hsqldb.jdbc.JDBCDataSource.getConnection(Unknown Source)
    at org.geotools.referencing.factory.epsg.DirectEpsgFactory.getConnection(DirectEpsgFactory.java:3529)
    at org.geotools.referencing.factory.epsg.ThreadedEpsgFactory.createBackingStore(ThreadedEpsgFactory.java:437)
    at org.geotools.referencing.factory.DeferredAuthorityFactory.getBackingStore(DeferredAuthorityFactory.java:114)
    at org.geotools.referencing.factory.BufferedAuthorityFactory.isAvailable(BufferedAuthorityFactory.java:218)
    at org.geotools.referencing.factory.DeferredAuthorityFactory.isAvailable(DeferredAuthorityFactory.java:100)
    at org.geotools.util.factory.FactoryRegistry.isAvailable(FactoryRegistry.java:808)
    at org.geotools.util.factory.FactoryRegistry.isAcceptable(FactoryRegistry.java:631)
    at org.geotools.util.factory.FactoryRegistry.lambda$getFactories$0(FactoryRegistry.java:300)
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:174)
    at java.util.Spliterators$IteratorSpliterator.tryAdvance(Spliterators.java:1812)
    at java.util.stream.StreamSpliterators$WrappingSpliterator.lambda$initPartialTraversalState$0(StreamSpliterators.java:294)
    at java.util.stream.StreamSpliterators$AbstractWrappingSpliterator.fillBuffer(StreamSpliterators.java:206)
    at java.util.stream.StreamSpliterators$AbstractWrappingSpliterator.doAdvance(StreamSpliterators.java:161)
    at java.util.stream.StreamSpliterators$WrappingSpliterator.tryAdvance(StreamSpliterators.java:300)
    at java.util.Spliterators$1Adapter.hasNext(Spliterators.java:681)
    at org.geotools.util.LazySet.isEmpty(LazySet.java:98)
    at org.geotools.referencing.factory.ManyAuthoritiesFactory.<init>(ManyAuthoritiesFactory.java:115)
    at org.geotools.referencing.DefaultAuthorityFactory.getBackingFactory(DefaultAuthorityFactory.java:114)
    at org.geotools.referencing.DefaultAuthorityFactory.<init>(DefaultAuthorityFactory.java:67)
    at org.geotools.referencing.CRS.getAuthorityFactory(CRS.java:253)
    at org.geotools.referencing.CRS.decode(CRS.java:533)
    at org.geotools.referencing.CRS.decode(CRS.java:447)
    at org.geotools.dev.SelectApp.fromBytes(SelectApp.java:153)
    at org.geotools.dev.SelectApp.selectAll(SelectApp.java:81)
    at org.geotools.dev.SelectApp.main(SelectApp.java:96)
Caused by: java.lang.RuntimeException: Failed to instantiate Log4j Logger
    at org.hsqldb.lib.FrameworkLogger.<init>(Unknown Source)
    at org.hsqldb.lib.FrameworkLogger.getLog(Unknown Source)
    at org.hsqldb.lib.FrameworkLogger.getLog(Unknown Source)
    at org.hsqldb.lib.FileUtil.<clinit>(Unknown Source)
    ... 33 more
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    ... 37 more
Caused by: java.lang.ExceptionInInitializerError
    at org.apache.log4j.Logger.getLogger(Logger.java:39)
    ... 41 more
Caused by: java.lang.IllegalStateException: Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflowError. See also http://www.slf4j.org/codes.html#log4jDelegationLoop for more details.
    at org.apache.log4j.Log4jLoggerFactory.<clinit>(Log4jLoggerFactory.java:49)
    ... 42 more
</code>```

What I have tried sofar…,

as suggested in this accepted answer, I have added the exclusions. Still having the same error.

I don't have any dependency with them, even I have removed both the jar files, still the error remains same!!

my Pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
           <modelVersion>4.0.0</modelVersion>
           <groupId>org.geotools</groupId>
           <artifactId>tutorial</artifactId>
           <version>0.0.1-SNAPSHOT</version>
           <packaging>jar</packaging>
           <name>tutorial</name>
           <url>http://maven.apache.org</url>
           <properties>
              <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
              <geotools.version>24-SNAPSHOT</geotools.version>
           </properties>
           <dependencies>
              <dependency>
                 <groupId>junit</groupId>
                 <artifactId>junit</artifactId>
                 <version>4.11</version>
                 <scope>test</scope>
              </dependency>
              <dependency>
                 <groupId>org.geotools</groupId>
                 <artifactId>gt-shapefile</artifactId>
                 <version>${geotools.version}</version>
              </dependency>
              <dependency>
                 <groupId>org.geotools</groupId>
                 <artifactId>gt-swing</artifactId>
                 <version>${geotools.version}</version>
              </dependency>
              <!-- https://mvnrepository.com/artifact/log4j/log4j -->
              <!-- <dependency>
                 <groupId>log4j</groupId>
                 <artifactId>log4j</artifactId>
                 <version>1.2.17</version>
              </dependency> -->
           </dependencies>
           <repositories>
              <repository>
                 <id>osgeo</id>
                 <name>OSGeo Release Repository</name>
                 <url>https://repo.osgeo.org/repository/release/</url>
                 <snapshots>
                    <enabled>false</enabled>
                 </snapshots>
                 <releases>
                    <enabled>true</enabled>
                 </releases>
              </repository>
              <repository>
                 <id>osgeo-snapshot</id>
                 <name>OSGeo Snapshot Repository</name>
                 <url>https://repo.osgeo.org/repository/snapshot/</url>
                 <snapshots>
                    <enabled>true</enabled>
                 </snapshots>
                 <releases>
                    <enabled>false</enabled>
                 </releases>
              </repository>
           </repositories>
           <exclusions>
              <exclusion>
                 <groupId>org.slf4j</groupId>
                 <artifactId>slf4j-log4j12</artifactId>
              </exclusion>
              <exclusion>
                 <groupId>log4j</groupId>
                 <artifactId>log4j</artifactId>
              </exclusion>
           </exclusions>
           <build>
              <plugins>
                 <plugin>
                    <inherited>true</inherited>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                       <source>1.8</source>
                       <target>1.8</target>
                    </configuration>
                 </plugin>
              </plugins>
           </build>
        </project>
</code>```

In my maven dependencies by default I got slf4j-api-1.7.13.jar

答: I have updated my geotools library to 23.x, then all my issues got resolved.

Body:
I have used geotools library, in my project I have added all the dependencies to the buildpath

Downloaded the libraries from Sourseforge. Added the same to the library, When I try to execute the application, I am getting the below error.

    SLF4J: Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflowError.
SLF4J: See also http://www.slf4j.org/codes.html#log4jDelegationLoop for more details.
Exception in thread "main" java.lang.ExceptionInInitializerError
    at org.hsqldb.DatabaseManager.filePathToKey(Unknown Source)
    at org.hsqldb.DatabaseManager.getDatabaseObject(Unknown Source)
    at org.hsqldb.DatabaseManager.getDatabase(Unknown Source)
    at org.hsqldb.DatabaseManager.newSession(Unknown Source)
    at org.hsqldb.jdbc.JDBCConnection.<init>(Unknown Source)
    at org.hsqldb.jdbc.JDBCDriver.getConnection(Unknown Source)
    at org.hsqldb.jdbc.JDBCDataSource.getConnection(Unknown Source)
    at org.hsqldb.jdbc.JDBCDataSource.getConnection(Unknown Source)
    at org.geotools.referencing.factory.epsg.DirectEpsgFactory.getConnection(DirectEpsgFactory.java:3529)
    at org.geotools.referencing.factory.epsg.ThreadedEpsgFactory.createBackingStore(ThreadedEpsgFactory.java:437)
    at org.geotools.referencing.factory.DeferredAuthorityFactory.getBackingStore(DeferredAuthorityFactory.java:114)
    at org.geotools.referencing.factory.BufferedAuthorityFactory.isAvailable(BufferedAuthorityFactory.java:218)
    at org.geotools.referencing.factory.DeferredAuthorityFactory.isAvailable(DeferredAuthorityFactory.java:100)
    at org.geotools.util.factory.FactoryRegistry.isAvailable(FactoryRegistry.java:808)
    at org.geotools.util.factory.FactoryRegistry.isAcceptable(FactoryRegistry.java:631)
    at org.geotools.util.factory.FactoryRegistry.lambda$getFactories$0(FactoryRegistry.java:300)
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:174)
    at java.util.Spliterators$IteratorSpliterator.tryAdvance(Spliterators.java:1812)
    at java.util.stream.StreamSpliterators$WrappingSpliterator.lambda$initPartialTraversalState$0(StreamSpliterators.java:294)
    at java.util.stream.StreamSpliterators$AbstractWrappingSpliterator.fillBuffer(StreamSpliterators.java:206)
    at java.util.stream.StreamSpliterators$AbstractWrappingSpliterator.doAdvance(StreamSpliterators.java:161)
    at java.util.stream.StreamSpliterators$WrappingSpliterator.tryAdvance(StreamSpliterators.java:300)
    at java.util.Spliterators$1Adapter.hasNext(Spliterators.java:681)
    at org.geotools.util.LazySet.isEmpty(LazySet.java:98)
    at org.geotools.referencing.factory.ManyAuthoritiesFactory.<init>(ManyAuthoritiesFactory.java:115)
    at org.geotools.referencing.DefaultAuthorityFactory.getBackingFactory(DefaultAuthorityFactory.java:114)
    at org.geotools.referencing.DefaultAuthorityFactory.<init>(DefaultAuthorityFactory.java:67)
    at org.geotools.referencing.CRS.getAuthorityFactory(CRS.java:253)
    at org.geotools.referencing.CRS.decode(CRS.java:533)
    at org.geotools.referencing.CRS.decode(CRS.java:447)
    at org.geotools.dev.SelectApp.fromBytes(SelectApp.java:153)
    at org.geotools.dev.SelectApp.selectAll(SelectApp.java:81)
    at org.geotools.dev.SelectApp.main(SelectApp.java:96)
Caused by: java.lang.RuntimeException: Failed to instantiate Log4j Logger
    at org.hsqldb.lib.FrameworkLogger.<init>(Unknown Source)
    at org.hsqldb.lib.FrameworkLogger.getLog(Unknown Source)
    at org.hsqldb.lib.FrameworkLogger.getLog(Unknown Source)
    at org.hsqldb.lib.FileUtil.<clinit>(Unknown Source)
    ... 33 more
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    ... 37 more
Caused by: java.lang.ExceptionInInitializerError
    at org.apache.log4j.Logger.getLogger(Logger.java:39)
    ... 41 more
Caused by: java.lang.IllegalStateException: Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflowError. See also http://www.slf4j.org/codes.html#log4jDelegationLoop for more details.
    at org.apache.log4j.Log4jLoggerFactory.<clinit>(Log4jLoggerFactory.java:49)
    ... 42 more

What I have tried sofar…,

as suggested in this accepted answer, I have added the exclusions. Still having the same error.

I don't have any dependency with them, even I have removed both the jar files, still the error remains same!!

my Pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
           <modelVersion>4.0.0</modelVersion>
           <groupId>org.geotools</groupId>
           <artifactId>tutorial</artifactId>
           <version>0.0.1-SNAPSHOT</version>
           <packaging>jar</packaging>
           <name>tutorial</name>
           <url>http://maven.apache.org</url>
           <properties>
              <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
              <geotools.version>24-SNAPSHOT</geotools.version>
           </properties>
           <dependencies>
              <dependency>
                 <groupId>junit</groupId>
                 <artifactId>junit</artifactId>
                 <version>4.11</version>
                 <scope>test</scope>
              </dependency>
              <dependency>
                 <groupId>org.geotools</groupId>
                 <artifactId>gt-shapefile</artifactId>
                 <version>${geotools.version}</version>
              </dependency>
              <dependency>
                 <groupId>org.geotools</groupId>
                 <artifactId>gt-swing</artifactId>
                 <version>${geotools.version}</version>
              </dependency>

           </dependencies>
           <repositories>
              <repository>
                 <id>osgeo</id>
                 <name>OSGeo Release Repository</name>
                 <url>https://repo.osgeo.org/repository/release/</url>
                 <snapshots>
                    <enabled>false</enabled>
                 </snapshots>
                 <releases>
                    <enabled>true</enabled>
                 </releases>
              </repository>
              <repository>
                 <id>osgeo-snapshot</id>
                 <name>OSGeo Snapshot Repository</name>
                 <url>https://repo.osgeo.org/repository/snapshot/</url>
                 <snapshots>
                    <enabled>true</enabled>
                 </snapshots>
                 <releases>
                    <enabled>false</enabled>
                 </releases>
              </repository>
           </repositories>
           <exclusions>
              <exclusion>
                 <groupId>org.slf4j</groupId>
                 <artifactId>slf4j-log4j12</artifactId>
              </exclusion>
              <exclusion>
                 <groupId>log4j</groupId>
                 <artifactId>log4j</artifactId>
              </exclusion>
           </exclusions>
           <build>
              <plugins>
                 <plugin>
                    <inherited>true</inherited>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                       <source>1.8</source>
                       <target>1.8</target>
                    </configuration>
                 </plugin>
              </plugins>
           </build>
        </project>

In my maven dependencies by default I got slf4j-api-1.7.13.jar


来源: stackexchange

问:
Trying to Read ORC as Dask Dataframe
I have an ORC file in s3 that I would like to read into a Dask dataframe.  I'm using conda to get a python 3.7 virtual env and I have Dask installed.  My environment looks like this:

```<code># Name                    Version                   Build  Channel
appnope                   0.1.0                    py37_0
backcall                  0.1.0                    py37_0
blas                      1.0                         mkl
bokeh                     2.0.2                    py37_0
ca-certificates           2020.1.1                      0
certifi                   2020.4.5.1               py37_0
click                     7.1.2                      py_0
cloudpickle               1.4.1                      py_0
cytoolz                   0.10.1           py37h1de35cc_0
dask                      2.17.0                     py_0
dask-core                 2.17.0                     py_0
decorator                 4.4.2                      py_0
distributed               2.17.0                   py37_0
entrypoints               0.3                      py37_0
freetype                  2.9.1                hb4e5f40_0
fsspec                    0.7.1                      py_0
heapdict                  1.0.1                      py_0
intel-openmp              2019.4                      233
ipykernel                 5.1.4            py37h39e3cac_0
ipython                   7.13.0           py37h5ca1d4c_0
ipython_genutils          0.2.0                    py37_0
jedi                      0.17.0                   py37_0
jinja2                    2.11.2                     py_0
jpeg                      9b                   he5867d9_2
jupyter_client            6.1.3                      py_0
jupyter_core              4.6.3                    py37_0
libcxx                    10.0.0                        1
libedit                   3.1.20181209         hb402a30_0
libffi                    3.3                  h0a44026_1
libgfortran               3.0.1                h93005f0_2
libpng                    1.6.37               ha441bb4_0
libsodium                 1.0.16               h3efe00b_0
libtiff                   4.1.0                hcb84e12_0
locket                    0.2.0                    py37_1
markupsafe                1.1.1            py37h1de35cc_0
mkl                       2019.4                      233
mkl-service               2.3.0            py37hfbe908c_0
mkl_fft                   1.0.15           py37h5e564d8_0
mkl_random                1.1.1            py37h959d312_0
msgpack-python            1.0.0            py37h04f5b5a_1
ncurses                   6.2                  h0a44026_1
numpy                     1.18.1           py37h7241aed_0
numpy-base                1.18.1           py37h3304bdc_1
olefile                   0.46                       py_0
openssl                   1.1.1g               h1de35cc_0
packaging                 20.3                       py_0
pandas                    1.0.3            py37h6c726b0_0
parso                     0.7.0                      py_0
partd                     1.1.0                      py_0
pexpect                   4.8.0                    py37_0
pickleshare               0.7.5                    py37_0
pillow                    7.1.2            py37h4655f20_0
pip                       20.0.2                   py37_3
prompt-toolkit            3.0.4                      py_0
prompt_toolkit            3.0.4                         0
psutil                    5.7.0            py37h1de35cc_0
ptyprocess                0.6.0                    py37_0
pyarrow                   0.17.1                   pypi_0    pypi
pygments                  2.6.1                      py_0
pyparsing                 2.4.7                      py_0
python                    3.7.7                hf48f09d_4
python-dateutil           2.8.1                      py_0
pytz                      2020.1                     py_0
pyyaml                    5.3.1            py37h1de35cc_0
pyzmq                     18.1.1           py37h0a44026_0
readline                  8.0                  h1de35cc_0
setuptools                46.4.0                   py37_0
six                       1.14.0                   py37_0
sortedcontainers          2.1.0                    py37_0
sqlite                    3.31.1               h5c1f38d_1
tblib                     1.6.0                      py_0
tk                        8.6.8                ha441bb4_0
toolz                     0.10.0                     py_0
tornado                   6.0.4            py37h1de35cc_1
traitlets                 4.3.3                    py37_0
typing_extensions         3.7.4.1                  py37_0
wcwidth                   0.1.9                      py_0
wheel                     0.34.2                   py37_0
xz                        5.2.5                h1de35cc_0
yaml                      0.1.7                hc338f04_2
zeromq                    4.3.1                h0a44026_3
zict                      2.0.0                      py_0
zlib                      1.2.11               h1de35cc_3
zstd                      1.3.7                h5bba6e5_0
</code>```

I tried to do this:

```<code>import dask.dataframe as dd
orders_path = "s3://bucketname/folder/ord_files_dir/"
orders = dd.read_orc(orders_path)
</code>```

But I'm getting this error:

```<code>---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
/anaconda3/envs/dask_env/lib/python3.7/site-packages/dask/utils.py in import_required(mod_name, error_msg)
     96     try:
---> 97         return import_module(mod_name)
     98     except ImportError:

/anaconda3/envs/dask_env/lib/python3.7/importlib/__init__.py in import_module(name, package)
    126             level += 1
--> 127     return _bootstrap._gcd_import(name[level:], package, level)
    128

/anaconda3/envs/dask_env/lib/python3.7/importlib/_bootstrap.py in _gcd_import(name, package, level)

/anaconda3/envs/dask_env/lib/python3.7/importlib/_bootstrap.py in _find_and_load(name, import_)

/anaconda3/envs/dask_env/lib/python3.7/importlib/_bootstrap.py in _find_and_load_unlocked(name, import_)

/anaconda3/envs/dask_env/lib/python3.7/importlib/_bootstrap.py in _load_unlocked(spec)

/anaconda3/envs/dask_env/lib/python3.7/importlib/_bootstrap_external.py in exec_module(self, module)

/anaconda3/envs/dask_env/lib/python3.7/importlib/_bootstrap.py in _call_with_frames_removed(f, *args, **kwds)

/anaconda3/envs/dask_env/lib/python3.7/site-packages/pyarrow/orc.py in <module>
     23 from pyarrow.lib import Schema
---> 24 import pyarrow._orc as _orc
     25

ModuleNotFoundError: No module named 'pyarrow._orc'

During handling of the above exception, another exception occurred:

RuntimeError                              Traceback (most recent call last)
<ipython-input-3-67de491f90db> in <module>
----> 1 orders = dd.read_orc(orders_path)

/anaconda3/envs/dask_env/lib/python3.7/site-packages/dask/dataframe/io/orc.py in read_orc(path, columns, storage_options)
     46     ...                  'master/examples/demo-11-zlib.orc')  # doctest: +SKIP
     47     """
---> 48     orc = import_required("pyarrow.orc", "Please install pyarrow >= 0.9.0")
     49     import pyarrow as pa
     50

/anaconda3/envs/dask_env/lib/python3.7/site-packages/dask/utils.py in import_required(mod_name, error_msg)
     97         return import_module(mod_name)
     98     except ImportError:
---> 99         raise RuntimeError(error_msg)
    100
    101

RuntimeError: Please install pyarrow >= 0.9.0
</code>```

As far as I can tell, I'm using a supported version of all relevant entities python=3.7 and pyarrow >= 0.9.0.

Any suggestions towards what to try next would be great!

答:
Pasting conversation from the dask/dev gitter channel (thanks @uwe-l-korn ):

For pyarrow installed with pip,

ORC builds are disabled in the wheels due to linking issues:

https://github.com/apache/arrow/blob/f79a38169bd2e29b0dc2f27cf0006b9fec613774/python/manylinux201x/build_arrow.sh#L46-L48

Might be solved by updating ORC and protobuf versions in these scripts
  but this needs a volunteer to look at.

The simplest solution for this question, then, would be to install pyarrow using conda.

ContentLicense: CC BY-SA 4.0

Title: Trying to Read ORC as Dask Dataframe

Body:
I have an ORC file in s3 that I would like to read into a Dask dataframe.  I'm using conda to get a python 3.7 virtual env and I have Dask installed.  My environment looks like this:

# Name                    Version                   Build  Channel
appnope                   0.1.0                    py37_0
backcall                  0.1.0                    py37_0
blas                      1.0                         mkl
bokeh                     2.0.2                    py37_0
ca-certificates           2020.1.1                      0
certifi                   2020.4.5.1               py37_0
click                     7.1.2                      py_0
cloudpickle               1.4.1                      py_0
cytoolz                   0.10.1           py37h1de35cc_0
dask                      2.17.0                     py_0
dask-core                 2.17.0                     py_0
decorator                 4.4.2                      py_0
distributed               2.17.0                   py37_0
entrypoints               0.3                      py37_0
freetype                  2.9.1                hb4e5f40_0
fsspec                    0.7.1                      py_0
heapdict                  1.0.1                      py_0
intel-openmp              2019.4                      233
ipykernel                 5.1.4            py37h39e3cac_0
ipython                   7.13.0           py37h5ca1d4c_0
ipython_genutils          0.2.0                    py37_0
jedi                      0.17.0                   py37_0
jinja2                    2.11.2                     py_0
jpeg                      9b                   he5867d9_2
jupyter_client            6.1.3                      py_0
jupyter_core              4.6.3                    py37_0
libcxx                    10.0.0                        1
libedit                   3.1.20181209         hb402a30_0
libffi                    3.3                  h0a44026_1
libgfortran               3.0.1                h93005f0_2
libpng                    1.6.37               ha441bb4_0
libsodium                 1.0.16               h3efe00b_0
libtiff                   4.1.0                hcb84e12_0
locket                    0.2.0                    py37_1
markupsafe                1.1.1            py37h1de35cc_0
mkl                       2019.4                      233
mkl-service               2.3.0            py37hfbe908c_0
mkl_fft                   1.0.15           py37h5e564d8_0
mkl_random                1.1.1            py37h959d312_0
msgpack-python            1.0.0            py37h04f5b5a_1
ncurses                   6.2                  h0a44026_1
numpy                     1.18.1           py37h7241aed_0
numpy-base                1.18.1           py37h3304bdc_1
olefile                   0.46                       py_0
openssl                   1.1.1g               h1de35cc_0
packaging                 20.3                       py_0
pandas                    1.0.3            py37h6c726b0_0
parso                     0.7.0                      py_0
partd                     1.1.0                      py_0
pexpect                   4.8.0                    py37_0
pickleshare               0.7.5                    py37_0
pillow                    7.1.2            py37h4655f20_0
pip                       20.0.2                   py37_3
prompt-toolkit            3.0.4                      py_0
prompt_toolkit            3.0.4                         0
psutil                    5.7.0            py37h1de35cc_0
ptyprocess                0.6.0                    py37_0
pyarrow                   0.17.1                   pypi_0    pypi
pygments                  2.6.1                      py_0
pyparsing                 2.4.7                      py_0
python                    3.7.7                hf48f09d_4
python-dateutil           2.8.1                      py_0
pytz                      2020.1                     py_0
pyyaml                    5.3.1            py37h1de35cc_0
pyzmq                     18.1.1           py37h0a44026_0
readline                  8.0                  h1de35cc_0
setuptools                46.4.0                   py37_0
six                       1.14.0                   py37_0
sortedcontainers          2.1.0                    py37_0
sqlite                    3.31.1               h5c1f38d_1
tblib                     1.6.0                      py_0
tk                        8.6.8                ha441bb4_0
toolz                     0.10.0                     py_0
tornado                   6.0.4            py37h1de35cc_1
traitlets                 4.3.3                    py37_0
typing_extensions         3.7.4.1                  py37_0
wcwidth                   0.1.9                      py_0
wheel                     0.34.2                   py37_0
xz                        5.2.5                h1de35cc_0
yaml                      0.1.7                hc338f04_2
zeromq                    4.3.1                h0a44026_3
zict                      2.0.0                      py_0
zlib                      1.2.11               h1de35cc_3
zstd                      1.3.7                h5bba6e5_0

I tried to do this:

import dask.dataframe as dd
orders_path = "s3://bucketname/folder/ord_files_dir/"
orders = dd.read_orc(orders_path)

But I'm getting this error:

---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
/anaconda3/envs/dask_env/lib/python3.7/site-packages/dask/utils.py in import_required(mod_name, error_msg)
     96     try:
---> 97         return import_module(mod_name)
     98     except ImportError:

/anaconda3/envs/dask_env/lib/python3.7/importlib/__init__.py in import_module(name, package)
    126             level += 1
--> 127     return _bootstrap._gcd_import(name[level:], package, level)
    128

/anaconda3/envs/dask_env/lib/python3.7/importlib/_bootstrap.py in _gcd_import(name, package, level)

/anaconda3/envs/dask_env/lib/python3.7/importlib/_bootstrap.py in _find_and_load(name, import_)

/anaconda3/envs/dask_env/lib/python3.7/importlib/_bootstrap.py in _find_and_load_unlocked(name, import_)

/anaconda3/envs/dask_env/lib/python3.7/importlib/_bootstrap.py in _load_unlocked(spec)

/anaconda3/envs/dask_env/lib/python3.7/importlib/_bootstrap_external.py in exec_module(self, module)

/anaconda3/envs/dask_env/lib/python3.7/importlib/_bootstrap.py in _call_with_frames_removed(f, *args, **kwds)

/anaconda3/envs/dask_env/lib/python3.7/site-packages/pyarrow/orc.py in <module>
     23 from pyarrow.lib import Schema
---> 24 import pyarrow._orc as _orc
     25

ModuleNotFoundError: No module named 'pyarrow._orc'

During handling of the above exception, another exception occurred:

RuntimeError                              Traceback (most recent call last)
<ipython-input-3-67de491f90db> in <module>
----> 1 orders = dd.read_orc(orders_path)

/anaconda3/envs/dask_env/lib/python3.7/site-packages/dask/dataframe/io/orc.py in read_orc(path, columns, storage_options)
     46     ...                  'master/examples/demo-11-zlib.orc')  # doctest: +SKIP
     47     """
---> 48     orc = import_required("pyarrow.orc", "Please install pyarrow >= 0.9.0")
     49     import pyarrow as pa
     50

/anaconda3/envs/dask_env/lib/python3.7/site-packages/dask/utils.py in import_required(mod_name, error_msg)
     97         return import_module(mod_name)
     98     except ImportError:
---> 99         raise RuntimeError(error_msg)
    100
    101

RuntimeError: Please install pyarrow >= 0.9.0

As far as I can tell, I'm using a supported version of all relevant entities python=3.7 and pyarrow >= 0.9.0.

Any suggestions towards what to try next would be great!


问:
Global http response error handling in vue/axios with vuex
I'm trying to fix a behavior in my VueJS SPA wherein a limbo state arises. The app doesn't know the JWT has already expired and therefore presents itself as if the user is still logged in. This can happen after hibernation, for example.

These users can keep on making any request to the API, but end up with a 401 response (and correctly so).

I'd like to have a global handler for 401 responses. (This would be: "clear everything user-related from vuex and present the page as if the user was a guest, with login form popup, etc.") Otherwise, I would have to write a 401 handler for EVERY request.

I can add response interceptors to axios, and they work fine. These interceptors don't have access to Vuex (or Vue), though.

Whenever I try to import Vuex or Vue into my Axios, I get circular dependencies (of course) and everything breaks.

If I just throw/return the error, I still have to handle it separately on every request. How can I dispatch methods on this.$store from within an axios interceptor?

The Axios file contains an export default class API that is added to Vue globally in main.js:

```<code>import api from 'Api/api'
// ...
Vue.prototype.$http = api
</code>```

I had thought there has to be a way to access Vue from $http, since it's a global instance method. But I appear to be mistaken?

Code

main.js

```<code>// ...
import api from 'Api/api'
// ...
Vue.prototype.$http = api

new Vue({
  el: '#app',
  router,
  store,
  template: '<App/>',
  components: { App },
  vuetify: new Vuetify(opts),
});

</code>```

api.js

```<code>import Client from './ApiClient'

const apiClient = new Client({ basePath: process.env.VUE_APP_API_URL })

const api = {
  get(url) {
    return apiClient._get(`${basePath}/${url}`)
  },
  post(url, data) {
    return apiClient._post(`${basePath}/${url}`, data)
  },
  // ...
}
export default api

</code>```

ApiClient.js

```<code>const axios = require('axios')

const errorHandler = (error) => {
  if (error.response.status === 401) {
    store.dispatch('user/logout') // here is the problem
  }
  return Promise.reject({ ...error })
}

export default class API {
  constructor(options) {
    this.options = Object.assign({ basePath: '' }, options)
    this.axios = axios.create({ timeout: 60000 })
    this.axios.interceptors.response.use(
      response => response,
      error => errorHandler(error)
    )
  }
  // ...
}
</code>```

Importing store in ApiClient.js results in a dependency cycle: I assume because I'm importing Vue in it?

store.js

```<code>import Vue from 'vue'
import Vuex from 'vuex'
import PersistedState from 'vuex-persistedstate'
import CreateMutationsSharer from 'vuex-shared-mutations';
import SecureLS from 'secure-ls';
// import modules

Vue.use(Vuex);
const ls = new SecureLS({ encodingType: 'aes' });

export default new Vuex.Store({
  // options
})
</code>```

答:
main.js:

```<code>import store from './store';

const Instance = new Vue({
  store,
  ...
})

export const { $store } = Instance;
</code>```

Now you can import { $store } from '@/main.js' anywhere you want. And it's going to be the same instance you have mounted in your app, not a new Vuex.Store({}) (which is what ./store exports, each time you import it somewhere else).

You can export the same way anything else you might want to use in services, tests, helpers, etc... I.e:

```<code>export const { $store, $http, $bus, $t } = Instance;
</code>```

Body:
I'm trying to fix a behavior in my VueJS SPA wherein a limbo state arises. The app doesn't know the JWT has already expired and therefore presents itself as if the user is still logged in. This can happen after hibernation, for example.

These users can keep on making any request to the API, but end up with a 401 response (and correctly so).

I'd like to have a global handler for 401 responses. (This would be: "clear everything user-related from vuex and present the page as if the user was a guest, with login form popup, etc.") Otherwise, I would have to write a 401 handler for EVERY request.

I can add response interceptors to axios, and they work fine. These interceptors don't have access to Vuex (or Vue), though.

Whenever I try to import Vuex or Vue into my Axios, I get circular dependencies (of course) and everything breaks.

If I just throw/return the error, I still have to handle it separately on every request. How can I dispatch methods on this.$store from within an axios interceptor?

The Axios file contains an export default class API that is added to Vue globally in main.js:

import api from 'Api/api'
// ...
Vue.prototype.$http = api

I had thought there has to be a way to access Vue from $http, since it's a global instance method. But I appear to be mistaken?

Code

main.js

// ...
import api from 'Api/api'
// ...
Vue.prototype.$http = api

new Vue({
  el: '#app',
  router,
  store,
  template: '<App/>',
  components: { App },
  vuetify: new Vuetify(opts),
});

api.js

import Client from './ApiClient'

const apiClient = new Client({ basePath: process.env.VUE_APP_API_URL })

const api = {
  get(url) {
    return apiClient._get(`${basePath}/${url}`)
  },
  post(url, data) {
    return apiClient._post(`${basePath}/${url}`, data)
  },
  // ...
}
export default api

ApiClient.js

const axios = require('axios')

const errorHandler = (error) => {
  if (error.response.status === 401) {
    store.dispatch('user/logout') // here is the problem
  }
  return Promise.reject({ ...error })
}

export default class API {
  constructor(options) {
    this.options = Object.assign({ basePath: '' }, options)
    this.axios = axios.create({ timeout: 60000 })
    this.axios.interceptors.response.use(
      response => response,
      error => errorHandler(error)
    )
  }
  // ...
}

Importing store in ApiClient.js results in a dependency cycle: I assume because I'm importing Vue in it?

store.js

import Vue from 'vue'
import Vuex from 'vuex'
import PersistedState from 'vuex-persistedstate'
import CreateMutationsSharer from 'vuex-shared-mutations';
import SecureLS from 'secure-ls';
// import modules

Vue.use(Vuex);
const ls = new SecureLS({ encodingType: 'aes' });

export default new Vuex.Store({
  // options
})

Body:
main.js:

import store from './store';

const Instance = new Vue({
  store,
  ...
})

export const { $store } = Instance;

Now you can import { $store } from '@/main.js' anywhere you want. And it's going to be the same instance you have mounted in your app, not a new Vuex.Store({}) (which is what ./store exports, each time you import it somewhere else).

You can export the same way anything else you might want to use in services, tests, helpers, etc... I.e:

export const { $store, $http, $bus, $t } = Instance;


问:
Identify SQL Server deadlock on AWS RDS
Anybody know how to identify SQL Server deadlocks on AWS RDS? I try

```<code>dbcc traceon(1222,-1)
</code>```

but I don't have the necessary permissions; the AWS monitoring page doesn't have deadlock info.

答:
I'm also struggling with getting the monitoring within AWS to show the deadlocks. However, I can show you how to enable traceflag 1222. This blog post on SQLTips covers almost all of what's needed if you want to use Parameter Groups. It covers everything if you're just going to use PowerShell. Enabling it using either of these methods, and you will see the errors in the log.

One additional thing you'll need to do after you create a customized parameter group with 1222 enabled is to associate that group with your database instance. Select the instance and select modify. Scroll down to find the parameters & settings section. Select the group you defined using the instructions above.

I'm going to keep searching for a way to see the deadlocks directly in the monitor page. Implication is they should be there because you can call up the counter. However, I can't get it to generate any values.

UPDATE:
I'm continuing to research this. You can query the system_health Extended Event session. Even though Extended Events are not available within AWS RDS, system_health is still there. This query works:

```<code>    WITH fxd
AS (SELECT CAST(fx.event_data AS XML) AS Event_Data
    FROM sys.fn_xe_file_target_read_file(N'system_health*.xel', NULL, NULL, NULL) AS fx )
SELECT dl.deadlockgraph
FROM
(
    SELECT dl.query('.') AS deadlockgraph
    FROM fxd
        CROSS APPLY event_data.nodes('(/event/data/value/deadlock)') AS d(dl)
) AS dl;
</code>```

Title: Identify SQL Server deadlock on AWS RDS

Body:
Anybody know how to identify SQL Server deadlocks on AWS RDS? I try

dbcc traceon(1222,-1)

but I don't have the necessary permissions; the AWS monitoring page doesn't have deadlock info.

Body:
I'm also struggling with getting the monitoring within AWS to show the deadlocks. However, I can show you how to enable traceflag 1222. This blog post on SQLTips covers almost all of what's needed if you want to use Parameter Groups. It covers everything if you're just going to use PowerShell. Enabling it using either of these methods, and you will see the errors in the log.

One additional thing you'll need to do after you create a customized parameter group with 1222 enabled is to associate that group with your database instance. Select the instance and select modify. Scroll down to find the parameters & settings section. Select the group you defined using the instructions above.

I'm going to keep searching for a way to see the deadlocks directly in the monitor page. Implication is they should be there because you can call up the counter. However, I can't get it to generate any values.

UPDATE:
I'm continuing to research this. You can query the system_health Extended Event session. Even though Extended Events are not available within AWS RDS, system_health is still there. This query works:

    WITH fxd
AS (SELECT CAST(fx.event_data AS XML) AS Event_Data
    FROM sys.fn_xe_file_target_read_file(N'system_health*.xel', NULL, NULL, NULL) AS fx )
SELECT dl.deadlockgraph
FROM
(
    SELECT dl.query('.') AS deadlockgraph
    FROM fxd
        CROSS APPLY event_data.nodes('(/event/data/value/deadlock)') AS d(dl)
) AS dl;


问:
The request was rejected because no multipart boundary was found in springboot
As I am trying this with spring boot and webservices with postman chrome add-ons.

In postman content-type="multipart/form-data" and I am getting the below exception.

```<code>HTTP Status 500 - Request processing failed;
nested exception is org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request;
nested exception is java.io.IOException:
org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
</code>```

In Controller I specified the below code

```<code>@ResponseBody
@RequestMapping(value = "/file", headers = "Content-Type= multipart/form-data", method = RequestMethod.POST)

public String upload(@RequestParam("name") String name,
        @RequestParam(value = "file", required = true) MultipartFile file)
//@RequestParam ()CommonsMultipartFile[] fileUpload
{
    // @RequestMapping(value="/newDocument", , method = RequestMethod.POST)
    if (!file.isEmpty()) {
        try {
            byte[] fileContent = file.getBytes();
            fileSystemHandler.create(123, fileContent, name);
            return "You successfully uploaded " + name + "!";
        } catch (Exception e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name + " because the file was empty.";
    }
}
</code>```

Here I specify the file handler code

```<code>public String create(int jonId, byte[] fileContent, String name) {
    String status = "Created file...";
    try {
        String path = env.getProperty("file.uploadPath") + name;
        File newFile = new File(path);
        newFile.createNewFile();
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(newFile));
        stream.write(fileContent);
        stream.close();
    } catch (IOException ex) {
        status = "Failed to create file...";
        Logger.getLogger(FileSystemHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return status;
}
</code>```

答: Heard you can do this in postman:

ContentLicense: CC BY-SA 3.0

Body:
As I am trying this with spring boot and webservices with postman chrome add-ons.

In postman content-type="multipart/form-data" and I am getting the below exception.

HTTP Status 500 - Request processing failed;
nested exception is org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request;
nested exception is java.io.IOException:
org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

In Controller I specified the below code

@ResponseBody
@RequestMapping(value = "/file", headers = "Content-Type= multipart/form-data", method = RequestMethod.POST)

public String upload(@RequestParam("name") String name,
        @RequestParam(value = "file", required = true) MultipartFile file)
//@RequestParam ()CommonsMultipartFile[] fileUpload
{
    // @RequestMapping(value="/newDocument", , method = RequestMethod.POST)
    if (!file.isEmpty()) {
        try {
            byte[] fileContent = file.getBytes();
            fileSystemHandler.create(123, fileContent, name);
            return "You successfully uploaded " + name + "!";
        } catch (Exception e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name + " because the file was empty.";
    }
}

Here I specify the file handler code

public String create(int jonId, byte[] fileContent, String name) {
    String status = "Created file...";
    try {
        String path = env.getProperty("file.uploadPath") + name;
        File newFile = new File(path);
        newFile.createNewFile();
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(newFile));
        stream.write(fileContent);
        stream.close();
    } catch (IOException ex) {
        status = "Failed to create file...";
        Logger.getLogger(FileSystemHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return status;
}

Body: Heard you can do this in postman:


问:
Release an amount of pallets from a pallet rack to a certain time
I would like to release an amount of pallets to certain times loaded from my databases with a dynamic event. So for example at 6 am 50 pallets should leave my pallet rack. At 8 am another 20 pallets should leave the PR. I get the following function but I don't know how I use it in connection with a dynamic event and the parameters which determine the quantities of the pallets. So where can I insert the parameter? In this function below or should I create a dynamic event where I use the pallets in "action". I read a lot about dynamic events but don't understand it in connection with a database.

```<code>List< Date > dates=selectFrom(database).list(database.dates);
for(Date date : dates ) {
    Date today=date();
    long diff = date.getTime() - today.getTime();
    create_MyDynamicEvent(diff,MILLISECOND);
}
</code>```

database

答:
the dynamic events can take arguments... when you create it with arguments...
Like this:

then you can generate the event with the argument that defines the quantity that you need to use:
create_MyDynamicEvent(diff,MILLISECOND, amount);

Then in your dynamic event you release the required pallets, however you do that.

Your code will be:

```<code>List< Tuple > amounts =selectFrom( my_db ).list();
for( Tuple tup : amounts ) {
    Date today=date();
    Date future=tup.get(my_db.dates);
    long diff = future.getTime() - today.getTime();
    int amount=tup.get(my_db.amount);
    create_MyDynamicEvent(diff,MILLISECOND,amount);
}
</code>```

Body:
I would like to release an amount of pallets to certain times loaded from my databases with a dynamic event. So for example at 6 am 50 pallets should leave my pallet rack. At 8 am another 20 pallets should leave the PR. I get the following function but I don't know how I use it in connection with a dynamic event and the parameters which determine the quantities of the pallets. So where can I insert the parameter? In this function below or should I create a dynamic event where I use the pallets in "action". I read a lot about dynamic events but don't understand it in connection with a database.

List< Date > dates=selectFrom(database).list(database.dates);
for(Date date : dates ) {
    Date today=date();
    long diff = date.getTime() - today.getTime();
    create_MyDynamicEvent(diff,MILLISECOND);
}

database

Body:
the dynamic events can take arguments... when you create it with arguments...
Like this:

then you can generate the event with the argument that defines the quantity that you need to use:
create_MyDynamicEvent(diff,MILLISECOND, amount);

Then in your dynamic event you release the required pallets, however you do that.

Your code will be:

List< Tuple > amounts =selectFrom( my_db ).list();
for( Tuple tup : amounts ) {
    Date today=date();
    Date future=tup.get(my_db.dates);
    long diff = future.getTime() - today.getTime();
    int amount=tup.get(my_db.amount);
    create_MyDynamicEvent(diff,MILLISECOND,amount);
}


问:
Does + 1 really matter in the python function below?
I am new to programming and I'm taking a online course in python. I have a question to ask about a line in the below function:

```<code>def sum_first_n(n):
    result = 0
    for i in range(n):
        result += i + 1
    print(result)
sum_first_n(100)
</code>```

The result is 5050. Now looking at line 4: result += i  + 1, if I remove the  + 1  from that line, I still get the same result. Can anyone kindly explain what the work of + 1 is or can it be omitted when writing?

答:
'result += i + 1' is the same as 'result = result + i + 1'.

'result = result + i + 1' leads to 5050 and 'result = result + i' leads to 4050.

Maybe you are missing any environment option.

Body:
I am new to programming and I'm taking a online course in python. I have a question to ask about a line in the below function:

def sum_first_n(n):
    result = 0
    for i in range(n):
        result += i + 1
    print(result)
sum_first_n(100)

The result is 5050. Now looking at line 4: result += i  + 1, if I remove the  + 1  from that line, I still get the same result. Can anyone kindly explain what the work of + 1 is or can it be omitted when writing?


问:
How to create a RedHat repository with a reduced set of packages
Dears,

I am managing a pool of servers running under RHEL 7.6, I created a local repository of RHEL packages to be able to udpated the other servers by limiting the internet access to the server hosting the local repository.

I used the reposync command to populate my repository but I am downloading a huge number of rpms packages!

I would like to reduce the set of packages to download to the ones already deployed on all the severs, I can do the list using the rpm command, (~750 packages).

I read that there is an includepkgs directive to be used with the reposync command.
How is it working, what is the required format?

I know it is possible to use the yumdownloader command to update the local repository, how is it possible to populate the repository for the first time ?

Any help advice would be appreciated

Regards
Fdv

答:
It seems that the best option is to limit to the last version of the packages by using the option : </p>

```<code>-n, --newest-only     Download only newest packages per-repo
</code>```

Body:
It seems that the best option is to limit to the last version of the packages by using the option :

-n, --newest-only     Download only newest packages per-repo


问:
unable to log in to apache superset
I installed Apache superset through docker but I cannot make the login. I am trying use admin/admin credentials but it returns invalid login.
I am trying to use some information found here, like docker-compose exec superset bash -c 'export FLASK_APP=superset && flask fab create-admin' but I got the error flask_appbuilder.security.sqla.manager:Error adding new user to database. (psycopg2.ProgrammingError) relation "ab_user_role" does not exist
LINE 1: INSERT INTO ab_user_role (id, user_id, role_id) VALUES (next....

I am beginner in use docker and Apache superset, could someone help me to understand what is going wrong?

答:
I had the same error. Apparently, you need to create the db. Run this first:</p>

```<code>docker-compose run --rm -e FLASK_APP=superset superset flask fab create-db
</code>```

Title: unable to log in to apache superset

Body:
I had the same error. Apparently, you need to create the db. Run this first:

docker-compose run --rm -e FLASK_APP=superset superset flask fab create-db


问:
Stuck in Processing Update for over a month
We try to get an update into the play store for over a month now (34 days). But we‘re basically stuck in „processing update“.

We tried to contact the Google Play Console support, they can‘t help us, they keep telling us „it takes time“. We also tried to contact them via Twitter, their they either said „it takes time“ and once „you were rejected, check the email for details“.

We never got an email, so we have no clue what‘s going on, we asked them to send the email again, no response.

Is there any way to get in touch with the review team to get this sorted, we‘re getting mad with this problem.

答:
So basically nothing really helped here besides waiting, after 36 days both updates got approved. End of story.

Unless you know someone at the review team you won't have any luck.


问:
Use Multiple Services for Singleton in ASP.NET Core 3.1
I am using the repository method for a data access class. So the constructor looks something like this:

```<code>public class MongoDbUnitOfWork : IMongoDbUnitOfWork
{

    private readonly ILogger _logger;
    private readonly IConfiguration _config;

    public MongoDbUnitOfWork(ILogger logger, IConfiguration config)
    {
        _logger = logger;
        _config = config

        //do other stuff here, create database connection, etc.
    }

}

public interface IMongoDbUnitOfWork
{
    // various methods go in here
}
</code>```

The key thing is that the constructor relies on the fact that 2 services are parsed to it.

Then in startup.cs I tried to do the following:

```<code>
public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IMongoDbUnitOfWork>(sp =>
    {
        var logger = sp.GetRequiredService<ILogger>();
        var config = sp.GetRequiredService<IConfiguration>();
        return new MongoDbUnitOfWork(logger, config);
    });

    //add other services

}

</code>```

This compiled but did not work when I tried to run an API route through a controller. I got an error stating:

```<code>System.InvalidOperationException: Unable to resolve service for type 'NamespaceDetailsHere.IMongoDbUnitOfWork' while attempting to activate 'NamespaceDetailsHere.Controllersv1.TestController'.
</code>```

Then I ran a little Debug.WriteLine() script in startup.cs to see whether the ILogger and IConfiguration services existed. They did. I'm not sure what I'm doing wrong here.

答:
The ASP.NET Core service container will automatically resolve the services dependencies that are injected through the constructor, so you dont need the action configuration at all. When the service is constructed, any dependencies in the constructor are automatically required (as you're able to see with the exception).

Simply register your services with

```<code>services.AddSingleton<IMongoDbUnitOfWork, MongoDbUnitOfWork>();
</code>```

Body:
I am using the repository method for a data access class. So the constructor looks something like this:

public class MongoDbUnitOfWork : IMongoDbUnitOfWork
{

    private readonly ILogger _logger;
    private readonly IConfiguration _config;

    public MongoDbUnitOfWork(ILogger logger, IConfiguration config)
    {
        _logger = logger;
        _config = config

        //do other stuff here, create database connection, etc.
    }

}

public interface IMongoDbUnitOfWork
{
    // various methods go in here
}

The key thing is that the constructor relies on the fact that 2 services are parsed to it.

Then in startup.cs I tried to do the following:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IMongoDbUnitOfWork>(sp =>
    {
        var logger = sp.GetRequiredService<ILogger>();
        var config = sp.GetRequiredService<IConfiguration>();
        return new MongoDbUnitOfWork(logger, config);
    });

    //add other services

}

This compiled but did not work when I tried to run an API route through a controller. I got an error stating:

System.InvalidOperationException: Unable to resolve service for type 'NamespaceDetailsHere.IMongoDbUnitOfWork' while attempting to activate 'NamespaceDetailsHere.Controllersv1.TestController'.

Then I ran a little Debug.WriteLine() script in startup.cs to see whether the ILogger and IConfiguration services existed. They did. I'm not sure what I'm doing wrong here.

Body:
The ASP.NET Core service container will automatically resolve the services dependencies that are injected through the constructor, so you dont need the action configuration at all. When the service is constructed, any dependencies in the constructor are automatically required (as you're able to see with the exception).

Simply register your services with

services.AddSingleton<IMongoDbUnitOfWork, MongoDbUnitOfWork>();


问:
How to set cookie for a different website when open new browser tab
Good afternoon,
I have a problem that I would like to get your help with if it were possible.

First of all I would like to mention that I am using Angular with TypeScript.
I am trying to make a kind of single sign on of several websites in a single application and I am having some problems when it comes to redirecting to the desired website.
All websites that I am trying to sign in cannot be changed and I can only make changes to the application I am developing.
On the client side, I make a request to the API (NodeJS) that performs the authentication on the intended website and returns an authentication cookie to the client.

So far so good, it's working perfectly. The problem arises when I need to open a new browser tab and pass the authentication cookie I received.
When opening a new tab I am forwarding to the page after login and I need the cookie for that task.

I tried to set the cookie in the browser to a different domain but without success.
Can someone help me, whether it is trying to find a solution or indicating a possible different way to solve the problem?
I would like to mention that the domain of all websites are different from each other and different from the application I am developing.

Thank you in advance to anyone who can help or direct me to the solution and I apologize if I did not understand perfectly what I want. Any doubts tell me that I try to explain better.

Regards,
André Pinto

答:
From frontend you cannot set a cookie of another domain, but what you can do is to have a php page, which sets cookie of another domain or have a backend redirect. you can use this article for detailed information :-

https://subinsb.com/set-same-cookie-on-different-domains/

On reference link more :- Setting cookie for different domain from javascript


问:
Android Gradle build is taking lot of time to execute the code
Earlier, build was taking only 2 to 3 minutes to run, but now it's taking 8 to 11 minutes. I found in Task Manager, OpenJDK platform uses high memory. But I did not get any resource to overcome this. Please give me suggestion to solve this.

答:
You can find some information Android studio is slow in gradle building

Also you could update your Android Studio's Gradle plugin if you hadn't done it before.


问:
Spring Kafka can not deserialize JSON
My consumer, which is a Spring Boot application, uses Spring Kafka. It is supposed to read messages from a topic in JSON format. When the messages are "small", everything goes without problems.

However, when the message is "big" (which is not actually that big - 6,7kB), my application throws the following exception. The input JSON is valid:

```<code>org.apache.kafka.common.errors.SerializationException: Error deserializing key/value for partition input-topic-0 at offset 0. If needed, please seek past the record to continue consumption.
Caused by: org.apache.kafka.common.errors.SerializationException: Can't deserialize data [[31, 58, 55,...]]
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Unexpected end-of-input in VALUE_STRING
</code>```

Please, be aware, that [[INT1, INT2, INT3,...]] denotes just a beginning of a long sequence of integers.

Example of a "small" JSON, that is processed without any problems (138 characters):

```<code>{"attr1":"value","timestamp":1589880366240,"encoding":"UTF-8aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}
</code>```

Example of a "big" JSON, that throws exception (4648 characters, 6,7kB):

```<code>{"attr1":"value","timestamp":1589880366240,"encoding":"[encoded data, 4600 characters]"}
</code>```

When I consumed the input topic, which the JSON was produced to, the "big" consumed JSON were cut to first 4087 characters. Therefore, I suspect, that the problem is in Kafka config.

答:
Have you tried setting String deserializers for the key and values explicitly( in consumer factory)?

Please refer to the below code snippet. Thanks!

DefaultKafkaConsumerFactory<String, String> factory =
    new DefaultKafkaConsumerFactory<String, String>(props, new StringDeserializer(), new StringDeserializer());

Title: Spring Kafka can not deserialize JSON

Body:
My consumer, which is a Spring Boot application, uses Spring Kafka. It is supposed to read messages from a topic in JSON format. When the messages are "small", everything goes without problems.

However, when the message is "big" (which is not actually that big - 6,7kB), my application throws the following exception. The input JSON is valid:

org.apache.kafka.common.errors.SerializationException: Error deserializing key/value for partition input-topic-0 at offset 0. If needed, please seek past the record to continue consumption.
Caused by: org.apache.kafka.common.errors.SerializationException: Can't deserialize data [[31, 58, 55,...]]
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Unexpected end-of-input in VALUE_STRING

Please, be aware, that [[INT1, INT2, INT3,...]] denotes just a beginning of a long sequence of integers.

Example of a "small" JSON, that is processed without any problems (138 characters):

{"attr1":"value","timestamp":1589880366240,"encoding":"UTF-8aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}

Example of a "big" JSON, that throws exception (4648 characters, 6,7kB):

{"attr1":"value","timestamp":1589880366240,"encoding":"[encoded data, 4600 characters]"}

When I consumed the input topic, which the JSON was produced to, the "big" consumed JSON were cut to first 4087 characters. Therefore, I suspect, that the problem is in Kafka config.


问:
Python alters original list despite using list.copy()
So I just encountered something weird.

I had problems with copying lists and altering when I started programming, then learned that I had to use my_list.copy() to get an actual copy. Now I just stumbled upon the same effect, despite using list.copy().

So here is an example:

```<code>ori = [['1', '2', '3'],['1', '2', '3'],['1', '2', '3'],['1', '2', '3']]
copy = ori.copy()

for i, item in enumerate(copy):
    del copy[i][0]

print('Original list: ', ori)
print('Copy of list: ', copy)
</code>```

What I expected as output:

```<code>Original list: [['1', '2', '3'],['1', '2', '3'],['1', '2', '3'],['1', '2', '3']]
Copy of list: [['2', '3'], ['2', '3'], ['2', '3'], ['2', '3']]
</code>```

Actual output:

```<code>Original list: [['2', '3'],['2', '3'],['2', '3'],['2', '3']]
Copy of list: [['2', '3'], ['2', '3'], ['2', '3'], ['2', '3']]
</code>```

So I guess my question is: Is this expected behaviour? Do I need to use copy.deepcopy() or is there another solution with built in tools?

I am using Python 3.8.1 on the PC I just had this 'issue'.

答:
The copy() method returns a shallow copy of the list.
Use copy.deepcopy() instead.

Body:
So I just encountered something weird.

I had problems with copying lists and altering when I started programming, then learned that I had to use my_list.copy() to get an actual copy. Now I just stumbled upon the same effect, despite using list.copy().

So here is an example:

ori = [['1', '2', '3'],['1', '2', '3'],['1', '2', '3'],['1', '2', '3']]
copy = ori.copy()

for i, item in enumerate(copy):
    del copy[i][0]

print('Original list: ', ori)
print('Copy of list: ', copy)

What I expected as output:

Original list: [['1', '2', '3'],['1', '2', '3'],['1', '2', '3'],['1', '2', '3']]
Copy of list: [['2', '3'], ['2', '3'], ['2', '3'], ['2', '3']]

Actual output:

Original list: [['2', '3'],['2', '3'],['2', '3'],['2', '3']]
Copy of list: [['2', '3'], ['2', '3'], ['2', '3'], ['2', '3']]

So I guess my question is: Is this expected behaviour? Do I need to use copy.deepcopy() or is there another solution with built in tools?

I am using Python 3.8.1 on the PC I just had this 'issue'.


问:
how do I pass information from one class to another
I am creating a program which allows the user to input details of customers. When they have saved each customers record there is the choice to add additional information. I am having trouble getting the the name of the saved file in my append class. I need the filename so I  can then save the additional information to the same file already created for the customer. How do I pass the file name from one file to another.

```<code>File FName = fileChooser.getSelectedFile();
      String name = FName.getName();

 public String getname() { return name; }
</code>```

This code is in my customer class how do I get this information in my append class??

答:
There are a couple of ways to do this depending on what exactly it is you are trying to do.

Give the Append class a member variable of the Customer class

Have the Append class constructor take a parameter that would refer to a Customer, such as a String of name or a Customer object as this is Java

Body:
I am creating a program which allows the user to input details of customers. When they have saved each customers record there is the choice to add additional information. I am having trouble getting the the name of the saved file in my append class. I need the filename so I  can then save the additional information to the same file already created for the customer. How do I pass the file name from one file to another.

File FName = fileChooser.getSelectedFile();
      String name = FName.getName();

 public String getname() { return name; }

This code is in my customer class how do I get this information in my append class??


问:
How can I call a method within a parent view from a child view in xamarin forms with paramaters
I have tried to use Parent.Parent to be able to call the desired function within the parent view but I get the "Object not set to an instance" exception. Is there another method of doing this?

The following is the event to which the method within the parent view should be triggered.
event within child view which should call function within parent view

This Parent.Parent will only get me to the "telerikDataControls:NonVirtualizedItemsControl"
and I require the Main parent view in order to call the function from the child view.
The following is elements that I used to display items within a list. This list is also within another list so this complicates things. This is unfortunately required for the data structure used for this data.

```<code><!--  Display items per Order  -->
                                                        <telerikDataControls:NonVirtualizedItemsControl
                                                            x:Name="lstChronicItems"
                                                            Grid.Row="1"
                                                            BackgroundColor="Transparent"
                                                            ItemsSource="{Binding Chronics, Mode=TwoWay}"
                                                            SelectionMode="None">
                                                            <telerikDataControls:NonVirtualizedItemsControl.ItemTemplate>
                                                                <DataTemplate x:DataType="local:ChronicDataModel">
                                                                    <telerikPrimitives:RadBorder>
                                                                        <views:ChronicMainItemTemplate />
                                                                    </telerikPrimitives:RadBorder>
                                                                </DataTemplate>
                                                            </telerikDataControls:NonVirtualizedItemsControl.ItemTemplate>
                                                        </telerikDataControls:NonVirtualizedItemsControl>
</code>```

I hope this helps.. Thank you

答:
You could use Xamarin.Forms MessagingCenter , as the documentation mentioned ,the class implements the publish-subscribe pattern, allowing message-based communication between components that are inconvenient to link by object and type references .

Usage below

```<code>//in child view
MessagingCenter.Send<object, string>(this, "Hi", "John");    //parameter "John"

//in parent view
MessagingCenter.Subscribe<MainPage, string>(this, "Hi", async (sender, arg) =>
{
  //call the method
});
</code>```

Body:
I have tried to use Parent.Parent to be able to call the desired function within the parent view but I get the "Object not set to an instance" exception. Is there another method of doing this?

The following is the event to which the method within the parent view should be triggered.
event within child view which should call function within parent view

This Parent.Parent will only get me to the "telerikDataControls:NonVirtualizedItemsControl"
and I require the Main parent view in order to call the function from the child view.
The following is elements that I used to display items within a list. This list is also within another list so this complicates things. This is unfortunately required for the data structure used for this data.

                                                        <telerikDataControls:NonVirtualizedItemsControl
                                                            x:Name="lstChronicItems"
                                                            Grid.Row="1"
                                                            BackgroundColor="Transparent"
                                                            ItemsSource="{Binding Chronics, Mode=TwoWay}"
                                                            SelectionMode="None">
                                                            <telerikDataControls:NonVirtualizedItemsControl.ItemTemplate>
                                                                <DataTemplate x:DataType="local:ChronicDataModel">
                                                                    <telerikPrimitives:RadBorder>
                                                                        <views:ChronicMainItemTemplate />
                                                                    </telerikPrimitives:RadBorder>
                                                                </DataTemplate>
                                                            </telerikDataControls:NonVirtualizedItemsControl.ItemTemplate>
                                                        </telerikDataControls:NonVirtualizedItemsControl>

I hope this helps.. Thank you

Body:
You could use Xamarin.Forms MessagingCenter , as the documentation mentioned ,the class implements the publish-subscribe pattern, allowing message-based communication between components that are inconvenient to link by object and type references .

Usage below

//in child view
MessagingCenter.Send<object, string>(this, "Hi", "John");    //parameter "John"

//in parent view
MessagingCenter.Subscribe<MainPage, string>(this, "Hi", async (sender, arg) =>
{
  //call the method
});


问:
Laravel validation messages array indices starting from 0
If in a form request I have rules

```<code>[
    'items' => ['required', 'array'],
    'items.*' => ['required', 'numeric'],
]
</code>```

Then error message returns like this:

```<code>"items.0" => array:1 [
  0 => "The selected items.0 is invalid."
]
</code>```

Is there any way to have the message look like "The selected items #1 is invalid" or something similar, that is actually human readable?

Please note, I need this for the whole system globally, there's already >500 form request classes, although not that many are using array validation, so changing extended class or adding a trait wouldn't be too horrible

答:
Try This,</p>

```<code>[
   'items' => ['required', 'array'],
   'items.*' => ['required', 'numeric'],
],
[
    'items.required' => 'Your Message',
]
</code>```

Body:
If in a form request I have rules

[
    'items' => ['required', 'array'],
    'items.*' => ['required', 'numeric'],
]

Then error message returns like this:

"items.0" => array:1 [
  0 => "The selected items.0 is invalid."
]

Is there any way to have the message look like "The selected items #1 is invalid" or something similar, that is actually human readable?

Please note, I need this for the whole system globally, there's already >500 form request classes, although not that many are using array validation, so changing extended class or adding a trait wouldn't be too horrible

Body:
Try This,

[
   'items' => ['required', 'array'],
   'items.*' => ['required', 'numeric'],
],
[
    'items.required' => 'Your Message',
]


问:
A classloader problem related to spring-boot-devtools
Background:
Spring boot project, add goods and goods price list

```<code>Goods:
List<GoodsPrice> pricelist;
</code>```

in controller first convert goodsForm to goods(by dozer), then save goods,after saving goods iterate goods price list to populate goodsId.

```<code>goods.getPriceList().forEach(p -> p.setGoodsId(goods.getId()));
</code>```

When iterate goods price list, throw exception:

```<code>java.lang.ClassCastException: com.foo.goods.model.GoodsPrice cannot be cast to com.foo.goods.model.GoodsPrice
at com.foo.goods.service.GoodsService$$Lambda$11/310447431.accept(Unknown Source) ~[na:na]
at java.util.ArrayList.forEach(ArrayList.java:1249) ~[na:1.8.0_51]
at com.foo.goods.service.GoodsService.saveGoods(GoodsService.java:34) ~[classes/:na]
</code>```

Somebody remind me this exception related to classloader, and in eclipse debug mode, I outputed the GoodsPrice's ClassLoader:

```<code>sun.misc.Launcher$AppClassLoader@14dad5dc
</code>```

and goods:
    org.springframework.boot.devtools.restart.classloader.RestartClassLoader@591c6338

Indeed exist diff classloader.
Then I commented spring-boot-devtools then tried again this time it's ok.
So if still retain spring-boot-devtools, how to solve this problem?

答:
The same has been asked here.

You need to set the excludeDevTools to false

Body:
Background:
Spring boot project, add goods and goods price list

Goods:
List<GoodsPrice> pricelist;

in controller first convert goodsForm to goods(by dozer), then save goods,after saving goods iterate goods price list to populate goodsId.

goods.getPriceList().forEach(p -> p.setGoodsId(goods.getId()));

When iterate goods price list, throw exception:

java.lang.ClassCastException: com.foo.goods.model.GoodsPrice cannot be cast to com.foo.goods.model.GoodsPrice
at com.foo.goods.service.GoodsService$$Lambda$11/310447431.accept(Unknown Source) ~[na:na]
at java.util.ArrayList.forEach(ArrayList.java:1249) ~[na:1.8.0_51]
at com.foo.goods.service.GoodsService.saveGoods(GoodsService.java:34) ~[classes/:na]

Somebody remind me this exception related to classloader, and in eclipse debug mode, I outputed the GoodsPrice's ClassLoader:

sun.misc.Launcher$AppClassLoader@14dad5dc

and goods:
    org.springframework.boot.devtools.restart.classloader.RestartClassLoader@591c6338

Indeed exist diff classloader.
Then I commented spring-boot-devtools then tried again this time it's ok.
So if still retain spring-boot-devtools, how to solve this problem?


问:
execute exe from incomplete name in .bat
I wanna make a .bat for installing service, I use that

```<code>C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil.exe "ServiceName.exe"
</code>```

But the "v4.0.30319" can be "v4.0.otherVersion" and I look for a way to execute anyway.
I searched a lot of but didn't find something who work and I'm really bad with bash.

Thanks.

答:
Based upon your provided information, this idea retrieves the location you require from the registry:

@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "Net4RegPath=HKLM\SOFTWARE\Microsoft\Net Framework Setup\NDP\v4"
Set "InstallUtil="
For /F "EOL=HTokens=2*" %%G In (
    '%__AppDir__%reg.exe Query "%Net4RegPath%" /S /F "InstallPath" /V /E
     2^>NUL^|%__AppDir__%find.exe "_SZ"')Do For /F "Delims=" %%I In (
    '%__AppDir__%where.exe "%%~H\.":"InstallUtil.exe" 2^>NUL'
)Do Set "InstallUtil=%%I"
If Defined InstallUtil "%InstallUtil%" "ServiceName.exe"
```

Please note that this will not currently retrieve the appropriate file path if you're wanting to specifically identify the location of the x86 InstallUtil.exe file on an x64 OS. But as that is technically outside of the scope of your question at the time of answering, I'll leave that for you to implement if required.

Body:
I wanna make a .bat for installing service, I use that

C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil.exe "ServiceName.exe"

But the "v4.0.30319" can be "v4.0.otherVersion" and I look for a way to execute anyway.
I searched a lot of but didn't find something who work and I'm really bad with bash.

Thanks.

Body:
Based upon your provided information, this idea retrieves the location you require from the registry:

@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "Net4RegPath=HKLM\SOFTWARE\Microsoft\Net Framework Setup\NDP\v4"
Set "InstallUtil="
For /F "EOL=HTokens=2*" %%G In (
    '%__AppDir__%reg.exe Query "%Net4RegPath%" /S /F "InstallPath" /V /E
     2^>NUL^|%__AppDir__%find.exe "_SZ"')Do For /F "Delims=" %%I In (
    '%__AppDir__%where.exe "%%~H\.":"InstallUtil.exe" 2^>NUL'
)Do Set "InstallUtil=%%I"
If Defined InstallUtil "%InstallUtil%" "ServiceName.exe"

Please note that this will not currently retrieve the appropriate file path if you're wanting to specifically identify the location of the x86 InstallUtil.exe file on an x64 OS. But as that is technically outside of the scope of your question at the time of answering, I'll leave that for you to implement if required.


问:
The right way to pass a input to the typescript file
I know about this way to send a input from the user to the typescript (angular) :

```<code>    <form >
    <input #input type="text" [(ngModel)]="inputColor" (input)="sendInput(input.value)" />
    </form>
</code>```

But its looking for not very effective , i create a reference to the DOM with #input and after that send the input.value .

After all, I am very confused about the input.value does he refer to #input or to to (input)=...;.

Bottom line, is there a more efficient way to pass the value the user puts into the box, into the typescript file and then use it for another tag in the HTML file?

For example the user put a size of text and i want to use with the use on another tag on HTML ....

答:
If i understand well, you re looking for $event ?

```<code><input #input type="text" [(ngModel)]="inputColor" (input)="sendInput($event)" />
</code>```

typescript side:

```<code>sendInput($event) {
  console.log('input value:', $event.data);
}
</code>```

But $event.data will only contain the last typed char, is it what you re looking for ?.

EDIT:
With (input), you can have the content of input in $event.target.value:

```<code><input #input type="text" [(ngModel)]="inputColor"
(input)="sendInput($event.target.value)" />
</code>```

Body:
I know about this way to send a input from the user to the typescript (angular) :

    <form >
    <input #input type="text" [(ngModel)]="inputColor" (input)="sendInput(input.value)" />
    </form>

But its looking for not very effective , i create a reference to the DOM with #input and after that send the input.value .

After all, I am very confused about the input.value does he refer to #input or to to (input)=...;.

Bottom line, is there a more efficient way to pass the value the user puts into the box, into the typescript file and then use it for another tag in the HTML file?

For example the user put a size of text and i want to use with the use on another tag on HTML ....

Body:
If i understand well, you re looking for $event ?

<input #input type="text" [(ngModel)]="inputColor" (input)="sendInput($event)" />

typescript side:

sendInput($event) {
  console.log('input value:', $event.data);
}

But $event.data will only contain the last typed char, is it what you re looking for ?.

EDIT:
With (input), you can have the content of input in $event.target.value:

<input #input type="text" [(ngModel)]="inputColor"
(input)="sendInput($event.target.value)" />


问:
SQLITE (The system cannot find the path specified)
I am a beginner, currently learning Python. This is my first time asking a doubt on this platform.
 I (I have inserted the image here->1 )downloaded the sqlite database from sqlite.org for my windows laptop and now when i run the command prompt and try to access sqlite from there, it is saying path not found.
I am extremely confused as this is my firs time with any computer language... I am unable to figure out what the problem is. I have also typed out the problem below.

Microsoft Windows [Version 10.0.17763.914]
(c) 2018 Microsoft Corporation. All rights reserved.

C:\Users\myusername>cd\

C:>cd sqlite-tools-win32-x86-3320100

The system cannot find the path specified.

C:>

答:
After you downloaded the zip(?) file, did you extract it? If so, where did you extract it to? Assuming you downloaded it to the default location Downloads, and extracted the zip file there: your user directory is the default folder when you do cmd. Your Downloads are under that, so from the starting point, do cd Downloads (press Tab key after typing Dow to make use of auto-completion). Then cd sqlite-tools-win32-x86-3320100 (again, use Tab-completion instead of typing the whole thing) since that folder is where the extracted zip contents would go, by default.

So:

```<code>C:\Users\your_username>cd Downloads

C:\Users\your_username\Downloads>cd sqlite-tools-win32-x86-3320100

C:\Users\your_username\Downloads\sqlite-tools-win32-x86-3320100>dir
</code>```

FYI, you can do both cd's in one command:

```<code>C:\Users\your_username>cd Downloads\sqlite-tools-win32-x86-3320100

C:\Users\your_username\Downloads\sqlite-tools-win32-x86-3320100>
</code>```

Body:
After you downloaded the zip(?) file, did you extract it? If so, where did you extract it to? Assuming you downloaded it to the default location Downloads, and extracted the zip file there: your user directory is the default folder when you do cmd. Your Downloads are under that, so from the starting point, do cd Downloads (press Tab key after typing Dow to make use of auto-completion). Then cd sqlite-tools-win32-x86-3320100 (again, use Tab-completion instead of typing the whole thing) since that folder is where the extracted zip contents would go, by default.

So:

C:\Users\your_username>cd Downloads

C:\Users\your_username\Downloads>cd sqlite-tools-win32-x86-3320100

C:\Users\your_username\Downloads\sqlite-tools-win32-x86-3320100>dir

FYI, you can do both cd's in one command:

C:\Users\your_username>cd Downloads\sqlite-tools-win32-x86-3320100

C:\Users\your_username\Downloads\sqlite-tools-win32-x86-3320100>


问:
Contentful BlogPost: How can I display different category blogs on 2 different container using gatsby graphql
Hi I'm very new on using gatsby and contentful for cms. I just want to display different category blog post on the same page. Is there a way that this can be possible? Below is the code on how I show the loop of blogpost and also the graphql that gets the data from contentful(not really sure). Sorry for the bad coding. Is it possible that I make 2 different container with blogpost with different category?</p>

```<code>    const siteTitle = get(this, 'props.data.site.siteMetadata.title')
const posts = get(this, 'props.data.allContentfulBlogPost.edges')<div className="row">
<div className="col-lg-12 text-left">
    <h2>Title</h2>
</div>
    {posts.map(({ node }) => {
        return (
            <ArticlePreview article={node} />
        )
    })}
</div>
export const CommunityQuery = graphql
    query CommunityIndexQuery {
    site {
        siteMetadata {
        title
    }
    }
allContentfulBlogPost(sort: { fields: [publishDate], order: DESC }) {
    edges {
        node {
          title
          slug
          publishDate(formatString: "MMMM Do, YYYY")
          tags
          heroImage {
            fluid(maxWidth: 350, maxHeight: 156, resizingBehavior: SCALE) {
              ...GatsbyContentfulFluid_tracedSVG
            }
          }
          description {
            childMarkdownRemark {
              html
            }
          }
        }
      }
    }
}`
</code>```

答:
Yes, you can achieve this by using 2 different queries in your communityQuery. It should look like:

```<code>export const CommunityQuery = graphql
    query CommunityIndexQuery {
    site {
        siteMetadata {
        title
    }
    }
categoryOne: allContentfulBlogPost(
   filter: {category: {eq: "category one name"}}
   sort: { fields: [publishDate], order: DESC }) {
    edges {
        node {
        //your fields
        }
      }
    }
categoryTwo: allContentfulBlogPost(
   filter: {category: {eq: "category two name"}}
   sort: { fields: [publishDate], order: DESC }) {
    edges {
        node {
        //your fields
        }
      }
    }
}`
</code>```

Note: keep in mind that you provided a generic query so I don't know what fields or what filters you should put to filter by category, this is just an approach.

This will generate 2 objects that you can retrieve easily by props.data.categoryOne and props.data.categoryTwo (that queries are aliased, it's a good way to clean up your code, if don't, your object may look like: props.data.allContentfulBlogPost).

Body:
Hi I'm very new on using gatsby and contentful for cms. I just want to display different category blog post on the same page. Is there a way that this can be possible? Below is the code on how I show the loop of blogpost and also the graphql that gets the data from contentful(not really sure). Sorry for the bad coding. Is it possible that I make 2 different container with blogpost with different category?

    const siteTitle = get(this, 'props.data.site.siteMetadata.title')
const posts = get(this, 'props.data.allContentfulBlogPost.edges')

Title

    {posts.map(({ node }) => {
        return (
            <ArticlePreview article={node} />
        )
    })}

export const CommunityQuery = graphql
    query CommunityIndexQuery {
    site {
        siteMetadata {
        title
    }
    }
allContentfulBlogPost(sort: { fields: [publishDate], order: DESC }) {
    edges {
        node {
          title
          slug
          publishDate(formatString: "MMMM Do, YYYY")
          tags
          heroImage {
            fluid(maxWidth: 350, maxHeight: 156, resizingBehavior: SCALE) {
              ...GatsbyContentfulFluid_tracedSVG
            }
          }
          description {
            childMarkdownRemark {
              html
            }
          }
        }
      }
    }
}`

Body:
Yes, you can achieve this by using 2 different queries in your communityQuery. It should look like:

export const CommunityQuery = graphql
    query CommunityIndexQuery {
    site {
        siteMetadata {
        title
    }
    }
categoryOne: allContentfulBlogPost(
   filter: {category: {eq: "category one name"}}
   sort: { fields: [publishDate], order: DESC }) {
    edges {
        node {
        //your fields
        }
      }
    }
categoryTwo: allContentfulBlogPost(
   filter: {category: {eq: "category two name"}}
   sort: { fields: [publishDate], order: DESC }) {
    edges {
        node {
        //your fields
        }
      }
    }
}`

Note: keep in mind that you provided a generic query so I don't know what fields or what filters you should put to filter by category, this is just an approach.

This will generate 2 objects that you can retrieve easily by props.data.categoryOne and props.data.categoryTwo (that queries are aliased, it's a good way to clean up your code, if don't, your object may look like: props.data.allContentfulBlogPost).


问:
mongoexport data from last n minutes of document using timestamp from objectID?
I want to export last n minutes data from MongoDB using mongoexport using timestamp value from objectID.

example document

{
    "_id": ObjectId("5ec428cf85aff1e13c9058a4"),
    "key": "val"
}
```

<p>Failed attempts   </p>

<pre class="lang-sh prettyprint-override"><code>mongoexport -d data -c logs -o out.json -q "{_id:{$gt: new Date(ISODate().getTime() - 1000 * 60 * 18)}}"

mongoexport -d data -c logs -o out.json -q "{'_id.getTimestamp()':{$gt: new Date(ISODate().getTime() - 1000 * 60 * 18)}}"

mongoexport -d data -c logs -o out.json -q "{'this._id.getTimestamp()':{$gt: new Date(ISODate().getTime() - 1000 * 60 * 18)}}"
</code>```

Any idea of how to do this correctly

答:
I think when passing query as JSON you will not be able to pass the new Date() function to it, also the document id is of type ObjectId so you need to convert the id to ISODate before comparing.

If you already have a valid date string eg: 2020-06-03T00:00:00.000Z then you can query like

mongoexport -d data -c logs -o out.json -q '{"$expr": {"$gt":[{"$toDate":"$_id"}, {"$toDate": "2020-06-03T00:00:00.000Z"}]}}'
```

Body:
I want to export last n minutes data from MongoDB using mongoexport using timestamp value from objectID.

example document

{
    "_id": ObjectId("5ec428cf85aff1e13c9058a4"),
    "key": "val"
}

Failed attempts

mongoexport -d data -c logs -o out.json -q "{_id:{$gt: new Date(ISODate().getTime() - 1000 * 60 * 18)}}"

mongoexport -d data -c logs -o out.json -q "{'_id.getTimestamp()':{$gt: new Date(ISODate().getTime() - 1000 * 60 * 18)}}"

mongoexport -d data -c logs -o out.json -q "{'this._id.getTimestamp()':{$gt: new Date(ISODate().getTime() - 1000 * 60 * 18)}}"

Any idea of how to do this correctly


问:
C++ Continue the execution after signal handler
I am trying to manage a signal in C++ and then continue with the program execution normally. I use signals instead of exceptions because the program blocks itself when a sensor is not connected (I can't change this).

The part of code that raise the signal uses a thread as a timer. Since the threads can't throw exceptions, I have decided to raise a signal (SIGTERM in this case).

The problem starts when I try to continue the program in the same way that with the exceptions but with the signal handler. I make use of the setjmp library to solve the problem:

```<code>jmp_buf gBuffer;
void signalHandler(int signal) {
    longjmp(gBuffer, 1);
}

int main() {
    std::signal(SIGTERM, signalHandler);

    if (setjmp(gBuffer) == 0) {
        /* ---------------------
           Part of code that raise the signal
        --------------------- */
    }
}
</code>```

It works fine, but when the program finishes, a memory error appear:

```<code>*** stack smashing detected ***: <unknown> terminated
Aborted (core dumped)
</code>```

The backtrace when execute the program in debug mode is:

```<code>Thread 2 "EXECUTABLE_FILE" received signal SIGTERM, Terminated.
[Switching to Thread 0x7ffff01f2700 (LWP 31718)]
raise (sig=<optimized out>) at ../sysdeps/unix/sysv/linux/raise.c:51
51  ../sysdeps/unix/sysv/linux/raise.c: No such file or directory.
(gdb) bt
#0  raise (sig=<optimized out>) at ../sysdeps/unix/sysv/linux/raise.c:51
#1  0x00007ffff78531ab in "THREAD THAT RAISE THE SIGNAL" (futureObj=...)
    at "LINE THAT RAISE THE SIGNAL"
#2  0x00007ffff7856ffd in std::__invoke_impl<void, void (*)(std::future<void>), std::future<void> >
    (__f=<optimized out>) at /usr/include/c++/7/bits/invoke.h:60
#3  std::__invoke<void (*)(std::future<void>), std::future<void> > (__fn=<optimized out>)
    at /usr/include/c++/7/bits/invoke.h:95
#4  std::thread::_Invoker<std::tuple<void (*)(std::future<void>), std::future<void> > >::_M_invoke<0ul, 1ul> (this=<optimized out>) at /usr/include/c++/7/thread:234
#5  std::thread::_Invoker<std::tuple<void (*)(std::future<void>), std::future<void> > >::operator()
    (this=<optimized out>) at /usr/include/c++/7/thread:243
#6  std::thread::_State_impl<std::thread::_Invoker<std::tuple<void (*)(std::future<void>), std::future<void> > > >::_M_run (this=<optimized out>) at /usr/include/c++/7/thread:186
#7  0x00007ffff6e41d80 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#8  0x00007ffff714c6db in start_thread (arg=0x7ffff01f2700) at pthread_create.c:463
#9  0x00007ffff688988f in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:95
</code>```

I really appreciate if someone could help me. I could also change the part of code that raises the signal, throwing an exception, but I don't know how to do that within a thread.

答:
You cannot do it the way you envision directly - sorry. Yes, your signal handler gets called, but in generally you cannot (and should not try to) continue execution of the main program from within a signal handler due to the limitations listed of signal handlers (eg. new signals may be blocked from being raised, etc.).

Therefore, your signal handler should set some sort of flag, eg. an atomic bool or condition variable or whatever method you prefer. Then return from the signal handler. Then have a loop near the 'offending code' that can check that and that is then able to return/unwind/terminate the timer.

Body:
I am trying to manage a signal in C++ and then continue with the program execution normally. I use signals instead of exceptions because the program blocks itself when a sensor is not connected (I can't change this).

The part of code that raise the signal uses a thread as a timer. Since the threads can't throw exceptions, I have decided to raise a signal (SIGTERM in this case).

The problem starts when I try to continue the program in the same way that with the exceptions but with the signal handler. I make use of the setjmp library to solve the problem:

jmp_buf gBuffer;
void signalHandler(int signal) {
    longjmp(gBuffer, 1);
}

int main() {
    std::signal(SIGTERM, signalHandler);

    if (setjmp(gBuffer) == 0) {
        /* ---------------------
           Part of code that raise the signal
        --------------------- */
    }
}

It works fine, but when the program finishes, a memory error appear:

*** stack smashing detected ***: <unknown> terminated
Aborted (core dumped)

The backtrace when execute the program in debug mode is:

Thread 2 "EXECUTABLE_FILE" received signal SIGTERM, Terminated.
[Switching to Thread 0x7ffff01f2700 (LWP 31718)]
raise (sig=<optimized out>) at ../sysdeps/unix/sysv/linux/raise.c:51
51  ../sysdeps/unix/sysv/linux/raise.c: No such file or directory.
(gdb) bt
#0  raise (sig=<optimized out>) at ../sysdeps/unix/sysv/linux/raise.c:51
#1  0x00007ffff78531ab in "THREAD THAT RAISE THE SIGNAL" (futureObj=...)
    at "LINE THAT RAISE THE SIGNAL"
#2  0x00007ffff7856ffd in std::__invoke_impl<void, void (*)(std::future<void>), std::future<void> >
    (__f=<optimized out>) at /usr/include/c++/7/bits/invoke.h:60
#3  std::__invoke<void (*)(std::future<void>), std::future<void> > (__fn=<optimized out>)
    at /usr/include/c++/7/bits/invoke.h:95
#4  std::thread::_Invoker<std::tuple<void (*)(std::future<void>), std::future<void> > >::_M_invoke<0ul, 1ul> (this=<optimized out>) at /usr/include/c++/7/thread:234
#5  std::thread::_Invoker<std::tuple<void (*)(std::future<void>), std::future<void> > >::operator()
    (this=<optimized out>) at /usr/include/c++/7/thread:243
#6  std::thread::_State_impl<std::thread::_Invoker<std::tuple<void (*)(std::future<void>), std::future<void> > > >::_M_run (this=<optimized out>) at /usr/include/c++/7/thread:186
#7  0x00007ffff6e41d80 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#8  0x00007ffff714c6db in start_thread (arg=0x7ffff01f2700) at pthread_create.c:463
#9  0x00007ffff688988f in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:95

I really appreciate if someone could help me. I could also change the part of code that raises the signal, throwing an exception, but I don't know how to do that within a thread.