问:
How to "bootstrap" parent POM in GCP Artifact Registry
I followed the instructions to configure a maven client to use an Artifact Registry. I was able to deploy my root pom to it successfully; however, when I have a separate project that inherits from that root pom, it fails to build because it doesn't know where to find the root pom. This makes sense: the child project has no way of knowing that the parent pom is to be found in a random Artifact Registry repo. What is the standard practice for this?

What i've done before is in every programmer's computer, configure the <repository> in their settings.xml but this doesn't scale well + it needs human intervention + it's very cumbersome when dealing with CI since now you need to configure the settings.xml of the build robot. Considering there's so many CI systems nowadays I imagine there's a convention by now. Is there a better way to accomplish this? some way that's committed in the repo and where everything works right out of the box? git clone... mvn package... done. I ask specifically about Artifact Registry because it doesn't use a static username/password but uses the maven wagon to authenticate

One potential solution is to not put the <repository> in the root pom but in every project's pom but that leads to a lot of duplication since the config + the wagon is pretty verbose

答:
Assuming your child and parent share a common .mvn/ folder, you can add:

.mvn/extensions.xml:

<extensions xmlns="http://maven.apache.org/EXTENSIONS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/EXTENSIONS/1.0.0 http://maven.apache.org/xsd/core-extensions-1.0.0.xsd">

    <extension>
        <groupId>com.google.cloud.artifactregistry</groupId>
        <artifactId>artifactregistry-maven-wagon</artifactId>
        <version>2.1.1</version>
    </extension>

    <extension>
        <groupId>com.github.gzm55.maven</groupId>
        <artifactId>project-settings-extension</artifactId>
        <version>0.1.1</version>
    </extension>
</extensions>
```
<p>.mvn/settings.xml (don't forget to use your actual artifactregistry URL):</p>
<pre class="lang-xml prettyprint-override"><code><settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd">
  <profiles>
    <profile>
      <id>default</id>
      <activation>
        <activeByDefault>true</activeByDefault>
      </activation>
      <repositories>
        <!--This has to be declared here in order to allow child modules to be able to fetch older parent POMs.-->
        <repository>
          <id>cloud-artifacts</id>
          <url>artifactregistry://...</url> <!--use actual full URL here-->
          <releases>
            <enabled>true</enabled>
          </releases>
          <snapshots>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
          </snapshots>
        </repository>
      </repositories>
    </profile>
  </profiles>
</settings>
</code>```

The repository in settings.xml informs Maven to consider that location when searching for artifacts. The artifactregistry-maven-wagon extension allows Maven to access artifacts via the artifactregistry:// protocol.

The other extension (com.github.gzm55.maven) causes Maven to look at the project-specific settings.xml file (you could also just pass --settings=<path to file>, perhaps in .mvn/maven.config, but that would override any user settings).

Body:
Assuming your child and parent share a common .mvn/ folder, you can add:

.mvn/extensions.xml:

<extensions xmlns="http://maven.apache.org/EXTENSIONS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/EXTENSIONS/1.0.0 http://maven.apache.org/xsd/core-extensions-1.0.0.xsd">
    <!--This has to be declared here in order to allow child modules to be able to fetch older parent POMs.-->
    <extension>
        <groupId>com.google.cloud.artifactregistry</groupId>
        <artifactId>artifactregistry-maven-wagon</artifactId>
        <version>2.1.1</version>
    </extension>
    <!--project-settings-extension allows using project-specific .mvn/settings.xml-->
    <extension>
        <groupId>com.github.gzm55.maven</groupId>
        <artifactId>project-settings-extension</artifactId>
        <version>0.1.1</version>
    </extension>
</extensions>

.mvn/settings.xml (don't forget to use your actual artifactregistry URL):

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd">
  <profiles>
    <profile>
      <id>default</id>
      <activation>
        <activeByDefault>true</activeByDefault>
      </activation>
      <repositories>
        <!--This has to be declared here in order to allow child modules to be able to fetch older parent POMs.-->
        <repository>
          <id>cloud-artifacts</id>
          <url>artifactregistry://...</url> <!--use actual full URL here-->
          <releases>
            <enabled>true</enabled>
          </releases>
          <snapshots>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
          </snapshots>
        </repository>
      </repositories>
    </profile>
  </profiles>
</settings>

The repository in settings.xml informs Maven to consider that location when searching for artifacts. The artifactregistry-maven-wagon extension allows Maven to access artifacts via the artifactregistry:// protocol.

The other extension (com.github.gzm55.maven) causes Maven to look at the project-specific settings.xml file (you could also just pass --settings=<path to file>, perhaps in .mvn/maven.config, but that would override any user settings).


来源: stackexchange

问:
How to plot 'log' and 'first difference of log' in R?
This might sound easy question to some people, but I am a beginner in R and I couldn't find an answer to my problem.

So, basically, I have uploaded my excel data into R. I have three variables. The first variable is in the format of the date (1994-01-03), the other two are just numbers.

dataset looks like this

I have plotted my main graphs using this command:

plot(dataset$observation_date,dataset$interest_rate,t="l", xlab = "Observation date" , ylab = "Interest Rate")

Now I need to plot a graph of the "log" and "first difference of log" of two variables.

Big thanks in advance for any help!!

答:
1. Just the log.

From help("plot.default"):

log

a character string which contains "x" if the x axis is to be logarithmic, "y" if the y axis is to be logarithmic and "xy" or "yx" if both axes are to be logarithmic.

And here is a reproducible example.

plot(1:10, 1:10,
     type = "l", xlab = "Observation date" , ylab = "Interest Rate",
     log = "y")
```
<p><img src="https://i.imgur.com/D0PEL3D.png" alt="" /></p>
<p><sup>Created on 2022-02-09 by the reprex package (v2.0.1)</sup></p>
<h2>2. log and diff log</h2>
<p>To plot both the log and the first differences of the log, here are two ways.</p>
<pre class="lang-r prettyprint-override"><code>plot(1:10, 1:10,
     type = "l", xlab = "Observation date" , ylab = "Interest Rate",
     xlim = c(0, 10), ylim = c(0, 10))
lines(1:10, log(1:10))
lines(2:10, diff(log(1:10)))
</code>```

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

3. log and diff log (cont.)

The second way is more clear if an auxiliary function to compute the diff logs is defined.

dl <- function(x) c(0, diff(log(x)))
plot(1:10, 1:10,
     type = "l", xlab = "Observation date" , ylab = "Interest Rate",
     xlim = c(0, 10), ylim = c(0, 10))
curve(log, from = 1, to = 10, add = TRUE)
curve(dl, from = 1, to = 10, add = TRUE)
```

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

ContentLicense: CC BY-SA 4.0

Body:
1. Just the log.

From help("plot.default"):

log

a character string which contains "x" if the x axis is to be logarithmic, "y" if the y axis is to be logarithmic and "xy" or "yx" if both axes are to be logarithmic.

And here is a reproducible example.

plot(1:10, 1:10,
     type = "l", xlab = "Observation date" , ylab = "Interest Rate",
     log = "y")

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

2. log and diff log

To plot both the log and the first differences of the log, here are two ways.

plot(1:10, 1:10,
     type = "l", xlab = "Observation date" , ylab = "Interest Rate",
     xlim = c(0, 10), ylim = c(0, 10))
lines(1:10, log(1:10))
lines(2:10, diff(log(1:10)))

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

3. log and diff log (cont.)

The second way is more clear if an auxiliary function to compute the diff logs is defined.

dl <- function(x) c(0, diff(log(x)))
plot(1:10, 1:10,
     type = "l", xlab = "Observation date" , ylab = "Interest Rate",
     xlim = c(0, 10), ylim = c(0, 10))
curve(log, from = 1, to = 10, add = TRUE)
curve(dl, from = 1, to = 10, add = TRUE)

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


问:
IntelliSense Problem in VisualStudio code
i have a problem with Visual Studio Code for Mac OS

Since my small industry where i work, decided one week ago to change from Windows to Apple problems started.
I installed VS code in my Apple laptop but when i started to programming, i saw that if i make a Syntax error, the IDE doesn't highlight it (i write programs in C).

For example if i write: println("hello word") without ; VS doesn't show a red underline and a message (for example "Syntax error missing ;")

i searched on internet, and i found that is a problem of "IntelliSense" i think. I also tried some solutions, but without any result.
thanks for your answers

答: Setting up VS code for C / C++ on mac is a bit of a pain. I've found this page from MS to give a thorough run through on getting setting up, and then you can also follow this guide which will take you through setting up project configurations and in your case intellisense.</p>


问:
How do you find the max in a particular cell across all sheets and return a different cell?
I have been able to return the max value of F1 from all sheets by using this formula located in cell G13:

```<code>G13=MAX(ABC:XYZ!F1)
</code>```

Now I also want to return the value of A5 from the sheet where the MAX was found in G13.

How do I write the formula for that?

TIA.

答:
Create a named range that includes all the sheet names.

Then using INDEX/MATCH and INDIRECT inside MAX and SUMIFS we get:

```<code>=INDEX(INDIRECT("'"&TRANSPOSE(Sheets)&"'!A5"),MATCH(MAX(INDIRECT("'"&TRANSPOSE(Sheets)&"'!f1")),SUMIF(INDIRECT("'"&TRANSPOSE(Sheets)&"'!F1"),"<>"),0))
</code>```

Depending on one's version one may need to use Ctrl-Shift-Enter instead of Enter.

The HERE is coming from Sheet2!A5 where Sheet2!F1 has 1000 in it.  All other sheets have 1 in F1

Body:
I have been able to return the max value of F1 from all sheets by using this formula located in cell G13:

G13=MAX(ABC:XYZ!F1)

Now I also want to return the value of A5 from the sheet where the MAX was found in G13.

How do I write the formula for that?

TIA.

Body:
Create a named range that includes all the sheet names.

Then using INDEX/MATCH and INDIRECT inside MAX and SUMIFS we get:

=INDEX(INDIRECT("'"&TRANSPOSE(Sheets)&"'!A5"),MATCH(MAX(INDIRECT("'"&TRANSPOSE(Sheets)&"'!f1")),SUMIF(INDIRECT("'"&TRANSPOSE(Sheets)&"'!F1"),"<>"),0))

Depending on one's version one may need to use Ctrl-Shift-Enter instead of Enter.

The HERE is coming from Sheet2!A5 where Sheet2!F1 has 1000 in it.  All other sheets have 1 in F1


问:
How to refer environment variable inside GitHub workflow?
I'm trying to read the the GitHub environment variable inside the request json payload while making the curl request but somewhat these variables are not resolving and it gives an error the values I'm trying to read are KEY_VAULT and ACR_PATH:SNAPSHOT_VERSION inside the flow create container web. I've attached the GitHub workflow sample below.</p>
```<code>name: Pull Request

on:
  pull_request:
    types: [review_requested]

env:

  KEY_VAULT: "some vault"
  SNAPSHOT_VERSION: ${{ format('{0}-SNAPSHOT', github.event.number) }}
  GITHUB_ISSUE_NUMBER: ${{ github.event.number }}
  GITHUB_REPO: ${{ github.event.repository.name }}
  DEPLOYMENT_NOTIFICATION_URL_TOKEN: ${{ secrets.SOME_TOKEN }}
  DEPLOYMENT_URL_TOKEN: 123
  ENVIRONMENT: sandbox
jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2
        with:
          fetch-depth: 0

      - name: Docker login
        #if: steps.pr-label.outputs.result == 'true'
        uses: azure/docker-login@v1
        with:
          login-server: acr-login.com
          username: user
          password: pwd

      - name: Publish Snapshot To ACR
        #if: steps.pr-label.outputs.result == 'true'
        run: |
          echo steps.pr-label.outputs.result
          echo Publishing to $ACR_PATH:$SNAPSHOT_VERSION
          docker build . -t $ACR_PATH:$SNAPSHOT_VERSION
          docker push $ACR_PATH:$SNAPSHOT_VERSION

      - name: Create Container Web
          #if: steps.pr-label.outputs.result == 'true'
        run: |
            AUTH_HEADER="Authorization: token $DEPLOYMENT_URL_TOKEN"
            CONTAINER_WEB_NAME="CONATINER"
            PROJECT_NAME="tirumalesh-automate"
            REGION="US"
         URL="https://abcd.com/$REGION/$PROJECT_NAME/container-web/$CONTAINER_WEB_NAME"
            PAYLOAD='{
                                 "spec": {
                                   "image": "${{env.ACR_PATH}}:${{env.SNAPSHOT_VERSION}}",
                                   "secrets": {
                                     "key_vaults": [
                                       {
                                         "name": "${{env.KEY_VAULT}}",
                                         "secrets": [
                                           {
                                             "name": "mysql-pwd",
                                             "environment_variable": "mysql_pwd"
                                           },

                                         ]
                                       }
                                     ],
                                   },
                                 }
                                 }'
            curl --location --request PUT 'https://abcd/us/projects/tirumalesh-automate/resources/container-web/configuration-service' \
            --header "$AUTH_HEADER" \
            --header 'Content-Type: application/json' \
                        --data-raw "$PAYLOAD"
