问:
TypeError: props.routes.map is not a function
I'm new to react-redux. I am trying to pull data from Asp.Net Core Web Api to my react project.

I get an error when mapping the data I receive with redux in react.

I see the data coming in redux DevTools. State is filling up.

```<code>import React, { useEffect } from "react";
import * as actions from "../redux/actions/routeActions";
import { connect } from "react-redux";
import PropTypes from 'prop-types'

function Data({ ...props }) {
  useEffect(() => {
    props.fetchRoutes();
  });

    function renderData() {
        return props.routes.map((route) => {
            const { id, departureLocation, arrivalLocation, distance } = route
            return (
                <tr key={id}>
                    <td>{id}</td>
                    <td>{departureLocation}</td>
                    <td>{arrivalLocation}</td>
                    <td>{distance}</td>
                </tr>
            )
        })
    }
    return(
        < div >
            <table className="table">
                <thead>
                    <tr>
                        <th />
                        <th>departureLocation</th>
                        <th>arrivalLocation</th>
                        <th>Distance</th>
                    </tr>
                </thead>
                <tbody>
                    {renderData()}
                </tbody>
            </table>
        </div >
    );
}

Data.propTypes = {
    routes: PropTypes.array.isRequired
}

const mapStateToProps = (state) => ({
  routes: state.routes,
});

const mapDispatchToProps = {
  fetchRoutes: actions.fetchAll,
};

export default connect(mapStateToProps, mapActionToProps)(Data);
</code>```

And i get this error.

```<code>TypeError: props.routes.map is not a function.
</code>```

I couldn't find where I made a mistake.

答:
Careful as you are fetching your routes in an effect without dependencies.

useEffect(() => {
  props.fetchRoutes();
});
```

<p>This might enter an infinite loop as you are fetching routes every time your component re-renders.</p>

<p>To ensure that does not happen add a <code>dependency</code> to the <code>useEffect</code>:</p>

<pre class="lang-js prettyprint-override"><code>useEffect(() => {
  props.fetchRoutes();
}, [props.fetchRoutes]);
</code>```

This will only enter the useEffect (besides the first render) whenever the fetchRoutes variables changes, which should once at a maximum. You could use [] to do it like it was ComponentDidMount. If you're using react hooks eslint it won't let you without a warning though. You can read more about the useEffect hook here.

Regarding the not a function part, the reason is likely to be that your data still isn't there when the first render happens (as you still need to fetch your data) and therefore it will try to do a map of an undefined.

As said in other comments one option is to only map through the variable if the variable has any value. The other would be to destructure your props and default the variable to [].

function Data({ fetchRoutes, routes = [] }) {
  ...
}
```

This way you also won't need the props. part.

Body:
I'm new to react-redux. I am trying to pull data from Asp.Net Core Web Api to my react project.

I get an error when mapping the data I receive with redux in react.

I see the data coming in redux DevTools. State is filling up.

import React, { useEffect } from "react";
import * as actions from "../redux/actions/routeActions";
import { connect } from "react-redux";
import PropTypes from 'prop-types'

function Data({ ...props }) {
  useEffect(() => {
    props.fetchRoutes();
  });

    function renderData() {
        return props.routes.map((route) => {
            const { id, departureLocation, arrivalLocation, distance } = route
            return (

                    {id}
                    {departureLocation}
                    {arrivalLocation}
                    {distance}

            )
        })
    }
    return(

                        departureLocation
                        arrivalLocation
                        Distance

                    {renderData()}

    );
}

Data.propTypes = {
    routes: PropTypes.array.isRequired
}

const mapStateToProps = (state) => ({
  routes: state.routes,
});

const mapDispatchToProps = {
  fetchRoutes: actions.fetchAll,
};

export default connect(mapStateToProps, mapActionToProps)(Data);

And i get this error.

TypeError: props.routes.map is not a function.

I couldn't find where I made a mistake.

Body:
Careful as you are fetching your routes in an effect without dependencies.

useEffect(() => {
  props.fetchRoutes();
});

This might enter an infinite loop as you are fetching routes every time your component re-renders.

To ensure that does not happen add a dependency to the useEffect:

useEffect(() => {
  props.fetchRoutes();
}, [props.fetchRoutes]);

This will only enter the useEffect (besides the first render) whenever the fetchRoutes variables changes, which should once at a maximum. You could use [] to do it like it was ComponentDidMount. If you're using react hooks eslint it won't let you without a warning though. You can read more about the useEffect hook here.

Regarding the not a function part, the reason is likely to be that your data still isn't there when the first render happens (as you still need to fetch your data) and therefore it will try to do a map of an undefined.

As said in other comments one option is to only map through the variable if the variable has any value. The other would be to destructure your props and default the variable to [].

function Data({ fetchRoutes, routes = [] }) {
  ...
}

This way you also won't need the props. part.


来源: stackexchange

问:
Javascript, Ajax : Bad Request 400
I'm working on ASP Net Core Project and I'm trying to send to my controller with JQuery Ajax function from a partial view modal, parameters.

The recovered URL is correct for example : http://localhost:44321/Validations/ValidationRefuse?ficheId=24&commentaire=Commentaire%20de%20test

But it's always :
Failed to load resource: the server responded with a status of 400 (Bad Request)

My Javascript :

```<code>    $("#buttonRefusFiche").click(function (e) {
        ficheId = $("#ficheId").val();
        commentaire = $("#inputCommentaire").val();
        $.ajax({
            url: "/Validations/ValidationRefuse?ficheId=" + ficheId + "&commentaire" + commentaire,
            type: 'POST',
            contentType: 'application/html',
            cache: true,
            success: function () {
                alert("Validation refusée.");
            },
            error: function () {
            }
        })
    });
</code>```

My C# method :

```<code>        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> ValidationRefuse(int ficheId, string commentaire)
        { ... }

</code>```

My Partial View :

```<code>
<div class="modal-header">
    <h5 class="modal-title" id="exampleModalLongTitle">Validez-vous cette fiche ?</h5>
    <button type="button" class="btn btn-outline-dark btn-circle" data-dismiss="modal" aria-label="Close">
        <i class="fa fa-close"></i>
    </button>
</div>
<form asp-controller="Validations" asp-action="ValidationParResponsable" asp-route-id="@Model.FicheId" asp-route-eId="@Model.EnseignantId">
    <div class="modal-body">
        <div class="form-group">
            <input type="hidden" id="ficheId" asp-for="FicheId" />
            <input type="hidden" asp-for="EnseignantId" />
            <input type="hidden" asp-for="EtatId" />
            <label class="control-label font-weight-bold">Commentaire :</label>
            <textarea class="form-control" id="inputCommentaire" asp-for="Commentaire" placeholder="Votre commentaire"></textarea>
        </div>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-danger" id="buttonRefusFiche">Refuser</button>
        <button type="submit" class="btn btn-success">Valider</button>
    </div>
</form>
</code>```

I hope it's understandable, thanks for your responses. :)

答:
When you use a POST request you have to send the parameters in the body of the request, not in the URL like that :

```<code>  $("#buttonRefusFiche").click(function (e) {
            ficheId = $("#ficheId").val();
            commentaire = $("#inputCommentaire").val();
            $.ajax({
                url: "/Validations/ValidationRefuse",
                type: 'POST',
                contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                dataType : "html",
                data : {
                    ficheId : ficheId,
                    commentaire : commentaire
                },
                cache: true,
                success: function () {
                    alert("Validation refusée.");
                },
                error: function () {
                }
            })
        });
</code>```

I also changed the contentType and added dataType.

For more information about ajax Post see documentation

ContentLicense: CC BY-SA 4.0

Title: Javascript, Ajax : Bad Request 400

Body:
I'm working on ASP Net Core Project and I'm trying to send to my controller with JQuery Ajax function from a partial view modal, parameters.

The recovered URL is correct for example : http://localhost:44321/Validations/ValidationRefuse?ficheId=24&commentaire=Commentaire%20de%20test

But it's always :
Failed to load resource: the server responded with a status of 400 (Bad Request)

My Javascript :

    $("#buttonRefusFiche").click(function (e) {
        ficheId = $("#ficheId").val();
        commentaire = $("#inputCommentaire").val();
        $.ajax({
            url: "/Validations/ValidationRefuse?ficheId=" + ficheId + "&commentaire" + commentaire,
            type: 'POST',
            contentType: 'application/html',
            cache: true,
            success: function () {
                alert("Validation refusée.");
            },
            error: function () {
            }
        })
    });

My C# method :

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> ValidationRefuse(int ficheId, string commentaire)
        { ... }

My Partial View :

Validez-vous cette fiche ?

    <button type="button" class="btn btn-outline-dark btn-circle" data-dismiss="modal" aria-label="Close">

    </button>

<form asp-controller="Validations" asp-action="ValidationParResponsable" asp-route-id="@Model.FicheId" asp-route-eId="@Model.EnseignantId">

            <input type="hidden" id="ficheId" asp-for="FicheId" />
            <input type="hidden" asp-for="EnseignantId" />
            <input type="hidden" asp-for="EtatId" />
            Commentaire :
            <textarea class="form-control" id="inputCommentaire" asp-for="Commentaire" placeholder="Votre commentaire"></textarea>

        <button type="button" class="btn btn-danger" id="buttonRefusFiche">Refuser</button>
        <button type="submit" class="btn btn-success">Valider</button>

</form>

I hope it's understandable, thanks for your responses. :)

Body:
When you use a POST request you have to send the parameters in the body of the request, not in the URL like that :

  $("#buttonRefusFiche").click(function (e) {
            ficheId = $("#ficheId").val();
            commentaire = $("#inputCommentaire").val();
            $.ajax({
                url: "/Validations/ValidationRefuse",
                type: 'POST',
                contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                dataType : "html",
                data : {
                    ficheId : ficheId,
                    commentaire : commentaire
                },
                cache: true,
                success: function () {
                    alert("Validation refusée.");
                },
                error: function () {
                }
            })
        });

I also changed the contentType and added dataType.

For more information about ajax Post see documentation


问:
R: Create Indicator Columns from list of conditions
I have a dataframe and a number of conditions. Each condition is supposed to check whether the value in a certain column of the dataframe is within a set of valid values.

This is what I tried:

```<code># create the sample dataframe
age <- c(120, 45)
sex <- c("x", "f")

df <-data.frame(age, sex)

# create the sample conditions
conditions <- list(
  list("age", c(18:100)),
  list("sex", c("f", "m"))
)

addIndicator <- function (df, columnName, validValues) {
  indicator <- vector()

  for (row in df[, toString(columnName)]) {
    # for some strange reason, %in% doesn't work correctly here, but always returns FALSe
    indicator <- append(indicator, row %in% validValues)
  }
  df <- cbind(df, indicator)

  # rename the column
  names(df)[length(names(df))] <- paste0("I_", columnName)

  return(df)
}

for (condition in conditions){
  columnName <- condition[1]
  validValues <- condition[2]
  df <- addIndicator(df, columnName, validValues)
}

