问:
Error:Kotlin: Module was compiled with an incompatible version of Kotlin in a project of Spring Boot with Java not Kotlin not gradle
Intellij IDEA and JDK 11, this is not an android project, not using Kotlin. It is a Spring Boot application generated with initilizer. Like this:

https://start.spring.io/starter.zip?type=maven-project&language=java&bootVersion=2.6.3&baseDir=demo&groupId=com.example&artifactId=demo&name=multidatasource&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.demo&packaging=jar&javaVersion=11&dependencies=lombok,data-jpa,mysql,webflux,data-rest

Then I added service code in it. When built, it stopped for been missing error, after I fix them, it cannot be built at all, IDEA gives error:

Information:Kotlin: kotlinc-jvm 1.3.41 (JRE 11.0.4+10-b304.77)

Information:2/11/2022 3:20 PM - Build completed with 1 error and 0 warnings in 1 s 823 ms

Error:Kotlin: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

pom.xml remains the same as generated from above link. I checked IDEA module settings, nothing odd.
And I grep -rn kotlin * in project folder, no matched result.

Then I wonder if it is because dependency has kotlin confliction, so I start from a fresh download project, and run it successfully (it proves that kotlin problem is not because of dependencies); then I replace folder src, it run successfully too.

Has anyone used a Spring Boot + Java + maven, and IDEA, and perhaps JDK11, and encountered the same error?

Thanks.

updates:
I think this is an Intellij IDEA bug, not all run has this problem

答: I have just had the exact problem. Just go to the Build menu and click on the rebuild project.</p>


来源: stackexchange

问:
Clicking a button image using selenium and Python
I'm trying to click that button, I've tried several ways and I couldn't.

bottom id = edita_cliente

HTML:

```<code><div class="card mb-3" style="color: #ace;">
                <div class="card-header">
                        <div class="card-title" style="text-align: left; font-size: 16px;margin: 5px;">
                            <div style="display: inline-block; width: 100px">
                            <i style="padding-left: 15px; cursor: pointer;" id="novo_cliente" class="tooltipped fas fa-plus-circle" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="Novo cliente"></i>
                            <i style="padding-left: 15px; cursor: pointer;" id="edita_cliente" class="tooltipped far fa-edit" data-toggle="tooltip" data-placement="bottom" title="" data-valor="203739" data-original-title="Editar cliente"></i>
</code>```

答:
To click() on a element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

Using CSS_SELECTOR:

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "i#edita_cliente[data-original-title='Editar cliente']"))).click()
</code>```

Using XPATH:

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//i[@id='edita_cliente' and @data-original-title='Editar cliente']"))).click()
</code>```

Note: You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

ContentLicense: CC BY-SA 4.0

Body:
To click() on a element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

Using CSS_SELECTOR:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "i#edita_cliente[data-original-title='Editar cliente']"))).click()

Using XPATH:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//i[@id='edita_cliente' and @data-original-title='Editar cliente']"))).click()

Note: You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


问:
Fade a color to white (increasing brightness)
I want to make a text box in .NET "glow" yellow, and then "fade" to white (basically, by incrementally increasing the brightness). I think Stackoverflow does this after you've posted an answer. I know that increasing brightness is not all that simple (it's not just uniformly increasing/decreasing RGB), but I'm not sure how to do this.

Perfect color accuracy is not important for this. I am using C#, although VB examples would be just fine, too.

Edit: This is for Winforms.

答:
You didn't originally specify a technology when I submitted this answer, but here's how you'd do it using jQuery.

UI/Effects/Highlight.

```<code>$("div").click(function () {
      $(this).effect("highlight", {}, 3000);
});
</code>```

OwnerDisplayName: Jon B

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Jon B

Body:
You didn't originally specify a technology when I submitted this answer, but here's how you'd do it using jQuery.

UI/Effects/Highlight.

$("div").click(function () {
      $(this).effect("highlight", {}, 3000);
});

OwnerDisplayName: Chris Doggett

LastEditorDisplayName: Chris Doggett


问:
Doing multiple sorts across more than one line of code?
I have an array that stores the order that I want to sort a list by.

```<code>SortOrderArray: "Color", "Volume", "Weight"
</code>```

So I want to order my list by Color, Volume, then Weight

```<code>MyList.OrderBy(a=>a.Color).ThenBy(a=>a.Volume).ThenBy(a=>a.Weight).ToList();
</code>```

So that's pretty good.  Now, I want to be able to write a function that does this sorting based on the sortOrder array I send in:

```<code>public List<row> GetSortedList(List<row> list, string[] sortOrder){
    ???
}
</code>```

I can't figure out how to do this without writing a linq query for every combination of sortOrders (27 different queries just seems like the worst way to accomplish this, and has a fairly high possibility of me making a tiny mistake).  I would like to be able to just write 3 linq queries that reorders the list according to each of the 3 sorting methods, something like this:

```<code>switch(sortOrder[0]){
    Sort by the first sort method
}
switch(sortOrder[1]){
    Sort by the second sort method
}
switch(sortOrder[2]){
    Sort by the third sort method
}
</code>```

But if I try doing the above code, it just resorts it each time, instead of doing sub-sorts after the one above it.  Hope that is clear, any help would be appreciated.

答:
I guess, you are not using the return value of the order clauses.

```<code>public List<row> GetSortedList(List<row> list, string[] sortOrder)
{
    IOrderedEnumerable<row> result = null;

    bool first = true;

    foreach(sortClause in sortOrder)
    {
        switch sortClause
        {
            case "Color":
                if(first)
                    result = list.OrderBy(x => x.Color);
                else
                    result = result.ThenBy(x => x.Color);
                break;
            // the other cases
        }
        first = false;
    }

    return result.ToList();
}
</code>```

Something like that.

ContentLicense: CC BY-SA 3.0

Body:
I have an array that stores the order that I want to sort a list by.

SortOrderArray: "Color", "Volume", "Weight"

So I want to order my list by Color, Volume, then Weight

MyList.OrderBy(a=>a.Color).ThenBy(a=>a.Volume).ThenBy(a=>a.Weight).ToList();

So that's pretty good.  Now, I want to be able to write a function that does this sorting based on the sortOrder array I send in:

public List<row> GetSortedList(List<row> list, string[] sortOrder){
    ???
}

I can't figure out how to do this without writing a linq query for every combination of sortOrders (27 different queries just seems like the worst way to accomplish this, and has a fairly high possibility of me making a tiny mistake).  I would like to be able to just write 3 linq queries that reorders the list according to each of the 3 sorting methods, something like this:

switch(sortOrder[0]){
    Sort by the first sort method
}
switch(sortOrder[1]){
    Sort by the second sort method
}
switch(sortOrder[2]){
    Sort by the third sort method
}

But if I try doing the above code, it just resorts it each time, instead of doing sub-sorts after the one above it.  Hope that is clear, any help would be appreciated.

Body:
I guess, you are not using the return value of the order clauses.

public List<row> GetSortedList(List<row> list, string[] sortOrder)
{
    IOrderedEnumerable<row> result = null;

    bool first = true;

    foreach(sortClause in sortOrder)
    {
        switch sortClause
        {
            case "Color":
                if(first)
                    result = list.OrderBy(x => x.Color);
                else
                    result = result.ThenBy(x => x.Color);
                break;
            // the other cases
        }
        first = false;
    }

    return result.ToList();
}

Something like that.


问:
correct sign when converting sin to cos (or vice versa) using sin = sqrt(1-cos^2)
I'm using the formula sin = sqrt(1-cos^2) to convert from cos to sin where source angle is not known an a call to arccos is too expensive. This operation obviously produces a wrong sign if source angle is in the 3rd or 4th quadrants. Could someone recommend me an effective way to compute the correct sign?

Thank you!

答:
The correct sign will depend on the quadrant of the original angle. If you don't have the angle, the solution is ambiguous.

Note that the arccos will not solve your problem because it will return only angles in the 1st and 2nd quadrants.

You simply do not have enough information!


问:
How to 'melt' a wide table/array in google app script?
I have an array/table in Google Sheets with data in the following format:

Catergory1
A
A
A
A
A
B
B
B
B
B
C
C
C
C
C

Catergory2
Q1
Q2
Q3
Q4
Q5
Q1
Q2
Q3
Q4
Q5
Q1
Q2
Q3
Q4
Q5

Propotions
34%
66%
9%
49%
31%
36%
69%
1%
10%
20%
98%
38%
21%
57%
76%

I want to use Google App Script to convert this array into the following format:

Catergory1
Q1
Q2
Q3
Q4
Q5

A
34%
66%
9%
49%
31%

B
36%
69%
1%
10%
20%

C
98%
38%
21%
57%
76%

Thanks in advance.

答:
app script

Try this

```<code>function myFunction(){
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sh = ss.getActiveSheet()
  var values = sh.getRange(1,2,3,sh.getLastColumn()-1).getValues()
  var rows = Array.from(new Set(values[0])).sort();
  var cols = Array.from(new Set(values[1])).sort();
  var result = Array.from({ length: rows.length }, () => Array.from({ length: cols.length }, () => ''));
  for (var i=0;i<sh.getLastColumn()-1;i++){
    result[rows.indexOf(values[0][i])][cols.indexOf(values[1][i])] = values[2][i]
  }
  sh.getRange(6,1,rows.length,1).setValues(transpose([rows]))
  sh.getRange(5,2,1,cols.length).setValues([cols])
  sh.getRange(6,2,rows.length,cols.length).setValues(result)
}
function transpose(a){
  return Object.keys(a[0]).map(function (c) { return a.map(function (r) { return r[c]; }); });
}
</code>```

formula

```<code>=query(TRANSPOSE(B1:3),"select Col1, sum(Col3) where Col1 is not null group by Col1 pivot Col2")
</code>```

Body:
app script

Try this

function myFunction(){
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sh = ss.getActiveSheet()
  var values = sh.getRange(1,2,3,sh.getLastColumn()-1).getValues()
  var rows = Array.from(new Set(values[0])).sort();
  var cols = Array.from(new Set(values[1])).sort();
  var result = Array.from({ length: rows.length }, () => Array.from({ length: cols.length }, () => ''));
  for (var i=0;i<sh.getLastColumn()-1;i++){
    result[rows.indexOf(values[0][i])][cols.indexOf(values[1][i])] = values[2][i]
  }
  sh.getRange(6,1,rows.length,1).setValues(transpose([rows]))
  sh.getRange(5,2,1,cols.length).setValues([cols])
  sh.getRange(6,2,rows.length,cols.length).setValues(result)
}
function transpose(a){
  return Object.keys(a[0]).map(function (c) { return a.map(function (r) { return r[c]; }); });
}

formula

=query(TRANSPOSE(B1:3),"select Col1, sum(Col3) where Col1 is not null group by Col1 pivot Col2")


问:
Conditionally add commands to SwiftUI WindowGroup
With macOS 12 Apple fixed the omission of „Continuity Camera“ in SwiftUI by introducing the command group ImportFromDevicesCommands which can simply be added to a window.

