问:
Can you declare a Java enum to have variable generic types per instance?
What I am trying to do is implement a fixed set of converters as abstract enums with individual implementations, and supply different generics per implementation. The below code doesn't work, but it should indicate what I am trying to do. I am all but certain the answer is 'no'. If I remove all generics and use type casting, this will for sure work. But I'd prefer generics

    public enum Converter implements ValueConverter {
        LONG_DOUBLE<Long,Double> {
            @Override
            public Long convertInput(Double value) {
                return null;
            }

            @Override
            public Double convertOutput(Long value) {
                return null;
            }
        },
        DATE_LOCALDATE<Date,LocalDate> {
            @Override
            public Date convertInput(LocalDate value) {
                return null;
            }

            @Override
            public LocalDate convertOutput(Date value) {
                return null;
            }
        }
    }
```


来源: stackexchange

问:
Uploading image via ASP.NET Core Web API gets corrupted
I'm developing an ASP.NET Core Web API that posts an image and saves it to the server.

When I using Visual Studio, it works fine and saves the image in the Pics directory.

But when uploading it to Windows VPS, it saves the file, but there is no size - it means it's corrupted.

```<code>[HttpPost]
public async Task<ActionResult<ImageFile>> PostImage([FromForm] ImageFile image)
{
    try
    {
        // string Pic = Path.GetFileNameWithoutExtension(image.AttImage.FileName);
        string path = Path.Combine(wwrootPath + "/Pics/" + RandomString(32) + ".jpg");

        // Logger.LogError("Omar1 : " + path);
        if (image.AttImage == null)
            return null;

        using (var filestream = new FileStream(path, FileMode.Create))
        {
            _= image.AttImage.CopyToAsync(filestream);
        }

        image.ImagePath = path;
        image.CreatedDate = DateTime.UtcNow;

        // Logger.LogError("Omar2 : "+path);

        _context.Images.Add(image);
        await _context.SaveChangesAsync();

        return image;
    }
    catch (Exception ex)
    {
        Logger.LogError(ex.Message+" : "+ex.InnerException);
        return null;
    }
}
</code>```

I searched for many solutions and give the Pics directory full control permission but the problem persists.

Does anyone have any idea?

ContentLicense: CC BY-SA 4.0

Body:
I'm developing an ASP.NET Core Web API that posts an image and saves it to the server.

When I using Visual Studio, it works fine and saves the image in the Pics directory.

But when uploading it to Windows VPS, it saves the file, but there is no size - it means it's corrupted.

[HttpPost]
public async Task<ActionResult<ImageFile>> PostImage([FromForm] ImageFile image)
{
    try
    {
        // string Pic = Path.GetFileNameWithoutExtension(image.AttImage.FileName);
        string path = Path.Combine(wwrootPath + "/Pics/" + RandomString(32) + ".jpg");

        // Logger.LogError("Omar1 : " + path);
        if (image.AttImage == null)
            return null;

        using (var filestream = new FileStream(path, FileMode.Create))
        {
            _= image.AttImage.CopyToAsync(filestream);
        }

        image.ImagePath = path;
        image.CreatedDate = DateTime.UtcNow;

        // Logger.LogError("Omar2 : "+path);

        _context.Images.Add(image);
        await _context.SaveChangesAsync();

        return image;
    }
    catch (Exception ex)
    {
        Logger.LogError(ex.Message+" : "+ex.InnerException);
        return null;
    }
}

I searched for many solutions and give the Pics directory full control permission but the problem persists.

Does anyone have any idea?


问:
Python Mocking - How to mock sqlalchemy query?
I want to try mocking my SQL query

So far I've mocked the DB connection and validation but have not gotten any idea how to mock the query.

Here's my function which I'm calling to execute queries

query_functions.py

```<code>
CONST_INSERT = "INSERT INTO user (user_name, password, email_address, dob, address, uid ) VALUES(:user_name , :password, :email_address, :dob, :address, :uid)"

def connection():

    engine = create_engine('mysql://root:admin@172.17.0.2:3306/flask', poolclass = NullPool)
    conn = engine.connect()
    return conn

def run_insert(data):
    conn = connection()
    sql = text(CONST_INSERT)
    conn.execute(sql, data)
    conn.close()
    return ("executed")
</code>```

This is what I've tried

test.py

```<code> @patch.object(query_functions, 'connection')
    def test_service_reg_return_correct_data(self, mock_sqlalchmey):
        data = {
            "user_name": "testuser56",
            "password": "123456",
            "email_address": "testuser56@example.com",
            "dob": "2022-06-07 00:00:00",
            "address": "Ahmedabad",

        }

        # json_data = json.dumps(data)
        # print("jsob", json_data)
        m1 = mock.MagicMock()
        m1.get_json.return_value = data

        print("m", m1)
        with mock.patch("backened.routes.register.request", m1):

            response =user_register()
            self.assertTrue(mock_sqlalchmey.called)
            self.assertEqual(response.json, {'Message': 'New user Created'},201)

</code>```

I'm calling run_insert() inside user_register()

```<code>def user_register():
         *** some code
      validate=  validate():
         *** some code
      insert = run_insert()
</code>```

Body:
I want to try mocking my SQL query

So far I've mocked the DB connection and validation but have not gotten any idea how to mock the query.

Here's my function which I'm calling to execute queries

query_functions.py

CONST_INSERT = "INSERT INTO user (user_name, password, email_address, dob, address, uid ) VALUES(:user_name , :password, :email_address, :dob, :address, :uid)"

def connection():

    engine = create_engine('mysql://root:admin@172.17.0.2:3306/flask', poolclass = NullPool)
    conn = engine.connect()
    return conn

def run_insert(data):
    conn = connection()
    sql = text(CONST_INSERT)
    conn.execute(sql, data)
    conn.close()
    return ("executed")

This is what I've tried

test.py

 @patch.object(query_functions, 'connection')
    def test_service_reg_return_correct_data(self, mock_sqlalchmey):
        data = {
            "user_name": "testuser56",
            "password": "123456",
            "email_address": "testuser56@example.com",
            "dob": "2022-06-07 00:00:00",
            "address": "Ahmedabad",

        }

        # json_data = json.dumps(data)
        # print("jsob", json_data)
        m1 = mock.MagicMock()
        m1.get_json.return_value = data

        print("m", m1)
        with mock.patch("backened.routes.register.request", m1):

            response =user_register()
            self.assertTrue(mock_sqlalchmey.called)
            self.assertEqual(response.json, {'Message': 'New user Created'},201)

I'm calling run_insert() inside user_register()

def user_register():
         *** some code
      validate=  validate():
         *** some code
      insert = run_insert()


问:
HubSpot form script is throwing the Error: reCAPTCHA placeholder element must be an element or id
I'm embedding a HubSpot form in a Next.js site and it's showing up properly but I'm getting the error: Unhandled Runtime Error Error: reCAPTCHA placeholder element must be an element or id

Here's the code

useEffect(() => {
    const script = document.createElement("script");
    script.src = "https://js.hsforms.net/forms/v2.js";
    document.body.appendChild(script);

    script.addEventListener("load", () => {
      if ((window as any).hbspt) {
        // casting as "any" is needed because TypeScript will throw an error without it
        (window as any).hbspt.forms.create({
          // casting as "any" is needed because TypeScript will throw an error without it
          portalId: "my-portal-id",
          formId: "my-form-id",
          target: "#hubspotForm",
        });
      }
    });
  }, []);
```
<p>And in the body</p>
<pre class="lang-html prettyprint-override"><code><div id="hubspotForm" />
</code>```

Body:
I'm embedding a HubSpot form in a Next.js site and it's showing up properly but I'm getting the error: Unhandled Runtime Error Error: reCAPTCHA placeholder element must be an element or id

Here's the code

useEffect(() => {
    const script = document.createElement("script");
    script.src = "https://js.hsforms.net/forms/v2.js";
    document.body.appendChild(script);

    script.addEventListener("load", () => {
      if ((window as any).hbspt) {
        // casting as "any" is needed because TypeScript will throw an error without it
        (window as any).hbspt.forms.create({
          // casting as "any" is needed because TypeScript will throw an error without it
          portalId: "my-portal-id",
          formId: "my-form-id",
          target: "#hubspotForm",
        });
      }
    });
  }, []);

And in the body


问:
Find strings and add html tags to the beginning and end
How to add html tags (like
 and
) to the beginning and end of a string that is shorter than 100 characters?

For example the string is:

My name is John

And as a result we should get:
My name is John

I know how to find strings shorter than 100 characters

```<code>^.{0,150}$
</code>```

But I can't figure out how to add tags
 and
 to the beginning and end of this line.

Body:
How to add html tags (like
 and
) to the beginning and end of a string that is shorter than 100 characters?

For example the string is:

My name is John

And as a result we should get:
My name is John

I know how to find strings shorter than 100 characters

^.{0,150}$

But I can't figure out how to add tags
 and
 to the beginning and end of this line.


问:
TypeError: Indexed expression has to be a type, mapping or array (is function (address) view external returns (uint256))
`why compile time getting error:: TypeError: Indexed expression has to be a type, mapping or array (is function (address) view external returns (uint256))

I want to assign ERC20 token address to token variable then Deposit function using token balance Of getting error why?? here is my code

pragma solidity ^0.8.17;