print(df)
</code>```

However, this leads to all conditions considered not to be met - which is not what I expect:

```<code>  age sex I_age I_sex
1 120   x FALSE FALSE
2  45   f FALSE FALSE
</code>```

I figured that %in% does not return the expected result. I checked for the typeof(row) and tried to boil this down into a minimum example. In a simple ME, with the same type and values of the variables, the %in% works properly. So, something must be wrong within the context I try to apply this. Since this is my first attempt to write anything in R, I am stuck here.

What am I doing wrong and how can I achieve what I want?

答:
If you prefer an approach that uses the tidyverse family of packages:

```<code>library(tidyverse)

allowed_values <- list(age = 18:100, sex = c("f", "m"))

df %>%
  imap_dfr(~ .x %in% allowed_values[[.y]]) %>%
  rename_with(~ paste0('I_', .x)) %>%
  bind_cols(df)
</code>```

imap_dfr allows you to manipulate each column in df using a lambda function. .x references the column content and .y references the name.

rename_with renames the columns using another lambda function and bind_cols combines the results with the original dataframe.

I borrowed the simplified list of conditions from ben's answer. I find my approach slightly more readable but that is a matter of taste and of whether you are already using the tidyverse elsewhere.

Body:
I have a dataframe and a number of conditions. Each condition is supposed to check whether the value in a certain column of the dataframe is within a set of valid values.

This is what I tried:

# create the sample dataframe
age <- c(120, 45)
sex <- c("x", "f")

df <-data.frame(age, sex)

# create the sample conditions
conditions <- list(
  list("age", c(18:100)),
  list("sex", c("f", "m"))
)

addIndicator <- function (df, columnName, validValues) {
  indicator <- vector()

  for (row in df[, toString(columnName)]) {
    # for some strange reason, %in% doesn't work correctly here, but always returns FALSe
    indicator <- append(indicator, row %in% validValues)
  }
  df <- cbind(df, indicator)

  # rename the column
  names(df)[length(names(df))] <- paste0("I_", columnName)

  return(df)
}

for (condition in conditions){
  columnName <- condition[1]
  validValues <- condition[2]
  df <- addIndicator(df, columnName, validValues)
}

print(df)

However, this leads to all conditions considered not to be met - which is not what I expect:

  age sex I_age I_sex
1 120   x FALSE FALSE
2  45   f FALSE FALSE

I figured that %in% does not return the expected result. I checked for the typeof(row) and tried to boil this down into a minimum example. In a simple ME, with the same type and values of the variables, the %in% works properly. So, something must be wrong within the context I try to apply this. Since this is my first attempt to write anything in R, I am stuck here.

What am I doing wrong and how can I achieve what I want?

Body:
If you prefer an approach that uses the tidyverse family of packages:

library(tidyverse)

allowed_values <- list(age = 18:100, sex = c("f", "m"))

df %>%
  imap_dfr(~ .x %in% allowed_values[[.y]]) %>%
  rename_with(~ paste0('I_', .x)) %>%
  bind_cols(df)

imap_dfr allows you to manipulate each column in df using a lambda function. .x references the column content and .y references the name.

rename_with renames the columns using another lambda function and bind_cols combines the results with the original dataframe.

I borrowed the simplified list of conditions from ben's answer. I find my approach slightly more readable but that is a matter of taste and of whether you are already using the tidyverse elsewhere.


问:
How to retrieve items stored with the Remember function in Twilio
I am creating a chat bot with Twilio Autopilot that asks for personal information in the beginning and I would like to much later in the chat give back that information back to verify.

According to the Twilio docs the Remember action can be used to store a key-value pair to be returned later.
I am, however, unable to find any documentation on how to retrieve the data stored later.

I have attempted to use the event.Memory.[keyName] in a function as well as

```<code>memory.twilio.collected_data.[keyName]
</code>```

答:
Things saved with the remember action get put at the top level of the memory object.

You can pull it out with the following:

```<code>JSON.parse(event.Memory)[keyName]
</code>```

Body:
I am creating a chat bot with Twilio Autopilot that asks for personal information in the beginning and I would like to much later in the chat give back that information back to verify.

According to the Twilio docs the Remember action can be used to store a key-value pair to be returned later.
I am, however, unable to find any documentation on how to retrieve the data stored later.

I have attempted to use the event.Memory.[keyName] in a function as well as

memory.twilio.collected_data.[keyName]

Body:
Things saved with the remember action get put at the top level of the memory object.

You can pull it out with the following:

JSON.parse(event.Memory)[keyName]


问:
Get Bitmap from file path which contains whitespaces
I need to display image from bitmap.It work well but when image with white name spaces not getting bitmap.

Following is my method  for getting bitmap from file path.

```<code>var bitmap = MediaStore.Images.Media.getBitmap(
                            mContext.contentResolver,
                            Uri.fromFile(File("" +imagePathCon))
                        )
</code>```

While file with whitespaces name it gives null pointer exception for above line

Thanks

答:
Get the file name from the Uri using the getScheme().

Then remove every whitespace from such a file name. This answer should help: https://stackoverflow.com/a/10944400/8649647

Body:
I need to display image from bitmap.It work well but when image with white name spaces not getting bitmap.

Following is my method  for getting bitmap from file path.

var bitmap = MediaStore.Images.Media.getBitmap(
                            mContext.contentResolver,
                            Uri.fromFile(File("" +imagePathCon))
                        )

While file with whitespaces name it gives null pointer exception for above line

Thanks


问:
cmath header confusion
What is the namespace for math functions? Global or std?

Consider cos function. It has 3 overloads. But there is also legacy cos from math.h. C doesn't know anything about function overloading. Therefore cos(x) can't be resolved to cos(float). The solution is to call the single precision version explicitly cosf(x). Did I miss anything?

答:
The cXXX headers place all their stuff in the std namespace. They may also put them in the global namespace but it's not required.

This is from C++0x, the upcoming standard, section D.7:

2/ Every C header, each of which has a name of the form name.h, behaves as if each name placed in the standard library namespace by the corresponding cname header is placed within the global namespace scope. It is unspecified whether these names are first declared or defined within namespace scope (3.3.6) of the namespace std and are then injected into the global namespace scope by explicit using-declarations (7.3.3).

3/ [ Example: The header <cstdlib> assuredly provides its declarations and definitions within the namespace std. It may also provide these names within the global namespace. The header <stdlib.h> assuredly provides the same declarations and definitions within the global namespace, much as in the C Standard. It may also provide these names within the namespace std. —end example ]

This is unchanged from section D.5 from C++03 (it's made more explicit in the newer standard but the effect is the same):

2/ Every C header, each of which has a name of the form name.h, behaves as if each name placed in the Standard library namespace by the corresponding cname header is also placed within the namespace scope of the namespace std and is followed by an explicit using-declaration.

3/ [Example: The header <cstdlib> provides its declarations and definitions within the namespace std. The header <stdlib.h> makes these available also in the global namespace, much as in the C Standard. —end example]

If you include the 'old-style' XXX.h header, it's placed in both namespaces (in both iterations of the standard).

Title: cmath header confusion

ContentLicense: CC BY-SA 3.0


问:
Public Key of ECC P256K1 in AWS-KMS is 88 bytes?

I am using AWS KMS with ECC_SECG_P256K1 key. When I retreive the
public key via aws-sdk the key is 88 bytes, which suppoed to be 64 bytes (as shown in the code)

Even more the size of signature is varying between 70,71,72, which
means we can't calculate the (r,s) values based on r=[0:32],s=[32,64]

```<code>var kms = new AWS.KMS();

var pubKeyParam = {
  KeyId: 'xxxxxxxx', /* required */
};

kms.getPublicKey(pubKeyParam, function(err, data) {
  if (err) console.log(err, err.stack);
  else
      publicKey = data.PublicKey
      console.log(publicKey.length) <-- 88 bytes not 64 bytes
});
</code>```

Thanks in advance for help

答:
KMS Public Key Parsing

KMS is returning the public key in ASN.1 format.

If you convert the key using publicKeyFromAsn1 here, it returns 64 bytes:

```<code>import * as asn1js from 'asn1js';

function toArrayBuffer(buffer: Buffer): ArrayBuffer {
  const ab = new ArrayBuffer(buffer.length);
  const view = new Uint8Array(ab);
  for (let i = 0; i < buffer.length; ++i) {
    view[i] = buffer[i];
  }
  return ab;
}

// call this with your KMS public key
function publicKeyFromAsn1(buf: Buffer): Buffer {
  const { result } = asn1js.fromBER(toArrayBuffer(buf));
  const values = (result as asn1js.Sequence).valueBlock.value;
  const value = values[1] as asn1js.BitString;
  return Buffer.from(value.valueBlock.valueHex.slice(1));
}

</code>```

KMS Signature Parsing

The KMS Signature is in DER format (which is valid BER).   It ends up looking like this: 30440220{r}0220{s}  Here is some parsing logic to help you extract r & s.

```<code>import * as asn1js from 'asn1js';

function toArrayBuffer(buffer: Buffer): ArrayBuffer {
  const ab = new ArrayBuffer(buffer.length);
  const view = new Uint8Array(ab);
  for (let i = 0; i < buffer.length; ++i) {
    view[i] = buffer[i];
  }
  return ab;
}

//call this with your signature buffer
function parseBERSignature(sig: Buffer): { r: Buffer; s: Buffer } {
  const { result } = asn1js.fromBER(toArrayBuffer(sig));
  const part1 = (result as asn1js.Sequence).valueBlock.value[0] as asn1js.BitString;
  const part2 = (result as asn1js.Sequence).valueBlock.value[1] as asn1js.BitString;

  return {
    r: Buffer.from(part1.valueBlock.valueHex),
    s: Buffer.from(part2.valueBlock.valueHex),
  };
}
</code>```

Body:
I am using AWS KMS with ECC_SECG_P256K1 key. When I retreive the
public key via aws-sdk the key is 88 bytes, which suppoed to be 64 bytes (as shown in the code)

Even more the size of signature is varying between 70,71,72, which
means we can't calculate the (r,s) values based on r=[0:32],s=[32,64]

var kms = new AWS.KMS();

var pubKeyParam = {
  KeyId: 'xxxxxxxx', /* required */
};

kms.getPublicKey(pubKeyParam, function(err, data) {
  if (err) console.log(err, err.stack);
  else
      publicKey = data.PublicKey
      console.log(publicKey.length) <-- 88 bytes not 64 bytes
});

Thanks in advance for help

Body:
KMS Public Key Parsing

KMS is returning the public key in ASN.1 format.

If you convert the key using publicKeyFromAsn1 here, it returns 64 bytes:

import * as asn1js from 'asn1js';

function toArrayBuffer(buffer: Buffer): ArrayBuffer {
  const ab = new ArrayBuffer(buffer.length);
  const view = new Uint8Array(ab);
  for (let i = 0; i < buffer.length; ++i) {
    view[i] = buffer[i];
  }
  return ab;
}

// call this with your KMS public key
function publicKeyFromAsn1(buf: Buffer): Buffer {
  const { result } = asn1js.fromBER(toArrayBuffer(buf));
  const values = (result as asn1js.Sequence).valueBlock.value;
  const value = values[1] as asn1js.BitString;
  return Buffer.from(value.valueBlock.valueHex.slice(1));
}

KMS Signature Parsing

The KMS Signature is in DER format (which is valid BER).   It ends up looking like this: 30440220{r}0220{s}  Here is some parsing logic to help you extract r & s.

import * as asn1js from 'asn1js';

function toArrayBuffer(buffer: Buffer): ArrayBuffer {
  const ab = new ArrayBuffer(buffer.length);
  const view = new Uint8Array(ab);
  for (let i = 0; i < buffer.length; ++i) {
    view[i] = buffer[i];
  }
  return ab;
}

//call this with your signature buffer
function parseBERSignature(sig: Buffer): { r: Buffer; s: Buffer } {
  const { result } = asn1js.fromBER(toArrayBuffer(sig));
  const part1 = (result as asn1js.Sequence).valueBlock.value[0] as asn1js.BitString;
  const part2 = (result as asn1js.Sequence).valueBlock.value[1] as asn1js.BitString;

  return {
    r: Buffer.from(part1.valueBlock.valueHex),
    s: Buffer.from(part2.valueBlock.valueHex),
  };
}


问:
Error message trying to change string to year
I'm trying to combine three fields to make a date, the year is currently string:
code to change string to datetime:

```<code>f2[:,'frt_eli_year'] = pd.to_datetime(f2['frt_eli_year'].astype(str), format='%Y',errors='coerce',utc=True)
</code>```

error message:

```<code>TypeError: unhashable type: 'slice'
</code>```

Then code to join year, month, date:

```<code>f2[:,'test'] = pd.to_datetime(f2['frt_eli_year'].dt.year,f2['frt_eli_year'].dt.month,f2['frt_eli_year'].dt.day)
</code>```

Appreciate the help, thanks!

答:
The mistake is in f2[:,'frt_eli_year']. Check this this answer. Basically it'll work if you change to f2.loc[:,'frt_eli_year'], or or since you want all rows, just f2['frt_eli_year'].

In total:

```<code>f2['frt_eli_year'] = pd.to_datetime(f2['frt_eli_year'],
                                    format='%Y', errors='coerce', utc=True)