But when you try to use it in an app supporting macOS 11 and 12, you are missing the conditionality support as it is common when combining SwiftUI views.

I have tried the following:

import SwiftUI

@main
struct ThrowAwayApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .commands {
            if #available(macOS 12, *) {
                ImportFromDevicesCommands()
            }
        }
    }
}
```
<p>But the compiler brings up the following error message:</p>
```Closure containing control flow statement cannot be used with result builder 'CommandsBuilder'
```

I understand the CommandsBuilder does not support buildIf(), buildEither(first:) and buildEither(second:) and is therefore missing the if-block support as for SwiftUI views.

Is there a way to conditionally add commands to the WindowGroup?
Can I do some trickery with @available? (I'm really missing the @unavailable...)

答:
I've come up with a solution which allows me to check whether code is compiled for macOS 11 or macOS 12 by defining derived User-Defined build configuration in Xcodes project settings:

```<code>TARGET_MAJOR = $(SUPPORTED_PLATFORMS:upper)$(MACOSX_DEPLOYMENT_TARGET:base)
</code>```

And then referring to this variable in the Other Swift Flags

```<code>OTHER_SWIFT_FLAGS = -DTARGET_$(TARGET_MAJOR)
</code>```

Afterwards I can conditionally compile code for macOS 12 by using:

WindowGroup {
    ContentView()
}
.commands {
#if TARGET_MACOSX12
    ImportFromDevicesCommands()
#elseif TARGET_MACOSX11
    #warning("ImportFromDevicesCommands not implemented")
#endif
}
```

Body:
With macOS 12 Apple fixed the omission of „Continuity Camera“ in SwiftUI by introducing the command group ImportFromDevicesCommands which can simply be added to a window.

But when you try to use it in an app supporting macOS 11 and 12, you are missing the conditionality support as it is common when combining SwiftUI views.

I have tried the following:

import SwiftUI

@main
struct ThrowAwayApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .commands {
            if #available(macOS 12, *) {
                ImportFromDevicesCommands()
            }
        }
    }
}

But the compiler brings up the following error message:

Closure containing control flow statement cannot be used with result builder 'CommandsBuilder'

I understand the CommandsBuilder does not support buildIf(), buildEither(first:) and buildEither(second:) and is therefore missing the if-block support as for SwiftUI views.

Is there a way to conditionally add commands to the WindowGroup?
Can I do some trickery with @available? (I'm really missing the @unavailable...)

Body:
I've come up with a solution which allows me to check whether code is compiled for macOS 11 or macOS 12 by defining derived User-Defined build configuration in Xcodes project settings:

TARGET_MAJOR = $(SUPPORTED_PLATFORMS:upper)$(MACOSX_DEPLOYMENT_TARGET:base)

And then referring to this variable in the Other Swift Flags

OTHER_SWIFT_FLAGS = -DTARGET_$(TARGET_MAJOR)

Afterwards I can conditionally compile code for macOS 12 by using:

WindowGroup {
    ContentView()
}
.commands {
#if TARGET_MACOSX12
    ImportFromDevicesCommands()
#elseif TARGET_MACOSX11
    #warning("ImportFromDevicesCommands not implemented")
#endif
}


问:
JavaScript function default parameters

const add = (a = 1, b = 1, c = 1) => a + b + c
add(4, , 2)```

Throws Uncaught SyntaxError, unexpected token ','

How do I call the function so b defaults to the value 1

答:
Just take undefined as value.

const add = (a = 1, b = 1, c = 1) => a + b + c
console.log(add(4, undefined, 2));```

Title: JavaScript function default parameters

Body:
const add = (a = 1, b = 1, c = 1) => a + b + c
add(4, , 2)

Throws Uncaught SyntaxError, unexpected token ','

How do I call the function so b defaults to the value 1


问:
Programmatically navigate using React router
With react-router I can use the Link element to create links which are natively handled by react router.

I see internally it calls this.context.transitionTo(...).

I want to do a navigation. Not from a link, but from a dropdown selection (as an example). How can I do this in code? What is this.context?

I saw the Navigation mixin, but can I do this without mixins?

答:
For Latest react-router-dom v6

useHistory() is replaced with useNavigate().

You need to use:

```<code>import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
navigate('/your-page-link');
</code>```

Body:
For Latest react-router-dom v6

useHistory() is replaced with useNavigate().

You need to use:

import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
navigate('/your-page-link');


问:
How to remove old chart and append new chart to div using chartjs
I need to remove an old chart when the user clicks a button to retrieve a new chart. Im aware that the chart needs to be destroyed before a new one is created but the charts are not created globally, they cannot be destroyed with the code I have now. Are there any workarounds?
When I click another button to display a chart it wont display because the previous chart/canvas is still there

```<code><template>
  <div class="container-fluid">
    <div class="row">
      <div class="col-12 p-0">
        <div class="jumbotron min-vh-100 text-center m-0 d-flex flex-column">
          <h1 class="display-1" style="margin-top: 10px">Sentiment</h1>
          <form v-on:submit.prevent="generateSentiment().then(getSentiment)">
            <p style="margin-top: 30px">
              <input
                :disabled="isDisabled"
                v-model="video_ID"
                type="text"
                class="form-control input-lg mx-auto"
                id="youtube-url"
                placeholder="youtube addess"
                style="width: 15%"
              />
            </p>
            <p style="margin-top: 30px">
              <button class="btn btn-primary btn-lg" :disabled="isDisabled" v-on:click="isHidden = !isHidden">get sentiment</button>
            </p>
            <p style="margin-top: 28px"><span>{{ sentimentComment }}</span></p>
            <p style="margin-top: 5px" v-if="!isHidden">Refresh to generate new sentiment</p>
          </form>
          <p style="margin-top: 10px"></p>
           <div class="btn-groupd">
                <button class="btn btn-secondary mr-1" role="button" v-if="!isHidden" @click="drawChart">Total Sentiment</button>
                <button class="btn btn-secondary mr-1" role="button" v-if="!isHidden" @click="drawPieChart">ML Sentiment</button>
                <button class="btn btn-secondary mr-1" role="button" v-if="!isHidden">Lexicon Sentiment</button>
          </div>
          <div id = "canvas-div">
          <canvas v-if="!isHidden" id = 'example' height = '90' width = '400' ></canvas>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import axios from "axios";
import { defineComponent } from "vue";
import { Chart, registerables } from "chart.js";

export default defineComponent({
  name: "app",
  data() {
    return {
      commentSentiment: "",
      video_ID: "",
      sentimentRank: 0,
      sentimentComment: "",
      totalPositiveSent: 0,
      totalNegativeSent: 0,
      totalPosMLSen: 0,
      totalNegMLSen: 0,
      isHidden: true,
      isDisabled: false,
    };
  },
  methods: {
    generateSentiment: function() {
      this.isDisabled = true
      return axios
        .post("http://localhost:3000/api/yt", { video_ID: `${this.video_ID}` })
        .then((response) => {
          this.video_ID = response.data.video_ID;
        })
        .catch((error) => {
          window.alert(`The api returned an error: ${error}`);
        });

    },
    getSentiment: function() {
      return axios
        .get("http://localhost:3000/api/yt/get")
        .then((response) => {
          this.sentimentRank = response.data.sentScore.SentScore;
          this.totalPositiveSent =
            response.data.sentScore.TotalPositiveComments;
          this.totalNegativeSent =
            response.data.sentScore.TotalNegativeComments;
          this.totalPosMLSen = response.data.sentScore.PositiveMLComments
          this.totalNegMLSen = response.data.sentScore.NegativeMLComments
          // console.log(this.totalPositiveSent)
          if (this.sentimentRank == 0) {
            return;
          } else if (this.sentimentRank == 1) {
            return (this.sentimentComment = `This video has a good sentiment`);
          } else if (this.sentimentRank == -1) {
            return (this.sentimentComment = `This video has a bad sentiment`);
          }
        })

        .catch((error) => {
          window.alert(`The api returned an error: ${error}`);
        });
    },
    drawChart: function() {
      Chart.register(...registerables)
      let canvas = document.getElementById('example')
        let ctx = canvas.getContext('2d')
        const chrt = new Chart(ctx, {
        type: 'bar',
        data: {
        labels: ["Positive Sentiment", "Negative Sentiment"],
        datasets: [
          {
            label: "Overall Sentiment",
            backgroundColor: ["green", "red"],
            data: [this.totalPositiveSent, this.totalNegativeSent],
          },
          ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: true,
      }
      });
        chrt.render();
    },
    drawPieChart: function() {
      Chart.register(...registerables)
      let canvas = document.getElementById('example')
      let ctx = canvas.getContext('2d')
      const chrt = new Chart(ctx, {
        type: 'pie',
        data: {
        labels: ["Positive Sentiment", "Negative Sentiment"],
        datasets: [
          {
            label: "Overall ML Sentiment",
            backgroundColor: ["green", "red"],
            data: [this.totalPosMLSen, this.totalNegMLSen],
          },
          ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: true,
      }
      });
        chrt.render();
    },
  },
});
</script>
</code>```

答:
You can use the API method getChart to see if it exists. If it does not exist it will return undefined, if it does exist it will return that chart.

So you would get:

const tmpChart = Chart.getChart('canvasID');
if (tmpChart) {
  tmpChart.destroy()
}
```

Body:
I need to remove an old chart when the user clicks a button to retrieve a new chart. Im aware that the chart needs to be destroyed before a new one is created but the charts are not created globally, they cannot be destroyed with the code I have now. Are there any workarounds?
When I click another button to display a chart it wont display because the previous chart/canvas is still there

<template>

Sentiment

          <form v-on:submit.prevent="generateSentiment().then(getSentiment)">

              <input
                :disabled="isDisabled"
                v-model="video_ID"
                type="text"
                class="form-control input-lg mx-auto"
                id="youtube-url"
                placeholder="youtube addess"
                style="width: 15%"
              />

              <button class="btn btn-primary btn-lg" :disabled="isDisabled" v-on:click="isHidden = !isHidden">get sentiment</button>

{{ sentimentComment }}

Refresh to generate new sentiment

          </form>

                <button class="btn btn-secondary mr-1" role="button" v-if="!isHidden" @click="drawChart">Total Sentiment</button>
                <button class="btn btn-secondary mr-1" role="button" v-if="!isHidden" @click="drawPieChart">ML Sentiment</button>
                <button class="btn btn-secondary mr-1" role="button" v-if="!isHidden">Lexicon Sentiment</button>

          <canvas v-if="!isHidden" id = 'example' height = '90' width = '400' ></canvas>

</template>


问:
why can't we use BlocProvider.of(blocContext) inside of Consumer with bloc attribute? and what is the solution?
inside of a build method:

```<code>  return BlocBuilder<UserCubit, UserState>(
    bloc: UserCubit("firstName", "lastName"),
    builder: (BuildContext blocContext, UserState state) {
                  print(BlocProvider.of<UserCubit>(blocContext).user.fullName);  // error here
});
</code>```

error:

```<code>BlocProvider.of() called with a context that does not contain a UserCubit.
</code>```

which is obviously not the case...

the question is, how can I access the cubit in case of BlocBuilder/BlocConsumer where bloc attribute is not null.

答:
Basically it is because the widget BlocBuilder is not injecting the provided bloc parameter in your BuildContext blocContext.

The flutter_bloc documentation says that that BlocBuilder is working like a StreamBuilder, it is not injecting anything in your widget tree it will only "listen" to your provided UserCubit in the bloc property. And because UserCubit is not injected in your widget tree you won't ever be able to access it by using BlocProvider.

BlocBuilder handles building a widget in response to new states.
BlocBuilder is analogous to StreamBuilder but has simplified API to
reduce the amount of boilerplate code needed as well as bloc-specific
performance improvements.

When you are using a BlocBuilder you will need to rely on the state value to access properties from your bloc or cubit and you will have to inject your bloc/cubit in the widget tree by using a parent BlocProvider, here's an example:

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final userCubit = UserCubit("firstName", "lastName");

    // Using BlocProvider to inject your UserCubit
    return BlocProvider(
      create: (_) => userCubit,
      child: BlocBuilder<UserCubit, UserState>(
        // Still using the instance of userCubit as the injected instance is not
        // available in the widget tree at this point.
        bloc: userCubit,
        builder: (blocContext, state) {
          // Now that you are in your builder with an up-to-date blocContext you can
          // have access to your instance of UserCubit with BlocProvider.
          print(BlocProvider.of<UserCubit>(blocContext).user.fullName);
          return Text("State is $state");
        },
      ),
    );
  }
}
```

You can try the full example on DartPad

Body:
inside of a build method:

  return BlocBuilder<UserCubit, UserState>(
    bloc: UserCubit("firstName", "lastName"),
    builder: (BuildContext blocContext, UserState state) {
                  print(BlocProvider.of<UserCubit>(blocContext).user.fullName);  // error here
});

error:

BlocProvider.of() called with a context that does not contain a UserCubit.

which is obviously not the case...

the question is, how can I access the cubit in case of BlocBuilder/BlocConsumer where bloc attribute is not null.

Body:
Basically it is because the widget BlocBuilder is not injecting the provided bloc parameter in your BuildContext blocContext.

The flutter_bloc documentation says that that BlocBuilder is working like a StreamBuilder, it is not injecting anything in your widget tree it will only "listen" to your provided UserCubit in the bloc property. And because UserCubit is not injected in your widget tree you won't ever be able to access it by using BlocProvider.

BlocBuilder handles building a widget in response to new states.
BlocBuilder is analogous to StreamBuilder but has simplified API to
reduce the amount of boilerplate code needed as well as bloc-specific
performance improvements.

When you are using a BlocBuilder you will need to rely on the state value to access properties from your bloc or cubit and you will have to inject your bloc/cubit in the widget tree by using a parent BlocProvider, here's an example:

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final userCubit = UserCubit("firstName", "lastName");

    // Using BlocProvider to inject your UserCubit
    return BlocProvider(
      create: (_) => userCubit,
      child: BlocBuilder<UserCubit, UserState>(
        // Still using the instance of userCubit as the injected instance is not
        // available in the widget tree at this point.
        bloc: userCubit,
        builder: (blocContext, state) {
          // Now that you are in your builder with an up-to-date blocContext you can
          // have access to your instance of UserCubit with BlocProvider.
          print(BlocProvider.of<UserCubit>(blocContext).user.fullName);
          return Text("State is $state");
        },
      ),
    );
  }
}

