问:
how to get specific row text haviing same class in a table column when clicking on a button in one row
I want to get the date of the same row when I click on Hold Button in the same row. I have tried more searching on Google but I couldn't find any helpful query to fix this issue.

I am new in ajax that's why I need help from this community. Please help me fix it.

Here is what I am trying:

HTML:

```<code><table class="table table-hover table-bordered">
    <thead>
        <tr>
            <th>User ID</th>
            <th>Date</th>
            <th>Name</th>
            <th>User Status</th>
            <th colspan="4" class="text-center">Action</th>
        </tr>
    </thead>
    <tbody id="load-table">
        <!-- dummy data for StackOverFlow to show you data (By the way this data is dynamic coming from a database. I have placed dummy data only to show the output. So you can ignore data in #load-table)-->
        <tr>
            <td>1</td>
            <td class="statsdate">2022-02-12</td>
            <td>Jhon</td>
            <td>Active</td>
            <td><Button class="hold" data-holdid="holdid">Hold</Button></td>
        </tr>
        <tr>
            <td>4</td>
            <td class="statsdate">2022-02-11</td>
            <td>Michele</td>
            <td>Active</td>
            <td><Button class="hold" data-holdid="holdid">Hold</Button></td>
        </tr>
        <tr>
            <td>10</td>
            <td class="statsdate">2022-02-10</td>
            <td>William</td>
            <td>Active</td>
            <td><Button class="hold" data-holdid="holdid">Hold</Button></td>
        </tr>
    </tbody>
</table>
</code>```

AJAX:

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#load-table").append(
            "<tr>"
            + "<td>" + value.id + "</td>" +
            "<td class='statsdate'>" + statsDate + "</td>" +
            "<td>" + value.full_name + "</td>" +
            "<td><button type='button' title='Approve this user stat' class='approve btn btn-success btn-rounded btn-icon' data-approveid='" + value.id + "'><i class='typcn typcn-thumbs-up'></td>" +
            "<td><button type='button' title='Mark as Hold' class='hold btn btn-danger btn-rounded btn-icon' data-holdid='" + value.id + "'><i class='typcn typcn-archive'></td>" +
            "</tr>"
        );
  });

  //Hold user by clicking on hold modal
        $(document).on("click",".hold",function(){
            var answer = window.confirm("Are You sure to mark this user as Hold?");
            if (answer) {
                var holdid = $(this).data("holdid");
                var sts_date = $(this).closest(".statsDate").text();
                var obj = {uID : holdid, date: sts_date};
                var myJSON = JSON.stringify(obj);
                console.log(myJSON);
            }
            else {
                $("#usersCount").html("");
            }
        });
</script>
</code>```

Here is an image to make my question clear.

Image:

Question Image

Please help me fix it. Thanks in advance!

答:
The issue is because closest() only looks through the parent elements of the target. In your HTML, .statsdate is a child of the sibling to the parent. As such the simplest way to do what you need is to use closest() to get the common parent tr, then find() to get the .statsdate.

Also note that the class is statsdate, not .statsDate - case is important in selectors.

```<code>var sts_date = $(this).closest('tr').find(".statsdate").text();
</code>```

Working example:

$(document).ready(function() {
  let statsDate = (new Date()).toLocaleDateString();
  let value = {
    id: '123',
    full_name: 'foo bar'
  }

  $("#load-table").append(
    "
" +
    "" + value.id + "	" +
    "" + statsDate + "	" +
    "" + value.full_name + "	" +
    "<button type='button' title='Approve this user stat' class='approve btn btn-success btn-rounded btn-icon' data-approveid='" + value.id + "'>	" +
    "<button type='button' title='Mark as Hold' class='hold btn btn-danger btn-rounded btn-icon' data-holdid='" + value.id + "'>	" +
    "
"
  );
});

//Hold user by clicking on hold modal
$(document).on("click", ".hold", function() {
  var answer = window.confirm("Are You sure to mark this user as Hold?");
  if (answer) {
    var holdid = $(this).data("holdid");
    var sts_date = $(this).closest('tr').find(".statsdate").text();
    var obj = {
      uID: holdid,
      date: sts_date
    };
    var myJSON = JSON.stringify(obj);

    console.log(myJSON);
  } else {
    $("#usersCount").html("");
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="table table-hover table-bordered">
  <thead>
    <tr>
      <th>User ID</th>
      <th>Date</th>
      <th>Name</th>
      <th>User Status</th>
      <th colspan="4" class="text-center">Action</th>
    </tr>
  </thead>
  <tbody id="load-table">
    <!-- dummy data for StackOverFlow to show you data (By the way this data is dynamic coming from a database. I have placed dummy data only to show the output. So you can ignore data in #load-table)-->
    <tr>
      <td>1</td>
      <td class="statsdate">2022-02-12</td>
      <td>Jhon</td>
      <td>Active</td>
      <td>
        <button class="hold" data-holdid="holdid">Hold</button>
      </td>
    </tr>
    <tr>
      <td>4</td>
      <td class="statsdate">2022-02-11</td>
      <td>Michele</td>
      <td>Active</td>
      <td>
        <button class="hold" data-holdid="holdid">Hold</button>
      </td>
    </tr>
    <tr>
      <td>10</td>
      <td class="statsdate">2022-02-10</td>
      <td>William</td>
      <td>Active</td>
      <td>
        <button class="hold" data-holdid="holdid">Hold</button>
      </td>
    </tr>
  </tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script></code>```

Body:
I want to get the date of the same row when I click on Hold Button in the same row. I have tried more searching on Google but I couldn't find any helpful query to fix this issue.

I am new in ajax that's why I need help from this community. Please help me fix it.

Here is what I am trying:

HTML:

            User ID
            Date
            Name
            User Status
            Action

            1
            2022-02-12
            Jhon
            Active
            <Button class="hold" data-holdid="holdid">Hold</Button>

            4
            2022-02-11
            Michele
            Active
            <Button class="hold" data-holdid="holdid">Hold</Button>

            10
            2022-02-10
            William
            Active
            <Button class="hold" data-holdid="holdid">Hold</Button>

AJAX:

Here is an image to make my question clear.

Image:

Question Image

Please help me fix it. Thanks in advance!

Body:
The issue is because closest() only looks through the parent elements of the target. In your HTML, .statsdate is a child of the sibling to the parent. As such the simplest way to do what you need is to use closest() to get the common parent tr, then find() to get the .statsdate.

Also note that the class is statsdate, not .statsDate - case is important in selectors.

var sts_date = $(this).closest('tr').find(".statsdate").text();

Working example:

$(document).ready(function() {
  let statsDate = (new Date()).toLocaleDateString();
  let value = {
    id: '123',
    full_name: 'foo bar'
  }

  $("#load-table").append(
    "<tr>" +
    "<td>" + value.id + "</td>" +
    "<td class='statsdate'>" + statsDate + "</td>" +
    "<td>" + value.full_name + "</td>" +
    "<td><button type='button' title='Approve this user stat' class='approve btn btn-success btn-rounded btn-icon' data-approveid='" + value.id + "'><i class='typcn typcn-thumbs-up'></td>" +
    "<td><button type='button' title='Mark as Hold' class='hold btn btn-danger btn-rounded btn-icon' data-holdid='" + value.id + "'><i class='typcn typcn-archive'></td>" +
    "</tr>"
  );
});

//Hold user by clicking on hold modal
$(document).on("click", ".hold", function() {
  var answer = window.confirm("Are You sure to mark this user as Hold?");
  if (answer) {
    var holdid = $(this).data("holdid");
    var sts_date = $(this).closest('tr').find(".statsdate").text();
    var obj = {
      uID: holdid,
      date: sts_date
    };
    var myJSON = JSON.stringify(obj);

    console.log(myJSON);
  } else {
    $("#usersCount").html("");
  }
});