</code>```

Body:
I'm trying to combine three fields to make a date, the year is currently string:
code to change string to datetime:

f2[:,'frt_eli_year'] = pd.to_datetime(f2['frt_eli_year'].astype(str), format='%Y',errors='coerce',utc=True)

error message:

TypeError: unhashable type: 'slice'

Then code to join year, month, date:

f2[:,'test'] = pd.to_datetime(f2['frt_eli_year'].dt.year,f2['frt_eli_year'].dt.month,f2['frt_eli_year'].dt.day)

Appreciate the help, thanks!

Body:
The mistake is in f2[:,'frt_eli_year']. Check this this answer. Basically it'll work if you change to f2.loc[:,'frt_eli_year'], or or since you want all rows, just f2['frt_eli_year'].

In total:

f2['frt_eli_year'] = pd.to_datetime(f2['frt_eli_year'],
                                    format='%Y', errors='coerce', utc=True)


问:
How can I find the data parameters required for a requests.post function with a specific URL?
I would like to use the requests library to make a request to a particular webpage, http://latex2png.com/api/convert, in order to convert some latex to a PNG image. However, I am unsure of what data parameters the website accepts.

Is there any way to use the requests library to see which parameters need to be fulfilled?

I've tried running

options = {
    "auth": {"user": "guest", "password": "guest"},
    "latex": '$a^3$',
    "resolution": 900,
    "color": "969696",
}

r = requests.post('http://latex2png.com/api/convert')

print(r.content)
```

but I get b'{"result-message":"no request","result-code":-2}'.

There is no documentation or help online with this specific API and website.

答:
That's because the way you post is wrong, try this:</p>

```<code>import requests

headers = {
    "Content-type": "application/x-www-form-urlencoded",
}

data = {
    "auth": {
        "user": "guest",
        "password": "guest"
    },
    "latex": "a^3",
    "resolution": 600,
    "color": "969696"
}

r = requests.post('http://latex2png.com/api/convert', headers=headers, json=data) # the right way to send POST requests
print(r.json())  # print the json
image_url = "http://latex2png.com" + r.json()['url']
r = requests.get(image_url)
with open("download.png", "wb+") as f: # download it.
    f.write(r.content)
</code>```

Body:
I would like to use the requests library to make a request to a particular webpage, http://latex2png.com/api/convert, in order to convert some latex to a PNG image. However, I am unsure of what data parameters the website accepts.

Is there any way to use the requests library to see which parameters need to be fulfilled?

I've tried running

options = {
    "auth": {"user": "guest", "password": "guest"},
    "latex": '$a^3$',
    "resolution": 900,
    "color": "969696",
}

r = requests.post('http://latex2png.com/api/convert')

print(r.content)

but I get b'{"result-message":"no request","result-code":-2}'.

There is no documentation or help online with this specific API and website.

Body:
That's because the way you post is wrong, try this:

import requests

headers = {
    "Content-type": "application/x-www-form-urlencoded",
}

data = {
    "auth": {
        "user": "guest",
        "password": "guest"
    },
    "latex": "a^3",
    "resolution": 600,
    "color": "969696"
}

r = requests.post('http://latex2png.com/api/convert', headers=headers, json=data) # the right way to send POST requests
print(r.json())  # print the json
image_url = "http://latex2png.com" + r.json()['url']
r = requests.get(image_url)
with open("download.png", "wb+") as f: # download it.
    f.write(r.content)


问:
FAB 2 coloured icon
I am using a FAB widget and I want to add a 2 coloured icon in it. Is that possible?  This is my current code right now:

```<code> <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/notificationFAB"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:fabSize="mini"
            android:tintMode="multiply"
            android:backgroundTint="@color/colorWhite"
            android:layout_marginTop="5dp"
            app:tint="@color/colorPrimaryLight"
            app:rippleColor="@color/colorPrimary"
            android:layout_marginHorizontal="10dp"
            android:src="@drawable/active_notif_final"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:borderWidth="0dp"
            />
</code>```

I did a workaround: made the colors of the icon light and added tintMode as multiply to get the original color. But it still doesn't look good.

workaround

Original

```<code><com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
            android:id="@+id/notificationFAB"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:backgroundTint="@color/colorWhite"
            android:layout_marginTop="5dp"
            app:rippleColor="@color/colorPrimary"
            android:layout_marginHorizontal="10dp"
            app:icon="@drawable/active_notif_final"
            app:iconTint="@color/colorPrimaryLight"
            app:iconTintMode="multiply"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:borderWidth="0dp"
            />
</code>```

with extended FAB:

答:
By default, the icon (app:srcCompat) is tinted with the app:tint color as per the FloatingActionButton documentation.

You can disable this behavior by adding app:tint="@null" to your fab:

```<code> <com.google.android.material.floatingactionbutton.FloatingActionButton
      app:srcCompat="@drawable/..."
      app:tint="@null"
      .../>
</code>```

In the ExtendedFloatingActionButton the app:icon is tinted with the app:iconTint:

```<code><com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
    app:icon="@drawable/...."
    app:iconTint="@null"
    .../>
</code>```

Title: FAB 2 coloured icon

Body:
I am using a FAB widget and I want to add a 2 coloured icon in it. Is that possible?  This is my current code right now:

 <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/notificationFAB"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:fabSize="mini"
            android:tintMode="multiply"
            android:backgroundTint="@color/colorWhite"
            android:layout_marginTop="5dp"
            app:tint="@color/colorPrimaryLight"
            app:rippleColor="@color/colorPrimary"
            android:layout_marginHorizontal="10dp"
            android:src="@drawable/active_notif_final"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:borderWidth="0dp"
            />

I did a workaround: made the colors of the icon light and added tintMode as multiply to get the original color. But it still doesn't look good.

workaround

Original

<com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
            android:id="@+id/notificationFAB"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:backgroundTint="@color/colorWhite"
            android:layout_marginTop="5dp"
            app:rippleColor="@color/colorPrimary"
            android:layout_marginHorizontal="10dp"
            app:icon="@drawable/active_notif_final"
            app:iconTint="@color/colorPrimaryLight"
            app:iconTintMode="multiply"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:borderWidth="0dp"
            />

with extended FAB:

Body:
By default, the icon (app:srcCompat) is tinted with the app:tint color as per the FloatingActionButton documentation.

You can disable this behavior by adding app:tint="@null" to your fab:

 <com.google.android.material.floatingactionbutton.FloatingActionButton
      app:srcCompat="@drawable/..."
      app:tint="@null"
      .../>

In the ExtendedFloatingActionButton the app:icon is tinted with the app:iconTint:

<com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
    app:icon="@drawable/...."
    app:iconTint="@null"
    .../>


问:
Disable zoom when clicking on form fields within a WebView?
I've looked through dozens of pages if similar questions, none of them have any answers, so hopefully this one will be different.

I have a webview, and I do not want the zoom of the view to change from the initial zoom level I have it set to.  The only thing which changes the zoom level currently is when a text box is focused.

I need to be able to do this through Java code, not using the viewport meta tag.

Just so I don't have the common responses, I have the following in my code to disable zooming, and the zoom controls:

```<code>mWebView.getSettings().setBuiltInZoomControls(false);
mWebView.getSettings().setSupportZoom(false);
</code>```

I'm thinking that a possible solution is to check to see when an onFocus or even an onClick event occurs within the WebView and then zoomOut, but I'm not even sure if that is possible?

Any suggestions would be appreciated.

答:
This issue has been fixed by a firmware update on HTC devices, it was (apparently) being caused by the Sense UI overriding default Android functionality incorrectly.

It is very difficult to provide information on exactly when this was corrected, however my web application no longer zooms when a text box is clicked on any HTC device with the latest firmware.

The following two lines of code will disable the "zoom" aspects of an android webview:

```<code>// disables the actual onscreen controls from showing up
mWebView.getSettings().setBuiltInZoomControls(false);
// disables the ability to zoom
mWebView.getSettings().setSupportZoom(false);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I've looked through dozens of pages if similar questions, none of them have any answers, so hopefully this one will be different.

I have a webview, and I do not want the zoom of the view to change from the initial zoom level I have it set to.  The only thing which changes the zoom level currently is when a text box is focused.

I need to be able to do this through Java code, not using the viewport meta tag.

Just so I don't have the common responses, I have the following in my code to disable zooming, and the zoom controls:

mWebView.getSettings().setBuiltInZoomControls(false);
mWebView.getSettings().setSupportZoom(false);

I'm thinking that a possible solution is to check to see when an onFocus or even an onClick event occurs within the WebView and then zoomOut, but I'm not even sure if that is possible?

Any suggestions would be appreciated.

Body:
This issue has been fixed by a firmware update on HTC devices, it was (apparently) being caused by the Sense UI overriding default Android functionality incorrectly.

It is very difficult to provide information on exactly when this was corrected, however my web application no longer zooms when a text box is clicked on any HTC device with the latest firmware.

The following two lines of code will disable the "zoom" aspects of an android webview:

// disables the actual onscreen controls from showing up
mWebView.getSettings().setBuiltInZoomControls(false);
// disables the ability to zoom
mWebView.getSettings().setSupportZoom(false);


问:
How to define rails constant Mailer::ApplicationMailer for Heroku deploy?
I have a rails application that is crashing because the ActionMailer constant apparently doesn't exist or something but it does.
Here are my Heroku logs:

```<code>2020-06-02T14:54:19.581698+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=beulah-ror-portfolio-1.herokuapp.com request_id=730c40fd-29b8-45f6-ac94-98839a66611a fwd="105.112.46.202" dyno= connect= service= status=503 bytes= protocol=http
2020-06-02T14:54:21.801858+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=beulah-ror-portfolio-1.herokuapp.com request_id=fe307ff5-6d4f-4305-a74d-54afeb92e3d6 fwd="105.112.46.202" dyno= connect= service= status=503 bytes= protocol=http
2020-06-02T14:54:35.626782+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=beulah-ror-portfolio-1.herokuapp.com request_id=ef7cd106-36d2-4a6e-93e3-aea874aa2c4d fwd="102.67.23.174" dyno= connect= service= status=503 bytes= protocol=http
2020-06-02T14:54:36.594530+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=beulah-ror-portfolio-1.herokuapp.com request_id=e6a8e65b-8aba-4165-aad8-890a2f505e82 fwd="102.67.23.174" dyno= connect= service= status=503 bytes= protocol=http
2020-06-02T14:56:05.955005+00:00 app[api]: Starting process with command `rails c` by user akibeulah@gmail.com
2020-06-02T14:56:20.095915+00:00 heroku[run.6268]: State changed from starting to up
2020-06-02T14:56:20.269238+00:00 heroku[run.6268]: Awaiting client
2020-06-02T14:56:20.298273+00:00 heroku[run.6268]: Starting process with command `rails c`
2020-06-02T14:56:30.227209+00:00 heroku[run.6268]: Process exited with status 1
2020-06-02T14:56:30.288477+00:00 heroku[run.6268]: State changed from up to complete
</code>```

Here is the output from the console:

```<code>1: from /app/vendor/bundle/ruby/2.6.0/gems/zeitwerk-2.3.0/lib/zeitwerk/kernel.rb:17:in `block in require'
/app/vendor/bundle/ruby/2.6.0/gems/zeitwerk-2.3.0/lib/zeitwerk/loader/callbacks.rb:17:in `on_file_autoloaded': expected file /app/app/models/mailers/application_mailer.rb to define constant Mailers::ApplicationMailer, but didn't (Zeitwerk::NameError)
</code>```

So my thinking was the Application mailer was not generated properly, so I regenerated it. It still did not work. I am thinking of removing the mailer entirely as I am not really using it at the moment. However, I want to know in case the error repeats itself in another project.

Here is my application mailer:

```<code>class ApplicationMailer < ActionMailer::Base
  default from: 'from@example.com'
  layout 'mailer'
end
</code>```

At this point, I believe there is something I do not understand. What could cause this error besides the application_mailer.rb?

I have tried restarting the Heroku app and also migrating the db... still nothing.

答:
You need to wrap ApplicationMailer inside the Mailers namespace - module.

```<code>module Mailers
  class ApplicationMailer < ActionMailer::Base
    default from: 'from@example.com'
    layout 'mailer'
  end
end
</code>```

That's at least basically what the error message "/mailers/application_mailer.rb to define constant Mailers::ApplicationMailer" is trying to tell you.

However, I am a bit confused that your mailers directory is nested inside app/models - I would expect it to be in app/mailers

So maybe better try to move the mailers directory out of the models and try without wrapping it in the module.

Body:
I have a rails application that is crashing because the ActionMailer constant apparently doesn't exist or something but it does.
Here are my Heroku logs:

2020-06-02T14:54:19.581698+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=beulah-ror-portfolio-1.herokuapp.com request_id=730c40fd-29b8-45f6-ac94-98839a66611a fwd="105.112.46.202" dyno= connect= service= status=503 bytes= protocol=http
2020-06-02T14:54:21.801858+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=beulah-ror-portfolio-1.herokuapp.com request_id=fe307ff5-6d4f-4305-a74d-54afeb92e3d6 fwd="105.112.46.202" dyno= connect= service= status=503 bytes= protocol=http
2020-06-02T14:54:35.626782+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=beulah-ror-portfolio-1.herokuapp.com request_id=ef7cd106-36d2-4a6e-93e3-aea874aa2c4d fwd="102.67.23.174" dyno= connect= service= status=503 bytes= protocol=http
2020-06-02T14:54:36.594530+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=beulah-ror-portfolio-1.herokuapp.com request_id=e6a8e65b-8aba-4165-aad8-890a2f505e82 fwd="102.67.23.174" dyno= connect= service= status=503 bytes= protocol=http
2020-06-02T14:56:05.955005+00:00 app[api]: Starting process with command `rails c` by user akibeulah@gmail.com
2020-06-02T14:56:20.095915+00:00 heroku[run.6268]: State changed from starting to up
2020-06-02T14:56:20.269238+00:00 heroku[run.6268]: Awaiting client
2020-06-02T14:56:20.298273+00:00 heroku[run.6268]: Starting process with command `rails c`
2020-06-02T14:56:30.227209+00:00 heroku[run.6268]: Process exited with status 1
2020-06-02T14:56:30.288477+00:00 heroku[run.6268]: State changed from up to complete

Here is the output from the console:

1: from /app/vendor/bundle/ruby/2.6.0/gems/zeitwerk-2.3.0/lib/zeitwerk/kernel.rb:17:in `block in require'
/app/vendor/bundle/ruby/2.6.0/gems/zeitwerk-2.3.0/lib/zeitwerk/loader/callbacks.rb:17:in `on_file_autoloaded': expected file /app/app/models/mailers/application_mailer.rb to define constant Mailers::ApplicationMailer, but didn't (Zeitwerk::NameError)

So my thinking was the Application mailer was not generated properly, so I regenerated it. It still did not work. I am thinking of removing the mailer entirely as I am not really using it at the moment. However, I want to know in case the error repeats itself in another project.

Here is my application mailer:

class ApplicationMailer < ActionMailer::Base
  default from: 'from@example.com'
  layout 'mailer'
end

At this point, I believe there is something I do not understand. What could cause this error besides the application_mailer.rb?

I have tried restarting the Heroku app and also migrating the db... still nothing.

Body:
You need to wrap ApplicationMailer inside the Mailers namespace - module.

module Mailers
  class ApplicationMailer < ActionMailer::Base
    default from: 'from@example.com'
    layout 'mailer'
  end
end

That's at least basically what the error message "/mailers/application_mailer.rb to define constant Mailers::ApplicationMailer" is trying to tell you.

However, I am a bit confused that your mailers directory is nested inside app/models - I would expect it to be in app/mailers

So maybe better try to move the mailers directory out of the models and try without wrapping it in the module.


问:
How to read data in blocks/chunks from CSV file in JMeter for the subsequent POSTs
I have say, 1000 users, each user needs to read 50 unique data from a CSV file and POST in the subsequent JSON API call. For example, data file looks like:

User-1 will have to read 50 data from D1 to D50, User-2 will read the next 50 data from D51 to D100 and so on.
As there are thousands of data, I cant have the data file like:

答:
This is quite an "exotic" use case for the CSV Data Set Config, the only way I can see is using i.e. __groovy() function

```<code>${__groovy(new File('/path/to/your/file.csv').readLines()[(ctx.getThreadNum()) * 50..((ctx.getThreadNum()) * 50)+50].join('\n'),)}
</code>```

Where ctx stands for JMeterContext, check out Top 8 JMeter Java Classes You Should Be Using with Groovy article for more information on this and other JMeter API shorthands available for JSR223 scripts

Body:
This is quite an "exotic" use case for the CSV Data Set Config, the only way I can see is using i.e. __groovy() function

${__groovy(new File('/path/to/your/file.csv').readLines()[(ctx.getThreadNum()) * 50..((ctx.getThreadNum()) * 50)+50].join('\n'),)}

Where ctx stands for JMeterContext, check out Top 8 JMeter Java Classes You Should Be Using with Groovy article for more information on this and other JMeter API shorthands available for JSR223 scripts


问:
Error ploting Marginal Effects with cplot() in R
I want to plot the marginal effects of my logit model (mod7) with cplot(), but I dont know how to solve this error

Here the Code:

```<code>mod7 <- glm(Crosssectionunique$ACQYes ~ Crosssectionunique$management + controls + Crosssectionunique$emp_firm)
mod8 <- glm(Crosssectionunique$ACQYes3 ~ Crosssectionunique$management + controls + Crosssectionunique$emp_firm)

summary(mod7)
install.packages("margins")
library("margins")
cplot(mod7, x = "Crosssectionunique$management", se.type = "shade")
</code>```

```<code>Error in names(classes) <- clean_terms(names(classes)) :
'names' attribute [3] must be the same length as the vector [2]
</code>```

Any suggestions ?

答:
You get this issue because you try to pass "Crosssectionunique$management" to cplot which can be pretty confusing. So using an example dataset:

```<code>library(margins)

Crosssectionunique = data.frame(
ACQYes = runif(50),
management = sample(letters[1:3],50,replace=TRUE),
emp_firm = factor(sample(1:3,50,replace=TRUE))
)
controls = runif(50)

mod <- glm(Crosssectionunique$ACQYes ~ Crosssectionunique$management + controls + Crosssectionunique$emp_firm)

cplot(mod, x = "Crosssectionunique$management", se.type = "shade")

Error in names(classes) <- clean_terms(names(classes)) :
  'names' attribute [5] must be the same length as the vector [3]
</code>```

You can see I get the same error. When doing lm etc, try to use a data.frame and call the variables from the data.frame, for example:

```<code>Crosssectionunique$controls = controls
mod <- glm(ACQYes ~ management + controls + emp_firm,data=Crosssectionunique)
</code>```

Now we call cplot, and specify the x should be a variable called "management", and it worksfine:

```<code>cplot(mod, x = "management", se.type = "shade")
</code>```

Body:
I want to plot the marginal effects of my logit model (mod7) with cplot(), but I dont know how to solve this error

Here the Code:

mod7 <- glm(Crosssectionunique$ACQYes ~ Crosssectionunique$management + controls + Crosssectionunique$emp_firm)
mod8 <- glm(Crosssectionunique$ACQYes3 ~ Crosssectionunique$management + controls + Crosssectionunique$emp_firm)

summary(mod7)
install.packages("margins")
library("margins")
cplot(mod7, x = "Crosssectionunique$management", se.type = "shade")

Error in names(classes) <- clean_terms(names(classes)) :
'names' attribute [3] must be the same length as the vector [2]

Any suggestions ?

Body:
You get this issue because you try to pass "Crosssectionunique$management" to cplot which can be pretty confusing. So using an example dataset:

library(margins)

Crosssectionunique = data.frame(
ACQYes = runif(50),
management = sample(letters[1:3],50,replace=TRUE),
emp_firm = factor(sample(1:3,50,replace=TRUE))
)
controls = runif(50)

mod <- glm(Crosssectionunique$ACQYes ~ Crosssectionunique$management + controls + Crosssectionunique$emp_firm)

cplot(mod, x = "Crosssectionunique$management", se.type = "shade")

Error in names(classes) <- clean_terms(names(classes)) :
  'names' attribute [5] must be the same length as the vector [3]

You can see I get the same error. When doing lm etc, try to use a data.frame and call the variables from the data.frame, for example:

Crosssectionunique$controls = controls
mod <- glm(ACQYes ~ management + controls + emp_firm,data=Crosssectionunique)

Now we call cplot, and specify the x should be a variable called "management", and it worksfine:

cplot(mod, x = "management", se.type = "shade")


问:
How to use sudo inside a docker container?
Normally, docker containers are run using the user root. I'd like to use a different user, which is no problem using docker's USER directive. But this user should be able to use sudo inside the container. This command is missing.

Here's a simple Dockerfile for this purpose:

```<code>FROM ubuntu:12.04