You can try the full example on DartPad


答:
Pass undefined as value

Check this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters#passing_undefined_vs._other_falsy_values

const add = (a = 1, b = 1, c = 1) => a + b + c
console.log(add(4, undefined, 2))```

Title: JavaScript function default parameters


问:
parsing across multiple lines with ansible
So I have an inventory output from a device that looks like this:

```<code>Name: "Chassis", DESCR: "ASA 5555-X with SW, 8 GE Data, 1 GE Mgmt"
PID: ASA5555           , VID: V05     , SN: FTXxxxxxD1

Name: "power supply 0", DESCR: "ASA 5545-X/5555-X AC Power Supply"
PID: ASA-PWR-AC        , VID: N/A     , SN: 6BxxNN

Name: "power supply 1", DESCR: "ASA 5545-X/5555-X AC Power Supply"
PID: ASA-PWR-AC        , VID: N/A     , SN: 6AxxxP

Name: "Storage Device 1", DESCR: "Model Number: Micron_M600_MTFDDAK128MBF"
PID: N/A               , VID: N/A     , SN: MSxxxxxKZ

Name: "Storage Device 2", DESCR: "Model Number: Micron_M600_MTFDDAK128MBF"
PID: N/A               , VID: N/A     , SN: MSAxxxxxYS
</code>```

This is the task that use to split the output, that the two corresponding lines for an item become a item in a list:

```<code> - name: split lines
      set_fact:
        item_list: "{{ inventory.stdout.split('\n\n') }}"
</code>```

Debug show this:

```<code>ok: [localhost] => {
    "msg": [
        "Name: \"Chassis\", DESCR: \"ASA 5555-X with SW, 8 GE Data, 1 GE Mgmt\"\nPID: ASA5555           , VID: V05     , SN: FTX21xxxxx3",
        "Name: \"power supply 0\", DESCR: \"ASA 5545-X/5555-X AC Power Supply\"\nPID: ASA-PWR-AC        , VID: N/A     , SN: 6xxxxxN",
        "Name: \"power supply 1\", DESCR: \"ASA 5545-X/5555-X AC Power Supply\"\nPID: ASA-PWR-AC        , VID: N/A     , SN: 6AxxxxP",
        "Name: \"Storage Device 1\", DESCR: \"Model Number: Micron_M600_MTFDDAK128MBF\"\nPID: N/A               , VID: N/A     , SN: MSAxxxxxxxZ",
        "Name: \"Storage Device 2\", DESCR: \"Model Number: Micron_M600_MTFDDAK128MBF\"\nPID: N/A               , VID: N/A     , SN: MSA2xxxxxxS"
    ]
}
</code>```

But I cannot get this into a proper dictionary with key value pairs for my next task.
Isn't there an easier method or parsing the text directly into a dict?

答:
Use the filter from_yaml to convert the items to dictionaries. For example

    - set_fact:
        dev: "{{ dev|d([]) + [_dict|from_yaml] }}"
      loop: "{{ inventory.stdout.split('\n\n') }}"
      vars:
        _dict: "{ {{ item.split('\n')|join(',') }} }"
```
<p>gives</p>
<pre class="lang-yaml prettyprint-override"><code>  dev:
  - DESCR: ASA 5555-X with SW, 8 GE Data, 1 GE Mgmt
    Name: Chassis
    PID: ASA5555
    SN: FTXxxxxxD1
    VID: V05
  - DESCR: ASA 5545-X/5555-X AC Power Supply
    Name: power supply 0
    PID: ASA-PWR-AC
    SN: 6BxxNN
    VID: N/A
  - DESCR: ASA 5545-X/5555-X AC Power Supply
    Name: power supply 1
    PID: ASA-PWR-AC
    SN: 6AxxxP
    VID: N/A
  - DESCR: 'Model Number: Micron_M600_MTFDDAK128MBF'
    Name: Storage Device 1
    PID: N/A
    SN: MSxxxxxKZ
    VID: N/A
  - DESCR: 'Model Number: Micron_M600_MTFDDAK128MBF'
    Name: Storage Device 2
    PID: N/A
    SN: MSAxxxxxYS
    VID: N/A
</code>```

Body:
So I have an inventory output from a device that looks like this:

Name: "Chassis", DESCR: "ASA 5555-X with SW, 8 GE Data, 1 GE Mgmt"
PID: ASA5555           , VID: V05     , SN: FTXxxxxxD1

Name: "power supply 0", DESCR: "ASA 5545-X/5555-X AC Power Supply"
PID: ASA-PWR-AC        , VID: N/A     , SN: 6BxxNN

Name: "power supply 1", DESCR: "ASA 5545-X/5555-X AC Power Supply"
PID: ASA-PWR-AC        , VID: N/A     , SN: 6AxxxP

Name: "Storage Device 1", DESCR: "Model Number: Micron_M600_MTFDDAK128MBF"
PID: N/A               , VID: N/A     , SN: MSxxxxxKZ

Name: "Storage Device 2", DESCR: "Model Number: Micron_M600_MTFDDAK128MBF"
PID: N/A               , VID: N/A     , SN: MSAxxxxxYS

This is the task that use to split the output, that the two corresponding lines for an item become a item in a list:

 - name: split lines
      set_fact:
        item_list: "{{ inventory.stdout.split('\n\n') }}"

Debug show this:

ok: [localhost] => {
    "msg": [
        "Name: \"Chassis\", DESCR: \"ASA 5555-X with SW, 8 GE Data, 1 GE Mgmt\"\nPID: ASA5555           , VID: V05     , SN: FTX21xxxxx3",
        "Name: \"power supply 0\", DESCR: \"ASA 5545-X/5555-X AC Power Supply\"\nPID: ASA-PWR-AC        , VID: N/A     , SN: 6xxxxxN",
        "Name: \"power supply 1\", DESCR: \"ASA 5545-X/5555-X AC Power Supply\"\nPID: ASA-PWR-AC        , VID: N/A     , SN: 6AxxxxP",
        "Name: \"Storage Device 1\", DESCR: \"Model Number: Micron_M600_MTFDDAK128MBF\"\nPID: N/A               , VID: N/A     , SN: MSAxxxxxxxZ",
        "Name: \"Storage Device 2\", DESCR: \"Model Number: Micron_M600_MTFDDAK128MBF\"\nPID: N/A               , VID: N/A     , SN: MSA2xxxxxxS"
    ]
}

But I cannot get this into a proper dictionary with key value pairs for my next task.
Isn't there an easier method or parsing the text directly into a dict?

Body:
Use the filter from_yaml to convert the items to dictionaries. For example

    - set_fact:
        dev: "{{ dev|d([]) + [_dict|from_yaml] }}"
      loop: "{{ inventory.stdout.split('\n\n') }}"
      vars:
        _dict: "{ {{ item.split('\n')|join(',') }} }"

gives

  dev:
  - DESCR: ASA 5555-X with SW, 8 GE Data, 1 GE Mgmt
    Name: Chassis
    PID: ASA5555
    SN: FTXxxxxxD1
    VID: V05
  - DESCR: ASA 5545-X/5555-X AC Power Supply
    Name: power supply 0
    PID: ASA-PWR-AC
    SN: 6BxxNN
    VID: N/A
  - DESCR: ASA 5545-X/5555-X AC Power Supply
    Name: power supply 1
    PID: ASA-PWR-AC
    SN: 6AxxxP
    VID: N/A
  - DESCR: 'Model Number: Micron_M600_MTFDDAK128MBF'
    Name: Storage Device 1
    PID: N/A
    SN: MSxxxxxKZ
    VID: N/A
  - DESCR: 'Model Number: Micron_M600_MTFDDAK128MBF'
    Name: Storage Device 2
    PID: N/A
    SN: MSAxxxxxYS
    VID: N/A


问:
In MongoDB's pymongo, how do I do a count()?
```<code>for post in db.datasets.find({"test_set":"abc"}).sort("abc",pymongo.DESCENDING).skip((page-1)*num).limit(num):
</code>```

How do I get the count()?

答: This thread happens to be 11 years old. However, in 2022 the 'count()' function has been deprecated. Here is a way I came up with to count documents in MongoDB using Python. Here is a picture of the code snippet. Making a empty list is not needed I just wanted to be outlandish. Hope this helps :). Code snippet here.</p>

Body:
for post in db.datasets.find({"test_set":"abc"}).sort("abc",pymongo.DESCENDING).skip((page-1)*num).limit(num):

How do I get the count()?


答:
This function works by computing the run lengths of consecutive zeroes, then replacing any runs longer than 1 with NA in the original vector:

```<code>NArun0 = function(v){
   vr=rle(v==0)
   vr$values = vr$length>1 & vr$values
   rv=inverse.rle(vr)
   v[rv]=NA
   v
}
</code>```

And a bunch of simple tests:

```<code>> NArun0(c(0,0,0,0))
[1] NA NA NA NA
> NArun0(c(0,1,1,0))
[1] 0 1 1 0
> NArun0(c(0,1,0,2,0))
[1] 0 1 0 2 0
> NArun0(c(0,1,0,0,2,0))
[1]  0  1 NA NA  2  0
> NArun0(c(0,1,0,0,2,0,0))
[1]  0  1 NA NA  2 NA NA
> NArun0(c(0,0,1,0,0,2,0,0))
[1] NA NA  1 NA NA  2 NA NA
</code>```

Note that the answer given in the question returns NA for all zeroes for me:

```<code>> v = c(1,0,2,3,4,0,0,0,0,9)
> ifelse(v==0 & lag(v)==0, NA, v)
 [1]  1 NA  2  3  4 NA NA NA NA  9
