问:
What is causing React to re-render this component infinitely?
I'm in the process of creating a login/signup component for an application I'm building. I would like the component to read the address bar and set itself to login mode or signup mode depending on if the domain is followed by a "/login" or "/signup" respectively.

For a reason unknown to me, the component is re-rendering infinitely when the state change function is called within the if block. It doesn't do this if I remove the else block from the if statement and attempt to access the page with "http://localhost:3000/signup"

Any and all advice is appreciated, as well as any possible solutions.

Register component: https://pastebin.com/pE2t5gdw

```<code>import React, {
  Fragment,
  useContext,
  useState,
  useMemo,
  useCallback,
} from "react";
import { useParams } from "react-router-dom";
import { AuthContext } from "../../shared/context/AuthContext";

import Card from "../../shared/components/UIElements/Card";

import "./Register.css";

const Register = () => {
  const [isLoginMode, setIsLoginMode] = useState(false);            // state creation
  const auth = useContext(AuthContext);
  const registerSubmitHandler = () => {
    auth.login();
  };

  if (window.location.pathname.toString() === "/login") {           // attempt to determine if we should present signup or login
    setIsLoginMode(true);
  } else {
    setIsLoginMode(false);
  }

  return (
    <Card className="authentication">
      <h1>{!isLoginMode ? "signup mode" : "login mode"}</h1>        // result of login or signup mode
      <div>
        <label>Email</label>
        <input type="text" />
        <label>Password</label>
        <input type="text" />
        <button onClick={registerSubmitHandler}>Register</button>
        <button onClick={setIsLoginMode(!isLoginMode)}>Switch mode</button>   // supposed to change modes within the component
      </div>
    </Card>
  );
};

export default Register;
</code>```

答:
Learn more about react lifecycles, especially with hooks now.

Import the useEffect hook from React and place your if block into it like this:

```<code>    useEffect(() => {
        if (window.location.pathname.toString() === "/login") setIsLoginMode(true);
        else setIsLoginMode(false);
    } , [])
</code>```

Body:
I'm in the process of creating a login/signup component for an application I'm building. I would like the component to read the address bar and set itself to login mode or signup mode depending on if the domain is followed by a "/login" or "/signup" respectively.

For a reason unknown to me, the component is re-rendering infinitely when the state change function is called within the if block. It doesn't do this if I remove the else block from the if statement and attempt to access the page with "http://localhost:3000/signup"

Any and all advice is appreciated, as well as any possible solutions.

Register component: https://pastebin.com/pE2t5gdw

import React, {
  Fragment,
  useContext,
  useState,
  useMemo,
  useCallback,
} from "react";
import { useParams } from "react-router-dom";
import { AuthContext } from "../../shared/context/AuthContext";

import Card from "../../shared/components/UIElements/Card";

import "./Register.css";

const Register = () => {
  const [isLoginMode, setIsLoginMode] = useState(false);            // state creation
  const auth = useContext(AuthContext);
  const registerSubmitHandler = () => {
    auth.login();
  };

  if (window.location.pathname.toString() === "/login") {           // attempt to determine if we should present signup or login
    setIsLoginMode(true);
  } else {
    setIsLoginMode(false);
  }

  return (
    <Card className="authentication">

{!isLoginMode ? "signup mode" : "login mode"}
        // result of login or signup mode

        Email
        <input type="text" />
        Password
        <input type="text" />
        <button onClick={registerSubmitHandler}>Register</button>
        <button onClick={setIsLoginMode(!isLoginMode)}>Switch mode</button>   // supposed to change modes within the component

    </Card>
  );
};

export default Register;

Body:
Learn more about react lifecycles, especially with hooks now.

Import the useEffect hook from React and place your if block into it like this:

    useEffect(() => {
        if (window.location.pathname.toString() === "/login") setIsLoginMode(true);
        else setIsLoginMode(false);
    } , [])


来源: stackexchange

问:
WebView - WebPage not available
I (like many others) followed the webview tutorial, but I can't get pages to load.  Everything comes up as 'Webpage not Available'

I have ensured that the emulator does have internet access, and just to rule out a problem with the emulator I tried installing it on my phone, which resulted in the same behavior.

I have read that the biggest issue is people not putting the INTERNET permission in my manifest file, which I have tried putting as a child of different elements in the manifest to no avail.  Does anyone know why I can't get this to load?

Here is my code:

Manifest:

```<code><application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".AndroidTestActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <uses-permission android:name="android.permission.INTERNET" />
    </activity>
</application>
</manifest>
</code>```

AndroidTestActivity

```<code>public class AndroidTestActivity extends Activity {
    WebView webview;
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            webview = (WebView) findViewById(R.id.webview);
            webview.getSettings().setJavaScriptEnabled(true);

            webview.loadUrl("http://www.google.com/m");

            Intent intent = getIntent();
            // To get the action of the intent use
            System.out.println(intent.getAction());
            // We current open a hard-coded URL
            try {
                webview.setWebViewClient(new AndroidTestClient());

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
                webview.goBack();
                return true;
            }
            return super.onKeyDown(keyCode, event);
        }

        private class AndroidTestClient extends WebViewClient {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        }
}
</code>```

Thanks!

答:
If you use VPN, it can lead to this error. I connected to VPN and started an emulator, then WebView showed an error:

I disconnected from the VPN, restarted the emulator, and web page loaded. Of course, I wrote <uses-permission android:name="android.permission.INTERNET" /> in AndroidManifest.

ContentLicense: CC BY-SA 3.0

Title: WebView - WebPage not available

Body:
I (like many others) followed the webview tutorial, but I can't get pages to load.  Everything comes up as 'Webpage not Available'

I have ensured that the emulator does have internet access, and just to rule out a problem with the emulator I tried installing it on my phone, which resulted in the same behavior.

I have read that the biggest issue is people not putting the INTERNET permission in my manifest file, which I have tried putting as a child of different elements in the manifest to no avail.  Does anyone know why I can't get this to load?

Here is my code:

Manifest:

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".AndroidTestActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <uses-permission android:name="android.permission.INTERNET" />
    </activity>
</application>
</manifest>

AndroidTestActivity

public class AndroidTestActivity extends Activity {
    WebView webview;
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            webview = (WebView) findViewById(R.id.webview);
            webview.getSettings().setJavaScriptEnabled(true);

            webview.loadUrl("http://www.google.com/m");

            Intent intent = getIntent();
            // To get the action of the intent use
            System.out.println(intent.getAction());
            // We current open a hard-coded URL
            try {
                webview.setWebViewClient(new AndroidTestClient());

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
                webview.goBack();
                return true;
            }
            return super.onKeyDown(keyCode, event);
        }

        private class AndroidTestClient extends WebViewClient {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        }
}

Thanks!

ContentLicense: CC BY-SA 4.0


问:
Send Word document as an attachment
I am creating a Word document dynamically using PHP, and I need to send it as an attachment.

Is there a way to do this that will save it to the server temporarily in order to email it? Is there a better way?

```<code><?php
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=giftboxnote.doc");
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Windows-1252">
...other stuf...
</html>
</code>```

答: You should have a look on programmershelp and on Stackoverflow: Create Word Document using PHP in Linux and also there.</p>

Title: Send Word document as an attachment

Body:
I am creating a Word document dynamically using PHP, and I need to send it as an attachment.

Is there a way to do this that will save it to the server temporarily in order to email it? Is there a better way?

<?php
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=giftboxnote.doc");
?>

<meta http-equiv="Content-Type" content="text/html; charset=Windows-1252">
...other stuf...


问:
File contents are copied again and again, ansible is not acting as idempotent
Im trying to add file contents into remote nodes, below script is working but problem is If I run it again the file contents are copied again and again to remote nodes, ansible is not acting as idempotent.Any suggestions will be appreciated

    hosts: all
    vars:
       content: "{{ lookup('file','/etc/foo.txt')}}"
    tasks:
      - name: finding all files present in directory
        find:
          paths: /etc/something.d/
          file_type: file
          patterns: '*.d'
        register: c1
        become: true
      - lineinfile:
          path: "{{ item.path }}"
          line: "{{ contents }}"
          state: present
          create: yes
          backup: yes
        register: c2
        become: true
        with_items: "{{ c1.files }}"
      - debug:
          var: c1
      - debug:
          var: c2
```

答:
Your lineinfile task is behaving as documented since you did neither specify the parameter regexp nor search_string.

Since we do not know whether the file you read might contain a regular expression, better use search_string as it can just contain the same line again.

```<code>- lineinfile:
      path: "{{ item.path }}"
      line: "{{ contents }}"
      search_string: "{{ contents }}"
      state: present
      create: yes
      backup: yes
    register: c2
    become: true
    with_items: "{{ c1.files }}"
</code>```

See https://docs.ansible.com/ansible/latest/collections/ansible/builtin/lineinfile_module.html:

Body:
Your lineinfile task is behaving as documented since you did neither specify the parameter regexp nor search_string.

Since we do not know whether the file you read might contain a regular expression, better use search_string as it can just contain the same line again.

- lineinfile:
      path: "{{ item.path }}"
      line: "{{ contents }}"
      search_string: "{{ contents }}"
      state: present
      create: yes
      backup: yes
    register: c2
    become: true
    with_items: "{{ c1.files }}"

See https://docs.ansible.com/ansible/latest/collections/ansible/builtin/lineinfile_module.html:


问:
swiftUI using picker to show different values in the Text field than in the selector
I've got an array of strings that I want to present using swiftUI Picker widget. Each string is composed of multiple words delimited by spaces.

I'd like to get the Picker showing the full string of each item in the list, while the selection variable should only get the first word (the selected item is stored in arg)

This was my attempt to do so. notice that the object that hold the items called myHandler, and it's shared to the swiftUI view, and can be modified by external swift closure:

```<code>class myHandler: ObservableObject {
  @Published var items = [String]()
}

