问:
Obtain text from Excel Name Box Using C# and WinAppDriver
I have an automation project in C# that works with Microsoft Excel using WinAppDriver Release Candidate 1.2.

I have a case where I am attempting to get the number of rows that have been populated on a sheet with the code below.

```<code>    public string GetLastCellBelowStartRange(string sheetName, string startRange)
    {
        var sheet = FindSheet(sheetName);

        var nameBox = this.GetNameBox();
        nameBox.SendKeys($"{sheetName}!{startRange}{Keys.Enter}");

        this.excel.SendKeys($"{Keys.Control}{Keys.ArrowDown}");

        var endCellRange = nameBox.GetAttribute("LegacyIAccessible.Value");

        return endCellRange;
    }
</code>```

The code successfully goes to the last cell in the workbook and nameBox is known as well as the excel driver (i.e. this.excel).

I cannot determine how to get the contents of the current cell which Inspect shows in both Value.Value and LegacyIAccessible.Value.

Does anybody know of a way to do this?

答:
```<code>public string GetLastCellBelowStartRange(string sheetName, string startRange)

    {
        var sheet = FindSheet(sheetName);

        var nameBox = this.GetNameBox();
        nameBox.SendKeys($"{sheetName}!{startRange}{Keys.Enter}");

        this.excel.SendKeys($"{Keys.Control}{Keys.ArrowDown}");

        string endCellRange = nameBox.GetAttribute("Value.Value").ToString();

        return endCellRange;
    }
</code>```

Body:
I have an automation project in C# that works with Microsoft Excel using WinAppDriver Release Candidate 1.2.

I have a case where I am attempting to get the number of rows that have been populated on a sheet with the code below.

    public string GetLastCellBelowStartRange(string sheetName, string startRange)
    {
        var sheet = FindSheet(sheetName);

        var nameBox = this.GetNameBox();
        nameBox.SendKeys($"{sheetName}!{startRange}{Keys.Enter}");

        this.excel.SendKeys($"{Keys.Control}{Keys.ArrowDown}");

        var endCellRange = nameBox.GetAttribute("LegacyIAccessible.Value");

        return endCellRange;
    }

The code successfully goes to the last cell in the workbook and nameBox is known as well as the excel driver (i.e. this.excel).

I cannot determine how to get the contents of the current cell which Inspect shows in both Value.Value and LegacyIAccessible.Value.

Does anybody know of a way to do this?


来源: stackexchange

问:
c++ SIGTERM not returning after caught
I am trying to catch SIGTERM in my program, this is the problem.

My program starts and sets ups the listener for the signal SIGTERM. The program then enters a loop which continuously checks a socket file descriptor using select so that it is non blocking.When I send the program TERM through kill the program acknowledges that it receives the signal but that's it no return back to the loop I describe earlier.

The signal handler sets a public variable inside the class so the loop knows to exit. I should mention that in gdb this works but outside of gdb it does not.

Thanks in advance.

```<code>class A
{
    public:
        bool volatile stop;

    void loop();
    {
        while(!stop)
            {
                //check socket
            }
    }
};

A *aptr;

void sigterm_handler(int i)
{
    aptr->stop = true;
}

int main()
{
    A a;
    aptr = &a;
    struct sigaction sa;
    sa.sa_handler = &sigterm_handler;
    sigaction(SIGTERM, &sa, NULL);
    a.stop = false;
    a.loop();
}
</code>```

EDIT: sorry did not finish the code off properly.

答:
You might find that any signal (especially SIGTERM) will terminate any system calls you are doing inside the while loop. And by "system calls" I mean anything that reads from or does select or connect on a socket.

Check out this write up.

Also check the example test program.

ContentLicense: CC BY-SA 3.0

Title: c++ SIGTERM not returning after caught

Body:
I am trying to catch SIGTERM in my program, this is the problem.

My program starts and sets ups the listener for the signal SIGTERM. The program then enters a loop which continuously checks a socket file descriptor using select so that it is non blocking.When I send the program TERM through kill the program acknowledges that it receives the signal but that's it no return back to the loop I describe earlier.

The signal handler sets a public variable inside the class so the loop knows to exit. I should mention that in gdb this works but outside of gdb it does not.

Thanks in advance.

class A
{
    public:
        bool volatile stop;

    void loop();
    {
        while(!stop)
            {
                //check socket
            }
    }
};

A *aptr;

void sigterm_handler(int i)
{
    aptr->stop = true;
}

int main()
{
    A a;
    aptr = &a;
    struct sigaction sa;
    sa.sa_handler = &sigterm_handler;
    sigaction(SIGTERM, &sa, NULL);
    a.stop = false;
    a.loop();
}

EDIT: sorry did not finish the code off properly.


问:
How to preserve spaces in data(4spaces) for a column while writing to a csv file in pyspark
I have a an input csv file with one record. When I read the file in pyspark, the dataframe has three columns a, b, c respectively. a and c has data and b has data that is 4 spaces. While writing the file to csv, the 4 spaces data is lost and it is writing to the file as empty string.

Input file:

```<code>aaaa,    , bbbb
</code>```

Output file:

```<code>aaaa,"", bbbb
</code>```

How can I preserve the 4 spaces data as is.?

答:
When writing you need to set the options:</p>

```<code>df.write
  .option("ignoreLeadingWhiteSpace", "false")
  .option("ignoreTrailingWhiteSpace", "false")
  .csv(path)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a an input csv file with one record. When I read the file in pyspark, the dataframe has three columns a, b, c respectively. a and c has data and b has data that is 4 spaces. While writing the file to csv, the 4 spaces data is lost and it is writing to the file as empty string.

Input file:

aaaa,    , bbbb

Output file:

aaaa,"", bbbb

How can I preserve the 4 spaces data as is.?

Body:
When writing you need to set the options:

df.write
  .option("ignoreLeadingWhiteSpace", "false")
  .option("ignoreTrailingWhiteSpace", "false")
  .csv(path)


问:
Example: Sending sendgrid email programmatically with Volley
I'm trying to send emails programmatically from Android through sendgrid's v3 email API with normal Java. While sendgrid has a Java library, it is not specific for Android and more than 4y old.

Android suggests to use the Volley library for simple requests. However, I couldn't find any boilerplate code to start off with on how to send a simple request to sendgrid specifically. This would really make it much easier for me to get started - I haven't done any network requests from Android before.

This is the only related post I could find, but the suggested code example is terribly old, more than 6 years: SendGrid API for Android using Java

答:
There is a new Android SendGrid library utilising Sendgrid's v3 API.

The update library negates many of the issues when implementing the older sendgrid libraries into applications that target newer Android API version.

The library can be imported with jitpack

```<code>allprojects {
    repositories {
        ...
        maven { url "https://jitpack.io" }
    }
}

dependencies {
     implementation 'com.github.jakebreen:android-sendgrid:1.2.3'
}
</code>```

https://github.com/Jakebreen/android-sendgrid

Body:
There is a new Android SendGrid library utilising Sendgrid's v3 API.

The update library negates many of the issues when implementing the older sendgrid libraries into applications that target newer Android API version.

The library can be imported with jitpack

allprojects {
    repositories {
        ...
        maven { url "https://jitpack.io" }
    }
}

dependencies {
     implementation 'com.github.jakebreen:android-sendgrid:1.2.3'
}

https://github.com/Jakebreen/android-sendgrid


问:
Unable to fetch rows from PostGresSQL table
I'm trying to fetch data from a table in the PostGreSQL database. I'm able to query the results using PostGreSQL but when I try to do so with Python using psycopg2 module, it doesn't return anything. The curse object returned is of type "None" and is non iterable.

Here's my code:

```<code>import psycopg2 as p
con = p.connect(database="Scheduling", user="postgres", password="test", host="127.0.0.1",
port="5432")
cur = con.cursor()
df = cur.execute(''' SELECT * FROM  public."HOME" ''').fetchall()
print(type(df))
</code>```

Here's the error message:
Traceback (most recent call last):
  File "C:/Users/adi.jakka/PycharmProjects/Flask/TEST.PY", line 4, in
    df = cur.execute(''' SELECT * FROM  public."HOME" ''').fetchall()
AttributeError: 'NoneType' object has no attribute 'fetchall'

Process finished with exit code 1

答:
This should work:</p>

```<code>import psycopg2 as p
con = p.connect(database="Scheduling", user="postgres", password="test", host="127.0.0.1",
port="5432")
cur = con.cursor()
cur.execute(''' SELECT * FROM  public."HOME" ''')
df = cur.fetchall()
print(df)
</code>```

Body:
I'm trying to fetch data from a table in the PostGreSQL database. I'm able to query the results using PostGreSQL but when I try to do so with Python using psycopg2 module, it doesn't return anything. The curse object returned is of type "None" and is non iterable.

Here's my code:

import psycopg2 as p
con = p.connect(database="Scheduling", user="postgres", password="test", host="127.0.0.1",
port="5432")
cur = con.cursor()
df = cur.execute(''' SELECT * FROM  public."HOME" ''').fetchall()
print(type(df))

Here's the error message:
Traceback (most recent call last):
  File "C:/Users/adi.jakka/PycharmProjects/Flask/TEST.PY", line 4, in
    df = cur.execute(''' SELECT * FROM  public."HOME" ''').fetchall()
AttributeError: 'NoneType' object has no attribute 'fetchall'

Process finished with exit code 1

Body:
This should work:

import psycopg2 as p
con = p.connect(database="Scheduling", user="postgres", password="test", host="127.0.0.1",
port="5432")
cur = con.cursor()
cur.execute(''' SELECT * FROM  public."HOME" ''')
df = cur.fetchall()
print(df)


问:
DocuSign Integration Siebel IP14
Is it feasible to integrate DocuSign with On Premise CRM applications (Siebel Remote) or it only supports integration with Cloud Solutions?</p>

答: If docusign still provides a WSDL, you can still consume it in Siebel OnPremise , then create your custom WFs to have the integration running. Siebel now supports REST interfaces as well. If your siebel is remote,it cannot accept inbound webservice calls from docusign. So you will need to have one WF to submit docs for signature, and another one to query docusign for signed docs and update the links back in siebel.</p>

Title: DocuSign Integration Siebel IP14


问:
Why are my data elements being copied instead of moved?
I'm performing some tests about move semantics, and my class behavior seems weird for me.

Given the mock class VecOfInt:

```<code>class VecOfInt {
public:
    VecOfInt(size_t num) : m_size(num), m_data(new int[m_size]) {}
    ~VecOfInt() { delete[] m_data; }
    VecOfInt(VecOfInt const& other) : m_size(other.m_size),  m_data(new int[m_size]) {
        std::cout << "copy..." <<std::endl;
        std::copy(other.m_data, other.m_data + m_size, m_data);
    }
    VecOfInt(VecOfInt&& other) : m_size(other.m_size) {
        std::cout << "move..." << std::endl;
        m_data = other.m_data;
        other.m_data = nullptr;
    }
    VecOfInt& operator=(VecOfInt const& other) {
        std::cout << "copy assignment..." << std::endl;
        m_size = other.m_size;
        delete m_data;
        m_data = nullptr;
        m_data = new int[m_size];
        m_data = other.m_data;
        return *this;
    }
    VecOfInt& operator=(VecOfInt&& other) {
        std::cout << "move assignment..." << std::endl;
        m_size = other.m_size;
        m_data = other.m_data;
        other.m_data = nullptr;
        return *this;
    }
private:
    size_t m_size;
    int* m_data;
};
</code>```

OK CASE

When I insert a single value in-place:

```<code>int main() {
    std::vector<VecOfInt> v;
    v.push_back(10);
    return 0;
}
</code>```

Then it gives me the following output (what I think is fine):

move...

WEIRD CASE

When I insert three different values in-place:

```<code>int main() {
    std::vector<VecOfInt> v;
    v.push_back(10);
    v.push_back(20);
    v.push_back(30);
    return 0;
}
</code>```

Then the output calls the copy constructor 3 times:

move...
move...
copy...
move...
copy...
copy...

What I'm missing here?

答:
tl;dr: std::vector will copy instead of moving if your move constructor isn't  noexcept.

1. It's not about the members and the dynamic allocations

The issue is not with what you do with the fields of foo. So your source could be just:

```<code>class foo {
public:
    foo(size_t num) {}
    ~foo() = default
    foo(foo const& other)  {
        std::cout << "copy..." <<std::endl;
    }
    foo(foo&& other) {
        std::cout << "move..." << std::endl;
    }
    foo& operator=(foo const& other) {
        std::cout << "copy assignment..." << std::endl;
        return *this;
    }
    foo& operator=(foo&& other) {
        std::cout << "move assignment..." << std::endl;
        return *this;
    }
};
</code>```

and you still get the same behavior: try it.

2. The move's you do see are a distraction

Now, push_back() will first construct an element - foo in this case; then make sure there's space for it in the vector; then std::move() it into its place. So 3 of your moves are of that kind. Let's try using emplace_back() instead, which constructs the vector element in its place:

```<code>#include <vector>
#include <iostream>