</code>```

I thought maybe it was because lag was operating on a time series vector, but if I convert v to a time series vector:

```<code>> v = ts(v)
> ifelse(v==0 & lag(v)==0, NA, v)
Time Series:
Start = 1
End = 9
Frequency = 1
[1]  1  0  2  3  4 NA NA NA  0
</code>```

I do get a zero, but also a zero in last place, because of the way lag works. So I dont understand how the code in the question gives the answer.

Title: I need to detect zero sequences and replace them with NAs

Body:
I am working with air quality data and I need to detect zero sequences (2+ zeros in sequence) and replace each element of this sequence with NA. The solo zero values must remain in the data.

Here's and example of the data:

date    TEMP    PM10    O3 (ug/m3)
5/25/2012 18:00:00  23,8    55  6,30397494404564
5/25/2012 19:00:00  22,8    75  0
5/25/2012 20:00:00  19,8    75  1,99689085129112
5/25/2012 21:00:00  15,3    98  11,1542397707455
5/25/2012 22:00:00  16,2    64  2,02173552751248
5/25/2012 23:00:00  16,3    44  0
5/25/2012 0:00:00   17,1    65  0
5/26/2012 1:00:00   17,5    73  0
5/26/2012 2:00:00   17,2    62  0
5/26/2012 3:00:00   17,1    45  0
5/26/2012 4:00:00   17  37  0
5/26/2012 5:00:00   17,3    29  0
5/26/2012 6:00:00   17,2    50  0
5/26/2012 7:00:00   17,1    36  0
5/26/2012 8:00:00   17,1    43  0
5/26/2012 9:00:00   17,9    45  0
5/26/2012 10:00:00  19,5    72  0
5/26/2012 11:00:00  21,3    85  3,57609276547571
5/26/2012 12:00:00  22,3    81  12,8699598468684

So, here I am with a solution:
df$oz<-ifelse(df$`O3 (ug/m3)`==0 & lag(df$`O3 (ug/m3)`)==0,NA,df$`O3 (ug/m3)`)

date    TEMP    PM10    O3 (ug/m3)  oz
5/25/2012 18:00:00  23,8    55  6,30397494404564    6,30397494404564
5/25/2012 19:00:00  22,8    75  0   0
5/25/2012 20:00:00  19,8    75  1,99689085129112    1,99689085129112
5/25/2012 21:00:00  15,3    98  11,1542397707455    11,1542397707455
5/25/2012 22:00:00  16,2    64  2,02173552751248    2,02173552751248
5/25/2012 23:00:00  16,3    44  0   NA
5/25/2012 0:00:00   17,1    65  0   NA
5/26/2012 1:00:00   17,5    73  0   NA
5/26/2012 2:00:00   17,2    62  0   NA
5/26/2012 3:00:00   17,1    45  0   NA
5/26/2012 4:00:00   17  37  0   NA
5/26/2012 5:00:00   17,3    29  0   NA
5/26/2012 6:00:00   17,2    50  0   NA
5/26/2012 7:00:00   17,1    36  0   NA
5/26/2012 8:00:00   17,1    43  0   NA
5/26/2012 9:00:00   17,9    45  0   NA
5/26/2012 10:00:00  19,5    72  0   NA
5/26/2012 11:00:00  21,3    85  3,57609276547571    3,57609276547571
5/26/2012 12:00:00  22,3    81  12,8699598468684    12,8699598468684

Body:
This function works by computing the run lengths of consecutive zeroes, then replacing any runs longer than 1 with NA in the original vector:

NArun0 = function(v){
   vr=rle(v==0)
   vr$values = vr$length>1 & vr$values
   rv=inverse.rle(vr)
   v[rv]=NA
   v
}

And a bunch of simple tests:

> NArun0(c(0,0,0,0))
[1] NA NA NA NA
> NArun0(c(0,1,1,0))
[1] 0 1 1 0
> NArun0(c(0,1,0,2,0))
[1] 0 1 0 2 0
> NArun0(c(0,1,0,0,2,0))
[1]  0  1 NA NA  2  0
> NArun0(c(0,1,0,0,2,0,0))
[1]  0  1 NA NA  2 NA NA
> NArun0(c(0,0,1,0,0,2,0,0))
[1] NA NA  1 NA NA  2 NA NA

Note that the answer given in the question returns NA for all zeroes for me:

> v = c(1,0,2,3,4,0,0,0,0,9)
> ifelse(v==0 & lag(v)==0, NA, v)
 [1]  1 NA  2  3  4 NA NA NA NA  9

I thought maybe it was because lag was operating on a time series vector, but if I convert v to a time series vector:

> v = ts(v)
> ifelse(v==0 & lag(v)==0, NA, v)
Time Series:
Start = 1
End = 9
Frequency = 1
[1]  1  0  2  3  4 NA NA NA  0

I do get a zero, but also a zero in last place, because of the way lag works. So I dont understand how the code in the question gives the answer.


问:
How to convert a csv file to parquet
I'm new to BigData. I need to convert a .csv/.txt file to Parquet format. I searched a lot but couldn't find any direct way to do so. Is there any way to achieve that?

答:
```<code>import pyspark

sc = pyspark.SparkContext('local[*]')
sqlContext = pyspark.sql.SQLContext(sc)

df = sqlContext.read.csv('file:///xxx/xxx.csv')
df.write.parquet('file:///xxx/output.parquet')
</code>```

Title: How to convert a csv file to parquet


问:
How to execute a method within a class without calling it, with self parameter
I am trying to make a randomized urls and save them in a database but this code keep return this error

```<code>TypeError: randomizer() missing 1 required positional argument: 'self'
</code>```

I Tried to call The randomizer as

```<code>randomizer()
</code>```

instead of

```<code>randomizer
</code>```

but this does not work because it will generate random characters for once.
It is the same when with qr_generator function it requires the self argument.

```<code>class Table(models.Model):

     def randomizer(self):
        qr  = str(self.restaurant.id).join((random.choice(string.ascii_letters) for x in range(5)))
        return qr

    def qr_generator(self):
        url = DOMAIN +"/table/" + self.qr
        qr_img = qrcode.make(url)
        qr_img.save(f"qrs/{self.restaurant.id}/{self.qr}.png")
        return f"qrs/{self.restaurant.id}/{self.qr}"

    number = models.IntegerField()
    restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
    qr = models.CharField(max_length=50, default=randomizer, unique=True)
    qr_img = models.CharField(default=qr_generator, max_length=100)
</code>```

答:
use static method</p>
```<code>import random

class Test():
    name = "joe"

    @staticmethod
    def name_with_random_number():
        print(Test.name+str(random.randint(0, 1000)))

    name_number = name_with_random_number

