问:
I am also getting this error on ROS realsense D435 camera. The code I wrote "roslaunch realsense2_camera rs_rgbd.launch"
Error message:</p>
```<code>opt/ros/noetic/lib/nodelet/nodelet: symbol lookup error: /home/ubuntu/catkin_ws/devel/lib//librealsense2_camera.so: undefined symbol: _ZN20ddynamic_reconfigure19DDynamicReconfigureC1ERKN3ros10NodeHandleE
[camera/realsense2_camera_manager-2] process has died [pid 13033, exit code 127, cmd /opt/ros/noetic/lib/nodelet/nodelet manager __name:=realsense2_camera_manager __log:=/home/ubuntu/.ros/log/bb60da40-105c-11ec-bdf8-27733b72faf1/camera-realsense2_camera_manager-2.log].
log file: /home/ubuntu/.ros/log/bb60da40-105c-11ec-bdf8-27733b72faf1/camera-realsense2_camera_manager-2*.log
[camera/realsense2_camera-3] process has finished cleanly
log file: /home/ubuntu/.ros/log/bb60da40-105c-11ec-bdf8-27733b72faf1/camera-realsense2_camera-3*.log
</code>```

答:
I had the same problem. it was caused by having ddynamic_reconfigure repo inside src/ and already installed ddynamic_reconfigure using apt

```<code>sudo apt install ros-melodic ros-melodic-ddynamic-reconfigure.
</code>```

Fixed by removing src/ddynamic_reconfigure/ and rebuilding.

Body:
Error message:

opt/ros/noetic/lib/nodelet/nodelet: symbol lookup error: /home/ubuntu/catkin_ws/devel/lib//librealsense2_camera.so: undefined symbol: _ZN20ddynamic_reconfigure19DDynamicReconfigureC1ERKN3ros10NodeHandleE
[camera/realsense2_camera_manager-2] process has died [pid 13033, exit code 127, cmd /opt/ros/noetic/lib/nodelet/nodelet manager __name:=realsense2_camera_manager __log:=/home/ubuntu/.ros/log/bb60da40-105c-11ec-bdf8-27733b72faf1/camera-realsense2_camera_manager-2.log].
log file: /home/ubuntu/.ros/log/bb60da40-105c-11ec-bdf8-27733b72faf1/camera-realsense2_camera_manager-2*.log
[camera/realsense2_camera-3] process has finished cleanly
log file: /home/ubuntu/.ros/log/bb60da40-105c-11ec-bdf8-27733b72faf1/camera-realsense2_camera-3*.log

Body:
I had the same problem. it was caused by having ddynamic_reconfigure repo inside src/ and already installed ddynamic_reconfigure using apt

sudo apt install ros-melodic ros-melodic-ddynamic-reconfigure.

Fixed by removing src/ddynamic_reconfigure/ and rebuilding.


来源: stackexchange

问:
Module not found: Error: Can't resolve 'util' in webpack
when i run the script it show me this errors
Here is error:

BREAKING CHANGE:webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to: add a fallback 'resolve.fallback: { "util": require.resolve("util/") }', install 'util';
If you don't want to include a polyfill, you can use an empty module like this:resolve.fallback: { "util": false }
@ ./node_modules/webpack/lib/index.js 74:30-50 77:9-29
@ ./src/googlesheets.js 21:16-34
@ ./src/index.js 1:0-44 2:0-10

答:
Last comment was very helpful, after that I've added:
enter image description here

after modifying resolve, install with npm all of those packages one by one.

ContentLicense: CC BY-SA 4.0


问:
Mismatch in UserAgent initiating Firefox manually and using GeckoDriver
Why is not the useragent the same in both cases?

https://www.whatsmyua.info/ reports the following when I browse with usual Firefox:

```<code>Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:96.0) Gecko/20100101 Firefox/96.0
</code>```

However, browsing with geckodriver reports:

```<code>Mozilla/5.0 (Windows NT 10.0; rv:91.0) Gecko/20100101 Firefox/91.0
</code>```

Here's how I start browsing with geckodriver:

```<code>options=Options()
profile_path = '/home/myuser/.mozilla/firefox/x9zoqd7t.default-release/'
options.set_preference('profile', profile_path)
service = Service('/usr/local/bin/geckodriver')
driver = Firefox(service=service, options=options)
driver.get("http://www.whatsmyua.info/")
</code>```

答:
Manually accessing Firefox v97.0 and accessing Selenium driven GeckoDriver v0.30.0 initiated firefox Browsing Context, either way I see the same User Agent as follows:

```<code>Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:97.0) Gecko/20100101 Firefox/97.0
</code>```

The most probhable reason for the mismatch is, you have 2 instances of Firefox browser installed.

The instance which you are accessing manually haven't been updated since it's previous version of 96.0, where as the instance installed at the location /home/myuser/.mozilla/firefox/ haven't been updated since 91.0. Hence you observe the difference in the useragent

Body:
Why is not the useragent the same in both cases?

https://www.whatsmyua.info/ reports the following when I browse with usual Firefox:

Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:96.0) Gecko/20100101 Firefox/96.0

However, browsing with geckodriver reports:

Mozilla/5.0 (Windows NT 10.0; rv:91.0) Gecko/20100101 Firefox/91.0

Here's how I start browsing with geckodriver:

options=Options()
profile_path = '/home/myuser/.mozilla/firefox/x9zoqd7t.default-release/'
options.set_preference('profile', profile_path)
service = Service('/usr/local/bin/geckodriver')
driver = Firefox(service=service, options=options)
driver.get("http://www.whatsmyua.info/")

Body:
Manually accessing Firefox v97.0 and accessing Selenium driven GeckoDriver v0.30.0 initiated firefox Browsing Context, either way I see the same User Agent as follows:

Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:97.0) Gecko/20100101 Firefox/97.0

The most probhable reason for the mismatch is, you have 2 instances of Firefox browser installed.

The instance which you are accessing manually haven't been updated since it's previous version of 96.0, where as the instance installed at the location /home/myuser/.mozilla/firefox/ haven't been updated since 91.0. Hence you observe the difference in the useragent


问:
How to use subList()
I have a JSF page which displays list of Glassfish log files. I use lazy loading for pagination. I keep the list of the log files names into Java List.

```<code>private List<directoryListObj> dataList = new ArrayList<>();

dataList = dataList.subList(firstRow, lastRow);
</code>```

And here is the problem. For example I have 35 files into the directory. When I do this

```<code>dataList = dataList.subList(5, 15);
</code>```

It works fine. But when I do this:

```<code>dataList = dataList.subList(30, 38);
</code>```

I get error wrong index because I want to get index outside of the List. How I can for example return List elements from 30 to 35? I want if I want to get index from 30 to 40 but if there only 35 indexes to get only 5.