<table class="table table-hover table-bordered">
  <thead>
    <tr>
      <th>User ID</th>
      <th>Date</th>
      <th>Name</th>
      <th>User Status</th>
      <th colspan="4" class="text-center">Action</th>
    </tr>
  </thead>
  <tbody id="load-table">
    <!-- dummy data for StackOverFlow to show you data (By the way this data is dynamic coming from a database. I have placed dummy data only to show the output. So you can ignore data in #load-table)-->
    <tr>
      <td>1</td>
      <td class="statsdate">2022-02-12</td>
      <td>Jhon</td>
      <td>Active</td>
      <td>
        <button class="hold" data-holdid="holdid">Hold</button>
      </td>
    </tr>
    <tr>
      <td>4</td>
      <td class="statsdate">2022-02-11</td>
      <td>Michele</td>
      <td>Active</td>
      <td>
        <button class="hold" data-holdid="holdid">Hold</button>
      </td>
    </tr>
    <tr>
      <td>10</td>
      <td class="statsdate">2022-02-10</td>
      <td>William</td>
      <td>Active</td>
      <td>
        <button class="hold" data-holdid="holdid">Hold</button>
      </td>
    </tr>
  </tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>


来源: stackexchange

问:
clangd language server gives weird errors. code compiles
I've got platformio project that compiles and works.
Using emacs + lsp-mode + clang.
One of the weird errors I get is for structures like this:

```<code>#include <queue>
#include <vector>

struct test_v{
    std::vector<int> buff;
};
</code>```

on the line #include <queue>

```<code>in included file: no type named 'pointer' in 'std::allocator_traits<std::allocator<int>>'
</code>```

on the line of buff definition

```<code>In template: no member named 'value' in 'std::is_void<int>'
</code>```

file is .hpp in case this matters

答: the config was incomplete and missing headers that define the needed std:: parts</p>

ContentLicense: CC BY-SA 4.0

Body:
I've got platformio project that compiles and works.
Using emacs + lsp-mode + clang.
One of the weird errors I get is for structures like this:

#include <queue>
#include <vector>

struct test_v{
    std::vector<int> buff;
};

on the line #include <queue>

in included file: no type named 'pointer' in 'std::allocator_traits<std::allocator<int>>'

on the line of buff definition

In template: no member named 'value' in 'std::is_void<int>'

file is .hpp in case this matters


问:
How to ignore acute accent in a javascript regex match?
I need to match a word like 'César' for a regex like this /^cesar/i.

Is there an option like /i to configure the regex so it ignores the acute accents?.
Or the only solution is to use a regex like this /^césar/i.

答:
Meanwhile, if it the OP's problem still is just about identifying/matching entire words, regardless of acute accent, diacritics etc, a new possible approach could be based on JavaScript's Intl module/API without the help of any regular expression.

The task of a text's word-segmentation can be achieved by the segment method of an Intl.Segmenter instance.

In order to get all the matching words of a word query, one could reduce the resulting segments, where the collecting reducer function would locale compare each segment's word-like token against the query, based on the compare method of an Intl.Collator instance.

function collectMatchingWordItemFromSegment(collector, segment, idx) {
  let { collator, wordQuery, wordCount = 0, result } = collector;

  const { segment: token, isWordLike } = segment;
  if (
    isWordLike &&
    (collator.compare(token, wordQuery) === 0)
  ) {
    ++wordCount;

    const { segment: match, index } = segment;

    result.push({
      match,
      index,
      wordCount,
      tokenCount: (idx + 1),
    });
  }
  return { collator, wordQuery, wordCount, result };
}
const sampleText = `Risus nonummy purus. César. Facilisis potenti
ultricies dis et in sagittis id nonummy Hac cubilia sapien, césar.
Habitant eleifend vulputate tristique phasellus consectetuer, cesar
erat sagittis hendrerit porttitor consectetuer posuere dui mus class
metus nunc litora Cesar.`;

const matchingWordItemList = Array
  .from(
    new Intl.Segmenter('en', { granularity: 'word' }).segment(sampleText)
  )
  .reduce(collectMatchingWordItemFromSegment, {

    collator: new Intl.Collator('en', { sensitivity: 'base' }),
    wordQuery: 'cesar',
    result: [],

  }).result;

console.log({
  sampleText,
  matchingWordItemList,
});
console.log({
  segmentArray: Array.from(
    new Intl.Segmenter('en', { granularity: 'word' }).segment(sampleText)
  )
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { min-height: 100%!important; top: 0; }</code>```

A most recently asked, similar question about how to search and replace/keep words "...regardless of existing accents, diacritics etc and upper/lowercase characters..." within a given text, received two answers/solutions based on the above shown techniques.

ContentLicense: CC BY-SA 3.0

Body:
Meanwhile, if it the OP's problem still is just about identifying/matching entire words, regardless of acute accent, diacritics etc, a new possible approach could be based on JavaScript's Intl module/API without the help of any regular expression.

The task of a text's word-segmentation can be achieved by the segment method of an Intl.Segmenter instance.

In order to get all the matching words of a word query, one could reduce the resulting segments, where the collecting reducer function would locale compare each segment's word-like token against the query, based on the compare method of an Intl.Collator instance.

function collectMatchingWordItemFromSegment(collector, segment, idx) {
  let { collator, wordQuery, wordCount = 0, result } = collector;

  const { segment: token, isWordLike } = segment;
  if (
    isWordLike &&
    (collator.compare(token, wordQuery) === 0)
  ) {
    ++wordCount;

    const { segment: match, index } = segment;

    result.push({
      match,
      index,
      wordCount,
      tokenCount: (idx + 1),
    });
  }
  return { collator, wordQuery, wordCount, result };
}
const sampleText = `Risus nonummy purus. César. Facilisis potenti
ultricies dis et in sagittis id nonummy Hac cubilia sapien, césar.
Habitant eleifend vulputate tristique phasellus consectetuer, cesar
erat sagittis hendrerit porttitor consectetuer posuere dui mus class
metus nunc litora Cesar.`;

const matchingWordItemList = Array
  .from(
    new Intl.Segmenter('en', { granularity: 'word' }).segment(sampleText)
  )
  .reduce(collectMatchingWordItemFromSegment, {

    collator: new Intl.Collator('en', { sensitivity: 'base' }),
    wordQuery: 'cesar',
    result: [],

  }).result;

console.log({
  sampleText,
  matchingWordItemList,
});
console.log({
  segmentArray: Array.from(
    new Intl.Segmenter('en', { granularity: 'word' }).segment(sampleText)
  )
});

.as-console-wrapper { min-height: 100%!important; top: 0; }

A most recently asked, similar question about how to search and replace/keep words "...regardless of existing accents, diacritics etc and upper/lowercase characters..." within a given text, received two answers/solutions based on the above shown techniques.


问:
How to route on basis of Http headers in Envoy Proxy
I am sending an http request with below header.

Header = {"InstanceId" : "1"}

How to route to an cluster(endpoint) using this header value i.e. 1

What i actually want to do in envoy.yaml :

If (header. InstanceId == 1)

```<code>Route to cluster A
</code>```

Else If (header. InstanceId == 2)

```<code>Route to cluster B
</code>```

Can someone please help me out.
Thanks in advance.

答:
If you want to redirect traffic to different clusters based on the headers, you can define the following listener (the interesting part is the static_resources.listeners[0].filter_chains[0].filters[0].route_config.virtual_hosts[0].routes part, with the two matches defined) :

static_resources:
  listeners:
  - address:
      socket_address:
        address: 0.0.0.0
        port_value: 8080
    filter_chains:
    - filters:
      - name: envoy.filters.network.http_connection_manager
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
          codec_type: AUTO
          stat_prefix: ingress_http
          route_config:
            name: local_route
            virtual_hosts:
            - name: backend
              domains:
              - "*"
              routes:
              - match:
                  prefix: "/"
                  headers:
                    - name: "InstanceId"
                      exact_match: "1"
                route:
                  cluster: clusterA
              - match:
                  prefix: "/"
                  headers:
                    - name: "InstanceId"
                      exact_match: "2"
                route:
                  cluster: clusterB
          http_filters:
          - name: envoy.filters.http.router
```

Body:
I am sending an http request with below header.

Header = {"InstanceId" : "1"}

How to route to an cluster(endpoint) using this header value i.e. 1

What i actually want to do in envoy.yaml :

If (header. InstanceId == 1)

Route to cluster A

Else If (header. InstanceId == 2)

Route to cluster B

Can someone please help me out.
Thanks in advance.


问:
How to show/hide a child QWidget with a motion animation?
I am working on an application with two children. One's a widget that functions as a toolbar, the second, below, functions as dashboard, on which information would appear. The latter can be shown/hidden with buttons on the former. Here's a screen-cast of the prototype.

Now I am looking at doing the same but with a motion animation whilst showing/hiding the lower widget.

In short: the effect should be giving the impression the entire application rises or falls progressively when toggling the dashboard.

In details: I would like the height of the lower widget to decrease until it is reduced to 0 and then hidden completely. Likewise it would increase slowly when showing the widget again. In the meanwhile the position of the application should change accordingly so it stays at the bottom of the screen.

How can I do that? I've never done animations on Qt before. If you don't have an answer, do you know of a quality tutorial that could lead me there.

NB: I am using PyQt.

答:
I think you can get what you want by using a QPropertyAnimation that animates the geometry property of your widget.
But IMHO this is the window manager's role to do what you want. Maybe you will have some headaches bypassing it (but I'm maybe wrong).

After better reading of your question, it seems that you want to use your own components to trigger the hiding/showing so the WM shouldn't be a problem.

As a start here is some code that animate a minimizing of a widget (assuming tbw is an instance of the widget you want to animate):

```<code>formerGeometry = QtCore.QRect(tbw.geometry()) # storing previous geometry in order to be able to restore it later

hideAnimation = QtCore.QPropertyAnimation(tbw, "geometry")
hideAnimation.setDuration(2000) # chose the value that fits you
hideAnimation.setStartValue(formerGeometry)
#computing final geometry
endTopLeftCorner = QtCore.QPoint(tbw.pos() + QtCore.QPoint(0, tbw.height()))
finalGeometry = QtCore.QRect(endTopLeftCorner, QtCore.QSize(tbw.width(), 0))
hideAnimation.setEndValue(finalGeometry)

hideAnimation.start()
</code>```

Body:
I think you can get what you want by using a QPropertyAnimation that animates the geometry property of your widget.
But IMHO this is the window manager's role to do what you want. Maybe you will have some headaches bypassing it (but I'm maybe wrong).

After better reading of your question, it seems that you want to use your own components to trigger the hiding/showing so the WM shouldn't be a problem.

As a start here is some code that animate a minimizing of a widget (assuming tbw is an instance of the widget you want to animate):

formerGeometry = QtCore.QRect(tbw.geometry()) # storing previous geometry in order to be able to restore it later

hideAnimation = QtCore.QPropertyAnimation(tbw, "geometry")
hideAnimation.setDuration(2000) # chose the value that fits you
hideAnimation.setStartValue(formerGeometry)
#computing final geometry
endTopLeftCorner = QtCore.QPoint(tbw.pos() + QtCore.QPoint(0, tbw.height()))
finalGeometry = QtCore.QRect(endTopLeftCorner, QtCore.QSize(tbw.width(), 0))
hideAnimation.setEndValue(finalGeometry)

hideAnimation.start()


问:
conditional block display with TBS in DOCX tables
I am processing DOCX files for invoices with TBS. A first TBS block contains all the taxable items, one per line, followed by lines for subtotal and tax. A second TBS block contains all the non-taxable items, followed by one line for grand total.

I would like to leave out the first block, the subtotal and the tax amount if there are no taxable items.
I also would like to leave the second block out if there are no non-taxable items.

This is the basic structure:

```<code>[ItemListTx;block=begin]
  [ItemListTx.s]  [ItemListTx.a]
[ItemListTx;block=end]
subtotal          [abk.tt]
tax               [abk.tx]

[ItemListEx;block=begin;enlarge=tbs:p]
  [ItemListTx.s]  [ItemListTx.a]
[ItemListEx;block=end;enlarge=tbs:p]

total             [abk.ttlx]
</code>```

I wrapped the first five lines into a guarding block with a condition under which to display it:

```<code>[onshow;block=begin;enlarge=tbs:p;when 0=1]
...
[onshow;block=end;enlarge=tbs:p]
</code>```

I did the same for the second block. This works OK. Note that the wrapper block statements are on different lines.

I am still a bit unhappy with the condition though. Is there any other way than setting a flag on the PHP side? It seems to me the second block should do without a wrapper, too.

Note: For editing reasons each item line is a table in itself, really.

答:
Here is how it can easily be done:

```<code>| [ItemListTx.s;block=tbs:row;bmagnet=3*tbs:row] | [ItemListTx.a] |
| Subtotal:                                      | [abk.tt]       |
| Tax:                                           | [abk.tx]       |

| [ItemListEx.s;block=tbs:row;bmagnet=3*tbs:row] | [ItemListEx.a] |

| Total:                                         | [abk.ttlx]     |
</code>```

Explanations:

Parameter bmagnet enabled you to define the block to delete when the data to merge with MergeBlock() are empty.

3*tbs:row means 3 successive table rows.

With OpenTBS it is not recommended to use explicit blocks (block=begin/block=end) because we cannot be sure where they is placed in the inner XML. It is better to use relatives blocks (such as block=tbs:p).

Body:
I am processing DOCX files for invoices with TBS. A first TBS block contains all the taxable items, one per line, followed by lines for subtotal and tax. A second TBS block contains all the non-taxable items, followed by one line for grand total.

I would like to leave out the first block, the subtotal and the tax amount if there are no taxable items.
I also would like to leave the second block out if there are no non-taxable items.

This is the basic structure:

[ItemListTx;block=begin]
  [ItemListTx.s]  [ItemListTx.a]
[ItemListTx;block=end]
subtotal          [abk.tt]
tax               [abk.tx]

[ItemListEx;block=begin;enlarge=tbs:p]
  [ItemListTx.s]  [ItemListTx.a]
[ItemListEx;block=end;enlarge=tbs:p]

total             [abk.ttlx]

I wrapped the first five lines into a guarding block with a condition under which to display it:

[onshow;block=begin;enlarge=tbs:p;when 0=1]
...
[onshow;block=end;enlarge=tbs:p]

I did the same for the second block. This works OK. Note that the wrapper block statements are on different lines.

I am still a bit unhappy with the condition though. Is there any other way than setting a flag on the PHP side? It seems to me the second block should do without a wrapper, too.

Note: For editing reasons each item line is a table in itself, really.

Body:
Here is how it can easily be done:

| [ItemListTx.s;block=tbs:row;bmagnet=3*tbs:row] | [ItemListTx.a] |
| Subtotal:                                      | [abk.tt]       |
| Tax:                                           | [abk.tx]       |

| [ItemListEx.s;block=tbs:row;bmagnet=3*tbs:row] | [ItemListEx.a] |

| Total:                                         | [abk.ttlx]     |

Explanations:

Parameter bmagnet enabled you to define the block to delete when the data to merge with MergeBlock() are empty.

3*tbs:row means 3 successive table rows.

With OpenTBS it is not recommended to use explicit blocks (block=begin/block=end) because we cannot be sure where they is placed in the inner XML. It is better to use relatives blocks (such as block=tbs:p).


问:
Query remains in table when i clear the search box
When I clear the search box in the form, the table shows the same info (I want the table to show the original one, without any query).

Code:

```<code>Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    If TextBox14.Text = "" Then
        Call NotFound()
        Exit Sub
    Else
        CustomerInfo1BindingSource.Filter = "(Convert(ID, 'System.String') LIKE '" & TextBox14.Text & "')" &
            "OR (CustomerName LIKE '" & TextBox14.Text & "') OR (CustomerNumber LIKE '" & TextBox14.Text & "')" &
            "OR (OrderDate LIKE '" & TextBox14.Text & "')"
        If CustomerInfo1BindingSource.Count <> 0 Then
            With CustomerInfo1DataGridView
                .DataSource = CustomerInfo1BindingSource
            End With

        Else
            MsgBox("Not Found!")
            CustomerInfoBindingSource.Filter = Nothing
        End If

    End If
End Sub
</code>```

答:
If I've read the question correctly it appears that you're saying this:

You add a search term to TextBox14 which is then applied to the CustomerInfo1BindingSource.Filter and in turn that filters CustomerInfo1DataGridView as expected

You remove the search term from TextBox14 and click the button again

The filtered CustomerInfo1DataGridView remains untouched rather than showing everything

If that is the case I can see that code flow isn't exactly what you're expecting. Change it to be something like:

```<code>Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    If TextBox14.Text = "" Then
        CustomerInfoBindingSource.Filter = Nothing
        MsgBox("Not Found!")
    Else
        CustomerInfo1BindingSource.Filter = "(Convert(ID, 'System.String') LIKE '" & TextBox14.Text & "')" &
            "OR (CustomerName LIKE '" & TextBox14.Text & "') OR (CustomerNumber LIKE '" & TextBox14.Text & "')" &
            "OR (OrderDate LIKE '" & TextBox14.Text & "')"
        If CustomerInfo1BindingSource.Count <> 0 Then
            With CustomerInfo1DataGridView
                .DataSource = CustomerInfo1BindingSource
            End With
        End If
    End If
End Sub
</code>```

As it stands with your code the lineCustomerInfoBindingSource.Filter = Nothing is not being hit because there is no search term in TextBox14. Instead it's calling this NotFound() method which we don't have visibility of, and then exiting the method.

It might be worth also reading up on the official documentation. You can call RemoveFilter on a BindingSource:

```<code>CustomerInfoBindingSource.RemoveFilter()
</code>```

Body:
When I clear the search box in the form, the table shows the same info (I want the table to show the original one, without any query).

Code:

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    If TextBox14.Text = "" Then
        Call NotFound()
        Exit Sub
    Else
        CustomerInfo1BindingSource.Filter = "(Convert(ID, 'System.String') LIKE '" & TextBox14.Text & "')" &
            "OR (CustomerName LIKE '" & TextBox14.Text & "') OR (CustomerNumber LIKE '" & TextBox14.Text & "')" &
            "OR (OrderDate LIKE '" & TextBox14.Text & "')"
        If CustomerInfo1BindingSource.Count <> 0 Then
            With CustomerInfo1DataGridView
                .DataSource = CustomerInfo1BindingSource
            End With

        Else
            MsgBox("Not Found!")
            CustomerInfoBindingSource.Filter = Nothing
        End If

    End If
End Sub

Body:
If I've read the question correctly it appears that you're saying this:

You add a search term to TextBox14 which is then applied to the CustomerInfo1BindingSource.Filter and in turn that filters CustomerInfo1DataGridView as expected

You remove the search term from TextBox14 and click the button again

The filtered CustomerInfo1DataGridView remains untouched rather than showing everything

If that is the case I can see that code flow isn't exactly what you're expecting. Change it to be something like:

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    If TextBox14.Text = "" Then
        CustomerInfoBindingSource.Filter = Nothing
        MsgBox("Not Found!")
    Else
        CustomerInfo1BindingSource.Filter = "(Convert(ID, 'System.String') LIKE '" & TextBox14.Text & "')" &
            "OR (CustomerName LIKE '" & TextBox14.Text & "') OR (CustomerNumber LIKE '" & TextBox14.Text & "')" &
            "OR (OrderDate LIKE '" & TextBox14.Text & "')"
        If CustomerInfo1BindingSource.Count <> 0 Then
            With CustomerInfo1DataGridView
                .DataSource = CustomerInfo1BindingSource
            End With
        End If
    End If
End Sub

As it stands with your code the lineCustomerInfoBindingSource.Filter = Nothing is not being hit because there is no search term in TextBox14. Instead it's calling this NotFound() method which we don't have visibility of, and then exiting the method.

It might be worth also reading up on the official documentation. You can call RemoveFilter on a BindingSource:

CustomerInfoBindingSource.RemoveFilter()


问:
Is there any way to convert the hex code from string to hex colour which discord.py supports?
I am trying to figure this out for so long,
but I am not able to convert the hex code from string to actual hex code like this 0xFFFFFF
since discord.py doesn't take hex code in str datatype.
Code Snippet:-

```<code>@client.command()
async def testing(ctx):
    # color = lgd.hexConvertor(colorCollection.find({},{"_id":0,"Hex":1}))
    c = "0xFFFFFF"
    inte = int(c,16)
    color = hex(inte)
    await ctx.send(embed = discord.Embed(description = "testing",color = color))
</code>```

Error:-

```<code>Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 221, in testing
    await ctx.send(embed = discord.Embed(description = "testing",color = color))
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/embeds.py", line 115, in __init__
    self.colour = colour
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/embeds.py", line 230, in colour
    raise TypeError('Expected discord.Colour, int, or Embed.Empty but received %s instead.' % value.__class__.__name__)
TypeError: Expected discord.Colour, int, or Embed.Empty but received str instead.
</code>```

This is how I stored the hex codes in my mongodb atlas database->

Edit:-
It worked on using inte instead of color

答:
Look at the error.

```<code>TypeError: Expected discord.Colour, int, or Embed.Empty
</code>```

An int would suffice, no need for extra conversions.

@client.command()
async def testing(ctx):
    # color = lgd.hexConvertor(colorCollection.find({},{"_id":0,"Hex":1}))
    c = "0xFFFFFF"
    int_colour = int(c,16)
    await ctx.send(embed = discord.Embed(description = "testing",color = int_colour))
```

Body:
I am trying to figure this out for so long,
but I am not able to convert the hex code from string to actual hex code like this 0xFFFFFF
since discord.py doesn't take hex code in str datatype.
Code Snippet:-

@client.command()
async def testing(ctx):
    # color = lgd.hexConvertor(colorCollection.find({},{"_id":0,"Hex":1}))
    c = "0xFFFFFF"
    inte = int(c,16)
    color = hex(inte)
    await ctx.send(embed = discord.Embed(description = "testing",color = color))

Error:-

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 221, in testing
    await ctx.send(embed = discord.Embed(description = "testing",color = color))
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/embeds.py", line 115, in __init__
    self.colour = colour
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/embeds.py", line 230, in colour
    raise TypeError('Expected discord.Colour, int, or Embed.Empty but received %s instead.' % value.__class__.__name__)
TypeError: Expected discord.Colour, int, or Embed.Empty but received str instead.

This is how I stored the hex codes in my mongodb atlas database->

Edit:-
It worked on using inte instead of color

Body:
Look at the error.

TypeError: Expected discord.Colour, int, or Embed.Empty

An int would suffice, no need for extra conversions.

@client.command()
async def testing(ctx):
    # color = lgd.hexConvertor(colorCollection.find({},{"_id":0,"Hex":1}))
    c = "0xFFFFFF"
    int_colour = int(c,16)
    await ctx.send(embed = discord.Embed(description = "testing",color = int_colour))


问:
list files pattern select date
Hello I have a set of daily meteo data, using the expression :

```<code>f <- list.files(getwd(), include.dirs=TRUE, recursive=TRUE, pattern= "PREC")
</code>```

I select only the files of Precipitation

I wonder how to select only files for example  of January, the one for example named 20170103 (yyyymmdd) ,  so the one named yyyy01dd....

the files are named in this way: "PREC_20010120.grd".

Title: list files pattern select date

Body:
Hello I have a set of daily meteo data, using the expression :

f <- list.files(getwd(), include.dirs=TRUE, recursive=TRUE, pattern= "PREC")

I select only the files of Precipitation

I wonder how to select only files for example  of January, the one for example named 20170103 (yyyymmdd) ,  so the one named yyyy01dd....

the files are named in this way: "PREC_20010120.grd".

Body:
Thank you , but I retrieved only 35 items instead of 31 days * 10 years   what's wrong ?

[1] "20100102/PREC_20100102.tif" "20100112/PREC_20100112.tif"
[3] "20100122/PREC_20100122.tif" "20110102/PREC_20110102.tif"
[5] "20110112/PREC_20110112.tif" "20110122/PREC_20110122.tif"
[7] "20120102/PREC_20120102.tif" "20120112/PREC_20120112.tif"
[9] "20120122/PREC_20120122.tif" "20130102/PREC_20130102.tif"
[11] "20130112/PREC_20130112.tif" "20130122/PREC_20130122.tif"
[13] "20140102/PREC_20140102.tif" "20140112/PREC_20140112.tif"
[15] "20140122/PREC_20140122.tif" "20150102/PREC_20150102.tif"
[17] "20150112/PREC_20150112.tif" "20150122/PREC_20150122.tif"
[19] "20160102/PREC_20160102.tif" "20160112/PREC_20160112.tif"
[21] "20160122/PREC_20160122.tif" "20170102/PREC_20170102.tif"
[23] "20170112/PREC_20170112.tif" "20170122/PREC_20170122.tif"
[25] "20180102/PREC_20180102.tif" "20180112/PREC_20180112.tif"
[27] "20180122/PREC_20180122.tif" "20190102/PREC_20190102.tif"
[29] "20190112/PREC_20190112.tif" "20190122/PREC_20190122.tif"
[31] "20200102/PREC_20200102.tif" "20200112/PREC_20200112.tif"
[33] "20200122/PREC_20200122.tif" "20210102/PREC_20210102.tif"
[35] "20210112/PREC_20210112.tif" "20210122/PREC_20210122.tif"


问:
Working with Json Logic on Pandas Dataframe
How can I use a manual logic for feature aggregation for example bu using Json Logic (open to other solutions as well) on large dataframes:

For example if I have this dataframe (in reality it's a large DF):

pie_df

       temp  pie_filling
    0  100  "apple"
    1  400  "apple"
    2  70  "cherry"
```
<p>and this logic (for example inside a json file), in reality the logic file will have multiple aggregations at different nesting levels:</p>
<pre class="lang-py prettyprint-override"><code>rules = { "and" : [
    {"<" : [ { "var" : "temp" }, 110 ]},
    {"==" : [ { "var" : "pie_filling" }, "apple" ] }
] }
</code>```

I want the answer to be:

```<code>   pie_ready
0  true
1  false
2  false
</code>```

The logic file should be generic and readable. I can convert the dataframe to json but I am worried this won't be computationally efficient.

I did find this package: https://github.com/nadirizr/json-logic-py but they didn't mention implementing the logic on dataframes

This line doesn't work:

```<code>jsonLogic(rules, pie_df.to_json())
</code>```

I get this error:

```<code>{TypeError}'dict_keys' object is not subscriptable
</code>```

答:
json-logi-py is not maintained anymore, use this fork instead: pip install json-logic-qubit

Then, you can handle your dataframe like this:

from json_logic import jsonLogic

rules = {
    "and": [{"<": [{"var": "temp"}, 110]}, {"==": [{"var": "pie_filling"}, "apple"]}]
}

print(
    pd.DataFrame(
        {"pie_ready": [jsonLogic(rules, row) for row in df.to_dict(orient="records")]}
    )
)

# Output
   pie_ready
0       True
1      False
2      False
```

Body:
How can I use a manual logic for feature aggregation for example bu using Json Logic (open to other solutions as well) on large dataframes:

For example if I have this dataframe (in reality it's a large DF):

pie_df

       temp  pie_filling
    0  100  "apple"
    1  400  "apple"
    2  70  "cherry"

and this logic (for example inside a json file), in reality the logic file will have multiple aggregations at different nesting levels:

rules = { "and" : [
    {"<" : [ { "var" : "temp" }, 110 ]},
    {"==" : [ { "var" : "pie_filling" }, "apple" ] }
] }

I want the answer to be:

   pie_ready
0  true
1  false
2  false

The logic file should be generic and readable. I can convert the dataframe to json but I am worried this won't be computationally efficient.

I did find this package: https://github.com/nadirizr/json-logic-py but they didn't mention implementing the logic on dataframes

This line doesn't work:

jsonLogic(rules, pie_df.to_json())

I get this error:

{TypeError}'dict_keys' object is not subscriptable


问:
Amazon SP-API get shipping addresses for all orders
In the old MWS "getOrders" api call, there was in the response a field for each order named "shippindAddress" which I could use to create my shipping labels.

In the new SP-API in the getOrders there is no such field. Instead you can get the shipping address via "/orders/v0/orders/{orderId}/address ". But you should call this api for each order (>100) and the rate is set for 1 per second.. So for 100 orders I will have to wait over 1.5 mins to get all addresses.

Is there a possibility to get all order with shipping addresses ? Or to increase the request limit ?

答: you should use restricted data token for buyer info and detailed address info, instead of "/orders/v0/orders/{orderId}/address" endpoint</p>


问:
fork/exec : operation not permitted Ubuntu 20.04
When trying to debug go application I get the following similar error messages.

I initially tried debugging simple golang program with the following vscode launch.json:

```<code>{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch Package",
            "type": "go",
            "request": "launch",
            "mode": "auto",
            "program": "${workspaceFolder}"
        }
    ]
}
</code>```

What I get is:

could not launch process: fork/exec /tmp/__debug_bin1874603807: operation not permitted

Setting "debugAdapter": "legacy" leads to similar result:

could not launch process: fork/exec /home/user/test/__debug_bin: operation not permitted

Starting dlv from command line has same output:

user@my-machine:~/test$ /home/user/go/bin/dlv debug
could not launch process: fork/exec /home/user/test/__debug_bin: operation not permitted

I have tested that running files from /tmp is allowed; I have tried setting kernel.yama.ptrace_scope = 0 in /etc/sysctl.d/10-ptrace.conf because all I can find on this error is related to ptrace (https://github.com/go-delve/delve/issues/515).

Also it is worth mentioning that command works as root:

```<code>user@my-machine:~/test$ su root
Password:
root@my-machine:/home/user/test# export PATH=$PATH:/usr/local/go/bin
root@my-machine:/home/user/test# go version
go version go1.17.6 linux/amd64
root@my-machine:/home/user/test# ../go/bin/dlv debug
Type 'help' for list of commands.
(dlv) quit
</code>```

Reinstalling dlv with deleting dlv binary and running go install github.com/go-delve/delve/cmd/dlv@latest does not help. I have a fresh Ubuntu Server 20.04 installation.

How to fix debugging?

答: I have figured out that setting kernel.yama.ptrace_scope = 0 did not work for some reason, however echo 0 > /proc/sys/kernel/yama/ptrace_scope helped

Body:
When trying to debug go application I get the following similar error messages.

I initially tried debugging simple golang program with the following vscode launch.json:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch Package",
            "type": "go",
            "request": "launch",
            "mode": "auto",
            "program": "${workspaceFolder}"
        }
    ]
}