print(Test.name_number())
</code>```

Body:
I am trying to make a randomized urls and save them in a database but this code keep return this error

TypeError: randomizer() missing 1 required positional argument: 'self'

I Tried to call The randomizer as

randomizer()

instead of

randomizer

but this does not work because it will generate random characters for once.
It is the same when with qr_generator function it requires the self argument.

class Table(models.Model):

     def randomizer(self):
        qr  = str(self.restaurant.id).join((random.choice(string.ascii_letters) for x in range(5)))
        return qr

    def qr_generator(self):
        url = DOMAIN +"/table/" + self.qr
        qr_img = qrcode.make(url)
        qr_img.save(f"qrs/{self.restaurant.id}/{self.qr}.png")
        return f"qrs/{self.restaurant.id}/{self.qr}"

    number = models.IntegerField()
    restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
    qr = models.CharField(max_length=50, default=randomizer, unique=True)
    qr_img = models.CharField(default=qr_generator, max_length=100)

Body:
use static method

import random

class Test():
    name = "joe"

    @staticmethod
    def name_with_random_number():
        print(Test.name+str(random.randint(0, 1000)))

    name_number = name_with_random_number

print(Test.name_number())


问:
React loses focus on input after the first character
Everytime I type, i lose the focus of the input text. I have other components which are working fine; but this one is losing focus. Any idea why would this happen?

I tried creating separate components and rendering them in my switch but still not working.

I have other components rendered with Switch statements and are working fine.

```<code>const FactionDetail = ({Faction}) => {
const [tab, setTab] = React.useState(0)
const [selectedMember, setSelectedMember] = React.useState(null)

const [receipt, setReceipt] = React.useState('')
const [selectedRank, setSelectedRank] = React.useState(null)

const [newRankDetails, setNewRankDetails] = React.useState({
    rankName: '',
    wage: 0,
    hasPerm: false
})

const menuOption = (tabId) =>{
    setTab(tabId)
}

const selectMember = (e) =>{
    setSelectedMember(e)
}

const renderDropdownOptions = () =>{
    let i  = 0
    for (const rank in Faction.ranks){
        i++
        return <option key = {i} value = {rank}>{rank}</option>
    }
}

React.useEffect(() =>{
    if(selectedMember != null && selectedRank != selectedMember.rank){
        setSelectedRank(selectedMember.rank)
    }
}, [selectedMember])

const RightBody = () =>{
    switch(tab){
        case 0: // Dashboard
            return <>

            </>
        case 1: //Members
            return <> </>

        case 2: //Manage
            return <>
                <div className ='CreateRanks'>
                    <label>Rank Name</label>
                    <input style ={{width:'80px'}} onChange = {(e) => setNewRankDetails((prev) => {return {...prev, rankName: e.target.value}})} value = {newRankDetails.rankName}></input>
                    <label>Wage</label>
                    <input style ={{width:'80px'}} onChange = {(e) => setNewRankDetails((prev) => {return {...prev, wage: e.target.value}})} value = {newRankDetails.wage}></input>
                    <label>Has Perm</label>
                    <input type="checkbox" onChange = {(e) => setNewRankDetails((prev) => {return {...prev, hasPerm: e.target.checked}})} value = {newRankDetails.hasPerm} />
                    <button onClick = {() =>{ updateClient('factions:createNewRank', newRankDetails)}}>Create</button>
                </div>

            </>
        default:
            return<>{tab}</>
    }
}
</code>```

答: I was rendering two compoenents in the 'main' component; therefor the data from the useStates were mixing and re-rendering.</p>

Body:
Everytime I type, i lose the focus of the input text. I have other components which are working fine; but this one is losing focus. Any idea why would this happen?

I tried creating separate components and rendering them in my switch but still not working.

I have other components rendered with Switch statements and are working fine.

const FactionDetail = ({Faction}) => {
const [tab, setTab] = React.useState(0)
const [selectedMember, setSelectedMember] = React.useState(null)

const [receipt, setReceipt] = React.useState('')
const [selectedRank, setSelectedRank] = React.useState(null)

const [newRankDetails, setNewRankDetails] = React.useState({
    rankName: '',
    wage: 0,
    hasPerm: false
})

const menuOption = (tabId) =>{
    setTab(tabId)
}

const selectMember = (e) =>{
    setSelectedMember(e)
}

const renderDropdownOptions = () =>{
    let i  = 0
    for (const rank in Faction.ranks){
        i++
        return <option key = {i} value = {rank}>{rank}</option>
    }
}

React.useEffect(() =>{
    if(selectedMember != null && selectedRank != selectedMember.rank){
        setSelectedRank(selectedMember.rank)
    }
}, [selectedMember])

const RightBody = () =>{
    switch(tab){
        case 0: // Dashboard
            return <>

            </>
        case 1: //Members
            return <> </>

        case 2: //Manage
            return <>

                    Rank Name
                    <input style ={{width:'80px'}} onChange = {(e) => setNewRankDetails((prev) => {return {...prev, rankName: e.target.value}})} value = {newRankDetails.rankName}></input>
                    Wage
                    <input style ={{width:'80px'}} onChange = {(e) => setNewRankDetails((prev) => {return {...prev, wage: e.target.value}})} value = {newRankDetails.wage}></input>
                    Has Perm
                    <input type="checkbox" onChange = {(e) => setNewRankDetails((prev) => {return {...prev, hasPerm: e.target.checked}})} value = {newRankDetails.hasPerm} />
                    <button onClick = {() =>{ updateClient('factions:createNewRank', newRankDetails)}}>Create</button>

            </>
        default:
            return<>{tab}</>
    }
}


问:
Verification URL for Discord JS
Would it be possible to create a one-click URL verification system in Discord JS. Essentially, when you signup for my service you get an email with a verification URL that when clicked adds you to the discord server, gives you the appropriate role, and adds you to my Mongoose database. I've seen this kind of system done for regular applications, but never through discord.</p>

答:
You can make use of the discord OAUTH2 system to gain access to add the user to guilds automatically. You can create a 2 stepped system first it would verify the user in the local database and then redirect them to the generated OAUTH2 URL
https://discord.com/developers/docs/topics/oauth2

Title: Verification URL for Discord JS


问:
"setstate" in vanilla javascript, enforce changes
I am new to Js, and i am coding a simple quiz app with HTML, CSS and JS to learn.

I am a mobile developer and use Flutter and Dart, dart is pretty similar to JS. On the quiz app, when someone presses the next button after an answered question, i want it to switch to the next question.

When the user presses the button nothing happens... In dart i would use the setState method, which forces the UI to reload with the updated changes. Is there an equivalent method in JS? I found that setState is used in ReactJS, however this is coded in vanilla Js.

I have an Array of 2 questions (which are maps containing the questiopn text, answer alternatives and correct answer). Then I have an integer variable which is the questionIndex. So first question the index i 0, and when the user presses the next button ( to go to the next question) it should increment by 1.

Here is the code for the button click:

```<code>function onClickNext() {
    console.log("called");

    currentQuestionIndex++;

}
</code>```

the Array of questions:

```<code>const questions = [
  {
    question: "What is the capital of Sweden?",
    "alt 1": "Stockholm",
    "alt 2": "Gothenburg",
    "alt 3": "Malmö",
    "alt 4": "Linköping",
    correctIndex: 0,
  },
  {
    question: "What is the capital of England?",
    "alt 1": "London",
    "alt 2": "Manchester",
    "alt 3": "Bournemouth",
    "alt 4": "Cardiff",
    correctIndex: 0,
  },
];
</code>```

And here are the dynamic HTML components (the question + answer alternatives, which are suppoosed to change when next is pressed, so it moves onto the next question.

```<code>document.getElementById("question").innerHTML =
  questions[currentQuestionIndex]["question"];
button1.innerHTML = questions[currentQuestionIndex]["alt 1"];
button2.innerHTML = questions[currentQuestionIndex]["alt 2"];
button3.innerHTML = questions[currentQuestionIndex]["alt 3"];
button4.innerHTML = questions[currentQuestionIndex]["alt 4"];
</code>```

Would be really thankful for some guidance, and also if someone knows a way to make my code more consise and efficiant.

Thank you!

答:
Since Vanilla JS has no state listeners that will update the DOM automatically, you can program this yourself, for example:

```<code>function onClickNext() {
    console.log("called")

    currentQuestionIndex++
    drawQuestionScreen()

}

function drawQuestionScreen(){
   document.getElementById("question").innerHTML =
      questions[currentQuestionIndex]["question"];
   button1.innerHTML = questions[currentQuestionIndex]["alt 1"];
   button2.innerHTML = questions[currentQuestionIndex]["alt 2"];
   button3.innerHTML = questions[currentQuestionIndex]["alt 3"];
   button4.innerHTML = questions[currentQuestionIndex]["alt 4"];
}
</code>```

Body:
I am new to Js, and i am coding a simple quiz app with HTML, CSS and JS to learn.

I am a mobile developer and use Flutter and Dart, dart is pretty similar to JS. On the quiz app, when someone presses the next button after an answered question, i want it to switch to the next question.

When the user presses the button nothing happens... In dart i would use the setState method, which forces the UI to reload with the updated changes. Is there an equivalent method in JS? I found that setState is used in ReactJS, however this is coded in vanilla Js.

I have an Array of 2 questions (which are maps containing the questiopn text, answer alternatives and correct answer). Then I have an integer variable which is the questionIndex. So first question the index i 0, and when the user presses the next button ( to go to the next question) it should increment by 1.

Here is the code for the button click:

function onClickNext() {
    console.log("called");

    currentQuestionIndex++;

}

the Array of questions:

const questions = [
  {
    question: "What is the capital of Sweden?",
    "alt 1": "Stockholm",
    "alt 2": "Gothenburg",
    "alt 3": "Malmö",
    "alt 4": "Linköping",
    correctIndex: 0,
  },
  {
    question: "What is the capital of England?",
    "alt 1": "London",
    "alt 2": "Manchester",
    "alt 3": "Bournemouth",
    "alt 4": "Cardiff",
    correctIndex: 0,
  },
];

And here are the dynamic HTML components (the question + answer alternatives, which are suppoosed to change when next is pressed, so it moves onto the next question.

document.getElementById("question").innerHTML =
  questions[currentQuestionIndex]["question"];
button1.innerHTML = questions[currentQuestionIndex]["alt 1"];
button2.innerHTML = questions[currentQuestionIndex]["alt 2"];
button3.innerHTML = questions[currentQuestionIndex]["alt 3"];
button4.innerHTML = questions[currentQuestionIndex]["alt 4"];

Would be really thankful for some guidance, and also if someone knows a way to make my code more consise and efficiant.

Thank you!

Body:
Since Vanilla JS has no state listeners that will update the DOM automatically, you can program this yourself, for example:

function onClickNext() {
    console.log("called")

    currentQuestionIndex++
    drawQuestionScreen()

}

function drawQuestionScreen(){
   document.getElementById("question").innerHTML =
      questions[currentQuestionIndex]["question"];
   button1.innerHTML = questions[currentQuestionIndex]["alt 1"];
   button2.innerHTML = questions[currentQuestionIndex]["alt 2"];
   button3.innerHTML = questions[currentQuestionIndex]["alt 3"];
   button4.innerHTML = questions[currentQuestionIndex]["alt 4"];
}


问:
Requiring same module in different modules are referencing different objects
I am trying to access an object exported from a module in two different modules. Logically in theese two different modules it must point to same object but it does not. Some how, i set the property of the object in a place and when i try to access this set property via a property of different object reference (but this property contains or should contain same reference to the object.) this property's reference does not reflect the changes. It's still the same. Let me make things clear with codes.

./startup/data/frontend/languages.js

```<code>const englishLanguage = {
    name:'English'
}

const turkishLanguage = {
    name:'Turkish'
}

const languagesData = {englishLanguage,turkishLanguage}

module.exports = {languagesData}
</code>```

./startup/data/frontend/languageCountryCodes.js

```<code>const { languagesData } = require('./languages');

const languageCountryCodesData = {
    turkishTR: {
        language: languagesData.turkishLanguage,
        countryCode: 'TR'
    },
    englishEN: {
        language: languagesData.englishLanguage,
        countryCode: 'EN'
    },
    englishUS: {
        language: languagesData.englishLanguage,
        countryCode: 'US'
    }
};

module.exports = { languageCountryCodesData };
</code>```

Below is the code i first reference this languagesData object.

./startup/tableDescriptor/frontend/language

```<code>const { languagesData } = require('../../data/frontend/languages');

const languagesTable = {
    tableName: 'languages',
    columns: [
        {
            name: 'id',
            type: 'SERIAL PRIMARY KEY',
            autoGenerated: true
        },
        {
            name: 'name',
            type: 'VARCHAR NOT NULL'
        }
    ],
    uniqueConstraints: [
        ['name']
    ],
    primaryKey: ['id'],
    prodData: languagesData
}

module.exports = { languagesTable };
</code>```

./startup/tableDescriptor/frontend/languageCountryCode

```<code>const { languageCountryCodesData } = require('../../data/frontEnd/languageCountryCodes');
const { languagesTable } = require('./language');

const languageCountryCodesTable = {
    tableName: 'language_country_codes',
    columns: [
        {
            name: 'id',
            type: 'SERIAL PRIMARY KEY',
            autoGenerated: true
        },
        {
            name: 'languageId',
            type: 'INT NOT NULL'
        },
        {
            name: 'countryCode',
            type: 'VARCHAR NOT NULL'
        }
    ],
    primaryKey: ['id'],
    uniqueConstrarints: [
        ['countryCode']
    ],
    foreignKeys: [
        {
            key: 'languageId',
            table: languagesTable,
            reference: 'id',
            dataProperty: 'language'
        }
    ],
    prodData: languageCountryCodesData
};

module.exports = {  languageCountryCodesTable };
</code>```

When i set a non-existing id property of one of languagesData value of languagesTable.prodData i expect it to be set on languageCountryCodesData.language of prodData property of languageCountryCodesTable object. languageCountryCodesData also references languagesData. And prodData property of languagesTable also references languagesData. But it seems they don't. They reference two different objects. But shouldn't theese be referencing same object?

Please let me know if am missing something.

答:
It was the character casing problem on require statement. I fixed the path with proper casing and it fixed...

Fixed

```<code>const { languageCountryCodesData } = require('../../data/frontEnd/languageCountryCodes');
</code>```

To

```<code>const { languageCountryCodesData } = require('../../data/frontend/languageCountryCodes');
</code>```

Changed 'frontEnd' to 'frontend'

Body:
I am trying to access an object exported from a module in two different modules. Logically in theese two different modules it must point to same object but it does not. Some how, i set the property of the object in a place and when i try to access this set property via a property of different object reference (but this property contains or should contain same reference to the object.) this property's reference does not reflect the changes. It's still the same. Let me make things clear with codes.

./startup/data/frontend/languages.js

const englishLanguage = {
    name:'English'
}

const turkishLanguage = {
    name:'Turkish'
}

const languagesData = {englishLanguage,turkishLanguage}

module.exports = {languagesData}

./startup/data/frontend/languageCountryCodes.js

const { languagesData } = require('./languages');

const languageCountryCodesData = {
    turkishTR: {
        language: languagesData.turkishLanguage,
        countryCode: 'TR'
    },
    englishEN: {
        language: languagesData.englishLanguage,
        countryCode: 'EN'
    },
    englishUS: {
        language: languagesData.englishLanguage,
        countryCode: 'US'
    }
};

module.exports = { languageCountryCodesData };

Below is the code i first reference this languagesData object.

./startup/tableDescriptor/frontend/language

const { languagesData } = require('../../data/frontend/languages');

const languagesTable = {
    tableName: 'languages',
    columns: [
        {
            name: 'id',
            type: 'SERIAL PRIMARY KEY',
            autoGenerated: true
        },
        {
            name: 'name',
            type: 'VARCHAR NOT NULL'
        }
    ],
    uniqueConstraints: [
        ['name']
    ],
    primaryKey: ['id'],
    prodData: languagesData
}

module.exports = { languagesTable };

./startup/tableDescriptor/frontend/languageCountryCode

const { languageCountryCodesData } = require('../../data/frontEnd/languageCountryCodes');
const { languagesTable } = require('./language');

const languageCountryCodesTable = {
    tableName: 'language_country_codes',
    columns: [
        {
            name: 'id',
            type: 'SERIAL PRIMARY KEY',
            autoGenerated: true
        },
        {
            name: 'languageId',
            type: 'INT NOT NULL'
        },
        {
            name: 'countryCode',
            type: 'VARCHAR NOT NULL'
        }
    ],
    primaryKey: ['id'],
    uniqueConstrarints: [
        ['countryCode']
    ],
    foreignKeys: [
        {
            key: 'languageId',
            table: languagesTable,
            reference: 'id',
            dataProperty: 'language'
        }
    ],
    prodData: languageCountryCodesData
};

module.exports = {  languageCountryCodesTable };

When i set a non-existing id property of one of languagesData value of languagesTable.prodData i expect it to be set on languageCountryCodesData.language of prodData property of languageCountryCodesTable object. languageCountryCodesData also references languagesData. And prodData property of languagesTable also references languagesData. But it seems they don't. They reference two different objects. But shouldn't theese be referencing same object?

Please let me know if am missing something.

Body:
It was the character casing problem on require statement. I fixed the path with proper casing and it fixed...

Fixed

const { languageCountryCodesData } = require('../../data/frontEnd/languageCountryCodes');

To

const { languageCountryCodesData } = require('../../data/frontend/languageCountryCodes');

Changed 'frontEnd' to 'frontend'


问:
Installing rjags on Fedora 33
I'm trying to install rjags on a Fedora 33 system running R 4.0.3.  I've installed JAGS 4.3.0 from source and can run the software from the command line, but when I try to install the package in R, I get this error:

```<code>checking version of JAGS library... link error
configure: error: Runtime link error: See the INSTALL file for help
ERROR: configuration failed for package ‘rjags’
</code>```

I've followed this tutorial for building an installing on Fedora, and have all the expected directories under /usr/local/lib64, but get the same errors.

I've also followed this tutorial which specifies the various file locations - also get the same errors.

Finally, I found this which gives some options under section 3, but none of those worked.

答:
I stumbled across a solution here that seems to work:
https://github.com/cran/rjags/blob/master/INSTALL

Installing rjags with the argument below seems to have worked:

```<code>> install.packages("rjags", configure.args="--enable-rpath")
</code>```

Title: Installing rjags on Fedora 33

Body:
I'm trying to install rjags on a Fedora 33 system running R 4.0.3.  I've installed JAGS 4.3.0 from source and can run the software from the command line, but when I try to install the package in R, I get this error:

checking version of JAGS library... link error
configure: error: Runtime link error: See the INSTALL file for help
ERROR: configuration failed for package ‘rjags’

I've followed this tutorial for building an installing on Fedora, and have all the expected directories under /usr/local/lib64, but get the same errors.

I've also followed this tutorial which specifies the various file locations - also get the same errors.

Finally, I found this which gives some options under section 3, but none of those worked.

Body:
I stumbled across a solution here that seems to work:
https://github.com/cran/rjags/blob/master/INSTALL

Installing rjags with the argument below seems to have worked:

> install.packages("rjags", configure.args="--enable-rpath")


答:
Just populate the question HTML anew after calling onClickNext so that the reassignment has an effect.

To make the code more concise, save the question at the current index in a variable first, instead of accessing through the index each time.

```<code>const questionDiv = document.getElementById("question");

const populateQuestion = () => {
  const question = questions[currentQuestionIndex];
  questionDiv.innerHTML = question.question;
  button1.innerHTML = question["alt 1"];
  button2.innerHTML = question["alt 2"];
  button3.innerHTML = question["alt 3"];
  button4.innerHTML = question["alt 4"];
}

// populate on pageload:
populateQuestion();

// and also on click:
function onClickNext() {
  currentQuestionIndex++;
  populateQuestion();
}
</code>```

An even better approach would be to use an array for the buttons and answers instead of separate property and variable names. Consider naming the array of possible answers answers instead of alt, it'll probably make more sense at a glance.

```<code>const populateQuestion = () => {
  const question = questions[currentQuestionIndex];
  questionDiv.innerHTML = question.question;
  question.answers.forEach((answer, i) => {
    buttons[i].textContent = answer;
  });
}
</code>```

You should also consider using .textContent - only use .innerHTML when deliberately inserting HTML markup.

Title: "setstate" in vanilla javascript, enforce changes

Body:
Just populate the question HTML anew after calling onClickNext so that the reassignment has an effect.

To make the code more concise, save the question at the current index in a variable first, instead of accessing through the index each time.

const questionDiv = document.getElementById("question");

const populateQuestion = () => {
  const question = questions[currentQuestionIndex];
  questionDiv.innerHTML = question.question;
  button1.innerHTML = question["alt 1"];
  button2.innerHTML = question["alt 2"];
  button3.innerHTML = question["alt 3"];
  button4.innerHTML = question["alt 4"];
}

// populate on pageload:
populateQuestion();

// and also on click:
function onClickNext() {
  currentQuestionIndex++;
  populateQuestion();
}

An even better approach would be to use an array for the buttons and answers instead of separate property and variable names. Consider naming the array of possible answers answers instead of alt, it'll probably make more sense at a glance.

const populateQuestion = () => {
  const question = questions[currentQuestionIndex];
  questionDiv.innerHTML = question.question;
  question.answers.forEach((answer, i) => {
    buttons[i].textContent = answer;
  });
}

You should also consider using .textContent - only use .innerHTML when deliberately inserting HTML markup.


问:
Is it safe to delete the pack files from .git/objects/?
I'm now planning to archive/deprecate a repository and move it to an external drive. However, some large pack files in .git/objects/pack could not be transferred because they were larger than 4GB. I'm aware that directly deleting the pack files would rewrite the history, but I'm wondering whether it is fine to just remove the files if I am sure that I'm not going to retrieve any files from the history in the future. Are there any other drawbacks of directly removing the whole pack folder? I assume that other files in the repo won't be influenced, but just their backups. Is this correct?

答:
but I'm wondering whether it is fine to just remove the files if I am sure that I'm not going to retrieve any files from the history in the future

It is just fine if you are never going to want any of the history again — because it will destroy that history, forever. In fact, if you are never going to want any of the history again, just delete the .git directory and all its contents. The enclosing folder (which you are about to move to an external drive) won't be a "repository" any more, but it will contain the current state of the project.


问:
How to make multiple constructor generic data Class in kotlin
I want to use multple Constructors like this :

```<code>data class MyData<T>(
    val code: String,
    val message: String,
    val data: T? = null,
) {
    constructor(code: String, message: String) : this(code, message, null)
}
</code>```

and I Use

```<code>MyData(code = "-1", message = "Support only application/json Content-Type") // Error :  Not Enough Information To Infer Parameter T
MyData(code = "-1", message = "message", data = "data")
</code>```

How to Use MyData property 'data' default value is 'null'?
( I want to MyData(code, message) not MyData(code, message) )

答:
You pass the type like this:

```<code>val obj1 = MyData<String>(code = "-1", message = "Support only application/json Content-Type")
</code>```

Note that data should probably be a var instead of a val, or you won't be able to change it.

Body:
I want to use multple Constructors like this :

data class MyData<T>(
    val code: String,
    val message: String,
    val data: T? = null,
) {
    constructor(code: String, message: String) : this(code, message, null)
}

and I Use

MyData(code = "-1", message = "Support only application/json Content-Type") // Error :  Not Enough Information To Infer Parameter T
MyData(code = "-1", message = "message", data = "data")

How to Use MyData property 'data' default value is 'null'?
( I want to MyData(code, message) not MyData(code, message) )

Body:
You pass the type like this:

val obj1 = MyData<String>(code = "-1", message = "Support only application/json Content-Type")

Note that data should probably be a var instead of a val, or you won't be able to change it.


问:
Exception of type 'Microsoft.TeamFoundation.Git.Contracts.GitCheckoutConflictException' was thrown
While trying to checkout to a new branch in Visual Studio 2019, I'm getting the below error:

I tried to do the same from GitBash cmd using the command git checkout branchname but here also, I'm getting an error:

```<code>error: The following untracked working tree files would be overwritten by checkout:
//list of file names below
...
...
...
Aborting
</code>```

I tried restarting VS also but it was of no help. Can you please assist?

答:
I just ran into this issue (VS 2022). My situation sounds very similar to Patrick's, so I'll share how I fixed it in case it helps anyone:

In my case, the branch switch looked successful at first (in reality it hadn't completed), and  then I started receiving said exception immediately afterwards. According to the Git Changes toolbar, I was trying to add a file that existed in the branch I was coming from that wasn't present yet in the branch I was going to. (Note there were several files that existed in one branch but not the other. But for some reason, this particular one had tripped things up.)

All I had to do was this:

Take the file in question out of the directory

From the shell window, switch back to the first branch, then switch to the second branch again. After this, everything merged fine for me and Visual Studio stopped throwing that exception.

(For those that don't know how to do any of this, you can get to the command line from Tools -> Command Line. Then enter git switch branch_name where "branch_name" is the name of the branch you're switching from, then repeat the command with the name of the branch you're switching to. If that goes well, you can then merge the first branch into the second by typing git merge branch_name where "branch_name" is the branch you switched from.

Body:
While trying to checkout to a new branch in Visual Studio 2019, I'm getting the below error:

I tried to do the same from GitBash cmd using the command git checkout branchname but here also, I'm getting an error:

error: The following untracked working tree files would be overwritten by checkout:
//list of file names below
...
...
...
Aborting

I tried restarting VS also but it was of no help. Can you please assist?


问:
How to solve network issue?
I'm getting the following error on npm install:

C:\projects\projects>npm install npm ERR! code ENOENT npm ERR! syscall
open npm ERR! path C:\projects\projects/package.jsonstrong text
npm ERR! errno -4058 npm ERR! enoent ENOENT: no such file or
directory, open 'C:\projects\projects\package.json' npm ERR! enoent
This is related to npm not being able to find a file. npm ERR! enoent

npm ERR! A complete log of this run can be found in: npm ERR!

C:\Users\USER\AppData\Local\npm-cache_logs\2022-02-12T15_43_40_855Z-debug-0.log

答:
It appears there is no package.json in your directory C:\projects\projects

Should it contain an existing node.js project or do you want to initialize a new project?

If so, use:

```<code>     npm init
</code>```

Title: How to solve network issue?

Body:
It appears there is no package.json in your directory C:\projects\projects

Should it contain an existing node.js project or do you want to initialize a new project?

If so, use:

     npm init


问:
How can I perform a select2 result infinite scroll with Laravel pagination
I've created a function that returns a json of products data, and I've wanted to display it in select2 in an infinite scroll way. Right now, I can only display according to the number of paginated results.

Here's my controller:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Models\Product;

class ReceiveInventoryController extends Controller
{
    public function index(Request $request) {
        return view('receive-inventory.index');
    }

    public function getProducts(Request $request){
        $search = $request->search;
        if($search == ''){
            $products = Product::orderby('name','asc')->select('id','name')->paginate(8);
        } else {
            $products = Product::orderby('name','asc')->select('id','name')->where('name', 'like', '%' .$search . '%')->paginate(8);
        }

        $response = array();
        foreach($products as $product){
            $response[] = array(
                "id" => $product->id,
                "text" => $product->name
            );
        }
        return response()->json($response);
    }
}
</code>```

And here's my select2 JS ajax call:

```<code>var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$(document).ready(function () {
    $.noConflict();
    $('#products-list').select2({
        ajax: {
            url: 'receive-inventory/get-products',
            type: 'post',
            dataType: 'json',
            delay: 250,
            data: function(params) {
                var query = {
                    _token: CSRF_TOKEN,
                    search: params.term, // search term
                    page: params.page || 1
                };

                // Query parameters will be ?search=[term]&page=[page]
                return query;
            },
            processResults: function(response) {
                return {
                    results: response
                };
            },
            cache: true
        }
    });
});
</code>```

I think I'm already near with answering the solution. Just lack a little thing.

答:
I don't have the rep to comment on the accepted answer but wanted to say "thanks" - that was a huge time saver to implement infinite scroll.  Here's my Laravel route response.  I've utilized the when method to tighten it up just a bit.

```<code>return \App\Models\User::when(request()->get('q'), function($q) {
    $q->where('name', 'like', '%' . request()->get('q') . '%');
})->orderBy('name')->paginate(10, ['*'], 'page', request()->get('page'));
</code>```

Body:
I've created a function that returns a json of products data, and I've wanted to display it in select2 in an infinite scroll way. Right now, I can only display according to the number of paginated results.

Here's my controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Models\Product;

class ReceiveInventoryController extends Controller
{
    public function index(Request $request) {
        return view('receive-inventory.index');
    }

    public function getProducts(Request $request){
        $search = $request->search;
        if($search == ''){
            $products = Product::orderby('name','asc')->select('id','name')->paginate(8);
        } else {
            $products = Product::orderby('name','asc')->select('id','name')->where('name', 'like', '%' .$search . '%')->paginate(8);
        }

        $response = array();
        foreach($products as $product){
            $response[] = array(
                "id" => $product->id,
                "text" => $product->name
            );
        }
        return response()->json($response);
    }
}

And here's my select2 JS ajax call:

var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$(document).ready(function () {
    $.noConflict();
    $('#products-list').select2({
        ajax: {
            url: 'receive-inventory/get-products',
            type: 'post',
            dataType: 'json',
            delay: 250,
            data: function(params) {
                var query = {
                    _token: CSRF_TOKEN,
                    search: params.term, // search term
                    page: params.page || 1
                };

                // Query parameters will be ?search=[term]&page=[page]
                return query;
            },
            processResults: function(response) {
                return {
                    results: response
                };
            },
            cache: true
        }
    });
});

I think I'm already near with answering the solution. Just lack a little thing.

Body:
I don't have the rep to comment on the accepted answer but wanted to say "thanks" - that was a huge time saver to implement infinite scroll.  Here's my Laravel route response.  I've utilized the when method to tighten it up just a bit.

return \App\Models\User::when(request()->get('q'), function($q) {
    $q->where('name', 'like', '%' . request()->get('q') . '%');
})->orderBy('name')->paginate(10, ['*'], 'page', request()->get('page'));


问:
Solidity - Check balance of a user address using openzeppelin
I'm using Truffle and upgradable Openzeppelin contracts. I have two contracts.

Token.sol:

```<code>// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;

import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";

contract MyToken is Initializable, ERC20Upgradeable {
    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() initializer {}

    function initialize() initializer public {
        __ERC20_init("MyToken", "MTK");

        _mint(msg.sender, 10000000 * 10 ** decimals());
    }
}
</code>```

AnotherContract.sol:

```<code>pragma solidity ^0.8.2;
import "./IAnotherContract.sol";

contract AnotherContract is IAnotherContract {
  function doSomethingIfBalanceIsEnough()
    external
    returns (string memory)
  {
    // ...
  }
}
</code>```

How do I check how many MTK tokens a user has? I need to check it in doSomethingIfBalanceIsEnough function.

答:
The token contract implements a balanceOf() function that returns token balance of an address.

You can make an external call from AnotherContract to MyToken address, invoking its balanceOf() function, passing it the user's address.

```<code>pragma solidity ^0.8.2;
import "./IAnotherContract.sol";

interface IERC20 {
    function balanceOf(address) external view returns (uint256);
}

contract AnotherContract is IAnotherContract {
    function doSomethingIfBalanceIsEnough()
      external
      returns (string memory)
    {
        uint256 userBalance = IERC20(myTokenAddress).balanceOf(msg.sender);
        if (userBalance > 0) {
            // ...
        }
    }
}
</code>```

Body:
I'm using Truffle and upgradable Openzeppelin contracts. I have two contracts.

Token.sol:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;

import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";

contract MyToken is Initializable, ERC20Upgradeable {
    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() initializer {}

    function initialize() initializer public {
        __ERC20_init("MyToken", "MTK");

        _mint(msg.sender, 10000000 * 10 ** decimals());
    }
}

AnotherContract.sol:

pragma solidity ^0.8.2;
import "./IAnotherContract.sol";

contract AnotherContract is IAnotherContract {
  function doSomethingIfBalanceIsEnough()
    external
    returns (string memory)
  {
    // ...
  }
}

How do I check how many MTK tokens a user has? I need to check it in doSomethingIfBalanceIsEnough function.

Body:
The token contract implements a balanceOf() function that returns token balance of an address.

You can make an external call from AnotherContract to MyToken address, invoking its balanceOf() function, passing it the user's address.

pragma solidity ^0.8.2;
import "./IAnotherContract.sol";

interface IERC20 {
    function balanceOf(address) external view returns (uint256);
}

contract AnotherContract is IAnotherContract {
    function doSomethingIfBalanceIsEnough()
      external
      returns (string memory)
    {
        uint256 userBalance = IERC20(myTokenAddress).balanceOf(msg.sender);
        if (userBalance > 0) {
            // ...
        }
    }
}


问:
How to select unique columns for two joined tables in SQL Server
I am using SQL Server. I have two tables employees and employees entry times.

I am joining these tables using a LEFT OUTER JOIN. But I want to get the last input value for each employee(Last entered date).

Summary purpose

Select all employee. If there is no input value corresponding to employee return null.

If there are much input value corresponding, select last entered date

How do I do this?

The problem I'm having is exponentially more complex.

So simplified example for understanding;

Table 1 : Employees

```<code>Id
Name
</code>```

Table 2 : Employee_Entry_Times

```<code>Id
Time_Entered
Employee_REFER
</code>```

答:
I think this should work.</p>
```<code>select e.name, MAX(t.Time_Entered)
from
employees e left outer join Employee_Entry_Times t
on e.id = t.Employee_REFER
group by e.name
</code>```

Body:
I am using SQL Server. I have two tables employees and employees entry times.

I am joining these tables using a LEFT OUTER JOIN. But I want to get the last input value for each employee(Last entered date).

Summary purpose

Select all employee. If there is no input value corresponding to employee return null.

If there are much input value corresponding, select last entered date

How do I do this?

The problem I'm having is exponentially more complex.

So simplified example for understanding;

Table 1 : Employees

Id
Name

Table 2 : Employee_Entry_Times

Id
Time_Entered
Employee_REFER

Body:
I think this should work.

select e.name, MAX(t.Time_Entered)
from
employees e left outer join Employee_Entry_Times t
on e.id = t.Employee_REFER
group by e.name


问:
Why would people use `$a = $b = 2;` in PHP?
Why would people use this format? Whats different between this and $a=2; $b=2;?

答: Not having to retype the 2. This is useful if the 2 changes to a 3 at some point.


问:
SwiftUI How to Make Page TabView Dynamic
So I am trying to make my TabView height dynamic. I have been looking for a way to do this but I can't seem to find a solution anywhere. This is how my code looks like.

```<code>struct ContentView: View {
    @State var contentHeight: CGFloat = 0

    var body: some View {
        NavigationView {
            ScrollView {
                VStack {
                    TabView {
                        TestView1(contentHeight: $contentHeight)

                        TestView2(contentHeight: $contentHeight)
                    }
                    .tabViewStyle(.page)
                    .frame(height: contentHeight)
                    .indexViewStyle(.page(backgroundDisplayMode: .always))
                    .background(.yellow)
                }

                .navigationBarTitleDisplayMode(.inline)
                .navigationTitle("Test Project")
            }
        }
    }
}
</code>```

This is how my test1view and test2view look like.

```<code>struct TestView1: View {
    @State var height: CGFloat = 0
    @Binding var  contentHeight: CGFloat

    var body: some View {
        Color.red
            .frame(maxWidth:.infinity, minHeight: 200, maxHeight: 200)

            .background(
                GeometryReader { geo in
                    Color.clear
                        .preference(
                            key: HeightPreferenceKey.self,
                            value: geo.size.height
                        )
                        .onAppear {
                            contentHeight = height
                        }
                }
                    .onPreferenceChange(HeightPreferenceKey.self) { height in
                        self.height = height
                    }
            )
    }
}

struct TestView2: View {
    @Binding var  contentHeight: CGFloat
    @State var height: CGFloat = 0

    var body: some View {
        Color.black
            .frame(maxWidth:.infinity, minHeight: 350, maxHeight: 350)
            .background(
                GeometryReader { geo in
                    Color.clear
                        .preference(
                            key: HeightPreferenceKey.self,
                            value: geo.size.height
                        )
                        .onAppear {
                            contentHeight = height
                        }
                }
                    .onPreferenceChange(HeightPreferenceKey.self) { height in
                        self.height = height
                    }
            )
    }
}

struct HeightPreferenceKey: PreferenceKey {
    static let defaultValue: CGFloat = 0

    static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
        value = nextValue()
    }
}
</code>```

Now the problem is that when I drag it just a little the height changes. So when I drag it a little to the left the height changes to the height of TestView2 and it is still on TestView1.

I tried to add a drag gesture but it didn't let me swipe to the next page. So I don't know how I will be able to achieve this. Ive been looking for a solution but still no luck.

答:
You can use the TabView($selection) initializer to do this. https://developer.apple.com/documentation/swiftui/tabview/init(selection:content:)

It tells you which tab you're currently viewing. Based off the middle point of the screen. And you don't have to deal with nasty GeometryReader and HeightPreferenceKey.

Here's your updated code. I even added a nice animation to fade between the two heights!

```<code>struct ContentView: View {

    @State var selectedTab: Tab = .first
    @State var animatedContentHeight: CGFloat = 300

    enum Tab {
        case first
        case second

        var contentHeight: CGFloat {
            switch self {
            case .first:
                return 200
            case .second:
                return 350
            }
        }
    }

    var body: some View {
        TabView(selection: $selectedTab) {
            TestView1()
                .tag(Tab.first)
            TestView2()
                .tag(Tab.second)
        }
        .tabViewStyle(.page)
//        .frame(height: selectedTab.contentHeight) // Uncomment to see without animation
        .frame(height: animatedContentHeight)
        .indexViewStyle(.page(backgroundDisplayMode: .always))
        .onChange(of: selectedTab) { newValue in
            print("now selected:", newValue)
            withAnimation { animatedContentHeight = selectedTab.contentHeight }
        }
    }
}

struct TestView1: View {
    var body: some View {
        Color.red
    }
}

struct TestView2: View {
    var body: some View {
        Color.black
    }
}
</code>```

Body:
So I am trying to make my TabView height dynamic. I have been looking for a way to do this but I can't seem to find a solution anywhere. This is how my code looks like.

struct ContentView: View {
    @State var contentHeight: CGFloat = 0

    var body: some View {
        NavigationView {
            ScrollView {
                VStack {
                    TabView {
                        TestView1(contentHeight: $contentHeight)

                        TestView2(contentHeight: $contentHeight)
                    }
                    .tabViewStyle(.page)
                    .frame(height: contentHeight)
                    .indexViewStyle(.page(backgroundDisplayMode: .always))
                    .background(.yellow)
                }

                .navigationBarTitleDisplayMode(.inline)
                .navigationTitle("Test Project")
            }
        }
    }
}

This is how my test1view and test2view look like.

struct TestView1: View {
    @State var height: CGFloat = 0
    @Binding var  contentHeight: CGFloat

    var body: some View {
        Color.red
            .frame(maxWidth:.infinity, minHeight: 200, maxHeight: 200)

            .background(
                GeometryReader { geo in
                    Color.clear
                        .preference(
                            key: HeightPreferenceKey.self,
                            value: geo.size.height
                        )
                        .onAppear {
                            contentHeight = height
                        }
                }
                    .onPreferenceChange(HeightPreferenceKey.self) { height in
                        self.height = height
                    }
            )
    }
}

struct TestView2: View {
    @Binding var  contentHeight: CGFloat
    @State var height: CGFloat = 0

    var body: some View {
        Color.black
            .frame(maxWidth:.infinity, minHeight: 350, maxHeight: 350)
            .background(
                GeometryReader { geo in
                    Color.clear
                        .preference(
                            key: HeightPreferenceKey.self,
                            value: geo.size.height
                        )
                        .onAppear {
                            contentHeight = height
                        }
                }
                    .onPreferenceChange(HeightPreferenceKey.self) { height in
                        self.height = height
                    }
            )
    }
}

struct HeightPreferenceKey: PreferenceKey {
    static let defaultValue: CGFloat = 0

    static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
        value = nextValue()
    }
}