interface IERC20 {
/**
* @dev Emitted when value tokens are moved from one account (from) to
* another (to).
*
* Note that value may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);

```<code>/**
 * @dev Emitted when the allowance of a `spender` for an `owner` is set by
 * a call to {approve}. `value` is the new allowance.
 */
event Approval(address indexed owner, address indexed spender, uint256 value);

/**
 * @dev Returns the amount of tokens in existence.
 */
function totalSupply() external view returns (uint256);

/**
 * @dev Returns the amount of tokens owned by `account`.
 */
function balanceOf(address account) external view returns (uint256);

/**
 * @dev Moves `amount` tokens from the caller's account to `to`.
 *
 * Returns a boolean value indicating whether the operation succeeded.
 *
 * Emits a {Transfer} event.
 */
function transfer(address to, uint256 amount) external returns (bool);

/**
 * @dev Returns the remaining number of tokens that `spender` will be
 * allowed to spend on behalf of `owner` through {transferFrom}. This is
 * zero by default.
 *
 * This value changes when {approve} or {transferFrom} are called.
 */
function allowance(address owner, address spender) external view returns (uint256);

/**
 * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
 *
 * Returns a boolean value indicating whether the operation succeeded.
 *
 * IMPORTANT: Beware that changing an allowance with this method brings the risk
 * that someone may use both the old and the new allowance by unfortunate
 * transaction ordering. One possible solution to mitigate this race
 * condition is to first reduce the spender's allowance to 0 and set the
 * desired value afterwards:
 * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
 *
 * Emits an {Approval} event.
 */
function approve(address spender, uint256 amount) external returns (bool);

/**
 * @dev Moves `amount` tokens from `from` to `to` using the
 * allowance mechanism. `amount` is then deducted from the caller's
 * allowance.
 *
 * Returns a boolean value indicating whether the operation succeeded.
 *
 * Emits a {Transfer} event.
 */
function transferFrom(
    address from,
    address to,
    uint256 amount
) external returns (bool);
</code>```

}

contract VeloxWrapper {
address payable owner;
IERC20 public token;

```<code>event Withdrawal(address indexed to, uint256 amount);
event Deposit(address indexed from, uint256 amount);

constructor(address tokenAddress) payable {
    token = IERC20(tokenAddress);
    owner = payable(msg.sender);
}

receive() external payable {
        token.balanceOf[msg.sender] += msg.value;
        emit Deposit(msg.sender, msg.value);
}

function totalBalance() external view returns (uint256) {
    return token.balanceOf(address(this));
}

function withdraw(uint withdrawalAmount) public {
    require(token.balanceOf[msg.sender] >= withdrawalAmount);
    token.balanceOf[msg.sender] -= withdrawalAmount;
    msg.sender.transfer(withdrawalAmount);
    Withdrawal(msg.sender, withdrawalAmount);}
</code>```

}

Body:
`why compile time getting error:: TypeError: Indexed expression has to be a type, mapping or array (is function (address) view external returns (uint256))

I want to assign ERC20 token address to token variable then Deposit function using token balance Of getting error why?? here is my code

pragma solidity ^0.8.17;

interface IERC20 {
/**
* @dev Emitted when value tokens are moved from one account (from) to
* another (to).
*
* Note that value may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);

/**
 * @dev Emitted when the allowance of a `spender` for an `owner` is set by
 * a call to {approve}. `value` is the new allowance.
 */
event Approval(address indexed owner, address indexed spender, uint256 value);

/**
 * @dev Returns the amount of tokens in existence.
 */
function totalSupply() external view returns (uint256);

/**
 * @dev Returns the amount of tokens owned by `account`.
 */
function balanceOf(address account) external view returns (uint256);

/**
 * @dev Moves `amount` tokens from the caller's account to `to`.
 *
 * Returns a boolean value indicating whether the operation succeeded.
 *
 * Emits a {Transfer} event.
 */
function transfer(address to, uint256 amount) external returns (bool);

/**
 * @dev Returns the remaining number of tokens that `spender` will be
 * allowed to spend on behalf of `owner` through {transferFrom}. This is
 * zero by default.
 *
 * This value changes when {approve} or {transferFrom} are called.
 */
function allowance(address owner, address spender) external view returns (uint256);

/**
 * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
 *
 * Returns a boolean value indicating whether the operation succeeded.
 *
 * IMPORTANT: Beware that changing an allowance with this method brings the risk
 * that someone may use both the old and the new allowance by unfortunate
 * transaction ordering. One possible solution to mitigate this race
 * condition is to first reduce the spender's allowance to 0 and set the
 * desired value afterwards:
 * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
 *
 * Emits an {Approval} event.
 */
function approve(address spender, uint256 amount) external returns (bool);

/**
 * @dev Moves `amount` tokens from `from` to `to` using the
 * allowance mechanism. `amount` is then deducted from the caller's
 * allowance.
 *
 * Returns a boolean value indicating whether the operation succeeded.
 *
 * Emits a {Transfer} event.
 */
function transferFrom(
    address from,
    address to,
    uint256 amount
) external returns (bool);

}

contract VeloxWrapper {
address payable owner;
IERC20 public token;

event Withdrawal(address indexed to, uint256 amount);
event Deposit(address indexed from, uint256 amount);

constructor(address tokenAddress) payable {
    token = IERC20(tokenAddress);
    owner = payable(msg.sender);
}

receive() external payable {
        token.balanceOf[msg.sender] += msg.value;
        emit Deposit(msg.sender, msg.value);
}

function totalBalance() external view returns (uint256) {
    return token.balanceOf(address(this));
}

function withdraw(uint withdrawalAmount) public {
    require(token.balanceOf[msg.sender] >= withdrawalAmount);
    token.balanceOf[msg.sender] -= withdrawalAmount;
    msg.sender.transfer(withdrawalAmount);
    Withdrawal(msg.sender, withdrawalAmount);}

}


问:
Python Selenium Having Issues Selecting From Dropdown
I have no training in python and am trying to write my first script using Python Selenium via Visual Studio Code. I'm currently trying to select an item from a dropdown box, but I'm not understanding how this html was put together, it feels pretty unconventional.

I want to select A-Active from the Status dropdown box:

However, when inspecting the code for the dropdown box it's not using a Select tag. When I copy outerHTML this is all I get back:

```<code><div class="g_GridElement g_GridElement_scrollignore gl_94_x_97 gl_94_w_97_12 gl_94_y_1 gl_94_h_1_1">
    <div class="containerElement gbc_WidgetBase gbc_ComboBoxWidget gbc_MunisComboBoxWidget w_111 g_measureable gbc_WidgetBase_standalone aui__1107 gbc_NotNull gbc_Required gbc_Focus editing" tabindex="0" role="combobox" __widgetbase="" __comboboxwidget="" __muniscomboboxwidget="" id="w_111" data-aui-id="1107" aria-expanded="false" aria-live="polite" aria-owns="w_113" aria-labelledby="w_112" data-gqa-name="prempmst.prem_act_stat" data-gqa-aui-id="1107" data-gqa-tabindex="7" data-aui-name="prempmst.prem_act_stat" aria-describedby="tcw-tooltip-22" aria-selected="true">
        <tcw-text-field density="dense" class="gbc_dataContentPlaceholder gbc_WidgetBase gbc_EditWidget gbc_MunisEditWidget w_112 g_measureable gbc_WidgetBase_standalone gbc_staticMeasure aui__1107" __widgetbase="" __editwidget="" __muniseditwidget="" id="w_112" data-aui-id="1107" tcw-text-field-label-floating="">
            <input type="text" class="gbc-label-text-container tyl-text-field__input--focused" autocomplete="new-password" __widgetbase="" __editwidget="" __muniseditwidget="" id="input-w_112" readonly="readonly">
            <label __widgetbase="" __editwidget="" __muniseditwidget="" for="input-w_112" slot="label" class="tyl-floating-label tyl-text-field__label--focused tyl-floating-label--float"></label>
            <char-measurer class="g_layout_charMeasurer" aria-hidden="true">
                <char-measurer-item class="g_layout_charMeasurer1">
                    MMMMMMMMMM
                    M
                    M
                    M
                    M
                    M
                    M
                    M
                    M
                    M
                </char-measurer-item><char-measurer-item class="g_layout_charMeasurer2">0000000000</char-measurer-item>
            </char-measurer><span class="gbc_dataContentMeasure" aria-hidden="" __leaflayoutmeasureelement="">B - BENEFITS ONLY</span><i slot="trailing" class="tyler-icons" aria-hidden="true">arrow_drop_down</i>
        </tcw-text-field><i class="zmdi toggle" title="Open list" __widgetbase="" __comboboxwidget="" __muniscomboboxwidget=""></i>
        <char-measurer class="g_layout_charMeasurer" aria-hidden="true">
            <char-measurer-item class="g_layout_charMeasurer1">
                MMMMMMMMMM
                M
                M
                M
                M
                M
                M
                M
                M
                M
            </char-measurer-item><char-measurer-item class="g_layout_charMeasurer2">0000000000</char-measurer-item>
        </char-measurer><div tabindex="0" class="gbc_dataContentPlaceholder mt-label gbc_WidgetBase gbc_LabelWidget gbc_MunisLabelWidget w_114 g_measureable tyl-typography--caption gbc_WidgetBase_standalone gbc_staticMeasure aui__1107" role="note" __widgetbase="" __labelwidget="" __munislabelwidget="" id="w_114" data-aui-id="1107">
            <span class="gbc-label-text-container is-empty-label" __widgetbase="" __labelwidget="" __munislabelwidget=""></span>
            <char-measurer class="g_layout_charMeasurer" aria-hidden="true">
                <char-measurer-item class="g_layout_charMeasurer1">
                    MMMMMMMMMM
                    M
                    M
                    M
                    M
                    M
                    M
                    M
                    M
                    M
                </char-measurer-item><char-measurer-item class="g_layout_charMeasurer2">0000000000</char-measurer-item>
            </char-measurer><span class="gbc_dataContentMeasure" aria-hidden="" __leaflayoutmeasureelement=""></span>
        </div><tcw-tooltip target="#w_111" text="Active Status from employee master" style="border: 0px; clip: rect(0px, 0px, 0px, 0px); height: 1px; margin: -1px; overflow: hidden; padding: 0px; position: absolute; width: 1px; outline: 0px; appearance: none;" id="tcw-tooltip-22">Active Status from employee master</tcw-tooltip>
    </div>
</div>
</code>```

It's not even showing all the options, just the first two. Has anybody come across html like this? Any ideas on how I can select A for the Status box? I feel like I'm not giving y'all enough to work with, but I'm not sure what else to provide...

Body:
I have no training in python and am trying to write my first script using Python Selenium via Visual Studio Code. I'm currently trying to select an item from a dropdown box, but I'm not understanding how this html was put together, it feels pretty unconventional.

I want to select A-Active from the Status dropdown box:

However, when inspecting the code for the dropdown box it's not using a Select tag. When I copy outerHTML this is all I get back:

    <div class="containerElement gbc_WidgetBase gbc_ComboBoxWidget gbc_MunisComboBoxWidget w_111 g_measureable gbc_WidgetBase_standalone aui__1107 gbc_NotNull gbc_Required gbc_Focus editing" tabindex="0" role="combobox" __widgetbase="" __comboboxwidget="" __muniscomboboxwidget="" id="w_111" data-aui-id="1107" aria-expanded="false" aria-live="polite" aria-owns="w_113" aria-labelledby="w_112" data-gqa-name="prempmst.prem_act_stat" data-gqa-aui-id="1107" data-gqa-tabindex="7" data-aui-name="prempmst.prem_act_stat" aria-describedby="tcw-tooltip-22" aria-selected="true">
        <tcw-text-field density="dense" class="gbc_dataContentPlaceholder gbc_WidgetBase gbc_EditWidget gbc_MunisEditWidget w_112 g_measureable gbc_WidgetBase_standalone gbc_staticMeasure aui__1107" __widgetbase="" __editwidget="" __muniseditwidget="" id="w_112" data-aui-id="1107" tcw-text-field-label-floating="">
            <input type="text" class="gbc-label-text-container tyl-text-field__input--focused" autocomplete="new-password" __widgetbase="" __editwidget="" __muniseditwidget="" id="input-w_112" readonly="readonly">

            <char-measurer class="g_layout_charMeasurer" aria-hidden="true">
                <char-measurer-item class="g_layout_charMeasurer1">
                    MMMMMMMMMM
                    M
                    M
                    M
                    M
                    M
                    M
                    M
                    M
                    M
                </char-measurer-item><char-measurer-item class="g_layout_charMeasurer2">0000000000</char-measurer-item>
            </char-measurer>B - BENEFITS ONLYarrow_drop_down
        </tcw-text-field>
        <char-measurer class="g_layout_charMeasurer" aria-hidden="true">
            <char-measurer-item class="g_layout_charMeasurer1">
                MMMMMMMMMM
                M
                M
                M
                M
                M
                M
                M
                M
                M
            </char-measurer-item><char-measurer-item class="g_layout_charMeasurer2">0000000000</char-measurer-item>
        </char-measurer>

            <char-measurer class="g_layout_charMeasurer" aria-hidden="true">
                <char-measurer-item class="g_layout_charMeasurer1">
                    MMMMMMMMMM
                    M
                    M
                    M
                    M
                    M
                    M
                    M
                    M
                    M
                </char-measurer-item><char-measurer-item class="g_layout_charMeasurer2">0000000000</char-measurer-item>
            </char-measurer>

<tcw-tooltip target="#w_111" text="Active Status from employee master" style="border: 0px; clip: rect(0px, 0px, 0px, 0px); height: 1px; margin: -1px; overflow: hidden; padding: 0px; position: absolute; width: 1px; outline: 0px; appearance: none;" id="tcw-tooltip-22">Active Status from employee master</tcw-tooltip>

It's not even showing all the options, just the first two. Has anybody come across html like this? Any ideas on how I can select A for the Status box? I feel like I'm not giving y'all enough to work with, but I'm not sure what else to provide...


问:
Activity unauthorized causes ondestroy and then immediately oncreate
The application has 2 functions, save the picture to the phone's memory and set the picture on the wallpaper.

They differ only in that the install button has a call to WallpaperManager.

When you click install on Android 12+, onDestroy is called, and then onCreate immediately.

When you click on the save button, the code works fine, the activity is not destroyed

Tell me how to make sure that the activity is not destroyed?

```<code>final WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
switch (ImageDialog.getWhere()) {
    case 1:
        try {
            wallpaperManager.setBitmap(bitmap);     // to the home screen
        } catch (IOException e) {
            e.printStackTrace();
        }
        break;
    case 2:
        try {
            wallpaperManager.setBitmap(bitmap, null, true, WallpaperManager.FLAG_LOCK); // to the lock screen
        } catch (IOException e) {
            e.printStackTrace();
        }
        break;
    case 3:
        try {
            wallpaperManager.setBitmap(bitmap); // to the home screen
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            wallpaperManager.setBitmap(bitmap, null, true, WallpaperManager.FLAG_LOCK); // to the lock screen
        } catch (IOException e) {
            e.printStackTrace();
        }
        break;
}
</code>```

Body:
The application has 2 functions, save the picture to the phone's memory and set the picture on the wallpaper.

They differ only in that the install button has a call to WallpaperManager.

When you click install on Android 12+, onDestroy is called, and then onCreate immediately.

When you click on the save button, the code works fine, the activity is not destroyed

Tell me how to make sure that the activity is not destroyed?

final WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
switch (ImageDialog.getWhere()) {
    case 1:
        try {
            wallpaperManager.setBitmap(bitmap);     // to the home screen
        } catch (IOException e) {
            e.printStackTrace();
        }
        break;
    case 2:
        try {
            wallpaperManager.setBitmap(bitmap, null, true, WallpaperManager.FLAG_LOCK); // to the lock screen
        } catch (IOException e) {
            e.printStackTrace();
        }
        break;
    case 3:
        try {
            wallpaperManager.setBitmap(bitmap); // to the home screen
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            wallpaperManager.setBitmap(bitmap, null, true, WallpaperManager.FLAG_LOCK); // to the lock screen
        } catch (IOException e) {
            e.printStackTrace();
        }
        break;
}


问:
Join and perform aggregation on 2 csv files in python without using panda or sqlite library
For the task, assume that we have a database with the following schema:

```<code>
CREATE TABLE transactions (
transaction_id UUID,
date DATE,
user_id UUID,
is_blocked BOOL,
transaction_amount INTEGER,
transaction_category_id INTEGER
);
CREATE TABLE users (
user_id UUID,
is_active BOOLEAN
);

</code>```

Example data for these tables is stored in the corresponding CSV files - transactions.csv and
users.csv, which can be generated from the generate_data.py script.
I want to compute the result of the following query:

```<code>
SELECT
t.transaction_category_id,
SUM(t.transaction_amount) AS sum_amount,
COUNT(DISTINCT t.user_id) AS num_users
FROM transactions t
JOIN users u USING (user_id)
WHERE t.is_blocked = False
AND u.is_active = 1
GROUP BY t.transaction_category_id
ORDER BY sum_amount DESC;

</code>```

I have to write a Python program using only the Python Standard Library1,2
(preferably not using external libraries at all), which reads data from CSV files
transactions.csv and users.csv, and computes the equivalent result of the SQL query in
an efficient way that would be scalable for large data sets as well. The result should be printed to stdout.

I am new to python so finding it difficult to implement the above code.

I have written the below code that helps to merge the two csv file, but dont know how I can use where or group by or order by .

```<code>import csv

transactions_file = open('M:\\Codebase\\PySpark\\test\\new\\transactions.csv', 'r')
users_file = open('M:\\Codebase\\PySpark\\test\\new\\users.csv', 'r')

transactions_reader1 = list(csv.reader(transactions_file))
users_reader1 = list(csv.reader(users_file))

transactions_reader = list(filter(None, transactions_reader1))
users_reader = list(filter(None, users_reader1))

data = []

for i in range(len(transactions_reader)):
    for j in range(len(users_reader)):
        output_line = []

    # Creating Headers
        if i == 0 and j == 0:
            output_line = ['transaction_id', 'date', 'user_id', 'is_blocked', 'transaction_amount', 'transaction_category_id', 'is_active']

    # Creating data
        else:

            users_line = users_reader[j]
            transactions_line = transactions_reader[i]

            if users_line[0] == transactions_line[2]:
                if str(transactions_line[3]) == 'False' and str(users_line[1]) == 'True':
                    output_line = [transactions_line[2],
                                   float(transactions_line[4]),
                                   int(transactions_line[5])]

        data.append(output_line)

data = list(filter(None, data))
output = []
last = None
data.pop(0)
data = sorted(data, key=lambda x: x[2])

for (user_id, transaction_amount, transaction_category_id) in data:
    if int(transaction_category_id) != last:
        output.append([int(transaction_category_id), 0, 0])
        last = int(transaction_category_id)
        ids = set()
    if user_id not in ids :
        output[-1][1] += 1
        ids.add(user_id)
    output[-1][2] += float(transaction_amount)

output = sorted(output, key=lambda x: x[2], reverse=True)

output.insert(0, "['transaction_category_id', 'num_users', 'sum_amount']")
print(*output, sep = "\n")

</code>```

I have written the above code and able to get the require result

Body:
For the task, assume that we have a database with the following schema:

CREATE TABLE transactions (
transaction_id UUID,
date DATE,
user_id UUID,
is_blocked BOOL,
transaction_amount INTEGER,
transaction_category_id INTEGER
);
CREATE TABLE users (
user_id UUID,
is_active BOOLEAN
);

Example data for these tables is stored in the corresponding CSV files - transactions.csv and
users.csv, which can be generated from the generate_data.py script.
I want to compute the result of the following query:

SELECT
t.transaction_category_id,
SUM(t.transaction_amount) AS sum_amount,
COUNT(DISTINCT t.user_id) AS num_users
FROM transactions t
JOIN users u USING (user_id)
WHERE t.is_blocked = False
AND u.is_active = 1
GROUP BY t.transaction_category_id
ORDER BY sum_amount DESC;

I have to write a Python program using only the Python Standard Library1,2
(preferably not using external libraries at all), which reads data from CSV files
transactions.csv and users.csv, and computes the equivalent result of the SQL query in
an efficient way that would be scalable for large data sets as well. The result should be printed to stdout.

I am new to python so finding it difficult to implement the above code.

I have written the below code that helps to merge the two csv file, but dont know how I can use where or group by or order by .

import csv

transactions_file = open('M:\\Codebase\\PySpark\\test\\new\\transactions.csv', 'r')
users_file = open('M:\\Codebase\\PySpark\\test\\new\\users.csv', 'r')

transactions_reader1 = list(csv.reader(transactions_file))
users_reader1 = list(csv.reader(users_file))

transactions_reader = list(filter(None, transactions_reader1))
users_reader = list(filter(None, users_reader1))

data = []

for i in range(len(transactions_reader)):
    for j in range(len(users_reader)):
        output_line = []