struct foo { // same as above */ };

int main() {
    std::vector<foo> v;
    v.emplace_back(10);
    v.emplace_back(20);
    v.emplace_back(30);
    return 0;
}
</code>```

This gives us:

```<code>copy
copy
copy
</code>```

try it. So the moves were just a distraction really.

3. The copies are due to the vector resizing itself

Your std::vector gradually grows as you insert elements - necessitating either moves or copy constructions. See @NutCracker's post for details.

4. The real issue is exceptions

See this question:

How to enforce move semantics when a vector grows?

std::vector doesn't know it can safely move elements when resizing - where "safely" means "without exceptions", so it falls back to copying.

5. "But my copy ctor can throw an exception too!"

I guess the rationale is that if you get an exception while copying the smaller buffer - you still haven't touched it, so at least your original, non-resized vector is valid and can be used. If you started moving elements and got an exception - then you have no valid copy of the element anyway, not to speak of a valid smaller vector.

Body:
I'm performing some tests about move semantics, and my class behavior seems weird for me.

Given the mock class VecOfInt:

class VecOfInt {
public:
    VecOfInt(size_t num) : m_size(num), m_data(new int[m_size]) {}
    ~VecOfInt() { delete[] m_data; }
    VecOfInt(VecOfInt const& other) : m_size(other.m_size),  m_data(new int[m_size]) {
        std::cout << "copy..." <<std::endl;
        std::copy(other.m_data, other.m_data + m_size, m_data);
    }
    VecOfInt(VecOfInt&& other) : m_size(other.m_size) {
        std::cout << "move..." << std::endl;
        m_data = other.m_data;
        other.m_data = nullptr;
    }
    VecOfInt& operator=(VecOfInt const& other) {
        std::cout << "copy assignment..." << std::endl;
        m_size = other.m_size;
        delete m_data;
        m_data = nullptr;
        m_data = new int[m_size];
        m_data = other.m_data;
        return *this;
    }
    VecOfInt& operator=(VecOfInt&& other) {
        std::cout << "move assignment..." << std::endl;
        m_size = other.m_size;
        m_data = other.m_data;
        other.m_data = nullptr;
        return *this;
    }
private:
    size_t m_size;
    int* m_data;
};

OK CASE

When I insert a single value in-place:

int main() {
    std::vector<VecOfInt> v;
    v.push_back(10);
    return 0;
}

Then it gives me the following output (what I think is fine):

move...

WEIRD CASE

When I insert three different values in-place:

int main() {
    std::vector<VecOfInt> v;
    v.push_back(10);
    v.push_back(20);
    v.push_back(30);
    return 0;
}

Then the output calls the copy constructor 3 times:

move...
move...
copy...
move...
copy...
copy...

What I'm missing here?

Body:
tl;dr: std::vector will copy instead of moving if your move constructor isn't  noexcept.

1. It's not about the members and the dynamic allocations

The issue is not with what you do with the fields of foo. So your source could be just:

class foo {
public:
    foo(size_t num) {}
    ~foo() = default
    foo(foo const& other)  {
        std::cout << "copy..." <<std::endl;
    }
    foo(foo&& other) {
        std::cout << "move..." << std::endl;
    }
    foo& operator=(foo const& other) {
        std::cout << "copy assignment..." << std::endl;
        return *this;
    }
    foo& operator=(foo&& other) {
        std::cout << "move assignment..." << std::endl;
        return *this;
    }
};

and you still get the same behavior: try it.

2. The move's you do see are a distraction

Now, push_back() will first construct an element - foo in this case; then make sure there's space for it in the vector; then std::move() it into its place. So 3 of your moves are of that kind. Let's try using emplace_back() instead, which constructs the vector element in its place:

#include <vector>
#include <iostream>

struct foo { // same as above */ };

int main() {
    std::vector<foo> v;
    v.emplace_back(10);
    v.emplace_back(20);
    v.emplace_back(30);
    return 0;
}

This gives us:

copy
copy
copy

try it. So the moves were just a distraction really.

3. The copies are due to the vector resizing itself

Your std::vector gradually grows as you insert elements - necessitating either moves or copy constructions. See @NutCracker's post for details.

4. The real issue is exceptions

See this question:

How to enforce move semantics when a vector grows?

std::vector doesn't know it can safely move elements when resizing - where "safely" means "without exceptions", so it falls back to copying.

5. "But my copy ctor can throw an exception too!"

I guess the rationale is that if you get an exception while copying the smaller buffer - you still haven't touched it, so at least your original, non-resized vector is valid and can be used. If you started moving elements and got an exception - then you have no valid copy of the element anyway, not to speak of a valid smaller vector.


问:
In reveal.js, is there a standard way to make left-click advance to the next slide?
In Powerpoint, clicking the left mouse button advances to the next slide. In reveal.js, it is done using the keyboard. Is it possible to configure reveal.js to advance to the next slide also when clicking the mouse button?</p>

答:
It looks like you can add a click event to the entire slide and and check the button for the event.

```<code>window.addEventListener("mousedown", handleClick, false);
window.addEventListener("contextmenu", function(e) { e.preventDefault(); }, false);

function handleClick(e) {
    e.preventDefault();
    if(e.button === 0) Reveal.next();
    if(e.button === 2) Reveal.prev();
}
</code>```

If you're worried about links on the page not being clickable you can check the target of the event. If it's a link, don't proceed to the next slide.

This site could be useful and has a more in depth explanation. It's where the above code is from.

Body:
It looks like you can add a click event to the entire slide and and check the button for the event.

window.addEventListener("mousedown", handleClick, false);
window.addEventListener("contextmenu", function(e) { e.preventDefault(); }, false);

function handleClick(e) {
    e.preventDefault();
    if(e.button === 0) Reveal.next();
    if(e.button === 2) Reveal.prev();
}

If you're worried about links on the page not being clickable you can check the target of the event. If it's a link, don't proceed to the next slide.

This site could be useful and has a more in depth explanation. It's where the above code is from.


问:
CSS Grid - How to implement grid items, which don't "stretch" the grid row and have a scroll-able container
My challenge is:

I want to have a grid with a fixed amount of columns (which can later be adjusted via javascript) and a flexible amount of rows of equal height.

The number of rows are determined by the amount of grid items, which are UI cards.

These cards should fill out the entire height of their respective cell but MUST not increase the height of the row. So basically max-height = row-height assigned by grid

Then inside these cards we have the typical three parts: Header, Body and Footer. The body MUST be scroll-able, if more list items exists than the row-height allows.

I've tried to implement this on stackblitz

https://stackblitz.com/edit/angular-3gkmtm

What i don't understand is

Why the cards "stretches" the row when more items appear

How to achieve the scroll-able card body section without manually using a fixed height (like in the example i use max-height)

Why when there are more then 3 rows, it overflows

Please help!

Fixed Gird with scrollable cards

    <button (click)="onAdd()">Add</button>
    <button (click)="onRemove()">Remove</button>

Card #{{card}}

{{item}}

            Some Footer

```

```
article{
  display: flex;
  flex-direction: column;
  height: 100%;
}
.remaining-height{
  flex:1
}
.grid-container {
    display: grid;
    grid-gap: 0.5rem;
    height: 100%;
    grid-auto-rows: auto;
  grid-template-columns: repeat(5, auto);
}

.grid-item{
  display: flex;
  padding:24px;
}

.card{
  display: flex;
  flex-direction: column;
  width: 100%;
  height:100%;
  background:#ccc;
}
.card-body{
  .list-item{
    padding: 6px;
    background:#fcd3d3;
  }
   .list-item:nth-child(even){
  background:#efefef;
 }
}
.card-flexible-scroll{
  flex:1;
  overflow-y:auto;
  max-height: 300px; // <= no max height
}

Angular Controller to generate cards and list items

```js
export class AppComponent {
  name = "Angular";
  cards = new Array(8).fill(0).map((_,idx)=>idx+1);
  list = new Array(30).fill(0).map((_,idx)=>idx+1);

  onAdd() {
    this.cards.push(this.cards.length + 1);
  }

  onRemove() {
    this.cards.pop();
  }
}

</code>```

global style

html , body{
  height: 100vh;
  overflow: hidden;
}
```

答:
If I understand correctly what you are trying to do you want that the card body takes all the available row space between the header and footer and not force the card to be bigger than the row if it contains items.
It is possible to achieve that with adding another div with absolute positioning inside the card body div that is sized to the full body height then the items inside will overflow correctly.

Here is the changed template:

```<code><article>
  <section>
    <h2>Fixed Gird with scrollable cards</h2>
  </section>
  <section>
    <button (click)="onAdd()">Add</button>
    <button (click)="onRemove()">Remove</button>
  </section>
    <section class="remaining-height">
        <div class="grid-container">
      <div class="grid-item" *ngFor="let card of cards">
      <div class="card">
        <div class="card-header">Card #{{card}}</div>
        <div class="card-body">
          <div class="card-flexible-scroll">
            <div class="list-item" *ngFor="let item of list">{{item}}</div>
          </div>
        </div>
        <div class="card-footer">
            Some Footer
        </div>
      </div>
      </div>
        </div>
    </section>
</article>
</code>```

And the updated CSS:

```<code>.card-body{
  .list-item{
    padding: 6px;
    background:#fcd3d3;
  }
   .list-item:nth-child(even){
    background:#efefef;
  }
  position: relative;
  flex:1;
}
.card-flexible-scroll{
  position: absolute;
  width: 100%;
  height: 100%;
  max-height: 100%;
  overflow-y: auto;
}
</code>```

I created a fork of your StackBlitz where you can see how it works. If this is not what you look for please explain more.

Body:
My challenge is:

I want to have a grid with a fixed amount of columns (which can later be adjusted via javascript) and a flexible amount of rows of equal height.

The number of rows are determined by the amount of grid items, which are UI cards.

These cards should fill out the entire height of their respective cell but MUST not increase the height of the row. So basically max-height = row-height assigned by grid

Then inside these cards we have the typical three parts: Header, Body and Footer. The body MUST be scroll-able, if more list items exists than the row-height allows.

I've tried to implement this on stackblitz

https://stackblitz.com/edit/angular-3gkmtm

What i don't understand is

Why the cards "stretches" the row when more items appear

How to achieve the scroll-able card body section without manually using a fixed height (like in the example i use max-height)

Why when there are more then 3 rows, it overflows

Please help!

Fixed Gird with scrollable cards