Now the problem is that when I drag it just a little the height changes. So when I drag it a little to the left the height changes to the height of TestView2 and it is still on TestView1.

I tried to add a drag gesture but it didn't let me swipe to the next page. So I don't know how I will be able to achieve this. Ive been looking for a solution but still no luck.

Body:
You can use the TabView($selection) initializer to do this. https://developer.apple.com/documentation/swiftui/tabview/init(selection:content:)

It tells you which tab you're currently viewing. Based off the middle point of the screen. And you don't have to deal with nasty GeometryReader and HeightPreferenceKey.

Here's your updated code. I even added a nice animation to fade between the two heights!

struct ContentView: View {

    @State var selectedTab: Tab = .first
    @State var animatedContentHeight: CGFloat = 300

    enum Tab {
        case first
        case second

        var contentHeight: CGFloat {
            switch self {
            case .first:
                return 200
            case .second:
                return 350
            }
        }
    }

    var body: some View {
        TabView(selection: $selectedTab) {
            TestView1()
                .tag(Tab.first)
            TestView2()
                .tag(Tab.second)
        }
        .tabViewStyle(.page)
//        .frame(height: selectedTab.contentHeight) // Uncomment to see without animation
        .frame(height: animatedContentHeight)
        .indexViewStyle(.page(backgroundDisplayMode: .always))
        .onChange(of: selectedTab) { newValue in
            print("now selected:", newValue)
            withAnimation { animatedContentHeight = selectedTab.contentHeight }
        }
    }
}

