问:
combine two different csv files and make them into one
I want to join csv1 with csv2 to result into final_csv, the schema only has String type columns (file contents are as follows):

```<code>  csv1
  emp_name   designation   salary_col
   smith        manager      40000
   john        analyst       35000
   adam       sr.engineer    50000
   eve           QA          36000
   mills      sr.manager     44000

   csv2
  emp_name   designation   advance_salary_col
   smith        manager      2000
   john        analyst       3030
   adam       sr.engineer    5044
   eve           QA          3600
   mills      sr.manager     4500

 final_csv
  emp_name   designation   salary_col   advance_salary_col
   smith        manager      40000           2000
   john        analyst       35000           3030
   adam       sr.engineer    50000           5044
   eve           QA          36000           3600
   mills      sr.manager     44000           4500
</code>```

I tried using few methods Union, Intersect, UnionByName but am getting null values for all of the columns in scala in my final_df

```<code>    val emp_dataDf1 = spark.read.format("csv")
                                 .option("header", "true")
                                 .load("data/emp_data1.csv")

    val emp_dataDf2 = spark.read.format("csv")
                                 .option("header", "true")
                                 .load("/data/emp_data2.csv")

    val final_df= emp_dataDf1.union(emp_dataDf2)
</code>```

答:
NOTE: you need to mention the separator for csv files and if you are using spaces (or any separator for that matter) make sure you use the exact string literal.

here is how you can do it:

```<code>val csv1 = spark
.read
.option("header","true")
.option("sep", " ")
.csv("your_csv1_file")

val csv2 = spark
.read
.option("header","true")
.option("sep", " ")
.csv("your_csv2_file")

val joinExpression = Seq("emp_name", "designation")
csv1.join(csv2, joinExpression, "inner").show(false)

/* output *
*
+--------+-----------+----------+------------------+
|emp_name|designation|salary_col|advance_salary_col|
+--------+-----------+----------+------------------+
|smith   |manager    |40000     |2000              |
|john    |analyst    |35000     |3030              |
|adam    |sr.engineer|50000     |5044              |
|eve     |QA         |36000     |3600              |
|mills   |sr.manager |44000     |4500              |
+--------+-----------+----------+------------------+

*/
</code>```

Body:
I want to join csv1 with csv2 to result into final_csv, the schema only has String type columns (file contents are as follows):

  csv1
  emp_name   designation   salary_col
   smith        manager      40000
   john        analyst       35000
   adam       sr.engineer    50000
   eve           QA          36000
   mills      sr.manager     44000

   csv2
  emp_name   designation   advance_salary_col
   smith        manager      2000
   john        analyst       3030
   adam       sr.engineer    5044
   eve           QA          3600
   mills      sr.manager     4500

 final_csv
  emp_name   designation   salary_col   advance_salary_col
   smith        manager      40000           2000
   john        analyst       35000           3030
   adam       sr.engineer    50000           5044
   eve           QA          36000           3600
   mills      sr.manager     44000           4500

I tried using few methods Union, Intersect, UnionByName but am getting null values for all of the columns in scala in my final_df

    val emp_dataDf1 = spark.read.format("csv")
                                 .option("header", "true")
                                 .load("data/emp_data1.csv")

    val emp_dataDf2 = spark.read.format("csv")
                                 .option("header", "true")
                                 .load("/data/emp_data2.csv")

    val final_df= emp_dataDf1.union(emp_dataDf2)

Body:
NOTE: you need to mention the separator for csv files and if you are using spaces (or any separator for that matter) make sure you use the exact string literal.

here is how you can do it:

val csv1 = spark
.read
.option("header","true")
.option("sep", " ")
.csv("your_csv1_file")

val csv2 = spark
.read
.option("header","true")
.option("sep", " ")
.csv("your_csv2_file")

val joinExpression = Seq("emp_name", "designation")
csv1.join(csv2, joinExpression, "inner").show(false)

/* output *
*
+--------+-----------+----------+------------------+
|emp_name|designation|salary_col|advance_salary_col|
+--------+-----------+----------+------------------+
|smith   |manager    |40000     |2000              |
|john    |analyst    |35000     |3030              |
|adam    |sr.engineer|50000     |5044              |
|eve     |QA         |36000     |3600              |
|mills   |sr.manager |44000     |4500              |
+--------+-----------+----------+------------------+

*/


来源: stackexchange

问:
PHP Print statement works only in Firefox
The site is built in drupal. The following code calls some data for the page:

```<code><span class="bold caps">Length: </span><?php print $node->field_length[0]['view'];?>
</code>```

The right information shows up when viewing the page in Firefox but that's it. Chrome, IE & Safari are all missing the info. The rendered HTML is fine but for the lack of the right data coming through.

Here is a link to the page in question

Any ideas?

答:
This is a server-side thing, not a client side. It SHOULD show in all browsers

1) Check the page source of Firefox and Opera/Safari/Chrome - the string might exist in all of them but due to rendering engine differences only show up in Firefox - then it's CSS/HTML issue

2) I don't see it in Firefox 6 (even in the source). I suspect it might be a SESSION thing. For example $node->field_length[0]['view'] is empty if you are missing something in your browser session. So for example you have active session with Firefox but because you haven't logged in with the other browsers - it doesn't show up.

Those are just guesses, without seeing more server side code.

ContentLicense: CC BY-SA 3.0

Body:
The site is built in drupal. The following code calls some data for the page:

Length: <?php print $node->field_length[0]['view'];?>

The right information shows up when viewing the page in Firefox but that's it. Chrome, IE & Safari are all missing the info. The rendered HTML is fine but for the lack of the right data coming through.

Here is a link to the page in question

Any ideas?


问:
Java Nested loops: Indent text
Can anybody help me solve this problem?

Print numbers 0, 1, 2, ..., userNum as shown, with each number indented by that number of spaces. For each printed line, print the leading spaces, then the number, and then a newline. Hint: Use i and j as loop variables (initialize i and j explicitly). Note: Avoid any other spaces like spaces after the printed number. Ex: userNum = 3 prints:

The code given is as follows:

```<code>public class NestedLoop {

public static void main (String [] args) {

  int userNum  = 0;
  int i = 0;
  int j = 0;

  /* Your solution goes here  */

  return;
}
}
</code>```

Any suggestions would be appreciated. Thank you.

答:
This was successful when I input it in my zyBook assignment!

```<code>#include <stdio.h>

int main(void) {
    int userNum;
    int i;
    int j;

    scanf("%d", &userNum);

    for (i=0; i<=userNum; i++){
       for (j=0; j<i; j++){
          printf(" ");
       }
       printf("%d\n", i);
    }

    return 0;
}
</code>```

Title: Java Nested loops: Indent text

Body:
Can anybody help me solve this problem?

Print numbers 0, 1, 2, ..., userNum as shown, with each number indented by that number of spaces. For each printed line, print the leading spaces, then the number, and then a newline. Hint: Use i and j as loop variables (initialize i and j explicitly). Note: Avoid any other spaces like spaces after the printed number. Ex: userNum = 3 prints:

The code given is as follows:

public class NestedLoop {

public static void main (String [] args) {

  int userNum  = 0;
  int i = 0;
  int j = 0;

  /* Your solution goes here  */

  return;
}
}

Any suggestions would be appreciated. Thank you.

Body:
This was successful when I input it in my zyBook assignment!

#include <stdio.h>

int main(void) {
    int userNum;
    int i;
    int j;

    scanf("%d", &userNum);

    for (i=0; i<=userNum; i++){
       for (j=0; j<i; j++){
          printf(" ");
       }
       printf("%d\n", i);
    }

    return 0;
}

ContentLicense: CC BY-SA 4.0


问:
flask-migrate doesn't detect models
I am reading (and watching) about Flask-Migrate here:
https://realpython.com/blog/python/flask-by-example-part-2-postgres-sqlalchemy-and-alembic/
and here https://www.youtube.com/watch?v=YJibNSI-iaE#t=21

and doing everything from this tutorial:

I started a local postgres server (using Postgres.App, which started the server at postgresql://localhost:5432)

updated configs as per said tutorial

updated app.py, created a models.py etc.

After you install Flask-Migrate and run

```<code>python manage.py db init
python manage.py db migrate
</code>```

it should detect all tables declared in models.py.

In my case, it detects nothing. And, based on the comments to the tutorial, it's not just my case.
So, how do I make this work?

答:
If Flask can't detect your models, add this to env.py in migrations folder:
from models import *

Title: flask-migrate doesn't detect models

Body:
I am reading (and watching) about Flask-Migrate here:
https://realpython.com/blog/python/flask-by-example-part-2-postgres-sqlalchemy-and-alembic/
and here https://www.youtube.com/watch?v=YJibNSI-iaE#t=21

and doing everything from this tutorial:

I started a local postgres server (using Postgres.App, which started the server at postgresql://localhost:5432)

updated configs as per said tutorial

updated app.py, created a models.py etc.

After you install Flask-Migrate and run

python manage.py db init
python manage.py db migrate

it should detect all tables declared in models.py.

In my case, it detects nothing. And, based on the comments to the tutorial, it's not just my case.
So, how do I make this work?


问:
How to write a simple CMAKELISTS for OpenViNO to my C++ programme in Linux
I have been trying very hard to set up OpenVINO for my C++ programme. But the official guide was very unclear to me (partially because I am a very beginner). I was struggling to understand how it finds "InferenceEngine_LIBRARIES" (or "OpenCV_LIBS") without even defining it.

I have tried to understand some examples in GitHub but sadly many of them are for older versions. I was wondering if I could have a minimum demo of the CMakeLists.txt to use the OpenVINO. Thank you very much.

--- Updates ---

Thanks for the comments. I understand some things were handled by CMake behind the scene. Going to the point, here is my CMakeLists file

```<code>cmake_minimum_required(VERSION 3.21)
project(openvino)
set(CMAKE_CXX_STANDARD 14)

# OpenVINO
set(ngraph_DIR "/opt/intel/openvino_2021/deployment_tools/ngraph/cmake")
find_package(ngraph REQUIRED)
set(InferenceEngine_DIR "/opt/intel/openvino_2021/deployment_tools/inference_engine/share")
find_package(InferenceEngine REQUIRED)
set(OpenCV_DIR "/opt/intel/openvino_2021/opencv/cmake")
find_package(OpenCV REQUIRED)

add_executable(openvino main.cpp)
target_link_libraries(
    ${PROJECT_NAME}
    PRIVATE ${InferenceEngine_LIBRARIES}
    ${OpenCV_LIBS}
    ${NGRAPH_LIBRARIES})
</code>```

And my "main.cpp" is just

```<code>#include <inference_engine.hpp>
int main() {
    InferenceEngine::Core core;
    InferenceEngine::ExecutableNetwork executable_network;
    executable_network = core.LoadNetwork("./models/decoder.xml", "CPU");
    auto infer_request = executable_network.CreateInferRequest();
    return 0;
}
</code>```

But When I build it, I got the following error, and I would like to ask for any help. Thank you very much!

```<code>====================[ Build | openvino | Debug ]================================
/home/kent/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/213.6777.58/bin/cmake/linux/bin/cmake --build /media/kent/DISK2/CLionProjects/openvino/cmake-build-debug --target openvino
[2/2] Linking CXX executable openvino
FAILED: openvino
: && /usr/bin/c++ -g  CMakeFiles/openvino.dir/main.cpp.o -o openvino  -Wl,-rpath,/opt/intel/openvino_2021/opencv/lib:/opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64:/opt/intel/openvino_2021/deployment_tools/ngraph/lib  /opt/intel/openvino_2021/opencv/lib/libopencv_gapi.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_highgui.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_ml.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_objdetect.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_photo.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_stitching.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_video.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_videoio.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_dnn.so.4.5.3  /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so  /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine_c_api.so  /opt/intel/openvino_2021/deployment_tools/ngraph/lib/libngraph.so  /opt/intel/openvino_2021/opencv/lib/libopencv_imgcodecs.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_calib3d.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_features2d.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_flann.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_imgproc.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_core.so.4.5.3 && :
/usr/bin/ld: warning: libtbb.so.2, needed by /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so, not found (try using -rpath or -rpath-link)
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::interface7::internal::task_arena_base::internal_max_concurrency(tbb::interface7::task_arena const*)'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::interface7::internal::task_arena_base::internal_initialize()'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::internal::task_scheduler_observer_v3::observe(bool)'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::internal::concurrent_vector_base_v3::internal_grow_by(unsigned long, unsigned long, void (*)(void*, void const*, unsigned long), void const*)'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::internal::concurrent_vector_base_v3::~concurrent_vector_base_v3()'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::internal::NFS_Allocate(unsigned long, unsigned long, void*)'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::internal::concurrent_vector_base_v3::internal_clear(void (*)(void*, unsigned long))'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::interface7::internal::task_arena_base::internal_current_slot()'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::internal::allocate_via_handler_v3(unsigned long)'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::interface7::internal::task_arena_base::internal_execute(tbb::interface7::internal::delegate_base&) const'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::interface7::internal::task_arena_base::internal_terminate()'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::internal::NFS_Free(void*)'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::internal::thread_get_id_v3()'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::internal::deallocate_via_handler_v3(void*)'
collect2: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.
</code>```

答:
The linker error shows that it cannot find the TBB symbols. The TBB library should be pointed to by the TBB_DIR variable. You don't have to set those variables manually using cmake's set() function. Instead - in the shell where you compile your own app - you can source OpenVINO's setupvars.sh script. Just run something like: source /opt/intel/openvino_2021/bin/setupvars.sh and re-run the compiler.
I can see you're using CLion, not the terminal directly. In that case you can try adding the variable manually. The TBB location might be slightly different between the OV versions but in general it should point to a subdirectory of /opt/intel/openvino_2021 - just browse the installation directory and try to find it or source setupvars.sh in the terminal and copy the TBB_DIR env var value to your IDE.

Body:
I have been trying very hard to set up OpenVINO for my C++ programme. But the official guide was very unclear to me (partially because I am a very beginner). I was struggling to understand how it finds "InferenceEngine_LIBRARIES" (or "OpenCV_LIBS") without even defining it.

I have tried to understand some examples in GitHub but sadly many of them are for older versions. I was wondering if I could have a minimum demo of the CMakeLists.txt to use the OpenVINO. Thank you very much.

--- Updates ---

Thanks for the comments. I understand some things were handled by CMake behind the scene. Going to the point, here is my CMakeLists file

cmake_minimum_required(VERSION 3.21)
project(openvino)
set(CMAKE_CXX_STANDARD 14)

# OpenVINO
set(ngraph_DIR "/opt/intel/openvino_2021/deployment_tools/ngraph/cmake")
find_package(ngraph REQUIRED)
set(InferenceEngine_DIR "/opt/intel/openvino_2021/deployment_tools/inference_engine/share")
find_package(InferenceEngine REQUIRED)
set(OpenCV_DIR "/opt/intel/openvino_2021/opencv/cmake")
find_package(OpenCV REQUIRED)

add_executable(openvino main.cpp)
target_link_libraries(
    ${PROJECT_NAME}
    PRIVATE ${InferenceEngine_LIBRARIES}
    ${OpenCV_LIBS}
    ${NGRAPH_LIBRARIES})

And my "main.cpp" is just

#include <inference_engine.hpp>
int main() {
    InferenceEngine::Core core;
    InferenceEngine::ExecutableNetwork executable_network;
    executable_network = core.LoadNetwork("./models/decoder.xml", "CPU");
    auto infer_request = executable_network.CreateInferRequest();
    return 0;
}

But When I build it, I got the following error, and I would like to ask for any help. Thank you very much!

====================[ Build | openvino | Debug ]================================
/home/kent/.local/share/JetBrains/Toolbox/apps/CLion/ch-0/213.6777.58/bin/cmake/linux/bin/cmake --build /media/kent/DISK2/CLionProjects/openvino/cmake-build-debug --target openvino
[2/2] Linking CXX executable openvino
FAILED: openvino
: && /usr/bin/c++ -g  CMakeFiles/openvino.dir/main.cpp.o -o openvino  -Wl,-rpath,/opt/intel/openvino_2021/opencv/lib:/opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64:/opt/intel/openvino_2021/deployment_tools/ngraph/lib  /opt/intel/openvino_2021/opencv/lib/libopencv_gapi.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_highgui.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_ml.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_objdetect.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_photo.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_stitching.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_video.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_videoio.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_dnn.so.4.5.3  /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so  /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine_c_api.so  /opt/intel/openvino_2021/deployment_tools/ngraph/lib/libngraph.so  /opt/intel/openvino_2021/opencv/lib/libopencv_imgcodecs.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_calib3d.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_features2d.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_flann.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_imgproc.so.4.5.3  /opt/intel/openvino_2021/opencv/lib/libopencv_core.so.4.5.3 && :
/usr/bin/ld: warning: libtbb.so.2, needed by /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so, not found (try using -rpath or -rpath-link)
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::interface7::internal::task_arena_base::internal_max_concurrency(tbb::interface7::task_arena const*)'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::interface7::internal::task_arena_base::internal_initialize()'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::internal::task_scheduler_observer_v3::observe(bool)'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::internal::concurrent_vector_base_v3::internal_grow_by(unsigned long, unsigned long, void (*)(void*, void const*, unsigned long), void const*)'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::internal::concurrent_vector_base_v3::~concurrent_vector_base_v3()'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::internal::NFS_Allocate(unsigned long, unsigned long, void*)'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::internal::concurrent_vector_base_v3::internal_clear(void (*)(void*, unsigned long))'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::interface7::internal::task_arena_base::internal_current_slot()'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::internal::allocate_via_handler_v3(unsigned long)'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::interface7::internal::task_arena_base::internal_execute(tbb::interface7::internal::delegate_base&) const'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::interface7::internal::task_arena_base::internal_terminate()'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::internal::NFS_Free(void*)'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::internal::thread_get_id_v3()'
/usr/bin/ld: /opt/intel/openvino_2021/deployment_tools/inference_engine/lib/intel64/libinference_engine.so: undefined reference to `tbb::internal::deallocate_via_handler_v3(void*)'
collect2: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.


问:
Clicking on part of an image
I'm sorry if this has been asked before, I tried to search and didn't find anything.

I am creating a C# WPF application.

I have an image, for example of a man.

Is there a way to detect which part of the man's body the mouse has clicked? for example if the mouse clicks his hand we get a message box : "You have clicked the hand"?

I would like to divide the into random shapes not just rectangles, so the mouse click have to be precise.

Thanks a lot for any help

答: You could crop the image into separate pieces and then load them into the window as if it was a complete image. It's not the most effective way, and it only works for static images (a flash video would be perfect for animated "images"), but it can be implemented quickly and easily. If you were to use HTML, the window would have to use the web browser toolbox item (unless you code your own somehow).</p>

Title: Clicking on part of an image


问:
Deeplink empty String Argument
I'm using the Jetpack Navigation as a navigation solution in my app.

I'm facing an inconsistent behaviour when using the generated safe args as opposed to the deeplink strategy.

Say I have following navigation graph:

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    app:startDestination="@+id/home_dest">

    <fragment
        android:id="@+id/home_dest"
        android:name="com.example.android.codelabs.navigation.HomeFragment"
        android:label="@string/home"
        tools:layout="@layout/home_fragment" >
        <action
            android:id="@+id/action_home_dest_to_deeplink_dest"
            app:destination="@id/deeplink_dest" />
    </fragment>

    <fragment
        android:id="@+id/deeplink_dest"
        android:name="com.example.android.codelabs.navigation.DeepLinkFragment"
        android:label="@string/deeplink"
        tools:layout="@layout/deeplink_fragment">

        <argument
            android:name="myarg"
            app:argType="string" />

        <deepLink app:uri="example://my-deelink-frag?myArg={myarg}" />
    </fragment>
</navigation>
```
<p>I have defined 2 ways to navigate to the <code>DeepLinkFragment</code>:</p>
<ul>
<li>Navigation action with id <code>action_home_dest_to_deeplink_dest</code></li>
<li>A deeplink <code>example://my-deelink-frag?myArg={myarg}</code></li>
</ul>
<p>In the <code>DeepLinkFragment</code> I'm using the <code>navArgs()</code> function to de-serialize the incoming <code>Bundle</code> and show a simple <code>Toast</code> message.</p>
<pre class="lang-kotlin prettyprint-override"><code>class DeepLinkFragment : Fragment() {

    private val args : DeepLinkFragmentArgs by navArgs()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Toast.makeText(requireContext(), args.myarg, Toast.LENGTH_SHORT).show()
    }
}
</code>```

When navigating with the generated safe args I can sent an empty string as the value for myArg.
No problem.

findNavController().navigate(HomeFragmentDirections.actionHomeDestToDeeplinkDest(""))
```
<p>However, when navigating with an empty string as argument via the deeplink way:</p>
<pre class="lang-kotlin prettyprint-override"><code>val arg = ""
findNavController().navigate("example://my-deelink-frag?myArg=${arg}".toUri())
</code>```

I get following stacktrace:

```<code> Caused by: java.lang.IllegalArgumentException: Required argument "myarg" is missing and does not have an android:defaultValue
    at com.example.android.codelabs.navigation.DeepLinkFragmentArgs$Companion.fromBundle(DeepLinkFragmentArgs.kt:29)
    at com.example.android.codelabs.navigation.DeepLinkFragmentArgs.fromBundle(Unknown Source:2)
    at java.lang.reflect.Method.invoke(Native Method)
    at androidx.navigation.NavArgsLazy.getValue(NavArgsLazy.kt:52)
    at androidx.navigation.NavArgsLazy.getValue(NavArgsLazy.kt:34)
    at com.example.android.codelabs.navigation.DeepLinkFragment.getArgs(DeepLinkFragment.kt:30)
    at com.example.android.codelabs.navigation.DeepLinkFragment.onViewCreated(DeepLinkFragment.kt:34)
    at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:2987)
    at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:546)
    at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282)
    at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
    at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2106)
    at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002)
    at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:524)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:233)
    at android.app.ActivityThread.main(ActivityThread.java:8068)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:631)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:978)