RUN useradd docker && echo "docker:docker" | chpasswd
RUN mkdir -p /home/docker && chown -R docker:docker /home/docker

USER docker
CMD /bin/bash
</code>```

Running this container, I get logged in with user 'docker'. When I try to use sudo, the command isn't found. So I tried to install the sudo package inside my Dockerfile using

```<code>RUN apt-get install sudo
</code>```

This results in Unable to locate package sudo

答:
Unlike accepted answer, I use usermod instead.

Assume already logged-in as root in docker, and "fruit" is the new non-root username I want to add, simply run this commands:

```<code>apt update && apt install sudo
adduser fruit
usermod -aG sudo fruit
</code>```

Remember to save image after update. Use docker ps to get current running docker's <CONTAINER ID> and <IMAGE>, then run docker commit -m "added sudo user" <CONTAINER ID>  <IMAGE> to save docker image.

Then test with:

```<code>su fruit
sudo whoami
</code>```

Or test by direct login(ensure save image first) as that non-root user when launch docker:

```<code>docker run -it --user fruit <IMAGE>
sudo whoami
</code>```

You can use sudo -k to reset password prompt timestamp:

```<code>sudo whoami # No password prompt
sudo -k # Invalidates the user's cached credentials
sudo whoami # This will prompt for password
</code>```

Body:
Normally, docker containers are run using the user root. I'd like to use a different user, which is no problem using docker's USER directive. But this user should be able to use sudo inside the container. This command is missing.

Here's a simple Dockerfile for this purpose:

FROM ubuntu:12.04

RUN useradd docker && echo "docker:docker" | chpasswd
RUN mkdir -p /home/docker && chown -R docker:docker /home/docker

USER docker
CMD /bin/bash

Running this container, I get logged in with user 'docker'. When I try to use sudo, the command isn't found. So I tried to install the sudo package inside my Dockerfile using

RUN apt-get install sudo

This results in Unable to locate package sudo

Body:
Unlike accepted answer, I use usermod instead.

Assume already logged-in as root in docker, and "fruit" is the new non-root username I want to add, simply run this commands:

apt update && apt install sudo
adduser fruit
usermod -aG sudo fruit

Remember to save image after update. Use docker ps to get current running docker's <CONTAINER ID> and <IMAGE>, then run docker commit -m "added sudo user" <CONTAINER ID>  <IMAGE> to save docker image.

Then test with:

su fruit
sudo whoami

Or test by direct login(ensure save image first) as that non-root user when launch docker:

docker run -it --user fruit <IMAGE>
sudo whoami

You can use sudo -k to reset password prompt timestamp:

sudo whoami # No password prompt
sudo -k # Invalidates the user's cached credentials
sudo whoami # This will prompt for password


问:
JavaScript 1 minute countdown not working properly
I created a simple 1 Minute countdown, but it seems not to be working I don't know why.

IT GIVES EXPIRED as response instead of the timer showing.

// Set the date we're counting down to
var setoneminutetime = new Date();
setoneminutetime.setMinutes(1);
var countDownDate = new Date(setoneminutetime).getTime();
//set interval for the actual countdown
var x = setInterval(function() {
    var now = new Date().getTime();
    //end time minus the current time
    var distance = countDownDate - now;
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    //show countdown  in div demo
    document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
    if (distance < 0) {
        clearInterval(x);
        document.getElementById("demo").innerHTML = "EXPIRED";
    }
}, 1000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p {
    text-align: center;
    font-size: 60px;
    margin-top: 0px;
}</code>```

```

答:
setMinutes set the minutes to 1 of the current hour. Right now, it's 5:19PM, with setMinutes(1), the hour is 5:01PM. You need to get the current time and add 1 minute to it.

// Set the date we're counting down to
var setoneminutetime = new Date();
setoneminutetime.setTime(Date.now() + 1 * 60 * 1000); // Add 1 minutes to current timestamp
var countDownDate = new Date(setoneminutetime).getTime();
//set interval for the actual countdown
var x = setInterval(function() {
    var now = new Date().getTime();
    //end time minus the current time
    var distance = countDownDate - now;
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    //show countdown  in div demo
    document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
    if (distance < 0) {
        clearInterval(x);
        document.getElementById("demo").innerHTML = "EXPIRED";
    }
}, 1000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p {
    text-align: center;
    font-size: 60px;
    margin-top: 0px;
}</code>```

```

Body:
I created a simple 1 Minute countdown, but it seems not to be working I don't know why.

IT GIVES EXPIRED as response instead of the timer showing.

// Set the date we're counting down to
var setoneminutetime = new Date();
setoneminutetime.setMinutes(1);
var countDownDate = new Date(setoneminutetime).getTime();
//set interval for the actual countdown
var x = setInterval(function() {
    var now = new Date().getTime();
    //end time minus the current time
    var distance = countDownDate - now;
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    //show countdown  in div demo
    document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
    if (distance < 0) {
        clearInterval(x);
        document.getElementById("demo").innerHTML = "EXPIRED";
    }
}, 1000);

p {
    text-align: center;
    font-size: 60px;
    margin-top: 0px;
}

Body:
setMinutes set the minutes to 1 of the current hour. Right now, it's 5:19PM, with setMinutes(1), the hour is 5:01PM. You need to get the current time and add 1 minute to it.

// Set the date we're counting down to
var setoneminutetime = new Date();
setoneminutetime.setTime(Date.now() + 1 * 60 * 1000); // Add 1 minutes to current timestamp
var countDownDate = new Date(setoneminutetime).getTime();
//set interval for the actual countdown
var x = setInterval(function() {
    var now = new Date().getTime();
    //end time minus the current time
    var distance = countDownDate - now;
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    //show countdown  in div demo
    document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
    if (distance < 0) {
        clearInterval(x);
        document.getElementById("demo").innerHTML = "EXPIRED";
    }
}, 1000);

p {
    text-align: center;
    font-size: 60px;
    margin-top: 0px;
}

<p id="demo"></p>


问:
Getting the average number of times a number appears between other numbers
In my cells I have three possible different values, 1 ,0 or ND. I want to get the average number of times 0 appears between the 1s.
But I cannot seem to get it, I have been playing around with =AVERAGE(COUNTIF(A60:C60,  0)). It seems simple but I cannot figure it out.
So I want the average number of times that 0 appears between 1s in the whole row.

imagine each cell is a day. 1s represent fail and 0 represent pass. If the cell has failed that day it is fixed that night. what i want to find out is when i fix a failed cell what is the average amount of days pass before that cell fails again

答:
A formula only solution to show the idea of how to calculate it

This solution doen't need VBA but a helper row.

Imagine the following data in row 1.

Row 2 is a helper row to calculate the average:

A2 is empty.

B2 write the formula =IF(B1=1,COUNTIF($A$1:B1,0)-SUM($A$2:A2),"") and copy it to the right.

The average is then calculated with =AVERAGE(2:2)

The numbers in row 2 are the count of 0 that are in front of the 1 in row 1. All ND get just ignored.

But this is the same result as

```<code>=COUNTIF(1:1,0)/COUNTIF(1:1,1)   '<-- = average
</code>```

Because the =AVERAGE is actually the sum of zeros devided by the amount of ones. So this formula is all you need, even no helper column is needed.

Body:
A formula only solution to show the idea of how to calculate it

This solution doen't need VBA but a helper row.

Imagine the following data in row 1.

Row 2 is a helper row to calculate the average:

A2 is empty.

B2 write the formula =IF(B1=1,COUNTIF($A$1:B1,0)-SUM($A$2:A2),"") and copy it to the right.

The average is then calculated with =AVERAGE(2:2)

The numbers in row 2 are the count of 0 that are in front of the 1 in row 1. All ND get just ignored.

But this is the same result as

=COUNTIF(1:1,0)/COUNTIF(1:1,1)   '<-- = average

Because the =AVERAGE is actually the sum of zeros devided by the amount of ones. So this formula is all you need, even no helper column is needed.


问:
Python equivalant for a curl command on an IP based relay controller
So I have an IP based relay controller that lets you turn the relays in it on and off using a curl command such as: curl "http://192.168.1.100/current_state.xml?pw=admin&Relay1=1"

How would I replicate this in python? I have attempted to use:
 requests.get("http://192.168.1.100/current_state.xml?pw=admin&Relay1=1")
time.sleep(5)
resquests.get("http://192.168.1.100/current_state.xml?pw=admin&Relay1=1")
print("Complete")

but it doesn't turn the relay on as it should.

Any pointers would be great, thanks in advance.

答:
Have you tried printing the result? I know it's pretty straight forward but you didn't mention  trying it.</p>

```<code>x = requests.get("http://192.168.1.100/current_state.xml?pw=admin&Relay1=1")
print(x.text)
</code>```

Body:
Have you tried printing the result? I know it's pretty straight forward but you didn't mention  trying it.

x = requests.get("http://192.168.1.100/current_state.xml?pw=admin&Relay1=1")
print(x.text)


问:
Angular Toggle only the element click on
I have a method that toggles a div area.

At the moment I have 3 areas

app.component.ts

```<code>show = false;

toggle() {
    this.show = !this.show;
}
</code>```

app.component.html

```<code><div>
    <div *ngIf="show">
      <div>One</div>
    </div>
    <button type="button" toggle()"></button>
</div>

<div>
    <div *ngIf="show">
      <div>Two</div>
    </div>
    <button type="button" toggle()"></button>
</div>

<div>
    <div *ngIf="show">
      <div>Three</div>
    </div>
    <button type="button" toggle()"></button>
</div>
</code>```

At the moment is will show and hide the 3 sections.

How can I chan it so that it just toggles the div with the *ngIf="show" that I of the button I clicked?

答:
I guess below is what you want:
app.component.ts

```<code>toggleStatus =[false,false,false];

toggle(index:number) {
    this.toggleStatus[index] = !this.toggleStatus[index];
}
</code>```

app.component.html

```<code><div>
    <div *ngIf="toggleStatus[0]">
      <div>One</div>
    </div>
    <button type="button" toggle(0)"></button>
</div>

<div>
    <div *ngIf="toggleStatus[1]">
      <div>Two</div>
    </div>
    <button type="button" toggle(1)"></button>
</div>

<div>
    <div *ngIf="toggleStatus[2]">
      <div>Three</div>
    </div>
    <button type="button" toggle(2)"></button>