struct TestView1: View {
    var body: some View {
        Color.red
    }
}

struct TestView2: View {
    var body: some View {
        Color.black
    }
}


问:
Is there any best JIRA server plugin/app for maintaining and managing cucumber feature files?
Is there any best JIRA server plugin/app for maintaining and managing cucumber feature files? There are few JIRA plugins like 'Cucumber for Jira - BDD natively in Jira', but they are for JIRA cloud. My need is for JIRA server and not data center. Thanks in advance.</p>

答:
We had a look at a couple and chose AssertThat.  Clean interface and easy to use.   Both are on cloud DC and Server.

https://marketplace.atlassian.com/apps/1219033/assertthat-bdd-cucumber-for-jira?hosting=datacenter&tab=overview

In terms of comparison between tools

A header
AssertThat
BehavePro

Ease of use and interface
9
6

Integrations / API's
yes
yes

Manual execution features
8
5

Import automated results
yes
No


问:
Cannot find module but is already installed in current Project (xml-js, Windows)
I'm actually working in a cross platform Project (Nodejs Package), all time I working under Linux platform, and sometimes I run the package on windows to test it. But for some reason in Windows I get "Cannot find module" error. That problem happen with 'xml-js' module, but the real strange situation happens when I init new clean package with 'xml-js' module installation. When I make a simple script that import the module, the error not appears. I really so confused and frustrated, because this only happens in Windows platform.