What I get is:

could not launch process: fork/exec /tmp/__debug_bin1874603807: operation not permitted

Setting "debugAdapter": "legacy" leads to similar result:

could not launch process: fork/exec /home/user/test/__debug_bin: operation not permitted

Starting dlv from command line has same output:

user@my-machine:~/test$ /home/user/go/bin/dlv debug
could not launch process: fork/exec /home/user/test/__debug_bin: operation not permitted

I have tested that running files from /tmp is allowed; I have tried setting kernel.yama.ptrace_scope = 0 in /etc/sysctl.d/10-ptrace.conf because all I can find on this error is related to ptrace (https://github.com/go-delve/delve/issues/515).

Also it is worth mentioning that command works as root:

user@my-machine:~/test$ su root
Password:
root@my-machine:/home/user/test# export PATH=$PATH:/usr/local/go/bin
root@my-machine:/home/user/test# go version
go version go1.17.6 linux/amd64
root@my-machine:/home/user/test# ../go/bin/dlv debug
Type 'help' for list of commands.
(dlv) quit

Reinstalling dlv with deleting dlv binary and running go install github.com/go-delve/delve/cmd/dlv@latest does not help. I have a fresh Ubuntu Server 20.04 installation.

How to fix debugging?


问:
aligning the text in a div to the bottom
I have two divs next to each other, one with float: right and the other with float: left. The one on the left contains an image (200x100px) and the div on the right should contain a text. I would like to have the text of the div on the right to start on the bottom left of the div instead of the top left, is that possible somehow?
Thanks

答:
You can make the container position: relative then make a div inside with position: absolute; bottom: 0; left: 0;

```<code><div style="position: relative; height: 300px; width: 300px; background-color: #f00;">
  <div style="position: absolute; bottom: 0; left: 0; right: 0; background-color: #00f;">
    This will be at the bottom!
  </div>
</div>
</code>```

Body:
You can make the container position: relative then make a div inside with position: absolute; bottom: 0; left: 0;

<div style="position: relative; height: 300px; width: 300px; background-color: #f00;">
  <div style="position: absolute; bottom: 0; left: 0; right: 0; background-color: #00f;">
    This will be at the bottom!
  </div>
</div>


问:
Generating new unique uuid4 in Django for each object of Factory class
I have a Model Sector which has a id field (pk) which is UUID4 type.
I am trying to populate that table(Sector Model) using faker and factory_boy.

But,

```<code>DETAIL:  Key (id)=(46f0cf58-7e63-4d0b-9dff-e157261562d2) already exists.
</code>```

This is the error I am getting.

Is it possible that the error is due to the fact that everytime I am creating SectorFactory objects (which is in a different django app) and the seed gets reset to some previous number causing the uuid to repeat?

Please suggest some ways as to how I shall get unique uuid for each Factory object?

SectorFactory class

```<code>import uuid
from factory.django import DjangoModelFactory
from factory.faker import Faker
from factory import Sequence

class SectorFactory(DjangoModelFactory):
    id = uuid.uuid4()
    name = Sequence(lambda n: f'Sector-{n}')

    class Meta:
        model = 'user.Sector'
        django_get_or_create = ['name']
</code>```

Class Sector

```<code>class Sector(models.Model):
    id      = models.UUIDField(primary_key=True, default = uuid.uuid4, editable=False)
    name    = models.CharField(max_length=100)

    class Meta:
        db_table = 'sector'
        constraints = [
            models.UniqueConstraint('name', name = 'unique_sector_name')
        ]
</code>```

The script which creates the custom command to create SectorFactory objects.

```<code>from types import NoneType
from django.core.management.base import BaseCommand
from user.factories import SectorFactory

class Command(BaseCommand):
    help = 'Generate fake data and seed the models with them.'

    def add_arguments(self, parser) -> None:
        parser.add_argument( '--amount', type=int, help='The amount of fake objects to create.' )

    def _generate_sectors(self, amount):
        for _ in range(amount):
            SectorFactory()

    def handle(self, *args, **options) :

        amount = options['amount']
        if(type(amount) == NoneType): amount = 10

        self._generate_sectors(amount)

</code>```

答:
just use like this:

class SectorFactory(DjangoModelFactory):
    id = Faker('uuid4')
    name = Sequence(lambda n: f'Sector-{n}')

    class Meta:
        model = 'user.Sector'
        django_get_or_create = ['name']
```

Body:
I have a Model Sector which has a id field (pk) which is UUID4 type.
I am trying to populate that table(Sector Model) using faker and factory_boy.

But,

DETAIL:  Key (id)=(46f0cf58-7e63-4d0b-9dff-e157261562d2) already exists.

This is the error I am getting.

Is it possible that the error is due to the fact that everytime I am creating SectorFactory objects (which is in a different django app) and the seed gets reset to some previous number causing the uuid to repeat?

Please suggest some ways as to how I shall get unique uuid for each Factory object?

SectorFactory class

import uuid
from factory.django import DjangoModelFactory
from factory.faker import Faker
from factory import Sequence

class SectorFactory(DjangoModelFactory):
    id = uuid.uuid4()
    name = Sequence(lambda n: f'Sector-{n}')

    class Meta:
        model = 'user.Sector'
        django_get_or_create = ['name']

Class Sector

class Sector(models.Model):
    id      = models.UUIDField(primary_key=True, default = uuid.uuid4, editable=False)
    name    = models.CharField(max_length=100)

    class Meta:
        db_table = 'sector'
        constraints = [
            models.UniqueConstraint('name', name = 'unique_sector_name')
        ]

The script which creates the custom command to create SectorFactory objects.

from types import NoneType
from django.core.management.base import BaseCommand
from user.factories import SectorFactory

class Command(BaseCommand):
    help = 'Generate fake data and seed the models with them.'

    def add_arguments(self, parser) -> None:
        parser.add_argument( '--amount', type=int, help='The amount of fake objects to create.' )

    def _generate_sectors(self, amount):
        for _ in range(amount):
            SectorFactory()

    def handle(self, *args, **options) :

        amount = options['amount']
        if(type(amount) == NoneType): amount = 10

        self._generate_sectors(amount)


问:
mobile version of my website burger button doesn't drop down
So I'm trying to make a navbar and make the mobile version of it following a tutorial but the burger drop down is not working .I spent hours trying to figure this out but I cant find what's wrong

const navSlide = () => {

  const burger = document.querySelector(".burger");
  const nav = document.querySelector(".nav-links");

  burger.addEventListener("click", function() {
    nav.classList.toggle('nav-active');
  });
}

navSlide();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  text-decoration: none;
}

.nav {
  display: flex;
  align-items: center;
  justify-content: space-around;
  font-family: 'Poppins', sans-serif;
  background-color: #5d4954;
  min-height: 8vh;
}

.logo {
  color: rgb(196, 194, 194);
  text-transform: uppercase;
  letter-spacing: 5px;
  font-size: 20px;
  font-weight: bold;
}

.nav-links {
  display: flex;
  justify-content: space-around;
  width: 50%;
  padding-right: 0px;
  font-weight: bold;
}

.nav-links li {
  list-style: none;
}

.nav-links a {
  color: rgb(196, 194, 194);
  text-decoration: none;
  letter-spacing: 2px;
  font-weight: bold;
  font-size: 14px;
}

.burger div {
  background-color: rgb(196, 194, 194);
  margin: 5px;
  width: 25px;
  height: 3px;
}

.burger {
  display: none;
  cursor: pointer;
}

@media screen and (max-width:768px) {
  body {
    overflow-x: hidden;
  }
  .nav-links {
    position: absolute;
    right: 0px;
    height: 92vh;
    top: 8vh;
    background-color: #5d4954;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 50%;
    transform: translateX(100%);
    transition: transform 0.5s ease-in;
  }
  .nav-links li {
    opacity: 0;
  }
  .burger {
    display: block;
  }
}

.nav-active {
  transform: translateX(0%);
}

/*
@media  screen and(max-width:1024px){
   .nav-links{
        width: 60%;
        }
 }*/</code>```

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>navbar</title>
  <link rel="stylesheet" href="style.css">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@200&display=swap" rel="stylesheet">

my nav

Home

About

work

projects

```

the JavaScript looks fine cause I traced it word for word, but its the CSS I'm kind of worried about maybe there is a problem in the media queries I made. thanks in advance :)

i realized that it runs well here when you click run snippet but it doesn't in chrome using live server in vscode, what is the problem???

答:
The opacity of your .nav-links li never changes when you change it to active you can either remove .nav-links li { opacity: 0; } or give them the opacity when the list is active as I have done below.

EDIT: I do not see a link to your JavaScript in your HTML file.  If it is working on stack overflow and not in your local files make sure you have properly linked your HTML and JavaScript files together by either having the JavaScript just before the closing body tag or add in a link to your script.js before your closing body tag.

/* script.js */

const navSlide = () => {

  const burger = document.querySelector(".burger");
  const nav = document.querySelector(".nav-links");

  burger.addEventListener("click", function() {
    nav.classList.toggle('nav-active');
  });
}

navSlide();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* style.css */

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  text-decoration: none;
}

.nav {
  display: flex;
  align-items: center;
  justify-content: space-around;
  font-family: 'Poppins', sans-serif;
  background-color: #5d4954;
  min-height: 8vh;
}

.logo {
  color: rgb(196, 194, 194);
  text-transform: uppercase;
  letter-spacing: 5px;
  font-size: 20px;
  font-weight: bold;
}

.nav-links {
  display: flex;
  justify-content: space-around;
  width: 50%;
  padding-right: 0px;
  font-weight: bold;
}

.nav-links li {
  list-style: none;
}

.nav-links a {
  color: rgb(196, 194, 194);
  text-decoration: none;
  letter-spacing: 2px;
  font-weight: bold;
  font-size: 14px;
}

.burger div {
  background-color: rgb(196, 194, 194);
  margin: 5px;
  width: 25px;
  height: 3px;
}

.burger {
  display: none;
  cursor: pointer;
}

@media screen and (max-width:768px) {
  body {
    overflow-x: hidden;
  }
  .nav-links {
    position: absolute;
    right: 0px;
    height: 92vh;
    top: 8vh;
    background-color: #5d4954;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 50%;
    transform: translateX(100%);
    transition: transform 0.5s ease-in;
  }

  .nav-links li {
    opacity: 0;
  }

  .burger {
    display: block;
  }
}

.nav-active {
  transform: translateX(0%);
}

/* changes opacity of li when active */
.nav-active li {
  opacity: 1;
}

/*
@media  screen and(max-width:1024px){
   .nav-links{
        width: 60%;
        }
 }*/</code>```

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>navbar</title>
  <link rel="stylesheet" href="style.css">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@200&display=swap" rel="stylesheet">

my nav

Home

About

work

projects

```

Body:
So I'm trying to make a navbar and make the mobile version of it following a tutorial but the burger drop down is not working .I spent hours trying to figure this out but I cant find what's wrong

const navSlide = () => {

  const burger = document.querySelector(".burger");
  const nav = document.querySelector(".nav-links");

  burger.addEventListener("click", function() {
    nav.classList.toggle('nav-active');
  });
}

navSlide();

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  text-decoration: none;
}

.nav {
  display: flex;
  align-items: center;
  justify-content: space-around;
  font-family: 'Poppins', sans-serif;
  background-color: #5d4954;
  min-height: 8vh;
}

.logo {
  color: rgb(196, 194, 194);
  text-transform: uppercase;
  letter-spacing: 5px;
  font-size: 20px;
  font-weight: bold;
}

.nav-links {
  display: flex;
  justify-content: space-around;
  width: 50%;
  padding-right: 0px;
  font-weight: bold;
}

.nav-links li {
  list-style: none;
}

.nav-links a {
  color: rgb(196, 194, 194);
  text-decoration: none;
  letter-spacing: 2px;
  font-weight: bold;
  font-size: 14px;
}

.burger div {
  background-color: rgb(196, 194, 194);
  margin: 5px;
  width: 25px;
  height: 3px;
}

.burger {
  display: none;
  cursor: pointer;
}

@media screen and (max-width:768px) {
  body {
    overflow-x: hidden;
  }
  .nav-links {
    position: absolute;
    right: 0px;
    height: 92vh;
    top: 8vh;
    background-color: #5d4954;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 50%;
    transform: translateX(100%);
    transition: transform 0.5s ease-in;
  }
  .nav-links li {
    opacity: 0;
  }
  .burger {
    display: block;
  }
}

.nav-active {
  transform: translateX(0%);
}

/*
@media  screen and(max-width:1024px){
   .nav-links{
        width: 60%;
        }
 }*/

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>navbar</title>
  <link rel="stylesheet" href="style.css">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@200&display=swap" rel="stylesheet">

my nav

Home

About

work

projects

the JavaScript looks fine cause I traced it word for word, but its the CSS I'm kind of worried about maybe there is a problem in the media queries I made. thanks in advance :)

i realized that it runs well here when you click run snippet but it doesn't in chrome using live server in vscode, what is the problem???

Body:
The opacity of your .nav-links li never changes when you change it to active you can either remove .nav-links li { opacity: 0; } or give them the opacity when the list is active as I have done below.

EDIT: I do not see a link to your JavaScript in your HTML file.  If it is working on stack overflow and not in your local files make sure you have properly linked your HTML and JavaScript files together by either having the JavaScript just before the closing body tag or add in a link to your script.js before your closing body tag. <script src="script.js"></script>

/* script.js */

const navSlide = () => {

  const burger = document.querySelector(".burger");
  const nav = document.querySelector(".nav-links");

  burger.addEventListener("click", function() {
    nav.classList.toggle('nav-active');
  });
}

navSlide();

/* style.css */

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  text-decoration: none;
}

.nav {
  display: flex;
  align-items: center;
  justify-content: space-around;
  font-family: 'Poppins', sans-serif;
  background-color: #5d4954;
  min-height: 8vh;
}

.logo {
  color: rgb(196, 194, 194);
  text-transform: uppercase;
  letter-spacing: 5px;
  font-size: 20px;
  font-weight: bold;
}

.nav-links {
  display: flex;
  justify-content: space-around;
  width: 50%;
  padding-right: 0px;
  font-weight: bold;
}

.nav-links li {
  list-style: none;
}

.nav-links a {
  color: rgb(196, 194, 194);
  text-decoration: none;
  letter-spacing: 2px;
  font-weight: bold;
  font-size: 14px;
}

.burger div {
  background-color: rgb(196, 194, 194);
  margin: 5px;
  width: 25px;
  height: 3px;
}

.burger {
  display: none;
  cursor: pointer;
}

@media screen and (max-width:768px) {
  body {
    overflow-x: hidden;
  }
  .nav-links {
    position: absolute;
    right: 0px;
    height: 92vh;
    top: 8vh;
    background-color: #5d4954;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 50%;
    transform: translateX(100%);
    transition: transform 0.5s ease-in;
  }

  .nav-links li {
    opacity: 0;
  }

  .burger {
    display: block;
  }
}

.nav-active {
  transform: translateX(0%);
}

/* changes opacity of li when active */
.nav-active li {
  opacity: 1;
}

/*
@media  screen and(max-width:1024px){
   .nav-links{
        width: 60%;
        }
 }*/

<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>navbar</title>
  <link rel="stylesheet" href="style.css">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@200&display=swap" rel="stylesheet">
</head>

<body>
  <nav class="nav">

    <div class="logo">
      <p>my nav</p>

    </div>

    <ul class="nav-links">
      <li class="el"><a href="#">Home</a></li>
      <li class="el"><a href="#">About</a></li>
      <li class="el"><a href="#">work</a></li>
      <li class="el"><a href="#">projects</a></li>
    </ul>
    <div class="burger">
      <div class="line1"></div>
      <div class="line2"></div>
      <div class="line3"></div>

    </div>

  </nav>
  <script src="script.js"></script>
</body>

</html>


问:
Can't find Oracle Database Driver in Eclipse JAVA Program
I am trying to connect to an oracle database in eclipse. I have ojdbc14.jar in a lib folder in the same project and i added it to the build path of my project, so it also resides in the Referenced Libraries directory, but yet i still get an output to the console of "Could not find the database driver"

Myself and another student employee have been trying to get this figured out for the past day and a half, and no one else in our department is experienced in Java and JSP so i thought StackOverflow would be our best bet =)

```<code>try {
            // Load the JDBC driver
            String driverName = "oracle.jdbc.driver.OracleDriver";
            System.out.println("Attempting to load the driver...");
            Class.forName(driverName);
            System.out.print("Loaded the driver");

            // Create a connection to the database
            String serverName = " ;) ";
            String portNumber = " ;) ";
            String sid = " ;) ";
            String url = "jdbc:oracle:thin:@" + serverName + ":"
                    + portNumber + ":" + sid;
            String username = "kenne13";
            String password = "**********";
            connection = DriverManager.getConnection(url, username, password);
            if (connection != null) {
                return true;
            }

        } catch (ClassNotFoundException e) {
            // Could not find the database driver
            System.out.println("Could not find the database driver");
            connected = false;
        } catch (SQLException e) {
            // Could not connect to the database
            System.out.println("Could not connect to the database");
            connected = false;
        }
</code>```

Here is the output in the console:

```<code>    Aug 18, 2011 10:07:50 AM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 382 ms
    Attempting to load the driver...
    Could not find the database driver
</code>```

Here is a screen capture of the code, the error, and my project directories.

答: I believe the Oracle Driver class is: oracle.jdbc.OracleDriver

Body:
I am trying to connect to an oracle database in eclipse. I have ojdbc14.jar in a lib folder in the same project and i added it to the build path of my project, so it also resides in the Referenced Libraries directory, but yet i still get an output to the console of "Could not find the database driver"

Myself and another student employee have been trying to get this figured out for the past day and a half, and no one else in our department is experienced in Java and JSP so i thought StackOverflow would be our best bet =)

try {
            // Load the JDBC driver
            String driverName = "oracle.jdbc.driver.OracleDriver";
            System.out.println("Attempting to load the driver...");
            Class.forName(driverName);
            System.out.print("Loaded the driver");

            // Create a connection to the database
            String serverName = " ;) ";
            String portNumber = " ;) ";
            String sid = " ;) ";
            String url = "jdbc:oracle:thin:@" + serverName + ":"
                    + portNumber + ":" + sid;
            String username = "kenne13";
            String password = "**********";
            connection = DriverManager.getConnection(url, username, password);
            if (connection != null) {
                return true;
            }

        } catch (ClassNotFoundException e) {
            // Could not find the database driver
            System.out.println("Could not find the database driver");
            connected = false;
        } catch (SQLException e) {
            // Could not connect to the database
            System.out.println("Could not connect to the database");
            connected = false;
        }

Here is the output in the console:

    Aug 18, 2011 10:07:50 AM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 382 ms
    Attempting to load the driver...
    Could not find the database driver

Here is a screen capture of the code, the error, and my project directories.


问:
Unable to start XAMPP properly on my Mac OS
I am trying to install XAMPP so that I can work it with PHP. But I have failed to open it, however I realised that other people downloading it, it comes as a dmg extension but mine comes as a bz2 extension. Is this the error? If so, how can I solve it? if it's not, would anyone share with me whats causing the error and how to solve it?
Thanks!</p>

答:
On macOS, simply change the extension from .bz2 to .dmg so the installer mentioned should be changed to xxxxx.dmg then you can install it right away just double click on it.

credit to : https://stackoverflow.com/a/68201277/7048025


问:
Strange java behavior of wait/notify
I've found strange behavior of java concurrency. See on the next code below:

```<code>public class Test {
    static CountDownLatch latch = new CountDownLatch(1);
    public static void main(String[] args) throws UnsupportedEncodingException, InterruptedException {
        final Thread t = new MyThread();
        t.start();
        synchronized (t) {
            latch.countDown();
            System.out.println("got to sleep");
            t.wait();
            System.out.println("wake up");
        }
    }

    static class MyThread extends Thread {
        @Override
        public void run() {
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (this) {
                System.out.println("inside run");
//                notifyAll();
            }
        }
    }
}
</code>```

In my point of view this code should be hang up and wait forever, but code is finished without any problem with next out in console:

```
got to sleep
inside run
wake up
```

I've tried to find some information about notifying locks if thread is died, but was lack in it.
Also I've not find any information in java specification.

But if I've tried to lock on some other object (not on the thread object) it was work fine as I expected.

答: It is behaving differently due to the lock is taken on the Thread instance, if you will lock on the different object (or maybe Object obj) then it will work fine i.e wake up will not be printed and the main thread would wait.

Title: Strange java behavior of wait/notify

Body:
I've found strange behavior of java concurrency. See on the next code below:

public class Test {
    static CountDownLatch latch = new CountDownLatch(1);
    public static void main(String[] args) throws UnsupportedEncodingException, InterruptedException {
        final Thread t = new MyThread();
        t.start();
        synchronized (t) {
            latch.countDown();
            System.out.println("got to sleep");
            t.wait();
            System.out.println("wake up");
        }
    }

    static class MyThread extends Thread {
        @Override
        public void run() {
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (this) {
                System.out.println("inside run");
//                notifyAll();
            }
        }
    }
}

In my point of view this code should be hang up and wait forever, but code is finished without any problem with next out in console:

got to sleep
inside run
wake up

I've tried to find some information about notifying locks if thread is died, but was lack in it.
Also I've not find any information in java specification.

But if I've tried to lock on some other object (not on the thread object) it was work fine as I expected.


问:
Python error:- TypeError: 'Timeout' object is not iterable while using simpy for AllOf
I was making a general simpy program but while making it the document said |,& are replaceable by  AnyOf, AllOf and the question also required us to use the statements rather than the symbols but when tried replacing the symbols with the statement the program started showing the following errors.

```<code>Traceback (most recent call last):
  File "e:\kanu\Coding Languages\VS code\4th semester\Data simulation lab\lab 5\lab_5(statements).py", line 6, in test_condition
    ret = yield simpy.AnyOf(t1 , t2)
  File "C:\Users\kanu\AppData\Local\Programs\Python\Python310\lib\site-packages\simpy\events.py", line 637, in __init__
    super().__init__(env, Condition.any_events, events)
  File "C:\Users\kanu\AppData\Local\Programs\Python\Python310\lib\site-packages\simpy\events.py", line 520, in __init__
    self._events = tuple(events)
TypeError: 'Timeout' object is not iterable

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "e:\kanu\Coding Languages\VS code\4th semester\Data simulation lab\lab 5\lab_5(statements).py", line 22, in <module>
    env.run()
  File "C:\Users\kanu\AppData\Local\Programs\Python\Python310\lib\site-packages\simpy\core.py", line 254, in run
    self.step()
  File "C:\Users\kanu\AppData\Local\Programs\Python\Python310\lib\site-packages\simpy\core.py", line 206, in step
    raise exc
TypeError: 'Timeout' object is not iterable
</code>```

these errors oucred in the following code: -

```<code>import simpy

def test_condition(env):
  t1, t2 = env.timeout(1, value='spam'), env.timeout(2, value='eggs')
  ret = yield simpy.AnyOf(t1 , t2)
  #assert ret == {t1: 'spam'}
  print(ret)

  t1, t2 = env.timeout(1, value='spam'), env.timeout(2, value='eggs')
  ret = yield t1 & t2
  #assert ret == {t1: 'spam', t2: 'eggs'}
  print(ret)

  e1, e2, e3 = [env.timeout(i) for i in range(3)]
  ret = yield simpy.AllOf( simpy.AnyOf ( e1,  e2),  e3)
  print(all(e.processed for e in [e1, e2, e3]))

env = simpy.Environment()
proc = env.process(test_condition(env))
env.run()
</code>```

答:
it seems you havn't send env parameter to the function, using following code:

```<code>t1, t2 = env.timeout(1, value='spam'), env.timeout(2, value='eggs')
ret = yield simpy.AnyOf(env=env, events=[t1 , t2]) # pay attentions here!!!
</code>```

what your code makes AnyOf function treat t1 as env and t2 as events and causing the error, for t2 is a Timeout instead of array.

Body:
I was making a general simpy program but while making it the document said |,& are replaceable by  AnyOf, AllOf and the question also required us to use the statements rather than the symbols but when tried replacing the symbols with the statement the program started showing the following errors.

Traceback (most recent call last):
  File "e:\kanu\Coding Languages\VS code\4th semester\Data simulation lab\lab 5\lab_5(statements).py", line 6, in test_condition
    ret = yield simpy.AnyOf(t1 , t2)
  File "C:\Users\kanu\AppData\Local\Programs\Python\Python310\lib\site-packages\simpy\events.py", line 637, in __init__
    super().__init__(env, Condition.any_events, events)
  File "C:\Users\kanu\AppData\Local\Programs\Python\Python310\lib\site-packages\simpy\events.py", line 520, in __init__
    self._events = tuple(events)
TypeError: 'Timeout' object is not iterable

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "e:\kanu\Coding Languages\VS code\4th semester\Data simulation lab\lab 5\lab_5(statements).py", line 22, in <module>
    env.run()
  File "C:\Users\kanu\AppData\Local\Programs\Python\Python310\lib\site-packages\simpy\core.py", line 254, in run
    self.step()
  File "C:\Users\kanu\AppData\Local\Programs\Python\Python310\lib\site-packages\simpy\core.py", line 206, in step
    raise exc
TypeError: 'Timeout' object is not iterable

these errors oucred in the following code: -

import simpy

def test_condition(env):
  t1, t2 = env.timeout(1, value='spam'), env.timeout(2, value='eggs')
  ret = yield simpy.AnyOf(t1 , t2)
  #assert ret == {t1: 'spam'}
  print(ret)

  t1, t2 = env.timeout(1, value='spam'), env.timeout(2, value='eggs')
  ret = yield t1 & t2
  #assert ret == {t1: 'spam', t2: 'eggs'}
  print(ret)

  e1, e2, e3 = [env.timeout(i) for i in range(3)]
  ret = yield simpy.AllOf( simpy.AnyOf ( e1,  e2),  e3)
  print(all(e.processed for e in [e1, e2, e3]))

env = simpy.Environment()
proc = env.process(test_condition(env))
env.run()

Body:
it seems you havn't send env parameter to the function, using following code:

t1, t2 = env.timeout(1, value='spam'), env.timeout(2, value='eggs')
ret = yield simpy.AnyOf(env=env, events=[t1 , t2]) # pay attentions here!!!

what your code makes AnyOf function treat t1 as env and t2 as events and causing the error, for t2 is a Timeout instead of array.


问:
Invalid Keystore Format while signing the react native app
I have developed a react native application. I am trying to push it to google playstore. I am following the same steps mentioned in react native official doc https://reactnative.dev/docs/signed-apk-android, and generated a kestore file called wings-prod.keystore file.

When I try signing the app using ./gradlew signingReport I am getting Invalid keystore format format. Can someone help with this?

```<code>Error: Failed to read key wings-prod from store "/Users/asrinivasarao/Projects/winggs-app/winggs-customer/winggs/android/app/wings-prod.keystore": Invalid keystore format
</code>```

答:
Try:

The command for generating a keystore file is (
Remember to run this command in the android/app directory, atleast if you are on a mac.)

keytool -genkey -v -keystore release.keystore -storepass android -alias androidreleasekey -keypass android -keyalg RSA -keysize 2048 -validity 10000
```
<p>On Windows:
The keytool must be run from C:\Program Files\Java\jdkx.x.x_x\bin</p>
<p>Follow the official guide</p>
<p>Also, keep in mind that it should be the same key, if you have already published the app to the play store.</p>
<h2>If any of the above does not work:</h2>
<ol>
<li>try deleting the .gradle file and running the</li>
</ol>
<pre class="lang-sh prettyprint-override"><code>./gradlew clean
</code>```

Check the Java Version if it is the same at

```<code>D:\Program Files\Java\
</code>```

and

```<code>D:\Program Files\Android\Android Studio\jre
</code>```

Additionally check if you are running on JDK11 if you are on react native 0.65 and above.

Body:
I have developed a react native application. I am trying to push it to google playstore. I am following the same steps mentioned in react native official doc https://reactnative.dev/docs/signed-apk-android, and generated a kestore file called wings-prod.keystore file.

When I try signing the app using ./gradlew signingReport I am getting Invalid keystore format format. Can someone help with this?

Error: Failed to read key wings-prod from store "/Users/asrinivasarao/Projects/winggs-app/winggs-customer/winggs/android/app/wings-prod.keystore": Invalid keystore format

Body:
Try:

The command for generating a keystore file is (
Remember to run this command in the android/app directory, atleast if you are on a mac.)

keytool -genkey -v -keystore release.keystore -storepass android -alias androidreleasekey -keypass android -keyalg RSA -keysize 2048 -validity 10000

On Windows:
The keytool must be run from C:\Program Files\Java\jdkx.x.x_x\bin

Follow the official guide

Also, keep in mind that it should be the same key, if you have already published the app to the play store.

If any of the above does not work:

try deleting the .gradle file and running the

./gradlew clean

Check the Java Version if it is the same at

D:\Program Files\Java\

and

D:\Program Files\Android\Android Studio\jre

Additionally check if you are running on JDK11 if you are on react native 0.65 and above.


问:
Saving fingerprint data into database
I am creating an android project for my college, and there I want to make something like fingerprint attendance system using mobile fingerprint sensor, so actually I want to save biometric data into database for further reference during attendance.
I want to save fingerprint data into MS SQL database which is taken from the mobile fingerprint sensor.</p>

答:
You cannot store/collect fingerprint image/data from android's fingerprint sensor. The fingerprint data is encrypted on the file system (Trusted Execution Environment).

All you can do is, authenticate the user if the fingerprint is registered on the device

Title: Saving fingerprint data into database


问:
Using Spring IoC to set up enum values
Is there a way to set up such enum values via Spring IoC at construction time?

What I would like to do is to inject, at class load time, values that are hard-coded in the code snippet below:

```<code>public enum Car
{
        NANO ("Very Cheap", "India"),
        MERCEDES ("Expensive", "Germany"),
        FERRARI ("Very Expensive", "Italy");

        public final String cost;
        public final String madeIn;

        Car(String cost, String madeIn)
        {
                this.cost= cost;
                this.madeIn= madeIn;
        }

}
</code>```

Let's say that the application must be deployed in Germany, where Nanos are "Nearly free", or in India where Ferraris are "Unaffordable". In both countries, there are only three cars (deterministic set), no more no less, hence an enum, but their "inner" values may differ. So, this is a case of contextual initialization of immutables.

答:
```<code><bean id="car" class="Foo">
    <property name="carString" value="NANO" />
</bean>
</code>```

And then in your class Foo, you would have this setter:

```<code>public void setCar(String carString) {
    this.carString = Car.valueOf(carString);
}
</code>```

OwnerDisplayName: Olivier

Title: Using Spring IoC to set up enum values

Body:
Is there a way to set up such enum values via Spring IoC at construction time?

What I would like to do is to inject, at class load time, values that are hard-coded in the code snippet below:

public enum Car
{
        NANO ("Very Cheap", "India"),
        MERCEDES ("Expensive", "Germany"),
        FERRARI ("Very Expensive", "Italy");

        public final String cost;
        public final String madeIn;

        Car(String cost, String madeIn)
        {
                this.cost= cost;
                this.madeIn= madeIn;
        }

}

Let's say that the application must be deployed in Germany, where Nanos are "Nearly free", or in India where Ferraris are "Unaffordable". In both countries, there are only three cars (deterministic set), no more no less, hence an enum, but their "inner" values may differ. So, this is a case of contextual initialization of immutables.

LastEditorDisplayName: Olivier

Body:
<bean id="car" class="Foo">
    <property name="carString" value="NANO" />
</bean>

And then in your class Foo, you would have this setter:

public void setCar(String carString) {
    this.carString = Car.valueOf(carString);
}

OwnerDisplayName: Greg Noe

ContentLicense: CC BY-SA 2.5


问:
How can you upload files as a []byte in go?
I would like to use golang post request, upload pictures, but I do not want to pass filepath, just want to pass [] byte
The following article are not what I need because they are used os.Open
golang POST data using the Content-Type multipart/form-data</p>

```<code>func Upload(url, file string) (err error) {
    // Prepare a form that you will submit to that URL.
    var b bytes.Buffer
    w := multipart.NewWriter(&b)
    // Add your image file
    f, err := os.Open(file)
    if err != nil {
        return
    }
    defer f.Close()
    fw, err := w.CreateFormFile("image", file)
    if err != nil {
        return
    }
    if _, err = io.Copy(fw, f); err != nil {
        return
    }
    // Add the other fields
    if fw, err = w.CreateFormField("key"); err != nil {
        return
    }
    if _, err = fw.Write([]byte("KEY")); err != nil {
        return
    }
    // Don't forget to close the multipart writer.
    // If you don't close it, your request will be missing the terminating boundary.
    w.Close()

    // Now that you have a form, you can submit it to your handler.
    req, err := http.NewRequest("POST", url, &b)
    if err != nil {
        return
    }
    // Don't forget to set the content type, this will contain the boundary.
    req.Header.Set("Content-Type", w.FormDataContentType())

    // Submit the request
    client := &http.Client{}
    res, err := client.Do(req)
    if err != nil {
        return
    }

    // Check the response
    if res.StatusCode != http.StatusOK {
        err = fmt.Errorf("bad status: %s", res.Status)
    }
    return
}
</code>```

答:
Since you use

```<code>if _, err = io.Copy(fw, f); err != nil {
    return
}
</code>```

You may as well edit your code to:

Add new import: "bytes"

Change the method signature to func Upload(url string, file []byte) (err error)

Use io.Copy(fw, bytes.NewReader(f))

Body:
I would like to use golang post request, upload pictures, but I do not want to pass filepath, just want to pass [] byte
The following article are not what I need because they are used os.Open
golang POST data using the Content-Type multipart/form-data

func Upload(url, file string) (err error) {
    // Prepare a form that you will submit to that URL.
    var b bytes.Buffer
    w := multipart.NewWriter(&b)
    // Add your image file
    f, err := os.Open(file)
    if err != nil {
        return
    }
    defer f.Close()
    fw, err := w.CreateFormFile("image", file)
    if err != nil {
        return
    }
    if _, err = io.Copy(fw, f); err != nil {
        return
    }
    // Add the other fields
    if fw, err = w.CreateFormField("key"); err != nil {
        return
    }
    if _, err = fw.Write([]byte("KEY")); err != nil {
        return
    }
    // Don't forget to close the multipart writer.
    // If you don't close it, your request will be missing the terminating boundary.
    w.Close()

    // Now that you have a form, you can submit it to your handler.
    req, err := http.NewRequest("POST", url, &b)
    if err != nil {
        return
    }
    // Don't forget to set the content type, this will contain the boundary.
    req.Header.Set("Content-Type", w.FormDataContentType())

    // Submit the request
    client := &http.Client{}
    res, err := client.Do(req)
    if err != nil {
        return
    }

    // Check the response
    if res.StatusCode != http.StatusOK {
        err = fmt.Errorf("bad status: %s", res.Status)
    }
    return
}

Body:
Since you use

if _, err = io.Copy(fw, f); err != nil {
    return
}

You may as well edit your code to:

Add new import: "bytes"

Change the method signature to func Upload(url string, file []byte) (err error)

Use io.Copy(fw, bytes.NewReader(f))


问:
How to solve local variable error with forloop in django?
Info: I want to get data from context. The context data is coming from for loop function.

Problem: I am getting this UnboundLocalError local variable 'context' referenced before assignment

```<code>def CurrentMatch(request, match_id):
    match = Match.objects.get(id=match_id)
    match_additional = MatchAdditional.objects.get(match=match)
    innings = match_additional.current_innings

    recent = Score.objects.filter(match=match).filter(innings=innings).order_by('over_number')[::-1][:1]

    for score in recent:
        context = {
            "ball_number": score.ball_number,
            "over_number": score.over_number,
        }

    return HttpResponse(json.dumps(context))
</code>```

答:
You should do something like this  :</p>
```<code>def CurrentMatch(request, match_id):
    match = Match.objects.get(id=match_id)
    match_additional = MatchAdditional.objects.get(match=match)
    innings = match_additional.current_innings

    recent = Score.objects.filter(match=match).filter(innings=innings).order_by('over_number')[::-1][:1]
    if recent:
        for score in recent:
            context = {
                "ball_number": score.ball_number,
                "over_number": score.over_number,
            }
        return HttpResponse(json.dumps(context))
    else:
        return HttpResponse(json.dumps({}))
</code>```

Body:
Info: I want to get data from context. The context data is coming from for loop function.

Problem: I am getting this UnboundLocalError local variable 'context' referenced before assignment

def CurrentMatch(request, match_id):
    match = Match.objects.get(id=match_id)
    match_additional = MatchAdditional.objects.get(match=match)
    innings = match_additional.current_innings

    recent = Score.objects.filter(match=match).filter(innings=innings).order_by('over_number')[::-1][:1]

    for score in recent:
        context = {
            "ball_number": score.ball_number,
            "over_number": score.over_number,
        }

    return HttpResponse(json.dumps(context))

Body:
You should do something like this  :

def CurrentMatch(request, match_id):
    match = Match.objects.get(id=match_id)
    match_additional = MatchAdditional.objects.get(match=match)
    innings = match_additional.current_innings

    recent = Score.objects.filter(match=match).filter(innings=innings).order_by('over_number')[::-1][:1]
    if recent:
        for score in recent:
            context = {
                "ball_number": score.ball_number,
                "over_number": score.over_number,
            }
        return HttpResponse(json.dumps(context))
    else:
        return HttpResponse(json.dumps({}))


问:
Why doesn't TypeApplications allow partially applied type synonyms to be used
I did some search and thought that LiberalTypeSynonyms would allow it. It would allow to use partially applied type synonyms as argument to Type in some cases.

```<code>{-# LANGUAGE LiberalTypeSynonyms #-}

type Value a = ExceptT [a] Identity a
type Apply m a = m a
run1 :: Apply Value a -> IO ()
run1 e = undefined
</code>```

But the following does not work in TypeApplications, why and is it possible to make it compiled?

```<code>{-# LANGUAGE LiberalTypeSynonyms #-}
{-# LANGUAGE TypeApplications #-}

type Value a = ExceptT [a] Identity a

run :: m Int -> IO ()
run e = undefined

main :: IO ()
main = do
    print "begin"
    let a = run @Value
    print "end"
</code>```

The above code does not compile due to the error

```<code>    • The type synonym ‘Value’ should have 1 argument, but has been given none
    • In the expression: run @Value
      In an equation for ‘a’: a = run @Value
      In the expression:
        do print "begin"
           let a = run @Value
           print "end"
   |
30 |     let a = run @Value
</code>```

答:
This doesn't have much to do with -XTypeApplications. Haskell generally doesn't allow type synonyms to be used without completely applied arguments. All that -XLiberalTypeSynonyms does is circumventing this in case it's possible to inline an entire expression – e.g. if you have

```<code>{-# LANGUAGE LiberalTypeSynonyms #-}

type IntApplied f = f Int
type List a = [a]

foo :: IntApplied List
foo = [1,2,3]
</code>```

In this case, the type synonyms can just be substituted right there and then to foo :: [Int], before any type checking or instance resolution happens. It's like something a simple macro processor could do.

But in your case you're trying to pass an incomplete type synonym to something else as-is. run can't know whether or not the type variable it receives can be “inlined” this way, but it would in general need to be able to match on this variable, and that's just not possible on general type-level functions (as you can define with type synonyms/families), it's only possible on type constructors.

See https://github.com/ghc-proposals/ghc-proposals/blob/master/proposals/0242-unsaturated-type-families.rst for how Haskell is moving forwards in this subject.

Body:
I did some search and thought that LiberalTypeSynonyms would allow it. It would allow to use partially applied type synonyms as argument to Type in some cases.

{-# LANGUAGE LiberalTypeSynonyms #-}

type Value a = ExceptT [a] Identity a
type Apply m a = m a
run1 :: Apply Value a -> IO ()
run1 e = undefined

But the following does not work in TypeApplications, why and is it possible to make it compiled?

{-# LANGUAGE LiberalTypeSynonyms #-}
{-# LANGUAGE TypeApplications #-}

type Value a = ExceptT [a] Identity a

run :: m Int -> IO ()
run e = undefined

main :: IO ()
main = do
    print "begin"
    let a = run @Value
    print "end"

The above code does not compile due to the error

    • The type synonym ‘Value’ should have 1 argument, but has been given none
    • In the expression: run @Value
      In an equation for ‘a’: a = run @Value
      In the expression:
        do print "begin"
           let a = run @Value
           print "end"
   |
30 |     let a = run @Value

Body:
This doesn't have much to do with -XTypeApplications. Haskell generally doesn't allow type synonyms to be used without completely applied arguments. All that -XLiberalTypeSynonyms does is circumventing this in case it's possible to inline an entire expression – e.g. if you have

{-# LANGUAGE LiberalTypeSynonyms #-}

type IntApplied f = f Int
type List a = [a]

foo :: IntApplied List
foo = [1,2,3]

In this case, the type synonyms can just be substituted right there and then to foo :: [Int], before any type checking or instance resolution happens. It's like something a simple macro processor could do.

But in your case you're trying to pass an incomplete type synonym to something else as-is. run can't know whether or not the type variable it receives can be “inlined” this way, but it would in general need to be able to match on this variable, and that's just not possible on general type-level functions (as you can define with type synonyms/families), it's only possible on type constructors.

See https://github.com/ghc-proposals/ghc-proposals/blob/master/proposals/0242-unsaturated-type-families.rst for how Haskell is moving forwards in this subject.


问:
Fix: React Native App error: "Task :app:processDebugMainManifest FAILED" with jdk17
I had problems setting up the updated environment for app development with RN.

openjdk version "17.0.1" / node 16+

If you're having the same problem, here's how to solve it:

Error Execution failed for task ':app:processDebugMainManifest'.

答:
it took me a while to get to this direct answer, everything from react-native is hard to find.

I'm use jdk16, and just add line in /android/gradle.properties works!


问:
Cannot read properties of undefined (reading 'name') / (reading 'location')
how to solve this error with 'Cannot read properties of undefined (reading 'name')' and the same with (reading 'location'), I don't understand.

Swagger : https://test-front.framework.team/api-docs/#/%2Flocations/locations

codesandbox: https://codesandbox.io/s/elem-1f5t5

I want the item blocks to be displayed correctly, with all the information I get from the API

```<code>import "./styles.css";
    import { useEffect, useState } from "react";

const App = () => {
  const baseURL = "https://test-front.framework.team/";
  const [items, setItems] = useState([]);
  const [authors, setAuthors] = useState([]);
  const [locations, setLocations] = useState([]);

  useEffect(() => {
    fetch("https://test-front.framework.team/paintings")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result);
          console.log("paintings");
        }
      );
    fetch("https://test-front.framework.team/authors")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setAuthors(result);
          console.log("authors");
        }
      );
    fetch("https://test-front.framework.team/locations")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setLocations(result);
          console.log("locations");
        }
      );
  }, []);

  const result = items.map((elem) => {
    return {
      author: authors.find((author) => author.id === elem.authorId).name,
      created: elem.created,
      id: elem.id,
      imgUrl: elem.imgUrl,
      location: locations.find((location) => location.id === elem.locationId)
        .location,
      name: elem.name
    };
  });

  return (
    <div className="App">
      {result.map((elem) => (
        <div key={elem.id} className={"item"}>
          <img src={`${baseURL}${elem.imageUrl}`} />
          <li className={"cardInfo"}>
            <ul>{elem.name}</ul>
            <ul> {elem.author}</ul>
            <ul>{elem.created}</ul>
            <ul>{elem.location}</ul>
          </li>
        </div>
      ))}
    </div>
  );
};