</div>
</code>```

Body:
I have a method that toggles a div area.

At the moment I have 3 areas

app.component.ts

show = false;

toggle() {
    this.show = !this.show;
}

app.component.html

One

    <button type="button" toggle()"></button>

Two

    <button type="button" toggle()"></button>

Three

    <button type="button" toggle()"></button>

At the moment is will show and hide the 3 sections.

How can I chan it so that it just toggles the div with the *ngIf="show" that I of the button I clicked?

Body:
I guess below is what you want:
app.component.ts

toggleStatus =[false,false,false];

toggle(index:number) {
    this.toggleStatus[index] = !this.toggleStatus[index];
}

app.component.html

<div>
    <div *ngIf="toggleStatus[0]">
      <div>One</div>
    </div>
    <button type="button" toggle(0)"></button>
</div>

<div>
    <div *ngIf="toggleStatus[1]">
      <div>Two</div>
    </div>
    <button type="button" toggle(1)"></button>
</div>

<div>
    <div *ngIf="toggleStatus[2]">
      <div>Three</div>
    </div>
    <button type="button" toggle(2)"></button>
</div>


问:
Azure CLI edit Content Type file property
I'm trying to update Content Type property of a file located in my Azure $web blob container using Azure CLI. I'm trying to do this because it's wrongly set and my service-worker.js (for my PWA) needs to have "application/javascript" instead of "text/plain; charset=utf-8" in order to be registered.</p>

答:
I found a way of doing this using Azure Pipelines:

```<code>
- task: AzureFileCopy@4
  displayName: "Azure Storage - copy new files"
  inputs:
    SourcePath: '$(System.DefaultWorkingDirectory)/dist/*'
    azureSubscription: 'johnykes-PAYG(44df419f-b455-4c4d-a8f8-c2a5fd479f10)'
    Destination: 'AzureBlob'
    storage: 'johnykeschatfrontend'
    ContainerName: '$web'

- task: AzureFileCopy@4
  displayName: "Azure Storage - overwrite .js files with correct Content Type"
  inputs:
    SourcePath: '$(System.DefaultWorkingDirectory)/dist/*.js'
    azureSubscription: 'johnykes-PAYG(44df419f-b455-4c4d-a8f8-c2a5fd479f10)'
    Destination: 'AzureBlob'
    storage: 'johnykeschatfrontend'
    ContainerName: '$web'
    AdditionalArgumentsForBlobCopy: '--content-type "application/javascript"'
</code>```

Please let me know if you find a way of doing using the Azure CLI or in my way but recursively (for all .js files) or in any other way.

Body:
I found a way of doing this using Azure Pipelines:

- task: AzureFileCopy@4
  displayName: "Azure Storage - copy new files"
  inputs:
    SourcePath: '$(System.DefaultWorkingDirectory)/dist/*'
    azureSubscription: 'johnykes-PAYG(44df419f-b455-4c4d-a8f8-c2a5fd479f10)'
    Destination: 'AzureBlob'
    storage: 'johnykeschatfrontend'
    ContainerName: '$web'

- task: AzureFileCopy@4
  displayName: "Azure Storage - overwrite .js files with correct Content Type"
  inputs:
    SourcePath: '$(System.DefaultWorkingDirectory)/dist/*.js'
    azureSubscription: 'johnykes-PAYG(44df419f-b455-4c4d-a8f8-c2a5fd479f10)'
    Destination: 'AzureBlob'
    storage: 'johnykeschatfrontend'
    ContainerName: '$web'
    AdditionalArgumentsForBlobCopy: '--content-type "application/javascript"'

Please let me know if you find a way of doing using the Azure CLI or in my way but recursively (for all .js files) or in any other way.


问:
How do I create specific quantities for specific products within Shopify?
I've got a few products where I need the quantities for a specific product to start at a number, 240 for example and then the customer can select in intervals of 240, and for a different product, say 100 units. I need a way to separate a list of quantities for separate products.</p>

答:
You can examine the documentation related to InventoryItem endpoints which leads to InventoryLevel endpoints. Once you get a handle on Locations, you are free to set inventory levels. Note that setting explicit amounts is no longer the fashion, instead you ask how much is there, and then modify that amount with a delta change. </p>

<p>So if you ask for a product's variant level, and it tells you the current availability is 0, your delta might be +240. </p>

Body:
You can examine the documentation related to InventoryItem endpoints which leads to InventoryLevel endpoints. Once you get a handle on Locations, you are free to set inventory levels. Note that setting explicit amounts is no longer the fashion, instead you ask how much is there, and then modify that amount with a delta change.

So if you ask for a product's variant level, and it tells you the current availability is 0, your delta might be +240.


问:
using http with axios return 400 with request it works
I use the following code using request which works as expected, got http response 200

```<code>var request = require('request');