In addition, I tried by globally installation of package and obviously also locally installation of 'xml-js' module. Is not a syntax error, because in Linux the package working perfectly.

Previously I have working with "xml2js", and the same error been occurred. So I don't have any idea of the real problem.

If anyone wants to see the error, it's here …

```<code>Error: Cannot find module 'xml-js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
    at Function.Module._load (internal/modules/cjs/loader.js:507:25)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.<anonymous> (C:\Users\eduar\my-package\lib\src\tools.js:2:15)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
</code>```

IMPORTANT EDIT:
Ok, by testing package I found a interesting thing. When I import the module in the root of project, this is correctly imported. I test my own package by other "clean" package creation. In the last I install my project (package) for testing but returns an error when my project tries to import the 'xml-js' module. I don't know if this error disappears once the package be uploaded in npmjs.com, but I don't want to upload a incomplete project only to test this problem.

答:
Try below command

npm i xml-js --save

then run again

Body:
I'm actually working in a cross platform Project (Nodejs Package), all time I working under Linux platform, and sometimes I run the package on windows to test it. But for some reason in Windows I get "Cannot find module" error. That problem happen with 'xml-js' module, but the real strange situation happens when I init new clean package with 'xml-js' module installation. When I make a simple script that import the module, the error not appears. I really so confused and frustrated, because this only happens in Windows platform.

In addition, I tried by globally installation of package and obviously also locally installation of 'xml-js' module. Is not a syntax error, because in Linux the package working perfectly.

Previously I have working with "xml2js", and the same error been occurred. So I don't have any idea of the real problem.

If anyone wants to see the error, it's here …

Error: Cannot find module 'xml-js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
    at Function.Module._load (internal/modules/cjs/loader.js:507:25)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.<anonymous> (C:\Users\eduar\my-package\lib\src\tools.js:2:15)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)

IMPORTANT EDIT:
Ok, by testing package I found a interesting thing. When I import the module in the root of project, this is correctly imported. I test my own package by other "clean" package creation. In the last I install my project (package) for testing but returns an error when my project tries to import the 'xml-js' module. I don't know if this error disappears once the package be uploaded in npmjs.com, but I don't want to upload a incomplete project only to test this problem.