答:
For kotlin, you could use:
myList.subList(min, max.coerceAtMost(myList.size)

Or in terms of the question above: myList.subList(30, 38.coerceAtMost(myList.size)

ContentLicense: CC BY-SA 3.0

Title: How to use subList()

Body:
I have a JSF page which displays list of Glassfish log files. I use lazy loading for pagination. I keep the list of the log files names into Java List.

private List<directoryListObj> dataList = new ArrayList<>();

dataList = dataList.subList(firstRow, lastRow);

And here is the problem. For example I have 35 files into the directory. When I do this

dataList = dataList.subList(5, 15);

It works fine. But when I do this:

dataList = dataList.subList(30, 38);

I get error wrong index because I want to get index outside of the List. How I can for example return List elements from 30 to 35? I want if I want to get index from 30 to 40 but if there only 35 indexes to get only 5.


问:
How can I execute multiple NN training?
I have two NVidia GPUs in the machine, but I am not using them.

I have three NN training running on my machine. When I am trying to run the fourth one, the script is giving me the following error:

```<code>my_user@my_machine:~/my_project/training_my_project$ python3 my_project.py
Traceback (most recent call last):
  File "my_project.py", line 211, in <module>
    load_data(
  File "my_project.py", line 132, in load_data
    tx = tf.convert_to_tensor(data_x, dtype=tf.float32)
  File "/home/my_user/.local/lib/python3.8/site-packages/tensorflow/python/util/traceback_utils.py", line 153, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "/home/my_user/.local/lib/python3.8/site-packages/tensorflow/python/framework/constant_op.py", line 106, in convert_to_eager_tensor
    return ops.EagerTensor(value, ctx.device_name, dtype)
tensorflow.python.framework.errors_impl.FailedPreconditionError: Failed to allocate scratch buffer for device 0
my_user@my_machine:~/my_project/training_my_project$
</code>```

How can I resolve this issue?

The following is my RAM usage:

```<code>my_user@my_machine:~/my_project/training_my_project$ free -m
              total        used        free      shared  buff/cache   available
Mem:          15947        6651        3650          20        5645        8952
Swap:          2047         338        1709
my_user@my_machine:~/my_project/training_my_project$
</code>```

The following is my CPU usage:

```<code>my_user@my_machine:~$ top -i
top - 12:46:12 up 79 days, 21:14,  2 users,  load average: 4,05, 3,82, 3,80
Tasks: 585 total,   2 running, 583 sleeping,   0 stopped,   0 zombie
%Cpu(s): 11,7 us,  1,6 sy,  0,0 ni, 86,6 id,  0,0 wa,  0,0 hi,  0,0 si,  0,0 st
MiB Mem :  15947,7 total,   3638,3 free,   6662,7 used,   5646,7 buff/cache
MiB Swap:   2048,0 total,   1709,4 free,    338,6 used.   8941,6 avail Mem

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
2081821 my_user  20   0   48,9g   2,5g 471076 S 156,1  15,8   1832:54 python3
2082196 my_user  20   0   48,8g   2,6g 467708 S 148,5  16,8   1798:51 python3
2076942 my_user  20   0   47,8g   1,6g 466916 R 147,5  10,3   2797:51 python3
   1594 gdm       20   0 3989336  65816  31120 S   0,7   0,4  38:03.14 gnome-shell
     93 root      rt   0       0      0      0 S   0,3   0,0   0:38.42 migration/13
   1185 root     -51   0       0      0      0 S   0,3   0,0   3925:59 irq/54-nvidia
2075861 root      20   0       0      0      0 I   0,3   0,0   1:30.17 kworker/22:0-events
2076418 root      20   0       0      0      0 I   0,3   0,0   1:38.65 kworker/1:0-events
2085325 root      20   0       0      0      0 I   0,3   0,0   1:17.15 kworker/3:1-events
2093002 root      20   0       0      0      0 I   0,3   0,0   1:00.05 kworker/23:0-events
2100000 root      20   0       0      0      0 I   0,3   0,0   0:45.78 kworker/2:2-events
2104688 root      20   0       0      0      0 I   0,3   0,0   0:33.08 kworker/9:0-events
2106767 root      20   0       0      0      0 I   0,3   0,0   0:25.16 kworker/20:0-events
2115469 root      20   0       0      0      0 I   0,3   0,0   0:01.98 kworker/11:2-events
2115470 root      20   0       0      0      0 I   0,3   0,0   0:01.96 kworker/12:2-events
2115477 root      20   0       0      0      0 I   0,3   0,0   0:01.95 kworker/30:1-events
2116059 my_user  20   0   23560   4508   3420 R   0,3   0,0   0:00.80 top
</code>```

The following is my TF configuration:

```<code>import os

os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
# os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
# os.environ["CUDA_VISIBLE_DEVICES"] = "99" # Use both gpus for training.

import sys, random
import time
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.callbacks import ModelCheckpoint
import numpy as np
from lxml import etree, objectify

# <editor-fold desc="GPU">
# resolve GPU related issues.
try:
    physical_devices = tf.config.list_physical_devices('GPU')
    for gpu_instance in physical_devices:
        tf.config.experimental.set_memory_growth(gpu_instance, True)
except Exception as e:
    pass
# END of try
# </editor-fold>
</code>```

Please, take the commented lines as commented-out lines.

Relevant source code:

```<code>def load_data(fname: str, class_index: int, feature_start_index: int, **selection):
    i = 0
    file = open(fname)
    if "top_n_lines" in selection:
        lines = [next(file) for _ in range(int(selection["top_n_lines"]))]
    elif "random_n_lines" in selection:
        tmp_lines = file.readlines()
        lines = random.sample(tmp_lines, int(selection["random_n_lines"]))
    else:
        lines = file.readlines()

    data_x, data_y = [], []
    for l in lines:
        row = l.strip().split()
        x = [float(ix) for ix in row[feature_start_index:]]
        y = encode(row[class_index])
        data_x.append(x)
        data_y.append(y)
    # END for l in lines

    num_rows = len(data_x)
    given_fraction = selection.get("validation_part", 1.0)
    if given_fraction > 0.9999:
        valid_x, valid_y = data_x, data_y
    else:
        n = int(num_rows * given_fraction)
        data_x, data_y = data_x[n:], data_y[n:]
        valid_x, valid_y = data_x[:n], data_y[:n]
    # END of if-else block

    tx = tf.convert_to_tensor(data_x, np.float32)
    ty = tf.convert_to_tensor(data_y, np.float32)

    vx = tf.convert_to_tensor(valid_x, np.float32)
    vy = tf.convert_to_tensor(valid_y, np.float32)

    return tx, ty, vx, vy
# END of the function
</code>```

答:
The RAM complaint isn't about your system ram (call it CPU RAM). It's about your GPU RAM.

The moment TF loads, it allocates all the GPU RAM for itself (some small fraction is left over due to page size stuff).

Your sample makes TF dynamically allocate GPU RAM, but it could still end up using up all the GPU RAM. Use the code below to provide a hard stop on GPU RAM per process. you'll likely want to change 1024 to 8096 or something like that.

and FYI, use nvidia-smi to monitor your GPU ram usage.

From the docs:

https://www.tensorflow.org/guide/gpu#limiting_gpu_memory_growth

```<code>gpus = tf.config.list_physical_devices('GPU')
if gpus:
  # Restrict TensorFlow to only allocate 1GB of memory on the first GPU
  try:
    tf.config.set_logical_device_configuration(
        gpus[0],
        [tf.config.LogicalDeviceConfiguration(memory_limit=1024)])
    logical_gpus = tf.config.list_logical_devices('GPU')
    print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
  except RuntimeError as e:
    # Virtual devices must be set before GPUs have been initialized
    print(e)
</code>```

Title: How can I execute multiple NN training?

Body:
I have two NVidia GPUs in the machine, but I am not using them.

I have three NN training running on my machine. When I am trying to run the fourth one, the script is giving me the following error:

my_user@my_machine:~/my_project/training_my_project$ python3 my_project.py
Traceback (most recent call last):
  File "my_project.py", line 211, in <module>
    load_data(
  File "my_project.py", line 132, in load_data
    tx = tf.convert_to_tensor(data_x, dtype=tf.float32)
  File "/home/my_user/.local/lib/python3.8/site-packages/tensorflow/python/util/traceback_utils.py", line 153, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "/home/my_user/.local/lib/python3.8/site-packages/tensorflow/python/framework/constant_op.py", line 106, in convert_to_eager_tensor
    return ops.EagerTensor(value, ctx.device_name, dtype)
tensorflow.python.framework.errors_impl.FailedPreconditionError: Failed to allocate scratch buffer for device 0
my_user@my_machine:~/my_project/training_my_project$

How can I resolve this issue?

The following is my RAM usage:

my_user@my_machine:~/my_project/training_my_project$ free -m
              total        used        free      shared  buff/cache   available
Mem:          15947        6651        3650          20        5645        8952
Swap:          2047         338        1709
my_user@my_machine:~/my_project/training_my_project$

The following is my CPU usage:

my_user@my_machine:~$ top -i
top - 12:46:12 up 79 days, 21:14,  2 users,  load average: 4,05, 3,82, 3,80
Tasks: 585 total,   2 running, 583 sleeping,   0 stopped,   0 zombie
%Cpu(s): 11,7 us,  1,6 sy,  0,0 ni, 86,6 id,  0,0 wa,  0,0 hi,  0,0 si,  0,0 st
MiB Mem :  15947,7 total,   3638,3 free,   6662,7 used,   5646,7 buff/cache
MiB Swap:   2048,0 total,   1709,4 free,    338,6 used.   8941,6 avail Mem

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
2081821 my_user  20   0   48,9g   2,5g 471076 S 156,1  15,8   1832:54 python3
2082196 my_user  20   0   48,8g   2,6g 467708 S 148,5  16,8   1798:51 python3
2076942 my_user  20   0   47,8g   1,6g 466916 R 147,5  10,3   2797:51 python3
   1594 gdm       20   0 3989336  65816  31120 S   0,7   0,4  38:03.14 gnome-shell
     93 root      rt   0       0      0      0 S   0,3   0,0   0:38.42 migration/13
   1185 root     -51   0       0      0      0 S   0,3   0,0   3925:59 irq/54-nvidia
2075861 root      20   0       0      0      0 I   0,3   0,0   1:30.17 kworker/22:0-events
2076418 root      20   0       0      0      0 I   0,3   0,0   1:38.65 kworker/1:0-events
2085325 root      20   0       0      0      0 I   0,3   0,0   1:17.15 kworker/3:1-events
2093002 root      20   0       0      0      0 I   0,3   0,0   1:00.05 kworker/23:0-events
2100000 root      20   0       0      0      0 I   0,3   0,0   0:45.78 kworker/2:2-events
2104688 root      20   0       0      0      0 I   0,3   0,0   0:33.08 kworker/9:0-events
2106767 root      20   0       0      0      0 I   0,3   0,0   0:25.16 kworker/20:0-events
2115469 root      20   0       0      0      0 I   0,3   0,0   0:01.98 kworker/11:2-events
2115470 root      20   0       0      0      0 I   0,3   0,0   0:01.96 kworker/12:2-events
2115477 root      20   0       0      0      0 I   0,3   0,0   0:01.95 kworker/30:1-events
2116059 my_user  20   0   23560   4508   3420 R   0,3   0,0   0:00.80 top

The following is my TF configuration:

import os

os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
# os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
# os.environ["CUDA_VISIBLE_DEVICES"] = "99" # Use both gpus for training.

import sys, random
import time
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.callbacks import ModelCheckpoint
import numpy as np
from lxml import etree, objectify

# <editor-fold desc="GPU">
# resolve GPU related issues.
try:
    physical_devices = tf.config.list_physical_devices('GPU')
    for gpu_instance in physical_devices:
        tf.config.experimental.set_memory_growth(gpu_instance, True)
except Exception as e:
    pass
# END of try
# </editor-fold>

Please, take the commented lines as commented-out lines.

Relevant source code:

def load_data(fname: str, class_index: int, feature_start_index: int, **selection):
    i = 0
    file = open(fname)
    if "top_n_lines" in selection:
        lines = [next(file) for _ in range(int(selection["top_n_lines"]))]
    elif "random_n_lines" in selection:
        tmp_lines = file.readlines()
        lines = random.sample(tmp_lines, int(selection["random_n_lines"]))
    else:
        lines = file.readlines()

    data_x, data_y = [], []
    for l in lines:
        row = l.strip().split()
        x = [float(ix) for ix in row[feature_start_index:]]
        y = encode(row[class_index])
        data_x.append(x)
        data_y.append(y)
    # END for l in lines

    num_rows = len(data_x)
    given_fraction = selection.get("validation_part", 1.0)
    if given_fraction > 0.9999:
        valid_x, valid_y = data_x, data_y
    else:
        n = int(num_rows * given_fraction)
        data_x, data_y = data_x[n:], data_y[n:]
        valid_x, valid_y = data_x[:n], data_y[:n]
    # END of if-else block

    tx = tf.convert_to_tensor(data_x, np.float32)
    ty = tf.convert_to_tensor(data_y, np.float32)

    vx = tf.convert_to_tensor(valid_x, np.float32)
    vy = tf.convert_to_tensor(valid_y, np.float32)

    return tx, ty, vx, vy
# END of the function

Body:
The RAM complaint isn't about your system ram (call it CPU RAM). It's about your GPU RAM.

The moment TF loads, it allocates all the GPU RAM for itself (some small fraction is left over due to page size stuff).

Your sample makes TF dynamically allocate GPU RAM, but it could still end up using up all the GPU RAM. Use the code below to provide a hard stop on GPU RAM per process. you'll likely want to change 1024 to 8096 or something like that.

and FYI, use nvidia-smi to monitor your GPU ram usage.

From the docs:

https://www.tensorflow.org/guide/gpu#limiting_gpu_memory_growth

gpus = tf.config.list_physical_devices('GPU')
if gpus:
  # Restrict TensorFlow to only allocate 1GB of memory on the first GPU
  try:
    tf.config.set_logical_device_configuration(
        gpus[0],
        [tf.config.LogicalDeviceConfiguration(memory_limit=1024)])
    logical_gpus = tf.config.list_logical_devices('GPU')
    print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
  except RuntimeError as e:
    # Virtual devices must be set before GPUs have been initialized
    print(e)


问:
How to prevent erase of cells in another Google Sheet file with importrange and make this process automatic
I am trying to set up 2 google sheet files where File 1 takes in quotes; code, description, quantity, unit cost, discount, price with discount, and total for in a table. And File 2 will copy over what is in File 1 and basically acts as long term records. I am using IMPORTRANGE to import the data.

To have a copy of File 1 each time there is a new record without eraising the other records, that's why I made this formula:

function copyFromOneSheetToAnother() {
  var sheet1 = SpreadsheetApp.openById("10gfdMLuEZL_e6KDu_PRhDgArKFIivVj3SkwWI-kMDws");
  var sheet2 = SpreadsheetApp.openById("10gfdMLuEZL_e6KDu_PRhDgArKFIivVj3SkwWI-kMDws");
  var currDate = new Date();
  var editedDate = new Date(currDate - 86400000);

  var insert = sheet1.getSheetByName("Nicaragua");
  var archive = sheet2.getSheetByName("NI");
  var insertData = insert.getRange(2, 1, (sheet1.getRange('A:G').getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow()), 28);

  for (row = 2; row <= insertData.getNumRows(); row++){
    var data = insert.getRange(row, 1, 1, 28).getValues();

    if (data[0][0] < currDate && data[0][0] > editedDate){
     archive.getRange((archive.getLastRow() + 1), 1, 1, 28).setValues(data).setNumberFormat("MM/dd/yyyy");
    }
  }
}```

But I when I run it is not working and I need this process happens automathic each time a new record is found

I've tried googling for my answer but I could not find one.

答:
Don't know what your function has to do with you question but this will have a much greater chance of working.

If you wish it to run automatically then create a timebased trigger for it.

```<code>function copyFromOneSheetToAnother() {
  const ss1 = SpreadsheetApp.openById("10gfdMLuEZL_e6KDu_PRhDgArKFIivVj3SkwWI-kMDws");
  const ss2 = SpreadsheetApp.openById("10gfdMLuEZL_e6KDu_PRhDgArKFIivVj3SkwWI-kMDws");
  const dt = new Date()
  const today = new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();
  const yesterday =new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()-1).valueOf();
  const sh1 = ss1.getSheetByName("Nicaragua");
  const sh2 = ss2.getSheetByName("NI");
  const vs1 = sh1.getRange(2, 1, sh1.getLastRow() - 1, 28).getValues();
  vs1.forEach((r, i) => {
    let dtv = new Date(r[0]);
    if (dtv < today && dtv > yesterday) {
      sh2.getRange(sh2.getLastRow() + 1, 1, 1, r.length).setValues(r).setNumberFormat("MM/dd/yyyy");
    }
  });
}
</code>```

Body:
I am trying to set up 2 google sheet files where File 1 takes in quotes; code, description, quantity, unit cost, discount, price with discount, and total for in a table. And File 2 will copy over what is in File 1 and basically acts as long term records. I am using IMPORTRANGE to import the data.

To have a copy of File 1 each time there is a new record without eraising the other records, that's why I made this formula:

function copyFromOneSheetToAnother() {
  var sheet1 = SpreadsheetApp.openById("10gfdMLuEZL_e6KDu_PRhDgArKFIivVj3SkwWI-kMDws");
  var sheet2 = SpreadsheetApp.openById("10gfdMLuEZL_e6KDu_PRhDgArKFIivVj3SkwWI-kMDws");
  var currDate = new Date();
  var editedDate = new Date(currDate - 86400000);

  var insert = sheet1.getSheetByName("Nicaragua");
  var archive = sheet2.getSheetByName("NI");
  var insertData = insert.getRange(2, 1, (sheet1.getRange('A:G').getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow()), 28);

  for (row = 2; row <= insertData.getNumRows(); row++){
    var data = insert.getRange(row, 1, 1, 28).getValues();

    if (data[0][0] < currDate && data[0][0] > editedDate){
     archive.getRange((archive.getLastRow() + 1), 1, 1, 28).setValues(data).setNumberFormat("MM/dd/yyyy");
    }
  }
}

But I when I run it is not working and I need this process happens automathic each time a new record is found

I've tried googling for my answer but I could not find one.

Body:
Don't know what your function has to do with you question but this will have a much greater chance of working.

If you wish it to run automatically then create a timebased trigger for it.

function copyFromOneSheetToAnother() {
  const ss1 = SpreadsheetApp.openById("10gfdMLuEZL_e6KDu_PRhDgArKFIivVj3SkwWI-kMDws");
  const ss2 = SpreadsheetApp.openById("10gfdMLuEZL_e6KDu_PRhDgArKFIivVj3SkwWI-kMDws");
  const dt = new Date()
  const today = new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();
  const yesterday =new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()-1).valueOf();
  const sh1 = ss1.getSheetByName("Nicaragua");
  const sh2 = ss2.getSheetByName("NI");
  const vs1 = sh1.getRange(2, 1, sh1.getLastRow() - 1, 28).getValues();
  vs1.forEach((r, i) => {
    let dtv = new Date(r[0]);
    if (dtv < today && dtv > yesterday) {
      sh2.getRange(sh2.getLastRow() + 1, 1, 1, r.length).setValues(r).setNumberFormat("MM/dd/yyyy");
    }
  });
}


问:
What features are people looking forward to in .Net 4.0 - 4.1
I am very interested in learning what features people are interested in in the forthcoming .net framework(s)?

Whether these be new classes or new controls I am curious to know people views.

答:
Code Contracts and Parallel Extensions. Neither are language features (which is mostly what I get interested in usually) but both have the potential to significantly change how we write code.

The DLR does sound cool and interesting, but I'm not sure I'd end up using it much, at least in terms of interoperating with IronRuby/IronPython. It'll be nice to be able to use late binding to reduce reflection boilerplate code though

In terms of C# 4 language features, covariance and contravariance will be more of a "phew, that reduces an annoyance" than a "wahay, cool stuff!" but optional/named arguments could be very handy. It'll make writing/using immutable types slightly easier, although I'd still like built-in support for the builder pattern :)

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Jon Skeet


问:
Windows batch: echo without new line
What is the Windows batch equivalent of the Linux shell command echo -n which suppresses the newline at the end of the output?

The idea is to write on the same line inside a loop.

答:
I believe there's no such option. Alternatively you can try this</p>

```<code>set text=Hello
set text=%text% world
echo %text%
</code>```

Title: Windows batch: echo without new line

Body:
I believe there's no such option. Alternatively you can try this

set text=Hello
set text=%text% world
echo %text%


问:
How to combine a print line into one line with an input line?
I'm using Python 3.10 and need help to combine a print line into one line with an input line. This is what I got:

```<code>for day in range (1, 6):
    print("Enter the amount of bugs collected on day", day)
    num_bugs_collected = int(input())
    total_bugs += num_bugs_collected

print("You collected a total of", total_bugs, "bugs.")
</code>```

I need to combine the second and third lines.

答:
Here's one way to do that.</p>
```<code>for day in range (1, 6):
    num_bugs_collected = int(input(f"Enter the amount of bugs collected on day {day}\n"))
    total_bugs += num_bugs_collected

print("You collected a total of", total_bugs, "bugs.")
</code>```

Body:
I'm using Python 3.10 and need help to combine a print line into one line with an input line. This is what I got:

for day in range (1, 6):
    print("Enter the amount of bugs collected on day", day)
    num_bugs_collected = int(input())
    total_bugs += num_bugs_collected

print("You collected a total of", total_bugs, "bugs.")

I need to combine the second and third lines.

Body:
Here's one way to do that.

for day in range (1, 6):
    num_bugs_collected = int(input(f"Enter the amount of bugs collected on day {day}\n"))
    total_bugs += num_bugs_collected

print("You collected a total of", total_bugs, "bugs.")


问:
How to get the results of a TDE in MarkLogic in RDF/JSON or Turtle format?
With any kind of Template Driven Extraction (TDE) in MarkLogic, how can I convert the results I get from the tde:node-data-extract function into RDF/JSON format? The JSON format returned by this method is not compliant with RDF/JSON, so I can't use it directly to insert triples into another database. In this case, I don't want to insert the triples into the same database that I'm applying the template against, I just want to use the template to create triples from XML data.

Here's an example of the JSON output that I get from the tde:node-data-extract function:

```<code>{
    "document/pt/document/39627370": [{
            "triple": {
                "subject": "http://www.example.com/document/id/39627370",
                "predicate": "http://www.example.com/typeOf",
                "object": {
                    "datatype": "http://www.w3.org/2001/XMLSchema#string",
                    "value": "http://www.example.com/document"
                }
            }
        },
        {
            "triple": {
                "subject": "http://www.example.com/publisher/Oxford_University_Press",
                "predicate": "http://www.example.com/typeOf",
                "object": {
                    "datatype": "http://www.w3.org/2001/XMLSchema#string",
                    "value": "http://www.example.com/publisher"
                }
            }
        }
   }
}
</code>```

答:
With the help from John and Mads, I found a slight variation that works really well assuming you're in the query console. $docs is any sequence of documents and $template is the TDE template.

```<code>let $jsontriples := tde:node-data-extract($docs, $template)

for $key in map:keys($jsontriples)
  let $entry := map:get($jsontriples, $key)
  return $entry["triple"]
</code>```

This will return the triples automatically serialized into Turtle format in the query console Result tab, which you can switch to JSON or Text. I assume the answer from John is the most correct in a situation where the serialization is not automatically performed (e.g. when not using the query console).

Body:
With any kind of Template Driven Extraction (TDE) in MarkLogic, how can I convert the results I get from the tde:node-data-extract function into RDF/JSON format? The JSON format returned by this method is not compliant with RDF/JSON, so I can't use it directly to insert triples into another database. In this case, I don't want to insert the triples into the same database that I'm applying the template against, I just want to use the template to create triples from XML data.

Here's an example of the JSON output that I get from the tde:node-data-extract function:

{
    "document/pt/document/39627370": [{
            "triple": {
                "subject": "http://www.example.com/document/id/39627370",
                "predicate": "http://www.example.com/typeOf",
                "object": {
                    "datatype": "http://www.w3.org/2001/XMLSchema#string",
                    "value": "http://www.example.com/document"
                }
            }
        },
        {
            "triple": {
                "subject": "http://www.example.com/publisher/Oxford_University_Press",
                "predicate": "http://www.example.com/typeOf",
                "object": {
                    "datatype": "http://www.w3.org/2001/XMLSchema#string",
                    "value": "http://www.example.com/publisher"
                }
            }
        }
   }
}

Body:
With the help from John and Mads, I found a slight variation that works really well assuming you're in the query console. $docs is any sequence of documents and $template is the TDE template.

let $jsontriples := tde:node-data-extract($docs, $template)

for $key in map:keys($jsontriples)
  let $entry := map:get($jsontriples, $key)
  return $entry["triple"]

This will return the triples automatically serialized into Turtle format in the query console Result tab, which you can switch to JSON or Text. I assume the answer from John is the most correct in a situation where the serialization is not automatically performed (e.g. when not using the query console).


问:
Bazel build file load multiple dependencies
I have a Python repo that contains two requirement files. In my WORKSPACE file, I imported both the dependencies.

requirements-1.txt:

```<code>numpy
</code>```

requirements-2.txt:

```<code>scipy
</code>```

WORKSPACE:

```<code>load("@rules_python//python:pip.bzl", "pip_install")

pip_install(
    name = "deps_1",
    requirements = "//:requirements-1.txt",
)

pip_install(
    name = "deps_2",
    requirements = "//folder2:requirements-2.txt",
)
</code>```

I have a BUILD file like this:

```<code>load("@rules_python//python:defs.bzl", "py_library")
load("@deps_1//:requirements.bzl", "requirement")
load("@deps_2//:requirements.bzl", "requirement")

py_library(
    name = "test",
    srcs = ["test.py"],
    deps = [
        requirement("numpy"),
        requirement("scipy"),
    ],
)
</code>```

The build can't import numpy

```<code>no such package '@deps//pypi__numpy': BUILD file not found in directory 'pypi__numpy' of external repository @deps2. Add a BUILD file to a directory to mark it as a package.
</code>```

How do I load two dependencies in the same BUILD file?

答:
In general, you can do this by loading the two requirements with different names. Like this:

load("@deps_1//:requirements.bzl", deps_1_requirement = "requirement")
load("@deps_2//:requirements.bzl", deps_2_requirement = "requirement")
```

Then you can use deps_1_requirement("numpy") and deps_2_requirement("scipy").

However, with those two particular libraries, scipy depends on numpy. If you load both of them, you'll end up with two different numpy copies. If they're both the same version, it'll probably work. If they're different versions, you might run into weird issues. I think you can just drop numpy from the list and your code should be able to import the single version that pip/rules_python bring in because it's a dependency of scipy.

Body:
I have a Python repo that contains two requirement files. In my WORKSPACE file, I imported both the dependencies.

requirements-1.txt:

numpy

requirements-2.txt:

scipy

WORKSPACE:

load("@rules_python//python:pip.bzl", "pip_install")

pip_install(
    name = "deps_1",
    requirements = "//:requirements-1.txt",
)

pip_install(
    name = "deps_2",
    requirements = "//folder2:requirements-2.txt",
)

I have a BUILD file like this:

load("@rules_python//python:defs.bzl", "py_library")
load("@deps_1//:requirements.bzl", "requirement")
load("@deps_2//:requirements.bzl", "requirement")

py_library(
    name = "test",
    srcs = ["test.py"],
    deps = [
        requirement("numpy"),
        requirement("scipy"),
    ],
)

The build can't import numpy

no such package '@deps//pypi__numpy': BUILD file not found in directory 'pypi__numpy' of external repository @deps2. Add a BUILD file to a directory to mark it as a package.

How do I load two dependencies in the same BUILD file?

Body:
In general, you can do this by loading the two requirements with different names. Like this:

load("@deps_1//:requirements.bzl", deps_1_requirement = "requirement")
load("@deps_2//:requirements.bzl", deps_2_requirement = "requirement")

Then you can use deps_1_requirement("numpy") and deps_2_requirement("scipy").

However, with those two particular libraries, scipy depends on numpy. If you load both of them, you'll end up with two different numpy copies. If they're both the same version, it'll probably work. If they're different versions, you might run into weird issues. I think you can just drop numpy from the list and your code should be able to import the single version that pip/rules_python bring in because it's a dependency of scipy.


问:
Reading *.wav files in Python
I need to analyze sound written in a .wav file. For that I need to transform this file into set of numbers (arrays, for example). I think I need to use the wave package. However, I do not know how exactly it works. For example I did the following:

```<code>import wave
w = wave.open('/usr/share/sounds/ekiga/voicemail.wav', 'r')
for i in range(w.getnframes()):
    frame = w.readframes(i)
    print frame
</code>```

As a result of this code I expected to see sound pressure as function of time. In contrast I see a lot of strange, mysterious symbols (which are not hexadecimal numbers). Can anybody, pleas, help me with that?

答:
My dear, as far as I understood what you are looking for, you are getting into a theory field called Digital Signal Processing (DSP). This engineering area comes from a simple analysis of discrete-time signals to complex adaptive filters. A nice idea is to think of the discrete-time signals as a vector, where each element of this vector is a sampled value of the original, continuous-time signal. Once you get the samples in a vector form, you can apply different digital signal techniques to this vector.

Unfortunately, on Python, moving from audio files to NumPy array vector is rather cumbersome, as you could notice... If you don't idolize one programming language over other, I highly suggest trying out MatLab/Octave. Matlab makes the samples access from files straightforward. audioread() makes this task to you :) And there are a lot of toolboxes designed specifically for DSP.

Nevertheless, if you really intend to get into Python for this, I'll give you a step-by-step to guide you.

1. Get the samples

The easiest way the get the samples from the .wav file is:

```<code>from scipy.io import wavfile

sampling_rate, samples = wavfile.read(f'/path/to/file.wav')

</code>```

Alternatively, you could use the wave and struct package to get the samples:

```<code>import numpy as np
import wave, struct

wav_file = wave.open(f'/path/to/file.wav', 'rb')
# from .wav file to binary data in hexadecimal
binary_data = wav_file.readframes(wav_file.getnframes())
# from binary file to samples
s = np.array(struct.unpack('{n}h'.format(n=wav_file.getnframes()*wav_file.getnchannels()), binary_data))
</code>```

Answering your question: binary_data is a bytes object, which is not human-readable and can only make sense to a machine. You can validate this statement typing type(binary_data). If you really want to understand a little bit more about this bunch of odd characters, click here.

If your audio is stereo (that is, has 2 channels), you can reshape this signal to achieve the same format obtained with scipy.io

```<code>s_like_scipy = s.reshape(-1, wav_file.getnchannels())
</code>```

Each column is a chanell. In either way, the samples obtained from the .wav file can be used to plot and understand the temporal behavior of the signal.

In both alternatives, the samples obtained from the files are represented in the Linear Pulse Code Modulation (LPCM)

2. Do digital signal processing stuffs onto the audio samples

I'll leave that part up to you :) But this is a nice book to take you through DSP. Unfortunately, I don't know good books with Python, they are usually horrible books... But do not worry about it, the theory can be applied in the very same way using any programming language, as long as you domain that language.

Whatever the book you pick up, stick with the classical authors, such as Proakis, Oppenheim, and so on... Do not care about the language programming they use. For a more practical guide of DPS for audio using Python, see this page.

3. Play the filtered audio samples

```<code>import pyaudio

p = pyaudio.PyAudio()
stream = p.open(format = p.get_format_from_width(wav_file.getsampwidth()),
                channels = wav_file.getnchannels(),
                rate = wav_file.getframerate(),
                output = True)
# from samples to the new binary file
new_binary_data = struct.pack('{}h'.format(len(s)), *s)
stream.write(new_binary_data)
</code>```

where wav_file.getsampwidth() is the number of bytes per sample, and wav_file.getframerate() is the sampling rate. Just use the same parameters of the input audio.

4. Save the result in a new .wav file

```<code>wav_file=wave.open('/phat/to/new_file.wav', 'w')

wav_file.setparams((nchannels, sampwidth, sampling_rate, nframes, "NONE", "not compressed"))

for sample in s:
   wav_file.writeframes(struct.pack('h', int(sample)))
</code>```

where nchannels is the number of channels, sampwidth is the number of bytes per samples, sampling_rate is the sampling rate, nframes is the total number of samples.

Title: Reading *.wav files in Python

Body:
I need to analyze sound written in a .wav file. For that I need to transform this file into set of numbers (arrays, for example). I think I need to use the wave package. However, I do not know how exactly it works. For example I did the following:

import wave
w = wave.open('/usr/share/sounds/ekiga/voicemail.wav', 'r')
for i in range(w.getnframes()):
    frame = w.readframes(i)
    print frame

As a result of this code I expected to see sound pressure as function of time. In contrast I see a lot of strange, mysterious symbols (which are not hexadecimal numbers). Can anybody, pleas, help me with that?

Body:
My dear, as far as I understood what you are looking for, you are getting into a theory field called Digital Signal Processing (DSP). This engineering area comes from a simple analysis of discrete-time signals to complex adaptive filters. A nice idea is to think of the discrete-time signals as a vector, where each element of this vector is a sampled value of the original, continuous-time signal. Once you get the samples in a vector form, you can apply different digital signal techniques to this vector.

Unfortunately, on Python, moving from audio files to NumPy array vector is rather cumbersome, as you could notice... If you don't idolize one programming language over other, I highly suggest trying out MatLab/Octave. Matlab makes the samples access from files straightforward. audioread() makes this task to you :) And there are a lot of toolboxes designed specifically for DSP.

Nevertheless, if you really intend to get into Python for this, I'll give you a step-by-step to guide you.

1. Get the samples

The easiest way the get the samples from the .wav file is:

from scipy.io import wavfile

sampling_rate, samples = wavfile.read(f'/path/to/file.wav')

Alternatively, you could use the wave and struct package to get the samples:

import numpy as np
import wave, struct

wav_file = wave.open(f'/path/to/file.wav', 'rb')
# from .wav file to binary data in hexadecimal
binary_data = wav_file.readframes(wav_file.getnframes())
# from binary file to samples
s = np.array(struct.unpack('{n}h'.format(n=wav_file.getnframes()*wav_file.getnchannels()), binary_data))

Answering your question: binary_data is a bytes object, which is not human-readable and can only make sense to a machine. You can validate this statement typing type(binary_data). If you really want to understand a little bit more about this bunch of odd characters, click here.

If your audio is stereo (that is, has 2 channels), you can reshape this signal to achieve the same format obtained with scipy.io

s_like_scipy = s.reshape(-1, wav_file.getnchannels())

Each column is a chanell. In either way, the samples obtained from the .wav file can be used to plot and understand the temporal behavior of the signal.

In both alternatives, the samples obtained from the files are represented in the Linear Pulse Code Modulation (LPCM)

2. Do digital signal processing stuffs onto the audio samples

I'll leave that part up to you :) But this is a nice book to take you through DSP. Unfortunately, I don't know good books with Python, they are usually horrible books... But do not worry about it, the theory can be applied in the very same way using any programming language, as long as you domain that language.

Whatever the book you pick up, stick with the classical authors, such as Proakis, Oppenheim, and so on... Do not care about the language programming they use. For a more practical guide of DPS for audio using Python, see this page.

3. Play the filtered audio samples

import pyaudio

p = pyaudio.PyAudio()
stream = p.open(format = p.get_format_from_width(wav_file.getsampwidth()),
                channels = wav_file.getnchannels(),
                rate = wav_file.getframerate(),
                output = True)
# from samples to the new binary file
new_binary_data = struct.pack('{}h'.format(len(s)), *s)
stream.write(new_binary_data)

where wav_file.getsampwidth() is the number of bytes per sample, and wav_file.getframerate() is the sampling rate. Just use the same parameters of the input audio.

4. Save the result in a new .wav file

wav_file=wave.open('/phat/to/new_file.wav', 'w')

wav_file.setparams((nchannels, sampwidth, sampling_rate, nframes, "NONE", "not compressed"))

for sample in s:
   wav_file.writeframes(struct.pack('h', int(sample)))

where nchannels is the number of channels, sampwidth is the number of bytes per samples, sampling_rate is the sampling rate, nframes is the total number of samples.


问:
Unable to use old java projects in new eclipse installation
I did an upgrade of my windows OS and restored my eclipse workspace from my backup. Now, when I try to open any of the older projects, they complain with a message:

```<code>Unbound classpath container: 'JRE System Library [jre6]' in project <ProjectName>
</code>```

When I looked around, I found pages which suggest that I change the JRE version for the project. However, I have about 50 projects in this workspace and do not want to change the value for each of them.

Any suggestions would be welcome.

Thanks and regards,

Karthick S.

答:
The problem is that if you backed up the eclipse project files, then these contain information regarding paths to your JRE or JDK install and any external jars (specific to your last install). There are 2 files that you can edit with any text editor to fix this problem .classpath and .project.

Other option would be to delete the classpath and project files and try to import the project as java project using File > Import.

Body:
I did an upgrade of my windows OS and restored my eclipse workspace from my backup. Now, when I try to open any of the older projects, they complain with a message:

Unbound classpath container: 'JRE System Library [jre6]' in project <ProjectName>

When I looked around, I found pages which suggest that I change the JRE version for the project. However, I have about 50 projects in this workspace and do not want to change the value for each of them.

Any suggestions would be welcome.

Thanks and regards,

Karthick S.


问:
Nullable Foreign Keys
I have an Orders wpf grid, this view includes 2 foreign keys, Customers and Vendors.
The Create Orders View includes these 2 foreign keys too, as well as imports extra info like vendor id and name and phone number.

It is not always necessary to fill out the vendor on this view, however everything I've tried doesn't allow the vendor to be null.

I've tried stuff like this but the flow here doesn't match my case, and can't seem to access the right properties when trying to manipulate the flow. https://stackoverflow.com/a/49652484/4583310

putting "?" after my variables is giving foreign key errors as well.

how can I get this baby to accept null values?

```<code> public readonly struct CreateOrderRequest
{
    //[Required]
    public int VendorId { get; init; }
    [Required]
    public int CustomerId { get; init; }
    public string SearchUrl { get; init; }
}

 public class Order
{
    [Key]
    public int Id { get; set; }
    public string Description { get; set; }

    [ForeignKey(nameof(Vendor))]
    public int VendorId { get; set; }
    public Vendor Vendor { get; set; }
    public string SearchUrl { get; set; }

    [ForeignKey(nameof(Customer))]
    public int CustomerId { get; set; }
    public Customer Customer { get; set; }
}

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
       // modelBuilder.Entity<Order>().HasMany(a => Vendor);
        OnModelCreatingPartial(modelBuilder);
    }
</code>```

I get errors on the await command

```<code>  public async Task<Order> CreateOrderAsync(Order order)
    {
        var entry = await _ordersDbSet.AddAsync(order);
        await _dbContext.SaveChangesAsync();
        return entry.Entity;
    }
</code>```

which stem from trying to post from the orders controller. I turned off validating the vendor

```<code> public async Task<IActionResult> CreateOrderAsync(CreateOrderRequest request)
    {
        if (await ValidateCreateOrderRequestAsync(request) is false)
            return BadRequest();

        var order = _mapper.Map<Order>(request);
        order = await _ordersUnitOfWork.CreateOrderAsync(order);
        order = await _ordersUnitOfWork.GetOrderAsync(order.Id);

        var orderDto = _mapper.Map<OrderDto>(order);
        return Ok(orderDto);
    }
</code>```

答: Took me a while, but I finally figured out I need to place some of those ?'s in my requests and my models where my foreign key id's were laying, not just for the Model that is currently in view. Edit: after fixing it this way, I had to go in and change some validation checks and Also add the ? to some of my DTO's</p>

Title: Nullable Foreign Keys

Body:
I have an Orders wpf grid, this view includes 2 foreign keys, Customers and Vendors.
The Create Orders View includes these 2 foreign keys too, as well as imports extra info like vendor id and name and phone number.

It is not always necessary to fill out the vendor on this view, however everything I've tried doesn't allow the vendor to be null.

I've tried stuff like this but the flow here doesn't match my case, and can't seem to access the right properties when trying to manipulate the flow. https://stackoverflow.com/a/49652484/4583310

putting "?" after my variables is giving foreign key errors as well.

how can I get this baby to accept null values?

 public readonly struct CreateOrderRequest
{
    //[Required]
    public int VendorId { get; init; }
    [Required]
    public int CustomerId { get; init; }
    public string SearchUrl { get; init; }
}

 public class Order
{
    [Key]
    public int Id { get; set; }
    public string Description { get; set; }

    [ForeignKey(nameof(Vendor))]
    public int VendorId { get; set; }
    public Vendor Vendor { get; set; }
    public string SearchUrl { get; set; }

    [ForeignKey(nameof(Customer))]
    public int CustomerId { get; set; }
    public Customer Customer { get; set; }
}

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
       // modelBuilder.Entity<Order>().HasMany(a => Vendor);
        OnModelCreatingPartial(modelBuilder);
    }

I get errors on the await command

  public async Task<Order> CreateOrderAsync(Order order)
    {
        var entry = await _ordersDbSet.AddAsync(order);
        await _dbContext.SaveChangesAsync();
        return entry.Entity;
    }

which stem from trying to post from the orders controller. I turned off validating the vendor

 public async Task<IActionResult> CreateOrderAsync(CreateOrderRequest request)
    {
        if (await ValidateCreateOrderRequestAsync(request) is false)
            return BadRequest();

        var order = _mapper.Map<Order>(request);
        order = await _ordersUnitOfWork.CreateOrderAsync(order);
        order = await _ordersUnitOfWork.GetOrderAsync(order.Id);

        var orderDto = _mapper.Map<OrderDto>(order);
        return Ok(orderDto);
    }


问:
Typescript Override Function for Object
So I am Having this small little function for pinia. Where I do throw in an ID of my Object to filter it (result is of type Task | undefined)
I am giving in a Key which should of course be a keyof Task and now I kind of struggle with the value part. I've tried to find out what serves my usecase best, it must be something like a value Of or so but I do currently not find the correct Utility Type (if it even should be one).

```<code>changeValue(id: number, key: keyof Task , value: Partial<Task>) {
    const task = this.one(id);

    if (task) {
        task[key] = value;
    }
}
</code>```

Also I have a Second Problem here that task[key] says its of type never can anyone explain why this is of type never?

答:
You could make your code work simply by leveraging the TypeScript inference with proper control flow:</p>
```<code>changeValue(id: number, key: keyof Task , value: Partial<Task>) {
    const task = this.one(id);

    if(task === undefined)
        return; // Handle the undefined case

    const propToAssign = value[key];

    if(propToAssign === undefined)
        return; // Handle the undefined case

    task[key] = propToAssign;
}
</code>```

Title: Typescript Override Function for Object

Body:
So I am Having this small little function for pinia. Where I do throw in an ID of my Object to filter it (result is of type Task | undefined)
I am giving in a Key which should of course be a keyof Task and now I kind of struggle with the value part. I've tried to find out what serves my usecase best, it must be something like a value Of or so but I do currently not find the correct Utility Type (if it even should be one).

changeValue(id: number, key: keyof Task , value: Partial<Task>) {
    const task = this.one(id);

    if (task) {
        task[key] = value;
    }
}

Also I have a Second Problem here that task[key] says its of type never can anyone explain why this is of type never?

Body:
You could make your code work simply by leveraging the TypeScript inference with proper control flow:

changeValue(id: number, key: keyof Task , value: Partial<Task>) {
    const task = this.one(id);

    if(task === undefined)
        return; // Handle the undefined case

    const propToAssign = value[key];

    if(propToAssign === undefined)
        return; // Handle the undefined case

    task[key] = propToAssign;
}


问:
How can you create a Project Sheet in SmartSheets with the API
I'm a new user of the SmartSheets API, attempting to create an integration.  I have projects that are created in an external system that I wish to represent in a Project Sheet in SmartSheets, but in my attempts so far using the SmartSheets API, all I can create is a simple grid.  Is there an API that will allow me to create a Project Sheet in SmartSheets?</p>

答:
You can autonomate the full process:

have a project sheet sitting somewhere for a system account you own.

share the sheet to the desired account (as viewer)

copy the sheet with that second (the second account is now the woner of the sheet)

unshare the first sheet (no longer needed)


问:
Template partial specialization for integral non-type parameters and non-integral non-types, difference between g++ and clang

The following is a simple template partial specialization:

```<code>// #1
template <typename T, T n1, T n2>
struct foo {
    static const char* scenario() {
        return "#1 the base template";
    }
};

// #2
// partial specialization where T is unknown and n1 == n2
template <typename T, T a>
struct foo<T, a, a> {
    static const char* scenario() {
        return "#2 partial specialization";
    }
};
</code>```

The main below gets different results on g++ (6.1) and clang++ (3.8.0):

```<code>extern const char HELLO[] = "hello";
double d = 2.3;

int main() {
    cout <<   foo<int, 1, 2>                    ::scenario() << endl;
    cout <<   foo<int, 2, 2>                    ::scenario() << endl;
    cout <<   foo<long, 3, 3>                   ::scenario() << endl;
    cout <<   foo<double&, d, d>                ::scenario() << endl;
    cout <<   foo<double*, &d, &d>              ::scenario() << endl;
    cout <<   foo<double*, nullptr, nullptr>    ::scenario() << endl;
    cout <<   foo<int*, nullptr, nullptr>       ::scenario() << endl;
    cout <<   foo<nullptr_t, nullptr, nullptr>  ::scenario() << endl;
    cout <<   foo<const char*, HELLO, HELLO>    ::scenario() << endl;
}
</code>```

Results on g++ and clang++

# | The code                          | g++ (6.1)       |  clang++ (3.8.0) |

1 | foo<int, 1, 2>                    | #1 as expected  |  #1 as expected  |

2 | foo<int, 2, 2>                    | #2 as expected  |  #2 as expected  |

3 | foo<long, 3, 3>                   | #2 as expected  |  #2 as expected  |

4 | foo<double&, d, d>                | #1 -- why?      |  #2 as expected  |

5 | foo<double*, &d, &d>              | #2 as expected  |  #2 as expected  |

6 | foo<double*, nullptr, nullptr>    | #2 as expected  |  #1 -- why?      |

7 | foo<int*, nullptr, nullptr>       | #2 as expected  |  #1 -- why?      |

8 | foo<nullptr_t, nullptr, nullptr>  | #2 as expected  |  #1 -- why?      |

9 | foo<const char*, HELLO, HELLO>    | #2 as expected  |  #2 as expected  |

Which one is right?

Code: https://godbolt.org/z/4GfYqxKn3

EDIT, Dec-2021:

Along the years since the original post, the results have changed, and were even identical for gcc and clang at a certain point in time, but checking again, g++ (11.2) and clang++ (12.0.1) changed their results on references (case 4), but still differ on it. It seems that currently gcc is getting it all right and clang is wrong on the reference case.

# | The code                          | g++ (11.2)      | clang++ (12.0.1) |

1 | foo<int, 1, 2>                    | #1 as expected  |  #1 as expected  |

2 | foo<int, 2, 2>                    | #2 as expected  |  #2 as expected  |

3 | foo<long, 3, 3>                   | #2 as expected  |  #2 as expected  |

4 | foo<double&, d, d>                | #2 as expected  |  #1 -- why?      |

5 | foo<double*, &d, &d>              | #2 as expected  |  #2 as expected  |

6 | foo<double*, nullptr, nullptr>    | #2 as expected  |  #2 as expected  |

7 | foo<int*, nullptr, nullptr>       | #2 as expected  |  #2 as expected  |

8 | foo<nullptr_t, nullptr, nullptr>  | #2 as expected  |  #2 as expected  |

9 | foo<const char*, HELLO, HELLO>    | #2 as expected  |  #2 as expected  |

答:
I will dedicate my answer to case #4, because according to the OP's EDIT, the compilers now agree on cases #6-8:

# | The code                          | g++ (6.1)       |  clang++ (3.8.0) |

4 | foo<double&, d, d>                | #1 -- why?      |  #2 as expected  |

Seems like clang++ 3.8.0 behaves correctly and gcc 6.1 rejects the perfectly fine partial specialization for this case because of the following bug that was fixed in gcc 7.2:

Bug 77435 - Dependent reference non-type template parameter not matched for partial specialization

There is a diff there with this key change in the compiler's code:

```<code>// Was: else if (same_type_p (TREE_TYPE (arg), tparm))
else if (same_type_p (non_reference (TREE_TYPE (arg)), non_reference(tparm)))
</code>```

Before gcc 7.2, when a dependent type T& was matched with argument of type T in a parital specialization candidate, the compiler falsely rejected it. This behavior can be demostrated in a cleaner example:

```<code>template <typename T, T... x>
struct foo {
    static void scenario() { cout << "#1" << endl; }
};

// Partial specialization when sizeof...(x) == 1
template <typename T, T a>
struct foo<T, a> {
    static void scenario() { cout << "#2" << endl; }
};
</code>```

In the case of T = const int the behavior of gcc 6.1 and gcc 7.2 is the same:

```<code>const int i1 = 1, i2 = 2;
foo<const int, i1, i2>::scenario(); // Both print #1
foo<const int, i1>::scenario();     // Both print #2
</code>```

But in case of T = const int& the behavior of gcc 6.1 is to reject the correct partial specialization and choose the base implementation instead:

```<code>foo<const int&, i1, i2>::scenario(); // Both print #1
foo<const int&, i1>::scenario();     // gcc 6.1 prints #1 but gcc 7.2 prints #2
</code>```

It affects any reference type, here are some more examples:

```<code>double d1 = 2.3, d2 = 4.6;

struct bar {};
bar b1, b2;

foo<double&, d1, d2>::scenario(); // Both print #1
foo<double&, d1>::scenario();     // gcc 6.1 prints #1 but gcc 7.2 prints #2
foo<bar&, b1, b2>::scenario();    // Both print #1
foo<bar&, b1>::scenario();        // gcc 6.1 prints #1 but gcc 7.2 prints #2
</code>```

You can run this example here: https://godbolt.org/z/Y1KjazrMP

gcc seems to make this mistake up to gcc 7.1 but from gcc 7.2 up to the current version it chooses the partial specialization correctly because of the bugfix above.

In conclusion, case #4's result in the question is just a symptom of a more general problem and it happens just because double& is a reference type. To demonstrate this claim, try to add the following line in the OP's code (and bar, b1 definitions from my example):

```<code>cout << foo<bar&, b1, b1>::scenario() << endl;
</code>```

and observe that gcc 6.1 prints again "#1 the base template" while gcc 7.2 and onward prints "#2 partial specialization" as expected.

EDIT

Regarding the follow-up question in the OP's EDIT:

# | The code                          | g++ (11.2)      | clang++ (12.0.1) |

4 | foo<double&, d, d>                | #2 as expected  |  #1 -- why?      |

I think that g++ (11.2) is correct.

Pay attention that clang wasn't flipped its answer entirely because in your link, you have used c++20 standard but if you change it back to c++14 as in the original question, even clang++ 12.0.1 agrees with g++ 11.2 and chooses the parial specialization.

Actually, it happens with clang in c++17 too and it seems to be an issue in clang that started with this standard and isn't fixed until today.

If you try to add the following test case to your code:

```<code>TEST (foo<const int, 2, 2>); // clang (c++17/20) prints #1 and gcc (any) prints #2
</code>```

clang also chooses the base template instead of the partial specialization like gcc while in this test case:

```<code>TEST (foo<int, 2, 2>); // Both agree on #2
</code>```

they both agree, which I find odd, because this added const to the type shouldn't impact the partial specialization's fitness and it seems like clang doesn't do that for references only, but for consts as well! and only when the standard >= C++17.

BTW, this issue can be reproduced in my example too:
https://godbolt.org/z/W9q83j3Pq

Observe that clang 8.0.0 disagrees with itself just by changing the language standard and it keeps doing that up to clang 13.0.0 even on such a simple case when no argument value equality required.

These odd template deductions in clang raise enough "red flags" so I must conclude that g++ (11.2) is correct.

My wild guess is - C++17 introduced CTAD, which make clang act differently with class template deduction, and this issue is somehow connected to its new implementation while the old C++14 implementation stayed intact.

Body:
The following is a simple template partial specialization:

// #1
template <typename T, T n1, T n2>
struct foo {
    static const char* scenario() {
        return "#1 the base template";
    }
};

// #2
// partial specialization where T is unknown and n1 == n2
template <typename T, T a>
struct foo<T, a, a> {
    static const char* scenario() {
        return "#2 partial specialization";
    }
};

The main below gets different results on g++ (6.1) and clang++ (3.8.0):

extern const char HELLO[] = "hello";
double d = 2.3;

int main() {
    cout <<   foo<int, 1, 2>                    ::scenario() << endl;
    cout <<   foo<int, 2, 2>                    ::scenario() << endl;
    cout <<   foo<long, 3, 3>                   ::scenario() << endl;
    cout <<   foo<double&, d, d>                ::scenario() << endl;
    cout <<   foo<double*, &d, &d>              ::scenario() << endl;
    cout <<   foo<double*, nullptr, nullptr>    ::scenario() << endl;
    cout <<   foo<int*, nullptr, nullptr>       ::scenario() << endl;
    cout <<   foo<nullptr_t, nullptr, nullptr>  ::scenario() << endl;
    cout <<   foo<const char*, HELLO, HELLO>    ::scenario() << endl;
}

Results on g++ and clang++

# | The code                          | g++ (6.1)       |  clang++ (3.8.0) |

1 | foo<int, 1, 2>                    | #1 as expected  |  #1 as expected  |

2 | foo<int, 2, 2>                    | #2 as expected  |  #2 as expected  |

3 | foo<long, 3, 3>                   | #2 as expected  |  #2 as expected  |

4 | foo<double&, d, d>                | #1 -- why?      |  #2 as expected  |

5 | foo<double*, &d, &d>              | #2 as expected  |  #2 as expected  |

6 | foo<double*, nullptr, nullptr>    | #2 as expected  |  #1 -- why?      |

7 | foo<int*, nullptr, nullptr>       | #2 as expected  |  #1 -- why?      |

8 | foo<nullptr_t, nullptr, nullptr>  | #2 as expected  |  #1 -- why?      |

9 | foo<const char*, HELLO, HELLO>    | #2 as expected  |  #2 as expected  |

Which one is right?

Code: https://godbolt.org/z/4GfYqxKn3

EDIT, Dec-2021:

Along the years since the original post, the results have changed, and were even identical for gcc and clang at a certain point in time, but checking again, g++ (11.2) and clang++ (12.0.1) changed their results on references (case 4), but still differ on it. It seems that currently gcc is getting it all right and clang is wrong on the reference case.

# | The code                          | g++ (11.2)      | clang++ (12.0.1) |

1 | foo<int, 1, 2>                    | #1 as expected  |  #1 as expected  |

2 | foo<int, 2, 2>                    | #2 as expected  |  #2 as expected  |

3 | foo<long, 3, 3>                   | #2 as expected  |  #2 as expected  |

4 | foo<double&, d, d>                | #2 as expected  |  #1 -- why?      |

5 | foo<double*, &d, &d>              | #2 as expected  |  #2 as expected  |

6 | foo<double*, nullptr, nullptr>    | #2 as expected  |  #2 as expected  |

7 | foo<int*, nullptr, nullptr>       | #2 as expected  |  #2 as expected  |

8 | foo<nullptr_t, nullptr, nullptr>  | #2 as expected  |  #2 as expected  |

9 | foo<const char*, HELLO, HELLO>    | #2 as expected  |  #2 as expected  |

Body:
I will dedicate my answer to case #4, because according to the OP's EDIT, the compilers now agree on cases #6-8:

# | The code                          | g++ (6.1)       |  clang++ (3.8.0) |

4 | foo<double&, d, d>                | #1 -- why?      |  #2 as expected  |

Seems like clang++ 3.8.0 behaves correctly and gcc 6.1 rejects the perfectly fine partial specialization for this case because of the following bug that was fixed in gcc 7.2:

Bug 77435 - Dependent reference non-type template parameter not matched for partial specialization

There is a diff there with this key change in the compiler's code:

// Was: else if (same_type_p (TREE_TYPE (arg), tparm))
else if (same_type_p (non_reference (TREE_TYPE (arg)), non_reference(tparm)))

Before gcc 7.2, when a dependent type T& was matched with argument of type T in a parital specialization candidate, the compiler falsely rejected it. This behavior can be demostrated in a cleaner example:

template <typename T, T... x>
struct foo {
    static void scenario() { cout << "#1" << endl; }
};

// Partial specialization when sizeof...(x) == 1
template <typename T, T a>
struct foo<T, a> {
    static void scenario() { cout << "#2" << endl; }
};

In the case of T = const int the behavior of gcc 6.1 and gcc 7.2 is the same:

const int i1 = 1, i2 = 2;
foo<const int, i1, i2>::scenario(); // Both print #1
foo<const int, i1>::scenario();     // Both print #2

But in case of T = const int& the behavior of gcc 6.1 is to reject the correct partial specialization and choose the base implementation instead:

foo<const int&, i1, i2>::scenario(); // Both print #1
foo<const int&, i1>::scenario();     // gcc 6.1 prints #1 but gcc 7.2 prints #2

It affects any reference type, here are some more examples:

double d1 = 2.3, d2 = 4.6;

struct bar {};
bar b1, b2;

foo<double&, d1, d2>::scenario(); // Both print #1
foo<double&, d1>::scenario();     // gcc 6.1 prints #1 but gcc 7.2 prints #2
foo<bar&, b1, b2>::scenario();    // Both print #1
foo<bar&, b1>::scenario();        // gcc 6.1 prints #1 but gcc 7.2 prints #2

You can run this example here: https://godbolt.org/z/Y1KjazrMP

gcc seems to make this mistake up to gcc 7.1 but from gcc 7.2 up to the current version it chooses the partial specialization correctly because of the bugfix above.

In conclusion, case #4's result in the question is just a symptom of a more general problem and it happens just because double& is a reference type. To demonstrate this claim, try to add the following line in the OP's code (and bar, b1 definitions from my example):

cout << foo<bar&, b1, b1>::scenario() << endl;

and observe that gcc 6.1 prints again "#1 the base template" while gcc 7.2 and onward prints "#2 partial specialization" as expected.

EDIT

Regarding the follow-up question in the OP's EDIT:

# | The code                          | g++ (11.2)      | clang++ (12.0.1) |

4 | foo<double&, d, d>                | #2 as expected  |  #1 -- why?      |

I think that g++ (11.2) is correct.

Pay attention that clang wasn't flipped its answer entirely because in your link, you have used c++20 standard but if you change it back to c++14 as in the original question, even clang++ 12.0.1 agrees with g++ 11.2 and chooses the parial specialization.

Actually, it happens with clang in c++17 too and it seems to be an issue in clang that started with this standard and isn't fixed until today.

If you try to add the following test case to your code:

TEST (foo<const int, 2, 2>); // clang (c++17/20) prints #1 and gcc (any) prints #2

clang also chooses the base template instead of the partial specialization like gcc while in this test case:

TEST (foo<int, 2, 2>); // Both agree on #2

they both agree, which I find odd, because this added const to the type shouldn't impact the partial specialization's fitness and it seems like clang doesn't do that for references only, but for consts as well! and only when the standard >= C++17.

BTW, this issue can be reproduced in my example too:
https://godbolt.org/z/W9q83j3Pq

Observe that clang 8.0.0 disagrees with itself just by changing the language standard and it keeps doing that up to clang 13.0.0 even on such a simple case when no argument value equality required.

These odd template deductions in clang raise enough "red flags" so I must conclude that g++ (11.2) is correct.

My wild guess is - C++17 introduced CTAD, which make clang act differently with class template deduction, and this issue is somehow connected to its new implementation while the old C++14 implementation stayed intact.


问:
Is it possible to add linq to the end of a method that returns rows from a database? I just want to tack on an ORDER BY clause
```<code>private void cboEventFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ComboBoxItem item = cboEventFilter.SelectedItem as ComboBoxItem;

        switch (item.Content)
        {
            case "Date":
                //Original method
                datActiveEvents.ItemsSource = _eventManager.RetreieveActiveEvents();
                //Something like this line commented out

                //datActiveEvents.ItemsSource = _eventManager.RetreieveActiveEvents().OrderBy<EventDateID>;
                break;
            case "Time":
                MessageBox.Show("Time filter selected");
                break;
            case "Name":
                MessageBox.Show("Event Name filter selected");
                break;
            case "Sublocation":
                MessageBox.Show("Sublocation filter selected");
                break;
        }

    }
</code>```

答:
If the return type of RetreieveActiveEvents() is an IEnumerable<T>, you could use the OrderBy LINQ extension method:

```<code>datActiveEvents.ItemsSource = _eventManager.RetreieveActiveEvents()
    .OrderBy(x => x.EventDateID);
</code>```

If the return type is a non-generic IEnumerable, you could use the Cast extension method to convert it to an IEnumerable<T> before you sort the results:

```<code>datActiveEvents.ItemsSource = _eventManager.RetreieveActiveEvents()
    .Cast<YourClassWithTheEventDateIDProperty>()
    .OrderBy(x => x.EventDateID);
</code>```

Body:
If the return type of RetreieveActiveEvents() is an IEnumerable<T>, you could use the OrderBy LINQ extension method:

datActiveEvents.ItemsSource = _eventManager.RetreieveActiveEvents()
    .OrderBy(x => x.EventDateID);

If the return type is a non-generic IEnumerable, you could use the Cast extension method to convert it to an IEnumerable<T> before you sort the results:

datActiveEvents.ItemsSource = _eventManager.RetreieveActiveEvents()
    .Cast<YourClassWithTheEventDateIDProperty>()
    .OrderBy(x => x.EventDateID);


问:
How to extend Leaflet Icon Class to add data-open attribute to marker HTML?
I'm trying to trigger some functionality based on the click of a marker on a GeoJSON layer in Leaflet. The eventual functionality I'm trying to implement is a flyout, or scroll out type modal populated from the individual feature's JSON attributes. Essentially, I'm trying to implement the functionality in this Tutsplus Tutorial with dynamic feature content based on the marker click.

I THINK I've figured out most of the pieces I need, but I'm struggling with how to add a data attribute, specifically data-open, to the individual marker. Building on an earlier question of mine I've realized it's not enough to just update a DOM element's CSS, but rather my app should be implementing changes based on data attributes to fully get the functionality I want.

From this question I know that this should be done by extending the L.Icon class that Leaflet provides, but the answer is a bit too terse for my current JS skills. I apologize for this effectively being a "ELI5" of a previously asked question, but I'm not sure where the options and slug come into function. I think they're implied by the question, rather than the answer I'm citing and being set on the marker itself.

Here's a simplified version of the the click handler on my markers, which grabs and zooms to location, gets feature info, and populates that info to a div. The zoom functionality works, as does extracting and placing the feature info, but I'm struggling with how to connect the functionality to trigger the modal and place the div with the feature info over the map.

```<code>function zoomToFeature(e) {
  var latLngs = [e.target.getLatLng()];
  var markerBounds = L.latLngBounds(latLngs);
  var street = e.target.feature.properties.str_addr;
  document.getElementById('street').textContent = street;
  mymap.fitBounds(markerBounds);
  //where the modal trigger should be
  document.getElementById('infoBox').classList.add('is-visible');
}
</code>```

Here are the event listeners taken from the linked tutorial, which are currently not firing, but I have them working in a standalone implementation:

```<code>const openEls = document.querySelectorAll("[data-open]");
const closeEls = document.querySelectorAll("[data-close]");
const isVisible = "is-visible";
//this is the event I want to trigger on marker click
for (const el of openEls) {
  el.addEventListener("click", function() {
    const modalId = this.dataset.open;
    console.log(this);
    document.getElementById(modalId).classList.add(isVisible);
  });
}
for (const el of closeEls) {
  el.addEventListener("click", function() {
 this.parentElement.parentElement.parentElement.classList.remove(isVisible);
  });
}
document.addEventListener("click", e => {
  if (e.target == document.querySelector(".modal.is-visible")) {
    document.querySelector(".modal.is-visible").classList.remove(isVisible);
  }
});
</code>```

So, where I'm trying to get is that when my markers are clicked, the trigger the modal to appear over the map. So, I think I'm missing connecting the marker click event with the event that triggers the modal. I think what's missing is adding the data attribute to the markers, or some way chain the events without the data attributes. As there's no direct way to add an attribute to the markers, I try to add slug option on my circle markers:

```<code>var circleMarkerOptions = {
    radius: 2,
    weight: 1,
    opacity: 1,
    fillOpacity: 0.8,
    slug: 'open',
}
</code>```

and If I read the previously asked question's answer correctly, than extending the Icon Class this way should add a data-open attribute.

```<code>L.Icon.DataMarkup = L.Icon.extend({

    _setIconStyles: function(img, name) {
        L.Icon.prototype._setIconStyles.call(this, img, name);

        if (options.slug) {
            img.dataset.slug = options.slug;
        }
    }

});
</code>```

A stripped down version of my code is here (thanks @ghybs). My full implementation pulls the markers from a PostGIS table. It's a bit hard to see in the Plunker, but this code adds my class to my modal, but doesn't trigger the functionality. It does trigger the visibility if the class is manually updated to modal.is-visible, but the current implementation which renders modal is-visbile doesn't, which I think is because the CSS is interpreted on page load(?) and not in response to the update via the dev tools, while the concatenated css class matches extactly(?). When I do trigger the modal via the dev tools, the close modal listeners don't seem to work, so I'm also missing that piece of the puzzle.

答:
So, it's a work-around to setting the data attribute, but I realized I was shoe-horning a solution where it wasn't needed. Assuming someone ends up with the same mental block. Appropriate listeners on the modal close button and another function passed to the existing marker click listener produce the desired functionality.

```<code>const closeM = document.querySelector(".close-modal");
closeM.addEventListener("click", closeMe);
var modal = document.getElementById('infoBox');
</code>```

and

```<code>function modalAction(){
    modal.style.display = 'block';
}
function closeMe(){
    modal.style.display = 'none';
}
</code>```

Body:
I'm trying to trigger some functionality based on the click of a marker on a GeoJSON layer in Leaflet. The eventual functionality I'm trying to implement is a flyout, or scroll out type modal populated from the individual feature's JSON attributes. Essentially, I'm trying to implement the functionality in this Tutsplus Tutorial with dynamic feature content based on the marker click.

I THINK I've figured out most of the pieces I need, but I'm struggling with how to add a data attribute, specifically data-open, to the individual marker. Building on an earlier question of mine I've realized it's not enough to just update a DOM element's CSS, but rather my app should be implementing changes based on data attributes to fully get the functionality I want.

From this question I know that this should be done by extending the L.Icon class that Leaflet provides, but the answer is a bit too terse for my current JS skills. I apologize for this effectively being a "ELI5" of a previously asked question, but I'm not sure where the options and slug come into function. I think they're implied by the question, rather than the answer I'm citing and being set on the marker itself.

Here's a simplified version of the the click handler on my markers, which grabs and zooms to location, gets feature info, and populates that info to a div. The zoom functionality works, as does extracting and placing the feature info, but I'm struggling with how to connect the functionality to trigger the modal and place the div with the feature info over the map.

function zoomToFeature(e) {
  var latLngs = [e.target.getLatLng()];
  var markerBounds = L.latLngBounds(latLngs);
  var street = e.target.feature.properties.str_addr;
  document.getElementById('street').textContent = street;
  mymap.fitBounds(markerBounds);
  //where the modal trigger should be
  document.getElementById('infoBox').classList.add('is-visible');
}

Here are the event listeners taken from the linked tutorial, which are currently not firing, but I have them working in a standalone implementation:

const openEls = document.querySelectorAll("[data-open]");
const closeEls = document.querySelectorAll("[data-close]");
const isVisible = "is-visible";
//this is the event I want to trigger on marker click
for (const el of openEls) {
  el.addEventListener("click", function() {
    const modalId = this.dataset.open;
    console.log(this);
    document.getElementById(modalId).classList.add(isVisible);
  });
}
for (const el of closeEls) {
  el.addEventListener("click", function() {
 this.parentElement.parentElement.parentElement.classList.remove(isVisible);
  });
}
document.addEventListener("click", e => {
  if (e.target == document.querySelector(".modal.is-visible")) {
    document.querySelector(".modal.is-visible").classList.remove(isVisible);
  }
});

So, where I'm trying to get is that when my markers are clicked, the trigger the modal to appear over the map. So, I think I'm missing connecting the marker click event with the event that triggers the modal. I think what's missing is adding the data attribute to the markers, or some way chain the events without the data attributes. As there's no direct way to add an attribute to the markers, I try to add slug option on my circle markers:

var circleMarkerOptions = {
    radius: 2,
    weight: 1,
    opacity: 1,
    fillOpacity: 0.8,
    slug: 'open',
}

and If I read the previously asked question's answer correctly, than extending the Icon Class this way should add a data-open attribute.

L.Icon.DataMarkup = L.Icon.extend({

    _setIconStyles: function(img, name) {
        L.Icon.prototype._setIconStyles.call(this, img, name);

        if (options.slug) {
            img.dataset.slug = options.slug;
        }
    }

});

A stripped down version of my code is here (thanks @ghybs). My full implementation pulls the markers from a PostGIS table. It's a bit hard to see in the Plunker, but this code adds my class to my modal, but doesn't trigger the functionality. It does trigger the visibility if the class is manually updated to modal.is-visible, but the current implementation which renders modal is-visbile doesn't, which I think is because the CSS is interpreted on page load(?) and not in response to the update via the dev tools, while the concatenated css class matches extactly(?). When I do trigger the modal via the dev tools, the close modal listeners don't seem to work, so I'm also missing that piece of the puzzle.

Body:
So, it's a work-around to setting the data attribute, but I realized I was shoe-horning a solution where it wasn't needed. Assuming someone ends up with the same mental block. Appropriate listeners on the modal close button and another function passed to the existing marker click listener produce the desired functionality.

const closeM = document.querySelector(".close-modal");
closeM.addEventListener("click", closeMe);
var modal = document.getElementById('infoBox');

and

function modalAction(){
    modal.style.display = 'block';
}
function closeMe(){
    modal.style.display = 'none';
}


问:
Get an arbitrary key/item from a map
I am new to Go and now I want to get an arbitrary item from a map; what's the idiomatic way to do that? I can only think of something like this:

```<code>func get_some_key(m map[int]int) int {
    for k := range m {
        return k
    }
    return 0
}
</code>```

The reason I want that is I am using a map to maintain a set of jobs, and with a map I can get a pending job or remove a finished job in O(1). I guess this should be a common requirement but it's not obvious how to do it in Go.

答:
Here is a faster way I found to do this :

In my test, I created the following function

```<code>type ItemType interface{}

func getMapItemRandKey(m map[string]ItemType) string {
    return reflect.ValueOf(m).MapKeys()[0].String()
}
</code>```

The key to each map is in the following format:

```<code>b := new(big.Int)
rbytes := (some random function to generate cryptographically safe random bytes)
b.SetBytes(rbytes)

key := b.String()
m := map[string]ItemType
m[key] = &ItemType{}

</code>```

As a test, I'm getting the first key from my value as I request all keys but there is only one (... MapKeys()[0]).

This is super fast and can be adapted to any kind of map very easily.

Title: Get an arbitrary key/item from a map

Body:
I am new to Go and now I want to get an arbitrary item from a map; what's the idiomatic way to do that? I can only think of something like this:

func get_some_key(m map[int]int) int {
    for k := range m {
        return k
    }
    return 0
}

The reason I want that is I am using a map to maintain a set of jobs, and with a map I can get a pending job or remove a finished job in O(1). I guess this should be a common requirement but it's not obvious how to do it in Go.

Body:
Here is a faster way I found to do this :

In my test, I created the following function

type ItemType interface{}

func getMapItemRandKey(m map[string]ItemType) string {
    return reflect.ValueOf(m).MapKeys()[0].String()
}

The key to each map is in the following format:

b := new(big.Int)
rbytes := (some random function to generate cryptographically safe random bytes)
b.SetBytes(rbytes)

key := b.String()
m := map[string]ItemType
m[key] = &ItemType{}

As a test, I'm getting the first key from my value as I request all keys but there is only one (... MapKeys()[0]).

This is super fast and can be adapted to any kind of map very easily.


问:
How can I run a mutually exclusive COUNT in Postgres?
Say I have a (virtual) table like the following:

firstColumn
secondColumn

fcVal1
scVal1

fcVal1
scVal2

fcVal2
scVal1

fcVal3
scVal2

I want to find the following counts:

Values in firstColumn that have both scVal1 and scVal2

Values in firstColumn that have only scVal1

Values in firstColumn that have only scVal2

So the result would be:

scVals
counts

scVal1 + scVal2
1

scVal1
1

scVal2
1

Note that these counts are mutually exclusive - fcVal1 is NOT included in the counts for having only scVal1 or scVal2

Preserving which firstColumn vals are associated with the secondColumn vals is not important, just the aggregate counts.

Thanks!

答:
You can use a self join to get a 'scVal1 + scVal2'  count

```<code>select count(distinct t1.firstColumn) n12
from tbl t1
join tbl t2 on t1.firstColumn = t2.firstColumn
   and t1.secondColumn = 'scVal1' and t2.secondColumn = 'scVal2'
</code>```

Alternatively, all three counts in a row

```<code>select
   count(f1) n1,
   count(f2) n2,
   count(f1 + f2) n12
from (
  select
     max(case secondColumn when 'scVal1' then 1 end) f1,
     max(case secondColumn when 'scVal2' then 1 end) f2
  from tbl
  where secondColumn in ('scVal1', 'scVal2')
  group by firstColumn
) t
</code>```

Body:
You can use a self join to get a 'scVal1 + scVal2'  count

select count(distinct t1.firstColumn) n12
from tbl t1
join tbl t2 on t1.firstColumn = t2.firstColumn
   and t1.secondColumn = 'scVal1' and t2.secondColumn = 'scVal2'

Alternatively, all three counts in a row

select
   count(f1) n1,
   count(f2) n2,
   count(f1 + f2) n12
from (
  select
     max(case secondColumn when 'scVal1' then 1 end) f1,
     max(case secondColumn when 'scVal2' then 1 end) f2
  from tbl
  where secondColumn in ('scVal1', 'scVal2')
  group by firstColumn
) t


问:
How to access has_many through relationship possible in rails?
How can I access my related records?

```<code>class Post < ActiveRecord::Base
has_many :post_categories
has_many :categories, through: :post_categories

class Categories < ActiveRecord::Base
has_many :post_categories
has_many :post, through: :post_categories

class PostCategories < ActiveRecord::Base
belongs_to :post
belongs_to :category
</code>```

PostCategories table has id, posts_id, and categories_id columns.

```<code>id | posts_id | categories_id
1. | 2       | 3
2. | 2       | 4
</code>```

What I want is: to get posts related to a category. like: all Posts where in x category.

答:
Not sure if this answers it but in ActiveRecord your Post will have direct access to your Category model and vice versa. So you could identify the category you want the posts from in a variable or an instance variable, and query @specific_category.posts. If you are doing this in your controller, you could even do it in before_action filter. If you are using it in serializers its not much different.

You could also create a scope in your Post model and use either active record or raw SQL to query specific parameters.

You also have an error in your Category model. Has many is always plural so it would be has_many :posts, through: :post_categories

Body:
How can I access my related records?

class Post < ActiveRecord::Base
has_many :post_categories
has_many :categories, through: :post_categories

class Categories < ActiveRecord::Base
has_many :post_categories
has_many :post, through: :post_categories

class PostCategories < ActiveRecord::Base
belongs_to :post
belongs_to :category

PostCategories table has id, posts_id, and categories_id columns.

id | posts_id | categories_id
1. | 2       | 3
2. | 2       | 4

What I want is: to get posts related to a category. like: all Posts where in x category.


问:
Can't run launch in VSCode with preLaunchTask. Always opens 'Select a task to configure' after remember choice
I had a task not working. This task was being used as preLaunchTask in a launch configuration, it wasn't essential, so every time I ran the launch VSCode would prompt for which action to take.

After a while I clicked the "Remember this option" check on the prompt and selected "Configure Task" option.

Now even though the task is properly configured when I launch I'm always presented the "remembered" option...even without it failing.

I can't find any setting on VSCode that would eliminate that option.

The task works fine.
The launch without the preLaunchTask works fine.

launch.json

```<code>{
    "configurations": [

        {
            "name": "Debug Client App",
            "type": "autohotkey",
            "request": "launch",
            "program": "${cwd}/Dynokey.ahk",
            "preLaunchTask": {
                "task": "IEDebugger"
            }
        }
    ]
}
</code>```

tasks.json

```<code>{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "IEDebugger",
            "command": "C:\\Windows\\System32\\F12\\IEChooser.exe",
            "type": "shell",
            "group": "none"
        }
    ]
}
</code>```

every time I run the launch with preLaunchTask

答:
this:

```<code>          "preLaunchTask": {
                "task": "IEDebugger"
            }
</code>```

should become this:

```<code>          "preLaunchTask": "IEDebugger"
</code>```

This is the reason why it wouldn't run.

It still does not answer where can one reset the prompt choice.

Body:
I had a task not working. This task was being used as preLaunchTask in a launch configuration, it wasn't essential, so every time I ran the launch VSCode would prompt for which action to take.

After a while I clicked the "Remember this option" check on the prompt and selected "Configure Task" option.

Now even though the task is properly configured when I launch I'm always presented the "remembered" option...even without it failing.

I can't find any setting on VSCode that would eliminate that option.

The task works fine.
The launch without the preLaunchTask works fine.

launch.json

{
    "configurations": [

        {
            "name": "Debug Client App",
            "type": "autohotkey",
            "request": "launch",
            "program": "${cwd}/Dynokey.ahk",
            "preLaunchTask": {
                "task": "IEDebugger"
            }
        }
    ]
}

tasks.json

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "IEDebugger",
            "command": "C:\\Windows\\System32\\F12\\IEChooser.exe",
            "type": "shell",
            "group": "none"
        }
    ]
}

