问:
Fix dropdown auto open in tailwind ui navbar component with vue.js
I use navbar component from tailwind ui. It's looks like something like this:

```<code><!-- Profile dropdown -->
<div class="ml-3 relative">
  <div>
    <button
      class="flex text-sm border-2 border-transparent rounded-full focus:outline-none focus:border-white transition duration-150 ease-in-out"
      id="user-menu"
      aria-label="User menu"
      aria-haspopup="true"
    >
      <img
        class="h-8 w-8 rounded-full"
        src="https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80"
        alt
      />
    </button>
  </div>
  <!--
  Profile dropdown panel, show/hide based on dropdown state.

  Entering: "transition ease-out duration-100"
    From: "transform opacity-0 scale-95"
    To: "transform opacity-100 scale-100"
  Leaving: "transition ease-in duration-75"
    From: "transform opacity-100 scale-100"
    To: "transform opacity-0 scale-95"
  -->
  <div class="origin-top-right absolute right-0 mt-2 w-48 rounded-md shadow-lg">
    <div
      class="py-1 rounded-md bg-white shadow-xs"
      role="menu"
      aria-orientation="vertical"
      aria-labelledby="user-menu"
    >
      <a
        href="#"
        class="block px-4 py-2 text-sm leading-5 text-gray-700 hover:bg-gray-100 focus:outline-none focus:bg-gray-100 transition duration-150 ease-in-out"
        role="menuitem"
      >Your Profile</a>
      <a
        href="#"
        class="block px-4 py-2 text-sm leading-5 text-gray-700 hover:bg-gray-100 focus:outline-none focus:bg-gray-100 transition duration-150 ease-in-out"
        role="menuitem"
      >Settings</a>
      <a
        href="#"
        class="block px-4 py-2 text-sm leading-5 text-gray-700 hover:bg-gray-100 focus:outline-none focus:bg-gray-100 transition duration-150 ease-in-out"
        role="menuitem"
      >Sign out</a>
    </div>
  </div>
</div>
</code>```

In this case when I run this code in vue.js navbar dropdown menu status is open by default. How can set status closed by defaul?

Here is preview:

答:
If the Alpine JS is working fine. Just Copy-paste this code and you will be good to go.

    <button x-on:click="dropdown = ! dropdown" type="button" class="max-w-xs bg-gray-800 rounded-full flex items-center text-sm focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-800 focus:ring-white" id="user-menu-button" aria-expanded="false" aria-haspopup="false">
      Open user menu

    </button>

    Your Profile

    Settings

    Sign out

```

Explanation of what I do

I just simply added x-data="{ dropdown: false }" in the parent div to hide the menu at the initial state.

Then, I added x-on:click="dropdown = ! dropdown" on the button to toggle the menu.

And lastly, I added x-show="dropdown" in the menu div. to show or hide the dropdown based on its value.

You can use any text at the spot of dropdown. Because its works like a variable.

Body:
I use navbar component from tailwind ui. It's looks like something like this:

    <button
      class="flex text-sm border-2 border-transparent rounded-full focus:outline-none focus:border-white transition duration-150 ease-in-out"
      id="user-menu"
      aria-label="User menu"
      aria-haspopup="true"
    >

    </button>

      Your Profile
      Settings
      Sign out

In this case when I run this code in vue.js navbar dropdown menu status is open by default. How can set status closed by defaul?

Here is preview:

Body:
If the Alpine JS is working fine. Just Copy-paste this code and you will be good to go.

<!-- Profile dropdown -->
<div class="ml-3 relative" x-data="{ dropdown: false }">
  <div>
    <button x-on:click="dropdown = ! dropdown" type="button" class="max-w-xs bg-gray-800 rounded-full flex items-center text-sm focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-800 focus:ring-white" id="user-menu-button" aria-expanded="false" aria-haspopup="false">
      <span class="sr-only">Open user menu</span>
      <img class="h-8 w-8 rounded-full" src="https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80" alt="">
    </button>
  </div>
  <div x-show="dropdown" class="origin-top-right absolute right-0 mt-2 w-48 rounded-md shadow-lg py-1 bg-white ring-1 ring-black ring-opacity-5 focus:outline-none" role="menu" aria-orientation="vertical" aria-labelledby="user-menu-button" tabindex="-1">
    <!-- Active: "bg-gray-100", Not Active: "" -->
    <a href="#" class="block px-4 py-2 text-sm text-gray-700" role="menuitem" tabindex="-1" id="user-menu-item-0">Your Profile</a>

    <a href="#" class="block px-4 py-2 text-sm text-gray-700" role="menuitem" tabindex="-1" id="user-menu-item-1">Settings</a>

    <a href="#" class="block px-4 py-2 text-sm text-gray-700" role="menuitem" tabindex="-1" id="user-menu-item-2">Sign out</a>
  </div>
</div>

Explanation of what I do

I just simply added x-data="{ dropdown: false }" in the parent div to hide the menu at the initial state.

Then, I added x-on:click="dropdown = ! dropdown" on the button to toggle the menu.

And lastly, I added x-show="dropdown" in the menu div. to show or hide the dropdown based on its value.

You can use any text at the spot of dropdown. Because its works like a variable.


来源: stackexchange

问:
TRACE StatusLogger Log4jLoggerFactory.getContext() found anchor class
When I launch any of my application, i receive a lot of these lines at console and logs:

```<code>TRACE StatusLogger Log4jLoggerFactory.getContext() found anchor class com.example.auth.api.SessionAgentImpl
TRACE StatusLogger Log4jLoggerFactory.getContext() found anchor class com.example.api.AbstractCloseableAgent
TRACE StatusLogger Log4jLoggerFactory.getContext() found anchor class com.example.api.AbstractCentral
TRACE StatusLogger Log4jLoggerFactory.getContext() found anchor class com.example.api.AbstractCloseHooksHandler
TRACE StatusLogger Log4jLoggerFactory.getContext() found anchor class com.example.core.api.plugins.AbstractCorePlugin
TRACE StatusLogger Log4jLoggerFactory.getContext() found anchor class com.example.config.api.ConfigImpl
TRACE StatusLogger Log4jLoggerFactory.getContext() found anchor class com.example.api.AbstractCentral
TRACE StatusLogger Log4jLoggerFactory.getContext() found anchor class com.example.api.AbstractCloseHooksHandler
TRACE StatusLogger Log4jLoggerFactory.getContext() found anchor class com.example.api.AbstractCloseableAgent
TRACE StatusLogger Log4jLoggerFactory.getContext() found anchor class com.example.api.AbstractCentral
</code>```

Then these lines appear in logs again and again.
It started after updating log4j version to 2.15.0 and greater.

Ever come across that?

答: If you are using IntelliJ, you can modified "enable debug output" select box via run/debug configuration to decide trace logger display on console</p>

ContentLicense: CC BY-SA 4.0

Body:
When I launch any of my application, i receive a lot of these lines at console and logs:

TRACE StatusLogger Log4jLoggerFactory.getContext() found anchor class com.example.auth.api.SessionAgentImpl
TRACE StatusLogger Log4jLoggerFactory.getContext() found anchor class com.example.api.AbstractCloseableAgent
TRACE StatusLogger Log4jLoggerFactory.getContext() found anchor class com.example.api.AbstractCentral
TRACE StatusLogger Log4jLoggerFactory.getContext() found anchor class com.example.api.AbstractCloseHooksHandler
TRACE StatusLogger Log4jLoggerFactory.getContext() found anchor class com.example.core.api.plugins.AbstractCorePlugin
TRACE StatusLogger Log4jLoggerFactory.getContext() found anchor class com.example.config.api.ConfigImpl
TRACE StatusLogger Log4jLoggerFactory.getContext() found anchor class com.example.api.AbstractCentral
TRACE StatusLogger Log4jLoggerFactory.getContext() found anchor class com.example.api.AbstractCloseHooksHandler
TRACE StatusLogger Log4jLoggerFactory.getContext() found anchor class com.example.api.AbstractCloseableAgent
TRACE StatusLogger Log4jLoggerFactory.getContext() found anchor class com.example.api.AbstractCentral

Then these lines appear in logs again and again.
It started after updating log4j version to 2.15.0 and greater.

Ever come across that?


问:
Python nested dictionary comprehension with file objects
Fairly new to Python. I'm working on making a code more eloquent by trying to minimally write a nested for loop within a nested for loop to ultimate create a dictionary, where the dictionary includes the words as key and the frequency of words as values in a file. I believe I figured out how to do the inner for loop using dictionary comprehension but am having trouble figuring out the syntax for the outer for loop. I am guessing the outer for loop would be set up as a list comprehension expression. Currently I am not going to worry about what type of character is being considered a word (symbol, number, alphabet), and am trying to avoid importing any additional libraries. Could you maybe show me some examples, or point me to a resource I could read up more into nested comprehensions/advanced comprehensions?

The "brute force" fundamental method I originally developed looks along the lines of this:

```<code>word_cache = {}
# Some code here

with open('myfile.txt') as lines:
    for line in lines:
        for word in line.split():
            word_cache[word]=word_cache.get(word,0)+1

    '''
    Below is alternatively what I have for dictionary comprehension.
    The "for line in lines" is what I am having difficulty trying to nest which I believe would replace the "line in the dictionary comprehension". Part of the issue I see is lines is considered a file object.
    '''
    word_cache.update({word:word_cache.get(word,0)+1 for word in line.split()})

    # Tried the below but did not work because this is the (line for line in lines) is a generator expression
    word_cache.update({word:word_cache.get(word,0)+1 for word in (line for line in lines).split()})
</code>```

Could someone help me understand what is the correct syntax for nested comprehensions of file objects (assuming the object file comes from a txt file)?

答:
A comprehension won't work in this case as you are relying on the container to reference itself. You will get a NameError as word_cache won't have been defined yet.

Your original code is something like this

```<code># initialising the dict
cache = {}

with open('myfile.txt') as lines:
    for line in lines:
        for word in line.split():
            # referencing the dict that has been initialised
            cache[word] = cache.get(word, 0) + 1
</code>```

What you might want to try is something like this

```<code>with open('myfile.txt') as lines:
    word_cache = {word: word_cache.get(word, 0) + 1 for line in lines for word in line.split()}
</code>```

This won't work because comprehensions create the object first and then perform assignment second. Therefore, when you use word_cache.get, Python has no idea what you're referring to as word_cache hasn't been created yet!

e.g.

```<code>In [1]: a = [a[0] + i for i in range(3)]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-3186711e5c1b> in <module>
----> 1 a = [a[0] + i for i in range(3)]

<ipython-input-1-3186711e5c1b> in <listcomp>(.0)
----> 1 a = [a[0] + i for i in range(3)]

NameError: name 'a' is not defined
</code>```

Consider using a Counter from collections.

```<code>In [1]: from collections import Counter

In [2]: with open('/path/to.file') as f:
   ...:     cache = c.Counter(f.read().split())
   ...:
</code>```

It's important to use the right tools for the job. In this case, it's a Counter.

More importantly, who is saying that your initial solution is not elegant or straightforward? A comprehension doesn't make a solution more elegant or readable.

An example of this (as you mention that you don't want to use additional libraries) might be

```<code>In [24]: with open('/path/to.file') as f:
    ...:     words = f.read().split()
    ...:     cache = {word: words.count(word) for word in set(words)}
    ...:
</code>```

But to me this is not elegant and it's going to be much slower. I know speed is not exactly what you asked about but the difference is instructive and shouldn't be ignored.

```<code>In [24]: with open('/path/to.file') as f:
    ...:     words = f.read().split()
    ...:

In [25]: %%timeit cache = {}
    ...: for word in words:
    ...:     cache[word] = cache.get(word, 0) + 1
    ...:
26.7 µs ± 802 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [26]: %timeit cache = Counter(words)
12.9 µs ± 703 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [27]: %timeit cache = {word: words.count(word) for word in set(words)}
451 µs ± 60.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [28]: len(words)
Out[28]: 245
</code>```

As you can see Counter is the fastest with the regular for loop being twice as slow. The comprehension is 30 times slower and this is for a word list of 245. The reason is that we're looping over the word list every time with words.count(word).

This might not be the most optimal comprehension we can come up with but you can now see that just because you can, doesn't mean you should. It's neither fast nor elegant.

To further demonstrate the how bad this solution is we can increase the file size.

```<code>In [30]: with open('/Downloads/sample-2mb-text-file.txt') as f:
    ...:     words = f.read().split()
    ...:

In [31]: len(words)
Out[31]: 322392

In [32]: %%timeit cache = {}
    ...: for word in words:
    ...:     cache[word] = cache.get(word, 0) + 1
    ...:
51 ms ± 6.25 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [33]: %timeit cache = c.Counter(words)
26.6 ms ± 1.25 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [34]: %timeit cache = {word: words.count(word) for word in set(words)}
2.54 s ± 72.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code>```

You can see here that the Counter and for loop solutions scale relative to one another (as before, Counter is about twice as fast). Our dict comprehension on the other hand is now nearly 100 times slower compared to Counter.

Body:
Fairly new to Python. I'm working on making a code more eloquent by trying to minimally write a nested for loop within a nested for loop to ultimate create a dictionary, where the dictionary includes the words as key and the frequency of words as values in a file. I believe I figured out how to do the inner for loop using dictionary comprehension but am having trouble figuring out the syntax for the outer for loop. I am guessing the outer for loop would be set up as a list comprehension expression. Currently I am not going to worry about what type of character is being considered a word (symbol, number, alphabet), and am trying to avoid importing any additional libraries. Could you maybe show me some examples, or point me to a resource I could read up more into nested comprehensions/advanced comprehensions?

The "brute force" fundamental method I originally developed looks along the lines of this:

word_cache = {}
# Some code here

with open('myfile.txt') as lines:
    for line in lines:
        for word in line.split():
            word_cache[word]=word_cache.get(word,0)+1

    '''
    Below is alternatively what I have for dictionary comprehension.
    The "for line in lines" is what I am having difficulty trying to nest which I believe would replace the "line in the dictionary comprehension". Part of the issue I see is lines is considered a file object.
    '''
    word_cache.update({word:word_cache.get(word,0)+1 for word in line.split()})

    # Tried the below but did not work because this is the (line for line in lines) is a generator expression
    word_cache.update({word:word_cache.get(word,0)+1 for word in (line for line in lines).split()})

Could someone help me understand what is the correct syntax for nested comprehensions of file objects (assuming the object file comes from a txt file)?

Body:
A comprehension won't work in this case as you are relying on the container to reference itself. You will get a NameError as word_cache won't have been defined yet.

Your original code is something like this

# initialising the dict
cache = {}

with open('myfile.txt') as lines:
    for line in lines:
        for word in line.split():
            # referencing the dict that has been initialised
            cache[word] = cache.get(word, 0) + 1

What you might want to try is something like this

with open('myfile.txt') as lines:
    word_cache = {word: word_cache.get(word, 0) + 1 for line in lines for word in line.split()}

This won't work because comprehensions create the object first and then perform assignment second. Therefore, when you use word_cache.get, Python has no idea what you're referring to as word_cache hasn't been created yet!

e.g.

In [1]: a = [a[0] + i for i in range(3)]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-3186711e5c1b> in <module>
----> 1 a = [a[0] + i for i in range(3)]

<ipython-input-1-3186711e5c1b> in <listcomp>(.0)
----> 1 a = [a[0] + i for i in range(3)]

NameError: name 'a' is not defined

Consider using a Counter from collections.

In [1]: from collections import Counter

In [2]: with open('/path/to.file') as f:
   ...:     cache = c.Counter(f.read().split())
   ...:

It's important to use the right tools for the job. In this case, it's a Counter.

More importantly, who is saying that your initial solution is not elegant or straightforward? A comprehension doesn't make a solution more elegant or readable.

An example of this (as you mention that you don't want to use additional libraries) might be

In [24]: with open('/path/to.file') as f:
    ...:     words = f.read().split()
    ...:     cache = {word: words.count(word) for word in set(words)}
    ...:

But to me this is not elegant and it's going to be much slower. I know speed is not exactly what you asked about but the difference is instructive and shouldn't be ignored.

In [24]: with open('/path/to.file') as f:
    ...:     words = f.read().split()
    ...:

In [25]: %%timeit cache = {}
    ...: for word in words:
    ...:     cache[word] = cache.get(word, 0) + 1
    ...:
26.7 µs ± 802 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [26]: %timeit cache = Counter(words)
12.9 µs ± 703 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [27]: %timeit cache = {word: words.count(word) for word in set(words)}
451 µs ± 60.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [28]: len(words)
Out[28]: 245

As you can see Counter is the fastest with the regular for loop being twice as slow. The comprehension is 30 times slower and this is for a word list of 245. The reason is that we're looping over the word list every time with words.count(word).

This might not be the most optimal comprehension we can come up with but you can now see that just because you can, doesn't mean you should. It's neither fast nor elegant.

To further demonstrate the how bad this solution is we can increase the file size.

In [30]: with open('/Downloads/sample-2mb-text-file.txt') as f:
    ...:     words = f.read().split()
    ...:

In [31]: len(words)
Out[31]: 322392

In [32]: %%timeit cache = {}
    ...: for word in words:
    ...:     cache[word] = cache.get(word, 0) + 1
    ...:
51 ms ± 6.25 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [33]: %timeit cache = c.Counter(words)
26.6 ms ± 1.25 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [34]: %timeit cache = {word: words.count(word) for word in set(words)}
2.54 s ± 72.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

You can see here that the Counter and for loop solutions scale relative to one another (as before, Counter is about twice as fast). Our dict comprehension on the other hand is now nearly 100 times slower compared to Counter.


问:
What is The Use Of # in C or C++?
i would like to know the usage of # in C or C++..... please can u inform me what is the purpose of # or Why it is used?</p>

答: It is used for all the preprocessor directives, like #include, #ifdef and all the others</p>

ContentLicense: CC BY-SA 3.0

Title: What is The Use Of # in C or C++?


问:
async function in Python not working as expected
I have the following code snippet:

```<code>import asyncio

def main():
    asyncio.run(work())
    print("BEFORE")

async def work():
    await asyncio.sleep(1)
    print("AFTER")

main()
</code>```

I would like "BEFORE" to be printed first, followed by "AFTER" however this prints "AFTER" first instead - have I misunderstood how async functions work? I thought that running asyncio.run(...) would allow my code to skip to print("BEFORE") while still running work() in the background.

Ideal output is:

```<code>BEFORE
AFTER
</code>```

Right now it's

```<code>AFTER
BEFORE
</code>```

答:
According to the documentation:

The asyncio.run() function to run the top-level entry point “main()” function (see the above example.)

The asyncio.run should be the entry point, not used for starting a background job. So it does not skip to print("BEFORE").

Body:
I have the following code snippet:

import asyncio

def main():
    asyncio.run(work())
    print("BEFORE")

async def work():
    await asyncio.sleep(1)
    print("AFTER")

main()

I would like "BEFORE" to be printed first, followed by "AFTER" however this prints "AFTER" first instead - have I misunderstood how async functions work? I thought that running asyncio.run(...) would allow my code to skip to print("BEFORE") while still running work() in the background.

Ideal output is:

BEFORE
AFTER

Right now it's

AFTER
BEFORE


问:
Using Generics in C# to compare conditionally
In my scenario, I have two types of objects. A plan and a tier. Each one shares certain values, while the tier has 3 additional values (Rate, Min, and Max).

I would like to make a generic method to conditionally evaluate whether or not the new object can be written to the database, based on the following conditions:

Creation:

A tier: ((o1.Rate!=o2.Rate) || ((o1.Start!=o2.Start) && (o1.End!=o2.End))) && (MinVal && MaxVal)

A tier or plan: (o1.Name!=o2.Name)

A tier or plan: Only one can have (Active == true), the rest must be false.

Is it possible to create a generic method for something like this? If so, are there any examples of something like this? Or does anyone have suggestions?

thanks!

MORE:
So I have a list of objects, and I need to compare a newly created one with each other object in the database before I actually write it to the database.

答:
Your options are basically:

use a common inherited base object with those props

implement an interface with those props

use reflection to get the values and compare them if the objects are really unrelated or if you only know the compared field values at runtime.

Reed mentioned below dynamic objects - that may work I'd have to trust his answer on that but includes the dynamic requirement though.


问:
Using Fetch to import JSON data and output to an HTML Table
I'm learning JavaScript and trying to master what should be a basic process, fetching data from a .json file and outputting it to an HTML Table.

No problem when I uncomment the first 7 lines of code and comment out the next 3 lines that use 'fetch' .  However when I try to 'fetch' and output the data from another file I get the error that I've indicated at line #39 (let data = Object.keys(mountains[0]. I checked the console.log and the 'names.json' file is there as expected so the problem is not with a file path or with the fetch request. I think my problem is at line 39 with the 'Object.keys function. I'm at a loss as to how to reference the json data that was fetched. Any help appreciated!

/*let mountains = [
    { name: "Monte Falco", height: 1658, place: "Parco Foreste Casentinesi" },
    { name: "Monte Falterona", height: 1654, place: "Parco Foreste Casentinesi" },
    { name: "Poggio Scali", height: 1520, place: "Parco Foreste Casentinesi" },
    { name: "Pratomagno", height: 1592, place: "Parco Foreste Casentinesi" },
    { name: "Monte Amiata", height: 1738, place: "Siena" }
  ]; */

 (fetch("names.json")
  .then(res => res.json()
  .then(json => console.log(json))))

  function generateTableHead(table, data) {
    let thead = table.createHead();
    let row = thead.insertRow();
    for (let key of data) {
      let th = document.createElement("th");
      let text = document.createTextNode(key);
      th.appendChild(text);
      row.appendChild(th);

    }
  }

  function generateTable(table, data) {
    for (let element of data) {
      let row = table.insertRow();
      for (key in element) {
        let cell = row.insertCell();
        let text = document.createTextNode(element[key]);
        cell.appendChild(text);
      }
    }
  }

let table = document.querySelector("table");
let data = Object.keys(mountains[0]); //****************************** Uncaught ReferenceError: mountains is not defined
generateTable(table, mountains); // generate the table first
generateTableHead(table, data); // then the head```