</code>```

Which is coming from the generated DeeplinkFragmentArgs code

public data class DeepLinkFragmentArgs(
  public val myarg: String = ""
) : NavArgs {
  public fun toBundle(): Bundle {
    val result = Bundle()
    result.putString("myarg", this.myarg)
    return result
  }

  public companion object {
    @JvmStatic
    public fun fromBundle(bundle: Bundle): DeepLinkFragmentArgs {
      bundle.setClassLoader(DeepLinkFragmentArgs::class.java.classLoader)
      val __myarg : String?
      if (bundle.containsKey("myarg")) {
        __myarg = bundle.getString("myarg")
        if (__myarg == null) {
          throw IllegalArgumentException("Argument \"myarg\" is marked as non-null but was passed a null value.")
        }
      } else {
        __myarg = ""
      }
      return DeepLinkFragmentArgs(__myarg)
    }
  }
}
```
<blockquote>
<p>Looking at the code it seems as if an empty string is making the <code>bundle.getString("myarg")</code> return <code>null</code> instead of the empty string?!</p>
</blockquote>
<p>As a <em>fix</em> I could add the <code>android:defaultValue</code>.<br />
However I don't think is the right solution.</p>
<pre class="lang-xml prettyprint-override"><code><argument
    android:name="myarg"
    android:defaultValue=""
    app:argType="string" />
</code>```

Is this a known limitation when using deeplinks?

答:
Not sure if this fully answers your question, but what you've done all looks correct. Some related notes below based on my own experience.

INTERNAL LINKS

I would maybe use SafeArgs for navigation internal to the app, or just call findNavController.navigate as in this code of mine. Personally I'm not a big fan of more Android XML markup.

EXTERNAL LINKS

If you want links to work from sources such as emails then the deep link option is the best fit, but you will also then need to validate input. As you seem to indicate, an empty default value on its own may not be sufficient.

So before using DeepLinkFragmentArgs I would ensure that you get the desired control. Eg in the past I have sometimes found it useful to do validation before allowing navigation to proceed - eg to receive deep links first in a Forwarder Activity. This meant I could prevent deep links from executing while a Chrome Custom Tab is topmost (since this caused problems such as recreating the main activity).

MOBILE DEEP LINKS

Incidentally I've found that custom URI scheme deep links may not be allowed by email clients such as gmail, so my sample uses Android https applinks, just in case that is of any interest to you.

Title: Deeplink empty String Argument

Body:
I'm using the Jetpack Navigation as a navigation solution in my app.

I'm facing an inconsistent behaviour when using the generated safe args as opposed to the deeplink strategy.

Say I have following navigation graph:

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    app:startDestination="@+id/home_dest">

    <fragment
        android:id="@+id/home_dest"
        android:name="com.example.android.codelabs.navigation.HomeFragment"
        android:label="@string/home"
        tools:layout="@layout/home_fragment" >
        <action
            android:id="@+id/action_home_dest_to_deeplink_dest"
            app:destination="@id/deeplink_dest" />
    </fragment>

    <fragment
        android:id="@+id/deeplink_dest"
        android:name="com.example.android.codelabs.navigation.DeepLinkFragment"
        android:label="@string/deeplink"
        tools:layout="@layout/deeplink_fragment">

        <argument
            android:name="myarg"
            app:argType="string" />

        <deepLink app:uri="example://my-deelink-frag?myArg={myarg}" />
    </fragment>
</navigation>

I have defined 2 ways to navigate to the DeepLinkFragment:

Navigation action with id action_home_dest_to_deeplink_dest

A deeplink example://my-deelink-frag?myArg={myarg}

In the DeepLinkFragment I'm using the navArgs() function to de-serialize the incoming Bundle and show a simple Toast message.

class DeepLinkFragment : Fragment() {

    private val args : DeepLinkFragmentArgs by navArgs()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Toast.makeText(requireContext(), args.myarg, Toast.LENGTH_SHORT).show()
    }
}

When navigating with the generated safe args I can sent an empty string as the value for myArg.
No problem.

findNavController().navigate(HomeFragmentDirections.actionHomeDestToDeeplinkDest(""))

However, when navigating with an empty string as argument via the deeplink way:

val arg = ""
findNavController().navigate("example://my-deelink-frag?myArg=${arg}".toUri())

I get following stacktrace:

 Caused by: java.lang.IllegalArgumentException: Required argument "myarg" is missing and does not have an android:defaultValue
    at com.example.android.codelabs.navigation.DeepLinkFragmentArgs$Companion.fromBundle(DeepLinkFragmentArgs.kt:29)
    at com.example.android.codelabs.navigation.DeepLinkFragmentArgs.fromBundle(Unknown Source:2)
    at java.lang.reflect.Method.invoke(Native Method)
    at androidx.navigation.NavArgsLazy.getValue(NavArgsLazy.kt:52)
    at androidx.navigation.NavArgsLazy.getValue(NavArgsLazy.kt:34)
    at com.example.android.codelabs.navigation.DeepLinkFragment.getArgs(DeepLinkFragment.kt:30)
    at com.example.android.codelabs.navigation.DeepLinkFragment.onViewCreated(DeepLinkFragment.kt:34)
    at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:2987)
    at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:546)
    at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282)
    at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
    at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2106)
    at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002)
    at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:524)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:233)
    at android.app.ActivityThread.main(ActivityThread.java:8068)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:631)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:978)

Which is coming from the generated DeeplinkFragmentArgs code

public data class DeepLinkFragmentArgs(
  public val myarg: String = ""
) : NavArgs {
  public fun toBundle(): Bundle {
    val result = Bundle()
    result.putString("myarg", this.myarg)
    return result
  }

  public companion object {
    @JvmStatic
    public fun fromBundle(bundle: Bundle): DeepLinkFragmentArgs {
      bundle.setClassLoader(DeepLinkFragmentArgs::class.java.classLoader)
      val __myarg : String?
      if (bundle.containsKey("myarg")) {
        __myarg = bundle.getString("myarg")
        if (__myarg == null) {
          throw IllegalArgumentException("Argument \"myarg\" is marked as non-null but was passed a null value.")
        }
      } else {
        __myarg = ""
      }
      return DeepLinkFragmentArgs(__myarg)
    }
  }
}

Looking at the code it seems as if an empty string is making the bundle.getString("myarg") return null instead of the empty string?!

As a fix I could add the android:defaultValue.

However I don't think is the right solution.

<argument
    android:name="myarg"
    android:defaultValue=""
    app:argType="string" />

Is this a known limitation when using deeplinks?


问:
EF Core add/save by Id OR entity reference
I have an entity I'm initiating to be saved as a record via EF Core code-first.

Sometimes I will have the related entity model - usually when I'm creating a new related entity at the same time, so it won't have an Id yet.

But sometimes I will only have the ForeignKey Id of the related entity, particularly when I'm adding just this new record related to an existing record.

I haven't been able to find anything on this specific dual-create-mode pattern, is this the correct convention in this situation?

```<code>public class ClownModel {
    public ClownModel (){}
    public ClownModel (CarModel car){
        Car = car;
    }
    public Clown (int carId){
        CarId = carId;
    }

    public int Id {get;set;}
    public int? CarId {get;set;}
    [ForeignKey("CarId")]
    public CarModel Car {get;set;} = null!;
}
</code>```

My thought is that the FK can be nullable on the entity, so when it's also creating a new related entity it will be assigned during the save?

答:
Long story short, all your reasonable expectations will be met:

If you create a new Clown and assign CarId=1, then EF will assume you know what car you wanted to assign even if it's never seen Car 1 be downloaded before; it will create a Clown with CarId 1. If you have a relationship DB side then Car 1 will need to exist otherwise the DB will reject it

If you create a new Clown and a new Car assigned to its Car property, and that new car has the default value for its CarId, the EF will save the Car first, retrieve the ID and wire it into the Clown before the Clown is saved so that the relationship is satisfied on the DB side

Don't create a new Clown with a new Car that has a CarId that already exists; EF will try to insert a new Car (because it knows the entity is new) with the given ID rather than leaving the DB to create oen, which would probably result in a "cannot insert PK value to a table with IDENTITY_INSERT OFF" type error. If yo uknow the Car Id, use Route 1 above and just assign it to the Clown.CarId

Body:
I have an entity I'm initiating to be saved as a record via EF Core code-first.

Sometimes I will have the related entity model - usually when I'm creating a new related entity at the same time, so it won't have an Id yet.

But sometimes I will only have the ForeignKey Id of the related entity, particularly when I'm adding just this new record related to an existing record.

I haven't been able to find anything on this specific dual-create-mode pattern, is this the correct convention in this situation?

public class ClownModel {
    public ClownModel (){}
    public ClownModel (CarModel car){
        Car = car;
    }
    public Clown (int carId){
        CarId = carId;
    }

    public int Id {get;set;}
    public int? CarId {get;set;}
    [ForeignKey("CarId")]
    public CarModel Car {get;set;} = null!;
}

My thought is that the FK can be nullable on the entity, so when it's also creating a new related entity it will be assigned during the save?


问:
spread operator for object containing readonly
My sample class:

class Foo {
  private static counter = 1;

  readonly id: number;

  constructor() {
    this.id = Foo.counter++;
  }
}
```

