问:
HTTP 400 Error: size is too accurate. Smallest unit is 0.00000001
i am making a call to

```<code>
authedClient.placeOrder(sellParams)

</code>```

with params:

```<code>
sellParams:any = {
    'side': 'sell',
    'product_id': 'BTC-USD',
    'type': ‘market’,
    ’size’: 0.012613515
}

</code>```

this throws error:

```<code>Error: HTTP 400 Error: size is too accurate. Smallest unit is 0.00000001
    at Request._callback (/srv/node_modules/coinbase-pro/lib/clients/public.js:68:15)
    at Request.self.callback (/srv/node_modules/request/request.js:185:22)
    at emitTwo (events.js:126:13)
</code>```

i am not sure why it fails. Please advise

答:
I can add an update this, definitely the order float algebra is a little wonky and differs by exchange.  For CB/CB Pro you'll want to get info on your base_increment for sell orders and quote_increment for buy orders, in string format, run a function like this:

```<code>def get_increments(ticker, auth_client):
    products = auth_client.get_products()
    for i in range(len(products)):
        if products[i]['id'] == ticker:
            base_incr = products[i]['base_increment']
            quote_incr = products[i]['quote_increment']
    return base_incr, quote_incr
</code>```

i.  Next, you'll want to utilize those increments to round down.  I divide by the appropriate increment, use floor division by 1, then multiply by the same increment.

ii.  To be safe, I get a decimal count again using string manipulation functions, and run something like round(qty, decimals).  This cleans up the occasional lagging string of 9999999 or else 00000001.

iii.  If you're looking to trade with 100% equity, use the funds argument in buy (quote asset value), and size argument in sell (base asset value).
Buy code looks something like:

```<code>decimals = int(str(quote_incr).find('1'))-int(str(quote_incr).find('.'))
quote_incr = float(quote_incr)
qty = (qty/quote_incr//1)*quote_incr
qty = str(round(qty,decimals))
auth_client.place_market_order(product_id=ticker, side='buy', funds=qty)
</code>```

While sell code looks something like:

```<code>decimals = int(str(base_incr).find('1'))-int(str(base_incr).find('.'))
base_incr = float(base_incr_
qty = (qty/base_incr//1)*base_incr
qty = str(round(qty,decimals))
auth_client.place_market_order(product_id=ticker, side='buy', size=qty)
</code>```

Body:
i am making a call to

authedClient.placeOrder(sellParams)

with params:

sellParams:any = {
    'side': 'sell',
    'product_id': 'BTC-USD',
    'type': ‘market’,
    ’size’: 0.012613515
}

this throws error:

Error: HTTP 400 Error: size is too accurate. Smallest unit is 0.00000001
    at Request._callback (/srv/node_modules/coinbase-pro/lib/clients/public.js:68:15)
    at Request.self.callback (/srv/node_modules/request/request.js:185:22)
    at emitTwo (events.js:126:13)

i am not sure why it fails. Please advise

Body:
I can add an update this, definitely the order float algebra is a little wonky and differs by exchange.  For CB/CB Pro you'll want to get info on your base_increment for sell orders and quote_increment for buy orders, in string format, run a function like this:

def get_increments(ticker, auth_client):
    products = auth_client.get_products()
    for i in range(len(products)):
        if products[i]['id'] == ticker:
            base_incr = products[i]['base_increment']
            quote_incr = products[i]['quote_increment']
    return base_incr, quote_incr

i.  Next, you'll want to utilize those increments to round down.  I divide by the appropriate increment, use floor division by 1, then multiply by the same increment.

ii.  To be safe, I get a decimal count again using string manipulation functions, and run something like round(qty, decimals).  This cleans up the occasional lagging string of 9999999 or else 00000001.

iii.  If you're looking to trade with 100% equity, use the funds argument in buy (quote asset value), and size argument in sell (base asset value).
Buy code looks something like:

decimals = int(str(quote_incr).find('1'))-int(str(quote_incr).find('.'))
quote_incr = float(quote_incr)
qty = (qty/quote_incr//1)*quote_incr
qty = str(round(qty,decimals))
auth_client.place_market_order(product_id=ticker, side='buy', funds=qty)

While sell code looks something like:

decimals = int(str(base_incr).find('1'))-int(str(base_incr).find('.'))
base_incr = float(base_incr_
qty = (qty/base_incr//1)*base_incr
qty = str(round(qty,decimals))
auth_client.place_market_order(product_id=ticker, side='buy', size=qty)


来源: stackexchange

问:
Generate a composite unique constraint/index with owned entity, in EF Core
I have an entity that owns another entity

```<code>public class Entity1
{
  [Key]
  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public virtual int ID { get; set; }

  public string Property { get; set; }

  public Entity2 Description { get; set; }
}

public class Entity2
{
   public string Test { get; set; }
}
</code>```

and I need to create an index on Entity1.Property and Entity2.Test. The configuration is like this

```<code>builder.OwnsOne(pt => pt.Description);

builder.HasIndex(p => new { p.Property, p.Description.Test }).IsUnique();
//builder.HasIndex("Property", "Description_Test").IsUnique();
</code>```

I tried both of the above code but they do not work. The first says

```<code>The properties expression 'p => new <>f__AnonymousType3`7(Property = p.DeviceClassId,
Test = p.Description.Test)' is not valid. The expression should represent a property
access: 't => t.MyProperty'. When specifying multiple properties use an anonymous type:
't => new { t.MyProperty1, t.MyProperty2 }'.
Parameter name: propertyAccessExpression
</code>```

and the second one says:

```<code>The property 'Description_test' cannot be added to the type 'Entity1' because there was no
property type specified and there is no corresponding CLR property or field. To add a
shadow state property the property type must be specified.
</code>```

Can this be achieved without modifying the migration manually?

答:
A workaround that solved for me, was deleting in the migration's directory the autogenerated file DataContextModelSnapshot.cs and running again the migration it was regenerated, had some databases already referenced in the migration file that was just deleting and was done...
Might not be the most elegant solution, but it does work.

Just for reference, it happened with the EF Core 6.0 twice.

ContentLicense: CC BY-SA 4.0

Body:
I have an entity that owns another entity

public class Entity1
{
  [Key]
  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public virtual int ID { get; set; }

  public string Property { get; set; }

  public Entity2 Description { get; set; }
}

public class Entity2
{
   public string Test { get; set; }
}

and I need to create an index on Entity1.Property and Entity2.Test. The configuration is like this

builder.OwnsOne(pt => pt.Description);

builder.HasIndex(p => new { p.Property, p.Description.Test }).IsUnique();
//builder.HasIndex("Property", "Description_Test").IsUnique();

I tried both of the above code but they do not work. The first says

The properties expression 'p => new <>f__AnonymousType3`7(Property = p.DeviceClassId,
Test = p.Description.Test)' is not valid. The expression should represent a property
access: 't => t.MyProperty'. When specifying multiple properties use an anonymous type:
't => new { t.MyProperty1, t.MyProperty2 }'.
Parameter name: propertyAccessExpression

and the second one says:

The property 'Description_test' cannot be added to the type 'Entity1' because there was no
property type specified and there is no corresponding CLR property or field. To add a
shadow state property the property type must be specified.

Can this be achieved without modifying the migration manually?


问:
Selenide-How to maximise the browser window
After Selenide 6.0.1 version they deleted Configuration.startMaximized. How can we maximize browser now?</p>

答:
Just use the pre-defined size of the browser, it helps you to avoid unexpected behavior in tests, especially on remote runs.</p>
```<code> Configuration.browserSize = "1920x1080";
</code>```

Body:
Just use the pre-defined size of the browser, it helps you to avoid unexpected behavior in tests, especially on remote runs.

 Configuration.browserSize = "1920x1080";


问:
How do I configure a secret in docker compose?
I have a simple docker compose that makes use of a secret. However I have been unable to access the secret. The logs show the /run/secrets/username being passed in the server but not the actual username. What's wrong with my setup? How do I get the secret value from DB_USERNAME within my service?

```<code>version: "3.9"

services:
  ...
  bank-microservice:
    image: ${IMAGE_BANK}
    restart: on-failure
    networks:
      - backend
    expose:
      - 80
    secrets:
      - username
    environment:
      - DB_USERNAME=/run/secrets/username
    env_file:
      - ./env/microservice.env
    depends_on:
      - db
secrets:
  username:
    file: ./secrets/username
...
</code>```

答:
Setting a secret only exposes that value at a filesystem location under /run/secrets. If you want to get that value into a variable, you would need to do that yourself as part of your container startup.

For example, an ENTRYPOINT script like that this would make /run/secrets/username available as DB_USERNAME:

```<code>#!/bin/sh

if [ -f /run/secrets/username ]; then
  export DB_USERNAME=$(cat /run/secrets/username)
fi

exec "$@"
</code>```

Body:
I have a simple docker compose that makes use of a secret. However I have been unable to access the secret. The logs show the /run/secrets/username being passed in the server but not the actual username. What's wrong with my setup? How do I get the secret value from DB_USERNAME within my service?

version: "3.9"

services:
  ...
  bank-microservice:
    image: ${IMAGE_BANK}
    restart: on-failure
    networks:
      - backend
    expose:
      - 80
    secrets:
      - username
    environment:
      - DB_USERNAME=/run/secrets/username
    env_file:
      - ./env/microservice.env
    depends_on:
      - db
secrets:
  username:
    file: ./secrets/username
...

Body:
Setting a secret only exposes that value at a filesystem location under /run/secrets. If you want to get that value into a variable, you would need to do that yourself as part of your container startup.

For example, an ENTRYPOINT script like that this would make /run/secrets/username available as DB_USERNAME:

#!/bin/sh

if [ -f /run/secrets/username ]; then
  export DB_USERNAME=$(cat /run/secrets/username)
fi

exec "$@"


问:
How do you represent the equivalent of java's MyType<? extends MyConstraint> in typescript without using "any"?
In Java I could write something like List<MyClass<? extends MyConstraint>> to express "a list of instances of MyClass instanciated with various types for T, all extending MyConstraint".

It's not the same thing as List<MyClass<MyConstraint>>, because A inheriting MyConstraint doesn't make MyClass assignable to MyClass<MyConstraint>

I think typescript should be expressive enough to express that, but I can't find how to do it... Did I miss something here ?

Oh and our project uses the no-explicit-any eslint rule. So it this situation a valid usecase for List<MyClass<any>> ?

答:
The equivilent in Typescript is actually very similar to what you referenced with Java.

type Foo<T extends MyConstraint> = Array<MyClass<T>>;
```

This would create an array type where the instances of MyClass have their parameterized generic argument constrained to anything that is a sub-type of MyConstraint just as you had done with Java.

This can come in different flavors depending on what you're doing (creating a type, defining a generic class, defining a generic function, etc) but the basic syntax is <T extends SomeConstraint>.

Here's the relevant Typescript docs talking about generic constraints which covers all the details:
https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-constraints

Body:
The equivilent in Typescript is actually very similar to what you referenced with Java.

type Foo<T extends MyConstraint> = Array<MyClass<T>>;

This would create an array type where the instances of MyClass have their parameterized generic argument constrained to anything that is a sub-type of MyConstraint just as you had done with Java.

This can come in different flavors depending on what you're doing (creating a type, defining a generic class, defining a generic function, etc) but the basic syntax is <T extends SomeConstraint>.

Here's the relevant Typescript docs talking about generic constraints which covers all the details:
https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-constraints


问:
How to create IOStream operator overloads so that anything derived from the base class can read from and written to such streams
This is my code so far:

```<code>
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <type_traits>

// Abstract base class given - cannot be changed

class basis{
public:
    virtual ~basis() { }
    virtual std::istream& load(std::istream& is) = 0;  // i.e., pure virtual
    virtual std::ostream& save(std::ostream& os) const = 0;  // i.e., pure virtual
};

// IOStream overloaded functions given - cannot be changed

inline std::ostream& operator<<(std::ostream& os, basis const& b){
    return b.save(os);
}
inline std::istream& operator>>(std::istream& is, basis& b){
    return b.load(is);
}

class vector3d : public basis {
private:
    double x, y, z;

public:
    // Define a public default constructor that initializes the x, y, and z values to
    // zero values BEFORE execution enters the constructor body

    vector3d() : x{ 0 }, y{ 0 }, z{ 0 } {}      // default constructor

    // Define a constructor accepting 3 double values (one each for x, y, and z)
    // and use those arguments to set the constructed object's x, y, and z values
    // BEFORE execution enters the constructor body

    vector3d(double x, double y, double z) : x{ x }, y{ y }, z{ z } {}

    // Since the parent basis class is abstract, you must
    // Implement the load() and save() functions in your vector3d object.
    // ******************************************************************
    // Prototypes are given - cannot be changed

    std::istream& load(std::istream& is) override {

        /* old version of this function, when vector3d was struct
        char lbraket = '<', comma1 = ',', comma2 = ',', rbraket = '>';
        vector3d temp;

        if ((is >> lbraket >> temp.x >> comma1 >> temp.y >> comma2 >> temp.z >> rbraket)
            && lbraket == '<' && comma1 == ',' && comma2 == ',' && rbraket == '>';){
            v = temp;
            return is;
        }
        else {
            is.setstate(std::ios::failbit);
        }
        */
        return is;
    }

    std::ostream& save(std::ostream& os) const override {

        os << '<' << vector3d.x << ',' << vector3d.y << ',' << vector3d.z << '>';
        //os << static_cast <std::underlying_type_t<vector3d>> (x, y, z);
        //os << static_cast <std::underlying_type_t<vector3d>>;

        return os;
    }

    // To perform the summing of vectors, write one more function,
    // e.g., an operator +() definition. You must write it as a friend
    // function to the class by first writing in your vector3d class :

    friend vector3d operator+(vector3d const& a, vector3d const& b);

};

    // Write a definition of this operator +() function(completely outside of your
    // vector3d class).

vector3d operator+(vector3d const& a, vector3d const& b) {
    vector3d s{ 0,0,0 };

    s.x = a.x + b.x;
    s.y = a.y + b.y;
    s.z = a.z + b.z;

    return s;

    }

// Main given - cannot be changed

int main(){

    unsigned count = 0;
    vector3d sum;
    for (vector3d v; std::cin >> v; ++count)
        sum = sum + v;

    basis& bsum = sum;  // bsum uses sum polymorphically
    std::cout
        << "count: " << count << '\n'
        << "sum: " << bsum << '\n'
        ;
}

</code>```

I know the load() and save() functions must be defined in vector3d. I know they must be able to input from/output to the console vectors in the format <1.0,2.0,3.0>. Input should be read in as long as the format is correct.

I don't understand how to define the load() and save() functions, or why they are called load and save (if it even matters). I tried everything in the textbook and lecture slides. I can't even find an example of how to write input/output function like these online.

I tried adapting the code from a similar but simpler program where vector3d was a struct instead of a class, but nothing has worked so far.

答:
This worked! Thank you!</p>
```<code>std::istream& load(std::istream& is) override {
        char lbraket = '<', comma1 = ',', comma2 = ',', rbraket = '>';
        vector3d temp;

        if ((is >> lbraket >> temp.x >> comma1 >> temp.y >> comma2 >> temp.z >> rbraket)
            && lbraket == '<' && comma1 == ',' && comma2 == ',' && rbraket == '>'){
            *this = temp;
            return is;
        }
        else {
            is.setstate(std::ios::failbit);
        }

        return is;
    }

    std::ostream& save(std::ostream& os) const override {
        os << '<' << x << ',' << y << ',' << z << '>';
        return os;
    }
</code>```

Body:
This is my code so far:

#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <type_traits>

// Abstract base class given - cannot be changed

class basis{
public:
    virtual ~basis() { }
    virtual std::istream& load(std::istream& is) = 0;  // i.e., pure virtual
    virtual std::ostream& save(std::ostream& os) const = 0;  // i.e., pure virtual
};

// IOStream overloaded functions given - cannot be changed

inline std::ostream& operator<<(std::ostream& os, basis const& b){
    return b.save(os);
}
inline std::istream& operator>>(std::istream& is, basis& b){
    return b.load(is);
}

class vector3d : public basis {
private:
    double x, y, z;

public:
    // Define a public default constructor that initializes the x, y, and z values to
    // zero values BEFORE execution enters the constructor body

    vector3d() : x{ 0 }, y{ 0 }, z{ 0 } {}      // default constructor

    // Define a constructor accepting 3 double values (one each for x, y, and z)
    // and use those arguments to set the constructed object's x, y, and z values
    // BEFORE execution enters the constructor body

    vector3d(double x, double y, double z) : x{ x }, y{ y }, z{ z } {}

    // Since the parent basis class is abstract, you must
    // Implement the load() and save() functions in your vector3d object.
    // ******************************************************************
    // Prototypes are given - cannot be changed

    std::istream& load(std::istream& is) override {

        /* old version of this function, when vector3d was struct
        char lbraket = '<', comma1 = ',', comma2 = ',', rbraket = '>';
        vector3d temp;

        if ((is >> lbraket >> temp.x >> comma1 >> temp.y >> comma2 >> temp.z >> rbraket)
            && lbraket == '<' && comma1 == ',' && comma2 == ',' && rbraket == '>';){
            v = temp;
            return is;
        }
        else {
            is.setstate(std::ios::failbit);
        }
        */
        return is;
    }

    std::ostream& save(std::ostream& os) const override {

        os << '<' << vector3d.x << ',' << vector3d.y << ',' << vector3d.z << '>';
        //os << static_cast <std::underlying_type_t<vector3d>> (x, y, z);
        //os << static_cast <std::underlying_type_t<vector3d>>;

        return os;
    }

    // To perform the summing of vectors, write one more function,
    // e.g., an operator +() definition. You must write it as a friend
    // function to the class by first writing in your vector3d class :

    friend vector3d operator+(vector3d const& a, vector3d const& b);

};

    // Write a definition of this operator +() function(completely outside of your
    // vector3d class).

vector3d operator+(vector3d const& a, vector3d const& b) {
    vector3d s{ 0,0,0 };

    s.x = a.x + b.x;
    s.y = a.y + b.y;
    s.z = a.z + b.z;

    return s;

    }

// Main given - cannot be changed

int main(){

    unsigned count = 0;
    vector3d sum;
    for (vector3d v; std::cin >> v; ++count)
        sum = sum + v;

    basis& bsum = sum;  // bsum uses sum polymorphically
    std::cout
        << "count: " << count << '\n'
        << "sum: " << bsum << '\n'
        ;
}

I know the load() and save() functions must be defined in vector3d. I know they must be able to input from/output to the console vectors in the format <1.0,2.0,3.0>. Input should be read in as long as the format is correct.

I don't understand how to define the load() and save() functions, or why they are called load and save (if it even matters). I tried everything in the textbook and lecture slides. I can't even find an example of how to write input/output function like these online.

I tried adapting the code from a similar but simpler program where vector3d was a struct instead of a class, but nothing has worked so far.

Body:
This worked! Thank you!

std::istream& load(std::istream& is) override {
        char lbraket = '<', comma1 = ',', comma2 = ',', rbraket = '>';
        vector3d temp;

        if ((is >> lbraket >> temp.x >> comma1 >> temp.y >> comma2 >> temp.z >> rbraket)
            && lbraket == '<' && comma1 == ',' && comma2 == ',' && rbraket == '>'){
            *this = temp;
            return is;
        }
        else {
            is.setstate(std::ios::failbit);
        }

        return is;
    }

    std::ostream& save(std::ostream& os) const override {
        os << '<' << x << ',' << y << ',' << z << '>';
        return os;
    }


问:
How to validate one input field + search-button with Formik in React?
I am trying to validate input using Formik with one single input field that is connected to a search button. This is what I want to achieve:

I want to accept only numbers

If the user enters alphabetic characters, I want to show a div with a error message.

My question is:

What's the best approach when instead of a submit button I have a SEARCH button?

All the solutions I find so far are with several input fields with a submit button, either like this one:

https://formik.org/docs/api/errormessage

```<code> Or like this one:
</code>```
```<code> // Synchronous validation
 const validate = (values, props /* only available when using withFormik */) => {
   const errors = {};

   if (!values.email) {
     errors.email = 'Required';
   } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
     errors.email = 'Invalid email address';
   }

   //...

   return errors;
 };
</code>```

My code so far:

```<code><FlexItem flex={1.5}>
                        <FormikInput
                            id={`reportName`}
                            name={`reportName`}
                            label={'Invoice number'}

                            placeholder={'Search for an existing invoice number'}
                            onChange={e => {
                                setInput(e.target.value);
                            }}
                            value={input}
                            type={'number'} //?
                        />
                    </FlexItem>
                    <FlexItem className="flex-toolbar-button">
                        <StyledToolbarButton
                            size="normal"
                            buttonStyling="primary"
                            onClick={() => {
                                setSegmentId(segmentInput);
                                setInvoiceId(input);
                            }}
                            disabled={!segmentInput || !input}
                        >
                            Search
                        </StyledToolbarButton>
                    </FlexItem>
</code>```

答:
I am not sure if this is what you are looking for, but this function will prevent the user from typing in the input if he types anything else than a number:

```<code> const handlePreventNonNumericOnKeyPress = e => {
    //on keypress prevent entering nonnumeric values
    //if key code is not between key codes of numeric values from 0 to 9, prevent the action
    if (!(e.which >= 48 && e.which <= 57)) {
        e.preventDefault();
    }
};
</code>```

also you should add the onKeyPress (or onKeyDown, not sure for Formik) handler on your input, where you call this function, I guess you need it here:

```<code><FormikInput
                            id={`reportName`}
                            name={`reportName`}
                            label={'Invoice number'}
                            placeholder={'Search for an existing invoice number'}
                           onKeyPress={handlePreventNonNumericOnKeyPress}
                          onChange={e => {
                                setInput(e.target.value);
                            }}
                            value={input}
                            type={'number'}
                        />
</code>```

Body:
I am trying to validate input using Formik with one single input field that is connected to a search button. This is what I want to achieve:

I want to accept only numbers

If the user enters alphabetic characters, I want to show a div with a error message.

My question is:

What's the best approach when instead of a submit button I have a SEARCH button?

All the solutions I find so far are with several input fields with a submit button, either like this one:

https://formik.org/docs/api/errormessage

 Or like this one:

 // Synchronous validation
 const validate = (values, props /* only available when using withFormik */) => {
   const errors = {};

   if (!values.email) {
     errors.email = 'Required';
   } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
     errors.email = 'Invalid email address';
   }

   //...

   return errors;
 };

My code so far:

<FlexItem flex={1.5}>
                        <FormikInput
                            id={`reportName`}
                            name={`reportName`}
                            label={'Invoice number'}

                            placeholder={'Search for an existing invoice number'}
                            onChange={e => {
                                setInput(e.target.value);
                            }}
                            value={input}
                            type={'number'} //?
                        />
                    </FlexItem>
                    <FlexItem className="flex-toolbar-button">

                    </FlexItem>

Body:
I am not sure if this is what you are looking for, but this function will prevent the user from typing in the input if he types anything else than a number:

 const handlePreventNonNumericOnKeyPress = e => {
    //on keypress prevent entering nonnumeric values
    //if key code is not between key codes of numeric values from 0 to 9, prevent the action
    if (!(e.which >= 48 && e.which <= 57)) {
        e.preventDefault();
    }
};

also you should add the onKeyPress (or onKeyDown, not sure for Formik) handler on your input, where you call this function, I guess you need it here:

<FormikInput
                            id={`reportName`}
                            name={`reportName`}
                            label={'Invoice number'}
                            placeholder={'Search for an existing invoice number'}
                           onKeyPress={handlePreventNonNumericOnKeyPress}
                          onChange={e => {
                                setInput(e.target.value);
                            }}
                            value={input}
                            type={'number'}
                        />


问:
C# Entity Framework Core: unable to resolve service
I'm trying to use Entity Framework Core for C# for the first time. My project does compile, but my add-migration does not run.

I get the error:

Unable to resolve service for type 'Microsoft.EntityFrameworkCore.Storage.TypeMappingSourceDependencies' while attempting to activate 'MySql.EntityFrameworkCore.Storage.Internal.MySQLTypeMappingSource'.

My project file:

```<code><Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="BCrypt.Net-Next" Version="4.0.2" />
    <PackageReference Include="EntityFramework" Version="6.4.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.1">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="MySql.EntityFrameworkCore" Version="6.0.0" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
  </ItemGroup>
</Project>
</code>```

My DbContext:

```<code>internal class DbModelContext : DbContext
{
    public DbSet<DbUser> Users { get; set; }
    public DbModelContext(DbContextOptions<DbModelContext> options)
        : base(options) { }
}
</code>```

My user table:

```<code>internal class DbUser
{
    [Key]
    public string? Email { get; set; }
    public string? PasswordHash { get; set; }
    public Guid UserId { get; set; }
}
</code>```

Here is my Program.cs (im using net6 so i dont have a startup.cs)

```<code>//Init DbConnectorClass
DatabaseConnector dbConnector = new();

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//TODO: move to appsettings.json
var connString = "server=192.168.178.XXX;user=XXX;database=XXX;password=XXX;port=3306";

builder.Services.AddDbContext<DbModelContext>(options => options.UseMySQL(connString));
builder.Services.AddScoped<IAuthenticationHandler>(ah => new AuthenticationHandler(dbConnector));

WebApplication app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
</code>```

答:
if you setup your database properly then try this command "dotnet ef migrations add Initial"
for update try "dotnet ef database update"</p>

Body:
I'm trying to use Entity Framework Core for C# for the first time. My project does compile, but my add-migration does not run.

I get the error:

Unable to resolve service for type 'Microsoft.EntityFrameworkCore.Storage.TypeMappingSourceDependencies' while attempting to activate 'MySql.EntityFrameworkCore.Storage.Internal.MySQLTypeMappingSource'.

My project file:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="BCrypt.Net-Next" Version="4.0.2" />
    <PackageReference Include="EntityFramework" Version="6.4.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.1">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="MySql.EntityFrameworkCore" Version="6.0.0" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
  </ItemGroup>
</Project>

My DbContext:

internal class DbModelContext : DbContext
{
    public DbSet<DbUser> Users { get; set; }
    public DbModelContext(DbContextOptions<DbModelContext> options)
        : base(options) { }
}

My user table:

internal class DbUser
{
    [Key]
    public string? Email { get; set; }
    public string? PasswordHash { get; set; }
    public Guid UserId { get; set; }
}

Here is my Program.cs (im using net6 so i dont have a startup.cs)

//Init DbConnectorClass
DatabaseConnector dbConnector = new();

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//TODO: move to appsettings.json
var connString = "server=192.168.178.XXX;user=XXX;database=XXX;password=XXX;port=3306";

builder.Services.AddDbContext<DbModelContext>(options => options.UseMySQL(connString));
builder.Services.AddScoped<IAuthenticationHandler>(ah => new AuthenticationHandler(dbConnector));

WebApplication app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();


问:
How filter array of objects based on objects exists in another array of objects?
I have

```<code>array1 = [{ name: sample1 }, { name: sample2 }, { name: sample3 }];
array2 = [{ name: sample1 }, { name: sample2 }];
</code>```

I want to filter objects of array1 which exists in array2.
So I need to have

```<code>[{ name: sample1 }, { name: sample2 }]
</code>```

How can I get it in javascript?

答:
You can use  .filter and .some function in JavaScript ,
Here is the example</p>
```<code>const array1 = [{ name: "sample1" }, { name: "sample2" }, {
name: "sample3" }];
 const array2 = [{ name: "sample1" }, { name: "sample2" }];
let Result = array1.filter(function(obj) {
  return array2.some(function(obj2) {
    return obj.name== obj2.name;
});
});
console.log(Result)
</code>```

Body:
I have

array1 = [{ name: sample1 }, { name: sample2 }, { name: sample3 }];
array2 = [{ name: sample1 }, { name: sample2 }];

I want to filter objects of array1 which exists in array2.
So I need to have

[{ name: sample1 }, { name: sample2 }]

How can I get it in javascript?

Body:
You can use  .filter and .some function in JavaScript ,
Here is the example

const array1 = [{ name: "sample1" }, { name: "sample2" }, {
name: "sample3" }];
 const array2 = [{ name: "sample1" }, { name: "sample2" }];
let Result = array1.filter(function(obj) {
  return array2.some(function(obj2) {
    return obj.name== obj2.name;
});
});
console.log(Result)


问:
How to get Array type data in Firebase in Kotlin?
I have this type of array in firebase but how to fetch it and use in kotlin
I was able to get as String but how to get its as a data class
 Like this

```<code>data class Comment(
    val uid: String,
    val comment: String,
    val stamp: Timestamp
)
</code>```

and here's the code of getting string

```<code>var text by remember { mutableStateOf("loading...") }
FirebaseFirestore.getInstance().collection("MyApp")
  .document("Something").get().addOnSuccessListener {
     text = it.get("Comments").toString()
}
</code>```

答:
I got ArrayLists with HashMaps represents my entities entities just using this:

```<code>                val cleanAnswers: List<Answer> = (document.get(FIELD_ANSWERS)
                        as ArrayList<HashMap<String, Any>>).map {
                    Answer(
                            it[FIELD_VARIANT] as String,
                            it[FIELD_IS_CORRECT] as Boolean
                        )
                }

</code>```

My entity:

```<code>class Answer(val answer: String,
         val isCorrect: Boolean) : Serializable
</code>```

Body:
I have this type of array in firebase but how to fetch it and use in kotlin
I was able to get as String but how to get its as a data class
 Like this

data class Comment(
    val uid: String,
    val comment: String,
    val stamp: Timestamp
)

and here's the code of getting string

var text by remember { mutableStateOf("loading...") }
FirebaseFirestore.getInstance().collection("MyApp")
  .document("Something").get().addOnSuccessListener {
     text = it.get("Comments").toString()
}

Body:
I got ArrayLists with HashMaps represents my entities entities just using this:

                val cleanAnswers: List<Answer> = (document.get(FIELD_ANSWERS)
                        as ArrayList<HashMap<String, Any>>).map {
                    Answer(
                            it[FIELD_VARIANT] as String,
                            it[FIELD_IS_CORRECT] as Boolean
                        )
                }

My entity:

class Answer(val answer: String,
         val isCorrect: Boolean) : Serializable


问:
ASP.NET MVC Identity with SQL Server and Azure AD SSO for Authentication
Does anyone have any knowledge of whether it is possible to implement an ASP.NET MVC website that uses Identity for authentication with both SQL Server user accounts and Azure AD?

Thanks in advance

答:
I created a solution for this case, that I feel is a good solution for authenticating users by user/pass and adding another option for login with Azure AD.

Initially, I implemented Identity in my project. I believe that you can create this with your Visual Studio templates.

After all Identity configurations are implemented, I go to add Azure AD OpenIdConnect instances and options. Its implementation is External Logins with Microsoft Account. (Note this block for personal account if your app registration is created in Azure AD).

It is very important to configure your app registration in Azure Portal with Web Platform and redirect URLs:
https://localhost:5001/signin-oidc
and
https://localhost:5001/

Follow my startup code:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    services.AddDistributedMemoryCache();

    services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromSeconds(10);
        options.Cookie.HttpOnly = true;
        options.Cookie.IsEssential = true;
    });

    #region Microsoft SSO
    // Please read readme.md to understand Microsoft SSO configuration.
    services.AddAuthentication()
        .AddMicrosoftAccount(options =>
        {
            options.ClientId = Configuration.GetValue<string>("ExternalLogin:Microsoft:ClientId");
            options.ClientSecret = Configuration.GetValue<string>("ExternalLogin:Microsoft:ClientSecret");
            options.CallbackPath = Configuration.GetValue<string>("ExternalLogin:Microsoft:CallbackPath");
        });
    #endregion

    services.AddRazorPages();
}
```
<p>And my <code>Configure</code> method to add all items for pipeline.</p>
<pre class="lang-csharp prettyprint-override"><code>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();
    app.UseSession();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
        endpoints.MapRazorPages();
        endpoints.MapControllers();
    });
}
</code>```

Body:
I created a solution for this case, that I feel is a good solution for authenticating users by user/pass and adding another option for login with Azure AD.

Initially, I implemented Identity in my project. I believe that you can create this with your Visual Studio templates.

After all Identity configurations are implemented, I go to add Azure AD OpenIdConnect instances and options. Its implementation is External Logins with Microsoft Account. (Note this block for personal account if your app registration is created in Azure AD).

It is very important to configure your app registration in Azure Portal with Web Platform and redirect URLs:
https://localhost:5001/signin-oidc
and
https://localhost:5001/

Follow my startup code:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    services.AddDistributedMemoryCache();

    services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromSeconds(10);
        options.Cookie.HttpOnly = true;
        options.Cookie.IsEssential = true;
    });

    #region Microsoft SSO
    // Please read readme.md to understand Microsoft SSO configuration.
    services.AddAuthentication()
        .AddMicrosoftAccount(options =>
        {
            options.ClientId = Configuration.GetValue<string>("ExternalLogin:Microsoft:ClientId");
            options.ClientSecret = Configuration.GetValue<string>("ExternalLogin:Microsoft:ClientSecret");
            options.CallbackPath = Configuration.GetValue<string>("ExternalLogin:Microsoft:CallbackPath");
        });
    #endregion

    services.AddRazorPages();
}

And my Configure method to add all items for pipeline.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();
    app.UseSession();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
        endpoints.MapRazorPages();
        endpoints.MapControllers();
    });
}


问:
What does if (print) means in Perl?
I got the following code

```<code>if (print msgsnd($ipc_msg_to_mppt_id, $msg, 0)) {
</code>```

what is the purpose of print here? What is returns?

Documentation says it returns true if successful. But how can printing be unsuccessfull?

答:
Printing isn't necessary as simple as dumping the output to a console. It could also be redirected to a file or some other kind of pipe. If it's redirected to a file you don't have write access to, then printing to that file will fail. If it's piped into another program and the latter program terminates, then writing to it will cause a broken pipe error.

As a general principle, I/O operations are outside the control of your program, so you should always assume that they can fail. Reading to or writing from a file, the console, or any kind of socket or pipe, can always, without warning, fail. So if you want your program to do something about it, you'll need to check the return value of functions like print.

Title: What does if (print) means in Perl?

Body:
I got the following code

if (print msgsnd($ipc_msg_to_mppt_id, $msg, 0)) {

what is the purpose of print here? What is returns?

Documentation says it returns true if successful. But how can printing be unsuccessfull?


问:
Does this cause a memory leak / How should I structure the code
I am slightly concerned that this code may have a memory leak.  I would like to know if in fact there is a leak, and also what is the correct way to go about this problem.

Description: I have a base class Pet with derived classes Cat, Dog, and Bird.  I am parsing lines from a file, and depending on certain contents in that line, I need to create an instance of the derived classes, and then parse part of the line again in a specific way.
Here is a sample file:

```<code>Dog Spot Brown,Labrador,5
Cat Felix Black,7
Bird Polly Green,Parrot,12,Crackers
</code>```

And some code:

```<code>class Pet
{
protected:
  string _type;
  string _name;
  string _desc;

public:
  Pet();
  bool ParseLine(std::string line);
  string Type() { return _type; }
  string Name() { return _name; }
  string Desc() { return _desc; }
};

class Dog : public Pet
{
private:
  string _color;
  string _type;
  int _age;

public:
  Dog(string type, string name, string desc);
  bool ParseDesc(string desc);
};
</code>```

Main Code:

```<code>ifstream infile(filename, ifstream::in);
string line;
while(getline(infile, line))
{
   Pet* pet = new Pet();    // "new" called once
   if(pet->ParseLine(line))
   {
      if(pet->Type() == "Dog")
      {
         pet = new Dog(pet->Type(), pet->Name(), pet->Desc());   // "new" called again
         pet->ParseDesc(pet->Desc());
      }
      else if(pet->Type() == "Cat")
      {
         // ...
      }
   }
}
</code>```

Basically what happens is this:

I take a line from the file and parse it into three fields (this is what ParseLine() does:

```<code>Type (Dog, Cat, Bird, etc.)
Name (Spot, Felix, Polly, etc.)
Description ("Brown,Labrador,5", "Black,7", "Green,Parrot,12,Crackers", etc)
</code>```

I then assign these three fields to my Pet* variable.

Then, according to the value in Pet*->Type(), I parse Pet*->Desc() to get the additional information for that particular type of animal.

I am worried about calling operator "new" twice.  I think there is probably a better way to format the code that could avoid this altogether.

I would really like to keep my getline() routine.  I do NOT want to peek at the line to determine the type, and then decide how to create my instance.

Also, I have to reassign my variables _type, _name, and _desc, when I recreate the Dog(), and I'd rather not have to do that.

Thanks.

--

Specifically, how do I avoid this:

```<code>Pet* pet = new Pet();
pet->ParseLine(line);
string type = pet->Type();
string name = pet->Name();
string desc = pet->Desc();
delete pet;
if(type == "Dog")
{
   Pet* dog = new Dog(type, name, desc);
   dog->ParseDesc(desc);
}
</code>```

答:
I agree with comment about boost::shared_ptr, learn how to use it - it will make your life better

Looking at your '2 news' solution I now see what you are asking. THe ParseLine function should not be an instance method of Pet (A pet doesnt parse a line, a pet barks, eats, walks etc)

YOu should have a PetFactory class, that has a static method ParseLine and that returns a polymorphic Pet* (or better a PetPtr)

ContentLicense: CC BY-SA 3.0

Body:
I am slightly concerned that this code may have a memory leak.  I would like to know if in fact there is a leak, and also what is the correct way to go about this problem.

Description: I have a base class Pet with derived classes Cat, Dog, and Bird.  I am parsing lines from a file, and depending on certain contents in that line, I need to create an instance of the derived classes, and then parse part of the line again in a specific way.
Here is a sample file:

Dog Spot Brown,Labrador,5
Cat Felix Black,7
Bird Polly Green,Parrot,12,Crackers

And some code:

class Pet
{
protected:
  string _type;
  string _name;
  string _desc;

public:
  Pet();
  bool ParseLine(std::string line);
  string Type() { return _type; }
  string Name() { return _name; }
  string Desc() { return _desc; }
};

class Dog : public Pet
{
private:
  string _color;
  string _type;
  int _age;

public:
  Dog(string type, string name, string desc);
  bool ParseDesc(string desc);
};

Main Code:

ifstream infile(filename, ifstream::in);
string line;
while(getline(infile, line))
{
   Pet* pet = new Pet();    // "new" called once
   if(pet->ParseLine(line))
   {
      if(pet->Type() == "Dog")
      {
         pet = new Dog(pet->Type(), pet->Name(), pet->Desc());   // "new" called again
         pet->ParseDesc(pet->Desc());
      }
      else if(pet->Type() == "Cat")
      {
         // ...
      }
   }
}

Basically what happens is this:

I take a line from the file and parse it into three fields (this is what ParseLine() does:

Type (Dog, Cat, Bird, etc.)
Name (Spot, Felix, Polly, etc.)
Description ("Brown,Labrador,5", "Black,7", "Green,Parrot,12,Crackers", etc)

I then assign these three fields to my Pet* variable.

Then, according to the value in Pet*->Type(), I parse Pet*->Desc() to get the additional information for that particular type of animal.

I am worried about calling operator "new" twice.  I think there is probably a better way to format the code that could avoid this altogether.

I would really like to keep my getline() routine.  I do NOT want to peek at the line to determine the type, and then decide how to create my instance.

Also, I have to reassign my variables _type, _name, and _desc, when I recreate the Dog(), and I'd rather not have to do that.

Thanks.

--

Specifically, how do I avoid this:

Pet* pet = new Pet();
pet->ParseLine(line);
string type = pet->Type();
string name = pet->Name();
string desc = pet->Desc();
delete pet;
if(type == "Dog")
{
   Pet* dog = new Dog(type, name, desc);
   dog->ParseDesc(desc);
}


问:
Django shell mode in docker
I am learning how to develop Django application in docker with this official tutorial: https://docs.docker.com/compose/django/

I have successfully run through the tutorial, and

docker-compose run web django-admin.py startproject composeexample . creates the image
docker-compose up runs the application

The question is:

I often use python manage.py shell to run Django in shell mode, but I do not know how to achieve that with docker.

答:
If you're using Docker Compose (using command docker compose up) to spin up your applications, after you run that command then you can run the interactive shell in the container by using the following command:

```<code>docker compose exec <container id or name of your Django app> python3 <path to your manage.py file, for example, src/manage.py> shell
</code>```

Keep in mind the above is using Python version 3+ with python3.

Title: Django shell mode in docker

Body:
If you're using Docker Compose (using command docker compose up) to spin up your applications, after you run that command then you can run the interactive shell in the container by using the following command:

docker compose exec <container id or name of your Django app> python3 <path to your manage.py file, for example, src/manage.py> shell

Keep in mind the above is using Python version 3+ with python3.


问:
Bisection Method Jupyter Notebook
Using bisection method to find p3 for f(x) = sqrt(x) - cos(x), I got the right answer on paper p3 = .625

I am having a trouble converting the problem and solving it using Jupyter notebook. Any tips?

Jupyter Notebook code

答:
0.625 is the third guess in the approximation process so the for loop should be completed before the fourth iteration and the code should be as follows.

import math

##problem statement
#finding a root of f(x) = sqrt(x)-cos(x) between the interval [0,1]
#f(0) = -1 f(1) = 0.45969..  so there is at least one root between the interval [0,1]

a = 0
b = 1
maxIt = 100
negative_result = math.sqrt(a) - math.cos(a)
positive_result = math.sqrt(b) - math.cos(b)

for i in range(maxIt):
    if i == 3:
        print("answer is: ", guess)
        break
    guess = (a+b)/2
    guess_result = math.sqrt(guess) - math.cos(guess)
    if guess_result*negative_result >= 0:
       a = guess
    else:
        b = guess
```
<p>And the output is</p>
```0.625
```

Title: Bisection Method Jupyter Notebook

Body:
0.625 is the third guess in the approximation process so the for loop should be completed before the fourth iteration and the code should be as follows.

import math

##problem statement
#finding a root of f(x) = sqrt(x)-cos(x) between the interval [0,1]
#f(0) = -1 f(1) = 0.45969..  so there is at least one root between the interval [0,1]

a = 0
b = 1
maxIt = 100
negative_result = math.sqrt(a) - math.cos(a)
positive_result = math.sqrt(b) - math.cos(b)

for i in range(maxIt):
    if i == 3:
        print("answer is: ", guess)
        break
    guess = (a+b)/2
    guess_result = math.sqrt(guess) - math.cos(guess)
    if guess_result*negative_result >= 0:
       a = guess
    else:
        b = guess

And the output is

0.625


问:
Function should be called on each calculation
I'm getting this error

line 205: The function 'ta.change' should be called on each
calculation for consistency. It is recommended to extract the call
from the ternary operator or from the scope.

I'm trying but I can't fix it. It's an indicator on tradingview name: OBV MACD Indicator by RafaelZioni, which I want to convert to pine script v5.

```<code>p = 1,src15=tt1
b5 = 0.,dev5 = 0.,oc = 0
n5 = ta.cum(1) - 1
a15 = ta.cum(math.abs(src15 - nz(b5[1],src15)))/n5*p
b5 := src15 > nz(b5[1],src15) + a15 ? src15 : src15 < nz(b5[1],src15) - a15 ? src15 : nz(b5[1],src15)
//----
dev5 := ta.change(b5) ? a15 : nz(dev5[1],a15)

//----
oc := ta.change(b5) > 0 ? 1 : ta.change(b5) < 0 ? -1 : nz(oc[1]) //-->this is the line 205 error
//----
cs = oc == 1 ? color.blue : color.red
//change(oc)>0
plot(b5,color=cs,linewidth=4,transp=50)
//
</code>```

答:
First of all, it is a warning, not an error.

It happens because you are calling a function within the ternary operator. If you want to get rid of this warning message, you should extract it from the ternary operator as the warning message says.

Below code will fix it

```<code>//----
_change_b5 = ta.change(b5)
dev5 := _change_b5 ? a15 : nz(dev5[1],a15)

//----
oc := _change_b5 > 0 ? 1 : _change_b5 < 0 ? -1 : nz(oc[1])
//----
</code>```

Body:
I'm getting this error

line 205: The function 'ta.change' should be called on each
calculation for consistency. It is recommended to extract the call
from the ternary operator or from the scope.

I'm trying but I can't fix it. It's an indicator on tradingview name: OBV MACD Indicator by RafaelZioni, which I want to convert to pine script v5.

p = 1,src15=tt1
b5 = 0.,dev5 = 0.,oc = 0
n5 = ta.cum(1) - 1
a15 = ta.cum(math.abs(src15 - nz(b5[1],src15)))/n5*p
b5 := src15 > nz(b5[1],src15) + a15 ? src15 : src15 < nz(b5[1],src15) - a15 ? src15 : nz(b5[1],src15)
//----
dev5 := ta.change(b5) ? a15 : nz(dev5[1],a15)

//----
oc := ta.change(b5) > 0 ? 1 : ta.change(b5) < 0 ? -1 : nz(oc[1]) //-->this is the line 205 error
//----
cs = oc == 1 ? color.blue : color.red
//change(oc)>0
plot(b5,color=cs,linewidth=4,transp=50)
//

Body:
First of all, it is a warning, not an error.

It happens because you are calling a function within the ternary operator. If you want to get rid of this warning message, you should extract it from the ternary operator as the warning message says.

Below code will fix it

//----
_change_b5 = ta.change(b5)
dev5 := _change_b5 ? a15 : nz(dev5[1],a15)

//----
oc := _change_b5 > 0 ? 1 : _change_b5 < 0 ? -1 : nz(oc[1])
//----


问:
How to write statement that deletes extra space in C++?
I have been working on a project. I am limited to using a few libraries so any additional library would not be helpful. I am building a project, but I am noticing an extra space after the last number when the calendar is finished. How do I fix this extra spacing issue?</p>
```<code>//extracted...
         if (day >= 9)
         {
            std::cout << day;
         }
         else
          std::cout << day << " ";
          std::cout << " ";
      }
   }

</code>```

答:
Version in C: (it uses printf so maybe not what you want)</p>
```<code>void printcalendarmonth(int month, int year)
{
    int indent;
    int nspace = 0;

    Monthinfo m = getmonthinfo(month, year);

    printf("\n%*s %d\n\n", 12, m.name, year);  // ex.) January 2012
    char weekTitle[] = "  S  M Tu  W Th  F  S";
    int spacing = sizeof(weekTitle)/7;

    printf("%s\n", weekTitle);

    indent = m.daystart * spacing;    // m.daystart = weekday number first day is starting on: ex.) Sunday = 0 or 1 I forgot sorry lol
    for (int i = 1; i <= m.days; i++) {
        printf("%*.d", indent, i);
        nspace += indent;
        indent = spacing;
        if (nspace >= spacing*7) {
            printf("\n");
            nspace = 0;
        }
    }
    printf("\n");
}
</code>```

Body:
I have been working on a project. I am limited to using a few libraries so any additional library would not be helpful. I am building a project, but I am noticing an extra space after the last number when the calendar is finished. How do I fix this extra spacing issue?

//extracted...
         if (day >= 9)
         {
            std::cout << day;
         }
         else
          std::cout << day << " ";
          std::cout << " ";
      }
   }