答:
When you comment first 7 lines of code so the mountains variable becomes undefined as it is not created yet.
So to run this code you can do your stuff inside the second callback of fetch function i.e. when you get the data in json format, like:</p>
```<code>function generateTableHead(table, data) {
  let thead = table.createHead();
  let row = thead.insertRow();
  for (let key of data) {
    let th = document.createElement("th");
    let text = document.createTextNode(key);
    th.appendChild(text);
    row.appendChild(th);

  }
}

function generateTable(table, data) {
  for (let element of data) {
    let row = table.insertRow();
    for (key in element) {
      let cell = row.insertCell();
      let text = document.createTextNode(element[key]);
      cell.appendChild(text);
    }
  }
}

fetch("names.json")
.then(res => res.json())
.then(json => {

    let mountains = json;
    let table = document.querySelector("table");
    let data = Object.keys(mountains[0]);
    generateTable(table, mountains); // generate the table first
    generateTableHead(table, data); // then the head

})
</code>```

Body:
When you comment first 7 lines of code so the mountains variable becomes undefined as it is not created yet.
So to run this code you can do your stuff inside the second callback of fetch function i.e. when you get the data in json format, like:

function generateTableHead(table, data) {
  let thead = table.createHead();
  let row = thead.insertRow();
  for (let key of data) {
    let th = document.createElement("th");
    let text = document.createTextNode(key);
    th.appendChild(text);
    row.appendChild(th);

  }
}

function generateTable(table, data) {
  for (let element of data) {
    let row = table.insertRow();
    for (key in element) {
      let cell = row.insertCell();
      let text = document.createTextNode(element[key]);
      cell.appendChild(text);
    }
  }
}

fetch("names.json")
.then(res => res.json())
.then(json => {

    let mountains = json;
    let table = document.querySelector("table");
    let data = Object.keys(mountains[0]);
    generateTable(table, mountains); // generate the table first
    generateTableHead(table, data); // then the head

})


问:
using .c files in C# (winform .net)
I am using visual studio 2010
my project is that,
 i want to encrypt text using blowfish algorithm and then add that encrypted data must be saved in my database

my blowfish algorthim is in .c file
my input must be taken via C# (windows form)
and my database is in sql server 2008