every time I run the launch with preLaunchTask

Body:
this:

          "preLaunchTask": {
                "task": "IEDebugger"
            }

should become this:

          "preLaunchTask": "IEDebugger"

This is the reason why it wouldn't run.

It still does not answer where can one reset the prompt choice.


问:
pyspark: rearrange nested array of struct sequence
I've a dataframe in this format and I would like to rearrange the fields inside item column.

root
 |-- order: string (nullable = true)
 |-- dt: struct (nullable = true)
 |-- item: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- a: long (nullable = true)
 |    |    |-- b: string (nullable = true)
 |    |    |-- c: long (nullable = true)
```
<p>So this is the desired format I'm looking for.</p>
<pre class="lang-none prettyprint-override"><code>root
 |-- order: string (nullable = true)
 |-- dt: struct (nullable = true)
 |-- item: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- a: long (nullable = true)
 |    |    |-- c: string (nullable = true)
 |    |    |-- b: long (nullable = true)
</code>```

答:
You can use transform function:

from pyspark.sql import functions as F

result = df.withColumn(
    "item",
    F.expr("transform(item, x -> struct(x.a as a, x.c as c, x.b as b))")
)
```

Body:
I've a dataframe in this format and I would like to rearrange the fields inside item column.

root
 |-- order: string (nullable = true)
 |-- dt: struct (nullable = true)
 |-- item: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- a: long (nullable = true)
 |    |    |-- b: string (nullable = true)
 |    |    |-- c: long (nullable = true)

So this is the desired format I'm looking for.

root
 |-- order: string (nullable = true)
 |-- dt: struct (nullable = true)
 |-- item: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- a: long (nullable = true)
 |    |    |-- c: string (nullable = true)
 |    |    |-- b: long (nullable = true)


问:
Change selection color for text field
I have two text fields inside of a form. When either input field is selected the outline for that field turns white. I need to change this color. How can I achieve this?</p>
```<code>input[type=text], input[type=password] {
    width: 65%;
    padding: 12px 20px;
    padding-top: 10px;
    margin: 4px 85px;
    display: inline-block;
    border: 1px solid rgba(115, 82, 122, 0.486);
    box-sizing: border-box;
    background-color: rgb(33, 33, 34);
    color:rgba(175, 149, 35, 0.836);
    font-size: 18px;
    /* border-color: rgb(63, 15, 15); */
}
</code>```

答:
In the solution below, when the focus event of the <input> elements occurs, the border style is assigned a value and the border color of the <input> element is changed.

body {
  background-color: black;
}
input[type=text], input[type=password] {
    width: 65%;
    padding: 12px 20px;
    padding-top: 10px;
    margin: 4px 85px;
    display: inline-block;
    border: 1px solid rgba(115, 82, 122, 0.486);
    box-sizing: border-box;
    background-color: rgb(33, 33, 34);
    color:rgba(175, 149, 35, 0.836);
    font-size: 18px;
}
input[type=text]:focus, input[type=password]:focus {
  outline: none !important;
  border: 1px solid red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <form>
    <input type="text">
    <input type="password">
  </form>
</body></code>```