I'm having 2 options:

Make the constructor accepts another Foo, so that I can clone using new Foo(foo)

Make id public, so that I can clone using { ...foo }

Is there anyway to use spread clone AND keep readonly (or anything that prevents id from being modified from outside)?

答:
Is there anyway to use spread clone AND keep readonly...

No. The result of { ...foo } is a plain object with read/write public data properties for the own, enumerable properties of foo. There's nothing you can add to your class to change that behavior.

Also note that because  { ...foo } creates a plain object, it will no longer be an instance of Foo. If Foo defined any methods, for instance, the clone wouldn't have them. (In the code in the question, that kind of clone would be assignment-compatible with Foo because it doesn't define any methods. But if Foo had methods, it wouldn't be.)

If you want to use spread syntax (it's not an operator) to clone objects, don't use class, use interface since the clones won't inherit from the prototype the class will assign.

In this case, as you said, you can make Foo's constructor optionally a copy-constructor:

```<code>class Foo {
    private static counter = 1;

    readonly id: number;

    constructor(other?: Foo) {
        if (other) {
            // Copying
            this.id = other.id; // Just to make TypeScript happy that `id` is
                                // definitely assigned on this path (it would be
                                // anyway, but TypeScript doesn't know that)
            Object.assign(this, other);
        } else {
            // Creating a new one
            this.id = Foo.counter++;
        }
    }
}
</code>```

(Instead of the this.id = other.id; line, we could have marked id with the "definitely assigned" annotation [readonly id!: number;]. But since there are multiple paths through the constructor, I wouldn't do that, because it's too easy to forget about it when modifying the code. So I'd use the unnecessary assignment above.)

Body:
My sample class:

class Foo {
  private static counter = 1;

  readonly id: number;

  constructor() {
    this.id = Foo.counter++;
  }
}

I'm having 2 options:

Make the constructor accepts another Foo, so that I can clone using new Foo(foo)

Make id public, so that I can clone using { ...foo }

Is there anyway to use spread clone AND keep readonly (or anything that prevents id from being modified from outside)?

Body:
Is there anyway to use spread clone AND keep readonly...

No. The result of { ...foo } is a plain object with read/write public data properties for the own, enumerable properties of foo. There's nothing you can add to your class to change that behavior.

Also note that because  { ...foo } creates a plain object, it will no longer be an instance of Foo. If Foo defined any methods, for instance, the clone wouldn't have them. (In the code in the question, that kind of clone would be assignment-compatible with Foo because it doesn't define any methods. But if Foo had methods, it wouldn't be.)

If you want to use spread syntax (it's not an operator) to clone objects, don't use class, use interface since the clones won't inherit from the prototype the class will assign.

In this case, as you said, you can make Foo's constructor optionally a copy-constructor:

class Foo {
    private static counter = 1;

    readonly id: number;

    constructor(other?: Foo) {
        if (other) {
            // Copying
            this.id = other.id; // Just to make TypeScript happy that `id` is
                                // definitely assigned on this path (it would be
                                // anyway, but TypeScript doesn't know that)
            Object.assign(this, other);
        } else {
            // Creating a new one
            this.id = Foo.counter++;
        }
    }
}

(Instead of the this.id = other.id; line, we could have marked id with the "definitely assigned" annotation [readonly id!: number;]. But since there are multiple paths through the constructor, I wouldn't do that, because it's too easy to forget about it when modifying the code. So I'd use the unnecessary assignment above.)


问:
Why is calling file write() method not working?
I have some Python3 code that opens a file in write mode, writes something to it, and then closes the file. The filename is an int. For some reason, the code doesn't work as expected. When I run the f.write() statement, a 6 is printed to the screen. And when I run the f.close() statement, the string that was supposed to be written is printed to the screen.

```<code>>>> f = open(2, 'w')
>>> f.write('FooBar')
6
>>> f.close()
FooBar>>>
>>>
</code>```

I checked the directory that I ran this in and the file (named 2) was not created. Can anyone explain what is going on? I suspect it has to do with the filename being an int, but I'm not sure.

答:
You're passing in a file descriptor number (2 for stderr).

See the documentation for open(), emphasis mine:

file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped.

As to why nothing happens before .close() (or .flush(): Your stream is line buffered, and you're not writing a newline.

```<code>f = open(2, 'wb', buffering=0)
</code>```

to disable buffering.

If you wish to write to a file called '2', you must pass a string.

```<code>f = open('2', 'w')
</code>```

Body:
I have some Python3 code that opens a file in write mode, writes something to it, and then closes the file. The filename is an int. For some reason, the code doesn't work as expected. When I run the f.write() statement, a 6 is printed to the screen. And when I run the f.close() statement, the string that was supposed to be written is printed to the screen.

>>> f = open(2, 'w')
>>> f.write('FooBar')
6
>>> f.close()
FooBar>>>
>>>

I checked the directory that I ran this in and the file (named 2) was not created. Can anyone explain what is going on? I suspect it has to do with the filename being an int, but I'm not sure.

Body:
You're passing in a file descriptor number (2 for stderr).

See the documentation for open(), emphasis mine:

file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped.

As to why nothing happens before .close() (or .flush(): Your stream is line buffered, and you're not writing a newline.

f = open(2, 'wb', buffering=0)

to disable buffering.

If you wish to write to a file called '2', you must pass a string.

f = open('2', 'w')


问:
How to get data from model fields in django?
I made a patient register form. I added two patient to database. And i wanna save each patient informations to text file. And i wanna make all txt file is uniqe name. So i am using this code for save txt file;

file_name must be each patient name, and i am having problem in this line... I didnt filter or pull data from model

```<code>def deneme(request):

    dir_path = Path('/Users/emr/Desktop/ngsaglik/homeo/patient/templates/kayitlar')
    file_name = str(Post.objects.get(???)) # i wanna pull each patient name as a txt file name

    f = open (dir_path.joinpath(file_name),'w')
    testfile = File(f)

    kayitlar = Post.objects.all()
    lines = []
    for kayit in kayitlar:
        lines.append(f'{kayit.soru1}\n{kayit.soru2}\n')

    testfile.write(str(lines))
    testfile.close
    f.close
    return HttpResponse()
</code>```

my models.py

```<code>from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
#from datetime import datetime, date

class Post(models.Model):

    name = models.CharField(verbose_name='Ad Soyad',max_length=10000, default="")
    surname = models.CharField(verbose_name='Tarih', max_length=10000, default="")
    soru3 = models.CharField(verbose_name='Doğum Tarihi', max_length=10000, default="")
    soru4 = models.CharField(verbose_name='Doğum Yeri', max_length=10000, default="")
    soru5 = models.CharField(verbose_name='Medeni Hali', max_length=10000, default="")
</code>```

答:
Iterate through all Post objects, and create a new file for each of them.

def deneme(request):

    dir_path = Path('/Users/emr/Desktop/ngsaglik/homeo/patient/templates/kayitlar')

    kayitlar = Post.objects.all()

    for kayit in kayitlar:

        file_name = str(kayit.name)
        f = open (dir_path.joinpath(file_name),'w')

        testfile = File(f)

        lines = []
        lines.append(f'{kayit.soru1}\n{kayit.soru2}\n')

        testfile.write(str(lines))
        testfile.close
        f.close

    return HttpResponse()
```

Body:
I made a patient register form. I added two patient to database. And i wanna save each patient informations to text file. And i wanna make all txt file is uniqe name. So i am using this code for save txt file;

file_name must be each patient name, and i am having problem in this line... I didnt filter or pull data from model

def deneme(request):

    dir_path = Path('/Users/emr/Desktop/ngsaglik/homeo/patient/templates/kayitlar')
    file_name = str(Post.objects.get(???)) # i wanna pull each patient name as a txt file name

    f = open (dir_path.joinpath(file_name),'w')
    testfile = File(f)

    kayitlar = Post.objects.all()
    lines = []
    for kayit in kayitlar:
        lines.append(f'{kayit.soru1}\n{kayit.soru2}\n')

    testfile.write(str(lines))
    testfile.close
    f.close
    return HttpResponse()

my models.py

from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
#from datetime import datetime, date

class Post(models.Model):

    name = models.CharField(verbose_name='Ad Soyad',max_length=10000, default="")
    surname = models.CharField(verbose_name='Tarih', max_length=10000, default="")
    soru3 = models.CharField(verbose_name='Doğum Tarihi', max_length=10000, default="")
    soru4 = models.CharField(verbose_name='Doğum Yeri', max_length=10000, default="")
    soru5 = models.CharField(verbose_name='Medeni Hali', max_length=10000, default="")


问:
How to include short signals in a Long only strategy on tradingview?
How to include short signals in a Long only strategy on tradingview?

I have a Tradingview strategy which gives only long/Buy signals as per matching conditions. I also need it to generate short signals when the conditions are suitable. How do I do it?

```<code>strategy("Varun scalp", shorttitle="Varun scalp", overlay=true)
timeframe = input('3')
box = input('Traditional')
boxsize = input(5, type=float)
reversal = input(1)
pnf = pointfigure(tickerid, 'close', box, boxsize, reversal)
pnf_open= security(pnf, timeframe , open)
pnf_close= security(pnf, timeframe , close)
p1 = plot(pnf_open, title="pnf_open", color=green)
p2 = plot(pnf_close,  title="pnf_close",color=maroon)
base = pnf_close> pnf_open? pnf_close: pnf_open
p0 = plot(base, title="base", color=gray)
fill(p0, p2, color=green, transp=70)
fill(p0, p1, color=maroon, transp=70)
entry() => (base > pnf_close)
exit() => (base > pnf_open)
alertcondition(entry(), title='buy', message='buy!')
alertcondition(exit(), title='sell', message='sell!')
strategy.risk.allow_entry_in(strategy.direction.long)
strategy.entry("Long", long=true, when=entry())
strategy.entry("close", false, when=exit())
</code>```

答:
to elaborate on Vitruvius' answer, you want to include those in addition to what you already have.  So the end of your code will look like this - which should be noted that it will reverse long and shorts back and forth OR close the long or short strategy, whicher happens first.

first define your entry and exit conditions outside of the strategy statement.

```<code>entry=(whatever your entry logic is)
exit=(whatever your exit logic is)
shortentry=(whatever your entry logic is)
shortexit=(short exit logic)
strategy.entry("Long", long=true, when=entry)
strategy.entry("Short", long=false, when=shortentry)
strategy.close("close long", when=exit)
strategy.entry("close short", when=shortexit)
</code>```

Body:
How to include short signals in a Long only strategy on tradingview?

I have a Tradingview strategy which gives only long/Buy signals as per matching conditions. I also need it to generate short signals when the conditions are suitable. How do I do it?

strategy("Varun scalp", shorttitle="Varun scalp", overlay=true)
timeframe = input('3')
box = input('Traditional')
boxsize = input(5, type=float)
reversal = input(1)
pnf = pointfigure(tickerid, 'close', box, boxsize, reversal)
pnf_open= security(pnf, timeframe , open)
pnf_close= security(pnf, timeframe , close)
p1 = plot(pnf_open, title="pnf_open", color=green)
p2 = plot(pnf_close,  title="pnf_close",color=maroon)
base = pnf_close> pnf_open? pnf_close: pnf_open
p0 = plot(base, title="base", color=gray)
fill(p0, p2, color=green, transp=70)
fill(p0, p1, color=maroon, transp=70)
entry() => (base > pnf_close)
exit() => (base > pnf_open)
alertcondition(entry(), title='buy', message='buy!')
alertcondition(exit(), title='sell', message='sell!')
strategy.risk.allow_entry_in(strategy.direction.long)
strategy.entry("Long", long=true, when=entry())
strategy.entry("close", false, when=exit())

Body:
to elaborate on Vitruvius' answer, you want to include those in addition to what you already have.  So the end of your code will look like this - which should be noted that it will reverse long and shorts back and forth OR close the long or short strategy, whicher happens first.

first define your entry and exit conditions outside of the strategy statement.

entry=(whatever your entry logic is)
exit=(whatever your exit logic is)
shortentry=(whatever your entry logic is)
shortexit=(short exit logic)
strategy.entry("Long", long=true, when=entry)
strategy.entry("Short", long=false, when=shortentry)
strategy.close("close long", when=exit)
strategy.entry("close short", when=shortexit)


问:
flutter_inappwebview dynamic URL change
I am using flutter_inappwebview for display my website in flutter application.

In my application one drawer menu when i am click on drawer menu item change flutter_inappwebview URL and load new URL in flutter_inappwebview.

Drawer menu and flutter_inappwebview both are in different page.

Can this is possible in flutter

This is my code for flutter_inappwebview

```<code>class homePage extends StatefulWidget {
  @override
  static const String routeName = '/homePage';
  _homePageState createState() => _homePageState();
}

class _homePageState extends State<homePage> {
  String url = "";
  double progress = 0;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
    debugShowCheckedModeBanner:false,
    home: Scaffold(
      body: Container(
        child: Column(children: <Widget>[
          Container(
            padding: EdgeInsets.all(2.0),
            child: progress < 1.0
                ? LinearProgressIndicator(value: progress)
                : Container()),
            Expanded(
              child: Container(
              margin: const EdgeInsets.all(0.0),
              child: InAppWebView(
                initialUrl: selectedUrl,
                initialOptions: InAppWebViewGroupOptions(
                  crossPlatform: InAppWebViewOptions(
                    debuggingEnabled: true,
                  )
               ),
               onWebViewCreated: (InAppWebViewController controller) {
                 _webViewController = controller;
               },
               onLoadStart: (InAppWebViewController controller, String url) {
                 setState(() {
                   this.url = url;
                 });
               },
               onLoadStop: (InAppWebViewController controller, String url) async {
                 setState(() {
                   this.url = url;
                 });
               },
               onProgressChanged: (InAppWebViewController controller, int progress) {
                 setState(() {
                   this.progress = progress / 100;
                 });
               },
             ),
           ),
         ),
       ]),
     ),
   ),
 );
</code>```

}
}

答:
Load new url from textform,drawer widget or while pressing button widget

```<code>widget._controller!.loadUrl(
                    urlRequest:
                        URLRequest(url: Uri.parse("www.google.com")));
</code>```

Initialise InAppWebViewController in inside onwebviewcreatedlistner:

```<code>  onWebViewCreated: (controller) {
                    widget._controller = controller;
                  },
</code>```

SampleCode:

```<code>import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

void main() => runApp(MyHomePage());

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: homePage(),
    );
  }
}

class homePage extends StatefulWidget {
  @override
  static const String routeName = '/homePage';
  InAppWebViewController? _controller;

  _homePageState createState() => _homePageState();
}
final GlobalKey webViewKey = GlobalKey();
InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
    crossPlatform: InAppWebViewOptions(
      useShouldOverrideUrlLoading: true,
      mediaPlaybackRequiresUserGesture: false,
    ),
    android: AndroidInAppWebViewOptions(
      useHybridComposition: true,
    ),
    ios: IOSInAppWebViewOptions(
      allowsInlineMediaPlayback: true,
    ));
class _homePageState extends State<homePage> {
  String url = "";
  double progress = 0;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        drawer: Container(
          width: 125,
          child: Drawer(
            child: ListView(
              // Important: Remove any padding from the ListView.
              padding: EdgeInsets.zero,
              children: [
                const DrawerHeader(
                  decoration: BoxDecoration(
                    color: Colors.blue,
                  ),
                  child: Text('Drawer Header'),
                ),
                ListTile(
                  title: const Text('google.com'),
                  onTap: () {
                    widget._controller!.loadUrl(
                        urlRequest:
                            URLRequest(url: Uri.parse("www.google.com")));

                    // Update the state of the app.
                    // ...
                  },
                ),
                ListTile(
                  title: const Text('yahoo.com'),
                  onTap: () {
                    widget._controller!.loadUrl(
                        urlRequest:
                            URLRequest(url: Uri.parse("www.yahoo.com")));
                    // ...
                  },
                ),
              ],
            ),
          ),
        ),
        body: Container(
          child: Column(children: <Widget>[
            Container(
                padding: EdgeInsets.all(2.0),
                child: progress < 1.0
                    ? LinearProgressIndicator(value: progress)
                    : Container()),
            Expanded(
              child: Container(
                margin: const EdgeInsets.all(0.0),
                child: InAppWebView(
                  key: webViewKey,
                  initialOptions: options,
                  initialUrlRequest:
                      URLRequest(url: Uri.parse("https://inappwebview.dev/")),
                  onWebViewCreated: (controller) {
                    widget._controller = controller;
                  },
                  onProgressChanged:
                      (InAppWebViewController controller, int progress) {
                    setState(() {
                      this.progress = progress / 100;
                    });
                  },
                ),
              ),
            ),
          ]),
        ),
      ),
    );
  }
}
</code>```

Title: flutter_inappwebview dynamic URL change

Body:
I am using flutter_inappwebview for display my website in flutter application.

In my application one drawer menu when i am click on drawer menu item change flutter_inappwebview URL and load new URL in flutter_inappwebview.

Drawer menu and flutter_inappwebview both are in different page.

Can this is possible in flutter

This is my code for flutter_inappwebview

class homePage extends StatefulWidget {
  @override
  static const String routeName = '/homePage';
  _homePageState createState() => _homePageState();
}

class _homePageState extends State<homePage> {
  String url = "";
  double progress = 0;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
    debugShowCheckedModeBanner:false,
    home: Scaffold(
      body: Container(
        child: Column(children: <Widget>[
          Container(
            padding: EdgeInsets.all(2.0),
            child: progress < 1.0
                ? LinearProgressIndicator(value: progress)
                : Container()),
            Expanded(
              child: Container(
              margin: const EdgeInsets.all(0.0),
              child: InAppWebView(
                initialUrl: selectedUrl,
                initialOptions: InAppWebViewGroupOptions(
                  crossPlatform: InAppWebViewOptions(
                    debuggingEnabled: true,
                  )
               ),
               onWebViewCreated: (InAppWebViewController controller) {
                 _webViewController = controller;
               },
               onLoadStart: (InAppWebViewController controller, String url) {
                 setState(() {
                   this.url = url;
                 });
               },
               onLoadStop: (InAppWebViewController controller, String url) async {
                 setState(() {
                   this.url = url;
                 });
               },
               onProgressChanged: (InAppWebViewController controller, int progress) {
                 setState(() {
                   this.progress = progress / 100;
                 });
               },
             ),
           ),
         ),
       ]),
     ),
   ),
 );

}
}

Body:
Load new url from textform,drawer widget or while pressing button widget

widget._controller!.loadUrl(
                    urlRequest:
                        URLRequest(url: Uri.parse("www.google.com")));

Initialise InAppWebViewController in inside onwebviewcreatedlistner:

  onWebViewCreated: (controller) {
                    widget._controller = controller;
                  },

SampleCode:

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

void main() => runApp(MyHomePage());

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: homePage(),
    );
  }
}

class homePage extends StatefulWidget {
  @override
  static const String routeName = '/homePage';
  InAppWebViewController? _controller;

  _homePageState createState() => _homePageState();
}
final GlobalKey webViewKey = GlobalKey();
InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
    crossPlatform: InAppWebViewOptions(
      useShouldOverrideUrlLoading: true,
      mediaPlaybackRequiresUserGesture: false,
    ),
    android: AndroidInAppWebViewOptions(
      useHybridComposition: true,
    ),
    ios: IOSInAppWebViewOptions(
      allowsInlineMediaPlayback: true,
    ));
class _homePageState extends State<homePage> {
  String url = "";
  double progress = 0;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        drawer: Container(
          width: 125,
          child: Drawer(
            child: ListView(
              // Important: Remove any padding from the ListView.
              padding: EdgeInsets.zero,
              children: [
                const DrawerHeader(
                  decoration: BoxDecoration(
                    color: Colors.blue,
                  ),
                  child: Text('Drawer Header'),
                ),
                ListTile(
                  title: const Text('google.com'),
                  onTap: () {
                    widget._controller!.loadUrl(
                        urlRequest:
                            URLRequest(url: Uri.parse("www.google.com")));

                    // Update the state of the app.
                    // ...
                  },
                ),
                ListTile(
                  title: const Text('yahoo.com'),
                  onTap: () {
                    widget._controller!.loadUrl(
                        urlRequest:
                            URLRequest(url: Uri.parse("www.yahoo.com")));
                    // ...
                  },
                ),
              ],
            ),
          ),
        ),
        body: Container(
          child: Column(children: <Widget>[
            Container(
                padding: EdgeInsets.all(2.0),
                child: progress < 1.0
                    ? LinearProgressIndicator(value: progress)
                    : Container()),
            Expanded(
              child: Container(
                margin: const EdgeInsets.all(0.0),
                child: InAppWebView(
                  key: webViewKey,
                  initialOptions: options,
                  initialUrlRequest:
                      URLRequest(url: Uri.parse("https://inappwebview.dev/")),
                  onWebViewCreated: (controller) {
                    widget._controller = controller;
                  },
                  onProgressChanged:
                      (InAppWebViewController controller, int progress) {
                    setState(() {
                      this.progress = progress / 100;
                    });
                  },
                ),
              ),
            ),
          ]),
        ),
      ),
    );
  }
}


问:
jQuery - chaining a native function
Can anyone explain why I can chain a native JavaScript function to a jQuery function like so:

```<code>$('#search').val().replace("00:00:00", "")
</code>```

In this case, replace is the native JavaScript function.

http://www.w3schools.com/jsref/jsref_replace.asp

Thanks

答:
In this case val() must be returning a string value and hence replace works as expected.  It's no different than calling a function which returns a string and chaining that

```<code>function example() {
  return "foo";
}