i just want to known that can i send the text taken via windows form (.net c#) to my .c file and proccess it and get that encrypted data and save that data in sql server via windows form

can this be done
please help me out

答: You'd have to compile the .c file into a DLL, and then you could use P/Invoke to create a C# binding to it</p>

Title: using .c files in C# (winform .net)


问:
golang - deadlock with gorutine
The code below is a code that puts a value into a channel and receives and print as much as you put in. I expected it to work, but an error occurs.

```<code>package main

import (
    "fmt"
    "time"
)

func main() {
    var ch chan int
    for i := 0; i < 3; i++ {
        go func(idx int) {
            ch <- (idx + 1) * 2
        }(i)
    }

    fmt.Println("result:", <-ch)
    fmt.Println("result:", <-ch)
    fmt.Println("result:", <-ch)
    //do other work
    time.Sleep(2 * time.Second)
}
</code>```

Tested on playground - https://go.dev/play/p/FFmoSMheNfu

答:
You are using a nil channel. The type declaration is not enough, you need to use make to initialize the channel.

ch := make(chan int)
```

https://go.dev/play/p/L1ewulPDYlS

There is an episode of justforfunc which explains how nil channels behave and why they are useful sometimes.

Title: golang - deadlock with gorutine

Body:
The code below is a code that puts a value into a channel and receives and print as much as you put in. I expected it to work, but an error occurs.

package main

import (
    "fmt"
    "time"
)

func main() {
    var ch chan int
    for i := 0; i < 3; i++ {
        go func(idx int) {
            ch <- (idx + 1) * 2
        }(i)
    }

    fmt.Println("result:", <-ch)
    fmt.Println("result:", <-ch)
    fmt.Println("result:", <-ch)
    //do other work
    time.Sleep(2 * time.Second)
}

Tested on playground - https://go.dev/play/p/FFmoSMheNfu

Body:
You are using a nil channel. The type declaration is not enough, you need to use make to initialize the channel.

ch := make(chan int)

https://go.dev/play/p/L1ewulPDYlS

There is an episode of justforfunc which explains how nil channels behave and why they are useful sometimes.


答:
Please note that if i <- colname, then data$i does not produce the corresponding column. Use data[[i]] instead.

```<code>for (i in names(predicted)){
  print(paste("The Mean Squared Forecast Error for",i,"is:",mean((real[[i]]-predicted[[i]])^2)))
}
</code>```

Title: Compute error with two datasets using For loop

Body:
I have 2 datasets that have the same column names.

One dataframe is predicted that has 12 forecasted values for each variable.
The other dataframe is real that has the 12 real values for each variable.

I am trying to make this for loop to print the Mean Squared Forecasted Error.

for (i in names(predicted)){
  print(paste("The Mean Squared Forecast Error for",i,"is:",mean((real$i-predicted$i)^2)))
}

This is the desired output is:

[1] "The Mean Squared Forecast Error for EMPL is: 2.22973256477949e-06"
[1] "The Mean Squared Forecast Error for CPI is: 5.15514699434535e-06"
[1] "The Mean Squared Forecast Error for FFR is: 0.0295111061402315"

I don't know why the for loop gives me that the calculation is NaN

Thanks in advance!

Data

> dput(real)
structure(list(CPI = c(0.00160433859088815, -0.00215862261991973,
-4.59020776588659e-06, -0.000538046208090392, 0.00265772082268079,
-0.00054730999077357, -0.00265434619923699, -0.000529520203581768,
0.00263754860468435, 0.00208864328030867, -0.000548981800946535,
-0.00470589103741226), EMPL = c(0.000440619330092318, 0.000505389630054864,
-0.00064261089956652, 0.00163820296223705, 0.00123949686537728,
0.00231633116306718, 0.00274100555496126, 0.000121807479846581,
-0.000616354925266904, 0.00175489535365614, 0.00356476054636445,
-0.000756181462504557), FFR = c(0.02, 0.01, -0.01, 0, 0, 0.03,
0.23, 0.17, 0.18, 0.15, 0.17, 0.23)), class = "data.frame", row.names = c(NA,
-12L))

> dput(predicted)
structure(list(CPI = c(-0.00185325936075232, -0.000205612911651649,
0.000515554281526663, 0.000832059799115526, -9.59291577299353e-05,
-0.000135397534643682, -0.000319969700328926, -0.000531443546314851,
0.000334709759798288, 0.000149004361515839, -0.000190722371242093,
-6.3736415706231e-05), EMPL = c(0.00180490246150916, 0.00155636832886101,
0.00142059674176869, 0.00104389866040043, 0.0016108887176987,
0.00152450457655764, 0.00106805136354765, 0.00151749850981702,
0.00126307148334478, 0.00121395424088581, 0.0013782559420265,
0.00149406940983166), FFR = c(0.0664586752084257, 0.228921245733048,
0.135151339424908, -0.162398412959252, -0.128277890243452, -0.134292810077186,
-0.049475881436482, 0.0442366320282881, -0.0376918344723898,
-0.018180368465285, 0.0655870731024621, 0.0492813528000579)), class = "data.frame", row.names = c(NA,
-12L))

Body:
Please note that if i <- colname, then data$i does not produce the corresponding column. Use data[[i]] instead.

for (i in names(predicted)){
  print(paste("The Mean Squared Forecast Error for",i,"is:",mean((real[[i]]-predicted[[i]])^2)))
}


问:
How can I switch my signed in user in Visual Studio 2013?
A new feature of Visual Studio 2013 is the ability to sign in with a Microsoft Account and have your settings be persisted across all of your instances of Visual Studio, amongst other things.

When I installed Visual Studio 2013 Preview I signed in with one of several Microsoft Accounts I hold.

I've now installed the RTM version of Visual Studio 2013 (after uninstalling the Preview version) and that has kept my previous user sign in credentials.

I would now like to change these sign in credentials to be a different Microsoft Account but every time I attempt to sign in with the new details I receive a message similar to the following

We were unable to establish the connection because it is configured for user olduser@old.com but you attempted to connect using user newuser@new.com. To connect as a different user perform a switch user operation. To connect with the configured identity just attempt the last operation again.

The problem is I can't find any documentation anywhere on how to perform a "switch user operation".   Maybe I'm just not looking hard enough but hopefully someone here can help me out.

答:
what did the trick for me, I just deleted the .vs folder and wallah it start working again.

It's i think a common bug, sometime visual studio stuck on error, although you have fix them too, you just need to remove the .vs code and everything goes back the way it should be.


问:
Is there a limit on unit number (other than being a positive integer) in gfortran Open statement
Is there a limit on the unit number ( the one specified as unit= ) in Open statement in GFortran.
I realize it needs to be a positive integer.

In early fortran manuals I believe it was a small positive integer under 100.
I used numbers beyond that but under 300 in GFortran and now wondering if I can use numbers as large a 1000,  even 10000.
I could not find any mention of a limit in GFortran manual.

答:
Most likely the typical 32-bit integer values apply, but only the non-negative values.

That would be 0 to 2,147,483,647 (which is evaluated from 2**31-1)

Interestingly the documentation for Intel Fortran states the domain is 0 to 2,147,483,643 which means to me the compiler has reserved some values for special purposes.

I assume gfortran might do the same, so the true max value is undetermined right now, although I bet it is a lot higher than 10000.


问:
create an html select via jquery with a while statement or similar
How do I write an html select statement via jquery?

Let's say I've got this in mind:

```<code><select id="mySelect">
  <option value="400">400</option>
  <option value="401">401</option>
  <option value="402">402</option>
  <option value="403">403</option>
</select>
</code>```

And I need it to be written from jquery.

I've tried this (without success)

```<code>$('#div2').append('<select name = "myshield2" id="myshieldSelect2">');
var i = 400;
while (i < '410') {
   // do some code
   $('#div1').append('<option name="asdf" value = "1">Hey ' + i + ' is the value!</option>');
   i++;
}
$('#div2').append('</select>');
</code>```

答:
```<code>$('#div1').append('<option name="asdf" value = "1">Hey ' + i....');
</code>```

is wrong It should be

```<code>$('#myshieldSelect2').append('<option name="asdf" ....');
</code>```

Completed it is:

```<code>$('#div2').append('<select name = "myshield2" id="myshieldSelect2">');
var i = 400;
while (i < '410')
   $('#myshieldSelect2').append('<option name="asdf" value = "1">Hey ' + i++ + '...');
</code>```

Body:
How do I write an html select statement via jquery?

Let's say I've got this in mind:

<select id="mySelect">
  <option value="400">400</option>
  <option value="401">401</option>
  <option value="402">402</option>
  <option value="403">403</option>
</select>

And I need it to be written from jquery.

I've tried this (without success)

$('#div2').append('<select name = "myshield2" id="myshieldSelect2">');
var i = 400;
while (i < '410') {
   // do some code
   $('#div1').append('<option name="asdf" value = "1">Hey ' + i + ' is the value!</option>');
   i++;
}
$('#div2').append('</select>');

Body:
$('#div1').append('<option name="asdf" value = "1">Hey ' + i....');

is wrong It should be

$('#myshieldSelect2').append('<option name="asdf" ....');

Completed it is:

$('#div2').append('<select name = "myshield2" id="myshieldSelect2">');
var i = 400;
while (i < '410')
   $('#myshieldSelect2').append('<option name="asdf" value = "1">Hey ' + i++ + '...');


问:
Flutter notification badge listen when update
I am new to flutter, I would like to make a chat app with notification badge that listen to incoming message and remove badge when I click. How do I make it?

Thank you.

答:
Can you try to look at into this? Hope this helps
https://api.flutter.dev/flutter/widgets/NotificationListener-class.html</p>


问:
How to get rank of a column by filtering by two columns?
I have the data frame below. I want to get a create a new column called rank that ranks the stock by growth for each year and sector.

```<code>import pandas as pd
d = {'date': [2000, 2000, 2001, 2001, 2002, 2002, 2003, 2003, 2004, 2004],  'Stock': ["GM", "F", "GM", "F", "GM", "F", "GM", "F", "GM", "F"], 'US Sales Growth': [.3, .3, .1, .1, .6, .6, .12, .12, .7, .7], 'Stock_Growth': [.1, .2, .3, .4, .14, .16,  .2, .1,.15,.16]}
df = pd.DataFrame(data=d)
</code>```

It should look like this.

```<code>d = {'date': [2000, 2000, 2001, 2001, 2002, 2002, 2003, 2003, 2004, 2004],  'Stock': ["GM", "F", "GM", "F", "GM", "F", "GM", "F", "GM", "F"], 'Sector': ['Auto', 'Auto', 'Auto', 'Auto', 'Auto', 'Auto', 'Auto', 'Auto', 'Auto', 'Auto'],  'US Sales Growth': [.3, .3, .1, .1, .6, .6, .12, .12, .7, .7], 'Stock_Growth': [.1, .2, .3, .4, .14, .16,  .2, .1,.15,.16], 'Rank': [2, 1, 2, 1, 2, 1, 1, 2, 2, 1]}

df2 = pd.DataFrame(data=d)
</code>```

I tried doing this but just gave me NANs

```<code>df['place_holder'] = df.groupby(['Stock','date'], as_index=False)['Stock_Growth'].transform(lambda x: x.shift(1))
df['rank']  = df.groupby('date', as_index=False)['place_holder'].transform(lambda x: x.rank())
</code>```

Another way of doing it was get groupby date first then sector and then rank them.

答:
Using groupby and then apply another step to rank each group seems the right approach. I recommend using the rank method of a Groupby object to compute the rank of the values of a column in each group. This means, that this should provide the expected output:

```<code>>> df["Rank"] = df.groupby(["date", "Sector"])["Stock_Growth"].rank(ascending=False)
>> df
   date Stock  US Sales Growth  Stock_Growth Sector  Rank
0  2000    GM             0.30          0.10   Auto   2.0
1  2000     F             0.30          0.20   Auto   1.0
2  2001    GM             0.10          0.30   Auto   2.0
3  2001     F             0.10          0.40   Auto   1.0
4  2002    GM             0.60          0.14   Auto   2.0
5  2002     F             0.60          0.16   Auto   1.0
6  2003    GM             0.12          0.20   Auto   1.0
7  2003     F             0.12          0.10   Auto   2.0
8  2004    GM             0.70          0.15   Auto   2.0
9  2004     F             0.70          0.16   Auto   1.0
</code>```

The ascending=False part ensures that higher values get a better (lower) rank.

Body:
I have the data frame below. I want to get a create a new column called rank that ranks the stock by growth for each year and sector.

import pandas as pd
d = {'date': [2000, 2000, 2001, 2001, 2002, 2002, 2003, 2003, 2004, 2004],  'Stock': ["GM", "F", "GM", "F", "GM", "F", "GM", "F", "GM", "F"], 'US Sales Growth': [.3, .3, .1, .1, .6, .6, .12, .12, .7, .7], 'Stock_Growth': [.1, .2, .3, .4, .14, .16,  .2, .1,.15,.16]}
df = pd.DataFrame(data=d)

It should look like this.

d = {'date': [2000, 2000, 2001, 2001, 2002, 2002, 2003, 2003, 2004, 2004],  'Stock': ["GM", "F", "GM", "F", "GM", "F", "GM", "F", "GM", "F"], 'Sector': ['Auto', 'Auto', 'Auto', 'Auto', 'Auto', 'Auto', 'Auto', 'Auto', 'Auto', 'Auto'],  'US Sales Growth': [.3, .3, .1, .1, .6, .6, .12, .12, .7, .7], 'Stock_Growth': [.1, .2, .3, .4, .14, .16,  .2, .1,.15,.16], 'Rank': [2, 1, 2, 1, 2, 1, 1, 2, 2, 1]}

df2 = pd.DataFrame(data=d)

I tried doing this but just gave me NANs

df['place_holder'] = df.groupby(['Stock','date'], as_index=False)['Stock_Growth'].transform(lambda x: x.shift(1))
df['rank']  = df.groupby('date', as_index=False)['place_holder'].transform(lambda x: x.rank())

Another way of doing it was get groupby date first then sector and then rank them.

Body:
Using groupby and then apply another step to rank each group seems the right approach. I recommend using the rank method of a Groupby object to compute the rank of the values of a column in each group. This means, that this should provide the expected output:

>> df["Rank"] = df.groupby(["date", "Sector"])["Stock_Growth"].rank(ascending=False)
>> df
   date Stock  US Sales Growth  Stock_Growth Sector  Rank
0  2000    GM             0.30          0.10   Auto   2.0
1  2000     F             0.30          0.20   Auto   1.0
2  2001    GM             0.10          0.30   Auto   2.0
3  2001     F             0.10          0.40   Auto   1.0
4  2002    GM             0.60          0.14   Auto   2.0
5  2002     F             0.60          0.16   Auto   1.0
6  2003    GM             0.12          0.20   Auto   1.0
7  2003     F             0.12          0.10   Auto   2.0
8  2004    GM             0.70          0.15   Auto   2.0
9  2004     F             0.70          0.16   Auto   1.0

The ascending=False part ensures that higher values get a better (lower) rank.


问:
issue in opening android studio app in pc. The finish icon is not showing hence I cannot complete the license agreement and cannot create new project
enter image description here

look that the finish icon is not showing , what shall I do help me out in this issue.

答: You are just accepting the android-sdk license not the other two marked with red asterisk. Accept all three and then proceed.


答: Yes. This is called interop and it can be done in various ways. One of them is called Pinvoke - you create a DLL that exports the function you want to call from c# and pinvoke will take care of the rest. I suggest you read about it in microsoft's docs. </p>

Title: using .c files in C# (winform .net)

Body:
I am using visual studio 2010
my project is that,
 i want to encrypt text using blowfish algorithm and then add that encrypted data must be saved in my database

my blowfish algorthim is in .c file
my input must be taken via C# (windows form)
and my database is in sql server 2008

i just want to known that can i send the text taken via windows form (.net c#) to my .c file and proccess it and get that encrypted data and save that data in sql server via windows form

can this be done
please help me out


问:
Can Anyone tell me the reason, why my method does not pass the sample test cases?
The following is my solution to Beautiful Days at the Movies problem on HackerRank.

Basically I need to implement the following method.

int beautifulNum(int from, int to, int k)
```
<p>The method should return the number of beautiful numbers between <code>from</code> and <code>to</code>.</p>
<p>A number is beautiful if the result of its difference with its reverse is divisible by <code>k</code>.</p>
<p>Example:
<code>beautifulNum(20, 23, 6)</code> should return 2.</p>
<ul>
<li>Reverse of 20 is 2. Difference is 18 which is divisible by 6 so 20 is a beautiful number.</li>
<li>Reverse of 21 is 12. Difference is 9 which is not divisible by 6 hence 21 is not a beautiful number.</li>
<li>Similarly, 22 is a beautiful number and 23 is not.</li>
<li>Therefore <code>beautifulNum(20, 23, 6)</code> should return 2.</li>
</ul>
<p>However, the following does not work, why?</p>
<pre class="lang-java prettyprint-override"><code>public static int beautifulNum(int from, int to, int k) {
    int reverse = 0;
    int num = 0;
    for (int n = from; n <= to; n++) {
        while(n != 0) {
            int remainder = n % 10;
            reverse = reverse * 10 + remainder;
            n = n/10;
        }
        int rreverse = (n-reverse)/k;
        if (rreverse % 1 == 0 ) {
            num++;
        }
    }
    return num;
}
</code>```

答:
There are many ways to reverse a number in Java. Refer to Java reverse an int value without using array. In the below code I chose to convert the number to a string and use method reverse of class StringBuilder.

Then you need to subtract the reversed number from the original number and then you need to see whether the result of that subtraction is divisible by the method parameter k. In other words you need to check whether difference % k == 0 where difference is the result of subtracting the reversed number from the original number.

public class MyClass {

    public static int beautifulNum(int from, int to, int k) {
        int reverse = 0;
        int num = 0;
        for (int n = from; n <= to; n++) {
            StringBuilder sb = new StringBuilder(Integer.toString(n));
            sb.reverse();
            reverse = Integer.parseInt(sb.toString());
            int rreverse = n - reverse;
            if (rreverse % k == 0) {
                num++;
            }
        }
        return num;
    }

    public static void main(String args[]) {
        System.out.println(beautifulNum(20, 23, 6));
    }
}
```

Body:
The following is my solution to Beautiful Days at the Movies problem on HackerRank.

Basically I need to implement the following method.

int beautifulNum(int from, int to, int k)

The method should return the number of beautiful numbers between from and to.

A number is beautiful if the result of its difference with its reverse is divisible by k.

Example:
beautifulNum(20, 23, 6) should return 2.

Reverse of 20 is 2. Difference is 18 which is divisible by 6 so 20 is a beautiful number.

Reverse of 21 is 12. Difference is 9 which is not divisible by 6 hence 21 is not a beautiful number.

Similarly, 22 is a beautiful number and 23 is not.

Therefore beautifulNum(20, 23, 6) should return 2.

However, the following does not work, why?

public static int beautifulNum(int from, int to, int k) {
    int reverse = 0;
    int num = 0;
    for (int n = from; n <= to; n++) {
        while(n != 0) {
            int remainder = n % 10;
            reverse = reverse * 10 + remainder;
            n = n/10;
        }
        int rreverse = (n-reverse)/k;
        if (rreverse % 1 == 0 ) {
            num++;
        }
    }
    return num;
}


问:
How to fix 'TransferHelper: ETH_TRANSFER_FAILED' when interacting with Uni V2
I'm dealing with a strange issue with the safeTransferETH helper function in Uniswap V2's router contract.

I'm trying to swap tokens held by the contract to Uniswap for Ether, using the swapExactTokensForETH function provided by the Uniswap V2 router. (The function code is present on Uniswap's github in router1). The function being called is:

```<code>function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        override
        ensure(deadline)
        returns (uint[] memory amounts)
    {
        require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
        amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
        require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
        TransferHelper.safeTransferFrom(path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]);
        _swap(amounts, path, address(this));
        IWETH(WETH).withdraw(amounts[amounts.length - 1]);
        TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
    }
</code>```

The only part of this code that is throwing an error is the TransferHelper.safeTransferETH function, which is:

```<code>function safeTransferETH(address to, uint value) internal {
    (bool success,) = to.call{value:value}(new bytes(0));
    require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
</code>```

My code is:

```<code>function uniV2ReceiveETH(address _token0, uint _amount0) public payable returns (uint[] memory amountsReceived) {
        require(_amount0 > 0, "Must provide tokens if we want tokens in return!");
        address[] memory path = new address[](2);
        path[0] = _token0;
        path[1] = WETH;

        IERC20 token;
        token = IERC20(_token0);

        if (token.balanceOf(address(this)) > 0) {
            _amount0 = token.balanceOf(address(this));
        }

        require(token.approve(address(uniV2Router), _amount0 + 10000), "approval failed");

        // Swap logic
        uint amountOutMin = UniswapV2Library.getAmountsOut(address(uniV2Factory), _amount0, path)[1];
        amountsReceived = uniV2Router.swapExactTokensForETH(_amount0, amountOutMin, path, address(this), deadline);
        uint endBalance = address(this).balance;

        // Let everyone know we're done!
        emit Swap(msg.sender, _amount0, endBalance);
}
</code>```

A few other notes are:

The contract does receive ETH from other addresses without issue.

I am using hardhat, and a forked version of the mainnet to test.

The contract also works with the Uniswap router's other swap functions, including SwapExactETHForTokens and SwapExactTokensForTokens.

答:
I solved this issue by having a payable fallback function by defining it as:

```<code>fallback() external payable { }
</code>```

inside my smart contract.

Body:
I'm dealing with a strange issue with the safeTransferETH helper function in Uniswap V2's router contract.

I'm trying to swap tokens held by the contract to Uniswap for Ether, using the swapExactTokensForETH function provided by the Uniswap V2 router. (The function code is present on Uniswap's github in router1). The function being called is:

function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        override
        ensure(deadline)
        returns (uint[] memory amounts)
    {
        require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
        amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
        require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
        TransferHelper.safeTransferFrom(path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]);
        _swap(amounts, path, address(this));
        IWETH(WETH).withdraw(amounts[amounts.length - 1]);
        TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
    }

The only part of this code that is throwing an error is the TransferHelper.safeTransferETH function, which is:

function safeTransferETH(address to, uint value) internal {
    (bool success,) = to.call{value:value}(new bytes(0));
    require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}

My code is:

function uniV2ReceiveETH(address _token0, uint _amount0) public payable returns (uint[] memory amountsReceived) {
        require(_amount0 > 0, "Must provide tokens if we want tokens in return!");
        address[] memory path = new address[](2);
        path[0] = _token0;
        path[1] = WETH;

        IERC20 token;
        token = IERC20(_token0);

        if (token.balanceOf(address(this)) > 0) {
            _amount0 = token.balanceOf(address(this));
        }

        require(token.approve(address(uniV2Router), _amount0 + 10000), "approval failed");

        // Swap logic
        uint amountOutMin = UniswapV2Library.getAmountsOut(address(uniV2Factory), _amount0, path)[1];
        amountsReceived = uniV2Router.swapExactTokensForETH(_amount0, amountOutMin, path, address(this), deadline);
        uint endBalance = address(this).balance;

        // Let everyone know we're done!
        emit Swap(msg.sender, _amount0, endBalance);
}

A few other notes are:

The contract does receive ETH from other addresses without issue.

I am using hardhat, and a forked version of the mainnet to test.

The contract also works with the Uniswap router's other swap functions, including SwapExactETHForTokens and SwapExactTokensForTokens.

Body:
I solved this issue by having a payable fallback function by defining it as:

fallback() external payable { }

inside my smart contract.


问:
How to pass button value to another component in React
I want to pass table cell data(URL) to another IFrame component.

The web app is used to preview CSV URL data, Once the URL clicked I want to show the web in the IFrame.

```<code><table className="table table-responsive overflow-x">
  <tbody>
    {items.map((d, x) => (
      <tr key={d.x}>
        <td scope="row">{x + 1}</td>
        <td id="urlcol">
          <button className="btn" onClick={(e) => this.onClick(e)}>
            {d.Link_Address}{" "}
          </button>
        </td>
      </tr>
    ))}
  </tbody>
</table>
</code>```

Iframe Component

How can I do this?

Thanks.

答:
Remove the double qoutes " " from:

```<code><Iframe url="{props.url}" />

</code>```

Should be like this:

```<code><Iframe url={props.url} />

</code>```

in general if you want to pass something from Parent component to child component, will be like this:

Parent component:

```<code>import React, { useState } from 'react';
import Child from './Child.js';

export default function Parent(){
  //you can put anything in inside useEffect, not only an array
  const [items, setItems] = useState(['item1','item2','item3']);
  const [currentItem, setCurrentItem] = useState('item1');

  const changeCurrentItem = (item)=> {
     setCurrentItem(item);
 }

 return (<div>

        {items.map((item, key)=> {return <button key={key} onClick={()=> changeCurrentItem(item)} > {item} </button>})}

        <div className='child-component-container'>
        <Child item={currentItem} />
        </div>

        </div>)
 }

</code>```

Child component:

```<code>import React from 'react';

export default function Child(props){

 return (<div>

<p> item from Parent component: {props.item} </p>

</div>);

 }

</code>```

Body:
I want to pass table cell data(URL) to another IFrame component.

The web app is used to preview CSV URL data, Once the URL clicked I want to show the web in the IFrame.

    {items.map((d, x) => (

        {x + 1}

          <button className="btn" onClick={(e) => this.onClick(e)}>
            {d.Link_Address}{" "}
          </button>

    ))}

Iframe Component

How can I do this?

Thanks.

Body:
Remove the double qoutes " " from:

<Iframe url="{props.url}" />

Should be like this:

<Iframe url={props.url} />

in general if you want to pass something from Parent component to child component, will be like this:

Parent component:

import React, { useState } from 'react';
import Child from './Child.js';

export default function Parent(){
  //you can put anything in inside useEffect, not only an array
  const [items, setItems] = useState(['item1','item2','item3']);
  const [currentItem, setCurrentItem] = useState('item1');

  const changeCurrentItem = (item)=> {
     setCurrentItem(item);
 }

 return (<div>

        {items.map((item, key)=> {return <button key={key} onClick={()=> changeCurrentItem(item)} > {item} </button>})}

        <div className='child-component-container'>
        <Child item={currentItem} />
        </div>

        </div>)
 }

Child component:

import React from 'react';

export default function Child(props){

 return (<div>

<p> item from Parent component: {props.item} </p>

</div>);

 }


问:
Jquery get image src array
I'm making a discord bot with discord.js.
jQuery get the image src

looked for the most relevant article, but it's different from what I'm trying to do.

I'd like to receive several srcs of img in the span tag by array.

        // this src

     Lv.5

        // this src
     Lv.5

```
<pre class="lang-js prettyprint-override"><code>const jewel = $(".jewel_level").text();
const jewel2 = $(".jewel_img").find('img').attr("src");

console.log("jewel : ", jewel, "jewel2 : ", jewel2);
</code>```

jewel receives both lv.5 and ex) lv.5lv.5.
jewel2 only receives one src.

How should I bring it?

console

```<code>jewel : Lv.5Lv.5 jewel2 : https://xxx/60.png
</code>```

答:
The problem with jQuery's .attr() is...

Get the value of an attribute for the first element in the set of matched elements

Instead, you can use jQuery's .map() to transform a collection of elements into an array

const sources = $(".jewel_img > img")
  .map((_, { src }) => src) // extract property
  .get() // get the array out of the jQuery object

console.log("sources", sources)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- minified HTML -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<div class="jewel__wrap"> <span id="gem00" class="jewel_btn" data-grade="3" data-item="E595062cGem_000"> <span class="jewel_img"> <img src="https://xxx/60.png" alt=""> </span> <span class="jewel_level">Lv.5</span> </span> <span id="gem01" class="jewel_btn" data-grade="3" data-item="E595062cGem_001"> <span class="jewel_img"> <img src="https://xxx/50.png" alt=""></span> <span class="jewel_level">Lv.5</span> </span></div></code>```

You may even want to treat the text in a similar way and collect all the data into objects

const data = $(".jewel_btn")
  .map((_, btn) => {
    const $btn = $(btn)
    return {
      image: $btn.find(".jewel_img img").attr("src"),
      level: $btn.find(".jewel_level").text()
    }
  })
  .get()

console.log("data", data)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<div class="jewel__wrap"> <span id="gem00" class="jewel_btn" data-grade="3" data-item="E595062cGem_000"> <span class="jewel_img"> <img src="https://xxx/60.png" alt=""> </span> <span class="jewel_level">Lv.5</span> </span> <span id="gem01" class="jewel_btn" data-grade="3" data-item="E595062cGem_001"> <span class="jewel_img"> <img src="https://xxx/50.png" alt=""></span> <span class="jewel_level">Lv.5</span> </span></div></code>```

Title: Jquery get image src array

Body:
I'm making a discord bot with discord.js.
jQuery get the image src

looked for the most relevant article, but it's different from what I'm trying to do.

I'd like to receive several srcs of img in the span tag by array.

        // this src

     Lv.5

        // this src
     Lv.5

const jewel = $(".jewel_level").text();
const jewel2 = $(".jewel_img").find('img').attr("src");

console.log("jewel : ", jewel, "jewel2 : ", jewel2);

jewel receives both lv.5 and ex) lv.5lv.5.
jewel2 only receives one src.

How should I bring it?

console

jewel : Lv.5Lv.5 jewel2 : https://xxx/60.png

Body:
The problem with jQuery's .attr() is...

Get the value of an attribute for the first element in the set of matched elements

Instead, you can use jQuery's .map() to transform a collection of elements into an array

const sources = $(".jewel_img > img")
  .map((_, { src }) => src) // extract property
  .get() // get the array out of the jQuery object

console.log("sources", sources)

<!-- minified HTML -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<div class="jewel__wrap"> <span id="gem00" class="jewel_btn" data-grade="3" data-item="E595062cGem_000"> <span class="jewel_img"> <img src="https://xxx/60.png" alt=""> </span> <span class="jewel_level">Lv.5</span> </span> <span id="gem01" class="jewel_btn" data-grade="3" data-item="E595062cGem_001"> <span class="jewel_img"> <img src="https://xxx/50.png" alt=""></span> <span class="jewel_level">Lv.5</span> </span></div>

You may even want to treat the text in a similar way and collect all the data into objects

const data = $(".jewel_btn")
  .map((_, btn) => {
    const $btn = $(btn)
    return {
      image: $btn.find(".jewel_img img").attr("src"),
      level: $btn.find(".jewel_level").text()
    }
  })
  .get()

console.log("data", data)

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<div class="jewel__wrap"> <span id="gem00" class="jewel_btn" data-grade="3" data-item="E595062cGem_000"> <span class="jewel_img"> <img src="https://xxx/60.png" alt=""> </span> <span class="jewel_level">Lv.5</span> </span> <span id="gem01" class="jewel_btn" data-grade="3" data-item="E595062cGem_001"> <span class="jewel_img"> <img src="https://xxx/50.png" alt=""></span> <span class="jewel_level">Lv.5</span> </span></div>


问:
Room Database migration code getting executed every time I open app
I am migrating from version 16 to version 17 in my database. But Whenever I open the application, The migration code gets executed. I am not even getting error or any exception.

Have tried to print the log statements after each query, all logs statements are getting printed.

And There is no error in SQL queries, I have tried executing those separately, Have tried commenting out the queries in the migration logic.  Still facing the same problem.
Please help. Thanks in advance.