struct ContentView: View {
  @State var arg: String = ""
  @ObservedObject var handler : myHandler
  ...
  VStack {
    Picker("items", selection: $arg) {
              Text("AAA").tag("xxx")
              Text("BBB").tag("yyy")
              Text("CCC").tag("zzz")

              ForEach(handler.items , id: \.self, content: {
                Text($0).tag($0.components(separatedBy: " ")[0])
              })
        }
  }
  .frame()
    TextField("firstword", text: $arg).frame()

</code>```

For the options outside the ForEach statement, I can see that arg get the value written in the tag. However, for all options that derived from the ForEach, I see that arg equals to the iterable item ($0) which is the multi work string, and not to the first word as expected.

Any idea how to fix those items that are generated from the ForEach, so that selection of such item, will set the arg to the string value of the first word in the iterator ?

答:
```<code>Picker("items", selection: $arg) {
  ForEach(handler.items, id: \.self) {
    Text($0)
        .tag($0.components(separatedBy: " ").first ?? "")
  }
}
</code>```

Body:
I've got an array of strings that I want to present using swiftUI Picker widget. Each string is composed of multiple words delimited by spaces.

I'd like to get the Picker showing the full string of each item in the list, while the selection variable should only get the first word (the selected item is stored in arg)

This was my attempt to do so. notice that the object that hold the items called myHandler, and it's shared to the swiftUI view, and can be modified by external swift closure:

class myHandler: ObservableObject {
  @Published var items = [String]()
}

struct ContentView: View {
  @State var arg: String = ""
  @ObservedObject var handler : myHandler
  ...
  VStack {
    Picker("items", selection: $arg) {
              Text("AAA").tag("xxx")
              Text("BBB").tag("yyy")
              Text("CCC").tag("zzz")

              ForEach(handler.items , id: \.self, content: {
                Text($0).tag($0.components(separatedBy: " ")[0])
              })
        }
  }
  .frame()
    TextField("firstword", text: $arg).frame()

For the options outside the ForEach statement, I can see that arg get the value written in the tag. However, for all options that derived from the ForEach, I see that arg equals to the iterable item ($0) which is the multi work string, and not to the first word as expected.

Any idea how to fix those items that are generated from the ForEach, so that selection of such item, will set the arg to the string value of the first word in the iterator ?


问:
How to push 1 D array to a column
I'm trying to push 1D array to a column but Im keep getting that error "Exception: The parameters (number[]) don't match the method signature for SpreadsheetApp.Range.setValues." which what I understood is that I cant use setValues for 1D array, it has to be 2D array or more.

Here is my code.

```<code>  var range = ss.getRange(3,5,ss.getLastRow()-2).getValues();
  var qValues = [];
  for( var i=0; i<range.length; i++ ) {
    qValues.push([range[i][0]]); // index 0 = column E.
  }

  var values = ss.getRange(3,14,ss.getLastRow()-2,11).getValues(); // N3:T??
  var results = [];
  for(var i=0; i<values.length; i++ ) {
    results.push((([values[i][0]+values[i][2]+values[i][4]+values[i][6]+values[i][8]+values[i][10]])*120*qValues[i][0])/1000); // index 0 = column N, etc.
  }

   ss.getRange(3, 27,).setValues(results);

</code>```

I tried to add

```<code>results.push([""]);
</code>```

before the setValues statement but it didn't work as well

If you need more info please let me know.

Thank you

答:
Flat array to column

```<code>function flatArraytoColumn() {
  let a = [...Array.from(new Array(10).keys(), x => [x + 1])];//second term of array.from returns each element in an array
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getActiveSheet()
  sh.getRange(1, 1, a.length, 1).setValues(a);//Post into column
  Logger.log(a);//log array
}

Execution log
1:07:57 PM  Notice  Execution started
1:07:58 PM  Info    [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0], [8.0], [9.0], [10.0]]
1:07:59 PM  Notice  Execution completed
</code>```

Active Sheet:

Title: How to push 1 D array to a column

Body:
I'm trying to push 1D array to a column but Im keep getting that error "Exception: The parameters (number[]) don't match the method signature for SpreadsheetApp.Range.setValues." which what I understood is that I cant use setValues for 1D array, it has to be 2D array or more.

Here is my code.

  var range = ss.getRange(3,5,ss.getLastRow()-2).getValues();
  var qValues = [];
  for( var i=0; i<range.length; i++ ) {
    qValues.push([range[i][0]]); // index 0 = column E.
  }

  var values = ss.getRange(3,14,ss.getLastRow()-2,11).getValues(); // N3:T??
  var results = [];
  for(var i=0; i<values.length; i++ ) {
    results.push((([values[i][0]+values[i][2]+values[i][4]+values[i][6]+values[i][8]+values[i][10]])*120*qValues[i][0])/1000); // index 0 = column N, etc.
  }

   ss.getRange(3, 27,).setValues(results);

I tried to add

results.push([""]);

before the setValues statement but it didn't work as well

If you need more info please let me know.

Thank you

Body:
Flat array to column

function flatArraytoColumn() {
  let a = [...Array.from(new Array(10).keys(), x => [x + 1])];//second term of array.from returns each element in an array
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getActiveSheet()
  sh.getRange(1, 1, a.length, 1).setValues(a);//Post into column
  Logger.log(a);//log array
}

Execution log
1:07:57 PM  Notice  Execution started
1:07:58 PM  Info    [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0], [8.0], [9.0], [10.0]]
1:07:59 PM  Notice  Execution completed

Active Sheet:


问:
How can i form the property in compose to return int(0) if condition is true and not return anything if condition is false?
How can i form this expression to return int value of 0 if true and don't return the property if false? warehouse event is an array and the property is inside a compose.

Expression:

if(contains(variables('WareHouseEvent'), 'OB_2910'), int(0), <not
return anything)

答:
One of the workarounds is that you can use Condition connector when if the mentioned condition satisfies it executes true block else it executes false. From there you can use the same Compose content.

Here is the screenshot of the logic app  -

output :-


问:
Is there any way to call base python function in r using reticulate?
I got a "generator object" from a python function. However, I tried many ways but failed to read the "generator object" in r using reticulate.  I know python base function list() can convert "generator object" to "json", which I can then read in r. I wonder how to use base python function in r? (I would not prefer to use py_run_file)

For example:

```<code>>library(reticulate)
>foo <- import("foo")
>res <- foo.func()
<generator object at 0x7fd4fe98ee40>
</code>```

答:
I'm not sure if you can in R directly, but you definitely can in R Markdown. I use R Markdown to flip objects back and forth between the two.

I use a basic html_document YAML output. However, I don't typically knit this type of RMD, so I don't think it really matters what you put there if you use it the same way.

When you use reticulate you need an environment.

So first I'll have an R chunk:

```<code>```{r setup}

library(tidyverse) # for random r object creation to use in Python
library(reticulate)
use_virtualenv("KerasEnv") # this is an environment I already have setup

# creating R objects to use with Python
str(diamonds)

cut <- diamonds$cut %>% unique()

```
</code>```

Then I'll create my Python chunk.

```<code>```{r usingPy,results="asis",engine="python"}

import numpy as np
import random

diamonds_py = r.diamonds # bring dataset into Python

mxX = max(diamonds_py.x) # create a new Python object to bring into R
print(mxX)
# 10.74

cut_py = r.cut # bring vector into Python

```
</code>```

Now let's say I want to bring something from Python back into R.

```<code>```{r tellMeMore}
# bring Python object into R
mxX_r = py $ mxX
# [1] 10.74

```
</code>```

You can run the Python and R code line by line, by chunk, or knit. To clear the Python environment, I'm pretty sure you have to restart RStudio.

Body:
I got a "generator object" from a python function. However, I tried many ways but failed to read the "generator object" in r using reticulate.  I know python base function list() can convert "generator object" to "json", which I can then read in r. I wonder how to use base python function in r? (I would not prefer to use py_run_file)

For example:

>library(reticulate)
>foo <- import("foo")
>res <- foo.func()
<generator object at 0x7fd4fe98ee40>

Body:
I'm not sure if you can in R directly, but you definitely can in R Markdown. I use R Markdown to flip objects back and forth between the two.

I use a basic html_document YAML output. However, I don't typically knit this type of RMD, so I don't think it really matters what you put there if you use it the same way.

When you use reticulate you need an environment.

So first I'll have an R chunk:

```{r setup}

library(tidyverse) # for random r object creation to use in Python
library(reticulate)
use_virtualenv("KerasEnv") # this is an environment I already have setup

# creating R objects to use with Python
str(diamonds)

cut <- diamonds$cut %>% unique()

```

Then I'll create my Python chunk.

```{r usingPy,results="asis",engine="python"}

import numpy as np
import random

diamonds_py = r.diamonds # bring dataset into Python

mxX = max(diamonds_py.x) # create a new Python object to bring into R
print(mxX)
# 10.74

cut_py = r.cut # bring vector into Python

```

Now let's say I want to bring something from Python back into R.

```{r tellMeMore}
# bring Python object into R
mxX_r = py $ mxX
# [1] 10.74

```

You can run the Python and R code line by line, by chunk, or knit. To clear the Python environment, I'm pretty sure you have to restart RStudio.


问:
Compress output raster and parallelize gdalwarp from R
I would like to include -co options to compress output raster using gdalwarp from gdalUtilities in R.

I have tried some options (commented in the code), but I have not been successful in generating the compressed raster.

```<code>gdalUtilities::gdalwarp(srcfile = paste0(source_path,"/mask_30.tif"),
                        dstfile = paste0(writing_path,"/mask_30_gdalwarp.tif"),
                        cutline = paste0(source_path,"/amazon.shp"),
                        crop_to_cutline = TRUE,
                        multi = TRUE,
                        wo = "NUM_THREADS = 32",
                        co = "COMPRESS = DEFLATE")
                        # co = c("COMPRESS = DEFLATE","ZLEVEL = 9"))
                        # co COMPRESS = DEFLATE,
                        # co ZLEVEL = 9),
                        # co = "COMPRESS = DEFLATE",
                        # co = ZLEVEL = 9")
</code>```

Additionally, I would like to use multithread warping implementation. I am including-multi and -wo "NUM_THREADS = 16" (my computer has 32 cores) options, but I also have not been able to decrease the runtime vs. the default -multi option, which uses two cores by default.

Any suggestions for compression and parallelization?

Many thanks in advance.

答:
1 - COMPRESSION

Please find the solution for the problem of file compression. To be honest, I have already been confronted with the same problem as you and, at the time, I was racking my brains... to finally find the solution which is quite simple (once we know it!): you must not put any spaces (i.e. "COMPRESS=DEFLATE" and not "COMPRESS = DEFLATE")

So, please find below a small reprex.

Reprex

library(gdalUtilities)
library(stars)        # Loaded just to have a '.tif' image for the reprex

# Import a '.tif' image from the 'stars' library
tif <- read_stars(system.file("tif/L7_ETMs.tif", package = "stars"))

# Write the image to disk (in your working directory)
write_stars(tif, "image.tif")

# Size of the image on disk (in bytes)
file.size("image.tif")
#> [1] 2950880

# Compress the image
gdalUtilities::gdalwarp(srcfile = "image.tif",
                        dstfile = "image_gdalwarp.tif",
                        co = "COMPRESS=DEFLATE")

# Size of the compressed image on disk (in bytes)
file.size("image_gdalwarp.tif")
#> [1] 937920                # The image has been successfully compressed.
```
<p>As @MarkAdler said, there is not much difference between the default compression level (i.e. 6) and level 9. That said, please find below how you should write the code to be able to apply the desired compression level (i.e. still without spaces and in a list):</p>
<pre class="lang-r prettyprint-override"><code>gdalUtilities::gdalwarp(srcfile = "image.tif",
                        dstfile = "image_gdalwarp_Z9.tif",
                        co = list("COMPRESS=DEFLATE", "ZLEVEL=9"))

