问:
Tensorflow not detecting GPU - Adding visible gpu devices: 0
I have a system with an NVIDIA GeForce GTX 980 Ti.  I installed tensorflow, and look for the gpu device with tf.test.gpu_device_name().  It looks like it finds the gpu, but then says "Adding visible gpu devices: 0"</p>

```<code>>>> import tensorflow as tf
>>> tf.test.gpu_device_name()
2019-01-08 10:01:12.589000: I tensorflow/core/platform/cpu_feature_guard.cc:141]
 Your CPU supports instructions that this TensorFlow binary was not compiled to
use: AVX2
2019-01-08 10:01:12.855000: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1
432] Found device 0 with properties:
name: GeForce GTX 980 Ti major: 5 minor: 2 memoryClockRate(GHz): 1.228
pciBusID: 0000:01:00.0
totalMemory: 6.00GiB freeMemory: 5.67GiB
2019-01-08 10:01:12.862000: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1
511] Adding visible gpu devices: 0
</code>```

答:
I was also facing the same problem and creating a conda environment with an environment.yml file solved the issue for me. The content of the .yml file are as follows: Please make sure to provide your system path in the last line of the code. eg. "/home/nikhilanand_1921cs24" should be replaced with your system path.

```<code>name: keras-gpu
channels:
  - conda-forge
  - defaults
dependencies:
  - _libgcc_mutex=0.1=main
  - _openmp_mutex=4.5=1_gnu
  - _tflow_select=2.1.0=gpu
  - absl-py=0.13.0=py39h06a4308_0
  - aiohttp=3.8.1=py39h7f8727e_0
  - aiosignal=1.2.0=pyhd3eb1b0_0
  - astor=0.8.1=py39h06a4308_0
  - astunparse=1.6.3=py_0
  - async-timeout=4.0.1=pyhd3eb1b0_0
  - attrs=21.2.0=pyhd3eb1b0_0
  - blas=1.0=mkl
  - blinker=1.4=py39h06a4308_0
  - brotli=1.0.9=h7f98852_5
  - brotli-bin=1.0.9=h7f98852_5
  - brotlipy=0.7.0=py39h27cfd23_1003
  - c-ares=1.17.1=h27cfd23_0
  - ca-certificates=2021.10.8=ha878542_0
  - cachetools=4.2.2=pyhd3eb1b0_0
  - certifi=2021.10.8=py39hf3d152e_1
  - cffi=1.14.6=py39h400218f_0
  - charset-normalizer=2.0.4=pyhd3eb1b0_0
  - click=8.0.3=pyhd3eb1b0_0
  - cryptography=3.4.8=py39hd23ed53_0
  - cudatoolkit=10.1.243=h6bb024c_0
  - cudnn=7.6.5=cuda10.1_0
  - cupti=10.1.168=0
  - cycler=0.11.0=pyhd8ed1ab_0
  - dataclasses=0.8=pyh6d0b6a4_7
  - dbus=1.13.6=he372182_0
  - expat=2.2.10=h9c3ff4c_0
  - fontconfig=2.13.1=h6c09931_0
  - fonttools=4.25.0=pyhd3eb1b0_0
  - freetype=2.10.4=h0708190_1
  - frozenlist=1.2.0=py39h7f8727e_0
  - gast=0.4.0=pyhd3eb1b0_0
  - glib=2.69.1=h4ff587b_1
  - google-auth=1.33.0=pyhd3eb1b0_0
  - google-auth-oauthlib=0.4.4=pyhd3eb1b0_0
  - google-pasta=0.2.0=pyhd3eb1b0_0
  - grpcio=1.42.0=py39hce63b2e_0
  - gst-plugins-base=1.14.0=hbbd80ab_1
  - gstreamer=1.14.0=h28cd5cc_2
  - h5py=2.10.0=py39hec9cf62_0
  - hdf5=1.10.6=hb1b8bf9_0
  - icu=58.2=hf484d3e_1000
  - idna=3.3=pyhd3eb1b0_0
  - importlib-metadata=4.8.2=py39h06a4308_0
  - intel-openmp=2021.4.0=h06a4308_3561
  - jpeg=9d=h7f8727e_0
  - keras-preprocessing=1.1.2=pyhd3eb1b0_0
  - kiwisolver=1.3.1=py39h2531618_0
  - lcms2=2.12=hddcbb42_0
  - ld_impl_linux-64=2.35.1=h7274673_9
  - libbrotlicommon=1.0.9=h7f98852_5
  - libbrotlidec=1.0.9=h7f98852_5
  - libbrotlienc=1.0.9=h7f98852_5
  - libffi=3.3=he6710b0_2
  - libgcc-ng=9.3.0=h5101ec6_17
  - libgfortran-ng=7.5.0=ha8ba4b0_17
  - libgfortran4=7.5.0=ha8ba4b0_17
  - libgomp=9.3.0=h5101ec6_17
  - libpng=1.6.37=h21135ba_2
  - libprotobuf=3.17.2=h4ff587b_1
  - libstdcxx-ng=9.3.0=hd4cf53a_17
  - libtiff=4.2.0=h85742a9_0
  - libuuid=1.0.3=h7f8727e_2
  - libwebp-base=1.2.0=h27cfd23_0
  - libxcb=1.13=h7f98852_1003
  - libxml2=2.9.12=h03d6c58_0
  - lz4-c=1.9.3=h9c3ff4c_1
  - markdown=3.3.4=py39h06a4308_0
  - matplotlib=3.4.3=py39hf3d152e_2
  - matplotlib-base=3.4.3=py39hbbc1b5f_0
  - mkl=2021.4.0=h06a4308_640
  - mkl-service=2.4.0=py39h7f8727e_0
  - mkl_fft=1.3.1=py39hd3c417c_0
  - mkl_random=1.2.2=py39h51133e4_0
  - multidict=5.1.0=py39h27cfd23_2
  - munkres=1.1.4=pyh9f0ad1d_0
  - ncurses=6.3=h7f8727e_2
  - numpy=1.21.2=py39h20f2e39_0
  - numpy-base=1.21.2=py39h79a1101_0
  - oauthlib=3.1.1=pyhd3eb1b0_0
  - olefile=0.46=pyh9f0ad1d_1
  - openssl=1.1.1m=h7f8727e_0
  - opt_einsum=3.3.0=pyhd3eb1b0_1
  - pcre=8.45=h9c3ff4c_0
  - pip=21.2.4=py39h06a4308_0
  - protobuf=3.17.2=py39h295c915_0
  - pthread-stubs=0.4=h36c2ea0_1001
  - pyasn1=0.4.8=pyhd3eb1b0_0
  - pyasn1-modules=0.2.8=py_0
  - pycparser=2.21=pyhd3eb1b0_0
  - pyjwt=2.1.0=py39h06a4308_0
  - pyopenssl=21.0.0=pyhd3eb1b0_1
  - pyparsing=3.0.7=pyhd8ed1ab_0
  - pyqt=5.9.2=py39h2531618_6
  - pysocks=1.7.1=py39h06a4308_0
  - python=3.9.7=h12debd9_1
  - python-dateutil=2.8.2=pyhd8ed1ab_0
  - python-flatbuffers=2.0=pyhd3eb1b0_0
  - python_abi=3.9=2_cp39
  - qt=5.9.7=h5867ecd_1
  - readline=8.1=h27cfd23_0
  - requests=2.26.0=pyhd3eb1b0_0
  - requests-oauthlib=1.3.0=py_0
  - rsa=4.7.2=pyhd3eb1b0_1
  - scipy=1.7.1=py39h292c36d_2
  - setuptools=58.0.4=py39h06a4308_0
  - sip=4.19.13=py39h295c915_0
  - six=1.16.0=pyhd3eb1b0_0
  - sqlite=3.36.0=hc218d9a_0
  - tensorboard-plugin-wit=1.6.0=py_0
  - tensorflow-estimator=2.6.0=pyh7b7c402_0
  - termcolor=1.1.0=py39h06a4308_1
  - tk=8.6.11=h1ccaba5_0
  - tornado=6.1=py39h3811e60_1
  - typing-extensions=3.10.0.2=hd3eb1b0_0
  - typing_extensions=3.10.0.2=pyh06a4308_0
  - tzdata=2021e=hda174b7_0
  - urllib3=1.26.7=pyhd3eb1b0_0
  - werkzeug=2.0.2=pyhd3eb1b0_0
  - wheel=0.37.0=pyhd3eb1b0_1
  - wrapt=1.13.3=py39h7f8727e_2
  - xorg-libxau=1.0.9=h7f98852_0
  - xorg-libxdmcp=1.1.3=h7f98852_0
  - xz=5.2.5=h7b6447c_0
  - yarl=1.6.3=py39h27cfd23_0
  - zipp=3.6.0=pyhd3eb1b0_0
  - zlib=1.2.11=h7f8727e_4
  - zstd=1.4.9=ha95c52a_0
  - pip:
    - joblib==1.1.0
    - keras==2.8.0
    - keras-applications==1.0.8
    - libclang==13.0.0
    - opencv-python==4.5.5.62
    - pandas==1.4.0
    - pillow==9.0.1
    - pytz==2021.3
    - pyyaml==6.0
    - scikit-learn==1.0.2
    - tensorboard==2.8.0
    - tensorboard-data-server==0.6.1
    - tensorflow==2.8.0
    - tensorflow-gpu==2.8.0
    - tensorflow-io-gcs-filesystem==0.23.1
    - tf-estimator-nightly==2.8.0.dev2021122109
    - threadpoolctl==3.0.0
prefix: /home/nikhilanand_1921cs24/anaconda3/envs/keras-gpu
</code>```