</code>```

答:
You have single quotes around PAYLOAD, which means that it will take the string literally and not expand anything.

Use double quotes and escape the quotes.

PAYLOAD="{
    \"spec\": {
        \"image\": \"${{env.ACR_PATH}}:${{env.SNAPSHOT_VERSION}}\",
        \"secrets\": {
            \"key_vaults\": [
                {
                    \"name\": \"${{env.KEY_VAULT}}\",
                    \"secrets\": [
                    {
                        \"name\": \"mysql-pwd\",
                        \"environment_variable\": \"mysql_pwd\"
                    },

                    ]
                }
            ],
        },
    }
}"
curl --location --request PUT 'https://abcd/us/projects/tirumalesh-automate/resources/container-web/configuration-service' \
--header "$AUTH_HEADER" \
--header 'Content-Type: application/json' \
--data-raw "$PAYLOAD"
```

Body:
I'm trying to read the the GitHub environment variable inside the request json payload while making the curl request but somewhat these variables are not resolving and it gives an error the values I'm trying to read are KEY_VAULT and ACR_PATH:SNAPSHOT_VERSION inside the flow create container web. I've attached the GitHub workflow sample below.

name: Pull Request

on:
  pull_request:
    types: [review_requested]

env:

  KEY_VAULT: "some vault"
  SNAPSHOT_VERSION: ${{ format('{0}-SNAPSHOT', github.event.number) }}
  GITHUB_ISSUE_NUMBER: ${{ github.event.number }}
  GITHUB_REPO: ${{ github.event.repository.name }}
  DEPLOYMENT_NOTIFICATION_URL_TOKEN: ${{ secrets.SOME_TOKEN }}
  DEPLOYMENT_URL_TOKEN: 123
  ENVIRONMENT: sandbox
jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2
        with:
          fetch-depth: 0

      - name: Docker login
        #if: steps.pr-label.outputs.result == 'true'
        uses: azure/docker-login@v1
        with:
          login-server: acr-login.com
          username: user
          password: pwd

      - name: Publish Snapshot To ACR
        #if: steps.pr-label.outputs.result == 'true'
        run: |
          echo steps.pr-label.outputs.result
          echo Publishing to $ACR_PATH:$SNAPSHOT_VERSION
          docker build . -t $ACR_PATH:$SNAPSHOT_VERSION
          docker push $ACR_PATH:$SNAPSHOT_VERSION

      - name: Create Container Web
          #if: steps.pr-label.outputs.result == 'true'
        run: |
            AUTH_HEADER="Authorization: token $DEPLOYMENT_URL_TOKEN"
            CONTAINER_WEB_NAME="CONATINER"
            PROJECT_NAME="tirumalesh-automate"
            REGION="US"
         URL="https://abcd.com/$REGION/$PROJECT_NAME/container-web/$CONTAINER_WEB_NAME"
            PAYLOAD='{
                                 "spec": {
                                   "image": "${{env.ACR_PATH}}:${{env.SNAPSHOT_VERSION}}",
                                   "secrets": {
                                     "key_vaults": [
                                       {
                                         "name": "${{env.KEY_VAULT}}",
                                         "secrets": [
                                           {
                                             "name": "mysql-pwd",
                                             "environment_variable": "mysql_pwd"
                                           },

                                         ]
                                       }
                                     ],
                                   },
                                 }
                                 }'
            curl --location --request PUT 'https://abcd/us/projects/tirumalesh-automate/resources/container-web/configuration-service' \
            --header "$AUTH_HEADER" \
            --header 'Content-Type: application/json' \
                        --data-raw "$PAYLOAD"


问:
Vue : how to change background color for each page
i have code below in Vue js below and i wanted to have different background color in each page, but whenever i do that i should go to App.vue and change color from their for all pages cuz the main container here that includes all pages is App , is there a way to change background color for only one page ? thanks in advance

<template>

 Ask Question

      <b-form-input
        type="text"
        name="title"
        v-model="posts.title"
        placeholder="Title"
        required

      Post

</template>

```
</div>
</div>
</p>
<p>App.vue</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><template>

<div class="app">
<Header />
<router-view />
</div>

</template>

<script>
import Header from './components/Header';

export default {
  name: 'App',

  components: {
    Header,
  },

  data: () => ({
    //
  }),
};

</script>
<style>
.app{
  width: auto;

}
</style></code>```

答:
You can simply add class and add a background color in the component's scoped style:

```<code><template>
  <main class="crypto_bg">
    ...
  </main>
</template>

<style scoped>
 .crypto_bg {
   background: #1d2444;
 }
</style>
</code>```

But for more.
In my case, I have 2 pages: crypto, and stock, controlled by a toggler in the Header.vue.
The stock page is like the home/default page, my unique page with a different background for header and body is the crypto page.

App.vue:

```<code><template>
  <div id="app">
    <Header @stock="showStockPlatform" @crypto="showCryptoPlatform" />

    <Main v-if="stockMainShown" />

    <CryptoMain v-if="cryptoMainShown" />

    <router-view />
  </div>
</template>

<script>
  data() {
    return {
        stockMainShown: true,
        cryptoMainShown: false,
    };
  },
  methods: {
    showStockPlatform: function (platform) {
        this.stockMainShown = platform;
    },

    showCryptoPlatform: function (platform) {
        this.cryptoMainShown = platform;
    },
  },
</script>
</code>```

In my Header.vue where I'm toggling to show this unique page/component:

Emit an event from your Header.vue to update the App.vue, setting a variable for this unique page to be true e.g stockMainShown: true, cryptoMainShown: false, as seen above.

```<code><script>
 export default {
  data() {
    return {
        stockPlat: true,
    };
  },
  methods: {
    showPlatform(platform) {
        if (platform.toLowerCase() == "stocks") {

            this.$emit("stock", true);
            this.$emit("crypto", false);

            this.stockPlat = true;
        } else if (platform.toLowerCase() == "crypto") {

            this.$emit("stock", false);
            this.$emit("crypto", true);

            this.stockPlat = !this.stockPlat;
        }
    },
  },
 };
</script>
</code>```

Inside the Template tag, change the header background color if it's this unique page, i.e where stockPlat is false as seen below

```<code><template>
  <div :class="[stockPlat ? 'bgDark' : 'bgBlue']">
    ...
  </div>
</template>
</code>```

Inside the Style tag, use this

```<code><style>
  .bgDark {
    background-color: black;
  }
  .bgBlue {
    background-color: blue;
  }
</style>
</code>```

Reference:
https://v2.vuejs.org/v2/guide/class-and-style.html
https://v2.vuejs.org/v2/guide/components-custom-events.html

Body:
i have code below in Vue js below and i wanted to have different background color in each page, but whenever i do that i should go to App.vue and change color from their for all pages cuz the main container here that includes all pages is App , is there a way to change background color for only one page ? thanks in advance

<template>

 Ask Question

      <b-form-input
        type="text"
        name="title"
        v-model="posts.title"
        placeholder="Title"
        required

      Post

</template>

App.vue

<template>

<router-view />

</template>

Body:
You can simply add class and add a background color in the component's scoped style:

<template>
  <main class="crypto_bg">
    ...
  </main>
</template>

<style scoped>
 .crypto_bg {
   background: #1d2444;
 }
</style>

But for more.
In my case, I have 2 pages: crypto, and stock, controlled by a toggler in the Header.vue.
The stock page is like the home/default page, my unique page with a different background for header and body is the crypto page.

App.vue:

<template>
  <div id="app">
    <Header @stock="showStockPlatform" @crypto="showCryptoPlatform" />

    <Main v-if="stockMainShown" />

    <CryptoMain v-if="cryptoMainShown" />

    <router-view />
  </div>
</template>

<script>
  data() {
    return {
        stockMainShown: true,
        cryptoMainShown: false,
    };
  },
  methods: {
    showStockPlatform: function (platform) {
        this.stockMainShown = platform;
    },

    showCryptoPlatform: function (platform) {
        this.cryptoMainShown = platform;
    },
  },
</script>

In my Header.vue where I'm toggling to show this unique page/component:

Emit an event from your Header.vue to update the App.vue, setting a variable for this unique page to be true e.g stockMainShown: true, cryptoMainShown: false, as seen above.

<script>
 export default {
  data() {
    return {
        stockPlat: true,
    };
  },
  methods: {
    showPlatform(platform) {
        if (platform.toLowerCase() == "stocks") {

            this.$emit("stock", true);
            this.$emit("crypto", false);

            this.stockPlat = true;
        } else if (platform.toLowerCase() == "crypto") {

            this.$emit("stock", false);
            this.$emit("crypto", true);

            this.stockPlat = !this.stockPlat;
        }
    },
  },
 };
</script>

Inside the Template tag, change the header background color if it's this unique page, i.e where stockPlat is false as seen below

<template>
  <div :class="[stockPlat ? 'bgDark' : 'bgBlue']">
    ...
  </div>
</template>

Inside the Style tag, use this

<style>
  .bgDark {
    background-color: black;
  }
  .bgBlue {
    background-color: blue;
  }
</style>

Reference:
https://v2.vuejs.org/v2/guide/class-and-style.html
https://v2.vuejs.org/v2/guide/components-custom-events.html