    # Creating Headers
        if i == 0 and j == 0:
            output_line = ['transaction_id', 'date', 'user_id', 'is_blocked', 'transaction_amount', 'transaction_category_id', 'is_active']

    # Creating data
        else:

            users_line = users_reader[j]
            transactions_line = transactions_reader[i]

            if users_line[0] == transactions_line[2]:
                if str(transactions_line[3]) == 'False' and str(users_line[1]) == 'True':
                    output_line = [transactions_line[2],
                                   float(transactions_line[4]),
                                   int(transactions_line[5])]

        data.append(output_line)

data = list(filter(None, data))
output = []
last = None
data.pop(0)
data = sorted(data, key=lambda x: x[2])

for (user_id, transaction_amount, transaction_category_id) in data:
    if int(transaction_category_id) != last:
        output.append([int(transaction_category_id), 0, 0])
        last = int(transaction_category_id)
        ids = set()
    if user_id not in ids :
        output[-1][1] += 1
        ids.add(user_id)
    output[-1][2] += float(transaction_amount)

output = sorted(output, key=lambda x: x[2], reverse=True)

output.insert(0, "['transaction_category_id', 'num_users', 'sum_amount']")
print(*output, sep = "\n")

I have written the above code and able to get the require result


问:
Puppeteer & Handlebars - Custom Fonts
I'm currently attempting to load custom font on a handlebar template using Puppeteer and I can't seem to get it to load custom fonts. The popular question here on stackoverflow linked here
links to a popular Github issues page for Puppeteer linked here. I have tried everything in those two links to no avail. I've tried:

{waitUntil: 'networkidle0'} & {waitUntil: 'networkidle2'}

```<code>await page.evaluateHandle('document.fonts.ready');
</code>```

```<code>await new Promise(resolve => setTimeout(resolve, 500));
</code>```

```<code>await page.focus('body');
</code>```

```<code>await page.screenshot({path: 'tester.png'});
</code>```

```<code>const loaded = page.waitForNavigation({
          waitUntil: "load",
      })
</code>```

From what I can tell on the Github issue, however, is that none of the posters are using Handlebars so that might be why they can get it to work. I noticed a few posters mention doing the HTML inline which I can't do with Handlebars. I've tried both local and online font files to no avail either. I've seen some posts mention using page.go to vs page.setContent like using setContent is the problem but I can't find how to use page.go with Handlebars. I'm also using VisualStudio code as the editor with WSL, not sure if that makes a difference.

Has anyone been able to get either online or local fonts to work with Puppeteer and Handlebars together?

I have this code in the app.js for the static folder:

app.use(express.static(path.join(__dirname, 'modules')))

Here is what I have for code in the app.js file for Puppeteer:

```<code>async function convertToPDF() {

const extData = await extensionListPDFOrganize();

const compile = async function() {
    const filePath = path.join(process.cwd(), 'extensionList.hbs');
    const html = fs.readFileSync(filePath, {encoding:'utf8'});
    return hbs.compile(html)(extData);
}
try {
    const browser = await puppeteer.launch({executablePath: '/usr/bin/google-chrome'});
    const page = await browser.newPage();

    const content = await compile();

    await page.setContent(content);

    //THIS IS WHERE I INSERT THOSE SOLUTIONS IN THE BULLETS ABOVE

    await page.emulateMediaType('screen');
    await page.pdf({
        path: 'test.pdf',
        format: 'Letter',
        printBackground: true
    })

    console.log('done');
    await browser.close();
    process.exit();

}  catch (error) {
    console.log(error)
    return(error);
}}
</code>```

Here is the Handlebar css:

```<code><style type="text/css">
@font-face {
    font-family: 'Lasiver';
    src: url("../modules/fonts/Lasiver.otf");
    font-style: normal;
}
p {
    font-family: 'Lasiver';
}
</style>
</code>```

Title: Puppeteer & Handlebars - Custom Fonts

Body:
I'm currently attempting to load custom font on a handlebar template using Puppeteer and I can't seem to get it to load custom fonts. The popular question here on stackoverflow linked here
links to a popular Github issues page for Puppeteer linked here. I have tried everything in those two links to no avail. I've tried:

{waitUntil: 'networkidle0'} & {waitUntil: 'networkidle2'}

await page.evaluateHandle('document.fonts.ready');

await new Promise(resolve => setTimeout(resolve, 500));

await page.focus('body');

await page.screenshot({path: 'tester.png'});

const loaded = page.waitForNavigation({
          waitUntil: "load",
      })

From what I can tell on the Github issue, however, is that none of the posters are using Handlebars so that might be why they can get it to work. I noticed a few posters mention doing the HTML inline which I can't do with Handlebars. I've tried both local and online font files to no avail either. I've seen some posts mention using page.go to vs page.setContent like using setContent is the problem but I can't find how to use page.go with Handlebars. I'm also using VisualStudio code as the editor with WSL, not sure if that makes a difference.

Has anyone been able to get either online or local fonts to work with Puppeteer and Handlebars together?

I have this code in the app.js for the static folder:

app.use(express.static(path.join(__dirname, 'modules')))

Here is what I have for code in the app.js file for Puppeteer:

async function convertToPDF() {

const extData = await extensionListPDFOrganize();

const compile = async function() {
    const filePath = path.join(process.cwd(), 'extensionList.hbs');
    const html = fs.readFileSync(filePath, {encoding:'utf8'});
    return hbs.compile(html)(extData);
}
try {
    const browser = await puppeteer.launch({executablePath: '/usr/bin/google-chrome'});
    const page = await browser.newPage();

    const content = await compile();

    await page.setContent(content);

    //THIS IS WHERE I INSERT THOSE SOLUTIONS IN THE BULLETS ABOVE

    await page.emulateMediaType('screen');
    await page.pdf({
        path: 'test.pdf',
        format: 'Letter',
        printBackground: true
    })

    console.log('done');
    await browser.close();
    process.exit();

}  catch (error) {
    console.log(error)
    return(error);
}}

Here is the Handlebar css:


问:
Jest-expo all tests fail after update to SDK 47
Before update my expo project to SDK 47, all test suites worked as a charm. But now I'm getting these kind of errors that I don't know how to solve it.

I've noticed those packages are written now with TS. Maybe the error is going around this. Do I need to change something in order to make packages with TS work?

Here are the versions that I'm using:

```<code>"devDependencies": {
    "@babel/core": "^7.19.3",
    "@babel/plugin-proposal-optional-chaining": "^7.16.7",
    "@types/react-native": "~0.70.6",
    "babel-eslint": "^10.1.0",
    "babel-jest": "^26.6.3",
    "babel-plugin-module-resolver": "^4.1.0",
    "babel-preset-expo": "~9.2.1",
    "concurrently": "^7.2.2",
    "deprecated-react-native-prop-types": "^2.3.0",
    "eslint": "^7.32.0",
    "eslint-plugin-jest": "^24.7.0",
    "eslint-plugin-react": "^7.29.4",
    "husky": "^6.0.0",
    "jest-expo": "^47.0.1",
    "jest-json": "^1.1.1",
    "postcss": "^8.4.14",
    "react-native-jest-mocks": "^1.5.0",
    "tailwindcss": "^3.1.4"
  }
</code>```

My jest config

```<code>"jest": {
    "preset": "jest-expo",
    "transformIgnorePatterns": [
      "node_modules/(?!(jest-)?react-native|unimodules-permissions-interface|react-clone-referenced-element|@react-native(-community)?|expo(nent)?|@expo(nent)?/.*|react-navigation|@react-navigation/.*|@unimodules/.*|sentry-expo|native-base|@codler/react-native-keyboard-aware-scroll-view|react-native-paper|react-native-paper/.*|expo-modules-core|expo-modules-core/.*|)"
    ],
    "setupFiles": [
      "./jest-setup.js"
    ],
    "setupFilesAfterEnv": [
      "jest-json"
    ]
  }
</code>```

Any idea? I'd aprreciate your help.

UPDATE
This is an example test.

```<code>import Home from './Home';

import React from 'react';
import {
    cleanup,
    render,
} from '@testing-library/react-native';

import axios from 'axios';
import { Alert } from 'react-native';
import { MockedNavigator, waitFor } from '../../../helpers/testing';

jest.mock('axios');

jest.mock('./Home', () => './Home');

const mockedNavigate = jest.fn();

jest.mock("@react-navigation/native", () => {
    const actualNav = jest.requireActual("@react-navigation/native");
    return {
        ...actualNav,
        useNavigation: () => ({
            navigate: mockedNavigate,
            dispatch: jest.fn(),
            addListener: jest.fn(),
            removeListener: jest.fn(),
        }),
    };
});

beforeAll(() => {
    // Home uses fetch to reload the user, so mock fetch to return a
    // fake user
    global.fetch = jest.fn().mockResolvedValue({
        status: 200,
        ok: true,
        json: () => Promise.resolve({ data: { user: {} } }),
    });
});

afterEach(cleanup);

const setup = async () => {
    return render(
        <MockedNavigator
            routes={[
                { name: 'Home', component: Home },
            ]}
        />
    );
};

describe('API', () => {
    test('Shows error when the request can not be completed', async () => {
        axios.get.mockRejectedValue({
            response: { data: undefined, status: 500 },
        });
        // Mock alert
        Alert.alert = jest.fn();
        await setup();

        await waitFor(() => {
            expect(Alert.alert).toHaveBeenCalledWith('Error', expect.any(String));
        });

    });
});
</code>```

I've already have react-native-paper as a Provider, in my MockedNavigator as follows:

```<code>export const MockedNavigator = ({ routes }) => {
    const { Screen, Navigator } = createStackNavigator();

    return (
        <NavigationContainer>
            <Providers>
                <ReservationProvider>
                    <Navigator>
                        {routes.map((props, index) => (
                            <Screen
                                key={index}
                                {...props}
                            />
                        ))}
                    </Navigator>
                </ReservationProvider>
            </Providers>
        </NavigationContainer>
    );
};
</code>```

```<code>export const Providers = ({ children }) => (
    <NotificationProvider>
        <GeolocationProvider>
            <SettingsProvider>
                <OAuthProvider>
                    <TailwindProvider>
                        <ThemeProvider>
                            <PortalProvider>
                                <CalendarProvider>
                                    <ForegroundNotification />
                                    {children}
                                </CalendarProvider>
                            </PortalProvider>
                        </ThemeProvider>
                    </TailwindProvider>
                </OAuthProvider>
            </SettingsProvider>
        </GeolocationProvider>
    </NotificationProvider>
);
</code>```

```<code>export const ThemeProvider = ({ children }) => {
    const [themeWithFont, setThemeWithFont] = useState(theme);
    useEffect(() => {
        const loadFonts = async () => {
            setThemeWithFont({
                ...theme,
                fonts: {
                    ...theme.fonts,
                    medium: { fontFamily: C.fontFamilyDefault },
                }
            });
        };
        loadFonts();
    }, []);

    return <PaperProvider theme={themeWithFont}>{children}</PaperProvider>;
};
</code>```

```<code>import { Provider as PaperProvider } from 'react-native-paper';
</code>```

Body:
Before update my expo project to SDK 47, all test suites worked as a charm. But now I'm getting these kind of errors that I don't know how to solve it.

I've noticed those packages are written now with TS. Maybe the error is going around this. Do I need to change something in order to make packages with TS work?

Here are the versions that I'm using:

"devDependencies": {
    "@babel/core": "^7.19.3",
    "@babel/plugin-proposal-optional-chaining": "^7.16.7",
    "@types/react-native": "~0.70.6",
    "babel-eslint": "^10.1.0",
    "babel-jest": "^26.6.3",
    "babel-plugin-module-resolver": "^4.1.0",
    "babel-preset-expo": "~9.2.1",
    "concurrently": "^7.2.2",
    "deprecated-react-native-prop-types": "^2.3.0",
    "eslint": "^7.32.0",
    "eslint-plugin-jest": "^24.7.0",
    "eslint-plugin-react": "^7.29.4",
    "husky": "^6.0.0",
    "jest-expo": "^47.0.1",
    "jest-json": "^1.1.1",
    "postcss": "^8.4.14",
    "react-native-jest-mocks": "^1.5.0",
    "tailwindcss": "^3.1.4"
  }

My jest config

"jest": {
    "preset": "jest-expo",
    "transformIgnorePatterns": [
      "node_modules/(?!(jest-)?react-native|unimodules-permissions-interface|react-clone-referenced-element|@react-native(-community)?|expo(nent)?|@expo(nent)?/.*|react-navigation|@react-navigation/.*|@unimodules/.*|sentry-expo|native-base|@codler/react-native-keyboard-aware-scroll-view|react-native-paper|react-native-paper/.*|expo-modules-core|expo-modules-core/.*|)"
    ],
    "setupFiles": [
      "./jest-setup.js"
    ],
    "setupFilesAfterEnv": [
      "jest-json"
    ]
  }

Any idea? I'd aprreciate your help.

UPDATE
This is an example test.

import Home from './Home';

import React from 'react';
import {
    cleanup,
    render,
} from '@testing-library/react-native';

import axios from 'axios';
import { Alert } from 'react-native';
import { MockedNavigator, waitFor } from '../../../helpers/testing';

jest.mock('axios');

jest.mock('./Home', () => './Home');

const mockedNavigate = jest.fn();

jest.mock("@react-navigation/native", () => {
    const actualNav = jest.requireActual("@react-navigation/native");
    return {
        ...actualNav,
        useNavigation: () => ({
            navigate: mockedNavigate,
            dispatch: jest.fn(),
            addListener: jest.fn(),
            removeListener: jest.fn(),
        }),
    };
});

beforeAll(() => {
    // Home uses fetch to reload the user, so mock fetch to return a
    // fake user
    global.fetch = jest.fn().mockResolvedValue({
        status: 200,
        ok: true,
        json: () => Promise.resolve({ data: { user: {} } }),
    });
});

afterEach(cleanup);

const setup = async () => {
    return render(
        <MockedNavigator
            routes={[
                { name: 'Home', component: Home },
            ]}
        />
    );
};

describe('API', () => {
    test('Shows error when the request can not be completed', async () => {
        axios.get.mockRejectedValue({
            response: { data: undefined, status: 500 },
        });
        // Mock alert
        Alert.alert = jest.fn();
        await setup();

        await waitFor(() => {
            expect(Alert.alert).toHaveBeenCalledWith('Error', expect.any(String));
        });

    });
});

I've already have react-native-paper as a Provider, in my MockedNavigator as follows:

export const MockedNavigator = ({ routes }) => {
    const { Screen, Navigator } = createStackNavigator();

    return (
        <NavigationContainer>
            <Providers>
                <ReservationProvider>
                    <Navigator>
                        {routes.map((props, index) => (
                            <Screen
                                key={index}
                                {...props}
                            />
                        ))}
                    </Navigator>
                </ReservationProvider>
            </Providers>
        </NavigationContainer>
    );
};

export const Providers = ({ children }) => (
    <NotificationProvider>
        <GeolocationProvider>
            <SettingsProvider>
                <OAuthProvider>
                    <TailwindProvider>
                        <ThemeProvider>
                            <PortalProvider>
                                <CalendarProvider>
                                    <ForegroundNotification />
                                    {children}
                                </CalendarProvider>
                            </PortalProvider>
                        </ThemeProvider>
                    </TailwindProvider>
                </OAuthProvider>
            </SettingsProvider>
        </GeolocationProvider>
    </NotificationProvider>
);

export const ThemeProvider = ({ children }) => {
    const [themeWithFont, setThemeWithFont] = useState(theme);
    useEffect(() => {
        const loadFonts = async () => {
            setThemeWithFont({
                ...theme,
                fonts: {
                    ...theme.fonts,
                    medium: { fontFamily: C.fontFamilyDefault },
                }
            });
        };
        loadFonts();
    }, []);

    return <PaperProvider theme={themeWithFont}>{children}</PaperProvider>;
};

import { Provider as PaperProvider } from 'react-native-paper';


问:
Doctriny - Symfony Flush not adding to DataBase
The flush function does not add anything to the database even though it doesn't return any error.
Any idea of how can I solve that?
Thanks in advance for your help!
Here is my code:

Controller:

```<code>#[Route("/messages")]
    public function create(Request $request, ManagerRegistry $signup, UserRepository $userRepository, MessageRepository $messageRepository): Response
    {
        $message = new Message();
        $userRepository = $signup->getRepository(User::class);
        $formdico = [];
        foreach ($userRepository->findAll() as $user) {
            $userform = $this->createForm(MessageType::class, $message);
            $formdico[$user->getId()] = $userform;
        }

        foreach ($formdico as $form) {

            $form->handleRequest($request);
            if ($form->isSubmitted() && $form->isValid()) {
                $newMessage = new Message();
                $newMessage->setSender($userRepository->findOneById($form->getData()->getSender()));
                $newMessage->setReceiver($userRepository->findOneById($form->getData()->getSender()));
                $newMessage->setContent($form->getData()->getContent());
                $newMessage->setCreatedAt(new \DateTime('now'));

                $em = $signup->getManager();
                $em->persist($newMessage);
                $em->flush($newMessage);
            }
        }
        foreach ($userRepository->findAll() as $user) {
            $userform = $this->createForm(MessageType::class, $message);
            $formdico[$user->getId()] = $userform->createView();
        }
        return $this->render('message/readAllUser.html.twig', ['users' => $userRepository->findAll(), "formdico" => $formdico, 'messages' => $messageRepository->findAll()]);
    }
</code>```

Entity:

```<code><?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity()]
class Message
{

    #[ORM\Id]
    #[ORM\GeneratedValue(strategy: "AUTO")]
    #[ORM\Column(type: "integer")]
    private int $id;

    #[ORM\ManyToOne(targetEntity: "App\Entity\User", inversedBy: "sendedMessages")]
    private $sender;

    #[ORM\ManyToOne(targetEntity: "App\Entity\User", inversedBy: "receivedMessages")]
    private $receiver;

    #[ORM\Column(type: "text")]
    private string $content;

    #[ORM\Column(type: "date")]
    private \DateTime $createdAt;

    /**
     * Get the value of id
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set the value of id
     *
     * @return  self
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * Get the value of sender
     */
    public function getSender()
    {
        return $this->sender;
    }

    /**
     * Set the value of sender
     *
     * @return  self
     */
    public function setSender($sender)
    {
        $this->sender = $sender;

        return $this;
    }

    /**
     * Get the value of receiver
     */
    public function getReceiver()
    {
        return $this->receiver;
    }

    /**
     * Set the value of receiver
     *
     * @return  self
     */
    public function setReceiver($receiver)
    {
        $this->receiver = $receiver;

        return $this;
    }

    /**
     * Get the value of content
     */
    public function getContent()
    {
        return $this->content;
    }

    /**
     * Set the value of content
     *
     * @return  self
     */
    public function setContent($content)
    {
        $this->content = $content;

        return $this;
    }

    /**
     * Get the value of createdAt
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set the value of createdAt
     *
     * @return  self
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }
}
</code>```

Form:

```<code><?php

namespace App\Form;

use App\Entity\Message;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;

class MessageType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('sender', IntegerType::class, [])
            ->add('content', TextType::class, ['label' => false, 'attr' => ['placeholder' => 'Message Content']])
            ->add('receiver', IntegerType::class, []);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults(['data_class' => Message::class,]);
    }
}

</code>```

I tried removing the persist, dumped a lot of things to try understanding the problem but I can't get to solve this...
And the form is valid

Body:
The flush function does not add anything to the database even though it doesn't return any error.
Any idea of how can I solve that?
Thanks in advance for your help!
Here is my code:

Controller:

#[Route("/messages")]
    public function create(Request $request, ManagerRegistry $signup, UserRepository $userRepository, MessageRepository $messageRepository): Response
    {
        $message = new Message();
        $userRepository = $signup->getRepository(User::class);
        $formdico = [];
        foreach ($userRepository->findAll() as $user) {
            $userform = $this->createForm(MessageType::class, $message);
            $formdico[$user->getId()] = $userform;
        }

        foreach ($formdico as $form) {

            $form->handleRequest($request);
            if ($form->isSubmitted() && $form->isValid()) {
                $newMessage = new Message();
                $newMessage->setSender($userRepository->findOneById($form->getData()->getSender()));
                $newMessage->setReceiver($userRepository->findOneById($form->getData()->getSender()));
                $newMessage->setContent($form->getData()->getContent());
                $newMessage->setCreatedAt(new \DateTime('now'));

                $em = $signup->getManager();
                $em->persist($newMessage);
                $em->flush($newMessage);
            }
        }
        foreach ($userRepository->findAll() as $user) {
            $userform = $this->createForm(MessageType::class, $message);
            $formdico[$user->getId()] = $userform->createView();
        }
        return $this->render('message/readAllUser.html.twig', ['users' => $userRepository->findAll(), "formdico" => $formdico, 'messages' => $messageRepository->findAll()]);
    }

Entity:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity()]
class Message
{