Create the environment by runningconda env create -f environment.yml

Body:
I have a system with an NVIDIA GeForce GTX 980 Ti.  I installed tensorflow, and look for the gpu device with tf.test.gpu_device_name().  It looks like it finds the gpu, but then says "Adding visible gpu devices: 0"

>>> import tensorflow as tf
>>> tf.test.gpu_device_name()
2019-01-08 10:01:12.589000: I tensorflow/core/platform/cpu_feature_guard.cc:141]
 Your CPU supports instructions that this TensorFlow binary was not compiled to
use: AVX2
2019-01-08 10:01:12.855000: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1
432] Found device 0 with properties:
name: GeForce GTX 980 Ti major: 5 minor: 2 memoryClockRate(GHz): 1.228
pciBusID: 0000:01:00.0
totalMemory: 6.00GiB freeMemory: 5.67GiB
2019-01-08 10:01:12.862000: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1
511] Adding visible gpu devices: 0

Body:
I was also facing the same problem and creating a conda environment with an environment.yml file solved the issue for me. The content of the .yml file are as follows: Please make sure to provide your system path in the last line of the code. eg. "/home/nikhilanand_1921cs24" should be replaced with your system path.

name: keras-gpu
channels:
  - conda-forge
  - defaults
dependencies:
  - _libgcc_mutex=0.1=main
  - _openmp_mutex=4.5=1_gnu
  - _tflow_select=2.1.0=gpu
  - absl-py=0.13.0=py39h06a4308_0
  - aiohttp=3.8.1=py39h7f8727e_0
  - aiosignal=1.2.0=pyhd3eb1b0_0
  - astor=0.8.1=py39h06a4308_0
  - astunparse=1.6.3=py_0
  - async-timeout=4.0.1=pyhd3eb1b0_0
  - attrs=21.2.0=pyhd3eb1b0_0
  - blas=1.0=mkl
  - blinker=1.4=py39h06a4308_0
  - brotli=1.0.9=h7f98852_5
  - brotli-bin=1.0.9=h7f98852_5
  - brotlipy=0.7.0=py39h27cfd23_1003
  - c-ares=1.17.1=h27cfd23_0
  - ca-certificates=2021.10.8=ha878542_0
  - cachetools=4.2.2=pyhd3eb1b0_0
  - certifi=2021.10.8=py39hf3d152e_1
  - cffi=1.14.6=py39h400218f_0
  - charset-normalizer=2.0.4=pyhd3eb1b0_0
  - click=8.0.3=pyhd3eb1b0_0
  - cryptography=3.4.8=py39hd23ed53_0
  - cudatoolkit=10.1.243=h6bb024c_0
  - cudnn=7.6.5=cuda10.1_0
  - cupti=10.1.168=0
  - cycler=0.11.0=pyhd8ed1ab_0
  - dataclasses=0.8=pyh6d0b6a4_7
  - dbus=1.13.6=he372182_0
  - expat=2.2.10=h9c3ff4c_0
  - fontconfig=2.13.1=h6c09931_0
  - fonttools=4.25.0=pyhd3eb1b0_0
  - freetype=2.10.4=h0708190_1
  - frozenlist=1.2.0=py39h7f8727e_0
  - gast=0.4.0=pyhd3eb1b0_0
  - glib=2.69.1=h4ff587b_1
  - google-auth=1.33.0=pyhd3eb1b0_0
  - google-auth-oauthlib=0.4.4=pyhd3eb1b0_0
  - google-pasta=0.2.0=pyhd3eb1b0_0
  - grpcio=1.42.0=py39hce63b2e_0
  - gst-plugins-base=1.14.0=hbbd80ab_1
  - gstreamer=1.14.0=h28cd5cc_2
  - h5py=2.10.0=py39hec9cf62_0
  - hdf5=1.10.6=hb1b8bf9_0
  - icu=58.2=hf484d3e_1000
  - idna=3.3=pyhd3eb1b0_0
  - importlib-metadata=4.8.2=py39h06a4308_0
  - intel-openmp=2021.4.0=h06a4308_3561
  - jpeg=9d=h7f8727e_0
  - keras-preprocessing=1.1.2=pyhd3eb1b0_0
  - kiwisolver=1.3.1=py39h2531618_0
  - lcms2=2.12=hddcbb42_0
  - ld_impl_linux-64=2.35.1=h7274673_9
  - libbrotlicommon=1.0.9=h7f98852_5
  - libbrotlidec=1.0.9=h7f98852_5
  - libbrotlienc=1.0.9=h7f98852_5
  - libffi=3.3=he6710b0_2
  - libgcc-ng=9.3.0=h5101ec6_17
  - libgfortran-ng=7.5.0=ha8ba4b0_17
  - libgfortran4=7.5.0=ha8ba4b0_17
  - libgomp=9.3.0=h5101ec6_17
  - libpng=1.6.37=h21135ba_2
  - libprotobuf=3.17.2=h4ff587b_1
  - libstdcxx-ng=9.3.0=hd4cf53a_17
  - libtiff=4.2.0=h85742a9_0
  - libuuid=1.0.3=h7f8727e_2
  - libwebp-base=1.2.0=h27cfd23_0
  - libxcb=1.13=h7f98852_1003
  - libxml2=2.9.12=h03d6c58_0
  - lz4-c=1.9.3=h9c3ff4c_1
  - markdown=3.3.4=py39h06a4308_0
  - matplotlib=3.4.3=py39hf3d152e_2
  - matplotlib-base=3.4.3=py39hbbc1b5f_0
  - mkl=2021.4.0=h06a4308_640
  - mkl-service=2.4.0=py39h7f8727e_0
  - mkl_fft=1.3.1=py39hd3c417c_0
  - mkl_random=1.2.2=py39h51133e4_0
  - multidict=5.1.0=py39h27cfd23_2
  - munkres=1.1.4=pyh9f0ad1d_0
  - ncurses=6.3=h7f8727e_2
  - numpy=1.21.2=py39h20f2e39_0
  - numpy-base=1.21.2=py39h79a1101_0
  - oauthlib=3.1.1=pyhd3eb1b0_0
  - olefile=0.46=pyh9f0ad1d_1
  - openssl=1.1.1m=h7f8727e_0
  - opt_einsum=3.3.0=pyhd3eb1b0_1
  - pcre=8.45=h9c3ff4c_0
  - pip=21.2.4=py39h06a4308_0
  - protobuf=3.17.2=py39h295c915_0
  - pthread-stubs=0.4=h36c2ea0_1001
  - pyasn1=0.4.8=pyhd3eb1b0_0
  - pyasn1-modules=0.2.8=py_0
  - pycparser=2.21=pyhd3eb1b0_0
  - pyjwt=2.1.0=py39h06a4308_0
  - pyopenssl=21.0.0=pyhd3eb1b0_1
  - pyparsing=3.0.7=pyhd8ed1ab_0
  - pyqt=5.9.2=py39h2531618_6
  - pysocks=1.7.1=py39h06a4308_0
  - python=3.9.7=h12debd9_1
  - python-dateutil=2.8.2=pyhd8ed1ab_0
  - python-flatbuffers=2.0=pyhd3eb1b0_0
  - python_abi=3.9=2_cp39
  - qt=5.9.7=h5867ecd_1
  - readline=8.1=h27cfd23_0
  - requests=2.26.0=pyhd3eb1b0_0
  - requests-oauthlib=1.3.0=py_0
  - rsa=4.7.2=pyhd3eb1b0_1
  - scipy=1.7.1=py39h292c36d_2
  - setuptools=58.0.4=py39h06a4308_0
  - sip=4.19.13=py39h295c915_0
  - six=1.16.0=pyhd3eb1b0_0
  - sqlite=3.36.0=hc218d9a_0
  - tensorboard-plugin-wit=1.6.0=py_0
  - tensorflow-estimator=2.6.0=pyh7b7c402_0
  - termcolor=1.1.0=py39h06a4308_1
  - tk=8.6.11=h1ccaba5_0
  - tornado=6.1=py39h3811e60_1
  - typing-extensions=3.10.0.2=hd3eb1b0_0
  - typing_extensions=3.10.0.2=pyh06a4308_0
  - tzdata=2021e=hda174b7_0
  - urllib3=1.26.7=pyhd3eb1b0_0
  - werkzeug=2.0.2=pyhd3eb1b0_0
  - wheel=0.37.0=pyhd3eb1b0_1
  - wrapt=1.13.3=py39h7f8727e_2
  - xorg-libxau=1.0.9=h7f98852_0
  - xorg-libxdmcp=1.1.3=h7f98852_0
  - xz=5.2.5=h7b6447c_0
  - yarl=1.6.3=py39h27cfd23_0
  - zipp=3.6.0=pyhd3eb1b0_0
  - zlib=1.2.11=h7f8727e_4
  - zstd=1.4.9=ha95c52a_0
  - pip:
    - joblib==1.1.0
    - keras==2.8.0
    - keras-applications==1.0.8
    - libclang==13.0.0
    - opencv-python==4.5.5.62
    - pandas==1.4.0
    - pillow==9.0.1
    - pytz==2021.3
    - pyyaml==6.0
    - scikit-learn==1.0.2
    - tensorboard==2.8.0
    - tensorboard-data-server==0.6.1
    - tensorflow==2.8.0
    - tensorflow-gpu==2.8.0
    - tensorflow-io-gcs-filesystem==0.23.1
    - tf-estimator-nightly==2.8.0.dev2021122109
    - threadpoolctl==3.0.0