example().replace("00:00:00", "");
</code>```

Title: jQuery - chaining a native function

Body:
Can anyone explain why I can chain a native JavaScript function to a jQuery function like so:

$('#search').val().replace("00:00:00", "")

In this case, replace is the native JavaScript function.

http://www.w3schools.com/jsref/jsref_replace.asp

Thanks

Body:
In this case val() must be returning a string value and hence replace works as expected.  It's no different than calling a function which returns a string and chaining that

function example() {
  return "foo";
}

example().replace("00:00:00", "");


问:
Replacing the value in a column based on a single vectorized condition
I tried the following code with multiple conditions and worked perfectly, somehow whatever I am trying with a single condition it won't work. It will simply return the values "1" & "SD" for every row no matter if the value of Col_A is True. Please let me know any suggestions, the weird part is that I am not getting any error whatsoever.</p>
```<code>condition = [
    df1['Col_A'] == 'TRUE'
]

result1 = ['1']
result2 = ['SD']

df1['Col_B'] = np.select(condition, result1, 'NA')
df1['Col_C'] = np.select(condition, result2, 'NA')
df1```

Input

        Col_A    Col_B     Col_C
    0   TRUE       NA         NA
    1   FALSE      1001       Valid
    2   TRUE       NA         NA
    3   TRUE       NA         NA

Output

        Col_A    Col_B     Col_C
    0   TRUE       NA         NA
    1   FALSE      NA         NA
    2   TRUE       NA         NA
    3   TRUE       NA         NA

Desired Output

        Col_A    Col_B     Col_C
    0   TRUE       1         SD
    1   FALSE      1001      Valid
    2   TRUE       1         SD
    3   TRUE       1         SD
</code>```