    #[ORM\Id]
    #[ORM\GeneratedValue(strategy: "AUTO")]
    #[ORM\Column(type: "integer")]
    private int $id;

    #[ORM\ManyToOne(targetEntity: "App\Entity\User", inversedBy: "sendedMessages")]
    private $sender;

    #[ORM\ManyToOne(targetEntity: "App\Entity\User", inversedBy: "receivedMessages")]
    private $receiver;

    #[ORM\Column(type: "text")]
    private string $content;

    #[ORM\Column(type: "date")]
    private \DateTime $createdAt;

    /**
     * Get the value of id
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set the value of id
     *
     * @return  self
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * Get the value of sender
     */
    public function getSender()
    {
        return $this->sender;
    }

    /**
     * Set the value of sender
     *
     * @return  self
     */
    public function setSender($sender)
    {
        $this->sender = $sender;

        return $this;
    }

    /**
     * Get the value of receiver
     */
    public function getReceiver()
    {
        return $this->receiver;
    }

    /**
     * Set the value of receiver
     *
     * @return  self
     */
    public function setReceiver($receiver)
    {
        $this->receiver = $receiver;

        return $this;
    }

    /**
     * Get the value of content
     */
    public function getContent()
    {
        return $this->content;
    }

    /**
     * Set the value of content
     *
     * @return  self
     */
    public function setContent($content)
    {
        $this->content = $content;

        return $this;
    }