var auth
var options = {
    'method': 'POST',
    'url': 'https://oauth2.k.de.com/oauth2/token',
    'headers': {
        'Accept': 'application/json',
        'Authorization': 'Basic NGViMTE2ODctZTNjNi00NDUyLTgwNjgtMzhiOjJDR2lJd0hxOFFx==',
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    form: {
        'grant_type': 'client_credentials',
        'scope': 'app:read'
    }
};
request(options, function (error, response) {
    if (error) throw new Error(error);

    let body = JSON.parse(response.body);

 ….
</code>```

Now I need to convert it to axios as request been deprecated but it’s not working for me ( I got http 400 response )

```<code>const axios = require('axios').default;

axios({
    method: 'post',
    'url': 'https://oauth2.k.de.com/oauth2/token',
    data: {
        'grant_type': 'client_credentials',
        'scope': 'app:read'
    },
    headers: {
        'Accept': 'application/json',
         'Authorization': 'Basic NGViMTE2ODctZTNjNi00NDUyLTgwNjgtMzhiOjJDR2lJd0hxOFFx==',
        'Content-Type': 'application/x-www-form-urlencoded'
    }
}).then(function (response: any) {
    console.log("Head With Authentication :" + response);
}).catch(function (error: any) {
    console.log("Post Error : " + error);
});
</code>```

Any idea why with request library with the exact same data it works (http response 200) and in axios I got 400 ?
In request I put the grant_type etc in form and in axios in data, this is the only diffrencace I see, any idea?

This is the error I got

Request failed with status code 400

Should I use other rest libary if it cannot be done via axios ?

答:
This is a bug, you might want to check this: https://github.com/axios/axios/issues/362

The problem is, because of axios interceptors, your Content-Type header is disappearing. If you have access and can change the backend, you can make it work with another header and set it on your client code. Otherwise if your code is working in a browser, you can try using URLSearchParams as suggested here.

Body:
I use the following code using request which works as expected, got http response 200

var request = require('request');

var auth
var options = {
    'method': 'POST',
    'url': 'https://oauth2.k.de.com/oauth2/token',
    'headers': {
        'Accept': 'application/json',
        'Authorization': 'Basic NGViMTE2ODctZTNjNi00NDUyLTgwNjgtMzhiOjJDR2lJd0hxOFFx==',
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    form: {
        'grant_type': 'client_credentials',
        'scope': 'app:read'
    }
};
request(options, function (error, response) {
    if (error) throw new Error(error);

    let body = JSON.parse(response.body);

 ….

Now I need to convert it to axios as request been deprecated but it’s not working for me ( I got http 400 response )

const axios = require('axios').default;

axios({
    method: 'post',
    'url': 'https://oauth2.k.de.com/oauth2/token',
    data: {
        'grant_type': 'client_credentials',
        'scope': 'app:read'
    },
    headers: {
        'Accept': 'application/json',
         'Authorization': 'Basic NGViMTE2ODctZTNjNi00NDUyLTgwNjgtMzhiOjJDR2lJd0hxOFFx==',
        'Content-Type': 'application/x-www-form-urlencoded'
    }
}).then(function (response: any) {
    console.log("Head With Authentication :" + response);
}).catch(function (error: any) {
    console.log("Post Error : " + error);
});

Any idea why with request library with the exact same data it works (http response 200) and in axios I got 400 ?
In request I put the grant_type etc in form and in axios in data, this is the only diffrencace I see, any idea?

This is the error I got

Request failed with status code 400

Should I use other rest libary if it cannot be done via axios ?


答: As others have mentioned you've set the Date minute to :01 not added one minute. A simple solution would be to define countDownDate as now + 60*1000.</p>

Title: JavaScript 1 minute countdown not working properly


答:
This is explicitly setting the "minute" value of the Date to 1:

```<code>setoneminutetime.setMinutes(1);
</code>```

So this will only work if you load the page exactly at the 0 minute mark of any given hour.  It looks like you intended to set it to the current minute plus 1:

```<code>setoneminutetime.setMinutes(setoneminutetime.getMinutes() + 1);
</code>```

Note that this would also fail any time the current minute is 59.  You should be able to get around this by creating a whole new date out of the total epoch miliseconds and adding 60,000 (miliseconds) to that:

```<code>var setoneminutetime = new Date(new Date().getTime() + 60000);
</code>```

Body:
This is explicitly setting the "minute" value of the Date to 1:

setoneminutetime.setMinutes(1);

So this will only work if you load the page exactly at the 0 minute mark of any given hour.  It looks like you intended to set it to the current minute plus 1:

setoneminutetime.setMinutes(setoneminutetime.getMinutes() + 1);

Note that this would also fail any time the current minute is 59.  You should be able to get around this by creating a whole new date out of the total epoch miliseconds and adding 60,000 (miliseconds) to that:

var setoneminutetime = new Date(new Date().getTime() + 60000);


问:
Wrong type of the expression
This question is strongly related to this SE question. MyMap has been created the same way as StringMap from that question.

```<code># lsc;;
- : (MyMap.key * testtype) list =
[(("", "Test1"),
  {name = ""; state = ""; region = "Test1a"});
(("", "Test1a"),
  {name = ""; state = ""; region = "Test1b"});
(("", "Test2"),
  {name = ""; state = ""; region = "Test2"})]
</code>```

I want to create a function which will give me a filtered list from lsc. I want to filter it according to (x, _) _. For instance, it is equal to Test1, then the function will return the list of records

[{name = ""; state = ""; region = "Test1a"}; {name = ""; state = ""; region = "Test1b"}]

For the moment, I just want to filter lsc to get

```<code>[(("", "Test1"),
  {name = ""; state = ""; region = "Test1a"});
(("", "Test1a"),
  {name = ""; state = ""; region = "Test1b"})]
</code>```

MyMap.filter (fun (x,_) _ -> x="Test1") lsc;; give me the following error :

```<code>Error: This expression has type (MyMap.key * testtype) list
       but an expression was expected of type
         'a MyMap.t = 'a Map.Make(PaireCles).t
</code>```

From the SE question, I thought it was the way to go, but I face always the same error. Is there a workaround for that?

答:
The Map.filter function takes a function and a map data structure, not an association list, which you have. You can use List.filter to filter the list of key * value pairs,

```<code>List.filter (fun (x,_) -> x = "Test1") lsc
</code>```

Title: Wrong type of the expression

Body:
This question is strongly related to this SE question. MyMap has been created the same way as StringMap from that question.

# lsc;;
- : (MyMap.key * testtype) list =
[(("", "Test1"),
  {name = ""; state = ""; region = "Test1a"});
(("", "Test1a"),
  {name = ""; state = ""; region = "Test1b"});
(("", "Test2"),
  {name = ""; state = ""; region = "Test2"})]

I want to create a function which will give me a filtered list from lsc. I want to filter it according to (x, _) _. For instance, it is equal to Test1, then the function will return the list of records

[{name = ""; state = ""; region = "Test1a"}; {name = ""; state = ""; region = "Test1b"}]

For the moment, I just want to filter lsc to get

[(("", "Test1"),
  {name = ""; state = ""; region = "Test1a"});
(("", "Test1a"),
  {name = ""; state = ""; region = "Test1b"})]

MyMap.filter (fun (x,_) _ -> x="Test1") lsc;; give me the following error :

Error: This expression has type (MyMap.key * testtype) list
       but an expression was expected of type
         'a MyMap.t = 'a Map.Make(PaireCles).t

From the SE question, I thought it was the way to go, but I face always the same error. Is there a workaround for that?

Body:
The Map.filter function takes a function and a map data structure, not an association list, which you have. You can use List.filter to filter the list of key * value pairs,

List.filter (fun (x,_) -> x = "Test1") lsc


问:
Add typeguard for null | undefined when "defined" type of value is unknown
I have NotEmpty validation function that throws an error if value is null / undefined:

```<code>function validateNotEmpty(data: unknown) {
  if (data) {
    return true;
  }

  throw new Error("Data is empty");
}
</code>```

It is used to validate various types of data, hence I am using unknown. I am trying to figure out how to add type guard to this in order for value to come out as "defined" and keep its original type?

For example

```<code>type TestType = null | undefined | string;
const testValue: TestType = "Hello World";

validateNotEmpty(testValue);

console.log(testValue); // This should be now typed as string only
</code>```

EDIT validateNotEmpty is a global utility function used to validate various data types, so it can't know what type it will be if it is not undefined | null

答:
you can use assertions or type guards:

function validateNotEmpty<T>(data: T): data is NonNullable<T> {
  return false; // some check here.
}

if (validateNotEmpty(testValue)) {
  console.log(testValue); // works
}
```

<p>or </p>

<pre class="lang-js prettyprint-override"><code>function validateNotEmpty<T>(data: T): asserts data is NonNullable<T> {
  throw new Error("Data is empty"); // throws in false case.
}

validateNotEmpty(testValue);
console.log(testValue); // works
</code>```

Body:
I have NotEmpty validation function that throws an error if value is null / undefined:

function validateNotEmpty(data: unknown) {
  if (data) {
    return true;
  }

  throw new Error("Data is empty");
}

It is used to validate various types of data, hence I am using unknown. I am trying to figure out how to add type guard to this in order for value to come out as "defined" and keep its original type?

For example

type TestType = null | undefined | string;
const testValue: TestType = "Hello World";

validateNotEmpty(testValue);

console.log(testValue); // This should be now typed as string only

EDIT validateNotEmpty is a global utility function used to validate various data types, so it can't know what type it will be if it is not undefined | null

Body:
you can use assertions or type guards:

function validateNotEmpty<T>(data: T): data is NonNullable<T> {
  return false; // some check here.
}

if (validateNotEmpty(testValue)) {
  console.log(testValue); // works
}

or

function validateNotEmpty<T>(data: T): asserts data is NonNullable<T> {
  throw new Error("Data is empty"); // throws in false case.
}

validateNotEmpty(testValue);
console.log(testValue); // works


问:
Kivy segmentation fault on blitting opencv picture
I am trying to cast video from my external cam, that is captured through some aliexpress EasyCap, to my kivy app. One issue I've faced is that crashes with segmentation fault on trying to

```<code>texture = Texture.create(size=(frame.shape[0], frame.shape[1]))
</code>```

I've found that the problem is on kivy's side. It sometimes can't create NPOT textures. So, I've changed it to POT shape and copied what is possible to another numpy array.

```<code>flipped = cv2.flip(frame, 0)
buf = np.zeros((512, 512, 3), dtype=np.uint8)
for i in range(min(frame.shape[0], 512)):
   for j in range(min(frame.shape[1], 512)):
      buf[i, j] = flipped[i, j]
buf = buf.tostring()
texture = Texture.create(size=(512, 512))
texture.blit_buffer(buf, colorfmt="bgr", bufferfmt="ubyte")
self.texture = texture
</code>```

But it still crashes with the same old segmentation fault on the following line:

```<code>texture.blit_buffer(buf, colorfmt="bgr", bufferfmt="ubyte")
</code>```

If it is relevant, cv2.imshow("image", buf) before buf.tostring() show the image correctly.

Here's the original code:

```<code>from kivy.app import App
from kivy.uix.image import Image
from kivy.clock import Clock
from kivy.graphics.texture import Texture
import cv2
import threading
from time import sleep
import numpy as np

class KivyCamera(Image):
   def __init__(self, **kwargs):
      super(KivyCamera, self).__init__(**kwargs)
      self.fps = 30
      self.capture = cv2.VideoCature(0)
      threading.Thread(target=self.update).start()

   def update(self):
      while True:
         ret, frame = self.capture.read()
         if ret:
            buf = cv2.flip(frame, 0).tostring()
            texture = Texture.create(size=(frame.shape[0], frame.shape[1])
            texture.blit_buffer(buf, colorfmt="bgr", bufferfmt="ubyte")
            self.texture = texture
         sleep(1.0 / self.fps)

class CamApp(App):
   def build(self):
         return KivyCamera()

if __name__ == "__main__":
   CamApp().run()
</code>```

答:
Few issues with your code:

The GUI updates should always be done in the mainthread as indicated by John Anderson. Hence instead of separate thread, the update() function should be called through Clock schedule.

The size tuple in the Texture.create statement should be reversed and the colorfmt="bgr" should be added. It should be: texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt="bgr").

There is no layout defined. Layouts like BoxLayout should be added as a placeholder of Image widget.

Below is the modified working version of your code:

```<code>from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock
from kivy.graphics.texture import Texture
import cv2

class KivyCamera(BoxLayout):
   def __init__(self, **kwargs):
      super(KivyCamera, self).__init__(**kwargs)
      self.img1=Image()
      self.add_widget(self.img1)
      self.capture = cv2.VideoCapture(0)
      Clock.schedule_interval(self.update, 1.0/33.0)

   def update(self, *args):
     ret, frame = self.capture.read()
     if ret:
        buf = cv2.flip(frame, 0).tostring()
        texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt="bgr")
        texture.blit_buffer(buf, colorfmt="bgr", bufferfmt="ubyte")
        self.img1.texture = texture

class CamApp(App):
   def build(self):
         return KivyCamera()

if __name__ == "__main__":
   CamApp().run()
</code>```

The while loop is removed and Clock.schedule_interval is used with 1 / 33. steps.

Hope this helps.

Body:
I am trying to cast video from my external cam, that is captured through some aliexpress EasyCap, to my kivy app. One issue I've faced is that crashes with segmentation fault on trying to

texture = Texture.create(size=(frame.shape[0], frame.shape[1]))

I've found that the problem is on kivy's side. It sometimes can't create NPOT textures. So, I've changed it to POT shape and copied what is possible to another numpy array.

flipped = cv2.flip(frame, 0)
buf = np.zeros((512, 512, 3), dtype=np.uint8)
for i in range(min(frame.shape[0], 512)):
   for j in range(min(frame.shape[1], 512)):
      buf[i, j] = flipped[i, j]
buf = buf.tostring()
texture = Texture.create(size=(512, 512))
texture.blit_buffer(buf, colorfmt="bgr", bufferfmt="ubyte")
self.texture = texture

But it still crashes with the same old segmentation fault on the following line:

texture.blit_buffer(buf, colorfmt="bgr", bufferfmt="ubyte")

If it is relevant, cv2.imshow("image", buf) before buf.tostring() show the image correctly.

Here's the original code:

from kivy.app import App
from kivy.uix.image import Image
from kivy.clock import Clock
from kivy.graphics.texture import Texture
import cv2
import threading
from time import sleep
import numpy as np

class KivyCamera(Image):
   def __init__(self, **kwargs):
      super(KivyCamera, self).__init__(**kwargs)
      self.fps = 30
      self.capture = cv2.VideoCature(0)
      threading.Thread(target=self.update).start()

   def update(self):
      while True:
         ret, frame = self.capture.read()
         if ret:
            buf = cv2.flip(frame, 0).tostring()
            texture = Texture.create(size=(frame.shape[0], frame.shape[1])
            texture.blit_buffer(buf, colorfmt="bgr", bufferfmt="ubyte")
            self.texture = texture
         sleep(1.0 / self.fps)

class CamApp(App):
   def build(self):
         return KivyCamera()

if __name__ == "__main__":
   CamApp().run()

Body:
Few issues with your code:

The GUI updates should always be done in the mainthread as indicated by John Anderson. Hence instead of separate thread, the update() function should be called through Clock schedule.

The size tuple in the Texture.create statement should be reversed and the colorfmt="bgr" should be added. It should be: texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt="bgr").

There is no layout defined. Layouts like BoxLayout should be added as a placeholder of Image widget.

Below is the modified working version of your code:

from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock
from kivy.graphics.texture import Texture
import cv2

class KivyCamera(BoxLayout):
   def __init__(self, **kwargs):
      super(KivyCamera, self).__init__(**kwargs)
      self.img1=Image()
      self.add_widget(self.img1)
      self.capture = cv2.VideoCapture(0)
      Clock.schedule_interval(self.update, 1.0/33.0)

   def update(self, *args):
     ret, frame = self.capture.read()
     if ret:
        buf = cv2.flip(frame, 0).tostring()
        texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt="bgr")
        texture.blit_buffer(buf, colorfmt="bgr", bufferfmt="ubyte")
        self.img1.texture = texture

class CamApp(App):
   def build(self):
         return KivyCamera()

if __name__ == "__main__":
   CamApp().run()

The while loop is removed and Clock.schedule_interval is used with 1 / 33. steps.

Hope this helps.


问:
How to use a variable from a component in another in Angular2
I was wondering if it is possible to use variable values from one component into another one without having to use the template of the first one, just need the value of the variable nothing else. Is it possible?</p>

答:
I was developing a thing and I faced the same challenge.
My approach.

I had two different components and a service.

loginComponent, headerCompnent and a loginauth service.

```<code>    validateUser(name,pass){

   this.loginStatus = this.loginauth.validateUser(name,pass);

   if(this.loginStatus) this.route.navigate(['/welcome']);
   else this.route.navigate(['/login']);

  }
</code>```

image from LoginComponent

I wanted to use "loginStatus" in headerComponent.

this.loginauth.validateUser(name,pass);    loginauth was the service and validateUser(...) method inside it.

So I created a static variable inside the service and inject that service into both components and by injecting the same service in headerComponent I was able to retrieve the value of that static variable.

In service, create and initialize it as per your requirement.

```<code>static loginFlag = false;
</code>```

loginAuth service img

In header component.

Import that service and access that static variable with class name.

```<code> LoginAuthService.loginFlag
</code>```

headerComponent img

Body:
I was developing a thing and I faced the same challenge.
My approach.

I had two different components and a service.

loginComponent, headerCompnent and a loginauth service.

    validateUser(name,pass){

   this.loginStatus = this.loginauth.validateUser(name,pass);

   if(this.loginStatus) this.route.navigate(['/welcome']);
   else this.route.navigate(['/login']);

  }

image from LoginComponent

I wanted to use "loginStatus" in headerComponent.

this.loginauth.validateUser(name,pass);    loginauth was the service and validateUser(...) method inside it.

So I created a static variable inside the service and inject that service into both components and by injecting the same service in headerComponent I was able to retrieve the value of that static variable.

In service, create and initialize it as per your requirement.

static loginFlag = false;

loginAuth service img

In header component.

Import that service and access that static variable with class name.

 LoginAuthService.loginFlag

headerComponent img


问:
Android Studio nested composite build - plugin com.android.library not found
I have a working composite build in Android Studio, consisting of
Project A (app)
Project B (lib)

I now want to add another dependency to project B, which will be another library project.
As I understand it, Gradle supports nested composite builds since 4.10.
I have modified the settings.gradle in project B and added:

```<code>def projectB = '../../ProjectB/projectB'
includeBuild(projectB)
</code>```

When I try to gradle sync Project B, I get the errors:

```<code>Build file '/Users/xxxx/Documents/source/ProjectB/projectB/build.gradle' line: 1
A problem occurred evaluating project ':projectB'.
> Plugin with id 'com.android.library' not found.
</code>```

Is it event possible to do what I am trying to do? I can't seem to find a good example of nested composite builds.

答:
Use include instead of includeBuild like this:

```<code>include("project1", "project2:child", "project3:child1")
</code>```

The include method takes project paths as arguments. The project path is assumed to be equal to the relative physical file system path. For example, a path services:api is mapped by default to a folder services/api (relative from the project root). You only need to specify the leaves of the tree. This means that the inclusion of the path services:hotels:api will result in creating 3 projects: services, services:hotels and services:hotels:api.

For more check this

Body:
I have a working composite build in Android Studio, consisting of
Project A (app)
Project B (lib)

I now want to add another dependency to project B, which will be another library project.
As I understand it, Gradle supports nested composite builds since 4.10.
I have modified the settings.gradle in project B and added:

def projectB = '../../ProjectB/projectB'
includeBuild(projectB)

When I try to gradle sync Project B, I get the errors:

Build file '/Users/xxxx/Documents/source/ProjectB/projectB/build.gradle' line: 1
A problem occurred evaluating project ':projectB'.
> Plugin with id 'com.android.library' not found.

Is it event possible to do what I am trying to do? I can't seem to find a good example of nested composite builds.

Body:
Use include instead of includeBuild like this:

include("project1", "project2:child", "project3:child1")

The include method takes project paths as arguments. The project path is assumed to be equal to the relative physical file system path. For example, a path services:api is mapped by default to a folder services/api (relative from the project root). You only need to specify the leaves of the tree. This means that the inclusion of the path services:hotels:api will result in creating 3 projects: services, services:hotels and services:hotels:api.

For more check this


问:
SQL Server stored procedures dynamic SQL with multiple different where clause
Input CASE1=wen @type is NULL-> WHERE c.Date_Redeemed BETWEEN @Start AND @End-- this should execute

If CASE2=wen @start,@end is NULL->WHERE c.Type=@type-- this should execute
CASE 3=wen @value is null->WHERE c.Date_Redeemed BETWEEN @Start AND @End AND c.Type=@type this should execute

CASE4=wen @marketclass is NULL->WHERE c.Date_Redeemed BETWEEN @Start AND @End AND c.Type=@type AND c.ordervalue BETWEEN @price1 AND @price2

VAR=@type,@start,@price1,@marketclass if eithr of var is NULL dynamicaly other input where condition has to execute like diff combination of input comes

```<code>WHERE
   (c.Type = @type AND o.Date_of_Purchase BETWEEN @start AND @end) OR
   (@start IS NULL AND c.Type = @type) OR
   (@type IS NULL and o.Date_of_Purchase BETWEEN @start AND @end) OR
   (@start IS NULL AND @type IS NULL)
</code>```

if both are provided, only rows where type and date match are returned,

if type is not provided, date is used,

if date not provided type is used and

if nothing provided all rows return. To make no rows return, remove the last predicate

Code:

```<code>CREATE PROCEDURE dbo.sample
    @start DATE, @end DATE,
    @type VARCHAR(5),
    @price1 MONEY, @price2 MONEY
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @SQL VARCHAR(MAX)

    SET @SQL= 'SELECT DISTINCT o.O_Id,o.Sale_Price,o.Order_Line_Id,Private_Band,c.Date_of_Purchase,c.Date_Redeemed,c.Credit_Memo,c.Credit_Memo_Created_Date,c.Credit_Memo_Approved_Date,
    c.Type,c.Points_Issued,o.Date_of_Purchase FROM Order_Details o ,Transaction_Historys c WHERE -1='-1''
    IF @type IS NOT NULL AND @type <> 0
    SET @SQL = @SQL+ 'c.Type = @type'
    ELSE
    IF @start IS NOT NULL AND @start <> 0
    SET @SQL = @SQL+ 'c.Date_redeemed BETWEEN @start AND @end'

    EXECUTE dbo.sample @type='Earn',@start='2010-02-10',@end='2020-04-11'
END
</code>```

答:
Having looked through this, I'm actually kind of reluctant to post this answer, because there's so many things wrong with this:

prone to SQL injection;

using antiquated JOIN syntax;

clunky logic.

The simple answer is that sometimes just because you CAN do something in SQL doesn't mean you actually SHOULD.

Anyway, I think is closer to what you wanted?

```<code>CREATE PROCEDURE dbo.[sample] (
    @start DATE,
    @end DATE,
    @type VARCHAR(5),
    @price1 NUMERIC(9,2),
    @price2 NUMERIC(9,2))
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @sql VARCHAR(1024);
    SELECT @sql = N'
        SELECT DISTINCT
            o.O_Id,
            o.Sale_Price,
            o.Order_Line_Id,
            Private_Band, --alias?
            c.Date_of_Purchase,
            c.Date_Redeemed,
            c.Credit_Memo,
            c.Credit_Memo_Created_Date,
            c.Credit_Memo_Approved_Date,
            c.Type,
            c.Points_Issued,
            o.Date_of_Purchase
        FROM
            Order_Details o,
            Transaction_Historys c'; --Join condition?!
    DECLARE @constraint VARCHAR(1024) = '';
    IF @type IS NOT NULL AND @type != 0
    BEGIN
        SELECT @constraint = CONCAT(' WHERE c.Type = ''', @type, '''');
    END;
    IF @start IS NOT NULL AND @end IS NOT NULL
    BEGIN
        SELECT @constraint = CONCAT(@constraint,
            CASE WHEN @constraint = '' THEN ' WHERE ' ELSE ' AND ' END,
            ' c.Date_redeemed BETWEEN ''',
            CONVERT(VARCHAR(12), @start, 112),
            ''' AND ''',
            CONVERT(VARCHAR(12), @end, 112)),
            '''';
    END;
    SELECT @sql = CONCAT(@sql, @constraint);
    EXEC sp_executesql @sql;
END;
GO
EXEC dbo.[sample] @type = 'Earn', @start = '20100210', @end = '20200411', @price1 = NULL, @price2 = NULL;
</code>```

I made quite a few changes here:

I couldn't bring myself to use a MONEY type, so change it back if you really want it;

I added some comments to your script ;)

I sort of fixed the actual issue, that you need to cope with one or two or even no constraints being passed in.

Body:
Input CASE1=wen @type is NULL-> WHERE c.Date_Redeemed BETWEEN @Start AND @End-- this should execute

If CASE2=wen @start,@end is NULL->WHERE c.Type=@type-- this should execute
CASE 3=wen @value is null->WHERE c.Date_Redeemed BETWEEN @Start AND @End AND c.Type=@type this should execute

CASE4=wen @marketclass is NULL->WHERE c.Date_Redeemed BETWEEN @Start AND @End AND c.Type=@type AND c.ordervalue BETWEEN @price1 AND @price2

VAR=@type,@start,@price1,@marketclass if eithr of var is NULL dynamicaly other input where condition has to execute like diff combination of input comes

WHERE
   (c.Type = @type AND o.Date_of_Purchase BETWEEN @start AND @end) OR
   (@start IS NULL AND c.Type = @type) OR
   (@type IS NULL and o.Date_of_Purchase BETWEEN @start AND @end) OR
   (@start IS NULL AND @type IS NULL)

if both are provided, only rows where type and date match are returned,

if type is not provided, date is used,

if date not provided type is used and

if nothing provided all rows return. To make no rows return, remove the last predicate

Code:

CREATE PROCEDURE dbo.sample
    @start DATE, @end DATE,
    @type VARCHAR(5),
    @price1 MONEY, @price2 MONEY
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @SQL VARCHAR(MAX)

    SET @SQL= 'SELECT DISTINCT o.O_Id,o.Sale_Price,o.Order_Line_Id,Private_Band,c.Date_of_Purchase,c.Date_Redeemed,c.Credit_Memo,c.Credit_Memo_Created_Date,c.Credit_Memo_Approved_Date,
    c.Type,c.Points_Issued,o.Date_of_Purchase FROM Order_Details o ,Transaction_Historys c WHERE -1='-1''
    IF @type IS NOT NULL AND @type <> 0
    SET @SQL = @SQL+ 'c.Type = @type'
    ELSE
    IF @start IS NOT NULL AND @start <> 0
    SET @SQL = @SQL+ 'c.Date_redeemed BETWEEN @start AND @end'

    EXECUTE dbo.sample @type='Earn',@start='2010-02-10',@end='2020-04-11'
END

Body:
Having looked through this, I'm actually kind of reluctant to post this answer, because there's so many things wrong with this:

prone to SQL injection;

using antiquated JOIN syntax;

clunky logic.

The simple answer is that sometimes just because you CAN do something in SQL doesn't mean you actually SHOULD.

Anyway, I think is closer to what you wanted?

CREATE PROCEDURE dbo.[sample] (
    @start DATE,
    @end DATE,
    @type VARCHAR(5),
    @price1 NUMERIC(9,2),
    @price2 NUMERIC(9,2))
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @sql VARCHAR(1024);
    SELECT @sql = N'
        SELECT DISTINCT
            o.O_Id,
            o.Sale_Price,
            o.Order_Line_Id,
            Private_Band, --alias?
            c.Date_of_Purchase,
            c.Date_Redeemed,
            c.Credit_Memo,
            c.Credit_Memo_Created_Date,
            c.Credit_Memo_Approved_Date,
            c.Type,
            c.Points_Issued,
            o.Date_of_Purchase
        FROM
            Order_Details o,
            Transaction_Historys c'; --Join condition?!
    DECLARE @constraint VARCHAR(1024) = '';
    IF @type IS NOT NULL AND @type != 0
    BEGIN
        SELECT @constraint = CONCAT(' WHERE c.Type = ''', @type, '''');
    END;
    IF @start IS NOT NULL AND @end IS NOT NULL
    BEGIN
        SELECT @constraint = CONCAT(@constraint,
            CASE WHEN @constraint = '' THEN ' WHERE ' ELSE ' AND ' END,
            ' c.Date_redeemed BETWEEN ''',
            CONVERT(VARCHAR(12), @start, 112),
            ''' AND ''',
            CONVERT(VARCHAR(12), @end, 112)),
            '''';
    END;
    SELECT @sql = CONCAT(@sql, @constraint);
    EXEC sp_executesql @sql;
END;
GO
EXEC dbo.[sample] @type = 'Earn', @start = '20100210', @end = '20200411', @price1 = NULL, @price2 = NULL;

I made quite a few changes here:

I couldn't bring myself to use a MONEY type, so change it back if you really want it;

I added some comments to your script ;)

I sort of fixed the actual issue, that you need to cope with one or two or even no constraints being passed in.