答:
You could use a simple loc assignment with a condition:

string "TRUE":

```<code>df.loc[df['Col_A'].eq('TRUE'), ['Col_B', 'Col_C']] = [1, 'SD']
</code>```

boolean True:

```<code>df.loc[df['Col_A'], ['Col_B', 'Col_C']] = [1, 'SD']
</code>```

output:

```<code>   Col_A   Col_B  Col_C
0   TRUE     1.0     SD
1  FALSE  1001.0  Valid
2   TRUE     1.0     SD
3   TRUE     1.0     SD
</code>```

Body:
I tried the following code with multiple conditions and worked perfectly, somehow whatever I am trying with a single condition it won't work. It will simply return the values "1" & "SD" for every row no matter if the value of Col_A is True. Please let me know any suggestions, the weird part is that I am not getting any error whatsoever.

condition = [
    df1['Col_A'] == 'TRUE'
]

result1 = ['1']
result2 = ['SD']

df1['Col_B'] = np.select(condition, result1, 'NA')
df1['Col_C'] = np.select(condition, result2, 'NA')
df1```

Input

        Col_A    Col_B     Col_C
    0   TRUE       NA         NA
    1   FALSE      1001       Valid
    2   TRUE       NA         NA
    3   TRUE       NA         NA

Output

        Col_A    Col_B     Col_C
    0   TRUE       NA         NA
    1   FALSE      NA         NA
    2   TRUE       NA         NA
    3   TRUE       NA         NA

Desired Output

        Col_A    Col_B     Col_C
    0   TRUE       1         SD
    1   FALSE      1001      Valid
    2   TRUE       1         SD
    3   TRUE       1         SD

Body:
You could use a simple loc assignment with a condition:

string "TRUE":

df.loc[df['Col_A'].eq('TRUE'), ['Col_B', 'Col_C']] = [1, 'SD']

boolean True:

df.loc[df['Col_A'], ['Col_B', 'Col_C']] = [1, 'SD']

output:

   Col_A   Col_B  Col_C
0   TRUE     1.0     SD
1  FALSE  1001.0  Valid
2   TRUE     1.0     SD
3   TRUE     1.0     SD


问:
ESP32 micropython PWM measurement
I'm trying to control a servo with a PWM signal with an ESP32 with micropython. I cannot seem to get the servo to move and therefore would like to check my PWM signal.

I created a testing script to generate a PWM signal on GPIO32 and measure this back on GPIO36. I connected a jumper wire between 32 and 36 and I'm using the following code:

"""Testing script"""
import machine
from machine import Pin, PWM
import utime

# PWM on pin 32
p_out = Pin(32, Pin.OUT)
pwm = PWM(p_out)
f = 500
pwm.freq(f)
dc = 512
pwm.duty(dc)

# Measure on pin 36
p_echo = Pin(36, Pin.IN)
while True:
    timeout_us = int(2 * 1 / f * 1e6)
    print(
        f"Trying to measure pulse length of {dc/1024*1 / f * 1e6} us with a timeout of {timeout_us} us"
    )
    print(f"Pulse length: {machine.time_pulse_us(p_echo,0,timeout_us)} us")
    utime.sleep_ms(100)
```
<p>The only thing I get back is</p>
```Trying to measure pulse length of 1000.0 us with a timeout of 4000 us
Pulse length: -1 us
```

I'm obviously missing something here. The documentation says:

machine.time_pulse_us(pin, pulse_level, timeout_us=1000000, /)

Time a pulse on the given pin, and return the duration of the pulse in
microseconds. The pulse_level argument should be 0 to time a low pulse
or 1 to time a high pulse.

If the current input value of the pin is different to pulse_level, the
function first (*) waits until the pin input becomes equal to
pulse_level, then (**) times the duration that the pin is equal to
pulse_level. If the pin is already equal to pulse_level then timing
starts straight away.

The function will return -2 if there was timeout waiting for condition
marked (*) above, and -1 if there was timeout during the main
measurement, marked (**) above. The timeout is the same for both cases
and given by timeout_us (which is in microseconds).

Seems like the timeout expired and nothing happened. I don't really have something else to verify that the PWM output is actually doing something like a scope.

答: Figured it out, my firmware had a bug (v1.18), updating to esp32-ota-20220213-unstable-v1.18-128-g2ea21abae fixed the issue for me.</p>

Title: ESP32 micropython PWM measurement

Body:
I'm trying to control a servo with a PWM signal with an ESP32 with micropython. I cannot seem to get the servo to move and therefore would like to check my PWM signal.

I created a testing script to generate a PWM signal on GPIO32 and measure this back on GPIO36. I connected a jumper wire between 32 and 36 and I'm using the following code:

"""Testing script"""
import machine
from machine import Pin, PWM
import utime

# PWM on pin 32
p_out = Pin(32, Pin.OUT)
pwm = PWM(p_out)
f = 500
pwm.freq(f)
dc = 512
pwm.duty(dc)

# Measure on pin 36
p_echo = Pin(36, Pin.IN)
while True:
    timeout_us = int(2 * 1 / f * 1e6)
    print(
        f"Trying to measure pulse length of {dc/1024*1 / f * 1e6} us with a timeout of {timeout_us} us"
    )
    print(f"Pulse length: {machine.time_pulse_us(p_echo,0,timeout_us)} us")
    utime.sleep_ms(100)

The only thing I get back is

Trying to measure pulse length of 1000.0 us with a timeout of 4000 us
Pulse length: -1 us

I'm obviously missing something here. The documentation says:

machine.time_pulse_us(pin, pulse_level, timeout_us=1000000, /)

Time a pulse on the given pin, and return the duration of the pulse in
microseconds. The pulse_level argument should be 0 to time a low pulse
or 1 to time a high pulse.

If the current input value of the pin is different to pulse_level, the
function first (*) waits until the pin input becomes equal to
pulse_level, then (**) times the duration that the pin is equal to
pulse_level. If the pin is already equal to pulse_level then timing
starts straight away.

The function will return -2 if there was timeout waiting for condition
marked (*) above, and -1 if there was timeout during the main
measurement, marked (**) above. The timeout is the same for both cases
and given by timeout_us (which is in microseconds).

Seems like the timeout expired and nothing happened. I don't really have something else to verify that the PWM output is actually doing something like a scope.


问:
How to call concatenated column in outer query from subquery in SQL?
In my subquery result I have concatenated first_name and last_name. In my outer query I'm calling subquery "temp". Since I have concatenated columns in my subquery, how to call that concatenated column in my outer query?

For example purpose, I have put Employee name within quotes which I know is why it's giving incorrect result by showing "Employee Name" as the 1st column values instead of showing actual employee names.

SQL query:

```<code>Select "Employee Name",
       dept_name, Salary,
       sum(Salary) OVER (partition by dept_name) as "Total Sal Dept",
       avg(Salary) OVER (partition by dept_name) as "Avg Sal / Dept"
FROM (
       Select concat(employees.first_name, ", ",employees.last_name) as "Employee Name",
              departments.dept_name,
              Max(salaries.salary) as "Salary"
       FROM departments
       JOIN dept_manager ON (departments.dept_no = dept_manager.dept_no)
       JOIN salaries ON (dept_manager.emp_no = salaries.emp_no)
       JOIN employees ON (salaries.emp_no = employees.emp_no)
       Group by employees.first_name, employees.last_name, departments.dept_name
     ) as temp
</code>```

Subquery temp result

Outer query with subquery temp result

答:
Use back-ticks instead of double-quotes.