export default App;
</code>```

答:
There is an issue with getting the value for image element from items array to result. I have updated your code sandbox and all the required attributes are displaying correctly.
Please verify.</p>

Body:
how to solve this error with 'Cannot read properties of undefined (reading 'name')' and the same with (reading 'location'), I don't understand.

Swagger : https://test-front.framework.team/api-docs/#/%2Flocations/locations

codesandbox: https://codesandbox.io/s/elem-1f5t5

I want the item blocks to be displayed correctly, with all the information I get from the API

import "./styles.css";
    import { useEffect, useState } from "react";

const App = () => {
  const baseURL = "https://test-front.framework.team/";
  const [items, setItems] = useState([]);
  const [authors, setAuthors] = useState([]);
  const [locations, setLocations] = useState([]);

  useEffect(() => {
    fetch("https://test-front.framework.team/paintings")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result);
          console.log("paintings");
        }
      );
    fetch("https://test-front.framework.team/authors")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setAuthors(result);
          console.log("authors");
        }
      );
    fetch("https://test-front.framework.team/locations")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setLocations(result);
          console.log("locations");
        }
      );
  }, []);

  const result = items.map((elem) => {
    return {
      author: authors.find((author) => author.id === elem.authorId).name,
      created: elem.created,
      id: elem.id,
      imgUrl: elem.imgUrl,
      location: locations.find((location) => location.id === elem.locationId)
        .location,
      name: elem.name
    };
  });

  return (

      {result.map((elem) => (

          <img src={`${baseURL}${elem.imageUrl}`} />

{elem.name}

 {elem.author}

{elem.created}

{elem.location}

      ))}

  );
};

export default App;


问:
Flutter + firebase: Configure app to use local firebase emulator
I have configured firebase to run locally for debugging using the emulator by following this link.

Now I want to be able to run my app connected to the localhost for debugging triggers as well. Is there a way to achieve this by configuring my flutter app to use the localhost?

My emulator is running as following:

答:
My init function looks like so:

init_firebase.dart

```<code>Future<void> initFirebase() async {
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  if (!kReleaseMode) {
    try {
      await Future.wait([
        FirebaseAuth.instance.useAuthEmulator('localhost', 9099),
        FirebaseStorage.instance.useStorageEmulator('localhost', 9199),
      ]);

      FirebaseFunctions.instance.useFunctionsEmulator('localhost', 5001);
      FirebaseFirestore.instance.useFirestoreEmulator('localhost', 8080);
    } catch (e) {}
  }
}
</code>```

By using !kReleaseMode, we don't have to have a boolean that we switch each time. It will just use emulator by default during development

By wrapping it in try-catch block we avoid some errors from hot reload

Body:
My init function looks like so:

init_firebase.dart

Future<void> initFirebase() async {
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  if (!kReleaseMode) {
    try {
      await Future.wait([
        FirebaseAuth.instance.useAuthEmulator('localhost', 9099),
        FirebaseStorage.instance.useStorageEmulator('localhost', 9199),
      ]);

      FirebaseFunctions.instance.useFunctionsEmulator('localhost', 5001);
      FirebaseFirestore.instance.useFirestoreEmulator('localhost', 8080);
    } catch (e) {}
  }
}

By using !kReleaseMode, we don't have to have a boolean that we switch each time. It will just use emulator by default during development

By wrapping it in try-catch block we avoid some errors from hot reload