prefix: /home/nikhilanand_1921cs24/anaconda3/envs/keras-gpu

Create the environment by runningconda env create -f environment.yml


来源: stackexchange

问:
Create new column using data from If Else Loop in R
I have data frame that consist of names and scores of certain individual

```<code>       name  score
0       Ted     90
1   Rebecca     88
2       Roy     78
3    Leslie     85
4    Nathan     75
5     Jamie     70
6       Sam     78
7     Isaac     70
8    Keeley     85
9     Beard     90
10    Colin     70
11     Will     70
12      Jan     82
13  Richard     70
</code>```

I want to add new column called verdict that contain their degree based on their score. I used loping to do that with hope that the result would be like this

```<code>       name  score               verdict
0       Ted     90     Passed, Cum Laude
1   Rebecca     88     Passed, Cum Laude
2       Roy     78          Passed, Good
3    Leslie     85     Passed, Cum Laude
4    Nathan     75          Passed, Good
5     Jamie     70          Passed, Good
6       Sam     78          Passed, Good
7     Isaac     70          Passed, Good
8    Keeley     85     Passed, Cum Laude
9     Beard     90     Passed, Cum Laude
10    Colin     70          Passed, Good
11     Will     70          Passed, Good
12      Jan     82     Passed, Excellent
13  Richard     70          Passed, Good
</code>```

I'm using this code below to do that, but nothing happened. The new column didnt exist and there is no error or warning message in R console

```<code>df$verdict <-
  for (score in df$score){
    if (score >= 85)
      return('Passed, Cum Laude')
    else if (score < 85 & score >= 80)
      return('Passed, Excellent')
    else if (score < 80 & score >= 70)
      return('Passed, Good')
    else if (score < 70 & score >= 60)
      return('Passed')
    else
      return('Not Passed')
}
</code>```

答:
Sure this can be done with cases or ifelse statements, but I think the best way is to use the base function cut here.

code

```<code>scores <- c(0, 60, 70, 80, 85, 100)
score_labels <- c("Not Passed", "Passed", "Passed, Good", "Passed, Excellent", "Passed, Cum Laude")

# using dplyr
df %>% mutate(verdict = cut(score, breaks = scores, labels = score_labels, right = FALSE))

# or in just base
df$verdict <- cut(df$score, breaks = scores, labels = score_labels, right = FALSE)
</code>```

output

```<code>      name score           verdict
1      Ted    90 Passed, Cum Laude
2  Rebecca    88 Passed, Cum Laude
3      Roy    78      Passed, Good
4   Leslie    85 Passed, Cum Laude
5   Nathan    75      Passed, Good
6    Jamie    70      Passed, Good
7      Sam    78      Passed, Good
8    Isaac    70      Passed, Good
9   Keeley    85 Passed, Cum Laude
10   Beard    90 Passed, Cum Laude
11   Colin    70      Passed, Good
12    Will    70      Passed, Good
13     Jan    82 Passed, Excellent
14 Richard    70      Passed, Good
</code>```

data

```<code>df <- structure(list(name = c("Ted", "Rebecca", "Roy", "Leslie", "Nathan",
"Jamie", "Sam", "Isaac", "Keeley", "Beard", "Colin", "Will",
"Jan", "Richard"), score = c(90L, 88L, 78L, 85L, 75L, 70L, 78L,
70L, 85L, 90L, 70L, 70L, 82L, 70L)), row.names = c(NA, -14L), class = c("data.frame"))
</code>```

sidenotes

With cut your breaks vector has one more item than your labels vector. This is because they are based on the breaks resulting in one group less, like here the 6 score values give these 5 groups: 0-60, 60-70, 70-80, 80-85 and 85-100

right = TRUE versus right = FALSE means how to treat the boundaries, compare it with > versus >=. right = TRUE would have resulted in those with a score of 70 fall in the group "Passed" while with right = FALSE it falls in the "Passed, Good" group.

ContentLicense: CC BY-SA 4.0

Body:
I have data frame that consist of names and scores of certain individual

       name  score
0       Ted     90
1   Rebecca     88
2       Roy     78
3    Leslie     85
4    Nathan     75
5     Jamie     70
6       Sam     78
7     Isaac     70
8    Keeley     85
9     Beard     90
10    Colin     70
11     Will     70
12      Jan     82
13  Richard     70

I want to add new column called verdict that contain their degree based on their score. I used loping to do that with hope that the result would be like this

       name  score               verdict
0       Ted     90     Passed, Cum Laude
1   Rebecca     88     Passed, Cum Laude
2       Roy     78          Passed, Good
3    Leslie     85     Passed, Cum Laude
4    Nathan     75          Passed, Good
5     Jamie     70          Passed, Good
6       Sam     78          Passed, Good
7     Isaac     70          Passed, Good
8    Keeley     85     Passed, Cum Laude
9     Beard     90     Passed, Cum Laude
10    Colin     70          Passed, Good
11     Will     70          Passed, Good
12      Jan     82     Passed, Excellent
13  Richard     70          Passed, Good

I'm using this code below to do that, but nothing happened. The new column didnt exist and there is no error or warning message in R console

df$verdict <-
  for (score in df$score){
    if (score >= 85)
      return('Passed, Cum Laude')
    else if (score < 85 & score >= 80)
      return('Passed, Excellent')
    else if (score < 80 & score >= 70)
      return('Passed, Good')
    else if (score < 70 & score >= 60)
      return('Passed')
    else
      return('Not Passed')
}

Body:
Sure this can be done with cases or ifelse statements, but I think the best way is to use the base function cut here.

code

scores <- c(0, 60, 70, 80, 85, 100)
score_labels <- c("Not Passed", "Passed", "Passed, Good", "Passed, Excellent", "Passed, Cum Laude")

# using dplyr
df %>% mutate(verdict = cut(score, breaks = scores, labels = score_labels, right = FALSE))

# or in just base
df$verdict <- cut(df$score, breaks = scores, labels = score_labels, right = FALSE)

output

      name score           verdict
1      Ted    90 Passed, Cum Laude
2  Rebecca    88 Passed, Cum Laude
3      Roy    78      Passed, Good
4   Leslie    85 Passed, Cum Laude
5   Nathan    75      Passed, Good
6    Jamie    70      Passed, Good
7      Sam    78      Passed, Good
8    Isaac    70      Passed, Good
9   Keeley    85 Passed, Cum Laude
10   Beard    90 Passed, Cum Laude
11   Colin    70      Passed, Good
12    Will    70      Passed, Good
13     Jan    82 Passed, Excellent
14 Richard    70      Passed, Good

data

df <- structure(list(name = c("Ted", "Rebecca", "Roy", "Leslie", "Nathan",
"Jamie", "Sam", "Isaac", "Keeley", "Beard", "Colin", "Will",
"Jan", "Richard"), score = c(90L, 88L, 78L, 85L, 75L, 70L, 78L,
70L, 85L, 90L, 70L, 70L, 82L, 70L)), row.names = c(NA, -14L), class = c("data.frame"))

sidenotes

With cut your breaks vector has one more item than your labels vector. This is because they are based on the breaks resulting in one group less, like here the 6 score values give these 5 groups: 0-60, 60-70, 70-80, 80-85 and 85-100

right = TRUE versus right = FALSE means how to treat the boundaries, compare it with > versus >=. right = TRUE would have resulted in those with a score of 70 fall in the group "Passed" while with right = FALSE it falls in the "Passed, Good" group.


问:
How to stop a for loop inside an ExecutorService?
I've tried looking on other threads and I can't seem to find a proper answer,

When using executorService.shutdownNow() almost all tasks stop immediately as intended except ones with for loops in them.
I have no idea why it happens, but the most I've seen from other threads is that you should be using Thread.currentThread().isInterrupted() to check if it is interrupted, but adding a

```<code>if(Thread.currentThread().isInterrupted())
    {return;}
</code>```

Doesn't actually stop it all.  I'm calling executor shutdownNow when a UI button is toggled off.

Code example:

```<code>executorService.submit(() -> {
            ctx.batzUtils.keyEvent(KeyEvent.KEY_PRESSED, VK_SHIFT);
            //Shit keeps going if you call ShutdownNow Todo
            for (Rectangle rect : rects)
            {
                ctx.batzUtils.click(rect);
                try
                {
                    Thread.sleep(minDelayBetween, maxDelayBetween);
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
            ctx.batzUtils.keyEvent(KeyEvent.KEY_RELEASED, VK_SHIFT);
            ctx.batzUtils.keyEvent(KeyEvent.KEY_TYPED, VK_SHIFT);
        });
</code>```

Any ideas as to why or solutions would be greatly appreciated

答:
2 solutions. your for loop you do need to check

if(Thread.currentThread().isInterrupted()) {[clean up and finish the thread code here]}

In your catch section, instead of e.printStackTrace(); place [clean up and finish the thread code]. In the catch statement you don't need to check if the thread has been interrupted. The fact that you caught the InterruptedException is already a flag that the thread has been interrupted

Body:
I've tried looking on other threads and I can't seem to find a proper answer,

When using executorService.shutdownNow() almost all tasks stop immediately as intended except ones with for loops in them.
I have no idea why it happens, but the most I've seen from other threads is that you should be using Thread.currentThread().isInterrupted() to check if it is interrupted, but adding a

if(Thread.currentThread().isInterrupted())
    {return;}

Doesn't actually stop it all.  I'm calling executor shutdownNow when a UI button is toggled off.

Code example:

executorService.submit(() -> {
            ctx.batzUtils.keyEvent(KeyEvent.KEY_PRESSED, VK_SHIFT);
            //Shit keeps going if you call ShutdownNow Todo
            for (Rectangle rect : rects)
            {
                ctx.batzUtils.click(rect);
                try
                {
                    Thread.sleep(minDelayBetween, maxDelayBetween);
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
            ctx.batzUtils.keyEvent(KeyEvent.KEY_RELEASED, VK_SHIFT);
            ctx.batzUtils.keyEvent(KeyEvent.KEY_TYPED, VK_SHIFT);
        });

Any ideas as to why or solutions would be greatly appreciated


问:
Get "Value" from simple JSON using "Key" as variable Azure Logic Apps
I have defined a simple JSON

```<code>{
  "12345": "Numbers",
  "AAAAA": "AllAs",
  "ABCXYZ": "AtoZ"
}
</code>```

All I want to extract the value of "Key" when passed as a variable. I have tried body('Parse_JSON')['name'] but its failing.

I just want to get the value of what ever Key I am looking for as variable.

答:
Figured it !

body('parse_JSON')?[variables('name')]

The above does the following:

1- body('parse_JSON') gets the body of Parsed JSON

2- ?[variables('name')]gets the value of name which is equal to ABCXYZ

3- Returns AtoZ

Body:
I have defined a simple JSON

{
  "12345": "Numbers",
  "AAAAA": "AllAs",
  "ABCXYZ": "AtoZ"
}

All I want to extract the value of "Key" when passed as a variable. I have tried body('Parse_JSON')['name'] but its failing.

I just want to get the value of what ever Key I am looking for as variable.


问:
Querying elastic search with linq using NEST
Is there any way to query Elasticsearch with NEST client using linq or lambda expressions.

I Want to do somthing like this :

```<code>client.Search<MyClass>(s => s.MyProperty.Contains("value") &&
                            (s.MySecondProperty == 123 ||
                             s.ThirdProperty > 12)) ;
</code>```

Or

```<code>var query = from m in MyContext.MyClass
            where ...
            select m
</code>```

I read a little about ElasticLinq but it seems that it is no more active. the last nuget package were published on october 2015

What i want to do is to create a method that get an Expression as parameter from the caller and search on elastic with it. the caller should not depend on ES or NEST API

答: I am currently working on the LINQ query provider library to generate NEST method calls. If someone is interested - here is the link to the GitHub repository - https://github.com/VladislavRybnikov/NEST.Linq</p>

ContentLicense: CC BY-SA 3.0

Body:
Is there any way to query Elasticsearch with NEST client using linq or lambda expressions.

I Want to do somthing like this :

client.Search<MyClass>(s => s.MyProperty.Contains("value") &&
                            (s.MySecondProperty == 123 ||
                             s.ThirdProperty > 12)) ;

Or

var query = from m in MyContext.MyClass
            where ...
            select m

I read a little about ElasticLinq but it seems that it is no more active. the last nuget package were published on october 2015

What i want to do is to create a method that get an Expression as parameter from the caller and search on elastic with it. the caller should not depend on ES or NEST API


问:
KafkaJs - running consumers in background
I'm writing a service which implements 2 consumers using Node and kafkajs
https://kafka.js.org/docs/consuming

I have 2 async function which have initialized consumers and in theory are pending to read messages. Something like this:

```<code>const { Kafka } = require('kafkajs')

// Create the client with the broker list
const kafka = new Kafka({
  clientId: 'my-app',
  brokers: ['kafka1:9092', 'kafka2:9092']
});
const consumer = kafka.consumer({ groupId: 'my-group' });

const consumerModule = async (): Promise<void> => {

 await consumer.connect();
 await consumer.subscribe({ topic: 'topic-A' });

 await consumer.run({
    eachMessage: async ({ topic, partition, message }) => {
        console.log({
            key: message.key.toString(),
            value: message.value.toString(),
            headers: message.headers,
        })
    },
 });
}

export default consumerModule;
</code>```

If I want the consumer to run in the background in the service, should I just import the module file when I initialize the server?

I have a feeling that this will not work, because a call to consumerModule function must be made and because it's async, not sure how to implement it properly.

For example:

```<code>import express, { Express } from 'express';
import consumerModuleA from './modules/consumerModuleA';
import consumerModuleB from './modules/consumerModuleB';

async function bootstrap(): Promise<Express> {

    const app = express();

    app.get('/health', (_req, res) => {
        res.send('ok');
    });

    return app;
}
</code>```

Please advise.

答:
i would suggest the below. Notes:

you can reuse the implementation of the consumer, by parametrizing the topic/group/etc).

explicitly call the consumer module to run it.

```<code>import express, { Express } from 'express';
import consumerModule from './modules/consumerModule';

consumerModule();

async function bootstrap(): Promise<Express> {

    const app = express();

    app.get('/health', (_req, res) => {
        res.send('ok');
    });

    return app;
}
</code>```

Body:
I'm writing a service which implements 2 consumers using Node and kafkajs
https://kafka.js.org/docs/consuming

I have 2 async function which have initialized consumers and in theory are pending to read messages. Something like this:

const { Kafka } = require('kafkajs')

// Create the client with the broker list
const kafka = new Kafka({
  clientId: 'my-app',
  brokers: ['kafka1:9092', 'kafka2:9092']
});
const consumer = kafka.consumer({ groupId: 'my-group' });

const consumerModule = async (): Promise<void> => {

 await consumer.connect();
 await consumer.subscribe({ topic: 'topic-A' });

 await consumer.run({
    eachMessage: async ({ topic, partition, message }) => {
        console.log({
            key: message.key.toString(),
            value: message.value.toString(),
            headers: message.headers,
        })
    },
 });
}

export default consumerModule;

If I want the consumer to run in the background in the service, should I just import the module file when I initialize the server?

I have a feeling that this will not work, because a call to consumerModule function must be made and because it's async, not sure how to implement it properly.

For example:

import express, { Express } from 'express';
import consumerModuleA from './modules/consumerModuleA';
import consumerModuleB from './modules/consumerModuleB';

async function bootstrap(): Promise<Express> {

    const app = express();

    app.get('/health', (_req, res) => {
        res.send('ok');
    });

    return app;
}

Please advise.

Body:
i would suggest the below. Notes:

you can reuse the implementation of the consumer, by parametrizing the topic/group/etc).

explicitly call the consumer module to run it.

import express, { Express } from 'express';
import consumerModule from './modules/consumerModule';

consumerModule();

async function bootstrap(): Promise<Express> {

    const app = express();

    app.get('/health', (_req, res) => {
        res.send('ok');
    });

    return app;
}


问:
cassandra is logging timeout of node URGENT_MESSAGES
URGENT_MESSAGES-[no-channel] dropping message of type GOSSIP_DIGEST_SYN whose timeout expired before reaching the network</p>

答:
You didn't provide a lot of information but I'm assuming that your cluster is running into a known issue where gossip messages are being dropped during startup of a Cassandra node (CASSANDRA-16877).

The starting node sends GOSSIP_DIGEST_SYN with a high priority (URGENT_MESSAGES) but for large clusters, Cassandra 4.0 nodes cannot serialise the gossip state when the size of the state exceeds 128kb and no acknowledgement gets sent. Since a node can not gossip with other nodes, it fails to start.

This was urgently fixed in Cassandra 4.0.1 last year. Upgrade the binaries on the affected Cassandra 4.0 nodes and that should allow them to start successfully and join the ring. Cheers!


问:
how to get the file properties in assets folder on android?
I want to get the file properties in assets folder on android,But it is unlike general operation use some kinds of methods to get,anybody can help me to get the file properties such as modified date.
My assets file has a "ok.txt",please do me a help?</p>

答: Take a look at the documentation of File class, there are lots of methods to get any kind of information about a file. </p>


问:
@FetchRequest predicate is ignored if the context changes
I have a simple SwiftUI application with CoreData and two views. One view displays all "Place" objects. You can create new places and you can show the details for the place.
Inside the second view you can add "PlaceItem"s to a place.

The problem is that, once a new "PlaceItem" is added to the viewContext, the @NSFetchRequest seems to forget about its additional predicates, which I set in onAppear. Then every place item is shown inside the details view. Once I update the predicate manually (the refresh button), only the items from the selected place are visible again.

Any idea how this can be fixed? Here's the code for my two views:

```<code>struct PlaceView: View {
    @FetchRequest(sortDescriptors: []) private var places: FetchedResults<Place>
    @Environment(\.managedObjectContext) private var viewContext

    var body: some View {
        NavigationView {
            List(places) { place in
                NavigationLink {
                    PlaceItemsView(place: place)
                } label: {
                    Text(place.name ?? "")
                }

            }
        }
        .toolbar {
            ToolbarItem(placement: .primaryAction) {
                Button {
                    let place = Place(context: viewContext)
                    place.name = NSUUID().uuidString
                    try! viewContext.save()
                } label: {
                    Label("Add", systemImage: "plus")
                }

            }
        }
        .navigationTitle("Places")
    }
}

struct PlaceItemsView: View {
    @ObservedObject var place: Place
    @State var searchText = ""

    @FetchRequest(sortDescriptors: []) private var items: FetchedResults<PlaceItem>
    @Environment(\.managedObjectContext) private var viewContext

    func updatePredicate() {
        var predicates = [NSPredicate]()
        predicates.append(NSPredicate(format: "place == %@", place))
        if !searchText.isEmpty {
            predicates.append(NSPredicate(format: "name CONTAINS %@", searchText))
        }

        items.nsPredicate = NSCompoundPredicate(type: .and, subpredicates: predicates)
    }

    var body: some View {
        NavigationView {
            List(items) { item in
                Text(item.name ?? "");
            }
        }
        .onAppear(perform: updatePredicate)
        .toolbar {
            ToolbarItem(placement: .primaryAction) {
                Button {
                    let item = PlaceItem(context: viewContext)
                    item.place = place
                    item.name = NSUUID().uuidString
                    try! viewContext.save()
                } label: {
                    Label("Add", systemImage: "plus")
                }
            }

            ToolbarItem(placement: .navigationBarLeading) {
                Button(action: updatePredicate) {
                    Label("Refresh", systemImage: "arrow.clockwise")
                }
            }
        }
        .searchable(
            text: $searchText,
            placement: .navigationBarDrawer(displayMode: .always),
            prompt: "Search or add articles …"
        )
        .onAppear(perform: updatePredicate)
        .onChange(of: searchText, perform: { _ in
            updatePredicate()
        })
        .navigationTitle(place.name ?? "")
    }
}

struct ContentView: View {
    @Environment(\.managedObjectContext) private var viewContext

    var body: some View {
        NavigationView {
            PlaceView()
        }
    }
}
</code>```

Thanks!

答:
import UIKit
import CoreData

class LoginViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{

```<code>//MARK: - Outlets

@IBOutlet weak var LogInDataTableView: UITableView!

@IBOutlet weak var btnLogIn: UIButton!
@IBOutlet weak var btnAdd: UIButton!

//MARK: - Variables

var fetchedCoreData = [NSManagedObject]()

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var name = String()

let placeHolderArray = ["username", "password"]
var isLogin = false

//MARK: - Methods and other functionalities

override func viewDidLoad() {
    super.viewDidLoad()

    btnLogIn.layer.cornerRadius = 20.0
    LogInDataTableView.layer.cornerRadius = 20.0
    LogInDataTableView.layer.borderWidth = 2.0
    LogInDataTableView.layer.borderColor = UIColor.blue.cgColor
    let tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))
    view.addGestureRecognizer(tap)
}

//MARK: - dismiss keyboard when tap on screen

@objc func dismissKeyboard() {
    //Causes the view (or one of its embedded text fields) to resign the first responder status.
    view.endEditing(true)
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.navigationController?.isNavigationBarHidden = true

    fetchRequest()
}

//MARK: - fetch saved data from coredata

func fetchRequest() {
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "EntityName")
    request.returnsObjectsAsFaults = false

    do {

        let result = try context.fetch(request)
        fetchedCoreData = result as! [NSManagedObject]
    } catch {
        print("error while fetch data from database")
    }
}

//MARK: - login button click with validation

@IBAction func btnLogInClick(_ sender: Any) {
    if loginData[0].isEmpty {
        let alert = UIAlertController(title: "Alert", message: "Please enter username", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(okAction)
        present(alert, animated: true, completion: nil)
    } else if loginData[1].isEmpty {
        let alert = UIAlertController(title: "Alert", message: "Please enter password", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(okAction)
        present(alert, animated: true, completion: nil)
    } else if  loginData[2].isEmpty{
        let alert = UIAlertController(title: "Alert", message: "Please enter id", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(okAction)
        present(alert, animated: true, completion: nil)
    } else {

        let registeredUser = clinicData.contains { objc in
            objc.value(forKey: "username") as! String == loginData[0] && objc.value(forKey: "password") as! String == loginData[1]
        }

        if registeredUser == true {
            for data in clinicData {
                if data.value(forKey: "username") as! String == loginData[0] && data.value(forKey: "password") as! String == loginData[1] {
                    clinicName = data.value(forKey: "clinic") as! String
                    let addClinicVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "HomeScreenViewController") as! HomeScreenViewController
                    addClinicVC.clinicName = clinicName
                    self.navigationController?.pushViewController(addClinicVC, animated: true)
                }
            }

        } else {
            //MARK: - alert
            let alert = UIAlertController(title: "Alert", message: "username and password mismatch", preferredStyle: .alert)
            let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
            alert.addAction(okAction)
            present(alert, animated: true, completion: nil)
        }

    }

}

@IBAction func didTapAddClinic(_ sender: UIButton) {
    let addVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NewScreenViewController") as! NewScreenViewController
    self.navigationController?.pushViewController(addVC, animated: true)
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return placeHolderArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "LoginTableViewCell", for: indexPath) as! LoginTableViewCell
    cell.txtLoginData.tag = indexPath.row
    cell.txtLoginData.placeholder = placeHolderArray[indexPath.row]
    return cell
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 60
}
</code>```

}

Body:
I have a simple SwiftUI application with CoreData and two views. One view displays all "Place" objects. You can create new places and you can show the details for the place.
Inside the second view you can add "PlaceItem"s to a place.

The problem is that, once a new "PlaceItem" is added to the viewContext, the @NSFetchRequest seems to forget about its additional predicates, which I set in onAppear. Then every place item is shown inside the details view. Once I update the predicate manually (the refresh button), only the items from the selected place are visible again.

Any idea how this can be fixed? Here's the code for my two views:

struct PlaceView: View {
    @FetchRequest(sortDescriptors: []) private var places: FetchedResults<Place>
    @Environment(\.managedObjectContext) private var viewContext

    var body: some View {
        NavigationView {
            List(places) { place in
                NavigationLink {
                    PlaceItemsView(place: place)
                } label: {
                    Text(place.name ?? "")
                }

            }
        }
        .toolbar {
            ToolbarItem(placement: .primaryAction) {
                Button {
                    let place = Place(context: viewContext)
                    place.name = NSUUID().uuidString
                    try! viewContext.save()
                } label: {
                    Label("Add", systemImage: "plus")
                }

            }
        }
        .navigationTitle("Places")
    }
}

struct PlaceItemsView: View {
    @ObservedObject var place: Place
    @State var searchText = ""

    @FetchRequest(sortDescriptors: []) private var items: FetchedResults<PlaceItem>
    @Environment(\.managedObjectContext) private var viewContext

    func updatePredicate() {
        var predicates = [NSPredicate]()
        predicates.append(NSPredicate(format: "place == %@", place))
        if !searchText.isEmpty {
            predicates.append(NSPredicate(format: "name CONTAINS %@", searchText))
        }

        items.nsPredicate = NSCompoundPredicate(type: .and, subpredicates: predicates)
    }

    var body: some View {
        NavigationView {
            List(items) { item in
                Text(item.name ?? "");
            }
        }
        .onAppear(perform: updatePredicate)
        .toolbar {
            ToolbarItem(placement: .primaryAction) {
                Button {
                    let item = PlaceItem(context: viewContext)
                    item.place = place
                    item.name = NSUUID().uuidString
                    try! viewContext.save()
                } label: {
                    Label("Add", systemImage: "plus")
                }
            }

            ToolbarItem(placement: .navigationBarLeading) {
                Button(action: updatePredicate) {
                    Label("Refresh", systemImage: "arrow.clockwise")
                }
            }
        }
        .searchable(
            text: $searchText,
            placement: .navigationBarDrawer(displayMode: .always),
            prompt: "Search or add articles …"
        )
        .onAppear(perform: updatePredicate)
        .onChange(of: searchText, perform: { _ in
            updatePredicate()
        })
        .navigationTitle(place.name ?? "")
    }
}

struct ContentView: View {
    @Environment(\.managedObjectContext) private var viewContext

    var body: some View {
        NavigationView {
            PlaceView()
        }
    }
}

Thanks!

Body:
import UIKit
import CoreData

class LoginViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{

//MARK: - Outlets

@IBOutlet weak var LogInDataTableView: UITableView!

@IBOutlet weak var btnLogIn: UIButton!
@IBOutlet weak var btnAdd: UIButton!

//MARK: - Variables

var fetchedCoreData = [NSManagedObject]()

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var name = String()

let placeHolderArray = ["username", "password"]
var isLogin = false

//MARK: - Methods and other functionalities

override func viewDidLoad() {
    super.viewDidLoad()

    btnLogIn.layer.cornerRadius = 20.0
    LogInDataTableView.layer.cornerRadius = 20.0
    LogInDataTableView.layer.borderWidth = 2.0
    LogInDataTableView.layer.borderColor = UIColor.blue.cgColor
    let tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))
    view.addGestureRecognizer(tap)
}

//MARK: - dismiss keyboard when tap on screen

@objc func dismissKeyboard() {
    //Causes the view (or one of its embedded text fields) to resign the first responder status.
    view.endEditing(true)
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.navigationController?.isNavigationBarHidden = true

    fetchRequest()
}

//MARK: - fetch saved data from coredata

func fetchRequest() {
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "EntityName")
    request.returnsObjectsAsFaults = false

    do {

        let result = try context.fetch(request)
        fetchedCoreData = result as! [NSManagedObject]
    } catch {
        print("error while fetch data from database")
    }
}

//MARK: - login button click with validation