```<code>select `Employee Name`
from (select 'your, name' AS "Employee Name") temp
</code>```

dbfiddle.uk

Better yet, avoid putting spaces in your column names while building your output. If you must have them formatted with spaces, do it at the very end.

```<code>select employee_name AS "Employee Name"
from (select 'your, name' AS employee_name) temp
</code>```

Body:
In my subquery result I have concatenated first_name and last_name. In my outer query I'm calling subquery "temp". Since I have concatenated columns in my subquery, how to call that concatenated column in my outer query?

For example purpose, I have put Employee name within quotes which I know is why it's giving incorrect result by showing "Employee Name" as the 1st column values instead of showing actual employee names.

SQL query:

Select "Employee Name",
       dept_name, Salary,
       sum(Salary) OVER (partition by dept_name) as "Total Sal Dept",
       avg(Salary) OVER (partition by dept_name) as "Avg Sal / Dept"
FROM (
       Select concat(employees.first_name, ", ",employees.last_name) as "Employee Name",
              departments.dept_name,
              Max(salaries.salary) as "Salary"
       FROM departments
       JOIN dept_manager ON (departments.dept_no = dept_manager.dept_no)
       JOIN salaries ON (dept_manager.emp_no = salaries.emp_no)
       JOIN employees ON (salaries.emp_no = employees.emp_no)
       Group by employees.first_name, employees.last_name, departments.dept_name
     ) as temp

Subquery temp result

Outer query with subquery temp result

Body:
Use back-ticks instead of double-quotes.

select `Employee Name`
from (select 'your, name' AS "Employee Name") temp

dbfiddle.uk

Better yet, avoid putting spaces in your column names while building your output. If you must have them formatted with spaces, do it at the very end.

select employee_name AS "Employee Name"
from (select 'your, name' AS employee_name) temp


问:
Automatically shutdown all `Process` instances if the parent thread crashed on Linux
One of my app's thread is responsible for running multiple processes in form of bash commands. It runs in a loop and for each found file runs specified command.

```<code>foreach (var file in files)
{
    string withoutExt = Path.GetFileNameWithoutExtension(file);
    string outputFile = Path.GetDirectoryName(file) + "/" + withoutExt + ".png";

    tasks.Add(Task.Run(delegate
    {
        ProcessStartInfo startInfo = new ProcessStartInfo()
            { FileName = "neato", Arguments = $"-Tpng {file} -o {outputFile}",  };

        Process.Start(startInfo)?.WaitForExit();
    }));
}

Task.WaitAll(tasks.ToArray());
</code>```

Although it does its job, I noticed that those processes are alive after my app is either forcibly closed or when it crashes. I found it out when I've ran this code on too many files: hundreds of processes appeared eating all my resources and when I've finally managed to close an app, they still persisted.

I'm looking for a way to somehow bound those processes to main thread, so they all be cleaned as soon as I close the main thread.

I'm aware that there are already questions asked about such problem on StackOverflow, but as far as I can see, solutions presented there are strictly bound to Windows OS, not Linux.

答:
One method to ensure that a set of created processes can be killed reliably is to start them in a new pid namespace.

In such a namespace, the "root" processes has pid 1 (init). As soon as that root process gets killed, the Linux kernel will ensure that all other processes in the namespace are killed. This will be independent from the sessions or the process groups which are associated to those processes.

This worked fine for me in a situation where I needed to reliably kill shell processes that I started from Python. Starting sub-processes in a new pid namespace is easy via the unshare shell command.

Body:
One of my app's thread is responsible for running multiple processes in form of bash commands. It runs in a loop and for each found file runs specified command.

foreach (var file in files)
{
    string withoutExt = Path.GetFileNameWithoutExtension(file);
    string outputFile = Path.GetDirectoryName(file) + "/" + withoutExt + ".png";

    tasks.Add(Task.Run(delegate
    {
        ProcessStartInfo startInfo = new ProcessStartInfo()
            { FileName = "neato", Arguments = $"-Tpng {file} -o {outputFile}",  };

        Process.Start(startInfo)?.WaitForExit();
    }));
}

Task.WaitAll(tasks.ToArray());

Although it does its job, I noticed that those processes are alive after my app is either forcibly closed or when it crashes. I found it out when I've ran this code on too many files: hundreds of processes appeared eating all my resources and when I've finally managed to close an app, they still persisted.

I'm looking for a way to somehow bound those processes to main thread, so they all be cleaned as soon as I close the main thread.

I'm aware that there are already questions asked about such problem on StackOverflow, but as far as I can see, solutions presented there are strictly bound to Windows OS, not Linux.


问:
Why does an h1 tag inside a body tag pushes the body tag down, resulting in a scrollbar showing up?
Why in this snipped the scrollbar shows up?

I see that body is 100% tall as indicated by CSS, but it is not positioned at the top of the page. Instead, the margin from the h1 tag is pushing body down by that amount, resulting in the scrollbar because the body does not fit in the page.

html, body {
  margin: 0;
  padding: 0;
  height: 100%;
}

.root {
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='root'>
<h1>Test</h1>
</div></code>```

My question is.. if the margin is in the h1 tag and h1 is inside body, why does body get pushed down and the scrollbar shows up?

答:
It works the same if you delete height: 100%;

html, body {
  margin: 0;
  padding: 0;
}

.root {
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='root'>
<h1>Test</h1>
</div></code>```

Use the margin to position the H1 element.

Most programmers use the CSS * Selector.

The * selector selects all elements.

The * selector can also select all elements inside another element.

Read more information here.

Example:

html, body {
  margin: 0;
  padding: 0;
}
*{
  margin: 0;
}
.root {
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='root'>
<h1>Test</h1>
</div></code>```

In this case, all elements will have a margin: 0;
It will work even if you leave height: 100%; the html and body.

And the last option, just like above, write a margin: 0; for each element.

html,
body {
  margin: 0;
  padding: 0;
}

.root {
  height: 100%;
}

h1 {
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='root'>
<h1>Test</h1>
</div></code>```

Body:
Why in this snipped the scrollbar shows up?

I see that body is 100% tall as indicated by CSS, but it is not positioned at the top of the page. Instead, the margin from the h1 tag is pushing body down by that amount, resulting in the scrollbar because the body does not fit in the page.

html, body {
  margin: 0;
  padding: 0;
  height: 100%;
}

.root {
  height: 100%;
}

Test

My question is.. if the margin is in the h1 tag and h1 is inside body, why does body get pushed down and the scrollbar shows up?

Body:
It works the same if you delete height: 100%;

html, body {
  margin: 0;
  padding: 0;
}

.root {
  height: 100%;
}

<div class='root'>
<h1>Test</h1>
</div>

Use the margin to position the H1 element.

Most programmers use the CSS * Selector.

The * selector selects all elements.

The * selector can also select all elements inside another element.

Read more information here.

Example:

html, body {
  margin: 0;
  padding: 0;
}
*{
  margin: 0;
}
.root {
  height: 100%;
}

<div class='root'>
<h1>Test</h1>
</div>

In this case, all elements will have a margin: 0;
It will work even if you leave height: 100%; the html and body.

And the last option, just like above, write a margin: 0; for each element.

html,
body {
  margin: 0;
  padding: 0;
}

.root {
  height: 100%;
}

h1 {
  margin: 0;
}

<div class='root'>
<h1>Test</h1>
</div>


问:
Unable to set cookie in nestjs, TypeError: Cannot set properties of undefined (setting 'color')
Am trying to set property in session but getting undefined. Using NestJs + Fastify

app.module.ts

```<code>import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
// import fastifyCookie, { FastifyCookieOptions } from 'fastify-cookie'; --this was also not workin

const cookieSession = require( 'cookie-session' );

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter( )
    );

  app.register( cookieSession( {
    keys: [ 'asdsds' ]
  } ) );

  lines...
}
bootstrap();
</code>```

users.controller.ts

```<code>imports...

export class UsersController {

    constructor( private usersService: UsersService, private authService: AuthService ) { }

    @Get( '/colors/:color' )
    setColor( @Param( 'color' ) color: string, @Session( ) session: any ) {
        // console.log( 'check ', session ); --> UNDEFINED
        session.color = color; --> Error HERE
        // session.set( color );
    }

    @Get( '/colors' )
    getColor( @Session( ) session: any ) {
        console.log( 'get session: ', session );
        return session.color;
    }
</code>```

Error is:

```<code>[Nest] 41229  - 13/02/2022, 9:51:06 pm   ERROR [ExceptionsHandler] Cannot set properties of undefined (setting 'color')
TypeError: Cannot set properties of undefined (setting 'color')
    at UsersController.setColor (/home/prabhat/Practice/Nest-Fastify/nestfastify/src/users/users.controller.ts:20:22)
    at /home/prabhat/Practice/Nest-Fastify/nestfastify/node_modules/@nestjs/core/router/router-execution-context.js:38:29
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
</code>```

I have also tried with

```<code>// app.register(fastifyCookie );
// app.register(fastifySession, {secret: 'a secret with minimum length of 32 characters'});
</code>```

答:
cookie-session is an express middleware. so if it's being used with fastify you'll probably end up with req.raw.session for the cookie.

fastify-cookie is a fastify specific package for cookie support, but not sessions directly, so you' need to use req.cookie or make a @Cookie() decorator

@fastify/session is the package for session support in fastify. By using @fastify/session with fastify-cookie you will have access to both req.session and req.cookie

Body:
Am trying to set property in session but getting undefined. Using NestJs + Fastify

app.module.ts

import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
// import fastifyCookie, { FastifyCookieOptions } from 'fastify-cookie'; --this was also not workin

const cookieSession = require( 'cookie-session' );

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter( )
    );

  app.register( cookieSession( {
    keys: [ 'asdsds' ]
  } ) );

  lines...
}
bootstrap();

users.controller.ts

imports...

export class UsersController {

    constructor( private usersService: UsersService, private authService: AuthService ) { }

    @Get( '/colors/:color' )
    setColor( @Param( 'color' ) color: string, @Session( ) session: any ) {
        // console.log( 'check ', session ); --> UNDEFINED
        session.color = color; --> Error HERE
        // session.set( color );
    }