Body:
Version in C: (it uses printf so maybe not what you want)

void printcalendarmonth(int month, int year)
{
    int indent;
    int nspace = 0;

    Monthinfo m = getmonthinfo(month, year);

    printf("\n%*s %d\n\n", 12, m.name, year);  // ex.) January 2012
    char weekTitle[] = "  S  M Tu  W Th  F  S";
    int spacing = sizeof(weekTitle)/7;

    printf("%s\n", weekTitle);

    indent = m.daystart * spacing;    // m.daystart = weekday number first day is starting on: ex.) Sunday = 0 or 1 I forgot sorry lol
    for (int i = 1; i <= m.days; i++) {
        printf("%*.d", indent, i);
        nspace += indent;
        indent = spacing;
        if (nspace >= spacing*7) {
            printf("\n");
            nspace = 0;
        }
    }
    printf("\n");
}


问:
Fatal error: Class 'Redis' not found
I've installed Redis on my ubuntu 14 server with phpredis extension. Im using Nginx server. I have php testing script

```<code>$redis=new Redis() or die("Cannot load Redis module.");
$redis->connect('localhost');
$redis->set('random', rand(5000,6000));
echo $redis->get('random');
</code>```

which is working fine from command-line but not from web browser.

Nginx error log:

```<code>[info] 31102#0: Using 32768KiB of shared memory for push module in /etc/nginx/nginx.conf:82
[error] 31108#0: *21 FastCGI sent in stderr: "PHP message: PHP Fatal error:  Class 'Redis' not found in...
</code>```