问:
In Scala, what is the running time of trimStart and trimEnd for ListBuffer?
Suppose I'm only removing a single element. I would like these methods to implement a fixed size ListBuffer. I would only use if they run in O(1) time. The documentation is slightly ambiguous does anybody know the implementation details?</p>

答:
The relevant implementation is there (for ListBuffer) and there (for BufferLike).

trimStart(n) is linear with respect to n (so, constant if you remove a single element); trimEnd(n) is linear with respect to the size of the collection.

Apart from that, I fail to see how you want to have a fixed-size ListBuffer on which you change the size with such trim methods…

ContentLicense: CC BY-SA 3.0


问:
How to Exclude retweets and replies in a search api?
How to Exclude retweets and replies in a search api?

I am trying to fetch the feeds from twitter using search api, in the result I am getting replies and retweets also.

So I want to exclude replies and retweets.

How to do it anybody help me.

This is my url:

https://api.twitter.com/1.1/search/tweets.json?q=from:rioferdy5&count=20&result_type=recent

答:
In the new Search Tweets API, including the following parameters will remove different flavors of retweets:

-is:retweet Excludes retweets

-is:quote Excludes quote tweets

-is:reply Excludes replies

Please see the API documentation here: Search Tweets - Build a Query

Only Mike Chen's response (which oddly had 0 upvotes until I upvoted it) is correct. The rest of the answers here are out of date due to the launch of the Twitter API v2. I would comment directly on Mike's answer, but I don't have enough reputation.


问:
Find all unique values for field in Elasticsearch through python
I've been scouring the web for some good python documentation for Elasticsearch. I've got a query term that I know returns the information I need, but I'm struggling to convert the raw string into something Python can interpret.

This will return a list of all unique 'VALUE's in the dataset.

```<code>{"find": "terms", "field": "hierarchy1.hierarchy2.VALUE"}
</code>```

Which I have taken from a dashboarding tool which accesses this data.
But I don't seem to be able to convert this into correct python.

I've tried this:

```<code>body_test = {"find": "terms", "field": "hierarchy1.hierarchy2.VALUE"}
es = Elasticsearch(SETUP CONNECTION)
es.search(
    index="INDEX_NAME",
    body = body_test
)
</code>```

but it doesn't like the find value. I can't find anything in the documentation about find.