@IBAction func btnLogInClick(_ sender: Any) {
    if loginData[0].isEmpty {
        let alert = UIAlertController(title: "Alert", message: "Please enter username", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(okAction)
        present(alert, animated: true, completion: nil)
    } else if loginData[1].isEmpty {
        let alert = UIAlertController(title: "Alert", message: "Please enter password", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(okAction)
        present(alert, animated: true, completion: nil)
    } else if  loginData[2].isEmpty{
        let alert = UIAlertController(title: "Alert", message: "Please enter id", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(okAction)
        present(alert, animated: true, completion: nil)
    } else {

        let registeredUser = clinicData.contains { objc in
            objc.value(forKey: "username") as! String == loginData[0] && objc.value(forKey: "password") as! String == loginData[1]
        }

        if registeredUser == true {
            for data in clinicData {
                if data.value(forKey: "username") as! String == loginData[0] && data.value(forKey: "password") as! String == loginData[1] {
                    clinicName = data.value(forKey: "clinic") as! String
                    let addClinicVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "HomeScreenViewController") as! HomeScreenViewController
                    addClinicVC.clinicName = clinicName
                    self.navigationController?.pushViewController(addClinicVC, animated: true)
                }
            }

        } else {
            //MARK: - alert
            let alert = UIAlertController(title: "Alert", message: "username and password mismatch", preferredStyle: .alert)
            let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
            alert.addAction(okAction)
            present(alert, animated: true, completion: nil)
        }

    }

}

@IBAction func didTapAddClinic(_ sender: UIButton) {
    let addVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NewScreenViewController") as! NewScreenViewController
    self.navigationController?.pushViewController(addVC, animated: true)
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return placeHolderArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "LoginTableViewCell", for: indexPath) as! LoginTableViewCell
    cell.txtLoginData.tag = indexPath.row
    cell.txtLoginData.placeholder = placeHolderArray[indexPath.row]
    return cell
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 60
}

}


问:
PHP Re-create Wordpress the_loop
I'm currently working on a basic, but bespoke CMS that we will be using across several of our sites. Before anyone flames me, I am well aware of other alternatives, however nothing we have tried is really flexible enough for our data.

With that out of the way, I shall begin.

One of the features I do like from Wordpress is the known as The Loop.

```<code>while(have_posts()) : the_content();
    the_content();
endwhile;
</code>```

I've studied the code and come up with a similar class, which you can see here.

From looking at the code, I've figured out that, has_posts() seems to be returning a boolean if there are still posts in an array.

the_article is saying that we're still in the loop, so set a variable for the articles(posts) with the data we need.

I've kind of got this working, however I only seem to be able to get one piece of information from the array:

```<code>while (have_articles()): the_article();
    echo "<h1 class='title'>" . the_title() . "</h1>";
endwhile;
</code>```

Where the_title is:

```<code>function the_title() {
    global $AC;

    return $AC->p_title;
}
</code>```

Thanks for the help!

答:
Funny, I see the loop as the worst part of Wordpress. Too much magic for nothing.

Anyway, to implement the loop, it's something like:

```<code>function the_title() {
    global $articles;
    static $position;

    return $articles[$position++]->title;
}
</code>```

See, each time you call the_title() and the like, you have to increment a pointer. Probably, you will have to make $position global as well, if you want to use it in other functions like the_post().

Title: PHP Re-create Wordpress the_loop

Body:
I'm currently working on a basic, but bespoke CMS that we will be using across several of our sites. Before anyone flames me, I am well aware of other alternatives, however nothing we have tried is really flexible enough for our data.

With that out of the way, I shall begin.

One of the features I do like from Wordpress is the known as The Loop.

while(have_posts()) : the_content();
    the_content();
endwhile;

I've studied the code and come up with a similar class, which you can see here.

From looking at the code, I've figured out that, has_posts() seems to be returning a boolean if there are still posts in an array.

the_article is saying that we're still in the loop, so set a variable for the articles(posts) with the data we need.

I've kind of got this working, however I only seem to be able to get one piece of information from the array:

while (have_articles()): the_article();
    echo "
" . the_title() . "
";
endwhile;

Where the_title is:

function the_title() {
    global $AC;

    return $AC->p_title;
}

Thanks for the help!

Body:
Funny, I see the loop as the worst part of Wordpress. Too much magic for nothing.

Anyway, to implement the loop, it's something like:

function the_title() {
    global $articles;
    static $position;

    return $articles[$position++]->title;
}

See, each time you call the_title() and the like, you have to increment a pointer. Probably, you will have to make $position global as well, if you want to use it in other functions like the_post().


问:
Unable to run Android Espresso tests. The project uses Hilt Dependency Injection and Navigation Components
I am trying to run the following Espresso test. I have Android Hilt dependency injection setup in my project and its working well in the application but am facing issues running UI tests.

I also have a project library which is using Hilt aswell.

Getting the following Exception:

```<code>Process: com.muddassir.myapp, PID: 15570
    java.lang.NoClassDefFoundError: Failed resolution of: Landroidx/test/internal/platform/tracker/UsageTracker;
        at java.lang.Class.newInstance(Native Method)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6952)
        at android.app.ActivityThread.access$1500(ActivityThread.java:272)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2055)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:237)
        at android.app.ActivityThread.main(ActivityThread.java:8019)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "androidx.test.internal.platform.tracker.UsageTracker" on path: DexPathList[[zip file "/system/framework/android.test.runner.jar", zip file "/system/framework/android.test.mock.jar", zip file "/data/app/com.muddassir.myapp.test-sXVdfWq9tpbgNg9sbalPuAase.apk", zip file "/data/app/com.cs.stackoverflow-hHsBjEoBRyEmFRYwawGgqA==/base.apk"],nativeLibraryDirectories=[/data/app/com.cs.stackoverflow.test-sXVdfWq9tpbgNg9sbalPuA==/lib/arm, /data/app/com.cs.stackoverflow-hHsBjEoBRyEmFRYwawGgqA==/lib/arm, /system/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:196)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
</code>```

My test is as follows

```<code>package com.muddassir.myapp.ui.activity

import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.*
import androidx.test.espresso.contrib.RecyclerViewActions.actionOnItemAtPosition
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.filters.LargeTest
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner
import com.cs.stackoverflow.R
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.allOf
import org.hamcrest.TypeSafeMatcher
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.internal.runners.JUnit4ClassRunner
import org.junit.runner.RunWith

@LargeTest
@HiltAndroidTest
@RunWith(AndroidJUnit4ClassRunner::class)
class ParameterTest {
    @get:Rule()
    var hiltRule = HiltAndroidRule(this)

    @get:Rule
    val activityRule = AndroidJUnit4ClassRunner(MainActivity::class.java)

    @Before
    fun init() {
        hiltRule.inject()
    }

    @Test
    fun parameterTest() {
        val recyclerView = onView(
            allOf(
                withId(R.id.questionsRv),
                childAtPosition(
                    withId(R.id.swipeToRefreshL),
                    0
                )
            )
        )
        recyclerView.perform(actionOnItemAtPosition<ViewHolder>(0, click()))
    }

    private fun childAtPosition(
        parentMatcher: Matcher<View>, position: Int
    ): Matcher<View> {

        return object : TypeSafeMatcher<View>() {
            override fun describeTo(description: Description) {
                description.appendText("Child at position $position in parent ")
                parentMatcher.describeTo(description)
            }

            public override fun matchesSafely(view: View): Boolean {
                val parent = view.parent
                return parent is ViewGroup && parentMatcher.matches(parent)
                        && view == parent.getChildAt(position)
            }
        }
    }
}

</code>```

lib/build.gradle

```<code>plugins {
    id 'com.android.library'
    id 'kotlin-android'
    id 'kotlin-android-extensions'
    id 'kotlin-kapt'
    id 'dagger.hilt.android.plugin'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.2"

    defaultConfig {
        minSdkVersion 21
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "com.cs.myapp_lib.HiltTestRunner"
        consumerProguardFiles "consumer-rules.pro"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.3.2'

    def test_version = "1.3.1-alpha03"

    implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'

    // Retrofit
    def retrofit = "2.9.0"
    api "com.squareup.retrofit2:retrofit:$retrofit"
    api "com.squareup.retrofit2:converter-gson:$retrofit"
    api "com.squareup.retrofit2:converter-scalars:$retrofit"
    api "com.squareup.retrofit2:adapter-rxjava2:$retrofit"

    api 'com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.2'

    // Utilities
    api 'com.github.muddassir235:kmacros:1.10'

    def room = "2.2.6"
    api "androidx.room:room-runtime:$room"
    api "androidx.room:room-ktx:$room"
    kapt "androidx.room:room-compiler:$room"

    // Dependency Injection through HILT
    def hilt_version = '2.31.2-alpha'
    api "com.google.dagger:hilt-android:$hilt_version"
    kapt "com.google.dagger:hilt-android-compiler:$hilt_version"

    // ...with Kotlin.
    kaptAndroidTest "com.google.dagger:hilt-android-compiler:$hilt_version"

    def hilt_view_models = '1.0.0-alpha03'
    api "androidx.hilt:hilt-lifecycle-viewmodel:$hilt_view_models"
    kapt "androidx.hilt:hilt-compiler:$hilt_view_models"

    // Libraries for tests

    kaptAndroidTest "com.google.dagger:hilt-android-compiler:$hilt_version"

    testImplementation 'junit:junit:4.13.1'
    androidTestImplementation 'androidx.test.ext:junit:1.3.1-alpha03'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0-alpha03'
    androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.4.0-alpha03'
    androidTestImplementation 'androidx.test.espresso:espresso-intents:3.4.0-alpha03'
    androidTestImplementation 'androidx.test.espresso:espresso-accessibility:3.4.0-alpha03'
    androidTestImplementation 'androidx.test.espresso:espresso-web:3.4.0-alpha03'
    androidTestImplementation 'androidx.test.espresso.idling:idling-concurrent:3.4.0-alpha03'

    androidTestImplementation 'androidx.test:runner:1.3.1-alpha03'
    androidTestImplementation "androidx.test:core-ktx:$test_version"
    androidTestImplementation 'androidx.test:rules:1.3.1-alpha03'
    androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.4.0-alpha03'
    androidTestImplementation "com.google.dagger:hilt-android-testing:$hilt_version"
}
</code>```