This is my Migration code.

```<code>private val MIGRATION_16_17: Migration = object : Migration(16, 17) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("DROP TABLE IF EXISTS beneficiary_meta_details")
                database.execSQL("CREATE TABLE IF NOT EXISTS beneficiary_details (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, beneficiaryRefId TEXT , beneficiaryInstrumentRefId TEXT, status TEXT, instrumentType TEXT, displayName TEXT, image TEXT, lastTxnTimeStamp INTEGER, lastTransactionAmount REAL, transactionCategory TEXT, vpa TEXT, bankingName TEXT, mobileNo TEXT, custId TEXT, nickName TEXT, accountRefId TEXT, accountNumber TEXT, maskedAccountNumber TEXT, ifsc TEXT, bankName TEXT, state TEXT, appLocalBeneficiaryName TEXT, appLocalBeneficiaryImageUrl TEXT)")
                database.execSQL("ALTER TABLE configuration_table ADD COLUMN refreshNumber INTEGER NOT NULL DEFAULT 0")
            }
        }
</code>```

And these are my corresponding data classes

```<code>@Entity(tableName = "beneficiary_details")
data class BeneficiaryDetailModel(
    @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") var id: Long = 0L,

    @ColumnInfo(name = "beneficiaryRefId") var beneficiaryRefId: String?,
    @ColumnInfo(name = "beneficiaryInstrumentRefId") var beneficiaryInstrumentRefId: String?,
    @ColumnInfo(name = "status") var status: String?,
    @ColumnInfo(name = "instrumentType") var instrumentType: String?,
    @ColumnInfo(name = "displayName") var displayName: String?,
    @ColumnInfo(name = "image") var image: String?,
    @ColumnInfo(name = "lastTxnTimeStamp") var lastTxnTimeStamp: Long?,
    @ColumnInfo(name = "lastTransactionAmount") var lastTransactionAmount: Float?,
    @ColumnInfo(name = "transactionCategory") var transactionCategory : String?,
    @ColumnInfo(name = "vpa") var vpa: String?,
    @ColumnInfo(name = "bankingName") var bankingName: String?,
    @ColumnInfo(name = "mobileNo") var mobileNo: String?,
    @ColumnInfo(name = "custId") var custId: String?,
    @ColumnInfo(name = "nickName") var nickName: String?,
    @ColumnInfo(name = "accountRefId") var accountRefId: String?,
    @ColumnInfo(name = "accountNumber") var accountNumber: String?,
    @ColumnInfo(name = "maskedAccountNumber") var maskedAccountNumber: String?,
    @ColumnInfo(name = "ifsc") var ifsc: String?,
    @ColumnInfo(name = "bankName") var bankName: String?,
    @ColumnInfo(name = "state") var state: String?,
    @ColumnInfo(name = "appLocalBeneficiaryName") var appLocalBeneficiaryName: String?=null,
    @ColumnInfo(name = "appLocalBeneficiaryImageUrl") var appLocalBeneficiaryImageUrl: String?=null
)
</code>```

and

```<code>@Entity(tableName = "configuration_table", indices = [androidx.room.Index(value = ["type"], unique = true)])
data class Configuration (
    @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") var id: Long = 0L,
    @ColumnInfo(name = "timestamp") var timestamp: Long,
    @ColumnInfo(name = "type") var type: Int?,
    @ColumnInfo(name = "fallbackEnabled") var fallbackEnabled: Boolean?,
    @ColumnInfo(name = "refreshNumber") var refreshNumber: Int
)
</code>```

答:
But Whenever I open the application, The migration code gets executed.

You don't say how you know this to be the case.

The code you have provided works as expected (as is shown below).

It is highly unlikely that the migration is actually being invoked and somehow reverting so that upon another run it is run again.

Often issues with the Migration not apparently running is due to a misunderstanding about exactly when the database migration occur, this being dependant upon an actual request for access to the database and the database being opened.

More specifically getting an instance of the Built database does not open the the database. Rather an attempt has to be made to access the database before it is opened.

e.g.

```<code>db = TheDatabase.getInstance(this) /* Does not open the database and therefore Migrate */
theDao = getTheDao() /* Only gets the Dao instance, does not open the database */
</code>```

It is not until:-

```<code>var whatever = theDao.doSomething()
</code>```

That the database will be opened.

This is perhaps what your issue is. If so just accessing the data via one of the functions in the class annotated with @Dao will open the dataabase. Alternately you could force an open e.g. db.openHelper.writableDatabase /* Force database open */

If not then I would suggest adding some debugging.

Note that the following is based upon and tested according to your code

As you are dropping the beneficial_meta_detail table the replacement beneficial_details table was used as the basis (i.e. the columns in the meta_details is irrelevant as they get dropped)

set a const for the Database version e.g.

```<code>  const val DATABASE_VERSION = 16
  @Database(entities = [BeneficiaryMetaDetailsModel::class,Configuration::class], exportSchema = false, version = DATABASE_VERSION)
</code>```

note this has been taken from an example/test where version 16 is built to then migrate to 17

add the function (this on it's own does nothing):-

```<code>  @SuppressLint("Range")
  private fun showDBInfo(db: SupportSQLiteDatabase) {
      Log.d("DBVERSIONINFO","Actual Database Version is ${db.version}, Build Version is ${DATABASE_VERSION}")
      val csr = db.query("SELECT * FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' AND name NOT LIKE 'room_%' AND name NOT LIKE 'android_%'")
      while (csr.moveToNext()) {
          Log.d("DBSCHEMA",csr.getString(csr.getColumnIndex("sql")))
      }
  }
</code>```

amend MIGRATION_16_17 to include a call to the new function
showDBInfo e.g.

```<code>  private val MIGRATION_16_17: Migration = object : Migration(16, 17) {
      override fun migrate(database: SupportSQLiteDatabase) {
          showDBInfo(database)
          database.execSQL("DROP TABLE IF EXISTS beneficiary_meta_details")
          database.execSQL("CREATE TABLE IF NOT EXISTS beneficiary_details (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, beneficiaryRefId TEXT , beneficiaryInstrumentRefId TEXT, status TEXT, instrumentType TEXT, displayName TEXT, image TEXT, lastTxnTimeStamp INTEGER, lastTransactionAmount REAL, transactionCategory TEXT, vpa TEXT, bankingName TEXT, mobileNo TEXT, custId TEXT, nickName TEXT, accountRefId TEXT, accountNumber TEXT, maskedAccountNumber TEXT, ifsc TEXT, bankName TEXT, state TEXT, appLocalBeneficiaryName TEXT, appLocalBeneficiaryImageUrl TEXT)")
          database.execSQL("ALTER TABLE configuration_table ADD COLUMN refreshNumber INTEGER NOT NULL DEFAULT 0")
      }
  }
</code>```

optional, but suggested, add a CallBack that will invoke the showDBInfo when the respective function is invoked e.g. :-

```<code>  private object cb: Callback() {
      override fun onCreate(db: SupportSQLiteDatabase) {
          super.onCreate(db)
          Log.d("DBCALLBACK","onCreate CallBack Invoked")
          showDBInfo(db)
      }

      override fun onOpen(db: SupportSQLiteDatabase) {
          super.onOpen(db)
          Log.d("DBCALLBACK","onOpen CallBack Invoked")
          showDBInfo(db)
      }

      override fun onDestructiveMigration(db: SupportSQLiteDatabase) {
          super.onDestructiveMigration(db)
          Log.d("DBCALLBACK","onDestructive CallBack Invoked")
          showDBInfo(db)
      }
  }
</code>```

amend the databaseBuilder to include the CallBack :-

```<code>              .addMigrations(MIGRATION_16_17)
              .addCallback(cb)
              .build()
</code>```

Now if you run the App then the log would include :-

```<code>D/DBVERSIONINFO: Actual Database Version is 16, Build Version is 17
D/DBSCHEMA: CREATE TABLE `beneficiary_meta_details` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `beneficiaryRefId` TEXT, `beneficiaryInstrumentRefId` TEXT, `status` TEXT, `instrumentType` TEXT, `displayName` TEXT, `image` TEXT, `lastTxnTimeStamp` INTEGER, `lastTransactionAmount` REAL, `transactionCategory` TEXT, `vpa` TEXT, `bankingName` TEXT, `mobileNo` TEXT, `custId` TEXT, `nickName` TEXT, `accountRefId` TEXT, `accountNumber` TEXT, `maskedAccountNumber` TEXT, `ifsc` TEXT, `bankName` TEXT, `state` TEXT, `appLocalBeneficiaryName` TEXT, `appLocalBeneficiaryImageUrl` TEXT)
D/DBSCHEMA: CREATE TABLE `configuration_table` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `timestamp` INTEGER NOT NULL, `type` INTEGER, `fallbackEnabled` INTEGER)
D/DBSCHEMA: CREATE UNIQUE INDEX `index_configuration_table_type` ON `configuration_table` (`type`)
D/DBCALLBACK: onOpen CallBack Invoked
D/DBVERSIONINFO: Actual Database Version is 17, Build Version is 17
D/DBSCHEMA: CREATE TABLE `configuration_table` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `timestamp` INTEGER NOT NULL, `type` INTEGER, `fallbackEnabled` INTEGER, refreshNumber INTEGER NOT NULL DEFAULT 0)
D/DBSCHEMA: CREATE UNIQUE INDEX `index_configuration_table_type` ON `configuration_table` (`type`)
D/DBSCHEMA: CREATE TABLE beneficiary_details (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, beneficiaryRefId TEXT , beneficiaryInstrumentRefId TEXT, status TEXT, instrumentType TEXT, displayName TEXT, image TEXT, lastTxnTimeStamp INTEGER, lastTransactionAmount REAL, transactionCategory TEXT, vpa TEXT, bankingName TEXT, mobileNo TEXT, custId TEXT, nickName TEXT, accountRefId TEXT, accountNumber TEXT, maskedAccountNumber TEXT, ifsc TEXT, bankName TEXT, state TEXT, appLocalBeneficiaryName TEXT, appLocalBeneficiaryImageUrl TEXT)
</code>```

Noting that when the Migration is called (first 4 lines) that the database version is 16 AND that when the onOpen callback is called that the database version is 17.

On a subsequent run (whilst still at version 17) you would get :-

```<code>D/DBCALLBACK: onOpen CallBack Invoked
D/DBVERSIONINFO: Actual Database Version is 17, Build Version is 17
D/DBSCHEMA: CREATE TABLE `configuration_table` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `timestamp` INTEGER NOT NULL, `type` INTEGER, `fallbackEnabled` INTEGER, refreshNumber INTEGER NOT NULL DEFAULT 0)
D/DBSCHEMA: CREATE UNIQUE INDEX `index_configuration_table_type` ON `configuration_table` (`type`)
D/DBSCHEMA: CREATE TABLE beneficiary_details (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, beneficiaryRefId TEXT , beneficiaryInstrumentRefId TEXT, status TEXT, instrumentType TEXT, displayName TEXT, image TEXT, lastTxnTimeStamp INTEGER, lastTransactionAmount REAL, transactionCategory TEXT, vpa TEXT, bankingName TEXT, mobileNo TEXT, custId TEXT, nickName TEXT, accountRefId TEXT, accountNumber TEXT, maskedAccountNumber TEXT, ifsc TEXT, bankName TEXT, state TEXT, appLocalBeneficiaryName TEXT, appLocalBeneficiaryImageUrl TEXT)
</code>```

Prior to the migration you would get something like:-

```<code>D/DBVERSIONINFO: Actual Database Version is 16, Build Version is 16
D/DBSCHEMA: CREATE TABLE `beneficiary_meta_details` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `beneficiaryRefId` TEXT, `beneficiaryInstrumentRefId` TEXT, `status` TEXT, `instrumentType` TEXT, `displayName` TEXT, `image` TEXT, `lastTxnTimeStamp` INTEGER, `lastTransactionAmount` REAL, `transactionCategory` TEXT, `vpa` TEXT, `bankingName` TEXT, `mobileNo` TEXT, `custId` TEXT, `nickName` TEXT, `accountRefId` TEXT, `accountNumber` TEXT, `maskedAccountNumber` TEXT, `ifsc` TEXT, `bankName` TEXT, `state` TEXT, `appLocalBeneficiaryName` TEXT, `appLocalBeneficiaryImageUrl` TEXT)
D/DBSCHEMA: CREATE TABLE `configuration_table` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `timestamp` INTEGER NOT NULL, `type` INTEGER, `fallbackEnabled` INTEGER)
D/DBSCHEMA: CREATE UNIQUE INDEX `index_configuration_table_type` ON `configuration_table` (`type`)
</code>```

Body:
I am migrating from version 16 to version 17 in my database. But Whenever I open the application, The migration code gets executed. I am not even getting error or any exception.

Have tried to print the log statements after each query, all logs statements are getting printed.

And There is no error in SQL queries, I have tried executing those separately, Have tried commenting out the queries in the migration logic.  Still facing the same problem.
Please help. Thanks in advance.

This is my Migration code.

private val MIGRATION_16_17: Migration = object : Migration(16, 17) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("DROP TABLE IF EXISTS beneficiary_meta_details")
                database.execSQL("CREATE TABLE IF NOT EXISTS beneficiary_details (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, beneficiaryRefId TEXT , beneficiaryInstrumentRefId TEXT, status TEXT, instrumentType TEXT, displayName TEXT, image TEXT, lastTxnTimeStamp INTEGER, lastTransactionAmount REAL, transactionCategory TEXT, vpa TEXT, bankingName TEXT, mobileNo TEXT, custId TEXT, nickName TEXT, accountRefId TEXT, accountNumber TEXT, maskedAccountNumber TEXT, ifsc TEXT, bankName TEXT, state TEXT, appLocalBeneficiaryName TEXT, appLocalBeneficiaryImageUrl TEXT)")
                database.execSQL("ALTER TABLE configuration_table ADD COLUMN refreshNumber INTEGER NOT NULL DEFAULT 0")
            }
        }