RequestError: RequestError(400, 'parsing_exception', 'Unknown key for
a VALUE_STRING in [find].')

The only way I've got it to slightly work is with

```<code>es_search = (
        Search(
            using=es,
            index=db_index
        ).source(['hierarchy1.hierarchy2.VALUE'])
    )
</code>```

But I think this is pulling the entire dataset and then filtering (which I obviously don't want to be doing each time I run this code). This needs to be done through python and so I cannot simply POST the query I know works.

I am completely new to ES and so this is all a little confusing. Thanks in advance!

答:
So it turns out that the find in this case was specific to Grafana (the dashboarding tool I took the query from.
In the end I used this site and used the code from there. It's a LOT more complicated than I thought it was going to be. But it works very quickly and doesn't put a strain on the database (which my alternative method was doing).

In case the link dies in future years, here's the code I used:

```<code>from elasticsearch import Elasticsearch

es = Elasticsearch()

def iterate_distinct_field(es, fieldname, pagesize=250, **kwargs):
    """
    Helper to get all distinct values from ElasticSearch
    (ordered by number of occurrences)
    """
    compositeQuery = {
        "size": pagesize,
        "sources": [{
                fieldname: {
                    "terms": {
                        "field": fieldname
                    }
                }
            }
        ]
    }
    # Iterate over pages
    while True:
        result = es.search(**kwargs, body={
            "aggs": {
                "values": {
                    "composite": compositeQuery
                }
            }
        })
        # Yield each bucket
        for aggregation in result["aggregations"]["values"]["buckets"]:
            yield aggregation
        # Set "after" field
        if "after_key" in result["aggregations"]["values"]:
            compositeQuery["after"] = \
                result["aggregations"]["values"]["after_key"]
        else: # Finished!
            break

# Usage example
for result in iterate_distinct_field(es, fieldname="pattern.keyword", index="strings"):
    print(result) # e.g. {'key': {'pattern': 'mypattern'}, 'doc_count': 315}
</code>```

Body:
I've been scouring the web for some good python documentation for Elasticsearch. I've got a query term that I know returns the information I need, but I'm struggling to convert the raw string into something Python can interpret.

This will return a list of all unique 'VALUE's in the dataset.

{"find": "terms", "field": "hierarchy1.hierarchy2.VALUE"}

Which I have taken from a dashboarding tool which accesses this data.
But I don't seem to be able to convert this into correct python.

I've tried this:

body_test = {"find": "terms", "field": "hierarchy1.hierarchy2.VALUE"}
es = Elasticsearch(SETUP CONNECTION)
es.search(
    index="INDEX_NAME",
    body = body_test
)

but it doesn't like the find value. I can't find anything in the documentation about find.

RequestError: RequestError(400, 'parsing_exception', 'Unknown key for
a VALUE_STRING in [find].')

The only way I've got it to slightly work is with

es_search = (
        Search(
            using=es,
            index=db_index
        ).source(['hierarchy1.hierarchy2.VALUE'])
    )

But I think this is pulling the entire dataset and then filtering (which I obviously don't want to be doing each time I run this code). This needs to be done through python and so I cannot simply POST the query I know works.

I am completely new to ES and so this is all a little confusing. Thanks in advance!

Body:
So it turns out that the find in this case was specific to Grafana (the dashboarding tool I took the query from.
In the end I used this site and used the code from there. It's a LOT more complicated than I thought it was going to be. But it works very quickly and doesn't put a strain on the database (which my alternative method was doing).

In case the link dies in future years, here's the code I used:

from elasticsearch import Elasticsearch

es = Elasticsearch()

def iterate_distinct_field(es, fieldname, pagesize=250, **kwargs):
    """
    Helper to get all distinct values from ElasticSearch
    (ordered by number of occurrences)
    """
    compositeQuery = {
        "size": pagesize,
        "sources": [{
                fieldname: {
                    "terms": {
                        "field": fieldname
                    }
                }
            }
        ]
    }
    # Iterate over pages
    while True:
        result = es.search(**kwargs, body={
            "aggs": {
                "values": {
                    "composite": compositeQuery
                }
            }
        })
        # Yield each bucket
        for aggregation in result["aggregations"]["values"]["buckets"]:
            yield aggregation
        # Set "after" field
        if "after_key" in result["aggregations"]["values"]:
            compositeQuery["after"] = \
                result["aggregations"]["values"]["after_key"]
        else: # Finished!
            break

# Usage example
for result in iterate_distinct_field(es, fieldname="pattern.keyword", index="strings"):
    print(result) # e.g. {'key': {'pattern': 'mypattern'}, 'doc_count': 315}


问:
Change Font Size in Excel Table
I have a table, "Schedule", and I want the check the table column, "Number". If "Number" in a row is blank I want to change the cell for that row in the column "Name" to be font size 11 non-bold but if "Number" isn't blank I want to change "Name" to font size 12 bold.

I'm not sure how to do this. I also have some 60,000 cells and growing so it needs to do as little work as possible so it stays as fast as possible.

I'll edit this since I added typeface in the question and not in the subject. I was planning on doing this with VBA because I can't do font size in conditional.

答:
With conditional formatting, you can set the font to bold (also change text colour and cell background colour). Unfortunately it can't change font size.

Starting with this table, where Number is column C:

You can add conditional formatting with "Use a formula..." for the rule, and set that formula to =ISBLANK(@$C:$C).

(Alternatively you could give a relevant name to the appropriate column and use the column name instead: =ISBLANK(@registration_number))

Then click Format and apply Bold style (and/or any highlighting colours).

Then in the Conditional Formatting Rules Manager(Conditional Formatting -> Manage rules), change Applies to to cover your table:

Rows where Number is blank are now bold.

To change font size automatically within Excel, this is only possible with Visual Basic.

You could however periodically filter the table for rows where Number is blank and manually set the font size / style.

Title: Change Font Size in Excel Table


问:
Is there an option in snowflake to escape /n in an enclosed field in CSV?
I am trying to load a csv file into snowflake from an external S3 stage.
The problem seems to be that my file has a new line inside a field enclosed by "".

I created a file format for the file as follows:

```<code>CREATE OR REPLACE FILE FORMAT file_format
     TYPE = CSV
     COMPRESSION = AUTO
     FIELD_OPTIONALLY_ENCLOSED_BY = '"'
     RECORD_DELIMITER = '\n'
     FIELD_DELIMITER = ','
     SKIP_HEADER = 1
     EMPTY_FIELD_AS_NULL = TRUE;

COPY INTO trans_table
    FROM  @data_stage
    FILES = ('file.csv')
    FILE_FORMAT = file_format
    FORCE = TRUE;
</code>```

When I try to load the file in a table, an error occurs related to the row ending unexpectedly:

"End of record reached while expected to parse column"

答:
It seems like the problem was that I had some rows that were not enclosed by "", but they contained newlines, so that what got me the error.

The file format statement above should be enough to escape /n in strings enclosed by "".

Body:
I am trying to load a csv file into snowflake from an external S3 stage.
The problem seems to be that my file has a new line inside a field enclosed by "".

I created a file format for the file as follows:

CREATE OR REPLACE FILE FORMAT file_format
     TYPE = CSV
     COMPRESSION = AUTO
     FIELD_OPTIONALLY_ENCLOSED_BY = '"'
     RECORD_DELIMITER = '\n'
     FIELD_DELIMITER = ','
     SKIP_HEADER = 1
     EMPTY_FIELD_AS_NULL = TRUE;

COPY INTO trans_table
    FROM  @data_stage
    FILES = ('file.csv')
    FILE_FORMAT = file_format
    FORCE = TRUE;

When I try to load the file in a table, an error occurs related to the row ending unexpectedly:

"End of record reached while expected to parse column"


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

答:
Your version is still right. you can use with a class

body {
    background-color: #2a2f3f;
}
.text-control {
    display: block;
    width: 30%;
    padding: 0.375rem 0.75rem;
    font-size: 1rem;
    font-weight: 400;
    outline: none;
    line-height: 1.5;
    color: #0c3d13;
    background-color: #538976;
    background-clip: padding-box;
    border: 2px solid yellow;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    border-radius: 0.25rem;
    transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}
.text-control:hover {
    border: 2px solid green;
    background-color: red;
}
.text-control:focus {
    border: 2px solid #00ba4a;
    background-color: #1c6b3c;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
    <input class="text-control" type="text" name="">
</form></code>```

Title: Change selection color for text field

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

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

Body:
Your version is still right. you can use with a class

body {
    background-color: #2a2f3f;
}
.text-control {
    display: block;
    width: 30%;
    padding: 0.375rem 0.75rem;
    font-size: 1rem;
    font-weight: 400;
    outline: none;
    line-height: 1.5;
    color: #0c3d13;
    background-color: #538976;
    background-clip: padding-box;
    border: 2px solid yellow;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    border-radius: 0.25rem;
    transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}
.text-control:hover {
    border: 2px solid green;
    background-color: red;
}
.text-control:focus {
    border: 2px solid #00ba4a;
    background-color: #1c6b3c;
}

<form>
    <input class="text-control" type="text" name="">
</form>


问:
Borrowed value does not live long enough when comparing values
I am making a simple rust program that requests an api and detects updates but currently i am getting a really strange error when comparing the new data with the old data to detect if something has changed.</p>
```<code>use std::io::prelude::*;
use std::net::TcpStream;
fn main() {
    let mut old = "";
    while true {
        let mut stream = TcpStream::connect("ip:port").unwrap();
        let _ = stream.write(b"GET /stats.json HTTP/1.0\r\nHost: example.com\r\n\r\n");

        let mut res: String = "".to_string();
        let mut buf = [0; 512];
        let data: Vec<&str>;

        while stream.read(&mut buf).unwrap() > 0 {
            res.push_str(&String::from_utf8_lossy(&buf[..]));
            for elem in buf.iter_mut() { *elem = 0;}
        }

        data = res.split("\r\n\r\n").collect();
        if data[1] != old {
            old = data[1];
            println!("new");
        }
    }
}
</code>```

答:
The problem with your code is that old is outside the while true loop.

In this line:

```<code>data = res.split("\r\n\r\n").collect();
</code>```

you are setting data that references (or borrows) res. Then here:

```<code>old = data[1];
</code>```

you practically set to old data that borrows res, but res gets dropped at the end of each iteration. And, of course, it wouldn't make sense to reference a dropped value, hence the error "Borrowed value does not live long enough".

One way to avoid this error is to make old a String. That way, old will own its data instead of depending on the data in res.

Body:
I am making a simple rust program that requests an api and detects updates but currently i am getting a really strange error when comparing the new data with the old data to detect if something has changed.

use std::io::prelude::*;
use std::net::TcpStream;
fn main() {
    let mut old = "";
    while true {
        let mut stream = TcpStream::connect("ip:port").unwrap();
        let _ = stream.write(b"GET /stats.json HTTP/1.0\r\nHost: example.com\r\n\r\n");

        let mut res: String = "".to_string();
        let mut buf = [0; 512];
        let data: Vec<&str>;

        while stream.read(&mut buf).unwrap() > 0 {
            res.push_str(&String::from_utf8_lossy(&buf[..]));
            for elem in buf.iter_mut() { *elem = 0;}
        }

        data = res.split("\r\n\r\n").collect();
        if data[1] != old {
            old = data[1];
            println!("new");
        }
    }
}

Body:
The problem with your code is that old is outside the while true loop.

In this line:

data = res.split("\r\n\r\n").collect();

you are setting data that references (or borrows) res. Then here:

old = data[1];

you practically set to old data that borrows res, but res gets dropped at the end of each iteration. And, of course, it wouldn't make sense to reference a dropped value, hence the error "Borrowed value does not live long enough".

One way to avoid this error is to make old a String. That way, old will own its data instead of depending on the data in res.


问:
java format string printing unable to print
I'm unable to run the code, it says it cannot resolve println with the parameters.</p>
```<code>public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("%s : %d", this.getName(), i);
        }
    }
</code>```

答:
System.out.println does not support format parameters.  You can either use System.out.printf to immediately format and then print or format it with String.format which will give you a String result that you can then print or store into a variable.

System.out.printf example:

```<code>for (int i = 0; i < 10; i++) {
        System.out.printf("%s : %d%n", this.getName(), i);
}
</code>```

You would need to add %n to the formatting in order to print on new lines shown above.

String.format example:

```<code>for (int i = 0; i < 10; i++) {
    System.out.println(String.format("%s : %d", this.getName(), i));

    //can also create a String variable with the result
    String formattedStr = String.format("%s : %d", this.getName(), i);
    //do whatever you want with the String
}
</code>```

You would not need to add %n in this case because println will add the new line.

Body:
I'm unable to run the code, it says it cannot resolve println with the parameters.

public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("%s : %d", this.getName(), i);
        }
    }

Body:
System.out.println does not support format parameters.  You can either use System.out.printf to immediately format and then print or format it with String.format which will give you a String result that you can then print or store into a variable.

System.out.printf example:

for (int i = 0; i < 10; i++) {
        System.out.printf("%s : %d%n", this.getName(), i);
}

You would need to add %n to the formatting in order to print on new lines shown above.

String.format example:

for (int i = 0; i < 10; i++) {
    System.out.println(String.format("%s : %d", this.getName(), i));

    //can also create a String variable with the result
    String formattedStr = String.format("%s : %d", this.getName(), i);
    //do whatever you want with the String
}

You would not need to add %n in this case because println will add the new line.


问:
Best ways to teach a beginner to program?
Original Question

I am currently engaged in teaching my brother to program.  He is a total beginner, but very smart. (And he actually wants to learn).  I've noticed that some of our sessions have gotten bogged down in minor details, and I don't feel I've been very organized. (But the answers to this post have helped a lot.)

What can I do better to teach him effectively?  Is there a logical order that I can use to run through concept by concept?  Are there complexities I should avoid till later?

The language we are working with is Python, but advice in any language is welcome.

How to Help

If you have good ones please add the following in your answer:

Beginner Exercises and Project Ideas

Resources for teaching beginners

Screencasts / blog posts / free e-books

Print books that are good for beginners

Please describe the resource with a link to it so I can take a look.  I want everyone to know that I have definitely been using some of these ideas.  Your submissions will be aggregated in this post.

Online Resources for teaching beginners:

A Gentle Introduction to Programming Using Python

How to Think Like a Computer Scientist

Alice: a 3d program for beginners

Scratch (A system to develop programming skills)

How To Design Programs

Structure and Interpretation of Computer Programs

Learn To Program

Robert Read's How To Be a Programmer

Microsoft XNA

Spawning the Next Generation of Hackers

COMP1917 Higher Computing lectures by Richard Buckland (requires iTunes)

Dive into Python

Python Wikibook

Project Euler - sample problems (mostly mathematical)

pygame - an easy python library for creating games

Invent Your Own Computer Games With Python

Foundations of Programming for a next step beyond basics.

Squeak by Example

Snake Wrangling For Kids (It's not just for kids!)

Recommended Print Books for teaching beginners

Accelerated C++

Python Programming for the Absolute Beginner

Code by Charles Petzold

Python Programming: An Introduction to Computer Science 2nd Edition

答: I'd recommend Think Python.</p>

LastEditorDisplayName: epatel

Body: I'd recommend Think Python.

ContentLicense: CC BY-SA 2.5


问:
Is there any way to implement ws-security in metro via annotations?
Since i do not want to create a lot of wsit files to enable security (encryption of message and authentication of users) and i do not want to use netbeans to use the metro plugin there, i want to ask if there is any easy way to implement ws-security via annotations?
Or is there any eclipse plugin besides soap ui, which is in fact not very usefull, to create such wsit files?

Thanks in advance.

答:
According to this post, Metro does not support ws-policy programmatically. That was 2009 though, so I don't know if that's still the case.

Metro can get the policy directly from the WSDL too if you don't want to use wsit files (if you have the policy in the WSDL at all, that is).

This is how I did in my Metro-generated service class. It loads the policy directly from the WSDL, which is in my classpath, and will apply all policies in runtime, provided that you have installed Metro in your application server and don't have any conflicting dependencies in your project (this one was a bit of a hassle for me to find, some of my dependencies had jaxws-rt as a dependency, which may ruin Metros policy resolving).

```<code>private final static URL CUSTOMERSERVICE_WSDL_LOCATION;

static {
    CUSTOMERSERVICE_WSDL_LOCATION =
        CustomerService.class.getClassLoader().getResource("Customer/CustomerService.wsdl");
}

public CustomerService(URL wsdlLocation, QName serviceName) {
    super(wsdlLocation, serviceName);
}
</code>```

Body:
According to this post, Metro does not support ws-policy programmatically. That was 2009 though, so I don't know if that's still the case.

Metro can get the policy directly from the WSDL too if you don't want to use wsit files (if you have the policy in the WSDL at all, that is).

This is how I did in my Metro-generated service class. It loads the policy directly from the WSDL, which is in my classpath, and will apply all policies in runtime, provided that you have installed Metro in your application server and don't have any conflicting dependencies in your project (this one was a bit of a hassle for me to find, some of my dependencies had jaxws-rt as a dependency, which may ruin Metros policy resolving).

private final static URL CUSTOMERSERVICE_WSDL_LOCATION;

static {
    CUSTOMERSERVICE_WSDL_LOCATION =
        CustomerService.class.getClassLoader().getResource("Customer/CustomerService.wsdl");
}

public CustomerService(URL wsdlLocation, QName serviceName) {
    super(wsdlLocation, serviceName);
}


问:
R: Summary of SQL Tables
I am working with the R programming language.

Normally, when I want to get the summary of a table, I can use something like the "str()" function or the "summary()" function:

```<code>str(my_table)

summary(my_table)
</code>```

However, now I am trying to do this with tables on a server.

For instance, I am trying to get the summaries of variable types for a specific table (e.g. "my_table") on a server. I found a very indirect way to do this:

```<code>#load libraries
library(OBDC)
library(RODBC)
library(dbi)

#establish a connection and name it as "dbhandle"

rs <- dbSendQuery(dbhandle, 'select * from my_table limit 1')

dbColumnInfo(rs)
</code>```

My Question: Is there a more "direct" way to do this? For example, can I get information  about each column (e.g. whether the column is integer, character, date, etc.) in a table without first sending the query and then requesting the information? Can I do this directly?

Thanks!

答:
You could try using fetch() from "RMySQL" to turn your SQL query into an R object (e.g. data frame)

```<code>library(RMySQL)
rs <- dbSendQuery(dbhandle, 'select * from my_table limit 1')
# Get the results from MySQL into R
my_table = fetch(rs, n=-1)
# clear result
dbClearResult(rs)
rm(rs)
</code>```

Then use the functions you describe.

```<code>str(my_table)

summary(my_table)
</code>```

Title: R: Summary of SQL Tables

Body:
I am working with the R programming language.

Normally, when I want to get the summary of a table, I can use something like the "str()" function or the "summary()" function:

str(my_table)

summary(my_table)

However, now I am trying to do this with tables on a server.

For instance, I am trying to get the summaries of variable types for a specific table (e.g. "my_table") on a server. I found a very indirect way to do this:

#load libraries
library(OBDC)
library(RODBC)
library(dbi)

#establish a connection and name it as "dbhandle"

rs <- dbSendQuery(dbhandle, 'select * from my_table limit 1')

dbColumnInfo(rs)

My Question: Is there a more "direct" way to do this? For example, can I get information  about each column (e.g. whether the column is integer, character, date, etc.) in a table without first sending the query and then requesting the information? Can I do this directly?

Thanks!

Body:
You could try using fetch() from "RMySQL" to turn your SQL query into an R object (e.g. data frame)

library(RMySQL)
rs <- dbSendQuery(dbhandle, 'select * from my_table limit 1')
# Get the results from MySQL into R
my_table = fetch(rs, n=-1)
# clear result
dbClearResult(rs)
rm(rs)

Then use the functions you describe.

str(my_table)

summary(my_table)


问:
Query withColumn Pyspark to add a column dataframe based on array
I have a dataframe:

   "people"      "other"
   father         ...
   mother
   cat
   brother
   dog
```
<p>I'm going to insert new column, if column <code>people</code> contains word in specific array then modify the content with that of other array, else word will remain the same:</p>
```array=['father','mother','brother']
array_new=['dad','mum','bro']

   "people"      "other"     "new"
   father         ...        dad
   mother                    mum
   cat                       cat
   brother                   bro
   dog                       dog
```
<p>I think to use this:</p>
```expression = ("CASE " +"".join(["WHEN people LIKE '{}' THEN '{}' ".format(val,array_new[array.index(val)](val)) for val in array]) +"ELSE 'None' END")

df_pyspark = df_pyspark.withColumn("new", functions.expr(expression))
```

I should change the else condition, but I don't know how to do it, for copy the same word in the else condition.

答:
You use a literal map expression that you create from array and array_new using create_map function:

```<code>from pyspark.sql import functions as F
from itertools import chain

mapping = F.create_map(*[F.lit(x) for x in chain(*zip(array, array_new))])

df1 = df.withColumn("new", F.coalesce(mapping[F.col("people")], F.col("people")))
</code>```

Or using na.replace by passing a dict that you create from the two arrays like this:

```<code>from pyspark.sql import functions as F

mapping_dict = dict(zip(array, array_new))

df1 = df.withColumn("new", F.col("people")).na.replace(mapping_dict, subset=["new"])
</code>```

Another way by chaining multiple when expressions:

```<code>from functools import reduce
from pyspark.sql import functions as F

when_expr = reduce(
    lambda acc, x: acc.when(F.col("people") == x[0], x[1]),
    zip(array, array_new),
    F
).otherwise(F.col("people"))

df1 = df.withColumn("new", when_expr)
</code>```

Body:
I have a dataframe:

   "people"      "other"
   father         ...
   mother
   cat
   brother
   dog

I'm going to insert new column, if column people contains word in specific array then modify the content with that of other array, else word will remain the same:

array=['father','mother','brother']
array_new=['dad','mum','bro']

   "people"      "other"     "new"
   father         ...        dad
   mother                    mum
   cat                       cat
   brother                   bro
   dog                       dog

I think to use this:

expression = ("CASE " +"".join(["WHEN people LIKE '{}' THEN '{}' ".format(val,array_new[array.index(val)](val)) for val in array]) +"ELSE 'None' END")

df_pyspark = df_pyspark.withColumn("new", functions.expr(expression))

I should change the else condition, but I don't know how to do it, for copy the same word in the else condition.

Body:
You use a literal map expression that you create from array and array_new using create_map function:

from pyspark.sql import functions as F
from itertools import chain

mapping = F.create_map(*[F.lit(x) for x in chain(*zip(array, array_new))])

df1 = df.withColumn("new", F.coalesce(mapping[F.col("people")], F.col("people")))

Or using na.replace by passing a dict that you create from the two arrays like this:

from pyspark.sql import functions as F

mapping_dict = dict(zip(array, array_new))

df1 = df.withColumn("new", F.col("people")).na.replace(mapping_dict, subset=["new"])

Another way by chaining multiple when expressions:

from functools import reduce
from pyspark.sql import functions as F

when_expr = reduce(
    lambda acc, x: acc.when(F.col("people") == x[0], x[1]),
    zip(array, array_new),
    F
).otherwise(F.col("people"))

df1 = df.withColumn("new", when_expr)


问:
Block.json returnes wrong paths
I've created a custom block plugin with @wordpress/create-block (https://developer.wordpress.org/block-editor/reference-guides/packages/packages-create-block/)

It works as a plugin, but when i move it into the theme, the "editorScript" in the block.json file, returns the wrong path.

```<code>themeDirectory/blocks/mycustomblock/block.json

{
    "name": "create-block/mycustomblock",
    "title": "Mycustomblock",
    "description": "Example block written with ESNext standard and JSX support – build step required.",
    "category": "text",
    "icon": "smiley",
    "supports": {
        "html": false
    },
    "attributes":{
        "backgroundColor": {
            "type": "string",
            "default": "red"
        }
    },
    "editorScript": "file:./build/index.js"
}
</code>```

Returned path from editorScript:

```<code>404 | http://localhost:8888/wordpress-test/wp-content/plugins/Users/jonrose/Dropbox/htdocs/wordpress-test/wp-content/themes/mytheme/blocks/mycustomblock/build/index.js?ver=4f45658ee3212a45c5d5367f6fbdfeba
</code>```

If i register the script inside the register_block_type function it works fine

```<code>wp_register_script( 'mycustomblock-js', get_template_directory_uri() . '/blocks/mycustomblock/build/index.js', array( 'wp-blocks' ));

    register_block_type( __DIR__, array(
        'editor_script' => 'mycustomblock-js'
    ) );
</code>```

答:
Registering a block type with block.json uses register_block_script_handle under the hood to register all relevant block scripts. That function uses plugins_url to generate URLs if the script uses the file:<path> pattern.

Passing in an already existing handle (e.g., mycustomblock-js) works because register_block_script_handle sees it's not file:<path> and just uses that handle (and corresponding URL) as-is.

Title: Block.json returnes wrong paths

Body:
I've created a custom block plugin with @wordpress/create-block (https://developer.wordpress.org/block-editor/reference-guides/packages/packages-create-block/)

It works as a plugin, but when i move it into the theme, the "editorScript" in the block.json file, returns the wrong path.

themeDirectory/blocks/mycustomblock/block.json

{
    "name": "create-block/mycustomblock",
    "title": "Mycustomblock",
    "description": "Example block written with ESNext standard and JSX support – build step required.",
    "category": "text",
    "icon": "smiley",
    "supports": {
        "html": false
    },
    "attributes":{
        "backgroundColor": {
            "type": "string",
            "default": "red"
        }
    },
    "editorScript": "file:./build/index.js"
}

Returned path from editorScript:

404 | http://localhost:8888/wordpress-test/wp-content/plugins/Users/jonrose/Dropbox/htdocs/wordpress-test/wp-content/themes/mytheme/blocks/mycustomblock/build/index.js?ver=4f45658ee3212a45c5d5367f6fbdfeba

If i register the script inside the register_block_type function it works fine

wp_register_script( 'mycustomblock-js', get_template_directory_uri() . '/blocks/mycustomblock/build/index.js', array( 'wp-blocks' ));

    register_block_type( __DIR__, array(
        'editor_script' => 'mycustomblock-js'
    ) );


答:
A non-volatile alternative, which references the maximum value you have already calculated in cell G13:

=INDEX(FILTERXML(""&TEXTJOIN("",,ABC:XYZ!A5)&"","//b"),MATCH(1,FREQUENCY(G13,ABC:XYZ!F1),0))

Title: How do you find the max in a particular cell across all sheets and return a different cell?

Body:
I have been able to return the max value of F1 from all sheets by using this formula located in cell G13:

G13=MAX(ABC:XYZ!F1)

Now I also want to return the value of A5 from the sheet where the MAX was found in G13.

How do I write the formula for that?

TIA.

Body:
A non-volatile alternative, which references the maximum value you have already calculated in cell G13:

=INDEX(FILTERXML("<a><b>"&TEXTJOIN("</b><b>",,ABC:XYZ!A5)&"</b></a>","//b"),MATCH(1,FREQUENCY(G13,ABC:XYZ!F1),0))


问:
Vue.js 3 and typescript : Property '$store' does not exist on type 'ComponentPublicInstance
Can't find anything to solve this seemingly obvious issue.

Just upgraded from Vue 2 to Vue 3 and Vuex with Typescript.

this.$store doesn't seem to be accessible, despite following the Vue 3 instructions.

ERROR in src/components/FlashMessages.vue:28:25
TS2339: Property '$store' does not exist on type 'ComponentPublicInstance<{}, {}, {}, { getAllFlashMessages(): Word; }, {}, EmitsOptions, {}, {}, false, ComponentOptionsBase<{}, {}, {}, { getAllFlashMessages(): Word; }, {}, ComponentOptionsMixin, ComponentOptionsMixin, EmitsOptions, string, {}>>'.

```<code>    26 |     computed: {
    27 |         getAllFlashMessages (): FlashType {
  > 28 |             return this.$store.getters.getFlashMessages;
       |                         ^^^^^^
    29 |         },
    30 |     },
    31 |
</code>```

main.ts

```<code>import { createApp } from 'vue'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'
import store from './store'
import './assets/styles/index.css'

const app = createApp(App)

app.use(store)
app.use(router)
app.mount('#app')
</code>```

store.ts

```<code>import { createStore } from 'vuex'
import FlashType from '@/init'

export default createStore({
    state: {
        flashMessages: [] as FlashType[],
    },

    getters: {
        getFlashMessages (state) {
            return state.flashMessages
        }
    },
</code>```

FlashMessages.vue

```<code><script lang="ts">
import { defineComponent } from "vue";
import FlashType from "@/init";

export default defineComponent({
    name: "FlashMessages",

    data () {
        return {};
    },

    computed: {
        getAllFlashMessages (): FlashType {
            return this.$store.getters.getFlashMessages;
        },
    },
</code>```

init.ts

```<code>export type FlashType = {
    kind: 'success' | 'error';
    message: string;
    time: number;
}
</code>```

Any wisdom appreciated :)

File structure

```<code>├── .editorconfig
├── client
│   ├── babel.config.js
│   ├── CONTRACTS.md
│   ├── cypress.json
│   ├── jest.config.js
│   ├── package.json
│   ├── package-lock.json
│   ├── postcss.config.js
│   ├── public
│   │   ├── favicon.ico
│   │   ├── index.html
│   │   └── robots.txt
│   ├── README.md
│   ├── src
│   │   ├── App.vue
│   │   ├── assets
│   │   │   ├── logo.png
│   │   │   └── styles
│   │   │       └── index.css
│   │   ├── components
│   │   │   ├── admin
│   │   │   │   ├── AdminAdd.vue
│   │   │   │   ├── AdminList.vue
│   │   │   │   ├── AdminWord.vue
│   │   │   │   ├── EmotionAdd.vue
│   │   │   │   ├── EmotionsList.vue
│   │   │   │   └── Emotion.vue
│   │   │   └── FlashMessages.vue
│   │   ├── init.ts
│   │   ├── main.ts
│   │   ├── registerServiceWorker.ts
│   │   ├── router
│   │   │   └── index.ts
│   │   ├── shims-vue.d.ts
│   │   ├── store
│   │   │   └── index.ts
│   │   └── views
│   │       ├── About.vue
│   │       ├── Admin.vue
│   │       ├── Emotions.vue
│   │       └── Home.vue
│   ├── tsconfig.json
│   └── vue.config.js
├
└── server
    ├── api
    ├── api.bundle.js
    ├── index.ts
    ├── logger
    │   └── logger.ts
    ├── models
    ├── nodemon.json
    ├── package.json
    ├── package-lock.json
    ├── router
    │   ├── db.ts
    │   └── emotions.ts
    ├── tsconfig.json
    └── webpack.config.js
</code>```

This is my first time properly using eslint, so I'm not sure if I've set it up correctly.. I ended up with a different tsconfig in /client and /server directories.

client/tsconfig.json

```<code>{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": "./",
    "types": [
      "webpack-env",
      "jest"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}
</code>```

答: I had a lot of problems trying to configure vuex with typescript and options API. Regardless of the API you use, I strongly recommend you to use Pinia as it is a typescript ready solution and is very similar to Vuex</p>

Body:
Can't find anything to solve this seemingly obvious issue.

Just upgraded from Vue 2 to Vue 3 and Vuex with Typescript.

this.$store doesn't seem to be accessible, despite following the Vue 3 instructions.

ERROR in src/components/FlashMessages.vue:28:25
TS2339: Property '$store' does not exist on type 'ComponentPublicInstance<{}, {}, {}, { getAllFlashMessages(): Word; }, {}, EmitsOptions, {}, {}, false, ComponentOptionsBase<{}, {}, {}, { getAllFlashMessages(): Word; }, {}, ComponentOptionsMixin, ComponentOptionsMixin, EmitsOptions, string, {}>>'.

    26 |     computed: {
    27 |         getAllFlashMessages (): FlashType {
  > 28 |             return this.$store.getters.getFlashMessages;
       |                         ^^^^^^
    29 |         },
    30 |     },
    31 |

main.ts

import { createApp } from 'vue'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'
import store from './store'
import './assets/styles/index.css'

const app = createApp(App)

app.use(store)
app.use(router)
app.mount('#app')

store.ts

import { createStore } from 'vuex'
import FlashType from '@/init'

export default createStore({
    state: {
        flashMessages: [] as FlashType[],
    },

    getters: {
        getFlashMessages (state) {
            return state.flashMessages
        }
    },

FlashMessages.vue


问:
Replace current activity
I need to replace the current activity with a new one. That is, I want to start a new activity and remove the current activity from the task stack.

Based on the documentation, it seems the best way would be to start the activity using Activity.startActivity as per usual, and then call Activity.finish immediately to close the current activity.

Is this a valid usage of these APIs or should I be doing something else?

答: try using FLAG_ACTIVITY_TASK_ON_HOME, FLAG_ACTIVITY_NEW_TASK in the intent flags

Title: Replace current activity


问:
Find closest elements of two lists - the best way
I have two lists(or columns of dataframe - doesn't matter) of numerical values:

```<code>L1 = [1, 0.5, 3, 7, 4.7]
L2 = [2, 0.4, 8, 0.3, 5]
</code>```

for example. I need to correlate these lists and find pairs(indexOfElementFromL1, indexOfElementFromL2) which corresponds min diff of two elements. For example, for my example it should be:
(0,1), (1,1), (2,0), (3,2), (4,4). Really what I want - find closest element L2 to each one of L1. Of course I could naive approch like:

```<code>for el1 in L1:
  for el2 in L2:
    ....
</code>```

But I'd to like to see more correct solution

答:
You can do it really fast by converting your lists to numpy arrays and using numpy broadcasting:

```<code>a1 = np.array(L1)
a2 = np.array(L2)

indexes = abs(a1[:, None] - a2).argmin(axis=1)
out = list(enumerate(indexes))
</code>```

Output:

```<code>>>> indexes
array([1, 1, 0, 2, 4])

>>> out
[(0, 1), (1, 1), (2, 0), (3, 2), (4, 4)]
</code>```

Body:
I have two lists(or columns of dataframe - doesn't matter) of numerical values:

L1 = [1, 0.5, 3, 7, 4.7]
L2 = [2, 0.4, 8, 0.3, 5]

for example. I need to correlate these lists and find pairs(indexOfElementFromL1, indexOfElementFromL2) which corresponds min diff of two elements. For example, for my example it should be:
(0,1), (1,1), (2,0), (3,2), (4,4). Really what I want - find closest element L2 to each one of L1. Of course I could naive approch like:

for el1 in L1:
  for el2 in L2:
    ....

But I'd to like to see more correct solution

Body:
You can do it really fast by converting your lists to numpy arrays and using numpy broadcasting:

a1 = np.array(L1)
a2 = np.array(L2)

indexes = abs(a1[:, None] - a2).argmin(axis=1)
out = list(enumerate(indexes))

Output:

>>> indexes
array([1, 1, 0, 2, 4])

>>> out
[(0, 1), (1, 1), (2, 0), (3, 2), (4, 4)]


问:
How to get Kendo Grid to stop refreshing on each filter key press
Every time I type a character in the filter box at the top of any of my columns, my Ajax Read method ("_CustomBinding") is called 2 times.  The first call populates the type ahead of the filter box, and the second one refreshes the grid.  I do not want the grid to refresh until the enter key is pressed in the filter box, not on each key press.  How do I disable the call to refresh the grid on every key press in the filter box?

I have a very complicated Kendo Grid.  Here is just part of it:

```<code>@(Html.Kendo().Grid<ProspectiveAdvantage.ViewModels.MemberListingModel>().Name("Members").TableHtmlAttributes(new { @class = "tblPatient" })
    .AutoBind(Model.AutoPopulateResults)
    .Columns(columns =>
    {
        columns.Bound(theMember => theMember.LastName).Width(30).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").ShowOperators(false).MinLength(3).SuggestionOperator(FilterType.Contains)));
        columns.Bound(theMember => theMember.FirstName).Width(30).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").ShowOperators(false).MinLength(3).SuggestionOperator(FilterType.Contains)));
        columns.Bound(theMember => theMember.DisplayClientMemberId).HeaderTemplate("Patient ID").Width(30).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").ShowOperators(false).MinLength(3).SuggestionOperator(FilterType.Contains)));
        columns.Bound(theMember => theMember.DisplayBirthDate).HeaderTemplate("DOB").Format("{0:MM/dd/yyyy}").Width(30).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").ShowOperators(false).MinLength(3).SuggestionOperator(FilterType.Contains)));
…
                .DataSource(dataBinding => dataBinding.Ajax()
                .Read(read => read.Action("_CustomBinding", "PCPandCA").Data("members_FetchSearchParameters"))
                .Events(events => events.Error("handleAjaxErrorFromGrid"))
                 .ServerOperation(true)
                 .PageSize(Model.PageSize).Model(model => { model.Id(e => e.MemberID); model.Field(f => f.FirstName); })
                 //default sort DisplaySignatureDue column by ascending
                 .Sort(sort => {
                     if (!AssessmentExpired) { sort.Add("DisplaySignatureDue").Ascending();}
                     if (AssessmentExpired) { sort.Add("DisplayExpiredDate").Ascending();}
                 })
    )

    .Pageable(pageable => pageable
        .PageSizes(true)
        .Refresh(true)
    )
    .Sortable()
    .NoRecords("No records found.")
    .Selectable()
    .Filterable(ftb => ftb.Mode(GridFilterMode.Row))
    .Events(events => events.Change("handleGridRowSelected").DataBinding("handleDataBinding").DataBound("handleDataBound").Filter("onFiltering"))
    .HtmlAttributes(new { style = "cursor:pointer;border: 0px;height: 380px;display: flex;overflow-y: scroll;" })
)
</code>```

答: I finally figured out why I was noticing this unexpected behavior.  I was running my website from Visual Studio and I had a VS breakpoint in my _CustomBinding method.  This would cause my cursor focus to move from the filter field in the UI to the breakpoint in VS.  Whenever the filter field loses focus, it triggers the grid to refresh.  So, I was only seeing the second call to _CustomBinding because of the breakpoint, not because of any configuration of the grid control.</p>

Body:
Every time I type a character in the filter box at the top of any of my columns, my Ajax Read method ("_CustomBinding") is called 2 times.  The first call populates the type ahead of the filter box, and the second one refreshes the grid.  I do not want the grid to refresh until the enter key is pressed in the filter box, not on each key press.  How do I disable the call to refresh the grid on every key press in the filter box?

I have a very complicated Kendo Grid.  Here is just part of it:

@(Html.Kendo().Grid<ProspectiveAdvantage.ViewModels.MemberListingModel>().Name("Members").TableHtmlAttributes(new { @class = "tblPatient" })
    .AutoBind(Model.AutoPopulateResults)
    .Columns(columns =>
    {
        columns.Bound(theMember => theMember.LastName).Width(30).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").ShowOperators(false).MinLength(3).SuggestionOperator(FilterType.Contains)));
        columns.Bound(theMember => theMember.FirstName).Width(30).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").ShowOperators(false).MinLength(3).SuggestionOperator(FilterType.Contains)));
        columns.Bound(theMember => theMember.DisplayClientMemberId).HeaderTemplate("Patient ID").Width(30).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").ShowOperators(false).MinLength(3).SuggestionOperator(FilterType.Contains)));
        columns.Bound(theMember => theMember.DisplayBirthDate).HeaderTemplate("DOB").Format("{0:MM/dd/yyyy}").Width(30).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").ShowOperators(false).MinLength(3).SuggestionOperator(FilterType.Contains)));
…
                .DataSource(dataBinding => dataBinding.Ajax()
                .Read(read => read.Action("_CustomBinding", "PCPandCA").Data("members_FetchSearchParameters"))
                .Events(events => events.Error("handleAjaxErrorFromGrid"))
                 .ServerOperation(true)
                 .PageSize(Model.PageSize).Model(model => { model.Id(e => e.MemberID); model.Field(f => f.FirstName); })
                 //default sort DisplaySignatureDue column by ascending
                 .Sort(sort => {
                     if (!AssessmentExpired) { sort.Add("DisplaySignatureDue").Ascending();}
                     if (AssessmentExpired) { sort.Add("DisplayExpiredDate").Ascending();}
                 })
    )

    .Pageable(pageable => pageable
        .PageSizes(true)
        .Refresh(true)
    )
    .Sortable()
    .NoRecords("No records found.")
    .Selectable()
    .Filterable(ftb => ftb.Mode(GridFilterMode.Row))
    .Events(events => events.Change("handleGridRowSelected").DataBinding("handleDataBinding").DataBound("handleDataBound").Filter("onFiltering"))
    .HtmlAttributes(new { style = "cursor:pointer;border: 0px;height: 380px;display: flex;overflow-y: scroll;" })
)


问:
How to outer-join two CSV files, using shell script?
I have two CSV files, like the following:

file1.csv

label,"Part-A"
"ABC mn","2.0"
"XYZ","3.0"
"PQR SN","6"
```
<p><strong>file2.csv</strong></p>
<pre class="lang-none prettyprint-override"><code>label,"Part-B"
"XYZ","4.0"
"LMN Wv","8"
"PQR SN","6"
"EFG","1.0"
</code>```

Desired Output.csv

label,"Part-A","Part-B"
"ABC mn","2.0",NA
"EFG",NA,"1.0"
"LMN Wv",NA,"8"
"PQR SN","6","6"
"XYZ","3.0","4.0"
```
<p>Currently with the below awk command i am able to combine the matching one's which have entries for label in both the files like PQR and XYZ but unable to append the ones that are not having label values present in both the files:</p>
```awk -F, 'NR==FNR{a[$1]=substr($0,length($1)+2);next} ($1 in a){print $0","a[$1]}' file1.csv file2.csv
```

答:
awk -v OFS=, '{
        if(!o1[$1]) { o1[$1]=$NF; o2[$1]="NA" } else { o2[$1]=$NF }
    }
    END{
        for(v in o1) { print v, o1[v], o2[v] }
    }' file{1,2}

## output
LMN,8,NA
ABC,2,NA
PQR,6,6
EFG,1,NA
XYZ,3,4
```

I think this will do nicely.

Body:
I have two CSV files, like the following:

file1.csv

label,"Part-A"
"ABC mn","2.0"
"XYZ","3.0"
"PQR SN","6"

file2.csv

label,"Part-B"
"XYZ","4.0"
"LMN Wv","8"
"PQR SN","6"
"EFG","1.0"

Desired Output.csv

label,"Part-A","Part-B"
"ABC mn","2.0",NA
"EFG",NA,"1.0"
"LMN Wv",NA,"8"
"PQR SN","6","6"
"XYZ","3.0","4.0"

Currently with the below awk command i am able to combine the matching one's which have entries for label in both the files like PQR and XYZ but unable to append the ones that are not having label values present in both the files:

awk -F, 'NR==FNR{a[$1]=substr($0,length($1)+2);next} ($1 in a){print $0","a[$1]}' file1.csv file2.csv

Body:
awk -v OFS=, '{
        if(!o1[$1]) { o1[$1]=$NF; o2[$1]="NA" } else { o2[$1]=$NF }
    }
    END{
        for(v in o1) { print v, o1[v], o2[v] }
    }' file{1,2}

## output
LMN,8,NA
ABC,2,NA
PQR,6,6
EFG,1,NA
XYZ,3,4

I think this will do nicely.


问:
Building a docker image to run go applications
I am building a docker image on mac OS (Monterrey) with below dockerfile

```<code>FROM golang:latest
WORKDIR /src
COPY go.* ./
RUN go mod download
COPY . /src
RUN go build -o /main
ENTRYPOINT ["/main"]
</code>```

It works fine til the 3rd line and on the 4th it complains of

```<code>=> ERROR [4/6] RUN go mod download                                                         0.2s
------
 > [4/6] RUN go mod download:
#8 0.206 go mod download: no modules specified (see 'go help mod download')
------
executor failed running [/bin/sh -c go mod download]: exit code: 1
</code>```

Any clues what I am doing wrong while the dependencies are being downloaded?

答:
Instead of using download do :

```<code>go mod tidy && go mod vendor
</code>```

You need to specify which package to download when you use "mod download"

Body:
I am building a docker image on mac OS (Monterrey) with below dockerfile

FROM golang:latest
WORKDIR /src
COPY go.* ./
RUN go mod download
COPY . /src
RUN go build -o /main
ENTRYPOINT ["/main"]

It works fine til the 3rd line and on the 4th it complains of

=> ERROR [4/6] RUN go mod download                                                         0.2s
------
 > [4/6] RUN go mod download:
#8 0.206 go mod download: no modules specified (see 'go help mod download')
------
executor failed running [/bin/sh -c go mod download]: exit code: 1

Any clues what I am doing wrong while the dependencies are being downloaded?

Body:
Instead of using download do :

go mod tidy && go mod vendor

You need to specify which package to download when you use "mod download"


问:
Class cannot be provided without an @Provides-annotated method
I'm using Hilt for dependency injection and getting an error saying:

[Dagger/MissingBinding] DialogsInteractor cannot be provided without @Provided-annoated method

I bind the class in an Activity scoped module:

```<code>@InstallIn(ActivityComponent::class)
@Module(includes = [ActivityModule.BindsModule::class])
class ActivityModule {
    ...
    @Module
    @InstallIn(ActivityComponent::class)
    interface BindsModule {
        ....
        @Binds
        fun bindDialogsInteractor(dialogsInteractorImpl: DialogsInteractorImpl): DialogsInteractor
    }
}
</code>```

Also of course added the @Inject constructor:

```<code>@ActivityScoped
class DialogsInteractorImpl @Inject constructor(
    @ActivityContext context: Context,
    ....
){
</code>```

I tried adding a @Provide injection method but still getting the same error.

Checked every dependency DialogsInteractorImpl has and nothing is wrong.

The weird thing is that I have other binds under BindsModule that don't cause any problem.

(I'm getting the problem on 5 different classes)

Thank you!

答:
As @IR42 stated,

you can't use ActivityScoped dependencies in ViewModels, check Component hierarchy

I changed the module scope to ActivityRetainedScoped and all the dependencies under it and it works.

The problem was that I tried to inject an @ActivityScoped dependency into a ViewModel and ViewModels are scoped to ActivityRetainedScoped and under.

Body:
I'm using Hilt for dependency injection and getting an error saying:

[Dagger/MissingBinding] DialogsInteractor cannot be provided without @Provided-annoated method

I bind the class in an Activity scoped module:

@InstallIn(ActivityComponent::class)
@Module(includes = [ActivityModule.BindsModule::class])
class ActivityModule {
    ...
    @Module
    @InstallIn(ActivityComponent::class)
    interface BindsModule {
        ....
        @Binds
        fun bindDialogsInteractor(dialogsInteractorImpl: DialogsInteractorImpl): DialogsInteractor
    }
}

Also of course added the @Inject constructor:

@ActivityScoped
class DialogsInteractorImpl @Inject constructor(
    @ActivityContext context: Context,
    ....
){

I tried adding a @Provide injection method but still getting the same error.

Checked every dependency DialogsInteractorImpl has and nothing is wrong.

The weird thing is that I have other binds under BindsModule that don't cause any problem.

(I'm getting the problem on 5 different classes)

Thank you!


问:
golang why comparing two variables pointing to struct behaves differently?
I have created two instances of same struct, Confused by the output when I compare two variables point to instances of struct.

```<code>package main

import "fmt"

type Person struct {
    name string
}

func main() {
   p1 := &Person{name: "guru"}
   p2 := &Person{name: "guru"}
   fmt.Println(p1 == p2) // false, compares by address?
   p3 := Person{name: "guru"}
   p4 := Person{name: "guru"}
   fmt.Println(p3 == p4) // true , why? compares by content?
}
</code>```

does == operator works like overload operator?

答:
Your first example

```<code>p1 := &Person{name: "guru"}
p2 := &Person{name: "guru"}

fmt.Println(p1 == p2) // false, compares by address?
</code>```

compares two pointers for equality. Since they each address different memory addresses, the do not compare as equal.

Your second example,

```<code> p3 := Person{name: "guru"}
 p4 := Person{name: "guru"}

fmt.Println(p3 == p4) // true , why? compares by content?
</code>```

compares two struct and does so by value, so they compare equal.

If you dereference the pointer before the comparison, you'll find that they compare as equal. For instance, given

```<code>p1 := &Person{ name: "guru" }
p2 := &Person{ name: "guru" }
p3 :=  Person{ name: "guru" }
p4 :=  Person{ name: "guru" }
</code>```

All of the following compare as equal:

*p1 == *p2

*p1 ==  p3

 p3 == *p2

 p3 ==  p4

Body:
I have created two instances of same struct, Confused by the output when I compare two variables point to instances of struct.

package main

import "fmt"

type Person struct {
    name string
}

func main() {
   p1 := &Person{name: "guru"}
   p2 := &Person{name: "guru"}
   fmt.Println(p1 == p2) // false, compares by address?
   p3 := Person{name: "guru"}
   p4 := Person{name: "guru"}
   fmt.Println(p3 == p4) // true , why? compares by content?
}

does == operator works like overload operator?

Body:
Your first example

p1 := &Person{name: "guru"}
p2 := &Person{name: "guru"}

fmt.Println(p1 == p2) // false, compares by address?

compares two pointers for equality. Since they each address different memory addresses, the do not compare as equal.

Your second example,

 p3 := Person{name: "guru"}
 p4 := Person{name: "guru"}

fmt.Println(p3 == p4) // true , why? compares by content?

compares two struct and does so by value, so they compare equal.

If you dereference the pointer before the comparison, you'll find that they compare as equal. For instance, given

p1 := &Person{ name: "guru" }
p2 := &Person{ name: "guru" }
p3 :=  Person{ name: "guru" }
p4 :=  Person{ name: "guru" }

All of the following compare as equal:

*p1 == *p2

*p1 ==  p3

 p3 == *p2

 p3 ==  p4


问:
How build bidirectional infinite scroll flat listwith javascript no typescript
I am usig react native with javascript, no typescript, and I want use flatlist "react-native-bidirectional-infinite-scroll" but I don't found example in javascript.

How I create flatlist that go to top and bottom with more items?

Thanks

答:
react-native-bidirectional-infinite-scroll authors example with TypeScript code convert to vanilla JavaScript.

utils.js file

// Generate random integer, we will use this to use random message from list of dummy messages.
export const getRandomInt = (min, max) => {
 return Math.floor(Math.random() * (max - min)) + min;
};

// Generate unique key for message component of FlatList.
export const generateUniqueKey = () =>
 `_${Math.random().toString(36).substr(2, 9)}`;

// List of test messages to generate chat data.
export const testMessages = [
 'Hey, where were you yesterday? I was trying to call you',
 'Yeah dude!! Had a really bad night. I was really hungover',
 'lol, thats so typical you. Who did you go out with?',
 'Dont even ask me about it, I am never going drink with Uthred again. That dude is a beast',
 'hahahaha, I can totally imagine!!',
 'Ciao :)',
];

/**
* Mocks the api call to query `n` number of messages.
* We are going to add some timeout before returning the result to simulate an api call over network.
*
* We are going to generate two types of message:
* - sent message
* - received message
*
* This will be controlled by a boolean property on message object - `isMyMessage`.
* This will be randomly assigned to message, based on result of getRandomInt.
* These two messages will be styled differently, which is the case for most of the
* popular messaging applications e.g., whatsapp, messenger
*
* @param n {number} Number of new messages to query
* @param networkLatency {number} Number of milliseconds, to simulate api call.
*/
export const queryMoreMessages  = (n, networkLatency = 100) => {
 return new Promise((resolve) => {
   const newMessages = [];

   for (let i = 0; i < n; i++) {
     const messageText = testMessages[getRandomInt(0, testMessages.length)];
     newMessages.push({
       id: generateUniqueKey(),
       text: messageText,
       isMyMessage: Boolean(getRandomInt(0, 2)), // Randomly assign true or false.
     });
   }

   // Lets resolve after 500 ms, to simulate network latency.
   setTimeout(() => {
     resolve(newMessages);
   }, networkLatency);
 });
};

```
<p>MessageBubble.js file</p>
<pre class="lang-js prettyprint-override"><code>import React from 'react';
import {StyleSheet, Text, View} from 'react-native';

/**
 * UI Component for message item, in message list (FlatList).
 */
export const MessageBubble = ({item}) => {
  if (item.isMyMessage) {
    // Align sent messages to right side of the screen, with a grey'ish background.
    return (
      <View
        key={`${item.id}`}
        style={[styles.messageBubble, styles.myMessageBubble]}>
        <Text style={styles.myMessageText}>{item.text}</Text>
      </View>
    );
  }

  // Align received messages to left side of the screen, with blue background.
  return (
    <View key={`${item.id}`} style={styles.messageBubble}>
      <Text style={styles.messageText}>{item.text}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  messageBubble: {
    maxWidth: 300,
    padding: 10,
    borderRadius: 10,
    marginVertical: 5,
    marginHorizontal: 5,
    backgroundColor: '#F1F0F0',
  },
  myMessageBubble: {
    alignSelf: 'flex-end',
    backgroundColor: '#3784FF',
  },
  messageText: {
    fontSize: 15,
  },
  myMessageText: {
    color: 'white',
    fontSize: 15,
  },
});

</code>```

App.js

import React, {useEffect, useState} from 'react';
import {
  SafeAreaView,
  StyleSheet,
  Text,
  Touchable,
  TouchableOpacity,
  View,
} from 'react-native';

import {FlatList} from 'react-native-bidirectional-infinite-scroll';
import {MessageBubble} from './MessageBubble';
import {queryMoreMessages} from './utils';

// Counter to keep track of how many times `loadMoreRecentMessages` function has been called.
// We want to simulate a UX where user has scrolled till the most recent message available in
// chat. So for our example, we are going stop querying (and appending) new messages to the screen,
// once loadMoreRecentCounter is greater than 2.
// In real chat applications, you generally receive a flag from pagination api, which tells the app
// if user is at the most recent message in chat or not.
let loadMoreRecentCounter = 0;

const App = () => {
  const [messages, setMessages] = useState();
  const [enableAutoscrollToTop, setEnableAutoscrollToTop] = useState(false);
  useEffect(() => {
    // When app is opened, we are going to render 50 messages on screen.
    // Generally this is where you connect to chat server and query first batch of messages.
    const initChat = async () => {
      const initialMessages = await queryMoreMessages(50, 0);
      setMessages(initialMessages);
    };

    initChat();
  }, []);

  // Add 10 more messages to end of the list.
  // In real chat application, this is where you have your pagination logic.
  const loadMoreOlderMessages = async () => {
    const newMessages = await queryMoreMessages(10);
    setMessages((m) => {
      return m.concat(newMessages);
    });
  };

  // Add 10 more messages to beginning of the list.
  // In real chat application, this is where you have your pagination logic.
  const loadMoreRecentMessages = async () => {
    if (loadMoreRecentCounter > 2) {
      // User is at the most recent message in chat.
      !enableAutoscrollToTop && setEnableAutoscrollToTop(true);
      return;
    }

    const newMessages = await queryMoreMessages(10);
    setMessages((m) => {
      return newMessages.concat(m);
    });

    loadMoreRecentCounter += 1;
  };

  /**
   * Simulates a send message feature of Chat applications. It simply adds a randomly
   * generated message at beginning of the list - it can either be a sent or received message.
   */
  const sendMessage = async () => {
    const newMessages = await queryMoreMessages(1, 0);
    setMessages((m) => {
      return newMessages.concat(m);
    });
  };

  if (!messages) {
    // If the messages are not ready, lets not show anything.
    // Generally you can render some kind of loading indicator in this case.
    return null;
  }

  /**
   * NOTE:
   *
   * - You can also control the scroll offset, at which `onEndReached` and `onStartReached`
   *   should be called, using props - onEndReachedThreshold and onStartReachedThrehols
   * - We are using `inverted` FlatList, since thats a common UX for Chat applications.
   */
  return (
    <SafeAreaView style={styles.safeArea}>
      <View style={styles.header}>
        <Text style={styles.headerTitle}>Chat between two users</Text>
      </View>
      <FlatList
        data={messages}
        inverted
        enableAutoscrollToTop={enableAutoscrollToTop}
        onEndReached={loadMoreOlderMessages}
        onStartReached={loadMoreRecentMessages}
        renderItem={MessageBubble}
      />
      <TouchableOpacity onPress={sendMessage} style={styles.sendMessageButton}>
        <Text style={styles.sendButtonTitle}>Send message</Text>
      </TouchableOpacity>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  header: {
    alignItems: 'center',
    paddingVertical: 10,
    borderBottomColor: '#BEBEBE',
    borderBottomWidth: 1,
  },
  headerTitle: {fontSize: 20, fontWeight: 'bold'},
  safeArea: {
    flex: 1,
  },
  sendMessageButton: {
    width: '100%',
    padding: 20,
    backgroundColor: '#FF4500',
    alignItems: 'center',
  },
  sendButtonTitle: {
    color: 'white',
    fontSize: 15,
    fontWeight: 'bold',
  },
});

export default App;

```

Expo snack - https://snack.expo.dev/@emmbyiringiro/cffec2

Note: Don't test with the web version, test with android or iOS

Body:
react-native-bidirectional-infinite-scroll authors example with TypeScript code convert to vanilla JavaScript.

utils.js file

// Generate random integer, we will use this to use random message from list of dummy messages.
export const getRandomInt = (min, max) => {
 return Math.floor(Math.random() * (max - min)) + min;
};

// Generate unique key for message component of FlatList.
export const generateUniqueKey = () =>
 `_${Math.random().toString(36).substr(2, 9)}`;

// List of test messages to generate chat data.
export const testMessages = [
 'Hey, where were you yesterday? I was trying to call you',
 'Yeah dude!! Had a really bad night. I was really hungover',
 'lol, thats so typical you. Who did you go out with?',
 'Dont even ask me about it, I am never going drink with Uthred again. That dude is a beast',
 'hahahaha, I can totally imagine!!',
 'Ciao :)',
];

/**
* Mocks the api call to query `n` number of messages.
* We are going to add some timeout before returning the result to simulate an api call over network.
*
* We are going to generate two types of message:
* - sent message
* - received message
*
* This will be controlled by a boolean property on message object - `isMyMessage`.
* This will be randomly assigned to message, based on result of getRandomInt.
* These two messages will be styled differently, which is the case for most of the
* popular messaging applications e.g., whatsapp, messenger
*
* @param n {number} Number of new messages to query
* @param networkLatency {number} Number of milliseconds, to simulate api call.
*/
export const queryMoreMessages  = (n, networkLatency = 100) => {
 return new Promise((resolve) => {
   const newMessages = [];

   for (let i = 0; i < n; i++) {
     const messageText = testMessages[getRandomInt(0, testMessages.length)];
     newMessages.push({
       id: generateUniqueKey(),
       text: messageText,
       isMyMessage: Boolean(getRandomInt(0, 2)), // Randomly assign true or false.
     });
   }

   // Lets resolve after 500 ms, to simulate network latency.
   setTimeout(() => {
     resolve(newMessages);
   }, networkLatency);
 });
};

MessageBubble.js file

import React from 'react';
import {StyleSheet, Text, View} from 'react-native';

/**
 * UI Component for message item, in message list (FlatList).
 */
export const MessageBubble = ({item}) => {
  if (item.isMyMessage) {
    // Align sent messages to right side of the screen, with a grey'ish background.
    return (
      <View
        key={`${item.id}`}
        style={[styles.messageBubble, styles.myMessageBubble]}>
        <Text style={styles.myMessageText}>{item.text}</Text>
      </View>
    );
  }

  // Align received messages to left side of the screen, with blue background.
  return (
    <View key={`${item.id}`} style={styles.messageBubble}>
      <Text style={styles.messageText}>{item.text}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  messageBubble: {
    maxWidth: 300,
    padding: 10,
    borderRadius: 10,
    marginVertical: 5,
    marginHorizontal: 5,
    backgroundColor: '#F1F0F0',
  },
  myMessageBubble: {
    alignSelf: 'flex-end',
    backgroundColor: '#3784FF',
  },
  messageText: {
    fontSize: 15,
  },
  myMessageText: {
    color: 'white',
    fontSize: 15,
  },
});

App.js

import React, {useEffect, useState} from 'react';
import {
  SafeAreaView,
  StyleSheet,
  Text,
  Touchable,
  TouchableOpacity,
  View,
} from 'react-native';

import {FlatList} from 'react-native-bidirectional-infinite-scroll';
import {MessageBubble} from './MessageBubble';
import {queryMoreMessages} from './utils';

// Counter to keep track of how many times `loadMoreRecentMessages` function has been called.
// We want to simulate a UX where user has scrolled till the most recent message available in
// chat. So for our example, we are going stop querying (and appending) new messages to the screen,
// once loadMoreRecentCounter is greater than 2.
// In real chat applications, you generally receive a flag from pagination api, which tells the app
// if user is at the most recent message in chat or not.
let loadMoreRecentCounter = 0;

const App = () => {
  const [messages, setMessages] = useState();
  const [enableAutoscrollToTop, setEnableAutoscrollToTop] = useState(false);
  useEffect(() => {
    // When app is opened, we are going to render 50 messages on screen.
    // Generally this is where you connect to chat server and query first batch of messages.
    const initChat = async () => {
      const initialMessages = await queryMoreMessages(50, 0);
      setMessages(initialMessages);
    };

    initChat();
  }, []);

  // Add 10 more messages to end of the list.
  // In real chat application, this is where you have your pagination logic.
  const loadMoreOlderMessages = async () => {
    const newMessages = await queryMoreMessages(10);
    setMessages((m) => {
      return m.concat(newMessages);
    });
  };

  // Add 10 more messages to beginning of the list.
  // In real chat application, this is where you have your pagination logic.
  const loadMoreRecentMessages = async () => {
    if (loadMoreRecentCounter > 2) {
      // User is at the most recent message in chat.
      !enableAutoscrollToTop && setEnableAutoscrollToTop(true);
      return;
    }

    const newMessages = await queryMoreMessages(10);
    setMessages((m) => {
      return newMessages.concat(m);
    });

    loadMoreRecentCounter += 1;
  };

  /**
   * Simulates a send message feature of Chat applications. It simply adds a randomly
   * generated message at beginning of the list - it can either be a sent or received message.
   */
  const sendMessage = async () => {
    const newMessages = await queryMoreMessages(1, 0);
    setMessages((m) => {
      return newMessages.concat(m);
    });
  };

  if (!messages) {
    // If the messages are not ready, lets not show anything.
    // Generally you can render some kind of loading indicator in this case.
    return null;
  }

  /**
   * NOTE:
   *
   * - You can also control the scroll offset, at which `onEndReached` and `onStartReached`
   *   should be called, using props - onEndReachedThreshold and onStartReachedThrehols
   * - We are using `inverted` FlatList, since thats a common UX for Chat applications.
   */
  return (
    <SafeAreaView style={styles.safeArea}>
      <View style={styles.header}>
        <Text style={styles.headerTitle}>Chat between two users</Text>
      </View>
      <FlatList
        data={messages}
        inverted
        enableAutoscrollToTop={enableAutoscrollToTop}
        onEndReached={loadMoreOlderMessages}
        onStartReached={loadMoreRecentMessages}
        renderItem={MessageBubble}
      />
      <TouchableOpacity onPress={sendMessage} style={styles.sendMessageButton}>
        <Text style={styles.sendButtonTitle}>Send message</Text>
      </TouchableOpacity>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  header: {
    alignItems: 'center',
    paddingVertical: 10,
    borderBottomColor: '#BEBEBE',
    borderBottomWidth: 1,
  },
  headerTitle: {fontSize: 20, fontWeight: 'bold'},
  safeArea: {
    flex: 1,
  },
  sendMessageButton: {
    width: '100%',
    padding: 20,
    backgroundColor: '#FF4500',
    alignItems: 'center',
  },
  sendButtonTitle: {
    color: 'white',
    fontSize: 15,
    fontWeight: 'bold',
  },
});

export default App;

Expo snack - https://snack.expo.dev/@emmbyiringiro/cffec2

Note: Don't test with the web version, test with android or iOS