i can't see it even in phpinfo()

all installed with apt-get install

all other modules (mysql, imagemagick...) are working fine

i've spent few hours on google but haven't found nothing useful

答: make sure to install a stable version of redis from there: https://pecl.php.net/package/redis</p>

Title: Fatal error: Class 'Redis' not found

Body:
I've installed Redis on my ubuntu 14 server with phpredis extension. Im using Nginx server. I have php testing script

$redis=new Redis() or die("Cannot load Redis module.");
$redis->connect('localhost');
$redis->set('random', rand(5000,6000));
echo $redis->get('random');

which is working fine from command-line but not from web browser.

Nginx error log:

[info] 31102#0: Using 32768KiB of shared memory for push module in /etc/nginx/nginx.conf:82
[error] 31108#0: *21 FastCGI sent in stderr: "PHP message: PHP Fatal error:  Class 'Redis' not found in...

i can't see it even in phpinfo()

all installed with apt-get install

all other modules (mysql, imagemagick...) are working fine

i've spent few hours on google but haven't found nothing useful


问:
Purity vs Referential transparency
The terms do appear to be  defined differently, but I've always thought of one implying the other; I can't think of any case when an expression is referentially transparent but not pure, or vice-versa.

Wikipedia maintains separate articles for these concepts and says:

From Referential transparency:

If all functions involved in the
  expression are pure functions, then
  the expression is referentially
  transparent. Also, some impure
  functions can be included in the
  expression if their values are
  discarded and their side effects are
  insignificant.

From Pure expressions:

Pure functions are required to
  construct pure expressions. [...] Pure
  expressions are often referred to as
  being referentially transparent.

I find these statements confusing. If the side effects from a so-called "impure function" are insignificant enough to allow not performing them (i.e. replace a call to such a function with its value) without materially changing the program, it's the same as if it were pure in the first place, isn't it?

Is there a simpler way to understand the differences between a pure expression and a referentially transparent one, if any? If there is a difference, an example expression that clearly demonstrates it would be appreciated.

答:
Pure functions are those that return the same value on every call, and do not have side effects.

Referential transparency means that you can replace a bound variable with its value and still receive the same output.

Both pure and referentially transparent:

```<code>def f1(x):
    t1 = 3 * x
    t2 = 6
    return t1 + t2
</code>```

Why is this pure?

Because it is a function of only the input x and has no side-effects.

Why is this referentially transparent?

You could replace t1 and t2 in f1 with their respective right hand sides in the return statement, as follows

```<code>def f2(x):
    return 3 * x + 6
</code>```

and f2 will still always return the same result as f1 in every case.

Pure, but not referentially transparent:

Let's modify f1 as follows:

```<code>def f3(x):
    t1 = 3 * x
    t2 = 6
    x = 10
    return t1 + t2
</code>```

Let us try the same trick again by replacing t1 and t2 with their right hand sides, and see if it is an equivalent definition of f3.

```<code>def f4(x):
    x = 10
    return 3 * x + 6
</code>```

We can easily observe that f3 and f4 are not equivalent on replacing variables with their right hand sides / values. f3(1) would return 9 and f4(1) would return 36.

Referentially transparent, but not pure:

Simply modifying f1 to receive a non-local value of x, as follows:

```<code>def f5:
    global x
    t1 = 3 * x
    t2 = 6
    return t1 + t2
</code>```

Performing the same replacement exercise from before shows that f5 is still referentially transparent. However, it is not pure because it is not a function of only the arguments passed to it.

Observing carefully, the reason we lose referential transparency moving from f3 to f4 is that x is modified. In the general case, making a variable final (or those familiar with Scala, using vals instead of vars) and using immutable objects can help keep a function referentially transparent. This makes them more like variables in the algebraic or mathematical sense, thus lending themselves better to formal verification.

Title: Purity vs Referential transparency

Body:
Pure functions are those that return the same value on every call, and do not have side effects.

Referential transparency means that you can replace a bound variable with its value and still receive the same output.

Both pure and referentially transparent:

def f1(x):
    t1 = 3 * x
    t2 = 6
    return t1 + t2

Why is this pure?

Because it is a function of only the input x and has no side-effects.

Why is this referentially transparent?

You could replace t1 and t2 in f1 with their respective right hand sides in the return statement, as follows

def f2(x):
    return 3 * x + 6

and f2 will still always return the same result as f1 in every case.

Pure, but not referentially transparent:

Let's modify f1 as follows:

def f3(x):
    t1 = 3 * x
    t2 = 6
    x = 10
    return t1 + t2

Let us try the same trick again by replacing t1 and t2 with their right hand sides, and see if it is an equivalent definition of f3.

def f4(x):
    x = 10
    return 3 * x + 6

We can easily observe that f3 and f4 are not equivalent on replacing variables with their right hand sides / values. f3(1) would return 9 and f4(1) would return 36.

Referentially transparent, but not pure:

Simply modifying f1 to receive a non-local value of x, as follows:

def f5:
    global x
    t1 = 3 * x
    t2 = 6
    return t1 + t2

Performing the same replacement exercise from before shows that f5 is still referentially transparent. However, it is not pure because it is not a function of only the arguments passed to it.

Observing carefully, the reason we lose referential transparency moving from f3 to f4 is that x is modified. In the general case, making a variable final (or those familiar with Scala, using vals instead of vars) and using immutable objects can help keep a function referentially transparent. This makes them more like variables in the algebraic or mathematical sense, thus lending themselves better to formal verification.


问:
Maximum transaction size in PostgreSQL
I have a utility in my application where i need to perform bulk load of INSERT, UPDATE & DELETE operations. I am trying to create transaction around this so that once this system is invoke and the data is fed to it, it is ensured that it is either all or none added to the database.

The concern what is have is what is the boundary conditions here? How many INSERT, UPDATE & DELETE can i have in one transaction? Is transaction size configurable?

答: I don't think there's a maximum amount of work that can be performed in a transaction. Data keeps getting added to the table files, and eventually the transaction either commits or rolls backs: AIUI this result gets stored in pg_clog; if it rolls back, the space will eventually be reclaimed by vacuum. So it's not as if the ongoing transaction work is held in memory and flushed at commit time, for instance.</p>

OwnerDisplayName: Salman

Title: Maximum transaction size in PostgreSQL

LastEditorDisplayName: Milen A. Radev

OwnerDisplayName: araqnid

ContentLicense: CC BY-SA 2.5


问:
localstack + docker-compose + S3
I got a service in Java with Spring-boot + spring-cloud-aws-messaging ... that uploads files into S3 ...

It's failing when tries to upload a file into S3 bucket (only when I run it in docker-compose).

here is my code

pom.xml

```<code><dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-aws-messaging</artifactId>
    <version>2.2.6.RELEASE</version>
</dependency>
</code>```

S3 client

```<code> public AmazonS3 amazonS3Client() {
        return AmazonS3ClientBuilder
                .standard()
                .withEndpointConfiguration(
                        new AwsClientBuilder.EndpointConfiguration(appConfig.getAwsS3Endpoint(), appConfig.getRegion()))
                .withCredentials(credentialsProvider)
                .build();
    }
</code>```

docker-compose yaml

```<code>version: '3.7'
services:

  dumb-service:
    build: ../dumb-service/.
    image: dumb-service:latest
    hostname: dumb-service
    ports:
      - '8080:8080'
      - '5006:5006'
    environment:
      JAVA_OPTS: '-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5006'
      AWS_S3_ENDPOINT: 'http://localstack:4566/'
      AWS_S3_BUCKET: 'dumb-bucket'
      AWS_SQS_ENDPOINT: 'http://localstack:4566'
      PDF_REQUEST_QUEUE_URL: 'http://localstack:4566/000000000000/dumb-inbound.fifo'
      PDF_REQUEST_QUEUE_NAME: 'dumb-inbound.fifo'
      AWS_REGION: "${AWS_REGION}"
      AWS_ACCESS_KEY_ID: "${AWS_ACCESS_KEY_ID}"
      AWS_SECRET_ACCESS_KEY: "${AWS_SECRET_ACCESS_KEY}"
    depends_on:
      - "localstack"

  # localstack home: https://github.com/localstack/localstack
  localstack:
    hostname: localstack
    container_name: "${LOCALSTACK_DOCKER_NAME-localstack_main}"
    image: localstack/localstack
    ports:
      - '4566:4566'
      - '4571:4571'
    environment:
      - SERVICES=${SERVICES-}
      - DEBUG=${DEBUG-}
      - DATA_DIR=${DATA_DIR-}
      - LAMBDA_EXECUTOR=${LAMBDA_EXECUTOR-}
      - HOST_TMP_FOLDER=${TMPDIR:-/tmp/}localstack
      - DOCKER_HOST=unix:///var/run/docker.sock
    volumes:
      - "${TMPDIR:-/tmp}/localstack:/tmp/localstack"
      - "/var/run/docker.sock:/var/run/docker.sock"

</code>```

Error is:

Unable to execute HTTP request: dumb-bucket.localstack

(This code is working fine with AWS services or running code native + localstack)

Any thoughts about how to connect to localstack S3 ?

答:
If you are trying to access an s3 bucket with localstack via an aws api; you would need to withPathStyleEnabled flag turned on.

for eg:

```<code>    AmazonS3 createLocalStackS3WithEndpointConfig(String endpointUrl, String awsRegion) {
    return createAwsBeanWithEndpointConfig(
        endpointUrl, awsRegion,
        epConf -> AmazonS3ClientBuilder.standard().withEndpointConfiguration(epConf).withPathStyleAccessEnabled(true).build(),
        AmazonS3ClientBuilder::defaultClient
    );
} `
</code>```

Reference : Troubleshooting section of https://pythonrepo.com/repo/localstack-localstack

Title: localstack + docker-compose + S3

Body:
I got a service in Java with Spring-boot + spring-cloud-aws-messaging ... that uploads files into S3 ...

It's failing when tries to upload a file into S3 bucket (only when I run it in docker-compose).

here is my code

pom.xml

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-aws-messaging</artifactId>
    <version>2.2.6.RELEASE</version>
</dependency>

S3 client

 public AmazonS3 amazonS3Client() {
        return AmazonS3ClientBuilder
                .standard()
                .withEndpointConfiguration(
                        new AwsClientBuilder.EndpointConfiguration(appConfig.getAwsS3Endpoint(), appConfig.getRegion()))
                .withCredentials(credentialsProvider)
                .build();
    }

docker-compose yaml

version: '3.7'
services:

  dumb-service:
    build: ../dumb-service/.
    image: dumb-service:latest
    hostname: dumb-service
    ports:
      - '8080:8080'
      - '5006:5006'
    environment:
      JAVA_OPTS: '-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5006'
      AWS_S3_ENDPOINT: 'http://localstack:4566/'
      AWS_S3_BUCKET: 'dumb-bucket'
      AWS_SQS_ENDPOINT: 'http://localstack:4566'
      PDF_REQUEST_QUEUE_URL: 'http://localstack:4566/000000000000/dumb-inbound.fifo'
      PDF_REQUEST_QUEUE_NAME: 'dumb-inbound.fifo'
      AWS_REGION: "${AWS_REGION}"
      AWS_ACCESS_KEY_ID: "${AWS_ACCESS_KEY_ID}"
      AWS_SECRET_ACCESS_KEY: "${AWS_SECRET_ACCESS_KEY}"
    depends_on:
      - "localstack"

  # localstack home: https://github.com/localstack/localstack
  localstack:
    hostname: localstack
    container_name: "${LOCALSTACK_DOCKER_NAME-localstack_main}"
    image: localstack/localstack
    ports:
      - '4566:4566'
      - '4571:4571'
    environment:
      - SERVICES=${SERVICES-}
      - DEBUG=${DEBUG-}
      - DATA_DIR=${DATA_DIR-}
      - LAMBDA_EXECUTOR=${LAMBDA_EXECUTOR-}
      - HOST_TMP_FOLDER=${TMPDIR:-/tmp/}localstack
      - DOCKER_HOST=unix:///var/run/docker.sock
    volumes:
      - "${TMPDIR:-/tmp}/localstack:/tmp/localstack"
      - "/var/run/docker.sock:/var/run/docker.sock"

Error is:

Unable to execute HTTP request: dumb-bucket.localstack

(This code is working fine with AWS services or running code native + localstack)

Any thoughts about how to connect to localstack S3 ?

Body:
If you are trying to access an s3 bucket with localstack via an aws api; you would need to withPathStyleEnabled flag turned on.

for eg:

    AmazonS3 createLocalStackS3WithEndpointConfig(String endpointUrl, String awsRegion) {
    return createAwsBeanWithEndpointConfig(
        endpointUrl, awsRegion,
        epConf -> AmazonS3ClientBuilder.standard().withEndpointConfiguration(epConf).withPathStyleAccessEnabled(true).build(),
        AmazonS3ClientBuilder::defaultClient
    );
} `

Reference : Troubleshooting section of https://pythonrepo.com/repo/localstack-localstack


问:
New c# nullable option
In new version of C# is default option nullable. I mean this

It's really good feature for me. But I don't understand one thing. Is property nullable by me or by program?

I know that this property should never be null because I fill it in the form and never set it as null. But in general it can be null. How should I mark it?

Example:

UserModel:

```<code>public string? Name { get; set; }

public string Name { get; set; } = null!
</code>```

I'm really confused.

答:
Where a value can be null, and the <Nullable>enable</Nullable> value is set in your *.csproj file, you must declare those values as nullable.

In your given example, the nullable type (instead of assigning null as a default) is the way to go:

public string? Name {get; set;}

You'll also notice VS complaining at you with warnings every time you introduce a property etc which can be nullable, but isn't marked as such.

Title: New c# nullable option

Body:
In new version of C# is default option nullable. I mean this

It's really good feature for me. But I don't understand one thing. Is property nullable by me or by program?

I know that this property should never be null because I fill it in the form and never set it as null. But in general it can be null. How should I mark it?

Example:

UserModel:

public string? Name { get; set; }

public string Name { get; set; } = null!

I'm really confused.


问:
Adding js to a drupal node form
In Drupal you can create your own nodetype in a custom module. Doing this you get to create your own form which is all very nice.

However if you want to add js the form things get a bit more tricky. If you add the js in the form, the js will only be added form the form when it is loaded. If the user would post the form with validation errors, the form function is not run again and thus the js is not added. Normally you would just create a menu callback and add the js there, but for the node add form, this wont be a possible solution.

So what is the best solution for adding js in a node add form, to keep it persistant when the form doesn't validate?

答:
You can user hook_nodeapi with case prepare:

Example:

```<code>/**
 * Implementation of hook_nodeapi
 */

function mymodulename_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch($op) {
    case 'prepare':
      $module_path = drupal_get_path('module' , 'mymodulename');
      drupal_add_js($module_path."/myscript.js");
      break;
  }
}
</code>```

Now you can add your javascript code in your module folder e.g. myscript.js.

Title: Adding js to a drupal node form

Body:
You can user hook_nodeapi with case prepare:

Example:

/**
 * Implementation of hook_nodeapi
 */

function mymodulename_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch($op) {
    case 'prepare':
      $module_path = drupal_get_path('module' , 'mymodulename');
      drupal_add_js($module_path."/myscript.js");
      break;
  }
}

Now you can add your javascript code in your module folder e.g. myscript.js.


问:
How do I find the immutable id of my Google Apps account?
Many of the Directory API calls require a customer parameter referred to as the "Immutable id of the Google Apps account. (string)".

e.g. GET https://www.googleapis.com/admin/directory/v1/customer/customer/domains

I have no idea how to find/generate this for my Google Apps account. I am an admin.

Can someone point me in the right direction please?