app/build.gradle

```<code>plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-android-extensions'
    id 'kotlin-kapt'
    id 'dagger.hilt.android.plugin'
    id 'androidx.navigation.safeargs.kotlin'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.2"

    defaultConfig {
        applicationId "com.cs.stackoverflow"
        minSdkVersion 21
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "com.muddassir.myapp.HiltTestRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {
    implementation project(':stackoverflow_lib')

    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.3.2'
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'

    implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'

    // Dependency Injection through HILT
    def hilt_version = '2.31.2-alpha'
    implementation "com.google.dagger:hilt-android:$hilt_version"
    kapt "com.google.dagger:hilt-android-compiler:$hilt_version"

    // ...with Kotlin.
    kaptAndroidTest "com.google.dagger:hilt-android-compiler:$hilt_version"
    // ...with Java.
//    androidTestAnnotationProcessor 'com.google.dagger:hilt-android-compiler:2.28-alpha'

    def hilt_view_models = '1.0.0-alpha03'
    implementation "androidx.hilt:hilt-lifecycle-viewmodel:$hilt_view_models"
    kapt "androidx.hilt:hilt-compiler:$hilt_view_models"

    // Libraries for tests

    kaptAndroidTest "com.google.dagger:hilt-android-compiler:$hilt_version"

    def fragment_version = '1.3.0-rc02'
    debugImplementation "androidx.fragment:fragment-testing:$fragment_version"

    def test_version = "1.3.1-alpha03"

    def nav_version = '2.3.3'

    // Kotlin
    implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
    implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
    implementation "androidx.navigation:navigation-dynamic-features-fragment:$nav_version"

    testImplementation 'junit:junit:4.13.1'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0-alpha03'
    androidTestImplementation 'androidx.test.espresso:espresso-intents:3.4.0-alpha03'
    androidTestImplementation 'androidx.test.espresso:espresso-accessibility:3.4.0-alpha03'
    androidTestImplementation 'androidx.test.espresso:espresso-web:3.4.0-alpha03'
    androidTestImplementation 'androidx.test.espresso.idling:idling-concurrent:3.4.0-alpha03'

    androidTestImplementation 'androidx.test:runner:1.3.1-alpha03'
    androidTestImplementation 'androidx.test:rules:1.3.1-alpha03'
    androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.4.0-alpha03'
    androidTestImplementation "com.google.dagger:hilt-android-testing:$hilt_version"
    androidTestImplementation "androidx.test:core-ktx:$test_version"
    androidTestImplementation "androidx.navigation:navigation-testing:$nav_version"
}
</code>```

Project build.gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext.kotlin_version = "1.4.30"
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.1.2"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.dagger:hilt-android-gradle-plugin:2.28-alpha'
        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.3.3"
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

答:
I'm facing the same.
If we use hilt test with custom runner class then we got issues in runner class.

```<code>testInstrumentationRunner "com.example.testing.HiltTestRunner"
</code>```

so while using hilt, the manual test cases would be better.

Body:
I am trying to run the following Espresso test. I have Android Hilt dependency injection setup in my project and its working well in the application but am facing issues running UI tests.

I also have a project library which is using Hilt aswell.

Getting the following Exception:

Process: com.muddassir.myapp, PID: 15570
    java.lang.NoClassDefFoundError: Failed resolution of: Landroidx/test/internal/platform/tracker/UsageTracker;
        at java.lang.Class.newInstance(Native Method)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6952)
        at android.app.ActivityThread.access$1500(ActivityThread.java:272)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2055)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:237)
        at android.app.ActivityThread.main(ActivityThread.java:8019)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "androidx.test.internal.platform.tracker.UsageTracker" on path: DexPathList[[zip file "/system/framework/android.test.runner.jar", zip file "/system/framework/android.test.mock.jar", zip file "/data/app/com.muddassir.myapp.test-sXVdfWq9tpbgNg9sbalPuAase.apk", zip file "/data/app/com.cs.stackoverflow-hHsBjEoBRyEmFRYwawGgqA==/base.apk"],nativeLibraryDirectories=[/data/app/com.cs.stackoverflow.test-sXVdfWq9tpbgNg9sbalPuA==/lib/arm, /data/app/com.cs.stackoverflow-hHsBjEoBRyEmFRYwawGgqA==/lib/arm, /system/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:196)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)

My test is as follows

package com.muddassir.myapp.ui.activity

import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.*
import androidx.test.espresso.contrib.RecyclerViewActions.actionOnItemAtPosition
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.filters.LargeTest
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner
import com.cs.stackoverflow.R
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.allOf
import org.hamcrest.TypeSafeMatcher
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.internal.runners.JUnit4ClassRunner
import org.junit.runner.RunWith

@LargeTest
@HiltAndroidTest
@RunWith(AndroidJUnit4ClassRunner::class)
class ParameterTest {
    @get:Rule()
    var hiltRule = HiltAndroidRule(this)

    @get:Rule
    val activityRule = AndroidJUnit4ClassRunner(MainActivity::class.java)

    @Before
    fun init() {
        hiltRule.inject()
    }

    @Test
    fun parameterTest() {
        val recyclerView = onView(
            allOf(
                withId(R.id.questionsRv),
                childAtPosition(
                    withId(R.id.swipeToRefreshL),
                    0
                )
            )
        )
        recyclerView.perform(actionOnItemAtPosition<ViewHolder>(0, click()))
    }

    private fun childAtPosition(
        parentMatcher: Matcher<View>, position: Int
    ): Matcher<View> {

        return object : TypeSafeMatcher<View>() {
            override fun describeTo(description: Description) {
                description.appendText("Child at position $position in parent ")
                parentMatcher.describeTo(description)
            }

            public override fun matchesSafely(view: View): Boolean {
                val parent = view.parent
                return parent is ViewGroup && parentMatcher.matches(parent)
                        && view == parent.getChildAt(position)
            }
        }
    }
}

lib/build.gradle