    @Get( '/colors' )
    getColor( @Session( ) session: any ) {
        console.log( 'get session: ', session );
        return session.color;
    }

Error is:

[Nest] 41229  - 13/02/2022, 9:51:06 pm   ERROR [ExceptionsHandler] Cannot set properties of undefined (setting 'color')
TypeError: Cannot set properties of undefined (setting 'color')
    at UsersController.setColor (/home/prabhat/Practice/Nest-Fastify/nestfastify/src/users/users.controller.ts:20:22)
    at /home/prabhat/Practice/Nest-Fastify/nestfastify/node_modules/@nestjs/core/router/router-execution-context.js:38:29
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

I have also tried with

// app.register(fastifyCookie );
// app.register(fastifySession, {secret: 'a secret with minimum length of 32 characters'});


问:
enable button after actual input entered
How  to enabled button, when the actual amount entered

lets say i have 100 minimum and 200 maximum

i want when user enters amount below 100 error comes actual amount needed and button reamins dsiabled

when user enters more than 200 do the same echo error

user has to enter 100 and above but not exceed maximum

```<code> <form method="post">
<input type="text" id="Textfield">
<button type="submit" class="disabledButton" disabled>Submit</button>
<p id="error"></p>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$('#Textfield').keyup(function(){
     var textBox = $('#Textfield').val();
     if((textBox >= 100) || (textBox <= 200) ){
       $('.disabledButton').prop("disabled", false);
     } else {
     $('#error').text('actual amount needed');
        return false;
    }
});
</script>
</code>```

答:
$('#Textfield').on('keyup',function(){
 //every time a key is pressed we count the total number of characters in the field
  var charLength = $(this).val().length;
  //if they are equal to or above 100 and equal to or below 200 we disable the disabled button property else we disable the button again
  if(charLength >= 100 && charLength <= 200){
    $('.disabledButton').prop('disabled',false)
  }else{
    $('.disabledButton').prop('disabled',true)
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post">
<input type="text" id="Textfield">
<button type="submit" class="disabledButton" disabled>Submit</button>
<p id="error"></p>
</form></code>```

Body:
How  to enabled button, when the actual amount entered

lets say i have 100 minimum and 200 maximum

i want when user enters amount below 100 error comes actual amount needed and button reamins dsiabled

when user enters more than 200 do the same echo error

user has to enter 100 and above but not exceed maximum

 <form method="post">
<input type="text" id="Textfield">
<button type="submit" class="disabledButton" disabled>Submit</button>

</form>

Body:
$('#Textfield').on('keyup',function(){
 //every time a key is pressed we count the total number of characters in the field
  var charLength = $(this).val().length;
  //if they are equal to or above 100 and equal to or below 200 we disable the disabled button property else we disable the button again
  if(charLength >= 100 && charLength <= 200){
    $('.disabledButton').prop('disabled',false)
  }else{
    $('.disabledButton').prop('disabled',true)
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post">
<input type="text" id="Textfield">
<button type="submit" class="disabledButton" disabled>Submit</button>
<p id="error"></p>
</form>


问:
Case_when adding on a function
I'm trying to write a function in R that generates three values that loops over each row of a df, checks the value of one column then, if it meets this condition, adds the value of the value of one column for this row to a value.

I thought that using the case_when construction would work best for this, but should I be using an lapply constructon instead ?

```<code>get_home_away_goals_for_team <- function(matches_df, team_list){

  complete_df <- data.frame(team = character(), goals_scored= double(),goals_conceded = double(), games_played = double())

  for (team in teams){

  print(team)

  goals_scored <- 0
  goals_conceded <- 0
  games_played <- 0

  case_when(
    matches_df$home == team ~ goals_scored = goals_scored + matches_df$hg,
    matches_df$home == team ~ goals_conceded = goals_conceded + matches_df$ag,
    matches_df$away == team ~ goals_scored = goals_scored + matches_df$ag,
    matches_df$away == team ~ goals_conceded = goals_conceded + matches_df$hg,
    matches_df$home == team ~ games_played = games_played + 1,
    matches_df$away == team ~ games_played = games_played + 1)

    temp_get_goals_df = data.frame(team,goals_scored,goals_conceded,games_played)

    complete_df <- rbind(complete_df,temp_get_goals_df)
    }

  complete_df

}

</code>```

The function takes a value of team, checks for each row whether this team was playing in a game home or away, then adds to the values of goals scored accordingly.

When I try to use the function though, I get the error Error: unexpected '}' in "    }" which makes me think I'm using case_when incorrectly.

Is this the case ?

Data:

matches_df_example :

```<code>structure(list(home = c("Colorado Rapids", "Vancouver Whitecaps",
"DC United", "Los Angeles Galaxy", "San Jose Earthquakes", "FC Dallas"
), away = c("Columbus Crew", "Club de Foot Montreal", "Sporting Kansas City",
"Real Salt Lake", "New England Revolution", "New York Red Bulls"
), res = c("H", "H", "A", "A", "H", "H"), season = c(2012, 2012,
2012, 2012, 2012, 2012), hg = c(2, 2, 0, 1, 1, 2), ag = c(0,
0, 1, 3, 0, 1), date_time = structure(c(1331420400, 1331420400,
1331425800, 1331436600, 1331436600, 1331492400), tzone = "UTC", class = c("POSIXct",
"POSIXt")), home_conference = c("West", "West", "East", "West",
"West", "West"), away_conference = c("East", "East", "East",
"West", "East", "East")), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"))
</code>```

teams

```<code>c("Colorado Rapids", "Vancouver Whitecaps", "DC United", "Los Angeles Galaxy",
"San Jose Earthquakes", "FC Dallas", "Chivas USA", "Portland Timbers",
"Club de Foot Montreal", "Sporting Kansas City", "Real Salt Lake",
"Seattle Sounders", "Philadelphia Union", "Toronto FC", "Columbus Crew",
"New England Revolution", "Chicago Fire", "New York Red Bulls",
"Houston Dynamo", "Orlando City", "New York City", "Atlanta United",
"Minnesota United", "Los Angeles FC", "FC Cincinnati", "Atlanta Utd",
"Nashville SC", "Inter Miami", "Austin FC")
</code>```

答:
Perhaps this?

homes <- matches_df %>%
  group_by(team = home) %>%
  summarize(
    goals_scored = sum(hg),
    goals_conceded = sum(ag),
    games_played = n(),
    .groups = "drop"
  )
aways <- matches_df %>%
  group_by(team = away) %>%
  summarize(
    goals_scored = sum(hg),
    goals_conceded = sum(ag),
    games_played = n(),
    .groups = "drop"
  )

full_join(homes, aways, by = "team", suffix = c("", ".y")) %>%
  full_join(tibble(team = teams), by = "team") %>%
  transmute(
    team,
    goals_scored = coalesce(goals_scored, goals_scored.y, 0),
    goals_conceded = coalesce(goals_conceded, goals_conceded.y, 0),
    games_played = coalesce(games_played, games_played.y, 0)
  )
# # A tibble: 29 x 4
#    team                   goals_scored goals_conceded games_played
#    <chr>                         <dbl>          <dbl>        <dbl>
#  1 Colorado Rapids                   2              0            1
#  2 DC United                         0              1            1
#  3 FC Dallas                         2              1            1
#  4 Los Angeles Galaxy                1              3            1
#  5 San Jose Earthquakes              1              0            1
#  6 Vancouver Whitecaps               2              0            1
#  7 Club de Foot Montreal             2              0            1
#  8 Columbus Crew                     2              0            1
#  9 New England Revolution            1              0            1
# 10 New York Red Bulls                2              1            1
# # ... with 19 more rows
```

Title: Case_when adding on a function

Body:
I'm trying to write a function in R that generates three values that loops over each row of a df, checks the value of one column then, if it meets this condition, adds the value of the value of one column for this row to a value.

I thought that using the case_when construction would work best for this, but should I be using an lapply constructon instead ?

get_home_away_goals_for_team <- function(matches_df, team_list){

  complete_df <- data.frame(team = character(), goals_scored= double(),goals_conceded = double(), games_played = double())

  for (team in teams){

  print(team)

  goals_scored <- 0
  goals_conceded <- 0
  games_played <- 0

  case_when(
    matches_df$home == team ~ goals_scored = goals_scored + matches_df$hg,
    matches_df$home == team ~ goals_conceded = goals_conceded + matches_df$ag,
    matches_df$away == team ~ goals_scored = goals_scored + matches_df$ag,
    matches_df$away == team ~ goals_conceded = goals_conceded + matches_df$hg,
    matches_df$home == team ~ games_played = games_played + 1,
    matches_df$away == team ~ games_played = games_played + 1)

    temp_get_goals_df = data.frame(team,goals_scored,goals_conceded,games_played)

    complete_df <- rbind(complete_df,temp_get_goals_df)
    }

  complete_df

}

The function takes a value of team, checks for each row whether this team was playing in a game home or away, then adds to the values of goals scored accordingly.

When I try to use the function though, I get the error Error: unexpected '}' in "    }" which makes me think I'm using case_when incorrectly.

Is this the case ?

Data:

matches_df_example :

structure(list(home = c("Colorado Rapids", "Vancouver Whitecaps",
"DC United", "Los Angeles Galaxy", "San Jose Earthquakes", "FC Dallas"
), away = c("Columbus Crew", "Club de Foot Montreal", "Sporting Kansas City",
"Real Salt Lake", "New England Revolution", "New York Red Bulls"
), res = c("H", "H", "A", "A", "H", "H"), season = c(2012, 2012,
2012, 2012, 2012, 2012), hg = c(2, 2, 0, 1, 1, 2), ag = c(0,
0, 1, 3, 0, 1), date_time = structure(c(1331420400, 1331420400,
1331425800, 1331436600, 1331436600, 1331492400), tzone = "UTC", class = c("POSIXct",
"POSIXt")), home_conference = c("West", "West", "East", "West",
"West", "West"), away_conference = c("East", "East", "East",
"West", "East", "East")), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"))

teams

c("Colorado Rapids", "Vancouver Whitecaps", "DC United", "Los Angeles Galaxy",
"San Jose Earthquakes", "FC Dallas", "Chivas USA", "Portland Timbers",
"Club de Foot Montreal", "Sporting Kansas City", "Real Salt Lake",
"Seattle Sounders", "Philadelphia Union", "Toronto FC", "Columbus Crew",
"New England Revolution", "Chicago Fire", "New York Red Bulls",
"Houston Dynamo", "Orlando City", "New York City", "Atlanta United",
"Minnesota United", "Los Angeles FC", "FC Cincinnati", "Atlanta Utd",
"Nashville SC", "Inter Miami", "Austin FC")