And these are my corresponding data classes

@Entity(tableName = "beneficiary_details")
data class BeneficiaryDetailModel(
    @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") var id: Long = 0L,

    @ColumnInfo(name = "beneficiaryRefId") var beneficiaryRefId: String?,
    @ColumnInfo(name = "beneficiaryInstrumentRefId") var beneficiaryInstrumentRefId: String?,
    @ColumnInfo(name = "status") var status: String?,
    @ColumnInfo(name = "instrumentType") var instrumentType: String?,
    @ColumnInfo(name = "displayName") var displayName: String?,
    @ColumnInfo(name = "image") var image: String?,
    @ColumnInfo(name = "lastTxnTimeStamp") var lastTxnTimeStamp: Long?,
    @ColumnInfo(name = "lastTransactionAmount") var lastTransactionAmount: Float?,
    @ColumnInfo(name = "transactionCategory") var transactionCategory : String?,
    @ColumnInfo(name = "vpa") var vpa: String?,
    @ColumnInfo(name = "bankingName") var bankingName: String?,
    @ColumnInfo(name = "mobileNo") var mobileNo: String?,
    @ColumnInfo(name = "custId") var custId: String?,
    @ColumnInfo(name = "nickName") var nickName: String?,
    @ColumnInfo(name = "accountRefId") var accountRefId: String?,
    @ColumnInfo(name = "accountNumber") var accountNumber: String?,
    @ColumnInfo(name = "maskedAccountNumber") var maskedAccountNumber: String?,
    @ColumnInfo(name = "ifsc") var ifsc: String?,
    @ColumnInfo(name = "bankName") var bankName: String?,
    @ColumnInfo(name = "state") var state: String?,
    @ColumnInfo(name = "appLocalBeneficiaryName") var appLocalBeneficiaryName: String?=null,
    @ColumnInfo(name = "appLocalBeneficiaryImageUrl") var appLocalBeneficiaryImageUrl: String?=null
)

and

@Entity(tableName = "configuration_table", indices = [androidx.room.Index(value = ["type"], unique = true)])
data class Configuration (
    @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") var id: Long = 0L,
    @ColumnInfo(name = "timestamp") var timestamp: Long,
    @ColumnInfo(name = "type") var type: Int?,
    @ColumnInfo(name = "fallbackEnabled") var fallbackEnabled: Boolean?,
    @ColumnInfo(name = "refreshNumber") var refreshNumber: Int
)

Body:
But Whenever I open the application, The migration code gets executed.

You don't say how you know this to be the case.

The code you have provided works as expected (as is shown below).

It is highly unlikely that the migration is actually being invoked and somehow reverting so that upon another run it is run again.

Often issues with the Migration not apparently running is due to a misunderstanding about exactly when the database migration occur, this being dependant upon an actual request for access to the database and the database being opened.

More specifically getting an instance of the Built database does not open the the database. Rather an attempt has to be made to access the database before it is opened.

e.g.

db = TheDatabase.getInstance(this) /* Does not open the database and therefore Migrate */
theDao = getTheDao() /* Only gets the Dao instance, does not open the database */

It is not until:-

var whatever = theDao.doSomething()

That the database will be opened.

This is perhaps what your issue is. If so just accessing the data via one of the functions in the class annotated with @Dao will open the dataabase. Alternately you could force an open e.g. db.openHelper.writableDatabase /* Force database open */

If not then I would suggest adding some debugging.

Note that the following is based upon and tested according to your code

As you are dropping the beneficial_meta_detail table the replacement beneficial_details table was used as the basis (i.e. the columns in the meta_details is irrelevant as they get dropped)

set a const for the Database version e.g.

  const val DATABASE_VERSION = 16
  @Database(entities = [BeneficiaryMetaDetailsModel::class,Configuration::class], exportSchema = false, version = DATABASE_VERSION)

note this has been taken from an example/test where version 16 is built to then migrate to 17

add the function (this on it's own does nothing):-

  @SuppressLint("Range")
  private fun showDBInfo(db: SupportSQLiteDatabase) {
      Log.d("DBVERSIONINFO","Actual Database Version is ${db.version}, Build Version is ${DATABASE_VERSION}")
      val csr = db.query("SELECT * FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' AND name NOT LIKE 'room_%' AND name NOT LIKE 'android_%'")
      while (csr.moveToNext()) {
          Log.d("DBSCHEMA",csr.getString(csr.getColumnIndex("sql")))
      }
  }

amend MIGRATION_16_17 to include a call to the new function
showDBInfo e.g.

  private val MIGRATION_16_17: Migration = object : Migration(16, 17) {
      override fun migrate(database: SupportSQLiteDatabase) {
          showDBInfo(database)
          database.execSQL("DROP TABLE IF EXISTS beneficiary_meta_details")
          database.execSQL("CREATE TABLE IF NOT EXISTS beneficiary_details (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, beneficiaryRefId TEXT , beneficiaryInstrumentRefId TEXT, status TEXT, instrumentType TEXT, displayName TEXT, image TEXT, lastTxnTimeStamp INTEGER, lastTransactionAmount REAL, transactionCategory TEXT, vpa TEXT, bankingName TEXT, mobileNo TEXT, custId TEXT, nickName TEXT, accountRefId TEXT, accountNumber TEXT, maskedAccountNumber TEXT, ifsc TEXT, bankName TEXT, state TEXT, appLocalBeneficiaryName TEXT, appLocalBeneficiaryImageUrl TEXT)")
          database.execSQL("ALTER TABLE configuration_table ADD COLUMN refreshNumber INTEGER NOT NULL DEFAULT 0")
      }
  }

optional, but suggested, add a CallBack that will invoke the showDBInfo when the respective function is invoked e.g. :-

  private object cb: Callback() {
      override fun onCreate(db: SupportSQLiteDatabase) {
          super.onCreate(db)
          Log.d("DBCALLBACK","onCreate CallBack Invoked")
          showDBInfo(db)
      }

      override fun onOpen(db: SupportSQLiteDatabase) {
          super.onOpen(db)
          Log.d("DBCALLBACK","onOpen CallBack Invoked")
          showDBInfo(db)
      }

      override fun onDestructiveMigration(db: SupportSQLiteDatabase) {
          super.onDestructiveMigration(db)
          Log.d("DBCALLBACK","onDestructive CallBack Invoked")
          showDBInfo(db)
      }
  }

amend the databaseBuilder to include the CallBack :-

              .addMigrations(MIGRATION_16_17)
              .addCallback(cb)
              .build()

Now if you run the App then the log would include :-

D/DBVERSIONINFO: Actual Database Version is 16, Build Version is 17
D/DBSCHEMA: CREATE TABLE `beneficiary_meta_details` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `beneficiaryRefId` TEXT, `beneficiaryInstrumentRefId` TEXT, `status` TEXT, `instrumentType` TEXT, `displayName` TEXT, `image` TEXT, `lastTxnTimeStamp` INTEGER, `lastTransactionAmount` REAL, `transactionCategory` TEXT, `vpa` TEXT, `bankingName` TEXT, `mobileNo` TEXT, `custId` TEXT, `nickName` TEXT, `accountRefId` TEXT, `accountNumber` TEXT, `maskedAccountNumber` TEXT, `ifsc` TEXT, `bankName` TEXT, `state` TEXT, `appLocalBeneficiaryName` TEXT, `appLocalBeneficiaryImageUrl` TEXT)
D/DBSCHEMA: CREATE TABLE `configuration_table` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `timestamp` INTEGER NOT NULL, `type` INTEGER, `fallbackEnabled` INTEGER)
D/DBSCHEMA: CREATE UNIQUE INDEX `index_configuration_table_type` ON `configuration_table` (`type`)
D/DBCALLBACK: onOpen CallBack Invoked
D/DBVERSIONINFO: Actual Database Version is 17, Build Version is 17
D/DBSCHEMA: CREATE TABLE `configuration_table` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `timestamp` INTEGER NOT NULL, `type` INTEGER, `fallbackEnabled` INTEGER, refreshNumber INTEGER NOT NULL DEFAULT 0)
D/DBSCHEMA: CREATE UNIQUE INDEX `index_configuration_table_type` ON `configuration_table` (`type`)
D/DBSCHEMA: CREATE TABLE beneficiary_details (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, beneficiaryRefId TEXT , beneficiaryInstrumentRefId TEXT, status TEXT, instrumentType TEXT, displayName TEXT, image TEXT, lastTxnTimeStamp INTEGER, lastTransactionAmount REAL, transactionCategory TEXT, vpa TEXT, bankingName TEXT, mobileNo TEXT, custId TEXT, nickName TEXT, accountRefId TEXT, accountNumber TEXT, maskedAccountNumber TEXT, ifsc TEXT, bankName TEXT, state TEXT, appLocalBeneficiaryName TEXT, appLocalBeneficiaryImageUrl TEXT)