file.size("image_gdalwarp_Z9.tif")
#> [1] 901542
</code>```

Created on 2022-02-09 by the reprex package (v2.0.1)

2 - PARALLELIZATION

For the problem of parallelization on the cores of the processor, you should not use multi = TRUE. Only the argument wo = "NUM_THREADS=4" (always without spaces ;-)) is enough.

Just a clarification, I guess you are confusing the RAM and the number of cores. Usually computers are equipped with a 4 or 8 cores processor. The 32 that you indicate in your code refers to the 32 gigas of RAM that your computer probably has.

Reprex

library(gdalUtilities)
library(stars)

tif <- read_stars(system.file("tif/L7_ETMs.tif", package = "stars"))

write_stars(tif, "image.tif")

file.size("image.tif")
#> [1] 2950880

gdalUtilities::gdalwarp(srcfile = "image.tif",
                        dstfile = "image_gdalwarp_Z9_parallel.tif",
                        co = list("COMPRESS=DEFLATE", "ZLEVEL=9"),
                        wo = "NUM_THREADS=4") # Replace '4' by '8' if your processor has 8 cores

file.size("image_gdalwarp_Z9_parallel.tif")
#> [1] 901542
```

Created on 2022-02-09 by the reprex package (v2.0.1)

Body:
I would like to include -co options to compress output raster using gdalwarp from gdalUtilities in R.

I have tried some options (commented in the code), but I have not been successful in generating the compressed raster.

gdalUtilities::gdalwarp(srcfile = paste0(source_path,"/mask_30.tif"),
                        dstfile = paste0(writing_path,"/mask_30_gdalwarp.tif"),
                        cutline = paste0(source_path,"/amazon.shp"),
                        crop_to_cutline = TRUE,
                        multi = TRUE,
                        wo = "NUM_THREADS = 32",
                        co = "COMPRESS = DEFLATE")
                        # co = c("COMPRESS = DEFLATE","ZLEVEL = 9"))
                        # co COMPRESS = DEFLATE,
                        # co ZLEVEL = 9),
                        # co = "COMPRESS = DEFLATE",
                        # co = ZLEVEL = 9")

Additionally, I would like to use multithread warping implementation. I am including-multi and -wo "NUM_THREADS = 16" (my computer has 32 cores) options, but I also have not been able to decrease the runtime vs. the default -multi option, which uses two cores by default.

Any suggestions for compression and parallelization?

Many thanks in advance.

Body:
1 - COMPRESSION

Please find the solution for the problem of file compression. To be honest, I have already been confronted with the same problem as you and, at the time, I was racking my brains... to finally find the solution which is quite simple (once we know it!): you must not put any spaces (i.e. "COMPRESS=DEFLATE" and not "COMPRESS = DEFLATE")

So, please find below a small reprex.

Reprex

library(gdalUtilities)
library(stars)        # Loaded just to have a '.tif' image for the reprex

# Import a '.tif' image from the 'stars' library
tif <- read_stars(system.file("tif/L7_ETMs.tif", package = "stars"))

# Write the image to disk (in your working directory)
write_stars(tif, "image.tif")

# Size of the image on disk (in bytes)
file.size("image.tif")
#> [1] 2950880

# Compress the image
gdalUtilities::gdalwarp(srcfile = "image.tif",
                        dstfile = "image_gdalwarp.tif",
                        co = "COMPRESS=DEFLATE")

# Size of the compressed image on disk (in bytes)
file.size("image_gdalwarp.tif")
#> [1] 937920                # The image has been successfully compressed.

As @MarkAdler said, there is not much difference between the default compression level (i.e. 6) and level 9. That said, please find below how you should write the code to be able to apply the desired compression level (i.e. still without spaces and in a list):

gdalUtilities::gdalwarp(srcfile = "image.tif",
                        dstfile = "image_gdalwarp_Z9.tif",
                        co = list("COMPRESS=DEFLATE", "ZLEVEL=9"))

file.size("image_gdalwarp_Z9.tif")
#> [1] 901542

Created on 2022-02-09 by the reprex package (v2.0.1)

2 - PARALLELIZATION

For the problem of parallelization on the cores of the processor, you should not use multi = TRUE. Only the argument wo = "NUM_THREADS=4" (always without spaces ;-)) is enough.

Just a clarification, I guess you are confusing the RAM and the number of cores. Usually computers are equipped with a 4 or 8 cores processor. The 32 that you indicate in your code refers to the 32 gigas of RAM that your computer probably has.

Reprex

library(gdalUtilities)
library(stars)

tif <- read_stars(system.file("tif/L7_ETMs.tif", package = "stars"))

write_stars(tif, "image.tif")

file.size("image.tif")
#> [1] 2950880

gdalUtilities::gdalwarp(srcfile = "image.tif",
                        dstfile = "image_gdalwarp_Z9_parallel.tif",
                        co = list("COMPRESS=DEFLATE", "ZLEVEL=9"),
                        wo = "NUM_THREADS=4") # Replace '4' by '8' if your processor has 8 cores

file.size("image_gdalwarp_Z9_parallel.tif")
#> [1] 901542

Created on 2022-02-09 by the reprex package (v2.0.1)


问:
"breakpoint will not currently be hit" in asp.net

Possible Duplicate:

  “The breakpoint will not currently be hit. The source code is different from the original version.” What the hell does this mean?

(A colleague helped me answer this so I will post the question and answer...)

When I try to debug an ASP.NET app, I am getting "The breakpoint will not currently be hit.  The source code is different then the original version" and no matter what I do or how many times I build, kill the web server, kill the browser, restart Visual Studio, etc. it keeps giving me that!

答:
I tried all of the answers above and none worked for me which is possibly due to the issue emanating from more than one cause.

What did work for me was Cleaning the solution and then Rebuilding the solution.

ContentLicense: CC BY-SA 2.5


问:
Unable to access DynamoDb Locally from Kotlin
First I want to say I am pretty new to Kotlin and DynamoDB. I am writing a sample program in Kotlin to play with DynamoDb. I am following the steps in this link: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/examples-dynamodb-tables.html

First I instantiate a client object for making requests to DynamoDB

```<code>val dynamoDbClient = DynamoDbClient { region = "us-east-1" }
</code>```

Then I run the code below to create a new table.

```<code>    suspend fun createNewTable(ddb: DynamoDbClient, newTableName: String, key: String): String {

    val attDef = AttributeDefinition {
        attributeName = key
        attributeType = ScalarAttributeType.S
    }
    val keySchemaVal = KeySchemaElement {
        attributeName = key
        keyType = KeyType.Hash
    }
    val provisionedVal = ProvisionedThroughput {
        readCapacityUnits = 10
        writeCapacityUnits = 10
    }
    val request = CreateTableRequest {
        attributeDefinitions = listOf(attDef)
        keySchema = listOf(keySchemaVal)
        provisionedThroughput = provisionedVal
        tableName = newTableName
    }
    try {
        val response = ddb.createTable(request)
        val tableActive = false
        // Wait until the table is in Active state.
        while (!tableActive) {
            val tableStatus = checkTableStatus(ddb, newTableName)
            if (tableStatus.equals("ACTIVE"))
                break
            delay(500)
        }
        return response.tableDescription?.tableArn.toString()
    } catch (e: DynamoDbException) {
        println("ERROR (DynamoDbException): " + e.message)
    } catch (e: UnknownServiceErrorException) {
        println("ERROR (UnknownServiceErrorException): " + e.message)
    } finally {
        ddb.close()
    }
    return ""
}
</code>```

I can see the table created on my AWS account. However I want to modify my DynamoDbClient to execute the table creation on a local instance of the DynamoDB. I followed the instructions from AWS pages and I installed DynamoDB locally.

Here is how I am running it locally:

```<code>c:\code\dynamodb_local_latest>java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb
Initializing DynamoDB Local with the following configuration:
Port:   8000
InMemory:       false
DbPath: null
SharedDb:       true
shouldDelayTransientStatuses:   false
CorsParams:     *
</code>```

I am able to access the local DynamoDB instance from the aws cli tool.

In order to try accessing the local instance of DynamoDB from the Kotlin code, I changed DynamoDbClient from this:

```<code>val dynamoDbClient = DynamoDbClient { region = "us-east-1" }
</code>```

to this:

```<code>val endpoint = aws.sdk.kotlin.runtime.endpoint.Endpoint( "localhost",
    "http",
    port=8000,
    false,
    null,
    "us-west-1")
val myEndpointResolver = StaticEndpointResolver(endpoint)
val dynamoDbClient = DynamoDbClient {endpointResolver = myEndpointResolver; region ="us-west-1" }
</code>```

However I get the following error:

```<code>Exception in thread "DefaultDispatcher-worker-1" software.amazon.awssdk.crt.http.HttpException: socket connection refused.
    at software.amazon.awssdk.crt.http.HttpClientConnection.onConnectionAcquired(HttpClientConnection.java:85)
</code>```

What is the proper way to resolve that?

Thanks!

答:
You can specify the EndPointResolver for the DynamoDbClient with the address of your DynamoDb local instance.
For example:</p>
```<code>class LocalHostDynamoDb: AwsEndpointResolver {
    override suspend fun resolve(service: String, region: String): AwsEndpoint
        = AwsEndpoint("http://localhost:8000")
}

class MyClient {
    ...
    val dynamoDbClient = DynamoDbClient {
        region = awsRegion
        endpointResolver = LocalHostDynamoDb()
    }
    ...
</code>```

Body:
First I want to say I am pretty new to Kotlin and DynamoDB. I am writing a sample program in Kotlin to play with DynamoDb. I am following the steps in this link: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/examples-dynamodb-tables.html

First I instantiate a client object for making requests to DynamoDB

val dynamoDbClient = DynamoDbClient { region = "us-east-1" }

Then I run the code below to create a new table.

    suspend fun createNewTable(ddb: DynamoDbClient, newTableName: String, key: String): String {

    val attDef = AttributeDefinition {
        attributeName = key
        attributeType = ScalarAttributeType.S
    }
    val keySchemaVal = KeySchemaElement {
        attributeName = key
        keyType = KeyType.Hash
    }
    val provisionedVal = ProvisionedThroughput {
        readCapacityUnits = 10
        writeCapacityUnits = 10
    }
    val request = CreateTableRequest {
        attributeDefinitions = listOf(attDef)
        keySchema = listOf(keySchemaVal)
        provisionedThroughput = provisionedVal
        tableName = newTableName
    }
    try {
        val response = ddb.createTable(request)
        val tableActive = false
        // Wait until the table is in Active state.
        while (!tableActive) {
            val tableStatus = checkTableStatus(ddb, newTableName)
            if (tableStatus.equals("ACTIVE"))
                break
            delay(500)
        }
        return response.tableDescription?.tableArn.toString()
    } catch (e: DynamoDbException) {
        println("ERROR (DynamoDbException): " + e.message)
    } catch (e: UnknownServiceErrorException) {
        println("ERROR (UnknownServiceErrorException): " + e.message)
    } finally {
        ddb.close()
    }
    return ""
}

I can see the table created on my AWS account. However I want to modify my DynamoDbClient to execute the table creation on a local instance of the DynamoDB. I followed the instructions from AWS pages and I installed DynamoDB locally.

Here is how I am running it locally:

c:\code\dynamodb_local_latest>java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb
Initializing DynamoDB Local with the following configuration:
Port:   8000
InMemory:       false
DbPath: null
SharedDb:       true
shouldDelayTransientStatuses:   false
CorsParams:     *

I am able to access the local DynamoDB instance from the aws cli tool.

In order to try accessing the local instance of DynamoDB from the Kotlin code, I changed DynamoDbClient from this:

val dynamoDbClient = DynamoDbClient { region = "us-east-1" }

to this:

val endpoint = aws.sdk.kotlin.runtime.endpoint.Endpoint( "localhost",
    "http",
    port=8000,
    false,
    null,
    "us-west-1")
val myEndpointResolver = StaticEndpointResolver(endpoint)
val dynamoDbClient = DynamoDbClient {endpointResolver = myEndpointResolver; region ="us-west-1" }

However I get the following error:

Exception in thread "DefaultDispatcher-worker-1" software.amazon.awssdk.crt.http.HttpException: socket connection refused.
    at software.amazon.awssdk.crt.http.HttpClientConnection.onConnectionAcquired(HttpClientConnection.java:85)

What is the proper way to resolve that?

Thanks!

Body:
You can specify the EndPointResolver for the DynamoDbClient with the address of your DynamoDb local instance.
For example:

class LocalHostDynamoDb: AwsEndpointResolver {
    override suspend fun resolve(service: String, region: String): AwsEndpoint
        = AwsEndpoint("http://localhost:8000")
}

class MyClient {
    ...
    val dynamoDbClient = DynamoDbClient {
        region = awsRegion
        endpointResolver = LocalHostDynamoDb()
    }
    ...


问:
How to stack promises dynamically?
I have a nested object subprojects with a property of type array: userEstimates holding object(s) Estimate.

I am looking to iterate through userEstimates and push a fetch/promise to an array without calling it.

main (inside async function)

```<code>await subproject.getUserEstimates(true);
let stack = [];

subproject.userEstimates.forEach(ue =>
    stack.push(ue.fetchAvailableRates)
);

console.log(stack);  // 3) [ƒ, ƒ, ƒ]

await Promise.all(stack);

fillForm(subproject);
</code>```

however, attributes on subproject are not defined when calling fillForm

function definition for fetchAvailableRates:

```<code>fetchAvailableRates = () => {
  this.availableRates = fetch(...)
  .then((resp) => {
    if (resp.ok) return resp.json();
    else throw new Error("Something went wrong");
  })
  .then((r) => {
    ...

    return {
      Rate.get(), // returns class
      ...
    };
  })
  .catch((e) => {
    console.error(e);
  });
};
</code>```

EDIT: Changed my wording frrom queue to stack as i'm trying to run all requests at once, and I don't care about order

答:
Your definition for fetchAvailableRates uses this, but when you refer to an object's function without calling it (like stack.push(ue.fetchAvailableRates)), it loses the reference to this and simply becomes a function.

To refer to a function that calls ue.fetchAvailableRates on the ue instance at the time, you should call either () => ue.fetchAvailableRates() or ue.fetchAvailableRates.bind(ue).

That's not the only change you'd need to make―Promise.all() doesn't accept functions, only promises, so the right call is probably to make ue.fetchAvailableRates() return the Promise and add that to the stack.

Title: How to stack promises dynamically?

Body:
I have a nested object subprojects with a property of type array: userEstimates holding object(s) Estimate.

I am looking to iterate through userEstimates and push a fetch/promise to an array without calling it.

main (inside async function)

await subproject.getUserEstimates(true);
let stack = [];

subproject.userEstimates.forEach(ue =>
    stack.push(ue.fetchAvailableRates)
);

console.log(stack);  // 3) [ƒ, ƒ, ƒ]

await Promise.all(stack);

fillForm(subproject);

however, attributes on subproject are not defined when calling fillForm

function definition for fetchAvailableRates:

fetchAvailableRates = () => {
  this.availableRates = fetch(...)
  .then((resp) => {
    if (resp.ok) return resp.json();
    else throw new Error("Something went wrong");
  })
  .then((r) => {
    ...

    return {
      Rate.get(), // returns class
      ...
    };
  })
  .catch((e) => {
    console.error(e);
  });
};

EDIT: Changed my wording frrom queue to stack as i'm trying to run all requests at once, and I don't care about order


问:
I am getting NaN when looping over an array inside an if statement. How can I sum up an array of even and odd nums?
I am trying to extra even and odd numbers of number(10), however when I try to sum the m5 which is an array of even numbers, I get the NaN. How can I add the sum of 5 and 3 in my loop?</p>
```<code>    let number = 10;
let array1 = new Array();
let m5 = new Array();
let m3 = new Array();

let sum5 = 0;
let sum3 = 0;
let arraySum = 0;

for (let i=0; i <= number; i++) {
    array1.push(i)

    if (array1[i] % 5 === 0 && array1[i] < number) {
        m5.push(i); // 0, 5
        sum5 += m5[i];
        console.log(sum5); //Return NaN
    }

    if (array1[i] % 3 === 0) {
        m3.push(i)

    }
    arraySum += array1[i];
}
</code>```

答:
Your problem is an out of bounds issue. You are trying to push the value of i to the m5 array, but the index where this value is put is different. You need to track the index and the values separately. I created a variable j to track the index for the m5 array. You will need to do the same for array m3.

```<code>let number = 10;
let array1 = new Array();
let m5 = new Array();
let m3 = new Array();

let sum5 = 0;
let sum3 = 0;
let arraySum = 0;

for (let i=0, j=0; i <= number; i++) {
    array1.push(i)

    if (array1[i] % 5 === 0 && array1[i] < number) {
        m5.push(i); // 0, 5
        sum5 += m5[j++];
        console.log(sum5); //Return the sum correctly
    }

    if (array1[i] % 3 === 0) {
        m3.push(i)

    }
    arraySum += array1[i];
}
</code>```

Body:
I am trying to extra even and odd numbers of number(10), however when I try to sum the m5 which is an array of even numbers, I get the NaN. How can I add the sum of 5 and 3 in my loop?

    let number = 10;
let array1 = new Array();
let m5 = new Array();
let m3 = new Array();

let sum5 = 0;
let sum3 = 0;
let arraySum = 0;

for (let i=0; i <= number; i++) {
    array1.push(i)

    if (array1[i] % 5 === 0 && array1[i] < number) {
        m5.push(i); // 0, 5
        sum5 += m5[i];
        console.log(sum5); //Return NaN
    }

    if (array1[i] % 3 === 0) {
        m3.push(i)

    }
    arraySum += array1[i];
}

Body:
Your problem is an out of bounds issue. You are trying to push the value of i to the m5 array, but the index where this value is put is different. You need to track the index and the values separately. I created a variable j to track the index for the m5 array. You will need to do the same for array m3.

let number = 10;
let array1 = new Array();
let m5 = new Array();
let m3 = new Array();

let sum5 = 0;
let sum3 = 0;
let arraySum = 0;

for (let i=0, j=0; i <= number; i++) {
    array1.push(i)

    if (array1[i] % 5 === 0 && array1[i] < number) {
        m5.push(i); // 0, 5
        sum5 += m5[j++];
        console.log(sum5); //Return the sum correctly
    }

    if (array1[i] % 3 === 0) {
        m3.push(i)

    }
    arraySum += array1[i];
}


问:
Understanding SendMessage wparam
I am working on an MFC project, which has the following code:

```<code>NMHDR pNMHDR;
pNMHDR.hwndFrom = GetSafeHwnd();
pNMHDR.idFrom = GetDlgCtrlID();
pNMHDR.code = EN_CHANGE;
GetParent()->SendMessage(WM_NOTIFY, (EN_CHANGE << 16) | GetDlgCtrlID(), ( LPARAM ) &pNMHDR);
</code>```

Please help me in understanding what (EN_CHANGE << 16) | GetDlgCtrlID() does.

答:
Per the EN_CHANGE documentation for standard EDIT controls:

wParam

The LOWORD contains the identifier of the edit control. The HIWORD specifies the notification code.

So, the code is taking the constant EN_CHANGE, shifting its bits to the left 16 places, and then OR'ing the bits of the control ID.  Thus, EN_CHANGE ends up in bits 16-31, and the control ID ends up in bits 0-15:

                              WPARAM
-----------------------------------------------------------------
|            EN_CHANGE          |             CtrlID            |
-----------------------------------------------------------------
 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
```
<p>However, the code <em>should</em> be using the <code>MAKEWPARAM()</code> macro instead of shifting + OR'ing bits manually, eg:</p>
```GetParent()->SendMessage(WM_NOTIFY, MAKEWPARAM(GetDlgCtrlID(), EN_CHANGE), (LPARAM) &pNMHDR);
```

Now, that being said, a standard EDIT control sends EN_CHANGE via WM_COMMAND, not WM_NOTIFY.  But a standard windowless RICHEDIT control sends EN_CHANGE via WM_NOTIFY, which carries only the control ID by itself in the wParam parameter. The command ID is carried in the NMHDR struct pointed at by the lParam parameter (except, RICHEDIT uses the CHANGENOTIFY struct, which is unrelated to NMHDR).

So, this code's use of EN_CHANGE is clearly non-standard usage, using a customized parameter scheme.

Title: Understanding SendMessage wparam

Body:
I am working on an MFC project, which has the following code:

NMHDR pNMHDR;
pNMHDR.hwndFrom = GetSafeHwnd();
pNMHDR.idFrom = GetDlgCtrlID();
pNMHDR.code = EN_CHANGE;
GetParent()->SendMessage(WM_NOTIFY, (EN_CHANGE << 16) | GetDlgCtrlID(), ( LPARAM ) &pNMHDR);

Please help me in understanding what (EN_CHANGE << 16) | GetDlgCtrlID() does.

Body:
Per the EN_CHANGE documentation for standard EDIT controls:

wParam

The LOWORD contains the identifier of the edit control. The HIWORD specifies the notification code.

So, the code is taking the constant EN_CHANGE, shifting its bits to the left 16 places, and then OR'ing the bits of the control ID.  Thus, EN_CHANGE ends up in bits 16-31, and the control ID ends up in bits 0-15:

                              WPARAM
-----------------------------------------------------------------
|            EN_CHANGE          |             CtrlID            |
-----------------------------------------------------------------
 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0

However, the code should be using the MAKEWPARAM() macro instead of shifting + OR'ing bits manually, eg:

GetParent()->SendMessage(WM_NOTIFY, MAKEWPARAM(GetDlgCtrlID(), EN_CHANGE), (LPARAM) &pNMHDR);

Now, that being said, a standard EDIT control sends EN_CHANGE via WM_COMMAND, not WM_NOTIFY.  But a standard windowless RICHEDIT control sends EN_CHANGE via WM_NOTIFY, which carries only the control ID by itself in the wParam parameter. The command ID is carried in the NMHDR struct pointed at by the lParam parameter (except, RICHEDIT uses the CHANGENOTIFY struct, which is unrelated to NMHDR).

So, this code's use of EN_CHANGE is clearly non-standard usage, using a customized parameter scheme.


问:
How to create a number of strings based of an array imported from a filetex?
I'm currently very new to python programming and encountered such problem
I have a textfile with strings separated by spaces and by new lines like this:

UR 11199 TPO 0625  APF 1371 ABS 1126 ABT 0475 ASL 0518

Im importing with numpy np.str and is printing out like this

```<code>`
[['UR' '11199']
 ['TPO' '0625']
 ['APF' '1371']
 ['ABS' '1126']
 ['ABT' '0475']
 ['ASL' '0518']]`
</code>```

My thing is that for each line I want to condense the letters with the numbers and make a single string so that the user might type anything beyond, complementing the string like this:

UR11199 OK

How should I do this? tried using hsplit but didnt worked out for me

##EDIT##
Maybe I wasnt clear enough, English isnt my first language.
I need to have different strings for each line, so that a user can input data for each line like

string a == UR11199 abcd

string b == TPO0625 EFGH

答:
You can simply use a list comprehension along with .join() like so:

```<code>import numpy as np

test = np.array([['UR' '11199'],
                 ['TPO' '0625'],
                 ['APF' '1371'],
                 ['ABS' '1126'],
                 ['ABT' '0475'],
                 ['ASL' '0518']])

string = " ".join([l[0] for l in list(test)])
print(string)
</code>```

Output:

```<code>UR11199 TPO0625 APF1371 ABS1126 ABT0475 ASL0518
</code>```

If you want each string separate you could just use:

```<code>stringList = [l[0] for l in list(test)]
print(stringList)
</code>```

Output:

```<code>['UR11199', 'TPO0625', 'APF1371', 'ABS1126', 'ABT0475', 'ASL0518']
</code>```

Print each one like so:

```<code>stringList = [l[0] for l in list(test)]
for c in stringList: print(c)
</code>```

Output:

```<code>UR11199
TPO0625
APF1371
ABS1126
ABT0475
ASL0518
</code>```

In fact it would be even cleaner potentially to use this for printing each separtately:

```<code>for l in list(test): print(l[0])
</code>```

Body:
I'm currently very new to python programming and encountered such problem
I have a textfile with strings separated by spaces and by new lines like this:

UR 11199 TPO 0625  APF 1371 ABS 1126 ABT 0475 ASL 0518

Im importing with numpy np.str and is printing out like this

`
[['UR' '11199']
 ['TPO' '0625']
 ['APF' '1371']
 ['ABS' '1126']
 ['ABT' '0475']
 ['ASL' '0518']]`

My thing is that for each line I want to condense the letters with the numbers and make a single string so that the user might type anything beyond, complementing the string like this:

UR11199 OK

How should I do this? tried using hsplit but didnt worked out for me

##EDIT##
Maybe I wasnt clear enough, English isnt my first language.
I need to have different strings for each line, so that a user can input data for each line like

string a == UR11199 abcd

string b == TPO0625 EFGH

Body:
You can simply use a list comprehension along with .join() like so:

import numpy as np

test = np.array([['UR' '11199'],
                 ['TPO' '0625'],
                 ['APF' '1371'],
                 ['ABS' '1126'],
                 ['ABT' '0475'],
                 ['ASL' '0518']])

string = " ".join([l[0] for l in list(test)])
print(string)

Output:

UR11199 TPO0625 APF1371 ABS1126 ABT0475 ASL0518

If you want each string separate you could just use:

stringList = [l[0] for l in list(test)]
print(stringList)

Output:

['UR11199', 'TPO0625', 'APF1371', 'ABS1126', 'ABT0475', 'ASL0518']

Print each one like so:

stringList = [l[0] for l in list(test)]
for c in stringList: print(c)

Output:

UR11199
TPO0625
APF1371
ABS1126
ABT0475
ASL0518

In fact it would be even cleaner potentially to use this for printing each separtately:

for l in list(test): print(l[0])


问:
Call python code in VBA: Permission Error
Im trying to Run the python code from the VBA (Run_report.xlsm).

My xlsm file and all the py files are in the same directory.

Python code has to work on the data which is itself in the Run_report.xlsm file(again this is the file from where i run VBA code to call the python script).

this is the VBA code:

```<code>Option Explicit
Sub RunPythonScript()

'Declare Variables
Dim objShell As Object
Dim PythonExe, PythonScript, cmd As String

'Create a new Object shell.
Set objShell = VBA.CreateObject("Wscript.Shell")

'Provide file path to Python.exe
'USE TRIPLE QUOTES WHEN FILE PATH CONTAINS SPACES.
PythonExe = """C:\Users\gobro7\AppData\Local\Programs\Python\Python39\python.exe"""
PythonScript = """C:\Users\gobro7\Digital Wholesale - Documents\2. Amazon\Customer Operations_OTC\02. Amazon weekly Report\Amazon weekly automation\VL.py"""

cmd = PythonExe & PythonScript
Debug.Print cmd

'Run the Python Script
objShell.run cmd, 0, True

MsgBox "Finished"

End Sub
</code>```

and this is the start of the python code to see how I defined the path and reading the files.

```<code>import pandas as pd
import numpy as np
import os as os

# Get the user
username = os.getlogin()

# search for directory
directory = r'C:/Users/' + username + '/Digital Wholesale - Documents/2. Amazon/Customer Operations_OTC/02. Amazon weekly Report/Amazon weekly automation/'

# reading SAP extract  files from Run_report.xlsm and creating csv from it

df_1 = pd.read_excel(os.path.join(directory,'Run_report.xlsm'), sheet_name= "weekly",header= None)
df_1 = df_1.drop(df_1.columns[[0,1]], axis=1)
df_1.columns = df_1.loc[3].rename(None)
df_1 = df_1.drop(range(5))

df_1.to_csv(directory + '1.csv', index=False, header= True)

#Read CSV of SAP extract

df_weekly=pd.read_csv(os.path.join(directory,'1.csv'), low_memory=False)
</code>```

VBA code give me very fast msgbox, and python code is not running.

I checked in CMD and it gave me a PermissionError - because the file is Run_report.xlsm is not closed but I have seen that its possible to Call the python script and do some work in the workbook with pandas even its open. Not sure what Im doing wrong here.

答:
This line 'cmd = PythonExe & PythonScript' produces this string:
C:\Users\gobro7\AppData\Local\Programs\Python\Python39\python.exeC:\Users\gobro7\Digital Wholesale - Documents\2. Amazon\Customer Operations_OTC\02. Amazon weekly Report\Amazon weekly automation\VL.py

what you want is: C:\Users\gobro7\AppData\Local\Programs\Python\Python39\python.exe C:\Users\gobro7\Digital Wholesale - Documents\2. Amazon\Customer Operations_OTC\02. Amazon weekly Report\Amazon weekly automation\VL.py

so you need a space between the python command and the location of the python script you are running.

just add a space at the end of the first string:

```<code>"""C:\Users\gobro7\AppData\Local\Programs\Python\Python39\python.exe """
</code>```

Body:
Im trying to Run the python code from the VBA (Run_report.xlsm).

My xlsm file and all the py files are in the same directory.

Python code has to work on the data which is itself in the Run_report.xlsm file(again this is the file from where i run VBA code to call the python script).

this is the VBA code:

Option Explicit
Sub RunPythonScript()

'Declare Variables
Dim objShell As Object
Dim PythonExe, PythonScript, cmd As String

'Create a new Object shell.
Set objShell = VBA.CreateObject("Wscript.Shell")

'Provide file path to Python.exe
'USE TRIPLE QUOTES WHEN FILE PATH CONTAINS SPACES.
PythonExe = """C:\Users\gobro7\AppData\Local\Programs\Python\Python39\python.exe"""
PythonScript = """C:\Users\gobro7\Digital Wholesale - Documents\2. Amazon\Customer Operations_OTC\02. Amazon weekly Report\Amazon weekly automation\VL.py"""

cmd = PythonExe & PythonScript
Debug.Print cmd

'Run the Python Script
objShell.run cmd, 0, True

MsgBox "Finished"

End Sub

and this is the start of the python code to see how I defined the path and reading the files.

import pandas as pd
import numpy as np
import os as os

# Get the user
username = os.getlogin()

# search for directory
directory = r'C:/Users/' + username + '/Digital Wholesale - Documents/2. Amazon/Customer Operations_OTC/02. Amazon weekly Report/Amazon weekly automation/'

# reading SAP extract  files from Run_report.xlsm and creating csv from it

df_1 = pd.read_excel(os.path.join(directory,'Run_report.xlsm'), sheet_name= "weekly",header= None)
df_1 = df_1.drop(df_1.columns[[0,1]], axis=1)
df_1.columns = df_1.loc[3].rename(None)
df_1 = df_1.drop(range(5))

df_1.to_csv(directory + '1.csv', index=False, header= True)

#Read CSV of SAP extract

df_weekly=pd.read_csv(os.path.join(directory,'1.csv'), low_memory=False)

VBA code give me very fast msgbox, and python code is not running.

I checked in CMD and it gave me a PermissionError - because the file is Run_report.xlsm is not closed but I have seen that its possible to Call the python script and do some work in the workbook with pandas even its open. Not sure what Im doing wrong here.

Body:
This line 'cmd = PythonExe & PythonScript' produces this string:
C:\Users\gobro7\AppData\Local\Programs\Python\Python39\python.exeC:\Users\gobro7\Digital Wholesale - Documents\2. Amazon\Customer Operations_OTC\02. Amazon weekly Report\Amazon weekly automation\VL.py

what you want is: C:\Users\gobro7\AppData\Local\Programs\Python\Python39\python.exe C:\Users\gobro7\Digital Wholesale - Documents\2. Amazon\Customer Operations_OTC\02. Amazon weekly Report\Amazon weekly automation\VL.py

so you need a space between the python command and the location of the python script you are running.

just add a space at the end of the first string:

"""C:\Users\gobro7\AppData\Local\Programs\Python\Python39\python.exe """


问:
How do I make separate hover functions work in javascript?
I'm trying to make an image {image 7} appear when hovering over {image 5} while also making {image 8} appear when hovering over {image 6}. It seems to work fine when using the hovering only once, but when I try to do it twice (make different images appear when hovering on different images), it doesn't work. I think that it is because i don't know how to call each set of images on script properly. I'm pretty new at this so any help would be super appreciated. Thank you in advaced!

p.s.
I will use the hover event for diferent elements several times in my webpage, not just twice.

here is my html:

```<code><div class="row1">

<div>
<div class="hover-title">

<a rel="history" href="enlightened-type" class="image-link" id="what" onmouseover="showImg()" onmouseout="hideImg()">{image 5 scale="19"}</a>

</div>

<div class="hover-image">
<div id="what1" style="visibility: hidden;"> {image 7 scale="27"} </div>
</div>

</div>

<div>

<div class="hover-title">
<a rel="history" href="enlightened-type" class="image-link" id="young" onmouseover="showImg()" onmouseout="hideImg()">{image 6 scale="16"}</a>
</div>

<div class="hover-image">
<div id="young1" style="visibility: hidden;">{image 8 scale="12"} </div>
</div>

</div>
</code>```

& this is my script:

```<code><script>

    var hoverImg =
        document.getElementById("what1");
        document.getElementById("young1");

    function showImg(x) {
      hoverImg.style.visibility = "visible";
    }