答: I found something simpler: gcloud organizations list. It will give you DISPLAY_NAME, ID and DIRECTORY_CUSTOMER_ID (this is what your are looking for) for all you organizations.


问:
Status bar color changed after Xcode 13 update
Before updating to xcode 13, the status bar's background color matched the color of the navigation bar. When I updated to xcode 13, the status bar is behaving strangely. It is showing different background colors in different view controllers. Some are black, some are gray, and some are transparent. I tried overriding the status bar style but it didn't work. There has been no change in the code whatsoever since the update. I want the status bar's background color to match that of the navigation bar.

答:
SwiftUI answer:

Try adding .ignoresSafeArea() to whatever parent of your child views is. I encountered a similar issue back in the day and solved it by something like this:

struct HomeView: View {
    var body: some View {
        VStack {

            Spacer()
        }.ignoresSafeArea()
    }
}
```

Body:
SwiftUI answer:

Try adding .ignoresSafeArea() to whatever parent of your child views is. I encountered a similar issue back in the day and solved it by something like this:

struct HomeView: View {
    var body: some View {
        VStack {
            <code>

            Spacer()
        }.ignoresSafeArea()
    }
}


问:
filter values using this code "Filter(function(x) condition on x , Var )" but using condition based on values calculated value of var
Apologies, if this is a simple question. I'm trying to use "Filter(function(x) condition with x , Var )" to filter values in a variable. The only thing is I want to be able to use a manipulation of "x" in the condition. Here below is a simplistic example. In the below code, I want to filter values in variable that are greater than the mean of that variable.

```<code>Var1 = 1:10
Filter(function(x) x > mean(x) , Var1 )
> integer(0)
</code>```

As you can see it doesn't work the way expected. There are other ways to filter but I'd like to do it in this format. Is there a way to write the "mean(x)" within the function part to make this work? Any help greatly appreciated. Thanks

答:
The x is a single value as it is looped over each element of the vector so mean(x) is just x.  Instead it would be mean(Var1).

```<code>Filter(function(x) x > mean(Var1), Var1 )
[1]  6  7  8  9 10
</code>```

If we want to understand what the 'x' is, just use a print statement

```<code>Filter(function(x) print(x), Var1)
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
 [1]  1  2  3  4  5  6  7  8  9 10
</code>```

This can be reused by wrapping in a function

```<code>f1 <- function(vec) {
      Filter(function(x) x > mean(vec), vec)
 }
f1(Var1)
[1]  6  7  8  9 10
</code>```

Or use subset

```<code>subset(Var1, Var1 > mean(Var1))
[1]  6  7  8  9 10
</code>```

Body:
Apologies, if this is a simple question. I'm trying to use "Filter(function(x) condition with x , Var )" to filter values in a variable. The only thing is I want to be able to use a manipulation of "x" in the condition. Here below is a simplistic example. In the below code, I want to filter values in variable that are greater than the mean of that variable.

Var1 = 1:10
Filter(function(x) x > mean(x) , Var1 )
> integer(0)

As you can see it doesn't work the way expected. There are other ways to filter but I'd like to do it in this format. Is there a way to write the "mean(x)" within the function part to make this work? Any help greatly appreciated. Thanks

Body:
The x is a single value as it is looped over each element of the vector so mean(x) is just x.  Instead it would be mean(Var1).

Filter(function(x) x > mean(Var1), Var1 )
[1]  6  7  8  9 10

If we want to understand what the 'x' is, just use a print statement

Filter(function(x) print(x), Var1)
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
 [1]  1  2  3  4  5  6  7  8  9 10

This can be reused by wrapping in a function

f1 <- function(vec) {
      Filter(function(x) x > mean(vec), vec)
 }
f1(Var1)
[1]  6  7  8  9 10

Or use subset

subset(Var1, Var1 > mean(Var1))
[1]  6  7  8  9 10


问:
Fixed Table Header Scrolling
With some tips found on this web site I was able to put together a fixed table header scrolling page. It works as expected until I add the  container to each row (to each  tag). Having the container is a must have for my app to use certain pre-existing functionality that is based on the  container.

Here's my CSS:

```<code><style>
table.tableFixedHdr {
    border:1px solid
}
tr td{
    border:none
}
tbody.tbScroll {
    display:block;
    max-height:200px;
    overflow-y:scroll;
}
thead.thFixed, tbody tr.trFixed {
    display:table;
    width:100%;
    table-layout:fixed;
}
thead {
    width:100%;
}
table.tableFixedHdr {
    width:60%;
}
</style>
</code>```

And here's a simplified version of the table:

```<code><table class="tableFixedHdr">
    <thead class="thFixed">
    <tr>
        <th>Date</th>
        <th>ID</th>
        <th>Code</th>
        <th>Segment</th>
        <th>Name</th>
        <th>Count</th>
    </tr>
    </thead>
<tbody class="tbScroll">
    <tr class="trFixed"><td>01/01/2021</td><td>3859303</td><td>ALA</td><td>KEY</td><td>Very Old Customer</td><td>250</td></tr>
    <tr class="trFixed"><td>01/01/2021</td><td>3859303</td><td>ALA</td><td>KEY</td><td>Very Old Customer</td><td>250</td></tr>
    <tr class="trFixed"><td>01/01/2021</td><td>3859303</td><td>ALA</td><td>KEY</td><td>Very Old Customer</td><td>250</td></tr>
    <tr class="trFixed"><td>01/01/2021</td><td>3859303</td><td>ALA</td><td>KEY</td><td>Very Old Customer</td><td>250</td></tr>
    <tr class="trFixed"><td>01/01/2021</td><td>3859303</td><td>ALA</td><td>KEY</td><td>Very Old Customer</td><td>250</td></tr>
    <tr class="trFixed"><td>01/01/2021</td><td>3859303</td><td>ALA</td><td>KEY</td><td>Very Old Customer</td><td>250</td></tr>
    <tr class="trFixed"><td>01/01/2021</td><td>3859303</td><td>ALA</td><td>KEY</td><td>Very Old Customer</td><td>250</td></tr>
    <tr class="trFixed"><td>01/01/2021</td><td>3859303</td><td>ALA</td><td>KEY</td><td>Very Old Customer</td><td>250</td></tr>
    <tr class="trFixed"><td>01/01/2021</td><td>3859303</td><td>ALA</td><td>KEY</td><td>Very Old Customer</td><td>250</td></tr>
    <tr class="trFixed"><td>01/01/2021</td><td>3859303</td><td>ALA</td><td>KEY</td><td>Very Old Customer</td><td>250</td></tr>
    <tr class="trFixed"><td>01/01/2021</td><td>3859303</td><td>ALA</td><td>KEY</td><td>Very Old Customer</td><td>250</td></tr>
    <tr class="trFixed"><td>01/01/2021</td><td>3859303</td><td>ALA</td><td>KEY</td><td>Very Old Customer</td><td>250</td></tr>
    </tbody>
</table>
</code>```

It works fine until I add the  container, as follows:

```<code><tbody><tr class="trFixed"><td>01/01/2021</td><td>3859303</td><td>ALA</td><td>KEY</td><td>Very Old Customer</td><td>250</td></tr></tbody>
</code>```

Once I add the  container the header row is no longer fixed.

Does anyone have an idea of how to get around this issue?

Thank you.

答:
Tried you this?

```<code><thead>
<tr class="thFixed">
    <th>Date</th>
    <th>ID</th>
    <th>Code</th>
    <th>Segment</th>
    <th>Name</th>
    <th>Count</th>
</tr>
</thead>
</code>```

Then:

```<code>thead tr.thFixed, tbody tr.trFixed {
    display:table;
    width:100%;
    table-layout:fixed;
}
</code>```

Title: Fixed Table Header Scrolling

Body:
With some tips found on this web site I was able to put together a fixed table header scrolling page. It works as expected until I add the  container to each row (to each  tag). Having the container is a must have for my app to use certain pre-existing functionality that is based on the  container.

Here's my CSS:

And here's a simplified version of the table:

        Date
        ID
        Code
        Segment
        Name
        Count

01/01/2021	3859303	ALA	KEY	Very Old Customer	250

01/01/2021	3859303	ALA	KEY	Very Old Customer	250

01/01/2021	3859303	ALA	KEY	Very Old Customer	250

01/01/2021	3859303	ALA	KEY	Very Old Customer	250

01/01/2021	3859303	ALA	KEY	Very Old Customer	250

01/01/2021	3859303	ALA	KEY	Very Old Customer	250

01/01/2021	3859303	ALA	KEY	Very Old Customer	250

01/01/2021	3859303	ALA	KEY	Very Old Customer	250

01/01/2021	3859303	ALA	KEY	Very Old Customer	250

01/01/2021	3859303	ALA	KEY	Very Old Customer	250

01/01/2021	3859303	ALA	KEY	Very Old Customer	250

01/01/2021	3859303	ALA	KEY	Very Old Customer	250

It works fine until I add the  container, as follows:

01/01/2021	3859303	ALA	KEY	Very Old Customer	250

Once I add the  container the header row is no longer fixed.

Does anyone have an idea of how to get around this issue?

Thank you.

Body:
Tried you this?

<thead>
<tr class="thFixed">
    <th>Date</th>
    <th>ID</th>
    <th>Code</th>
    <th>Segment</th>
    <th>Name</th>
    <th>Count</th>
</tr>
</thead>

Then:

thead tr.thFixed, tbody tr.trFixed {
    display:table;
    width:100%;
    table-layout:fixed;
}


问:
Vuetify - create a card with a button centered vertically and horizontally
I'm trying to create a card in Vuetify, within a Nuxt project running on Vue 2, which consists of a background image, and a single button centered both horizontally and vertically.

I've tried using d-flex, as well as v-row and v-col, but in the first case it's centered vertically but not horizontally, and in the second case it's centered horizontally but not vertically.

But as far as I can tell, I've written my code exactly as specified in Vuetify's documentation.

I've tested this on Chrome and Firefox and gotten the same result in each.

Here is my Nuxt page:

```<code><template>
  <div>
    <v-card >
      <v-img
        class="d-flex justify-center align-center"
        width="600"
        height="600"
        src="https://cdn.vuetifyjs.com/images/cards/cooking.png"
      >
        <v-btn
          icon
          width="300"
          height="300"
        >
          <v-icon color="white" size="300">mdi-emoticon-confused-outline</v-icon>
        </v-btn>
      </v-img>
    </v-card>

    <br >

    <v-card >
      <v-img
        width="600"
        height="600"
        src="https://cdn.vuetifyjs.com/images/cards/cooking.png"
      >
        <v-container>
          <v-row justify="center" align="center">
            <v-col align="center">
              <v-btn
                icon
                width="300"
                height="300"
              >
                <v-icon color="white" size="300">mdi-emoticon-confused-outline</v-icon>
              </v-btn>
            </v-col>
          </v-row>
        </v-container>
      </v-img>
    </v-card>
  </div>