Title: Change selection color for text field

Body:
I have two text fields inside of a form. When either input field is selected the outline for that field turns white. I need to change this color. How can I achieve this?

input[type=text], input[type=password] {
    width: 65%;
    padding: 12px 20px;
    padding-top: 10px;
    margin: 4px 85px;
    display: inline-block;
    border: 1px solid rgba(115, 82, 122, 0.486);
    box-sizing: border-box;
    background-color: rgb(33, 33, 34);
    color:rgba(175, 149, 35, 0.836);
    font-size: 18px;
    /* border-color: rgb(63, 15, 15); */
}

Body:
In the solution below, when the focus event of the <input> elements occurs, the border style is assigned a value and the border color of the <input> element is changed.

body {
  background-color: black;
}
input[type=text], input[type=password] {
    width: 65%;
    padding: 12px 20px;
    padding-top: 10px;
    margin: 4px 85px;
    display: inline-block;
    border: 1px solid rgba(115, 82, 122, 0.486);
    box-sizing: border-box;
    background-color: rgb(33, 33, 34);
    color:rgba(175, 149, 35, 0.836);
    font-size: 18px;
}
input[type=text]:focus, input[type=password]:focus {
  outline: none !important;
  border: 1px solid red;
}

<body>
  <form>
    <input type="text">
    <input type="password">
  </form>
</body>