    function hideImg(x) {
      hoverImg.style.visibility = "hidden";
    }

</script>
</code>```

答:
I think you should add the sender to the event handler and edit the related element

In html you should do this

```<code><a rel="history" href="enlightened-type" class="image-link" id="what" onmouseover="showImg(this)" onmouseout="hideImg(this)">{image 5 scale="19"}</a>
</code>```

And in Js

```<code>function showImg(x) {
  document.getElementById(x.id + "1").style.visibility = "visible";
}

function hideImg(x) {
  document.getElementById(x.id + "1").style.visibility = "hidden";
}
</code>```

Body:
I'm trying to make an image {image 7} appear when hovering over {image 5} while also making {image 8} appear when hovering over {image 6}. It seems to work fine when using the hovering only once, but when I try to do it twice (make different images appear when hovering on different images), it doesn't work. I think that it is because i don't know how to call each set of images on script properly. I'm pretty new at this so any help would be super appreciated. Thank you in advaced!

p.s.
I will use the hover event for diferent elements several times in my webpage, not just twice.

here is my html:

{image 5 scale="19"}

 {image 7 scale="27"}

{image 6 scale="16"}

{image 8 scale="12"}

& this is my script:

Body:
I think you should add the sender to the event handler and edit the related element

In html you should do this

<a rel="history" href="enlightened-type" class="image-link" id="what" onmouseover="showImg(this)" onmouseout="hideImg(this)">{image 5 scale="19"}</a>

And in Js

function showImg(x) {
  document.getElementById(x.id + "1").style.visibility = "visible";
}

function hideImg(x) {
  document.getElementById(x.id + "1").style.visibility = "hidden";
}


问:
Automatically generating JSON script files from file name
I'd like to use a JSON file as a template to create new JSON files with a couple of words in the script that change according to the file name.

For example, say I have a JSON file called word1.json, with a script looking like this:

filename: word1.json

script:

```<code>{
  "name": "word1",
  "annotates": "word1.wav",
  "sampleRate": 44100
}
</code>```

I want to automatically generate a new JSON script for every file name I enter, for example:

filename: word2.json

script:

```<code>{
  "name": "word2",
  "annotates": "word2.wav",
  "sampleRate": 44100
}
</code>```

filename: newword.json

script:

```<code>{
  "name": "newword",
  "annotates": "newword.wav",
  "sampleRate": 44100
}
</code>```

and so on.

Is there some software that allows me to do it? I'm currently editing the JSON files with TextEdit - I'm not a programmer as you can probably tell, but I can use R and can do a little bit of programming there.

EDIT: I'm on MacOS

Many thanks.

答:
I'll probably get some hate here, but since you are new, you are not a programmer, and it's a simple request I say 'Everybody gets one'.

This is a C# program that can be run in any compatible IDE. If you do not have one installed, you can run using LinqPad. It's a quick and simple installation. Open LinqPad and run as C# Program. Press the Play button start the program.

You will need to add the NuGet "Newtonsoft.Json".

This program will create a new directory on your hard drive at C:\jsonfiles. It will repeatedly ask you to enter in a file name until you enter in 'exit' at which point the program will exit. Rerun as needed.

```<code>void Main()
{
    Console.WriteLine("JSON Creator");
    Console.WriteLine("For each entered file name a JSON file will be created. The files will be created at C:/jsonfiles. If the file already exists it will be overwritten.");
    Console.WriteLine("Enter 'exit' to end the program");

    string jsonDirectory = @"C:\jsonfiles";
    CreateBaseDirectory(jsonDirectory);

    string jsonFileName = GetUserInput();

    while (QuitProgram(jsonFileName) == false)
    {
        string fullJsonPath = System.IO.Path.Combine(jsonDirectory, jsonFileName + ".json");

        try
        {
            DeleteExistingFile(fullJsonPath);
        }
        catch (IOException ioException)
        {
            Console.WriteLine("Unable to delete file. The file may be in use. Please close the file or manually delete the file before continuing on.");
            jsonFileName = GetUserInput();
            continue;
        }

        try
        {
            SaveToFile(jsonFileName, fullJsonPath);
        }
        catch (Exception ex)
        {
            Console.WriteLine("There was an issue creating the file. Verify the file does not already exist, the file name is valid, the file is not open, and you have privileges to write to the file system");
            jsonFileName = GetUserInput();
            continue;
        }

        jsonFileName = GetUserInput();
    }

}

private void CreateBaseDirectory(string jsonDirectory)
{
    if (System.IO.Directory.Exists(jsonDirectory) == false)
    {
        System.IO.Directory.CreateDirectory(jsonDirectory);
    }
}

private bool InputIsValid(string input)
{
    return string.IsNullOrWhiteSpace(input) == false;
}

private bool QuitProgram(string input)
{
    string modifiedInput = input?.Trim()?.ToLower();
    return modifiedInput == "quit" || modifiedInput == "q" || modifiedInput == "exit";
}

private string GetUserInput()
{
    Console.WriteLine("Please enter in the JSON file name");
    string input = Console.ReadLine();

    while (InputIsValid(input) == false)
    {
        Console.WriteLine("Please enter valid JSON file name. An empty or space-only file name is not valid.");
    }

    return input.Trim().Replace(".json", "");
}

private void DeleteExistingFile(string fullJsonPath)
{
    if (System.IO.File.Exists(fullJsonPath))
    {
        File.Delete(fullJsonPath);
    }
}

private void SaveToFile(string jsonFileName, string fullJsonPath)
{
    StringBuilder builder = new StringBuilder();
    JsonTemplate template = new JsonTemplate();
    template.name = jsonFileName;
    template.annotates = jsonFileName + ".wav";

    System.IO.File.WriteAllText(fullJsonPath, Newtonsoft.Json.JsonConvert.SerializeObject(template));
    Console.WriteLine(jsonFileName + " has been created");
}

private class JsonTemplate
{
    public string name { get; set; }
    public string annotates { get; set; }
    public int sampleRate { get; set; } = 44100;
}
</code>```

Edit

I just noticed that you are on MacOS. I do not have access nor much knowledge on programming through MacOS. At minimum, you will need to update the location as to where the directory is saved.

Body:
I'd like to use a JSON file as a template to create new JSON files with a couple of words in the script that change according to the file name.

For example, say I have a JSON file called word1.json, with a script looking like this:

filename: word1.json

script:

{
  "name": "word1",
  "annotates": "word1.wav",
  "sampleRate": 44100
}

I want to automatically generate a new JSON script for every file name I enter, for example:

filename: word2.json

script:

{
  "name": "word2",
  "annotates": "word2.wav",
  "sampleRate": 44100
}

filename: newword.json

script:

{
  "name": "newword",
  "annotates": "newword.wav",
  "sampleRate": 44100
}

and so on.

Is there some software that allows me to do it? I'm currently editing the JSON files with TextEdit - I'm not a programmer as you can probably tell, but I can use R and can do a little bit of programming there.

EDIT: I'm on MacOS

Many thanks.

Body:
I'll probably get some hate here, but since you are new, you are not a programmer, and it's a simple request I say 'Everybody gets one'.

This is a C# program that can be run in any compatible IDE. If you do not have one installed, you can run using LinqPad. It's a quick and simple installation. Open LinqPad and run as C# Program. Press the Play button start the program.

You will need to add the NuGet "Newtonsoft.Json".

This program will create a new directory on your hard drive at C:\jsonfiles. It will repeatedly ask you to enter in a file name until you enter in 'exit' at which point the program will exit. Rerun as needed.

void Main()
{
    Console.WriteLine("JSON Creator");
    Console.WriteLine("For each entered file name a JSON file will be created. The files will be created at C:/jsonfiles. If the file already exists it will be overwritten.");
    Console.WriteLine("Enter 'exit' to end the program");

    string jsonDirectory = @"C:\jsonfiles";
    CreateBaseDirectory(jsonDirectory);

    string jsonFileName = GetUserInput();

    while (QuitProgram(jsonFileName) == false)
    {
        string fullJsonPath = System.IO.Path.Combine(jsonDirectory, jsonFileName + ".json");

        try
        {
            DeleteExistingFile(fullJsonPath);
        }
        catch (IOException ioException)
        {
            Console.WriteLine("Unable to delete file. The file may be in use. Please close the file or manually delete the file before continuing on.");
            jsonFileName = GetUserInput();
            continue;
        }

        try
        {
            SaveToFile(jsonFileName, fullJsonPath);
        }
        catch (Exception ex)
        {
            Console.WriteLine("There was an issue creating the file. Verify the file does not already exist, the file name is valid, the file is not open, and you have privileges to write to the file system");
            jsonFileName = GetUserInput();
            continue;
        }

        jsonFileName = GetUserInput();
    }

}

private void CreateBaseDirectory(string jsonDirectory)
{
    if (System.IO.Directory.Exists(jsonDirectory) == false)
    {
        System.IO.Directory.CreateDirectory(jsonDirectory);
    }
}

private bool InputIsValid(string input)
{
    return string.IsNullOrWhiteSpace(input) == false;
}

private bool QuitProgram(string input)
{
    string modifiedInput = input?.Trim()?.ToLower();
    return modifiedInput == "quit" || modifiedInput == "q" || modifiedInput == "exit";
}

private string GetUserInput()
{
    Console.WriteLine("Please enter in the JSON file name");
    string input = Console.ReadLine();

    while (InputIsValid(input) == false)
    {
        Console.WriteLine("Please enter valid JSON file name. An empty or space-only file name is not valid.");
    }

    return input.Trim().Replace(".json", "");
}

private void DeleteExistingFile(string fullJsonPath)
{
    if (System.IO.File.Exists(fullJsonPath))
    {
        File.Delete(fullJsonPath);
    }
}

private void SaveToFile(string jsonFileName, string fullJsonPath)
{
    StringBuilder builder = new StringBuilder();
    JsonTemplate template = new JsonTemplate();
    template.name = jsonFileName;
    template.annotates = jsonFileName + ".wav";

    System.IO.File.WriteAllText(fullJsonPath, Newtonsoft.Json.JsonConvert.SerializeObject(template));
    Console.WriteLine(jsonFileName + " has been created");
}

private class JsonTemplate
{
    public string name { get; set; }
    public string annotates { get; set; }
    public int sampleRate { get; set; } = 44100;
}

Edit

I just noticed that you are on MacOS. I do not have access nor much knowledge on programming through MacOS. At minimum, you will need to update the location as to where the directory is saved.


问:
Select unique characters present in one list in a list of lists
I am trying to filter all the characters that are present in a that are not present in b and c. I want to do this from the list l.

```<code>a<-c("A", "B", "C", "D", "E")
b<-c("A", "E", "I", "O", "U")
c<-c("H", "E", "L", "L", "O")
l<-list(a,b,c)
</code>```

So the answer should be BCD.

答:
you can try the code below</p>
```<code>> d <- table(stack(setNames(l, seq_along(l))))

> row.names(d)[d[, 1] == 1 & rowSums(d) == 1]
[1] "B" "C" "D"
``
</code>```

Body:
I am trying to filter all the characters that are present in a that are not present in b and c. I want to do this from the list l.

a<-c("A", "B", "C", "D", "E")
b<-c("A", "E", "I", "O", "U")
c<-c("H", "E", "L", "L", "O")
l<-list(a,b,c)

So the answer should be BCD.

Body:
you can try the code below

> d <- table(stack(setNames(l, seq_along(l))))

> row.names(d)[d[, 1] == 1 & rowSums(d) == 1]
[1] "B" "C" "D"
``


问:
Creating Dataframes for different clusters
I have a dataset

```<code>Name    System
A       AZ
A       NaN
B       AZ
B       NaN
B       NaN
C       AY
C       AY
D       AZ
E       AY
E       AY
E       NaN
F       AZ
F       AZ
F       NaN
</code>```

Using this dataset, I clustered the dataset based on the number of times "System" is repeated for a particular "Name".

In the above example, Names A, B and D have one "AZ" "Subset" while C, E have two "AY" subsets and F has two AZ so it is a different cluster.
The clustered form is as follows;

```<code>Cluster     Names
AZ          A,B
AY,AY       C,E
AZ,AZ       F
</code>```

Code Used to generate Clusters:

```<code>df1 = (df.dropna(subset=['System'])
         .groupby('Name')['System']
         .agg(','.join)
         .reset_index()
         .groupby('System')['Name']
         .agg(','.join)
         .rename_axis('Cluster')
         .reset_index())
</code>```

Based on this clustered output, I need different dataframes for different clusters:
How can I do this?

Output Example-

Dataframe1-

```<code>Name    System
A       AZ
A       NaN
B       AZ
B       NaN
B       NaN
</code>```

Dataframe2

```<code>Name    System
C       AY
C       AY
E       AY
E       AY
E       NaN
</code>```

Dataframe 3

```<code>Name    System
F       AZ
F       AZ
F       NaN
</code>```

答:
You can adapt my previous answer:

getting the clusters

```<code>clusters = (df.groupby(['Name', 'System'])
   ['System'].agg(Cluster=lambda x: (x.iloc[0], len(x)))
   .droplevel('System').reset_index()
   .groupby('Cluster')['Name'].agg(frozenset)
   .reset_index()
)

#    Cluster       Name
# 0  (AY, 2)     (C, E)
# 1  (AZ, 1)  (A, B, D)
# 2  (AZ, 2)        (F)
</code>```

splitting by group

```<code>groups = df['Name'].map(clusters.explode('Name').set_index('Name')['Cluster'])

for _,d in df.groupby(groups):
    print(d)

#    Name System
# 5     C     AY
# 6     C     AY
# 8     E     AY
# 9     E     AY
# 10    E    NaN
#
#   Name System
# 0    A     AZ
# 1    A    NaN
# 2    B     AZ
# 3    B    NaN
# 4    B    NaN
# 7    D     AZ
#
#    Name System
# 11    F     AZ
# 12    F     AZ
# 13    F    NaN
</code>```

Body:
I have a dataset

Name    System
A       AZ
A       NaN
B       AZ
B       NaN
B       NaN
C       AY
C       AY
D       AZ
E       AY
E       AY
E       NaN
F       AZ
F       AZ
F       NaN

Using this dataset, I clustered the dataset based on the number of times "System" is repeated for a particular "Name".

In the above example, Names A, B and D have one "AZ" "Subset" while C, E have two "AY" subsets and F has two AZ so it is a different cluster.
The clustered form is as follows;

Cluster     Names
AZ          A,B
AY,AY       C,E
AZ,AZ       F

Code Used to generate Clusters:

df1 = (df.dropna(subset=['System'])
         .groupby('Name')['System']
         .agg(','.join)
         .reset_index()
         .groupby('System')['Name']
         .agg(','.join)
         .rename_axis('Cluster')
         .reset_index())

Based on this clustered output, I need different dataframes for different clusters:
How can I do this?

Output Example-

Dataframe1-

Name    System
A       AZ
A       NaN
B       AZ
B       NaN
B       NaN

Dataframe2

Name    System
C       AY
C       AY
E       AY
E       AY
E       NaN

Dataframe 3

Name    System
F       AZ
F       AZ
F       NaN

Body:
You can adapt my previous answer:

getting the clusters

clusters = (df.groupby(['Name', 'System'])
   ['System'].agg(Cluster=lambda x: (x.iloc[0], len(x)))
   .droplevel('System').reset_index()
   .groupby('Cluster')['Name'].agg(frozenset)
   .reset_index()
)

#    Cluster       Name
# 0  (AY, 2)     (C, E)
# 1  (AZ, 1)  (A, B, D)
# 2  (AZ, 2)        (F)

splitting by group

groups = df['Name'].map(clusters.explode('Name').set_index('Name')['Cluster'])

for _,d in df.groupby(groups):
    print(d)

#    Name System
# 5     C     AY
# 6     C     AY
# 8     E     AY
# 9     E     AY
# 10    E    NaN
#
#   Name System
# 0    A     AZ
# 1    A    NaN
# 2    B     AZ
# 3    B    NaN
# 4    B    NaN
# 7    D     AZ
#
#    Name System
# 11    F     AZ
# 12    F     AZ
# 13    F    NaN


问:
Azure Devops: The given cache key has changed in its resolved value between restore and save steps;
I am struggling with one warning which shows in Azure Devops.

```<code>##[warning]The given cache key has changed in its resolved value between restore and save steps;
original key: npm|"Linux"|1hQ5erTp1F2VHRtmwbSGxyt5NqLK6CNbXboa/qqfKiE=
modified key: npm|"Linux"|ckttYS61PMovYKX4+92Nb7dvktCebx236/7P4XqXK6Q=
</code>```

I don't know which step in yaml file would still touch package-lock.json.

DevOps uses following versions of nodejs and npm

```<code>Found tool in cache: node 16.13.2 x64
/opt/hostedtoolcache/node/16.13.2/x64/bin/npm --version
8.1.2
</code>```

My machine

```<code>node -v
v16.13.1
npm -v
8.3.0
</code>```

Any thoughts?

Thanks

Yaml

```<code>trigger:
- master
- develop
- features/*
- hotfix/*

pool:
  vmImage: ubuntu-latest
variables:
  NPM_CONFIG_CACHE: $(Pipeline.Workspace)/.npm
  disable.coverage.autogenerate: 'true'

steps:
- task: gitversion/setup@0
  displayName: "Setup Git versioning"
  inputs:
    versionSpec: '5.x'

- task: gitversion/execute@0
  displayName: "Execute Git versioning"
  inputs:
    useConfigFile: true
    configFilePath: 'GitVersion.yml'

- script: |
    echo '##vso[task.setvariable variable=buildVersion]$(GitVersion.FullSemVer)'
  displayName: 'Set build version variable'

- task: NodeTool@0
  displayName: 'Install Node.js'
  inputs:
    versionSpec: '16.x'

- task: Cache@2
  displayName: 'Restore NPM cache'
  inputs:
    key: 'npm | "$(Agent.OS)" | package-lock.json'
    restoreKeys: |
       npm | "$(Agent.OS)"
    path: $(NPM_CONFIG_CACHE)

- task: Npm@1
  displayName: 'NPM install'
  inputs:
    command: 'custom'
    customCommand: 'ci'

- task: Npm@1
  displayName: 'Lint'
  inputs:
    command: 'custom'
    workingDir: '$(Build.SourcesDirectory)'
    customCommand: 'run lint'

- task: Npm@1
  displayName: 'Build'
  inputs:
    command: 'custom'
    workingDir: '$(Build.SourcesDirectory)'
    customCommand: 'run build'

- task: Npm@1
  displayName: "Run unit tests"
  inputs:
    command: 'custom'
    workingDir: '$(Build.SourcesDirectory)'
    customCommand: 'run test:ci'

- task: Npm@1
  inputs:
    command: 'custom'
    workingDir: '$(Build.SourcesDirectory)'
    customCommand: 'version $(buildVersion) --no-git-tag-version'
  displayName: "Add version"

- task: Npm@1
  displayName: 'Publish to feed'
  inputs:
    command: 'publish'
    publishRegistry: 'useFeed'
    publishFeed: 'c63597a4-6555-4a12-a8dd-0a2a5a0fefe3/afac8330-979d-45e8-a168-8c0a2ed47ac4'
</code>```

package-lock.json

{
    "name": "test",
    "version": "0.1.0",
    "lockfileVersion": 2,
    "requires": true,
    "packages": {
        ...
     }
}
```

答:
After investigation, the step which invokes commands npm version $(buildVersion) --no-git-tag-version was touching package-lock.json

I added additional step which resets the version after Publish to feed

```<code>- task: Npm@1
  displayName: 'Reset version'
  inputs:
    command: 'custom'
    workingDir: '$(Build.SourcesDirectory)'
    customCommand: 'version 0.1.0 --no-git-tag-version'
</code>```

Body:
I am struggling with one warning which shows in Azure Devops.

##[warning]The given cache key has changed in its resolved value between restore and save steps;
original key: npm|"Linux"|1hQ5erTp1F2VHRtmwbSGxyt5NqLK6CNbXboa/qqfKiE=
modified key: npm|"Linux"|ckttYS61PMovYKX4+92Nb7dvktCebx236/7P4XqXK6Q=

I don't know which step in yaml file would still touch package-lock.json.

DevOps uses following versions of nodejs and npm

Found tool in cache: node 16.13.2 x64
/opt/hostedtoolcache/node/16.13.2/x64/bin/npm --version
8.1.2

My machine

node -v
v16.13.1
npm -v
8.3.0

Any thoughts?

Thanks

Yaml

trigger:
- master
- develop
- features/*
- hotfix/*

pool:
  vmImage: ubuntu-latest
variables:
  NPM_CONFIG_CACHE: $(Pipeline.Workspace)/.npm
  disable.coverage.autogenerate: 'true'

steps:
- task: gitversion/setup@0
  displayName: "Setup Git versioning"
  inputs:
    versionSpec: '5.x'

- task: gitversion/execute@0
  displayName: "Execute Git versioning"
  inputs:
    useConfigFile: true
    configFilePath: 'GitVersion.yml'

- script: |
    echo '##vso[task.setvariable variable=buildVersion]$(GitVersion.FullSemVer)'
  displayName: 'Set build version variable'

- task: NodeTool@0
  displayName: 'Install Node.js'
  inputs:
    versionSpec: '16.x'

- task: Cache@2
  displayName: 'Restore NPM cache'
  inputs:
    key: 'npm | "$(Agent.OS)" | package-lock.json'
    restoreKeys: |
       npm | "$(Agent.OS)"
    path: $(NPM_CONFIG_CACHE)

- task: Npm@1
  displayName: 'NPM install'
  inputs:
    command: 'custom'
    customCommand: 'ci'

- task: Npm@1
  displayName: 'Lint'
  inputs:
    command: 'custom'
    workingDir: '$(Build.SourcesDirectory)'
    customCommand: 'run lint'

- task: Npm@1
  displayName: 'Build'
  inputs:
    command: 'custom'
    workingDir: '$(Build.SourcesDirectory)'
    customCommand: 'run build'

- task: Npm@1
  displayName: "Run unit tests"
  inputs:
    command: 'custom'
    workingDir: '$(Build.SourcesDirectory)'
    customCommand: 'run test:ci'

- task: Npm@1
  inputs:
    command: 'custom'
    workingDir: '$(Build.SourcesDirectory)'
    customCommand: 'version $(buildVersion) --no-git-tag-version'
  displayName: "Add version"

- task: Npm@1
  displayName: 'Publish to feed'
  inputs:
    command: 'publish'
    publishRegistry: 'useFeed'
    publishFeed: 'c63597a4-6555-4a12-a8dd-0a2a5a0fefe3/afac8330-979d-45e8-a168-8c0a2ed47ac4'

package-lock.json

{
    "name": "test",
    "version": "0.1.0",
    "lockfileVersion": 2,
    "requires": true,
    "packages": {
        ...
     }
}

Body:
After investigation, the step which invokes commands npm version $(buildVersion) --no-git-tag-version was touching package-lock.json

I added additional step which resets the version after Publish to feed

- task: Npm@1
  displayName: 'Reset version'
  inputs:
    command: 'custom'
    workingDir: '$(Build.SourcesDirectory)'
    customCommand: 'version 0.1.0 --no-git-tag-version'


问:
Removing all options containing text from all select lists on a page load
I'm trying to come up with a javascript/jquery method that will allow me to remove all select list options containing a particular text pattern on page load.

So far I have:

```<code> $('select option:contains(\'foo\')')
</code>```

Which returns me all the elements - how can I remove them? My initial thought was something along the lines of:

```<code> $('select option:contains(\'foo\')').each().remove();
</code>```

But this throws an exception.

Am I approaching this incorrectly?

答:
```<code>$("select option:contains('foo')").remove();
</code>```

jQuery functions automatically work on all selected elements. No need to use each() here.

Body:
I'm trying to come up with a javascript/jquery method that will allow me to remove all select list options containing a particular text pattern on page load.

So far I have:

 $('select option:contains(\'foo\')')

Which returns me all the elements - how can I remove them? My initial thought was something along the lines of:

 $('select option:contains(\'foo\')').each().remove();

But this throws an exception.

Am I approaching this incorrectly?

Body:
$("select option:contains('foo')").remove();

jQuery functions automatically work on all selected elements. No need to use each() here.


问:
json dynamic node parse in C#
I am receiving json with dynamic one node based on sector like "DEL-BOM", "NYC-BOM".
trying to parse but body getting null.
I just add Dictionary and key as node and class as value but still not getting values in DeserializeObject.

```<code>{
    "fareRule": {
        "DEL-BOM": {
            "fr": {
                "NO_SHOW": {
                    "DEFAULT": {
                        "policyInfo": "If Cancelled within 6 hrs of scheduled departure only statutory taxes will be Refunded."
                    }
                },
                "DATECHANGE": {
                    "DEFAULT": {
                        "amount": 3000.00,
                        "additionalFee": 50.00,
                        "policyInfo": "__nls__Changes permitted 06 Hrs before scheduled departure  __nls__ Within 06-96 hrs Rs 3,000 + Fare Difference __nls__ Before 96 hrs Rs 2,500 + Fare Difference",
                        "fcs": {
                            "CRFT": 9.00,
                            "ARF": 3000.00,
                            "ARFT": 150.00,
                            "CRF": 50.00
                        }
                    }
                },
                "CANCELLATION": {
                    "DEFAULT": {
                        "amount": 3500.00,
                        "additionalFee": 50.00,
                        "policyInfo": "__nls__Cancellation permitted 06 Hrs before scheduled departure __nls__ Within 06-96 hrs Rs 3,500 __nls__ Before 96 hrs Rs 3,000",
                        "fcs": {
                            "ACFT": 175.00,
                            "CCFT": 9.00,
                            "ACF": 3500.00,
                            "CCF": 50.00
                        }
                    }
                },
                "SEAT_CHARGEABLE": {
                    "DEFAULT": {
                        "policyInfo": "Paid Seat"
                    }
                }
            }
        }
    },
    "status": {
        "success": true,
        "httpStatus": 200
    }
}
</code>```

this is my class

```<code>public class Response
    {
        public Dictionary<string, Fr> fareRule { get; set; }
        public Status status { get; set; }
    }

    public class DEFAULT
    {
        public string policyInfo { get; set; }
        public double amount { get; set; }
        public double additionalFee { get; set; }
        public Fcs fcs { get; set; }
    }

    public class NOSHOW
    {
        public DEFAULT DEFAULT { get; set; }
    }

    public class Fcs
    {
        public double ARFT { get; set; }
        public double ARF { get; set; }
        public double CRFT { get; set; }
        public double CRF { get; set; }
        public double CCF { get; set; }
        public double ACF { get; set; }
        public double CCFT { get; set; }
        public double ACFT { get; set; }
    }

    public class DATECHANGE
    {
        public DEFAULT DEFAULT { get; set; }
    }

    public class CANCELLATION
    {
        public DEFAULT DEFAULT { get; set; }
    }

    public class SEATCHARGEABLE
    {
        public DEFAULT DEFAULT { get; set; }
    }

    public class Fr
    {
        public NOSHOW NO_SHOW { get; set; }
        public DATECHANGE DATECHANGE { get; set; }
        public CANCELLATION CANCELLATION { get; set; }
        public SEATCHARGEABLE SEAT_CHARGEABLE { get; set; }
    }

    public class Sector
    {
        public Fr fr { get; set; }
    }

    public class FareRule
    {

        public Sector sector { get; set; }
    }

    public class Status
    {
        public bool success { get; set; }
        public int httpStatus { get; set; }
    }
</code>```

I have tried based on Parse dynamic JSON

Key is converting but body or value is null.

答:
try this, it was tested and working properly

```<code>var jsonDeserialized = JsonConvert.DeserializeObject<Data>(json);
</code>```

classes

```<code>public class Data
{
    public Dictionary<string,Dictionary<string, Mode>> fareRule { get; set; }
    public Status status { get; set; }
}

public class Status
{
    public bool? success { get; set; }
    public int? httpStatus { get; set; }
}

public class DEFAULT
{
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public string policyInfo { get; set; }
     [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public double? amount { get; set; }
     [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public double? additionalFee { get; set; }
     [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public Dictionary<string,double?> fcs { get; set; }
}

public class NOSHOW
{
    public DEFAULT DEFAULT { get; set; }
}

public class DATECHANGE
{
    public DEFAULT DEFAULT { get; set; }
}

public class CANCELLATION
{
    public DEFAULT DEFAULT { get; set; }
}

public class SEATCHARGEABLE
{
    public DEFAULT DEFAULT { get; set; }
}

public class Mode
{
    public NOSHOW NO_SHOW { get; set; }
    public DATECHANGE DATECHANGE { get; set; }
    public CANCELLATION CANCELLATION { get; set; }
    public SEATCHARGEABLE SEAT_CHARGEABLE { get; set; }
}
</code>```

Title: json dynamic node parse in C#

Body:
I am receiving json with dynamic one node based on sector like "DEL-BOM", "NYC-BOM".
trying to parse but body getting null.
I just add Dictionary and key as node and class as value but still not getting values in DeserializeObject.

{
    "fareRule": {
        "DEL-BOM": {
            "fr": {
                "NO_SHOW": {
                    "DEFAULT": {
                        "policyInfo": "If Cancelled within 6 hrs of scheduled departure only statutory taxes will be Refunded."
                    }
                },
                "DATECHANGE": {
                    "DEFAULT": {
                        "amount": 3000.00,
                        "additionalFee": 50.00,
                        "policyInfo": "__nls__Changes permitted 06 Hrs before scheduled departure  __nls__ Within 06-96 hrs Rs 3,000 + Fare Difference __nls__ Before 96 hrs Rs 2,500 + Fare Difference",
                        "fcs": {
                            "CRFT": 9.00,
                            "ARF": 3000.00,
                            "ARFT": 150.00,
                            "CRF": 50.00
                        }
                    }
                },
                "CANCELLATION": {
                    "DEFAULT": {
                        "amount": 3500.00,
                        "additionalFee": 50.00,
                        "policyInfo": "__nls__Cancellation permitted 06 Hrs before scheduled departure __nls__ Within 06-96 hrs Rs 3,500 __nls__ Before 96 hrs Rs 3,000",
                        "fcs": {
                            "ACFT": 175.00,
                            "CCFT": 9.00,
                            "ACF": 3500.00,
                            "CCF": 50.00
                        }
                    }
                },
                "SEAT_CHARGEABLE": {
                    "DEFAULT": {
                        "policyInfo": "Paid Seat"
                    }
                }
            }
        }
    },
    "status": {
        "success": true,
        "httpStatus": 200
    }
}

this is my class

public class Response
    {
        public Dictionary<string, Fr> fareRule { get; set; }
        public Status status { get; set; }
    }

    public class DEFAULT
    {
        public string policyInfo { get; set; }
        public double amount { get; set; }
        public double additionalFee { get; set; }
        public Fcs fcs { get; set; }
    }

    public class NOSHOW
    {
        public DEFAULT DEFAULT { get; set; }
    }

    public class Fcs
    {
        public double ARFT { get; set; }
        public double ARF { get; set; }
        public double CRFT { get; set; }
        public double CRF { get; set; }
        public double CCF { get; set; }
        public double ACF { get; set; }
        public double CCFT { get; set; }
        public double ACFT { get; set; }
    }

    public class DATECHANGE
    {
        public DEFAULT DEFAULT { get; set; }
    }

    public class CANCELLATION
    {
        public DEFAULT DEFAULT { get; set; }
    }

    public class SEATCHARGEABLE
    {
        public DEFAULT DEFAULT { get; set; }
    }

    public class Fr
    {
        public NOSHOW NO_SHOW { get; set; }
        public DATECHANGE DATECHANGE { get; set; }
        public CANCELLATION CANCELLATION { get; set; }
        public SEATCHARGEABLE SEAT_CHARGEABLE { get; set; }
    }

    public class Sector
    {
        public Fr fr { get; set; }
    }

    public class FareRule
    {

        public Sector sector { get; set; }
    }

    public class Status
    {
        public bool success { get; set; }
        public int httpStatus { get; set; }
    }

I have tried based on Parse dynamic JSON

Key is converting but body or value is null.

Body:
try this, it was tested and working properly

var jsonDeserialized = JsonConvert.DeserializeObject<Data>(json);

classes

public class Data
{
    public Dictionary<string,Dictionary<string, Mode>> fareRule { get; set; }
    public Status status { get; set; }
}

public class Status
{
    public bool? success { get; set; }
    public int? httpStatus { get; set; }
}

public class DEFAULT
{
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public string policyInfo { get; set; }
     [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public double? amount { get; set; }
     [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public double? additionalFee { get; set; }
     [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public Dictionary<string,double?> fcs { get; set; }
}

public class NOSHOW
{
    public DEFAULT DEFAULT { get; set; }
}

public class DATECHANGE
{
    public DEFAULT DEFAULT { get; set; }
}

public class CANCELLATION
{
    public DEFAULT DEFAULT { get; set; }
}

public class SEATCHARGEABLE
{
    public DEFAULT DEFAULT { get; set; }
}

public class Mode
{
    public NOSHOW NO_SHOW { get; set; }
    public DATECHANGE DATECHANGE { get; set; }
    public CANCELLATION CANCELLATION { get; set; }
    public SEATCHARGEABLE SEAT_CHARGEABLE { get; set; }
}