</template>
</code>```

I'm aware that I could probably fix this by fiddling with paddings and margins, but I'd rather figure out how to get it to work just by using Vuetify functionality, so that I can use this as a learning experience to learn how to use Vuetify correctly.

Thanks in advance for any help!

答:
I was actually able to get this to work without any custom CSS - it turned out my problem was that I need to change this:

```<code><v-card >
      <v-img
        width="600"
        height="600"
        src="https://cdn.vuetifyjs.com/images/cards/cooking.png"
      >
</code>```

to this:

```<code><v-card
      class="d-flex justify-center align-center"
      img="https://cdn.vuetifyjs.com/images/cards/cooking.png"
      width="600"
      height="600"
    >
</code>```

Body:
I'm trying to create a card in Vuetify, within a Nuxt project running on Vue 2, which consists of a background image, and a single button centered both horizontally and vertically.

I've tried using d-flex, as well as v-row and v-col, but in the first case it's centered vertically but not horizontally, and in the second case it's centered horizontally but not vertically.

But as far as I can tell, I've written my code exactly as specified in Vuetify's documentation.

I've tested this on Chrome and Firefox and gotten the same result in each.

Here is my Nuxt page:

<template>

    <v-card >
      <v-img
        class="d-flex justify-center align-center"
        width="600"
        height="600"
        src="https://cdn.vuetifyjs.com/images/cards/cooking.png"
      >
        <v-btn
          icon
          width="300"
          height="300"
        >
          <v-icon color="white" size="300">mdi-emoticon-confused-outline</v-icon>
        </v-btn>
      </v-img>
    </v-card>

    <v-card >
      <v-img
        width="600"
        height="600"
        src="https://cdn.vuetifyjs.com/images/cards/cooking.png"
      >
        <v-container>
          <v-row justify="center" align="center">
            <v-col align="center">
              <v-btn
                icon
                width="300"
                height="300"
              >
                <v-icon color="white" size="300">mdi-emoticon-confused-outline</v-icon>
              </v-btn>
            </v-col>
          </v-row>
        </v-container>
      </v-img>
    </v-card>

</template>

I'm aware that I could probably fix this by fiddling with paddings and margins, but I'd rather figure out how to get it to work just by using Vuetify functionality, so that I can use this as a learning experience to learn how to use Vuetify correctly.

Thanks in advance for any help!

Body:
I was actually able to get this to work without any custom CSS - it turned out my problem was that I need to change this:

<v-card >
      <v-img
        width="600"
        height="600"
        src="https://cdn.vuetifyjs.com/images/cards/cooking.png"
      >

to this:

<v-card
      class="d-flex justify-center align-center"
      img="https://cdn.vuetifyjs.com/images/cards/cooking.png"
      width="600"
      height="600"
    >


问:
Spacing of container (title) is not the same as row (form) with Bootstrap 5
Like I said in the title. I want the row to have the same spacing like the container. I am using Bootstrap 5. So if you preview the HTML in Stackoverflow it won't show you the way I see it. I added a picture, so you can understand it better.

Erstelle einen neuen Kunden

                    <input type="text" name="txtName" class="form-control border-dark" placeholder="Vorname *" value="" #firstName />

                    <input type="text" name="txtName" class="form-control border-dark" placeholder="Nachname *" value="" #familyName/>

                <input type="text" name="txtEmail" class="form-control border-dark" placeholder="Email *" value="" #email/>

                <input type="text" name="txtPhone" class="form-control border-dark" placeholder="Telefonnummer *" value="" #phoneNumber/>

                <textarea name="txtMsg" class="form-control border-dark" placeholder="Beschreibung" style="width: 100%; height: 150px;" #description></textarea>

            <input type="submit" name="btnSubmit" class="btn border-dark" value="Speichern" style="background-color: beige;"/>

```

答:
Simply wrap a div.container around your div.row to apply the .container styles to it.

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

Erstelle einen neuen Kunden

                        <input type="text" name="txtName" class="form-control border-dark" placeholder="Vorname *"
                            value="" #firstName />

                        <input type="text" name="txtName" class="form-control border-dark" placeholder="Nachname *"
                            value="" #familyName />

                    <input type="text" name="txtEmail" class="form-control border-dark" placeholder="Email *" value=""
                        #email />

                    <input type="text" name="txtPhone" class="form-control border-dark" placeholder="Telefonnummer *"
                        value="" #phoneNumber />

                    <textarea name="txtMsg" class="form-control border-dark" placeholder="Beschreibung"
                        style="width: 100%; height: 150px;" #description></textarea>

                <input type="submit" name="btnSubmit" class="btn border-dark" value="Speichern"
                    style="background-color: beige;" />

```

Body:
Simply wrap a div.container around your div.row to apply the .container styles to it.

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

<div class="container position-absolute top-50 start-50 translate-middle">
    <div class="container pt-5">
        <div class="h-100 p-5 rounded" style="background-color: beige;">
            <div class="display-4 text-center">Erstelle einen neuen Kunden</div>
        </div>
        <hr>
    </div>
    <div class="container">
        <div class="row">
            <div class="col-xl-6">
                <div class="row mb-3">
                    <div class="col-6">
                        <input type="text" name="txtName" class="form-control border-dark" placeholder="Vorname *"
                            value="" #firstName />
                    </div>
                    <div class="col-6">
                        <input type="text" name="txtName" class="form-control border-dark" placeholder="Nachname *"
                            value="" #familyName />
                    </div>
                </div>
                <div class="mb-3">
                    <input type="text" name="txtEmail" class="form-control border-dark" placeholder="Email *" value=""
                        #email />
                </div>
                <div class="mb-3">
                    <input type="text" name="txtPhone" class="form-control border-dark" placeholder="Telefonnummer *"
                        value="" #phoneNumber />
                </div>
            </div>
            <div class="col-xl-6">
                <div>
                    <textarea name="txtMsg" class="form-control border-dark" placeholder="Beschreibung"
                        style="width: 100%; height: 150px;" #description></textarea>
                </div>
            </div>
            <div class="text-center mt-3">
                <input type="submit" name="btnSubmit" class="btn border-dark" value="Speichern"
                    style="background-color: beige;" />
            </div>
        </div>
    </div>
</div>


问:
Can I put a <style>...</style> tag within the body of a HTML file to send in email?
Since a lot of email clients ignore the HEAD tag, can I embed an inline stylesheet in the body?</p>

答: The top answer is outdated. Gmail now supports using media query's along with other css properties now - https://developers.google.com/gmail/design/css</p>

OwnerDisplayName: Manu


问:
Why am I getting raise UnknownValueError() speech_recognition.UnknownValueError?
I'm trying to write a script that uses SpeechRecognition to run a function once say a wake-up word "Run" Everything works perfectly up until I get to my regex search to find my wake-up word in my alpha variable that is assigned to what I say. Upon running I get the error. I have tested my regex alg outside of the SpeechRecognition with a string and it worked perfectly.

ERROR:

```<code>raise UnknownValueError()
speech_recognition.UnknownValueError
</code>```

Could I get some help?

CODE:

```<code>import speech_recognition as sr
import re

def stt():
    recognizer = sr.Recognizer()
    microphone = sr.Microphone()

    # check that recognizer and microphone arguments are appropriate type
    if not isinstance(recognizer, sr.Recognizer):
        raise TypeError("`recognizer` must be `Recognizer` instance")

    if not isinstance(microphone, sr.Microphone):
        raise TypeError("`microphone` must be `Microphone` instance")

    # listen and assign
    with microphone as source:
        recognizer.adjust_for_ambient_noise(source)
        audio = recognizer.listen(source)
    # return output
    return recognizer.recognize_google(audio)

while True:
    alpha = stt()
    print(alpha)
    if re.search('.+Run.+', alpha):
        print("1")
        beta = alpha.split()
        query = beta.pop()
        print("working")
</code>```

答:
Try putting your whole code under a try and except.

Like this:

```<code>import speech_recognition as sr
import re

try:

    def stt():
        recognizer = sr.Recognizer()
        microphone = sr.Microphone()

        # check that recognizer and microphone arguments are appropriate type
        if not isinstance(recognizer, sr.Recognizer):
            raise TypeError("`recognizer` must be `Recognizer` instance")

        if not isinstance(microphone, sr.Microphone):
            raise TypeError("`microphone` must be `Microphone` instance")

        # listen and assign
        with microphone as source:
            recognizer.adjust_for_ambient_noise(source)
            audio = recognizer.listen(source)
        # return output
        return recognizer.recognize_google(audio)

    while True:
        alpha = stt()
        print(alpha)
        if re.search('.+Run.+', alpha):
            print("1")
            beta = alpha.split()
            query = beta.pop()
            print("working")

except sr.UnknownValueError() as e:
    pass
</code>```

If that doesn't work. Look at this github issue

Body:
I'm trying to write a script that uses SpeechRecognition to run a function once say a wake-up word "Run" Everything works perfectly up until I get to my regex search to find my wake-up word in my alpha variable that is assigned to what I say. Upon running I get the error. I have tested my regex alg outside of the SpeechRecognition with a string and it worked perfectly.

ERROR:

raise UnknownValueError()
speech_recognition.UnknownValueError

Could I get some help?

CODE:

import speech_recognition as sr
import re

def stt():
    recognizer = sr.Recognizer()
    microphone = sr.Microphone()

    # check that recognizer and microphone arguments are appropriate type
    if not isinstance(recognizer, sr.Recognizer):
        raise TypeError("`recognizer` must be `Recognizer` instance")

    if not isinstance(microphone, sr.Microphone):
        raise TypeError("`microphone` must be `Microphone` instance")

    # listen and assign
    with microphone as source:
        recognizer.adjust_for_ambient_noise(source)
        audio = recognizer.listen(source)
    # return output
    return recognizer.recognize_google(audio)

while True:
    alpha = stt()
    print(alpha)
    if re.search('.+Run.+', alpha):
        print("1")
        beta = alpha.split()
        query = beta.pop()
        print("working")

Body:
Try putting your whole code under a try and except.

Like this:

import speech_recognition as sr
import re

try:

    def stt():
        recognizer = sr.Recognizer()
        microphone = sr.Microphone()

        # check that recognizer and microphone arguments are appropriate type
        if not isinstance(recognizer, sr.Recognizer):
            raise TypeError("`recognizer` must be `Recognizer` instance")

        if not isinstance(microphone, sr.Microphone):
            raise TypeError("`microphone` must be `Microphone` instance")

        # listen and assign
        with microphone as source:
            recognizer.adjust_for_ambient_noise(source)
            audio = recognizer.listen(source)
        # return output
        return recognizer.recognize_google(audio)

    while True:
        alpha = stt()
        print(alpha)
        if re.search('.+Run.+', alpha):
            print("1")
            beta = alpha.split()
            query = beta.pop()
            print("working")

except sr.UnknownValueError() as e:
    pass

If that doesn't work. Look at this github issue