plugins {
    id 'com.android.library'
    id 'kotlin-android'
    id 'kotlin-android-extensions'
    id 'kotlin-kapt'
    id 'dagger.hilt.android.plugin'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.2"

    defaultConfig {
        minSdkVersion 21
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "com.cs.myapp_lib.HiltTestRunner"
        consumerProguardFiles "consumer-rules.pro"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.3.2'

    def test_version = "1.3.1-alpha03"

    implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'

    // Retrofit
    def retrofit = "2.9.0"
    api "com.squareup.retrofit2:retrofit:$retrofit"
    api "com.squareup.retrofit2:converter-gson:$retrofit"
    api "com.squareup.retrofit2:converter-scalars:$retrofit"
    api "com.squareup.retrofit2:adapter-rxjava2:$retrofit"

    api 'com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.2'

    // Utilities
    api 'com.github.muddassir235:kmacros:1.10'

    def room = "2.2.6"
    api "androidx.room:room-runtime:$room"
    api "androidx.room:room-ktx:$room"
    kapt "androidx.room:room-compiler:$room"

    // Dependency Injection through HILT
    def hilt_version = '2.31.2-alpha'
    api "com.google.dagger:hilt-android:$hilt_version"
    kapt "com.google.dagger:hilt-android-compiler:$hilt_version"

    // ...with Kotlin.
    kaptAndroidTest "com.google.dagger:hilt-android-compiler:$hilt_version"

    def hilt_view_models = '1.0.0-alpha03'
    api "androidx.hilt:hilt-lifecycle-viewmodel:$hilt_view_models"
    kapt "androidx.hilt:hilt-compiler:$hilt_view_models"

    // Libraries for tests

    kaptAndroidTest "com.google.dagger:hilt-android-compiler:$hilt_version"

    testImplementation 'junit:junit:4.13.1'
    androidTestImplementation 'androidx.test.ext:junit:1.3.1-alpha03'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0-alpha03'
    androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.4.0-alpha03'
    androidTestImplementation 'androidx.test.espresso:espresso-intents:3.4.0-alpha03'
    androidTestImplementation 'androidx.test.espresso:espresso-accessibility:3.4.0-alpha03'
    androidTestImplementation 'androidx.test.espresso:espresso-web:3.4.0-alpha03'
    androidTestImplementation 'androidx.test.espresso.idling:idling-concurrent:3.4.0-alpha03'

    androidTestImplementation 'androidx.test:runner:1.3.1-alpha03'
    androidTestImplementation "androidx.test:core-ktx:$test_version"
    androidTestImplementation 'androidx.test:rules:1.3.1-alpha03'
    androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.4.0-alpha03'
    androidTestImplementation "com.google.dagger:hilt-android-testing:$hilt_version"
}

app/build.gradle

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-android-extensions'
    id 'kotlin-kapt'
    id 'dagger.hilt.android.plugin'
    id 'androidx.navigation.safeargs.kotlin'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.2"

    defaultConfig {
        applicationId "com.cs.stackoverflow"
        minSdkVersion 21
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "com.muddassir.myapp.HiltTestRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {
    implementation project(':stackoverflow_lib')

    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.3.2'
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'

    implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'

    // Dependency Injection through HILT
    def hilt_version = '2.31.2-alpha'
    implementation "com.google.dagger:hilt-android:$hilt_version"
    kapt "com.google.dagger:hilt-android-compiler:$hilt_version"

    // ...with Kotlin.
    kaptAndroidTest "com.google.dagger:hilt-android-compiler:$hilt_version"
    // ...with Java.
//    androidTestAnnotationProcessor 'com.google.dagger:hilt-android-compiler:2.28-alpha'

    def hilt_view_models = '1.0.0-alpha03'
    implementation "androidx.hilt:hilt-lifecycle-viewmodel:$hilt_view_models"
    kapt "androidx.hilt:hilt-compiler:$hilt_view_models"

    // Libraries for tests

    kaptAndroidTest "com.google.dagger:hilt-android-compiler:$hilt_version"

    def fragment_version = '1.3.0-rc02'
    debugImplementation "androidx.fragment:fragment-testing:$fragment_version"

    def test_version = "1.3.1-alpha03"

    def nav_version = '2.3.3'

    // Kotlin
    implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
    implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
    implementation "androidx.navigation:navigation-dynamic-features-fragment:$nav_version"

    testImplementation 'junit:junit:4.13.1'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0-alpha03'
    androidTestImplementation 'androidx.test.espresso:espresso-intents:3.4.0-alpha03'
    androidTestImplementation 'androidx.test.espresso:espresso-accessibility:3.4.0-alpha03'
    androidTestImplementation 'androidx.test.espresso:espresso-web:3.4.0-alpha03'
    androidTestImplementation 'androidx.test.espresso.idling:idling-concurrent:3.4.0-alpha03'

    androidTestImplementation 'androidx.test:runner:1.3.1-alpha03'
    androidTestImplementation 'androidx.test:rules:1.3.1-alpha03'
    androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.4.0-alpha03'
    androidTestImplementation "com.google.dagger:hilt-android-testing:$hilt_version"
    androidTestImplementation "androidx.test:core-ktx:$test_version"
    androidTestImplementation "androidx.navigation:navigation-testing:$nav_version"
}

Project build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext.kotlin_version = "1.4.30"
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.1.2"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.dagger:hilt-android-gradle-plugin:2.28-alpha'
        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.3.3"
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Body:
I'm facing the same.
If we use hilt test with custom runner class then we got issues in runner class.

testInstrumentationRunner "com.example.testing.HiltTestRunner"

so while using hilt, the manual test cases would be better.


问:
How to get X-year low price of a stock with Google Finance using Google Sheets
I can currently get the 52-week low of a stock by using this call in Google Sheets.

```<code>=GOOGLEFINANCE("NYSE:UBER","low52")
</code>```

How do I get the 3-year and 5-year low of a stock?
For a 3-year low I tried something like this:

```<code>=GOOGLEFINANCE("NYSE:UBER","price",TODAY(),=EDATE(TODAY(),-12*3))
</code>```

However this returns a list of the past 20 prices, not a single value representing the lowest value over the past X-years.

答:
Get daily price data for your date range and find the mininum value

For 3-year low:

```<code>=MIN(INDEX(GOOGLEFINANCE("NYSE:UBER","price",DATE(YEAR(TODAY())-3,MONTH(TODAY()),DAY(TODAY())), TODAY()),0,2))
</code>```

and for 5-year low:

```<code>=MIN(INDEX(GOOGLEFINANCE("NYSE:UBER","price",DATE(YEAR(TODAY())-5,MONTH(TODAY()),DAY(TODAY())), TODAY()),0,2))
</code>```

Dynamically, add your number of years to a cell (for example A1) and use:

```<code>=MIN(INDEX(GOOGLEFINANCE("NYSE:UBER","price",DATE(YEAR(TODAY())-A1,MONTH(TODAY()),DAY(TODAY())), TODAY()),0,2))
</code>```

Note for this pair the 3-year and 5-year lows are the same

Formulae Used:

GOOGLEFINANCE

MIN

INDEX

DATE

TODAY

YEAR

MONTH

DAY

Body:
I can currently get the 52-week low of a stock by using this call in Google Sheets.

=GOOGLEFINANCE("NYSE:UBER","low52")

How do I get the 3-year and 5-year low of a stock?
For a 3-year low I tried something like this:

=GOOGLEFINANCE("NYSE:UBER","price",TODAY(),=EDATE(TODAY(),-12*3))

However this returns a list of the past 20 prices, not a single value representing the lowest value over the past X-years.

Body:
Get daily price data for your date range and find the mininum value

For 3-year low:

=MIN(INDEX(GOOGLEFINANCE("NYSE:UBER","price",DATE(YEAR(TODAY())-3,MONTH(TODAY()),DAY(TODAY())), TODAY()),0,2))

and for 5-year low:

=MIN(INDEX(GOOGLEFINANCE("NYSE:UBER","price",DATE(YEAR(TODAY())-5,MONTH(TODAY()),DAY(TODAY())), TODAY()),0,2))

Dynamically, add your number of years to a cell (for example A1) and use:

=MIN(INDEX(GOOGLEFINANCE("NYSE:UBER","price",DATE(YEAR(TODAY())-A1,MONTH(TODAY()),DAY(TODAY())), TODAY()),0,2))

Note for this pair the 3-year and 5-year lows are the same

Formulae Used:

GOOGLEFINANCE

MIN

INDEX

DATE

TODAY

YEAR

MONTH

DAY


问:
Symfony 5 - Multiple authenticators in firewall. I need to set the "entry_point
I don't know if what I'm trying to do is possible but I have the following configuration in my security.yaml and it shows me the following error:

Because you have multiple authenticators in firewall "administrator_secured_area", you need to set the "entry_point" key to one of your authenticators ("App\Security\AdministratorAuthenticator", "form_login") or a service ID implementing "Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface". The "entry_point" determines what should happen (e.g. redirect to "/login") when an anonymous user tries to access a protected page.

I have searched various solutions but none suits my current setup

security:
    enable_authenticator_manager: true
    # https://symfony.com/doc/current/security.html#registering-the-user-hashing-passwords
    password_hashers:
        Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
        App\Entity\Administrator:
            algorithm: auto
        App\Entity\Instructor:
            algorithm: auto

    # https://symfony.com/doc/current/security.html#loading-the-user-the-user-provider
    providers:
        # used to reload user from session & other features (e.g. switch_user)
        app_administrator_provider:
            entity:
                class: App\Entity\Administrator
                property: email
        app_instructor_provider:
            entity:
                class: App\Entity\Instructor
                property: email
        # used to reload user from session & other features (e.g. switch_user)
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        administrator_secured_area:
            lazy: true
            provider: app_administrator_provider
            custom_authenticator: App\Security\AdministratorAuthenticator
            form_login:
                login_path: /login/administrator
                check_path: /app_login_administrator
                default_target_path: /login/administrator
            logout:
                path: app_logout
                # where to redirect after logout
                target: app_login_administrator
        instructor_secured_area:
            lazy: true
            provider: app_instructor_provider
            custom_authenticator: App\Security\InstructorAuthenticator
            form_login:
                login_path: /login/instructor
                check_path: /app_login_instructor
                default_target_path: /login/instructor
            logout:
                path: app_logout
                # where to redirect after logout
                target: app_login_instructor

            # activate different ways to authenticate
            # https://symfony.com/doc/current/security.html#the-firewall

            # https://symfony.com/doc/current/security/impersonating_user.html
            # switch_user: true

    # Easy way to control access for large sections of your site
    # Note: Only the *first* access control that matches will be used
    access_control:
        # - { path: ^/admin, roles: ROLE_ADMIN }
        # - { path: ^/profile, roles: ROLE_USER }

when@test:
    security:
        password_hashers:
            # By default, password hashers are resource intensive and take time. This is
            # important to generate secure password hashes. In tests however, secure hashes
            # are not important, waste resources and increase test times. The following
            # reduces the work factor to the lowest possible values.
            Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface:
                algorithm: auto
                cost: 4 # Lowest possible value for bcrypt
                time_cost: 3 # Lowest possible value for argon
                memory_cost: 10 # Lowest possible value for argon

```

答:
As the error message suggests you should set the entry_point key to one of your authenticators, here is an example, you could choose to set in one of them, or you could try to set it in both:

```<code>administrator_secured_area:
    lazy: true
    provider: app_administrator_provider
    custom_authenticator: App\Security\AdministratorAuthenticator
    form_login:
        login_path: /login/administrator
        check_path: /app_login_administrator
        default_target_path: /login/administrator
    logout:
        path: app_logout
        # where to redirect after logout
        target: app_login_administrator
    entry_point: 'form_login'
instructor_secured_area:
    lazy: true
    provider: app_instructor_provider
    custom_authenticator: App\Security\InstructorAuthenticator
    form_login:
        login_path: /login/instructor
        check_path: /app_login_instructor
        default_target_path: /login/instructor
    logout:
        path: app_logout
        # where to redirect after logout
        target: app_login_instructor
</code>```

Body:
As the error message suggests you should set the entry_point key to one of your authenticators, here is an example, you could choose to set in one of them, or you could try to set it in both:

administrator_secured_area:
    lazy: true
    provider: app_administrator_provider
    custom_authenticator: App\Security\AdministratorAuthenticator
    form_login:
        login_path: /login/administrator
        check_path: /app_login_administrator
        default_target_path: /login/administrator
    logout:
        path: app_logout
        # where to redirect after logout
        target: app_login_administrator
    entry_point: 'form_login'
instructor_secured_area:
    lazy: true
    provider: app_instructor_provider
    custom_authenticator: App\Security\InstructorAuthenticator
    form_login:
        login_path: /login/instructor
        check_path: /app_login_instructor
        default_target_path: /login/instructor
    logout:
        path: app_logout
        # where to redirect after logout
        target: app_login_instructor