Noting that when the Migration is called (first 4 lines) that the database version is 16 AND that when the onOpen callback is called that the database version is 17.

On a subsequent run (whilst still at version 17) you would get :-

D/DBCALLBACK: onOpen CallBack Invoked
D/DBVERSIONINFO: Actual Database Version is 17, Build Version is 17
D/DBSCHEMA: CREATE TABLE `configuration_table` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `timestamp` INTEGER NOT NULL, `type` INTEGER, `fallbackEnabled` INTEGER, refreshNumber INTEGER NOT NULL DEFAULT 0)
D/DBSCHEMA: CREATE UNIQUE INDEX `index_configuration_table_type` ON `configuration_table` (`type`)
D/DBSCHEMA: CREATE TABLE beneficiary_details (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, beneficiaryRefId TEXT , beneficiaryInstrumentRefId TEXT, status TEXT, instrumentType TEXT, displayName TEXT, image TEXT, lastTxnTimeStamp INTEGER, lastTransactionAmount REAL, transactionCategory TEXT, vpa TEXT, bankingName TEXT, mobileNo TEXT, custId TEXT, nickName TEXT, accountRefId TEXT, accountNumber TEXT, maskedAccountNumber TEXT, ifsc TEXT, bankName TEXT, state TEXT, appLocalBeneficiaryName TEXT, appLocalBeneficiaryImageUrl TEXT)

Prior to the migration you would get something like:-

D/DBVERSIONINFO: Actual Database Version is 16, Build Version is 16
D/DBSCHEMA: CREATE TABLE `beneficiary_meta_details` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `beneficiaryRefId` TEXT, `beneficiaryInstrumentRefId` TEXT, `status` TEXT, `instrumentType` TEXT, `displayName` TEXT, `image` TEXT, `lastTxnTimeStamp` INTEGER, `lastTransactionAmount` REAL, `transactionCategory` TEXT, `vpa` TEXT, `bankingName` TEXT, `mobileNo` TEXT, `custId` TEXT, `nickName` TEXT, `accountRefId` TEXT, `accountNumber` TEXT, `maskedAccountNumber` TEXT, `ifsc` TEXT, `bankName` TEXT, `state` TEXT, `appLocalBeneficiaryName` TEXT, `appLocalBeneficiaryImageUrl` TEXT)
D/DBSCHEMA: CREATE TABLE `configuration_table` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `timestamp` INTEGER NOT NULL, `type` INTEGER, `fallbackEnabled` INTEGER)
D/DBSCHEMA: CREATE UNIQUE INDEX `index_configuration_table_type` ON `configuration_table` (`type`)


问:
How to add non-overlapping polylines and text labels to 3D pie chart using d3.js?
I have commented the extra code on the already existing code written by DavidB and created this example to extract only one 3d pie chart. I would like to add polylines(non-overlapping) and text labels to the pie chart. Any suggestions are highly appreciated.
The expected results should look like this.

答:
How to prevent overlapping SVG text

Since the text is absolutely positioned, there isn't a great way of dealing with overlapping labels. SVGs have tspan elements which allow you to word-wrap, but that's about it.

In one of my data visualization projects, we had to deal with many labels that needed to resize when the graph would shrink. The way we handled this, was by calculating the available space. Then "simulating" the total size of a text label (at a given font size) using:

```<code>selection.node().getBBox().width
selection.node().getBBox().height
</code>```

If the dimensions of the new label would have overlapped, then you would try again with a smaller font size, until the dimensions of the label were smaller than the available space. It wasn't a great solution...

One issue with generating SVG elements (in order to measure their size) is that it triggers a re-rendering, which is expensive, considering the number of iterations.

You can improve the performance of this "brute force" approach, by using a <canvas> to calculate the size of a given label, without rendering anything:

```<code>  let canvasEl = document.createElement('canvas');
  let canvas = canvasEl.getContext('2d').font('12px sans-serif');
  const getWidthHeightOfLabel = (label) => {
    return {
      width: canvas.measureText(label).width,
      height: canvas.measureText(label).height
    };
  }
</code>```

In certain situations, we avoided SVG labels altogether and opted for plain old HTML text, which we would dynamically position ontop of the SVG.

Please let me know if my suggestion is unclear or if you need additional information! Thanks.

Body:
How to prevent overlapping SVG text

Since the text is absolutely positioned, there isn't a great way of dealing with overlapping labels. SVGs have tspan elements which allow you to word-wrap, but that's about it.

In one of my data visualization projects, we had to deal with many labels that needed to resize when the graph would shrink. The way we handled this, was by calculating the available space. Then "simulating" the total size of a text label (at a given font size) using:

selection.node().getBBox().width
selection.node().getBBox().height

If the dimensions of the new label would have overlapped, then you would try again with a smaller font size, until the dimensions of the label were smaller than the available space. It wasn't a great solution...

One issue with generating SVG elements (in order to measure their size) is that it triggers a re-rendering, which is expensive, considering the number of iterations.

You can improve the performance of this "brute force" approach, by using a <canvas> to calculate the size of a given label, without rendering anything:

  let canvasEl = document.createElement('canvas');
  let canvas = canvasEl.getContext('2d').font('12px sans-serif');
  const getWidthHeightOfLabel = (label) => {
    return {
      width: canvas.measureText(label).width,
      height: canvas.measureText(label).height
    };
  }

In certain situations, we avoided SVG labels altogether and opted for plain old HTML text, which we would dynamically position ontop of the SVG.

Please let me know if my suggestion is unclear or if you need additional information! Thanks.


问:
How does noise cancellation work in android?
I came across this relatively old post which describes how impressively Nexus One's noise cancellation works and I was wondering where can I find more information about its implementation in the OS software.

In particular:

How much of it is done using software and how much of it is done in
hardware?

Which modules in the Android source code are responsible for noise
cancellation?

Can I control its behavior via Android's API? (if so, which ones)

Does it also work with the microphone in the headset that comes with
Nexus One (4-pin 3.5mm jack) or does it work with the built-in
microphone only?

答:
About the Nexus One:

All hardware only configuration in software.

Sound drivers and sound system but only configuration.

No API possibly some prop configuration but I haven't been able to get that to work.

No, longer reply following.

I haven't found any indication that it uses the other microphone to do noise reduction for the headset. It wouldn’t make much sense either as it would most likely just try to cancel out with the noise from your pocket.

For most other android phones and for headset on the Nexus One I'm pretty sure that there is only some sort of filter to reduce input of sound that is not speech.

I have done some research on this that I tried to get some help with on the android porting and dev lists. There is a little further info:

http://groups.google.com/group/android-porting/browse_thread/thread/fe1b92065b75c6da?pli=1

With the reservation that I haven't looked at the latest and greatest versions of android.


问:
InfluxDb on Kubernetes with TLS ingress
I'm setting up influxdb2 on a kubernetes cluster using helm. I have enabled ingress and it works ok on port 80, but when I enable TLS and set the "secretName" to an existing TLS secret on kubernetes it times out on port 443. Is my assumption that "secretName" in the helm chart refers to a kubernetes cluster secret? Or is it a secret within influxdb itself? I can't find any useful documentation about this.</p>

答: It is a reference to a new Kubernetes secret that is going to be created corresponding to the tls cert. It does not have to reference an existing secret. If you run kubectl get secrets after a successful apply , you would see a secret something like <cert-name>-afr5d

Title: InfluxDb on Kubernetes with TLS ingress


问:
How to do mongodb $lookup, but keep other fields
Each document in my collection has a list of people and their status:

```<code>[
  {
    _id: 61c005f839d7239960dced76,
    people: [
      { id: 61c005b939d7239960dceca5, status: 'pending' },
      { id: 6204232e0aa660002e2e2617, status: 'active' }
    ]
  },
  // ...
]
</code>```

I do a lookup to replace the person ID with the actual data from another collection, with this lookup stage:

```<code>{
  $lookup: {
    from: 'user',
    let: { people: '$people' },
    pipeline: [
      { $match: { $expr: { $in: [ '$_id', '$$people.id' ] } } }
    ],
    as: 'people'
  }
}
</code>```

The result of this is something like this:

```<code>[
  {
    _id: 61c005f839d7239960dced76,
    people: [
      {
        _id: 61c005b939d7239960dceca5,
        lastName: 'Joe',
        firstName: 'Shmo',
      },
      {
        _id: 6204232e0aa660002e2e2617,
        firstName: 'John',
        lastName: 'Appleseed',
      }
    ]
  },
  // ...
]
</code>```

That's great, but I've lost the "status" field from the original documents.
Is there a way to keep the status field in the result? Or copy it in afterward?

答:
It would be better to move status to the people collection but if you want to keep it and you are fine with having following structure

```<code>"people": {
   "data": {
       "_id": 100,
       "lastName": "...",
       "firstName": "..."
   },
   "status": "active"
}
</code>```

I can suggest using $unwind

```<code>db.user.aggregate([
  {
    "$unwind": "$people"
  },
  {
    "$lookup": {
      "from": "people",
      "localField": "people.id",
      "foreignField": "_id",
      "as": "people.data"
    }
  },
  {
    "$project": { // this one is used to remove duplicate id, can be skipped
      "people.data": 1,
      "people.status": 1
    }
  },
  {
    "$unwind": "$people.data"
  },
]);
</code>```

Body:
Each document in my collection has a list of people and their status:

[
  {
    _id: 61c005f839d7239960dced76,
    people: [
      { id: 61c005b939d7239960dceca5, status: 'pending' },
      { id: 6204232e0aa660002e2e2617, status: 'active' }
    ]
  },
  // ...
]

I do a lookup to replace the person ID with the actual data from another collection, with this lookup stage:

{
  $lookup: {
    from: 'user',
    let: { people: '$people' },
    pipeline: [
      { $match: { $expr: { $in: [ '$_id', '$$people.id' ] } } }
    ],
    as: 'people'
  }
}

The result of this is something like this:

[
  {
    _id: 61c005f839d7239960dced76,
    people: [
      {
        _id: 61c005b939d7239960dceca5,
        lastName: 'Joe',
        firstName: 'Shmo',
      },
      {
        _id: 6204232e0aa660002e2e2617,
        firstName: 'John',
        lastName: 'Appleseed',
      }
    ]
  },
  // ...
]

That's great, but I've lost the "status" field from the original documents.
Is there a way to keep the status field in the result? Or copy it in afterward?

Body:
It would be better to move status to the people collection but if you want to keep it and you are fine with having following structure

"people": {
   "data": {
       "_id": 100,
       "lastName": "...",
       "firstName": "..."
   },
   "status": "active"
}

I can suggest using $unwind

db.user.aggregate([
  {
    "$unwind": "$people"
  },
  {
    "$lookup": {
      "from": "people",
      "localField": "people.id",
      "foreignField": "_id",
      "as": "people.data"
    }
  },
  {
    "$project": { // this one is used to remove duplicate id, can be skipped
      "people.data": 1,
      "people.status": 1
    }
  },
  {
    "$unwind": "$people.data"
  },
]);