    /**
     * Get the value of createdAt
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set the value of createdAt
     *
     * @return  self
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }
}

Form:

<?php

namespace App\Form;

use App\Entity\Message;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;

class MessageType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('sender', IntegerType::class, [])
            ->add('content', TextType::class, ['label' => false, 'attr' => ['placeholder' => 'Message Content']])
            ->add('receiver', IntegerType::class, []);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults(['data_class' => Message::class,]);
    }
}

I tried removing the persist, dumped a lot of things to try understanding the problem but I can't get to solve this...
And the form is valid


问:
Hover Effect turns off text
I designed a blue button with a white text on it, but the blue effect on the button prevents the white text and destroys the text. How can I complete the text without destroying the effect?

.button {
  position: relative;
  top: -250px;
  left: 200px;
  display: inline-block;
  text-decoration: none;
  text-transform: uppercase;
  color: #fff;
  outline: 2px solid #0059f3;
  padding: 30px 60px;
  overflow: hidden;
  transition: color 1s;
}

.button:hover {
  color: #0059f3;
}

.button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -50px;
  z-index: 0;
  width: 150%;
  height: 100%;
  background-color: #0059f3;
  transform: scaleX(0) skewX(35deg);
  transform-origin: left;
  transition: transform 1s;
}

.button:hover::before {
  transform: scaleX(1) skewX(35deg);
}```

Title: Hover Effect turns off text


问:
Pyspark merge two dataframes based on condition

Last_name
Gender
Job
First_name

ABC
F
HR
Mary

ABC
F
HR
Lily

This is my first dataframe. And here is my second dataframe

Last_name
Gender
Job
First_name

ABC
F
HR
Lisa

ABC
F
HR
Jenny

DDD
F
AN
Luna

ABC
M
HR
Mike

I want to merge these two dataframes where [last_name, gender, first_name] match the first dataframe. So the final output should be:

Last_name
Gender
Job
First_name

ABC
F
HR
Mary

ABC
F
HR
Lily

ABC
F
HR
Lisa

ABC
F
HR
Jenny

How to do this in pyspark? Thanks.


问:
How can I write a unit test to check that a React component method calls a Firebase auth method?
I'm building a React web app with a Firebase backend. I'm cool with React and Firebase, and I'm able to implement all the functionality I need without issue.

However, I'm also using this project as an opportunity to learn unit testing, currently using React Testing Library and Jest.

I can successfully test for rendered UI elements. What I'm struggling to get my head around is how I can test for a successful call of the Firebase API, for example with the below form component which allows a user to request a password reset email.

So, as of now, I'm able to successfully test:

if the form is rendered correctly

if the correct UI (warning) elements are rendered when the form is submitted with an invalid or missing email address

What I also want to be able to test for is:

if the sendPasswordResetEmail method is called when the form is submitted with a valid email address

I've stripped the component back to its most basic form (ignoring validation, etc, for now) to demonstrate. Users enter an email address, submit the form, and the Firebase method sendPasswordResetEmail is called.

My question is: how can I write a test that checks whether the sendPasswordResetEmail method is called successfully on form submit?

Is it even possible to test for this case?

Is this even the right question to ask? I'm super new to unit testing. :o)

Any suggestions?

Thanks!

```<code>import React, { useState } from "react";
import { auth } from "../../lib/firebaseApp";
import { sendPasswordResetEmail } from "firebase/auth";

const PasswordResetForm = (props) => {
  const [email, setEmail] = useState(null);

  const handleChange = (e) => {
    setEmail(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    sendPasswordResetEmail(auth, email)
      .then(() => {
        //Email sent
      })
      .catch((error) => {
        console.log(error);
      });
  };

  return (
    <form noValidate onSubmit={handleSubmit}>
      <input type="text" name="email" value={email || ""} onChange={handleChange} />
      <SubmitButton buttonText="Reset password" />
    </form>
  );
};

export default PasswordResetForm;
</code>```

Here's a test I've written for one of the UI elements (for info only):

```<code>import { render, fireEvent, screen } from "@testing-library/react";
import { BrowserRouter } from "react-router-dom";
import userEvent from "@testing-library/user-event";
import "@testing-library/jest-dom";

//Component
import PasswordResetForm from "../../../components/forms/passwordresetform";

describe("Password reset form", () => {
  it("Should render an email field", () => {
    render(<PasswordResetForm />, { wrapper: BrowserRouter });
    const input = screen.getByRole("textbox", { name: "email" });
    expect(input).toBeInTheDocument();
  });
});
</code>```

UPDATE:

I've also now attempted to write a test to check whether the sendPasswordResetEmail method is called successfully:

```<code>import React from "react";
import { render, fireEvent, screen } from "@testing-library/react";
import { BrowserRouter } from "react-router-dom";
import userEvent from "@testing-library/user-event";
import "@testing-library/jest-dom";

import { getAuth, sendPasswordResetEmail } from "firebase/auth";

//Component
import PasswordResetForm from "../../../components/forms/passwordresetform";

//Mock firebase
jest.mock('firebase/auth', () => {
  return {
    getAuth: () => jest.fn(),
    sendPasswordResetEmail: () => jest.fn().mockResolvedValue({}),
  }
});

//UI tests
describe("Password reset form", () => {
  it("Should allow good email addresses and call sendPasswordResetEmail", async () => {
    render(<PasswordResetForm />, { wrapper: BrowserRouter });
    const input = screen.getByRole("textbox", { name: "email" });
    const button = screen.getByRole("button", { name: "submit" });
    const value = "user@domain.com";
    userEvent.type(input, value);
    fireEvent.click(button);
    expect(sendPasswordResetEmail).toBeCalledWith(getAuth(), value);
  });
});
</code>```

However, this is giving me the following error:

```<code>TypeError: (0 , _auth.sendPasswordResetEmail)(...).then is not a function

      42 |     if (dataValid) {
      43 |       sendPasswordResetEmail(auth, email)
    > 44 |         .then(() => {
         |          ^
</code>```

So, the question I now have is am I using jest.fn().mockResolvedValue({}) in the right way?

And if so, why isn't it working?

Body:
I'm building a React web app with a Firebase backend. I'm cool with React and Firebase, and I'm able to implement all the functionality I need without issue.

However, I'm also using this project as an opportunity to learn unit testing, currently using React Testing Library and Jest.

I can successfully test for rendered UI elements. What I'm struggling to get my head around is how I can test for a successful call of the Firebase API, for example with the below form component which allows a user to request a password reset email.

So, as of now, I'm able to successfully test:

if the form is rendered correctly

if the correct UI (warning) elements are rendered when the form is submitted with an invalid or missing email address

What I also want to be able to test for is:

if the sendPasswordResetEmail method is called when the form is submitted with a valid email address

I've stripped the component back to its most basic form (ignoring validation, etc, for now) to demonstrate. Users enter an email address, submit the form, and the Firebase method sendPasswordResetEmail is called.

My question is: how can I write a test that checks whether the sendPasswordResetEmail method is called successfully on form submit?

Is it even possible to test for this case?

Is this even the right question to ask? I'm super new to unit testing. :o)

Any suggestions?

Thanks!

import React, { useState } from "react";
import { auth } from "../../lib/firebaseApp";
import { sendPasswordResetEmail } from "firebase/auth";

const PasswordResetForm = (props) => {
  const [email, setEmail] = useState(null);

  const handleChange = (e) => {
    setEmail(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    sendPasswordResetEmail(auth, email)
      .then(() => {
        //Email sent
      })
      .catch((error) => {
        console.log(error);
      });
  };

  return (
    <form noValidate onSubmit={handleSubmit}>
      <input type="text" name="email" value={email || ""} onChange={handleChange} />
      <SubmitButton buttonText="Reset password" />
    </form>
  );
};

export default PasswordResetForm;

Here's a test I've written for one of the UI elements (for info only):

import { render, fireEvent, screen } from "@testing-library/react";
import { BrowserRouter } from "react-router-dom";
import userEvent from "@testing-library/user-event";
import "@testing-library/jest-dom";

//Component
import PasswordResetForm from "../../../components/forms/passwordresetform";

describe("Password reset form", () => {
  it("Should render an email field", () => {
    render(<PasswordResetForm />, { wrapper: BrowserRouter });
    const input = screen.getByRole("textbox", { name: "email" });
    expect(input).toBeInTheDocument();
  });
});

UPDATE:

I've also now attempted to write a test to check whether the sendPasswordResetEmail method is called successfully:

import React from "react";
import { render, fireEvent, screen } from "@testing-library/react";
import { BrowserRouter } from "react-router-dom";
import userEvent from "@testing-library/user-event";
import "@testing-library/jest-dom";

import { getAuth, sendPasswordResetEmail } from "firebase/auth";

//Component
import PasswordResetForm from "../../../components/forms/passwordresetform";

//Mock firebase
jest.mock('firebase/auth', () => {
  return {
    getAuth: () => jest.fn(),
    sendPasswordResetEmail: () => jest.fn().mockResolvedValue({}),
  }
});

//UI tests
describe("Password reset form", () => {
  it("Should allow good email addresses and call sendPasswordResetEmail", async () => {
    render(<PasswordResetForm />, { wrapper: BrowserRouter });
    const input = screen.getByRole("textbox", { name: "email" });
    const button = screen.getByRole("button", { name: "submit" });
    const value = "user@domain.com";
    userEvent.type(input, value);
    fireEvent.click(button);
    expect(sendPasswordResetEmail).toBeCalledWith(getAuth(), value);
  });
});

However, this is giving me the following error:

TypeError: (0 , _auth.sendPasswordResetEmail)(...).then is not a function

      42 |     if (dataValid) {
      43 |       sendPasswordResetEmail(auth, email)
    > 44 |         .then(() => {
         |          ^

So, the question I now have is am I using jest.fn().mockResolvedValue({}) in the right way?

And if so, why isn't it working?


问:
Is there an SMTPAppenter for log4net in .NetCore yet? Alternatives?
Is there an SMTPAppender for log4net in.NetCore yet?

I can find a post from 2017 saying it's not in yet,

Log4Net SmtpAppender not working in .netCore

but that's been quite a while. There are so many .net SMTPAppender posts that I'm not sure if it's lost in the noise, or doesn't actually exist.

If it doesn't exist, what is the best equivalent?

I'm on .netcore 3.1 Vs2019, WebApi if it matters.


问:
pip installed websockets but still getting "ModuleNotFoundError: No module named 'websockets' "
I am importing websockets into my project:

```<code>import websockets
</code>```

have installed websockets using pip but am still getting this error:

```<code>ModuleNotFoundError: No module named 'websockets'
</code>```

I've tried uninstalling and reinstalling websockets and clearing cache using pip
using python 3.10.2, VsCode

Body:
I am importing websockets into my project:

import websockets

have installed websockets using pip but am still getting this error:

ModuleNotFoundError: No module named 'websockets'

I've tried uninstalling and reinstalling websockets and clearing cache using pip
using python 3.10.2, VsCode


问:
Optimization based on rank and absolute deviation
I have a problem statement where i am trying to optimize the position of the shipment such that 2 specific objectives are met, Deviation time and inherent ranking

Given: some Shipments, the objective is to sequence them in a way such that the deviation between the actual start - planned start is minimized, while also ensuring that the ranking of shipments is optimized.

Example: 3 shipments which need to be executed at [10 am, 12 noon, 1 PM] , assuming each statement takes 1 hour to be executed, what should be the sequence of execution?

```<code>Shipments [S1 S2 S3]
Planned ranking [1 2 3]
Planned time [10,12,13]
</code>```

The solver should give me a solution where the ranking and deviation between the planned and actual time should be less

Example Solution
Optimized ranking can be [2 1 3] execute S2 first, then S1 and finally S3
Optimized time can be anywhere between 1 - 24 depending on other constraints.
hence S2 can begin at either 1 and can take values till 22
S1 should begin after S2 and can take matters from S1 end time till 23
and S3 should begin after S2 and S1 and can take values from the End of S1 till 24.

I was able to write down the ranking part where the objective function is Minimizing the rank(Derived froma pre-determined matrix) and binary choice of shipment and position:

'''

```<code>import random
import pandas as pd
from pulp import *

shipments = {'D1':1, 'D2':2, 'D3':3}
positions = {'P1':1, 'P2':2, 'P3':3}
endtime = {'D1':10, 'D2':15, 'D3':20}

rank={('D1', 'P1'): 2,
('D1', 'P2'): 4,
('D1', 'P3'): 7,
('D2', 'P1'): 3,
('D2', 'P3'): 2,
('D2', 'P2'): 1,
('D3', 'P3'): 1,
('D3', 'P2'): 2,
('D3', 'P1'): 3}

shipments_labels = sorted(shipments.keys())
positions_labels = sorted(positions.keys())

BIG_M = 9999.9

# Binary to hold shipment assigned to position
x = LpVariable.dicts("x", (shipments_labels,positions_labels), 0, 1, LpInteger)
y = LpVariable.dicts("y", (shipments_labels,positions_labels), 1, 24, LpInteger) # to hold the time starting for shipment
y_diff = LpVariable.dicts("y_diff", (shipments_labels),  cat='Real') # to hold absolute deviations

print(x)
print(y)
print(y_diff)
print(rank[('D1', 'P1')])

prob = LpProblem("ranking", LpMinimize)

prob += (lpSum([(rank[(i,j)]**2 -1) * x[i][j] for i in shipments_labels for j in positions_labels]),
                'Total_Cost') # Objective Function

# #every shipment should be assigned a position
for i in shipments_labels:
    prob += (lpSum([x[i][j] for j in positions_labels])==1)

# #every position only 1 shipment
for i in positions_labels:
    prob += (lpSum([x[j][i] for j in shipments_labels])==1)

prob.solve()

for v in prob.variables():
    print(v)
    print(v.varValue)

</code>```

'''

However, I am confused about how to code the deviation logic into the objective. I created the variables yij to hold the interger value of the allocated time and y_diff to hold the absolute deviation. Since deviation can be both positive and negative, it can be penalized differently.

1- Problem Statement

2- Problem Statement

3- Problem Statement

Body:
I have a problem statement where i am trying to optimize the position of the shipment such that 2 specific objectives are met, Deviation time and inherent ranking

Given: some Shipments, the objective is to sequence them in a way such that the deviation between the actual start - planned start is minimized, while also ensuring that the ranking of shipments is optimized.

Example: 3 shipments which need to be executed at [10 am, 12 noon, 1 PM] , assuming each statement takes 1 hour to be executed, what should be the sequence of execution?

Shipments [S1 S2 S3]
Planned ranking [1 2 3]
Planned time [10,12,13]

The solver should give me a solution where the ranking and deviation between the planned and actual time should be less

Example Solution
Optimized ranking can be [2 1 3] execute S2 first, then S1 and finally S3
Optimized time can be anywhere between 1 - 24 depending on other constraints.
hence S2 can begin at either 1 and can take values till 22
S1 should begin after S2 and can take matters from S1 end time till 23
and S3 should begin after S2 and S1 and can take values from the End of S1 till 24.

I was able to write down the ranking part where the objective function is Minimizing the rank(Derived froma pre-determined matrix) and binary choice of shipment and position:

'''

import random
import pandas as pd
from pulp import *

shipments = {'D1':1, 'D2':2, 'D3':3}
positions = {'P1':1, 'P2':2, 'P3':3}
endtime = {'D1':10, 'D2':15, 'D3':20}

rank={('D1', 'P1'): 2,
('D1', 'P2'): 4,
('D1', 'P3'): 7,
('D2', 'P1'): 3,
('D2', 'P3'): 2,
('D2', 'P2'): 1,
('D3', 'P3'): 1,
('D3', 'P2'): 2,
('D3', 'P1'): 3}

shipments_labels = sorted(shipments.keys())
positions_labels = sorted(positions.keys())

BIG_M = 9999.9

# Binary to hold shipment assigned to position
x = LpVariable.dicts("x", (shipments_labels,positions_labels), 0, 1, LpInteger)
y = LpVariable.dicts("y", (shipments_labels,positions_labels), 1, 24, LpInteger) # to hold the time starting for shipment
y_diff = LpVariable.dicts("y_diff", (shipments_labels),  cat='Real') # to hold absolute deviations

print(x)
print(y)
print(y_diff)
print(rank[('D1', 'P1')])

prob = LpProblem("ranking", LpMinimize)

prob += (lpSum([(rank[(i,j)]**2 -1) * x[i][j] for i in shipments_labels for j in positions_labels]),
                'Total_Cost') # Objective Function

# #every shipment should be assigned a position
for i in shipments_labels:
    prob += (lpSum([x[i][j] for j in positions_labels])==1)

# #every position only 1 shipment
for i in positions_labels:
    prob += (lpSum([x[j][i] for j in shipments_labels])==1)

prob.solve()

for v in prob.variables():
    print(v)
    print(v.varValue)

'''

However, I am confused about how to code the deviation logic into the objective. I created the variables yij to hold the interger value of the allocated time and y_diff to hold the absolute deviation. Since deviation can be both positive and negative, it can be penalized differently.

1- Problem Statement

2- Problem Statement

3- Problem Statement


问:
Can we use two status validation like for example * match 200 and 208 at same time in karate api testing automation
I need to validate two status code at same time for example

match 200,208
Any one of above if pass code should pass
Do we have something like it


问:
Local storage event listener not working for some users
I have a React app that opens a new tab using window.open('myurl.com') to authenticate a user. In the new tab, authentication receives a response object and updates local storage.
In the original tab, there is a local storage event listener that triggers another action like so:

```<code>useEffect(() => {
     window.addEventListener('storage', async (event) => {
        console.log(event.newValue);
        // do something with event.newValue here
    })
}, [])
</code>```

For most users, this works perfectly. But for a handful of users, when I console log the new value in the original tab, it keeps saying null. For the users that it's working, they are primarily using Edge browser. For the users that it isn't working, we have tried Edge, Chrome, Firefox, and all in private mode as well. We have also tried updating the browsers to the latest version

Is there some sort of browser setting that could be blocking the event listener from being triggered for some users?

Body:
I have a React app that opens a new tab using window.open('myurl.com') to authenticate a user. In the new tab, authentication receives a response object and updates local storage.
In the original tab, there is a local storage event listener that triggers another action like so:

useEffect(() => {
     window.addEventListener('storage', async (event) => {
        console.log(event.newValue);
        // do something with event.newValue here
    })
}, [])

For most users, this works perfectly. But for a handful of users, when I console log the new value in the original tab, it keeps saying null. For the users that it's working, they are primarily using Edge browser. For the users that it isn't working, we have tried Edge, Chrome, Firefox, and all in private mode as well. We have also tried updating the browsers to the latest version

Is there some sort of browser setting that could be blocking the event listener from being triggered for some users?


问:
Initialize Huggingface pipeline from binary file
I am storing my models in a mongodb.
I can get both the pytorch_model.bin and the config.json.

Now I am asking how I can use these two files to initialize a pipeline.

Can I somehow create a PretrainedModel from the binary and config?


问:
What to do with unused GtkGrid locations in UI created by Glade
I have created with Glade a fairly complicated UI and often there are unused GtkGrid locations. I was filling them with blank labels but now I'm thinking that's silly and I should just leave them blank. I believe (not 100% sure) that Glade puts <placeholder/> tags in those locations.

If I leave them as placeholders, does that leave the behaviour somewhat undefined or at risk of some weird thing happening depending upon platform or operating system?

Note: It does seem to usually be possible to avoid placeholders with carefully constructed grids in grids.


问:
Best Way to Remove Functionality from Java Spring Boot App at Build
I'm looking for a way to conditionally remove functionality from my Spring Boot app during the build. Whether that is a Maven plugin that strips out the actual Java classes or packages, or just is able to set a variable that cannot be later changed environmentally.

My spring boot app has a bunch of reports that can be generated but they shouldn't all be available in every environment they are deployed in. I would like an easy build config file where I can set which reports are enabled and disabled before build. I need them hard set at build, so someone with control of the environment can't just go in and update an associated property value and they become enabled again.

I was looking for some plugin that would remove classes or packages, or that could hardcode the variable value into the compiled class files but couldn't find anything. I figure there must be some way to make configuration stuck at build time. Have been unsuccessful finding a way to set properties at build that cannot be overridden.


问:
Formik validations not working after adding errors and touched
Below I have shown my Formik validations via "errors , touched".  However no errors are showing up if I try to submit the form

```<code>return (
    <div>
        {loading && "Loading..."}
        <Formik
            initialValues={{
                title: 'Software developer',
            }}
            onSubmit={handleSubmit}>
</code>```

Here I am passing in errors and touched as provided by the Formik tags started above

```<code>            {({ errors, touched }) => (
                <Form>
                    <Field name="title">
                        {({ field, form }) => (
                            <label className="mt-3 block">
                                <span className="text-gray-700">Title</span>
                                <input
                                    {...field}
                                    type="text"
                                    placeholder="Software developer"
                                    style={
                                        form.touched.title && form.errors.title ? (
                                            { border: '2px solid var(--primary-red)' }
                                        ) : null
                                    }
                                />
                            </label>
                        )}
                    </Field>

                    <button type="submit">Submit</button>
                </Form>
            )}
        </Formik>
    </div>
)
</code>```

Body:
Below I have shown my Formik validations via "errors , touched".  However no errors are showing up if I try to submit the form

return (

        {loading && "Loading..."}
        <Formik
            initialValues={{
                title: 'Software developer',
            }}
            onSubmit={handleSubmit}>

Here I am passing in errors and touched as provided by the Formik tags started above

            {({ errors, touched }) => (
                <Form>
                    <Field name="title">
                        {({ field, form }) => (

                                Title
                                <input
                                    {...field}
                                    type="text"
                                    placeholder="Software developer"
                                    style={
                                        form.touched.title && form.errors.title ? (
                                            { border: '2px solid var(--primary-red)' }
                                        ) : null
                                    }
                                />

                        )}
                    </Field>

                    <button type="submit">Submit</button>
                </Form>
            )}
        </Formik>

)


问:
BigQuery giving "Function Not Found" error although the schema column title was copied directly from the dataset
Screenshot of error msg & SQL query
Is my SQL query off? Is BigQuery off?

I attempted to copy the column title again [no R clicks needed, simply mouse click the schema title and it inserts into the query itself]


问:
Strategy error when try to update the RocksDB default column family options
I am trying to update the Ttl option (in scala) for the default column family in RocksDB.

Following the code snippet i am using:

```<code>db = RocksDB.open(options, dir)
val optionsBuilder = db.getOptions()
optionsBuilder.setTtl(30)
db.setOptions(optionsBuilder.build())
</code>```

But i am getting Error parsing:: blob_compression_type error

```<code> org.rocksdb.RocksDBException: Error parsing:: blob_compression_type
  at org.rocksdb.RocksDB.setOptions(Native Method)
  at org.rocksdb.RocksDB.setOptions(RocksDB.java:3436)

</code>```

I checked the default options, it's NO_COMPRESSION. Switching to other compression type doesn't work either

```<code>optionsBuilder.setBlobCompressionType(CompressionType.SNAPPY_COMPRESSION)
</code>```

Any suggestions?

How to update the default column family options in RocksDB

Body:
I am trying to update the Ttl option (in scala) for the default column family in RocksDB.

Following the code snippet i am using:

db = RocksDB.open(options, dir)
val optionsBuilder = db.getOptions()
optionsBuilder.setTtl(30)
db.setOptions(optionsBuilder.build())

But i am getting Error parsing:: blob_compression_type error

 org.rocksdb.RocksDBException: Error parsing:: blob_compression_type
  at org.rocksdb.RocksDB.setOptions(Native Method)
  at org.rocksdb.RocksDB.setOptions(RocksDB.java:3436)

I checked the default options, it's NO_COMPRESSION. Switching to other compression type doesn't work either

optionsBuilder.setBlobCompressionType(CompressionType.SNAPPY_COMPRESSION)

Any suggestions?

How to update the default column family options in RocksDB