    <button (click)="onAdd()">Add</button>
    <button (click)="onRemove()">Remove</button>

Card #{{card}}

{{item}}

            Some Footer

article{
  display: flex;
  flex-direction: column;
  height: 100%;
}
.remaining-height{
  flex:1
}
.grid-container {
    display: grid;
    grid-gap: 0.5rem;
    height: 100%;
    grid-auto-rows: auto;
  grid-template-columns: repeat(5, auto);
}

.grid-item{
  display: flex;
  padding:24px;
}

.card{
  display: flex;
  flex-direction: column;
  width: 100%;
  height:100%;
  background:#ccc;
}
.card-body{
  .list-item{
    padding: 6px;
    background:#fcd3d3;
  }
   .list-item:nth-child(even){
  background:#efefef;
 }
}
.card-flexible-scroll{
  flex:1;
  overflow-y:auto;
  max-height: 300px; // <= no max height
}

Angular Controller to generate cards and list items

```js
export class AppComponent {
  name = "Angular";
  cards = new Array(8).fill(0).map((_,idx)=>idx+1);
  list = new Array(30).fill(0).map((_,idx)=>idx+1);

  onAdd() {
    this.cards.push(this.cards.length + 1);
  }

  onRemove() {
    this.cards.pop();
  }
}

global style

html , body{
  height: 100vh;
  overflow: hidden;
}

Body:
If I understand correctly what you are trying to do you want that the card body takes all the available row space between the header and footer and not force the card to be bigger than the row if it contains items.
It is possible to achieve that with adding another div with absolute positioning inside the card body div that is sized to the full body height then the items inside will overflow correctly.

Here is the changed template:

<article>
  <section>
    <h2>Fixed Gird with scrollable cards</h2>
  </section>
  <section>
    <button (click)="onAdd()">Add</button>
    <button (click)="onRemove()">Remove</button>
  </section>
    <section class="remaining-height">
        <div class="grid-container">
      <div class="grid-item" *ngFor="let card of cards">
      <div class="card">
        <div class="card-header">Card #{{card}}</div>
        <div class="card-body">
          <div class="card-flexible-scroll">
            <div class="list-item" *ngFor="let item of list">{{item}}</div>
          </div>
        </div>
        <div class="card-footer">
            Some Footer
        </div>
      </div>
      </div>
        </div>
    </section>
</article>

And the updated CSS:

.card-body{
  .list-item{
    padding: 6px;
    background:#fcd3d3;
  }
   .list-item:nth-child(even){
    background:#efefef;
  }
  position: relative;
  flex:1;
}
.card-flexible-scroll{
  position: absolute;
  width: 100%;
  height: 100%;
  max-height: 100%;
  overflow-y: auto;
}

I created a fork of your StackBlitz where you can see how it works. If this is not what you look for please explain more.


问:
What could be causing a System.TypeLoadException in a Visual Studio Unit Test?
I've got a C# .NET class library MyClassLibrary that compiles fine. I'm trying to create a unit test project for it (using Visual Studio Unit Testing Framework, with Visual Studio 2010).  The class library does have big classes in it,  but whenever I run even the simplest test against the simplest class, I get the following exception:

Test method MyClassLibraryTest.MyClassLibraryTests.MySimpleClassTest threw exception:
  System.TypeLoadException: Could not load type 'MyClassLibrary.MySimpleClass' from assembly 'MyClassLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

All of the projects I'm dealing with are in the same solution, and all are compiled for .NET 4.0.  All of this is on a Windows 7 64-bit machine.

Here's the weird part: when I "Run" the test, I get the above error.  But when I "Debug" the test, it runs fine.  Why?

答: This happened to me as well. I had a nuget package installed on my domain project with version 1.5, but only had version 1.1 on my unit test project. I resolved the issue by updating the version on the unit test project to match the version on the domain project (the project being tested against).</p>


问:
destructor/callback in C for getting shared_ptr behavour
I'm writing a socket listener in C. Whenever it accepts, it creates a new thread (detached) recv the data and process.

But everytime, I need to manually call close(socket_descriptor). Had it been C++, I could have in someway choose to close it inside a destructor.

I was trying to find out something that provides me same behaviour.

Basically, I want to create something like shared_ptr in C.

Is there anyway in C where one can get a signal or a notification when an object is going out of scope?

答:
There is only one way you do it in "raw" C:

```<code>void abc_init (parameters);

void abc_cleanup (parameters);
</code>```

where all abc functions belong to the module abc, which consists of abc.h and abc.c. Allocation of objects can then either be handled by the caller to the abc module, or by the module itself:

```<code>// alternative 1, leave allocation to the caller

#include "abc.h"

int main()
{
  Abc_t x;

  abc_init(&x);

  ...

  abc_cleanup(&x);
}

// alternative 2, the module handles allocation

// abc.c

static Abc_t* x;

void abc_init (parameters)
{
  x = some_sort_of_allocation();
  set x based on parameters
}

...

void abc_cleanup (parameters)
{
  cleanup x
}
</code>```

Body:
There is only one way you do it in "raw" C:

void abc_init (parameters);

void abc_cleanup (parameters);

where all abc functions belong to the module abc, which consists of abc.h and abc.c. Allocation of objects can then either be handled by the caller to the abc module, or by the module itself:

// alternative 1, leave allocation to the caller

#include "abc.h"

int main()
{
  Abc_t x;

  abc_init(&x);

  ...

  abc_cleanup(&x);
}

// alternative 2, the module handles allocation

// abc.c

static Abc_t* x;

void abc_init (parameters)
{
  x = some_sort_of_allocation();
  set x based on parameters
}

...

void abc_cleanup (parameters)
{
  cleanup x
}


问:
How many results in these two programs and why?
```<code>//Number 1
    int x = 2;
    while (x < 200) {
        System.out.println(x + " ");
        x *= x;
</code>```

Output: 3

```<code>//Number 2
    String word = "a";
    while (word.length() < 10) {
        word = "b" + word + "b";
    }

    System.out.println(word);
</code>```

Output: bbbbbabbbbb

Number 1: Why is the output 3? I'm doing 2*2*2*2*2*2*2 = 128. Therefore, I think the answer should be 7?

Number 2: What happened there? And is the result "zero" or "infinity" or "unknown" or a number? Why?

答:
For Number#1 you are not multiplying by a factor of 2 but instead you are mutiplying x by the power of x

```<code>iteration #0 - x = 2
iteration #1 - x = 4
iteration #2 - x = 16
iteration #3 - x = 256
</code>```

change x *= x; to x *= 2;

For Number#2 just use a debugger to see what you are actually doing:

```<code>iteration #1 - word = "bab";
iteration #2 - word = "bbabb";
iteration #3 - word = "bbbabbb";
iteration #4 - word = "bbbbabbbb";
iteration #5 - word = "bbbbbabbbbb";
</code>```

word's length now is greater than 10, so it stops

Body:
//Number 1
    int x = 2;
    while (x < 200) {
        System.out.println(x + " ");
        x *= x;

Output: 3

//Number 2
    String word = "a";
    while (word.length() < 10) {
        word = "b" + word + "b";
    }

    System.out.println(word);

Output: bbbbbabbbbb

Number 1: Why is the output 3? I'm doing 2*2*2*2*2*2*2 = 128. Therefore, I think the answer should be 7?

Number 2: What happened there? And is the result "zero" or "infinity" or "unknown" or a number? Why?

Body:
For Number#1 you are not multiplying by a factor of 2 but instead you are mutiplying x by the power of x

iteration #0 - x = 2
iteration #1 - x = 4
iteration #2 - x = 16
iteration #3 - x = 256

change x *= x; to x *= 2;

For Number#2 just use a debugger to see what you are actually doing:

iteration #1 - word = "bab";
iteration #2 - word = "bbabb";
iteration #3 - word = "bbbabbb";
iteration #4 - word = "bbbbabbbb";
iteration #5 - word = "bbbbbabbbbb";

word's length now is greater than 10, so it stops


问:
An error occurred while installing mysql (2.9.1), and Bundler cannot continue
I am getting two errors with stack traces before this.  Those are:

```<code>/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:467:in `try_do':

 The compiler failed to generate an executable file. (RuntimeError).
 You have to install development tools first.

    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:546:in `block in try_link0'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/tmpdir.rb:93:in `mktmpdir'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:543:in `try_link0'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:570:in `try_link'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:782:in `try_func'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:1069:in `block in have_func'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:959:in `block in checking_for'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:361:in `block (2 levels) in postpone'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:331:in `open'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:361:in `block in postpone'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:331:in `open'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:357:in `postpone'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:958:in `checking_for'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:1068:in `have_func'
</code>```

and

```<code>/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/bin/ruby -I /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0 -r ./siteconf20200218-95654-zjppya.rb extconf.rb
checking for mysql_ssl_set()... *** extconf.rb failed ***

Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.
</code>```

This is the main error:  Or what bundler tells me:

```<code>An error occurred while installing mysql (2.9.1), and Bundler cannot continue.
Make sure that `gem install mysql -v '2.9.1' --source 'http://rubygems.org/'` succeeds before bundling.
</code>```

I have done a ton of research all over.

Solution 1 (Installing the correct developer tools):

Install xcode and xcode developer tools, run command:

```<code>xcode-select --install
</code>```

I get :

```<code>xcode-select: error: command line tools are already installed, use "Software Update" to install updates
</code>```

The project I'm working on requires ruby version 1.9.3.

I'm just really lost on what to do because I don't know what headers are and have entered a lot of commands through bundler and reseting xcode as well as deleting the tools and reinstalling.  When I use bundle clean --force I get:

```<code>Could not find mysql-2.9.1 in any of the sources
</code>```

What should I do?  I've looked at others that relate to this but the commands don't fix it and I don't anything about mysql 2.9.1 exactly.

EDIT: I should have posted this in since it requested me to make sure it worked:

```<code>mysql-2.9.1 git:(testupdategem) ✗ sudo gem install mysql -v '2.9.1'
Password:
Building native extensions.  This could take a while...
ERROR:  Error installing mysql:
    ERROR: Failed to build gem native extension.

        /Users/tblevins/.rvm/rubies/ruby-1.9.3-p545/bin/ruby extconf.rb
checking for mysql_ssl_set()... yes
checking for rb_str_set_len()... yes
checking for rb_thread_start_timer()... no
checking for mysql.h... yes
creating Makefile

make
compiling mysql.c
mysql.c:79:2: error: unknown type name 'my_bool'
        my_bool *is_null;
        ^
mysql.c:361:5: error: use of undeclared identifier 'my_bool'
    my_bool b;
    ^
mysql.c:391:10: error: use of undeclared identifier 'MYSQL_SET_CLIENT_IP'; did you mean 'MYSQL_SET_CHARSET_DIR'?
    case MYSQL_SET_CLIENT_IP:
         ^~~~~~~~~~~~~~~~~~~
         MYSQL_SET_CHARSET_DIR
/usr/local/Cellar/mysql/8.0.19/include/mysql/mysql.h:176:3: note: 'MYSQL_SET_CHARSET_DIR' declared here
  MYSQL_SET_CHARSET_DIR,
  ^
mysql.c:398:10: error: use of undeclared identifier 'MYSQL_SECURE_AUTH'; did you mean 'MYSQL_DEFAULT_AUTH'?
    case MYSQL_SECURE_AUTH:
         ^~~~~~~~~~~~~~~~~
         MYSQL_DEFAULT_AUTH
/usr/local/Cellar/mysql/8.0.19/include/mysql/mysql.h:187:3: note: 'MYSQL_DEFAULT_AUTH' declared here
  MYSQL_DEFAULT_AUTH,
  ^
mysql.c:400:6: error: use of undeclared identifier 'b'
            b = 1;
            ^
mysql.c:402:6: error: use of undeclared identifier 'b'
            b = 0;
            ^
mysql.c:403:14: error: use of undeclared identifier 'b'
        v = (char*)&b;
                    ^
mysql.c:391:10: error: duplicate case value 'MYSQL_SET_CHARSET_DIR'
    case MYSQL_SET_CLIENT_IP:
         ^
mysql.c:384:10: note: previous case defined here
    case MYSQL_SET_CHARSET_DIR:
         ^
mysql.c:588:9: warning: implicit conversion loses integer precision: 'uint64_t' (aka 'unsigned long long') to 'unsigned int' [-Wshorten-64-to-32]
    n = mysql_num_rows(res);
      ~ ^~~~~~~~~~~~~~~~~~~
mysql.c:633:9: warning: implicit conversion loses integer precision: 'uint64_t' (aka 'unsigned long long') to 'unsigned int' [-Wshorten-64-to-32]
    n = mysql_num_rows(res);
      ~ ^~~~~~~~~~~~~~~~~~~
mysql.c:878:5: error: use of undeclared identifier 'my_bool'
    my_bool true = 1;
    ^
mysql.c:883:61: error: cannot take the address of an rvalue of type 'int'
    if (mysql_stmt_attr_set(s, STMT_ATTR_UPDATE_MAX_LENGTH, &true))
                                                            ^~~~~
mysql.c:1068:73: warning: implicit conversion loses integer precision: 'unsigned long' to 'int' [-Wshorten-64-to-32]
                int len = strlen(fields[i].table)+strlen(fields[i].name)+1;
                    ~~~   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~
mysql.c:1661:9: warning: implicit conversion loses integer precision: 'unsigned long' to 'int' [-Wshorten-64-to-32]
    n = mysql_stmt_param_count(s->stmt);
      ~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
mysql.c:2049:52: error: use of undeclared identifier 'MYSQL_SECURE_AUTH'; did you mean 'MYSQL_DEFAULT_AUTH'?
    rb_define_const(cMysql, "SECURE_AUTH", INT2NUM(MYSQL_SECURE_AUTH));
                                                   ^~~~~~~~~~~~~~~~~
                                                   MYSQL_DEFAULT_AUTH
/Users/tblevins/.rvm/rubies/ruby-1.9.3-p545/include/ruby-1.9.1/ruby/ruby.h:973:35: note: expanded from macro 'INT2NUM'
# define INT2NUM(v) INT2FIX((int)(v))
                                  ^
/Users/tblevins/.rvm/rubies/ruby-1.9.3-p545/include/ruby-1.9.1/ruby/ruby.h:225:45: note: expanded from macro 'INT2FIX'
#define INT2FIX(i) ((VALUE)(((SIGNED_VALUE)(i))<<1 | FIXNUM_FLAG))
                                            ^
/usr/local/Cellar/mysql/8.0.19/include/mysql/mysql.h:187:3: note: 'MYSQL_DEFAULT_AUTH' declared here
  MYSQL_DEFAULT_AUTH,
  ^
mysql.c:2050:61: error: use of undeclared identifier 'MYSQL_OPT_GUESS_CONNECTION'; did you mean 'MYSQL_OPT_RECONNECT'?
    rb_define_const(cMysql, "OPT_GUESS_CONNECTION", INT2NUM(MYSQL_OPT_GUESS_CONNECTION));
                                                            ^~~~~~~~~~~~~~~~~~~~~~~~~~
                                                            MYSQL_OPT_RECONNECT
/Users/tblevins/.rvm/rubies/ruby-1.9.3-p545/include/ruby-1.9.1/ruby/ruby.h:973:35: note: expanded from macro 'INT2NUM'
# define INT2NUM(v) INT2FIX((int)(v))
                                  ^
/Users/tblevins/.rvm/rubies/ruby-1.9.3-p545/include/ruby-1.9.1/ruby/ruby.h:225:45: note: expanded from macro 'INT2FIX'
#define INT2FIX(i) ((VALUE)(((SIGNED_VALUE)(i))<<1 | FIXNUM_FLAG))
                                            ^
/usr/local/Cellar/mysql/8.0.19/include/mysql/mysql.h:185:3: note: 'MYSQL_OPT_RECONNECT' declared here
  MYSQL_OPT_RECONNECT,
  ^
mysql.c:2051:68: error: use of undeclared identifier 'MYSQL_OPT_USE_EMBEDDED_CONNECTION'
    rb_define_const(cMysql, "OPT_USE_EMBEDDED_CONNECTION", INT2NUM(MYSQL_OPT_USE_EMBEDDED_CONNECTION));
                                                                   ^
mysql.c:2052:66: error: use of undeclared identifier 'MYSQL_OPT_USE_REMOTE_CONNECTION'
    rb_define_const(cMysql, "OPT_USE_REMOTE_CONNECTION", INT2NUM(MYSQL_OPT_USE_REMOTE_CONNECTION));
                                                                 ^
mysql.c:2053:54: error: use of undeclared identifier 'MYSQL_SET_CLIENT_IP'; did you mean 'MYSQL_SET_CHARSET_DIR'?
    rb_define_const(cMysql, "SET_CLIENT_IP", INT2NUM(MYSQL_SET_CLIENT_IP));
                                                     ^~~~~~~~~~~~~~~~~~~
                                                     MYSQL_SET_CHARSET_DIR
/Users/tblevins/.rvm/rubies/ruby-1.9.3-p545/include/ruby-1.9.1/ruby/ruby.h:973:35: note: expanded from macro 'INT2NUM'
# define INT2NUM(v) INT2FIX((int)(v))
                                  ^
/Users/tblevins/.rvm/rubies/ruby-1.9.3-p545/include/ruby-1.9.1/ruby/ruby.h:225:45: note: expanded from macro 'INT2FIX'
#define INT2FIX(i) ((VALUE)(((SIGNED_VALUE)(i))<<1 | FIXNUM_FLAG))
                                            ^
/usr/local/Cellar/mysql/8.0.19/include/mysql/mysql.h:176:3: note: 'MYSQL_SET_CHARSET_DIR' declared here
  MYSQL_SET_CHARSET_DIR,
  ^
In file included from mysql.c:2287:
./error_const.h:2608:27: error: use of undeclared identifier 'ER_XPLUGIN_IP'
    rb_define_mysql_const(ER_XPLUGIN_IP);
                          ^
4 warnings and 16 errors generated.
make: *** [mysql.o] Error 1

Gem files will remain installed in /Users/tblevins/.rvm/rubies/ruby-1.9.3-p545/lib/ruby/gems/1.9.1/gems/mysql-2.9.1 for inspection.
Results logged to /Users/tblevins/.rvm/rubies/ruby-1.9.3-p545/lib/ruby/gems/1.9.1/gems/mysql-2.9.1/ext/mysql_api/gem_make.out
</code>```

Instructions:  Install RVM with \curl -sSL https://get.rvm.io | bash -s stable; restart your shell; install Ruby with rvm install 1.9.3.

```<code> Error running 'env GEM_HOME=/Users/tblevins/.rvm/gems/ruby-1.9.3-
 p551@global GEM_PATH= /Users/tblevins/.rvm/rubies/ruby-1.9.3-
 p551/bin/ruby -d /Users/tblevins/.rvm/src/rubygems-3.0.7/setup.rb --
 no-document', please read /Users/tblevins/.rvm/log/1582058102_ruby-
 1.9.3-p551/rubygems.install.log
</code>```

Says this is rubygems.install.log file:

```<code> Exception LoadError' at /Users/tblevins/.rvm/rubies/ruby-1.9.3-
 p551/lib/ruby/1.9.1/rubygems.rb:1264 - cannot load such file --
 rubygems/defaults/operating_system Exception LoadError' at /.
 Users/tblevins/.rvm/rubies/ruby-1.9.3-
 p551/lib/ruby/1.9.1/rubygems.rb:1273 - cannot load such file --
 rubygems/defaults/ruby. AND /Users/tblevins/.rvm/src/rubygems-
 3.0.7/lib/rubygems/core_ext/kernel_warn.rb:18: void value expression
 /Users/tblevins/.rvm/src/rubygems-
 3.0.7/lib/rubygems/core_ext/kernel_warn.rb:43: syntax error,
 unexpected '}', expecting keyword_end
</code>```

For future viewers:  I had to do:

```<code>gem install mysql -- --with-cflags=\"-I/usr/local/opt/openssl/include\" --with-ldflags=\"-L/usr/local/opt/openssl/lib\"
</code>```

I also had to clean up my brew and link git/node.  It was a lot of try and fail, I'm sorry I don't remember all of it.

Also I did:

```<code>bundle config --local build.mysql “--with-ldflags=-L/usr/local/opt/openssl/lib --with-cppflags=-I/usr/local/opt/openssl/include
</code>```

Bundler Version 1.16.4
Ruby version 1.9.3-p551

答:
Welcome to Stack Overflow.

Before I answer your question, I'd recommend anothermh's advice. I've been using rbenv because I work on a team of other people that do, but rvm is great. Don't use the system installation of Ruby. If you stick with Ruby development, you will be glad you did.

That said, setting up a non-system ruby environment won't be enough to fix this problem. First, the mysql gem version you're looking at is old, I think from 2013. It depends on a version of openssl that is no longer supported and has multiple security vulnerabilities. Please don't use it.

If you can, switch to using the mysql2 gem. For most Ruby and Rails projects, the mysql2 gem is pretty close to a drop-in replacement. If latest version of the mysql2 gem still doesn't compile on your machine, please see this previous question for answers on how to fix it.

It's possible that you're in the sad position where the mysql2 gem upgrade is not a option for you. If that's the case, you'll need to find a 1.0.x version of the OpenSSL library. Install the old version of OpenSSL on your machine to some path — let's call that path <openssl_path> for now. Then you can pass that path as an argument to bundler config or you can install the gem directly like so:

gem install mysql -v '2.9.1' -- --with-cflags=\"-I<openssl_path>/include\" --with-ldflags=\"-L<openssl_path>/lib\"

This still leaves you with the problem of finding OpenSSL 1.0, though. I know that several people previously posted ways to still install it via homebrew, though several of the repositories that hosted the required downloads for that to work are no longer active. Perhaps someone has posted another since last time I checked. I haven't been able to find one recently.

At worst, I suppose you could go to https://www.openssl.org/source/old/ and download an old version and compile it. Again, I recommend upgrading to the mysql2 gem instead as that might be a much easier path for you.

Body:
I am getting two errors with stack traces before this.  Those are:

/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:467:in `try_do':

 The compiler failed to generate an executable file. (RuntimeError).
 You have to install development tools first.

    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:546:in `block in try_link0'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/tmpdir.rb:93:in `mktmpdir'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:543:in `try_link0'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:570:in `try_link'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:782:in `try_func'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:1069:in `block in have_func'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:959:in `block in checking_for'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:361:in `block (2 levels) in postpone'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:331:in `open'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:361:in `block in postpone'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:331:in `open'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:357:in `postpone'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:958:in `checking_for'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/mkmf.rb:1068:in `have_func'

and

/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/bin/ruby -I /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0 -r ./siteconf20200218-95654-zjppya.rb extconf.rb
checking for mysql_ssl_set()... *** extconf.rb failed ***

Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

This is the main error:  Or what bundler tells me:

An error occurred while installing mysql (2.9.1), and Bundler cannot continue.
Make sure that `gem install mysql -v '2.9.1' --source 'http://rubygems.org/'` succeeds before bundling.

I have done a ton of research all over.

Solution 1 (Installing the correct developer tools):

Install xcode and xcode developer tools, run command:

xcode-select --install

I get :

xcode-select: error: command line tools are already installed, use "Software Update" to install updates

The project I'm working on requires ruby version 1.9.3.

I'm just really lost on what to do because I don't know what headers are and have entered a lot of commands through bundler and reseting xcode as well as deleting the tools and reinstalling.  When I use bundle clean --force I get:

Could not find mysql-2.9.1 in any of the sources

What should I do?  I've looked at others that relate to this but the commands don't fix it and I don't anything about mysql 2.9.1 exactly.

EDIT: I should have posted this in since it requested me to make sure it worked:

mysql-2.9.1 git:(testupdategem) ✗ sudo gem install mysql -v '2.9.1'
Password:
Building native extensions.  This could take a while...
ERROR:  Error installing mysql:
    ERROR: Failed to build gem native extension.

        /Users/tblevins/.rvm/rubies/ruby-1.9.3-p545/bin/ruby extconf.rb
checking for mysql_ssl_set()... yes
checking for rb_str_set_len()... yes
checking for rb_thread_start_timer()... no
checking for mysql.h... yes
creating Makefile

make
compiling mysql.c
mysql.c:79:2: error: unknown type name 'my_bool'
        my_bool *is_null;
        ^
mysql.c:361:5: error: use of undeclared identifier 'my_bool'
    my_bool b;
    ^
mysql.c:391:10: error: use of undeclared identifier 'MYSQL_SET_CLIENT_IP'; did you mean 'MYSQL_SET_CHARSET_DIR'?
    case MYSQL_SET_CLIENT_IP:
         ^~~~~~~~~~~~~~~~~~~
         MYSQL_SET_CHARSET_DIR
/usr/local/Cellar/mysql/8.0.19/include/mysql/mysql.h:176:3: note: 'MYSQL_SET_CHARSET_DIR' declared here
  MYSQL_SET_CHARSET_DIR,
  ^
mysql.c:398:10: error: use of undeclared identifier 'MYSQL_SECURE_AUTH'; did you mean 'MYSQL_DEFAULT_AUTH'?
    case MYSQL_SECURE_AUTH:
         ^~~~~~~~~~~~~~~~~
         MYSQL_DEFAULT_AUTH
/usr/local/Cellar/mysql/8.0.19/include/mysql/mysql.h:187:3: note: 'MYSQL_DEFAULT_AUTH' declared here
  MYSQL_DEFAULT_AUTH,
  ^
mysql.c:400:6: error: use of undeclared identifier 'b'
            b = 1;
            ^
mysql.c:402:6: error: use of undeclared identifier 'b'
            b = 0;
            ^
mysql.c:403:14: error: use of undeclared identifier 'b'
        v = (char*)&b;
                    ^
mysql.c:391:10: error: duplicate case value 'MYSQL_SET_CHARSET_DIR'
    case MYSQL_SET_CLIENT_IP:
         ^
mysql.c:384:10: note: previous case defined here
    case MYSQL_SET_CHARSET_DIR:
         ^
mysql.c:588:9: warning: implicit conversion loses integer precision: 'uint64_t' (aka 'unsigned long long') to 'unsigned int' [-Wshorten-64-to-32]
    n = mysql_num_rows(res);
      ~ ^~~~~~~~~~~~~~~~~~~
mysql.c:633:9: warning: implicit conversion loses integer precision: 'uint64_t' (aka 'unsigned long long') to 'unsigned int' [-Wshorten-64-to-32]
    n = mysql_num_rows(res);
      ~ ^~~~~~~~~~~~~~~~~~~
mysql.c:878:5: error: use of undeclared identifier 'my_bool'
    my_bool true = 1;
    ^
mysql.c:883:61: error: cannot take the address of an rvalue of type 'int'
    if (mysql_stmt_attr_set(s, STMT_ATTR_UPDATE_MAX_LENGTH, &true))
                                                            ^~~~~
mysql.c:1068:73: warning: implicit conversion loses integer precision: 'unsigned long' to 'int' [-Wshorten-64-to-32]
                int len = strlen(fields[i].table)+strlen(fields[i].name)+1;
                    ~~~   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~
mysql.c:1661:9: warning: implicit conversion loses integer precision: 'unsigned long' to 'int' [-Wshorten-64-to-32]
    n = mysql_stmt_param_count(s->stmt);
      ~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
mysql.c:2049:52: error: use of undeclared identifier 'MYSQL_SECURE_AUTH'; did you mean 'MYSQL_DEFAULT_AUTH'?
    rb_define_const(cMysql, "SECURE_AUTH", INT2NUM(MYSQL_SECURE_AUTH));
                                                   ^~~~~~~~~~~~~~~~~
                                                   MYSQL_DEFAULT_AUTH
/Users/tblevins/.rvm/rubies/ruby-1.9.3-p545/include/ruby-1.9.1/ruby/ruby.h:973:35: note: expanded from macro 'INT2NUM'
# define INT2NUM(v) INT2FIX((int)(v))
                                  ^
/Users/tblevins/.rvm/rubies/ruby-1.9.3-p545/include/ruby-1.9.1/ruby/ruby.h:225:45: note: expanded from macro 'INT2FIX'
#define INT2FIX(i) ((VALUE)(((SIGNED_VALUE)(i))<<1 | FIXNUM_FLAG))
                                            ^
/usr/local/Cellar/mysql/8.0.19/include/mysql/mysql.h:187:3: note: 'MYSQL_DEFAULT_AUTH' declared here
  MYSQL_DEFAULT_AUTH,
  ^
mysql.c:2050:61: error: use of undeclared identifier 'MYSQL_OPT_GUESS_CONNECTION'; did you mean 'MYSQL_OPT_RECONNECT'?
    rb_define_const(cMysql, "OPT_GUESS_CONNECTION", INT2NUM(MYSQL_OPT_GUESS_CONNECTION));
                                                            ^~~~~~~~~~~~~~~~~~~~~~~~~~
                                                            MYSQL_OPT_RECONNECT
/Users/tblevins/.rvm/rubies/ruby-1.9.3-p545/include/ruby-1.9.1/ruby/ruby.h:973:35: note: expanded from macro 'INT2NUM'
# define INT2NUM(v) INT2FIX((int)(v))
                                  ^
/Users/tblevins/.rvm/rubies/ruby-1.9.3-p545/include/ruby-1.9.1/ruby/ruby.h:225:45: note: expanded from macro 'INT2FIX'
#define INT2FIX(i) ((VALUE)(((SIGNED_VALUE)(i))<<1 | FIXNUM_FLAG))
                                            ^
/usr/local/Cellar/mysql/8.0.19/include/mysql/mysql.h:185:3: note: 'MYSQL_OPT_RECONNECT' declared here
  MYSQL_OPT_RECONNECT,
  ^
mysql.c:2051:68: error: use of undeclared identifier 'MYSQL_OPT_USE_EMBEDDED_CONNECTION'
    rb_define_const(cMysql, "OPT_USE_EMBEDDED_CONNECTION", INT2NUM(MYSQL_OPT_USE_EMBEDDED_CONNECTION));
                                                                   ^
mysql.c:2052:66: error: use of undeclared identifier 'MYSQL_OPT_USE_REMOTE_CONNECTION'
    rb_define_const(cMysql, "OPT_USE_REMOTE_CONNECTION", INT2NUM(MYSQL_OPT_USE_REMOTE_CONNECTION));
                                                                 ^
mysql.c:2053:54: error: use of undeclared identifier 'MYSQL_SET_CLIENT_IP'; did you mean 'MYSQL_SET_CHARSET_DIR'?
    rb_define_const(cMysql, "SET_CLIENT_IP", INT2NUM(MYSQL_SET_CLIENT_IP));
                                                     ^~~~~~~~~~~~~~~~~~~
                                                     MYSQL_SET_CHARSET_DIR
/Users/tblevins/.rvm/rubies/ruby-1.9.3-p545/include/ruby-1.9.1/ruby/ruby.h:973:35: note: expanded from macro 'INT2NUM'
# define INT2NUM(v) INT2FIX((int)(v))
                                  ^
/Users/tblevins/.rvm/rubies/ruby-1.9.3-p545/include/ruby-1.9.1/ruby/ruby.h:225:45: note: expanded from macro 'INT2FIX'
#define INT2FIX(i) ((VALUE)(((SIGNED_VALUE)(i))<<1 | FIXNUM_FLAG))
                                            ^
/usr/local/Cellar/mysql/8.0.19/include/mysql/mysql.h:176:3: note: 'MYSQL_SET_CHARSET_DIR' declared here
  MYSQL_SET_CHARSET_DIR,
  ^
In file included from mysql.c:2287:
./error_const.h:2608:27: error: use of undeclared identifier 'ER_XPLUGIN_IP'
    rb_define_mysql_const(ER_XPLUGIN_IP);
                          ^
4 warnings and 16 errors generated.
make: *** [mysql.o] Error 1

Gem files will remain installed in /Users/tblevins/.rvm/rubies/ruby-1.9.3-p545/lib/ruby/gems/1.9.1/gems/mysql-2.9.1 for inspection.
Results logged to /Users/tblevins/.rvm/rubies/ruby-1.9.3-p545/lib/ruby/gems/1.9.1/gems/mysql-2.9.1/ext/mysql_api/gem_make.out

Instructions:  Install RVM with \curl -sSL https://get.rvm.io | bash -s stable; restart your shell; install Ruby with rvm install 1.9.3.

 Error running 'env GEM_HOME=/Users/tblevins/.rvm/gems/ruby-1.9.3-
 p551@global GEM_PATH= /Users/tblevins/.rvm/rubies/ruby-1.9.3-
 p551/bin/ruby -d /Users/tblevins/.rvm/src/rubygems-3.0.7/setup.rb --
 no-document', please read /Users/tblevins/.rvm/log/1582058102_ruby-
 1.9.3-p551/rubygems.install.log

Says this is rubygems.install.log file:

 Exception LoadError' at /Users/tblevins/.rvm/rubies/ruby-1.9.3-
 p551/lib/ruby/1.9.1/rubygems.rb:1264 - cannot load such file --
 rubygems/defaults/operating_system Exception LoadError' at /.
 Users/tblevins/.rvm/rubies/ruby-1.9.3-
 p551/lib/ruby/1.9.1/rubygems.rb:1273 - cannot load such file --
 rubygems/defaults/ruby. AND /Users/tblevins/.rvm/src/rubygems-
 3.0.7/lib/rubygems/core_ext/kernel_warn.rb:18: void value expression
 /Users/tblevins/.rvm/src/rubygems-
 3.0.7/lib/rubygems/core_ext/kernel_warn.rb:43: syntax error,
 unexpected '}', expecting keyword_end

For future viewers:  I had to do:

gem install mysql -- --with-cflags=\"-I/usr/local/opt/openssl/include\" --with-ldflags=\"-L/usr/local/opt/openssl/lib\"

I also had to clean up my brew and link git/node.  It was a lot of try and fail, I'm sorry I don't remember all of it.

Also I did:

bundle config --local build.mysql “--with-ldflags=-L/usr/local/opt/openssl/lib --with-cppflags=-I/usr/local/opt/openssl/include

Bundler Version 1.16.4
Ruby version 1.9.3-p551


问:
JavaScript Object output
I am confused by JS object output.

First one:

var a = {}
console.log(a);```
</div>
</div>
</p>

<p>the output for the first one is <code>{}</code>.</p>

<p>Second one: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var a = {}
console.log(a + '123');</code>```

the output for the second one is [object Object]123

Third one:

var a = {
  toString: function() {
    return 'hello'
  }
}
console.log(a + '123');```

the output for the third one is hello123

I don't understand why the second one is [object Object]123 while the third one is hello123

答:
In the first example the value of the object at the moment you open the console is displayed

In the second example, the toString method inside the Object prototype is called on the object because of concatenation(+) with a string, which converts the object to string and concatenates the result to '123', note that when calling toString to an object it just gives you [object Object].

In the third example, toString is again called on the object due to concatenation(+) with a string. The object has, however, overridden the toString method definition in the prototype by a custom toString method
that returns 'hello', so it will concatenate 'hello' to '123'. Without the custom toString function definition it would have looked the function up in the prototype chain and would have printed [object Object] like the second example.

Title: JavaScript Object output

Body:
I am confused by JS object output.

First one:

var a = {}
console.log(a);

the output for the first one is {}.

Second one:

var a = {}
console.log(a + '123');

the output for the second one is [object Object]123

Third one:

var a = {
  toString: function() {
    return 'hello'
  }
}
console.log(a + '123');

the output for the third one is hello123

I don't understand why the second one is [object Object]123 while the third one is hello123


问:
vscode building and running from source hangs
I'm building vscode using the instructions here https://github.com/Microsoft/vscode/wiki/How-to-Contribute#build-and-run-from-source. When I get to the yarn run watch command, it hangs at Finished compilation with 0 errors after 54926 ms. What's going on?

nodejs: 8.9.4

yarn 1.3.2

npm 5.6.0

答:
I was running yarn run watch and encountered this problem.  I checked with du -s in the repo's folder a few times: no change, so I killed the command.

After killing yarn run watch I then ran yarn watch and once again it hung with the same error. I checked with du again. No change. I killed that command too.

I then ran

```<code>./scripts/code.sh
</code>```

And VS Code started fine. So in my experience, it is fine to kill the yarn command.

Body:
I was running yarn run watch and encountered this problem.  I checked with du -s in the repo's folder a few times: no change, so I killed the command.

After killing yarn run watch I then ran yarn watch and once again it hung with the same error. I checked with du again. No change. I killed that command too.

I then ran

./scripts/code.sh

And VS Code started fine. So in my experience, it is fine to kill the yarn command.


问:
Python: How do I get user input in the middle of a sentence (fill-in-the-blank style) using the input function?
I am trying to create a program that calculates sales tax. I first ask the user what was the total cost of their meal. I then ask them what is the sales tax of their area in the form of:

```<code>y = input('What is the sales tax of your area? ')
</code>```

I want to have a percent sign "%" at the end of the question so that the users sees the question as:

What is the sales tax of your area?_% , where the user can enter a number between the question and the percent sign (denoted by the underline).

This is what I have tried:

```<code>x = float(input("What is the cost of your meal? "))
y = input("What is the sales tax in your area? "+"%")

float(y)
y = y/100
cost = (x+(x*y))

print("The cost of your food is " + cost)
</code>```

答:
I recently had the same problem and I discovered a way to display what you are looking for! If you import getpass, then you should be able to use the code below to get the result you want.

import getpass

salesTax = getpass.getpass("The sales tax in my area is " + getpass.getpass() + " percent."```

If you run this, then the first thing displayed should be "Password:" If you enter 5, for example, then the output will be "The sales tax in my area is 5 percent." I am not the best at explaining things, so if you want to see it work in action, I made a repl that does this. https://repl.it/@ERokos_tcsyl/tester

Body:
I am trying to create a program that calculates sales tax. I first ask the user what was the total cost of their meal. I then ask them what is the sales tax of their area in the form of:

y = input('What is the sales tax of your area? ')

I want to have a percent sign "%" at the end of the question so that the users sees the question as:

What is the sales tax of your area?_% , where the user can enter a number between the question and the percent sign (denoted by the underline).

This is what I have tried:

x = float(input("What is the cost of your meal? "))
y = input("What is the sales tax in your area? "+"%")

float(y)
y = y/100
cost = (x+(x*y))

print("The cost of your food is " + cost)

Body:
I recently had the same problem and I discovered a way to display what you are looking for! If you import getpass, then you should be able to use the code below to get the result you want.

import getpass

salesTax = getpass.getpass("The sales tax in my area is " + getpass.getpass() + " percent."

If you run this, then the first thing displayed should be "Password:" If you enter 5, for example, then the output will be "The sales tax in my area is 5 percent." I am not the best at explaining things, so if you want to see it work in action, I made a repl that does this. https://repl.it/@ERokos_tcsyl/tester


答:
I suspect the part you're missing is that Objects already have a default toString() method, and its implementation returns [object Object]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString

Title: JavaScript Object output


问:
Making a random string based on random.random and a frequency table
I have this code:

```<code>base_distribution = {'A' : 0.345, 'C' : 0.158, 'G' : 0.059, 'T' : 0.437}

def get_random_uniform_sequence(alphabet, k):
    '''It return a random uniform distribuited sequence based in a alphabet
    with a k length (Bernoulli Distribuition)
    alphabet = list or array of strings representing a alphabet
    that the generated string is compsed.
    k = is a integer representing the length of the generated string.
    '''
    return ''.join(rd.choice(alphabet) for _ in range(k))

# choose a random symbol according to a given distribution
def weighted_choice(distribuition_probs):
    r = random.random()
    # make a choise based on r
    for k, v in distribuition_probs.items():
        if v >= r:
            print(k, v)

# generate a random sequence
def bernoulli_sequence(symbol_distribution, length):
    return ''.join(weighted_choice(symbol_distribution) for i in range(length))
</code>```

I need to make a random sequence based in a alphabet and k length based in certain probabilities(base_distributuion) using random.random. It is a task in a course I am doing, but I am not sure my weighted_choice functions is doing what is asked for.

I know that numpy random choices would be better, but the task not ask for that. What I am doing wrong?

I would appreciate any tip,

Thank you for your time and attention!

Paulo

PS- I hope I don't have offended anyone here because lately I have notice that I have being ignore around here! 8(

答:
I got this done.

```<code>def weighted_choice(prob_distribution):
    chars = list(prob_distribution.keys())
    probs = list(prob_distribution.values())
    cumdist = list(itertools.accumulate(probs))
    r = random.random() * cumdist[-1]
    return choices[bisect.bisect(cumdist, r)]
</code>```

Worked fine!

THank you

Body:
I have this code:

base_distribution = {'A' : 0.345, 'C' : 0.158, 'G' : 0.059, 'T' : 0.437}

def get_random_uniform_sequence(alphabet, k):
    '''It return a random uniform distribuited sequence based in a alphabet
    with a k length (Bernoulli Distribuition)
    alphabet = list or array of strings representing a alphabet
    that the generated string is compsed.
    k = is a integer representing the length of the generated string.
    '''
    return ''.join(rd.choice(alphabet) for _ in range(k))

# choose a random symbol according to a given distribution
def weighted_choice(distribuition_probs):
    r = random.random()
    # make a choise based on r
    for k, v in distribuition_probs.items():
        if v >= r:
            print(k, v)

# generate a random sequence
def bernoulli_sequence(symbol_distribution, length):
    return ''.join(weighted_choice(symbol_distribution) for i in range(length))

I need to make a random sequence based in a alphabet and k length based in certain probabilities(base_distributuion) using random.random. It is a task in a course I am doing, but I am not sure my weighted_choice functions is doing what is asked for.

I know that numpy random choices would be better, but the task not ask for that. What I am doing wrong?

I would appreciate any tip,

Thank you for your time and attention!

Paulo

PS- I hope I don't have offended anyone here because lately I have notice that I have being ignore around here! 8(

Body:
I got this done.

def weighted_choice(prob_distribution):
    chars = list(prob_distribution.keys())
    probs = list(prob_distribution.values())
    cumdist = list(itertools.accumulate(probs))
    r = random.random() * cumdist[-1]
    return choices[bisect.bisect(cumdist, r)]

Worked fine!

THank you


问:
How to change a range value in a for loop
I am getting an index error from trying to access values from a list after removing values whilst inside of a for loop. How do I change the range value in the for loop after each iteration? The function itself is to taken a list as an input and reverse the list in a new list but only by removing elements from one list into another so that the input list ends up empty.

```<code>def minsort(lst):
    new_lst = list()
    counter = 0
    while len(lst) > counter:
        smallest = lst[0]
        for i in range(1, len(lst)):
            if smallest > lst[i]:
                smallest = lst[i]
                new_lst.append(smallest)
                lst.remove(smallest)
                smallest = lst[0]
            else:
                new_lst.append(smallest)
                lst.remove(smallest)
    return new_lst

lst = [3,1,2]
print(minsort(lst))
</code>```

Error that I am getting:

```<code>    if smallest > lst[i]:
IndexError: list index out of range
</code>```

Edit: I am doing this without any inbuilt functions such as sorted()

答:
If you're trying to sort a list in ascending order you could use:

```<code>new_lst = sorted(lst)
</code>```

EDIT*

well, this seem to work without any built-in functions:

```<code>def minsort(lst):
    new_lst = []

    while lst:
        smallest = None
        for item in lst:
            if smallest == None:
                smallest = item
            elif item < smallest:
                smallest = item
        new_lst.append(smallest)
        lst.remove(smallest)
    return new_lst
</code>```

Body:
I am getting an index error from trying to access values from a list after removing values whilst inside of a for loop. How do I change the range value in the for loop after each iteration? The function itself is to taken a list as an input and reverse the list in a new list but only by removing elements from one list into another so that the input list ends up empty.

def minsort(lst):
    new_lst = list()
    counter = 0
    while len(lst) > counter:
        smallest = lst[0]
        for i in range(1, len(lst)):
            if smallest > lst[i]:
                smallest = lst[i]
                new_lst.append(smallest)
                lst.remove(smallest)
                smallest = lst[0]
            else:
                new_lst.append(smallest)
                lst.remove(smallest)
    return new_lst

lst = [3,1,2]
print(minsort(lst))

Error that I am getting:

    if smallest > lst[i]:
IndexError: list index out of range

Edit: I am doing this without any inbuilt functions such as sorted()

Body:
If you're trying to sort a list in ascending order you could use:

new_lst = sorted(lst)

EDIT*

well, this seem to work without any built-in functions:

def minsort(lst):
    new_lst = []

    while lst:
        smallest = None
        for item in lst:
            if smallest == None:
                smallest = item
            elif item < smallest:
                smallest = item
        new_lst.append(smallest)
        lst.remove(smallest)
    return new_lst


问:
Postgres text search with GIN index and sorted DESC on other column
I'm currently working on a search feature that ends up hitting the db with a LIKE query. It used to be of the form
WHERE some_id = blah AND some_timestamp > blah AND (field1 LIKE '%some_text%' OR field2 LIKE '%some_text%' OR ...) ORDER BY some_timestamp DESC.
This hasn't scaled well now that the table is in the size of tens of millions of rows, especially when it is filtered on a very old timestamp.

After some research it looked like a trigram index might be more performant for the text searching.
So I added a trigram index on all of the text fields concatenated and got good results initially. After varying the new query though I found a regression. An old index (btree on some_id and some_timestamp DESC) was not being hit anymore.
So the new text searching helps with certain text queries that used to be very slow, and other text queries that used to be very fast (a few ms) due to the btree index are now super slow (see below).

Is there a way to get the best of both worlds? Fast trigram text searching and fast btree indexing for the queries that need it?

Notes:

Postgres 11.6

I tried a btree_gin index to index the timestamp column as well but got pretty much the same performance.

I slightly modified my query (concatenated whitespace) to bypass the trigram index and verified the slow queries return to the btree index and <10ms execution times.

I tried some query rearrangement to try to get both indexes hit to no avail.

Table:

```<code>table1
---------------------------------
some_id        | bigint
field1         | text
field2         | text
field3         | text
field4         | text
field5         | text
field6         | bigint
some_timestamp | timestamp without time zone
</code>```

Trigram Index:

```<code>CREATE INDEX CONCURRENTLY IF NOT EXISTS trgm_idx ON table1 USING gin ((COALESCE(field1, '') || ' ' || COALESCE(field2, '') || COALESCE(field3, '') || ' ' || COALESCE(field4, '') || ' ' || COALESCE(field5, '') || ' ' || field6::text) gin_trgm_ops);
</code>```

Query:

```<code>SELECT *
FROM table1 i
WHERE i.some_id = 1
    AND (COALESCE(field1, '') || ' ' || COALESCE(field2, '') || COALESCE(field3, '') || ' ' || COALESCE(field4, '') || ' ' || COALESCE(field5, '') || ' ' || field6::text) ILIKE '%some_text%'
    AND i.some_timestamp > '2015-01-00 00:00:00.0'
ORDER BY some_timestamp DESC limit 20;
</code>```

Explain:

```<code> Limit  (cost=1043.06..1043.11 rows=20 width=446) (actual time=37240.094..37240.099 rows=20 loops=1)
   ->  Sort  (cost=1043.06..1043.15 rows=39 width=446) (actual time=37240.092..37240.095 rows=20 loops=1)
         Sort Key: some_timestamp
         Sort Method: top-N heapsort  Memory: 36kB
         ->  Bitmap Heap Scan on table1 i  (cost=345.01..1042.03 rows=39 width=446) (actual time=1413.415..37202.331 rows=83066 loops=1)
               Recheck Cond: ((((((((((COALESCE(field1, ''::text) || ' '::text) || COALESCE(field2, ''::text)) || COALESCE(field3, ''::text)) || ' '::text) || COALESCE(field4, ''::text)) || ' '::text) || COALESCE(field5, ''::text)) || ' '::text) || (field6)::text) ~~* '%some_text%'::text)
               Rows Removed by Index Recheck: 23
               Filter: ((some_timestamp > '2015-01-00 00:00:00'::timestamp without time zone) AND (some_id = 1))
               Rows Removed by Filter: 5746666
               Heap Blocks: exact=395922
               ->  Bitmap Index Scan on trgm_idx  (cost=0.00..345.00 rows=667 width=0) (actual time=1325.867..1325.867 rows=5833670 loops=1)
                     Index Cond: ((((((((((COALESCE(field1, ''::text) || ' '::text) || COALESCE(field2, ''::text)) || COALESCE(field3, ''::text)) || ' '::text) || COALESCE(field4, ''::text)) || ' '::text) || COALESCE(field5, ''::text)) || ' '::text) || (field6)::text) ~~* '%some_text%'::text)
 Planning Time: 0.252 ms
 Execution Time: 37243.205 ms
(14 rows)
</code>```

答:
I slightly modified my query (concatenated whitespace) to bypass the trigram index and verified the slow queries return to the btree index and <10ms execution times.

This is ugly, but it is almost certainly the solution.  Maybe we can fix things so that some (far) future version of PostgreSQL will not need such fixes, but that won't help you today.

```<code>Bitmap Index Scan on trgm_idx  (cost=0.00..345.00 rows=667 width=0) (actual time=1325.867..1325.867 rows=5833670 loops=1)
</code>```

This estimate is clearly deranged, and that is probably the source of the problem.  But trigram indexes and ILIKE queries are very sensitive to the actual query text.  Having only an (apparently) anonymized value '%some_text%' is not enough to take a deeper look.

And another approach would be use to use GiST rather than GIN.  GiST indexes can beneficially use multiple columns simultaneously.

```<code>CREATE INDEX CONCURRENTLY IF NOT EXISTS trgm_idx ON table1 USING gist
   (some_id, some_timestamp, (COALESCE(field1, '') || ' ' || COALESCE(field2, '') || COALESCE(field3, '') || ' ' || COALESCE(field4, '') || ' ' || COALESCE(field5, '') || ' ' || field6::text) gist_trgm_ops);
</code>```

You might want to include only one or the other of the first two columns, depending on how much selectivity each one provides.  You will probably need to do some experiments.

I don't like using GiST with pg_trgm, I find the performance (both in use and in building)  erratic.  But for a useful multi-column index in this fashion, you have little other choice.

Anyway, you have an index that works well already, it just isn't using it.  Making the GiST index might be "good enough" to lure the query away from GIN, but then it might just make some other query pick the wrong plan.

Another approach would be to use RUM indexes, this allows you to sort with data stored in the index, but I think you would have to write some code to make them support pg_trgm.

Body:
I'm currently working on a search feature that ends up hitting the db with a LIKE query. It used to be of the form
WHERE some_id = blah AND some_timestamp > blah AND (field1 LIKE '%some_text%' OR field2 LIKE '%some_text%' OR ...) ORDER BY some_timestamp DESC.
This hasn't scaled well now that the table is in the size of tens of millions of rows, especially when it is filtered on a very old timestamp.

After some research it looked like a trigram index might be more performant for the text searching.
So I added a trigram index on all of the text fields concatenated and got good results initially. After varying the new query though I found a regression. An old index (btree on some_id and some_timestamp DESC) was not being hit anymore.
So the new text searching helps with certain text queries that used to be very slow, and other text queries that used to be very fast (a few ms) due to the btree index are now super slow (see below).

Is there a way to get the best of both worlds? Fast trigram text searching and fast btree indexing for the queries that need it?

Notes:

Postgres 11.6

I tried a btree_gin index to index the timestamp column as well but got pretty much the same performance.

I slightly modified my query (concatenated whitespace) to bypass the trigram index and verified the slow queries return to the btree index and <10ms execution times.

I tried some query rearrangement to try to get both indexes hit to no avail.

Table:

table1
---------------------------------
some_id        | bigint
field1         | text
field2         | text
field3         | text
field4         | text
field5         | text
field6         | bigint
some_timestamp | timestamp without time zone

Trigram Index:

CREATE INDEX CONCURRENTLY IF NOT EXISTS trgm_idx ON table1 USING gin ((COALESCE(field1, '') || ' ' || COALESCE(field2, '') || COALESCE(field3, '') || ' ' || COALESCE(field4, '') || ' ' || COALESCE(field5, '') || ' ' || field6::text) gin_trgm_ops);

Query:

SELECT *
FROM table1 i
WHERE i.some_id = 1
    AND (COALESCE(field1, '') || ' ' || COALESCE(field2, '') || COALESCE(field3, '') || ' ' || COALESCE(field4, '') || ' ' || COALESCE(field5, '') || ' ' || field6::text) ILIKE '%some_text%'
    AND i.some_timestamp > '2015-01-00 00:00:00.0'
ORDER BY some_timestamp DESC limit 20;

Explain:

 Limit  (cost=1043.06..1043.11 rows=20 width=446) (actual time=37240.094..37240.099 rows=20 loops=1)
   ->  Sort  (cost=1043.06..1043.15 rows=39 width=446) (actual time=37240.092..37240.095 rows=20 loops=1)
         Sort Key: some_timestamp
         Sort Method: top-N heapsort  Memory: 36kB
         ->  Bitmap Heap Scan on table1 i  (cost=345.01..1042.03 rows=39 width=446) (actual time=1413.415..37202.331 rows=83066 loops=1)
               Recheck Cond: ((((((((((COALESCE(field1, ''::text) || ' '::text) || COALESCE(field2, ''::text)) || COALESCE(field3, ''::text)) || ' '::text) || COALESCE(field4, ''::text)) || ' '::text) || COALESCE(field5, ''::text)) || ' '::text) || (field6)::text) ~~* '%some_text%'::text)
               Rows Removed by Index Recheck: 23
               Filter: ((some_timestamp > '2015-01-00 00:00:00'::timestamp without time zone) AND (some_id = 1))
               Rows Removed by Filter: 5746666
               Heap Blocks: exact=395922
               ->  Bitmap Index Scan on trgm_idx  (cost=0.00..345.00 rows=667 width=0) (actual time=1325.867..1325.867 rows=5833670 loops=1)
                     Index Cond: ((((((((((COALESCE(field1, ''::text) || ' '::text) || COALESCE(field2, ''::text)) || COALESCE(field3, ''::text)) || ' '::text) || COALESCE(field4, ''::text)) || ' '::text) || COALESCE(field5, ''::text)) || ' '::text) || (field6)::text) ~~* '%some_text%'::text)
 Planning Time: 0.252 ms
 Execution Time: 37243.205 ms
(14 rows)

Body:
I slightly modified my query (concatenated whitespace) to bypass the trigram index and verified the slow queries return to the btree index and <10ms execution times.

This is ugly, but it is almost certainly the solution.  Maybe we can fix things so that some (far) future version of PostgreSQL will not need such fixes, but that won't help you today.

Bitmap Index Scan on trgm_idx  (cost=0.00..345.00 rows=667 width=0) (actual time=1325.867..1325.867 rows=5833670 loops=1)

This estimate is clearly deranged, and that is probably the source of the problem.  But trigram indexes and ILIKE queries are very sensitive to the actual query text.  Having only an (apparently) anonymized value '%some_text%' is not enough to take a deeper look.

And another approach would be use to use GiST rather than GIN.  GiST indexes can beneficially use multiple columns simultaneously.

CREATE INDEX CONCURRENTLY IF NOT EXISTS trgm_idx ON table1 USING gist
   (some_id, some_timestamp, (COALESCE(field1, '') || ' ' || COALESCE(field2, '') || COALESCE(field3, '') || ' ' || COALESCE(field4, '') || ' ' || COALESCE(field5, '') || ' ' || field6::text) gist_trgm_ops);

You might want to include only one or the other of the first two columns, depending on how much selectivity each one provides.  You will probably need to do some experiments.

I don't like using GiST with pg_trgm, I find the performance (both in use and in building)  erratic.  But for a useful multi-column index in this fashion, you have little other choice.

Anyway, you have an index that works well already, it just isn't using it.  Making the GiST index might be "good enough" to lure the query away from GIN, but then it might just make some other query pick the wrong plan.

Another approach would be to use RUM indexes, this allows you to sort with data stored in the index, but I think you would have to write some code to make them support pg_trgm.


问:
C program terminates without any error after execution of scanf() and taking the input from user
Program terminates automatically after the execution of scanf() and taking input from the user.

This is a program to print perfect number in a given range

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

void main() {
    int i, n, j, sum;
    printf("enter the number \n ");
    scanf("%d", &n);
    for (i = 1; i <= n; i++) {
        sum = 0;
        for (j = 1; j <= i; j++) {
            if (n % j == 0) {
                sum += j;
            }
        }
        if (sum == n) {
            printf("%d", i);
        }
    }
}
</code>```

execution image

答:
Performance tip - Perfect numbers

Presently code is O(n*n), which can take a long time for large n.

A significant speed up is to only iterate division attempts up to the sqrt(i), thus O(n*sqrt(n))

```<code>    sum = 1;
    // for (j = 1; j < i; j++) {
    for (j = 2; j < i/j; j++) {
      if (i % j == 0) {
        sum += j;   // Add both factors: j, i/j
        sum += i/j;
      }
    }
    if (j == i/j) {
      if (i % j == 0) { // perfect square?
        sum += j;  // Add 1 factor
      }
    }
    if (sum == i && i > 1) {
      printf("%d\n", i);
    }
</code>```

Even faster methods exist.  More info Perfect number

Body:
Program terminates automatically after the execution of scanf() and taking input from the user.

This is a program to print perfect number in a given range

#include <stdio.h>

void main() {
    int i, n, j, sum;
    printf("enter the number \n ");
    scanf("%d", &n);
    for (i = 1; i <= n; i++) {
        sum = 0;
        for (j = 1; j <= i; j++) {
            if (n % j == 0) {
                sum += j;
            }
        }
        if (sum == n) {
            printf("%d", i);
        }
    }
}

execution image

Body:
Performance tip - Perfect numbers

Presently code is O(n*n), which can take a long time for large n.

A significant speed up is to only iterate division attempts up to the sqrt(i), thus O(n*sqrt(n))

    sum = 1;
    // for (j = 1; j < i; j++) {
    for (j = 2; j < i/j; j++) {
      if (i % j == 0) {
        sum += j;   // Add both factors: j, i/j
        sum += i/j;
      }
    }
    if (j == i/j) {
      if (i % j == 0) { // perfect square?
        sum += j;  // Add 1 factor
      }
    }
    if (sum == i && i > 1) {
      printf("%d\n", i);
    }

Even faster methods exist.  More info Perfect number


问:
Is there a way to intercept setters and getters in C#?
In both Ruby and PHP (and I guess other languages as well) there are some utility methods that are called whenever a property is set. ( *instance_variable_set* for Ruby, *__set* for PHP).

So, let's say I have a C# class like this:

```<code>public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
</code>```

Now, let's say that if any property setter from the Person class is called, I want to call another method first, and then continue with the default behaviour of the setter, and the same applies for the property setters.

Is this possible?

Edit:
I want to do this without defining a backing field.

答:
I know this has been properly answered but I'll include an example to show you the syntax to achieve what you want:</p>

```<code>public class Person
{
    private
    public string FirstName
    {
        get
        {
            return _firstName;
        }
        set
        {
            // see how we can call a method below? or any code for that matter..
            _firstName = SanitizeName(value);
        }
    }
}
</code>```

Body:
In both Ruby and PHP (and I guess other languages as well) there are some utility methods that are called whenever a property is set. ( *instance_variable_set* for Ruby, *__set* for PHP).

So, let's say I have a C# class like this:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Now, let's say that if any property setter from the Person class is called, I want to call another method first, and then continue with the default behaviour of the setter, and the same applies for the property setters.

Is this possible?

Edit:
I want to do this without defining a backing field.

Body:
I know this has been properly answered but I'll include an example to show you the syntax to achieve what you want:

public class Person
{
    private
    public string FirstName
    {
        get
        {
            return _firstName;
        }
        set
        {
            // see how we can call a method below? or any code for that matter..
            _firstName = SanitizeName(value);
        }
    }
}


问:
Casting float to int doesn't work properly in C
I tried to solve a task on codewars and happened something strange, in one case casting worked as usual and in the second o got strange behavior. Here is the code:

```<code>#include <stdio.h>
#include <string.h>
#include <math.h>
int digital_root(int n) {
  char tmp[30];
  char *ptr;
  while(n > 9){
    sprintf(tmp, "%d", n);
    int len = strlen(tmp);
    float n_tmp = n / (pow(10, len));
    n = 0;

    for(int i = 1; i <=len; i++){
      float t = n_tmp * (pow(10, i));
      printf(" vars = [%f , %d] ", t, (int)t); //this line
      n += (int) t;
      n_tmp -= (int)t/pow(10,i);

    }

  }

  return n;
}

int main()
{
    digital_root(16);

    return 0;
}

</code>```

And the line printf(" vars = [%f , %d] ", t, (int)t); outputs: vars = [1.600000 , 1]  vars = [6.000000 , 5], what is so strange. Can someone explain this behavior?

答:
Every casting float to int is a rounding, so every time you do it, stop for a second and think: what kind of rounding do I need this time? Dropping the fractional part? floor()? ceil()? Or rounding positive float towards nearest int? If 5.999999999999 should be 6, use (int)(t+.5), not (int)t.

Or you can mimic the printf behavior and round only the smallest float fraction, which can vary (depending on the biggest value you use). (int)(t+.000001) will round both 1.9 to 1 (as it probably should), and 3.9999999999 to 4 (because it is 4 with some tiny number representation errors).

You should however know the size of a fraction which can be an actual, meaningful part of your data. Everything smaller than this fraction must be rounded. It can be either .00000001 or .5, that depends on your needs and the algorithm itself.

Body:
I tried to solve a task on codewars and happened something strange, in one case casting worked as usual and in the second o got strange behavior. Here is the code:

#include <stdio.h>
#include <string.h>
#include <math.h>
int digital_root(int n) {
  char tmp[30];
  char *ptr;
  while(n > 9){
    sprintf(tmp, "%d", n);
    int len = strlen(tmp);
    float n_tmp = n / (pow(10, len));
    n = 0;

    for(int i = 1; i <=len; i++){
      float t = n_tmp * (pow(10, i));
      printf(" vars = [%f , %d] ", t, (int)t); //this line
      n += (int) t;
      n_tmp -= (int)t/pow(10,i);

    }

  }

  return n;
}

int main()
{
    digital_root(16);

    return 0;
}

And the line printf(" vars = [%f , %d] ", t, (int)t); outputs: vars = [1.600000 , 1]  vars = [6.000000 , 5], what is so strange. Can someone explain this behavior?


问:
How do I bundle the C source in a Raku distribution that uses NativeCall?
I'm writing Raku bindings to a C library, but rather than require the users of the Raku code to install the C library on their own, I'd like to bundle the C code as part of the distribution (it's not such a widely distributed library).

I've read about a distribution's %?RESOURCES, and that seems like it would be useful. But I'm hazy on the specifics of how to apply it for this.

Can I bundle the C source code in the distribution, and specify some way for it to get compiled as part of the installation (eg. with zef)? Or would I need to bundle precompiled versions of the library, and get the code to choose the right one depending on the platform?

Or is this simply impossible, and I should just give users instructions on how to install the library separately?

答:
It's possible, and there exists a module LibraryMake to ease the process.

For an example of a module using it, see Digest::SHA1::Native.


问:
Converting code from functional React hooks to class components
I'm currently trying to convert some hooks over to being inside class components in React. I'm attempting to recreate the code that allows for session storage so that the app doesn't need to fetch from the API so much. Here is the code:

```<code>useEffect(() => {
        if(sessionStorage.homeState){
            // console.log("Getting from session storage");
            setState(JSON.parse(sessionStorage.homeState));
            setLoading(false);
        }else{
            // console.log("Getting from API");
            fetchMovies(POPULAR_BASE_URL);
        }
    }, [])

    useEffect(() => {
        if(!searchTerm){
            // console.log("Writing to session storage");
            sessionStorage.setItem('homeState', JSON.stringify(state));
        }
    }, [searchTerm, state])
</code>```

These are two useEffect hooks so it makes sense to me to go with a regular componentDidMount to get from the session storage. The only thing that I can't seem to figure out is how to recreate the second useEffect that sets session storage and fires only when searchTerm or state changes. searchTerm and state are simply two properties of the state. How could I implement this since componentDidMount only fires once when the app first mounts? Thanks

答:
The only thing that I can't seem to figure out is how to recreate the second useEffect that sets session storage and fires only when searchTerm or state changes. searchTerm and state are simply two properties of the state.

componentDidMount() is only one of methods used by the class components you can recreate the second hook with componentWillUpdate() or shouldComponentUpdate().

For example:

```<code>componentWillUpdate(nextProps, nextState) {
  if (this.props.searchTerm !== prevProps.searchTerm) {
    ...
  }
}
</code>```

You can check what lifecycle methods are available in class components by Googling "class component lifecycle".

But as you can read in the comment to your questions Hooks can offer you more than class components, and recreating them is not trivial. It is easier to move from the class component to the Hooks.

Body:
I'm currently trying to convert some hooks over to being inside class components in React. I'm attempting to recreate the code that allows for session storage so that the app doesn't need to fetch from the API so much. Here is the code:

useEffect(() => {
        if(sessionStorage.homeState){
            // console.log("Getting from session storage");
            setState(JSON.parse(sessionStorage.homeState));
            setLoading(false);
        }else{
            // console.log("Getting from API");
            fetchMovies(POPULAR_BASE_URL);
        }
    }, [])

    useEffect(() => {
        if(!searchTerm){
            // console.log("Writing to session storage");
            sessionStorage.setItem('homeState', JSON.stringify(state));
        }
    }, [searchTerm, state])

These are two useEffect hooks so it makes sense to me to go with a regular componentDidMount to get from the session storage. The only thing that I can't seem to figure out is how to recreate the second useEffect that sets session storage and fires only when searchTerm or state changes. searchTerm and state are simply two properties of the state. How could I implement this since componentDidMount only fires once when the app first mounts? Thanks

Body:
The only thing that I can't seem to figure out is how to recreate the second useEffect that sets session storage and fires only when searchTerm or state changes. searchTerm and state are simply two properties of the state.

componentDidMount() is only one of methods used by the class components you can recreate the second hook with componentWillUpdate() or shouldComponentUpdate().

For example:

componentWillUpdate(nextProps, nextState) {
  if (this.props.searchTerm !== prevProps.searchTerm) {
    ...
  }
}

You can check what lifecycle methods are available in class components by Googling "class component lifecycle".

But as you can read in the comment to your questions Hooks can offer you more than class components, and recreating them is not trivial. It is easier to move from the class component to the Hooks.


问:
How would I process loop index separately
would like to process different index ranges differently. </p>

```<code>for i in range(0,10):
        [0,3]:
           print('hello')
        [3,5]:
          print('hi')
        [5,10]:
          print('end')```
</code>```

答:
What you need is conditional expressions, read more about it here.

```<code>for i in range(0,10):
        if i<3:
           print('hello')
        elif i >=3 and i<=5:
          print('hi')
        else:
          print('end')
</code>```

Edit:

This should achieve what you want.

```<code>def loop_ranges(lb,ub):
    for i in range(lb,ub):
        if i<3:
           print('hello')
        elif i >=3 and i<=5:
          print('hi')
        else:
          print('end')

for i in range(len(list)-2):
   loop_ranges(list[i],list[i+1])

</code>```

Body:
would like to process different index ranges differently.

for i in range(0,10):
        [0,3]:
           print('hello')
        [3,5]:
          print('hi')
        [5,10]:
          print('end')```

Body:
What you need is conditional expressions, read more about it here.

for i in range(0,10):
        if i<3:
           print('hello')
        elif i >=3 and i<=5:
          print('hi')
        else:
          print('end')

Edit:

This should achieve what you want.

def loop_ranges(lb,ub):
    for i in range(lb,ub):
        if i<3:
           print('hello')
        elif i >=3 and i<=5:
          print('hi')
        else:
          print('end')

for i in range(len(list)-2):
   loop_ranges(list[i],list[i+1])