问:
i try rowspan in table which is not working
hey i tried rowspan in a table to get desired result but result i different from what i want i have also include desired result img and code.. please have a look on code..
thanks

desired result image

            A
            B

            C

            D
            E

            F
            G
            H

            I
            J

            K
            L

           M

```

答:
In this particular case (i.e. cells with hardly any contents) the only things you can do are:

1.) Add more content to the cells. If the amount of contents corresponds to the cell heights (or becomes even higher), they will adjust automatically.

or

2.) If you intend to have as few contents as in your example code, add a height setting to one of the cells that are supposed to span several rows - see snippet below, where the only change to your original code is an added height: 4em; for the bottom cell in the first column ("I").

            A
            B

            C

            D
            E

            F
            G
            H

            I
            J

            K
            L

           M

```

Body:
In this particular case (i.e. cells with hardly any contents) the only things you can do are:

1.) Add more content to the cells. If the amount of contents corresponds to the cell heights (or becomes even higher), they will adjust automatically.

or

2.) If you intend to have as few contents as in your example code, add a height setting to one of the cells that are supposed to span several rows - see snippet below, where the only change to your original code is an added height: 4em; for the bottom cell in the first column ("I").

<table border="1" width="100%" >
        <!--1st row-->
        <tr>
            <td rowspan="2" colspan="2">A</td>
            <td colspan="3" rowspan="1">B</td>
        </tr>
        <!--2nd row-->
        <tr>
            <td colspan="3" rowspan="1">C</td>
        </tr>
        <!--3rd row-->
        <tr>
            <td rowspan="1" colspan="1">D</td>
            <td rowspan="1" colspan="1">E</td>

            <td rowspan="3" colspan="1">F</td>
            <td rowspan="2" colspan="1">G</td>
            <td rowspan="1" colspan="1">H</td>

        </tr>
        <!--4th row-->
        <tr>
            <td rowspan="3" colspan="2" style="height: 4em;">I</td>
            <td rowspan="1" colspan="1">J</td>

        </tr>
        <!--5th row-->
        <tr>
            <td rowspan="2">K</td>
            <td rowspan="2">L</td>
        </tr>
        <!--6th row-->
       <tr>
           <td rowspan="1" colspan="1">M</td>
       </tr>

    </table>


来源: stackexchange

问:
Dynamic property type based on value of anther property
How to best implement a property with a dynamic data type depending on the value of another property?

I have a class for an Order with two properties OrderType (enum) and OrderStatus (enum)

The problem is that the data type for OrderStatus is different depending on the value OrderType

```<code>public class Order
{
    // Enums
    public enum OrderTypes { Restaurant, Grocery, Wallet }

    public enum RestaurantOrderStatus { OrderPlaced, Pending, Preparing, ReadyForPickup OnTheWay, Cancelled }
    public enum GroceryOrderStatus { OrderPlaced, Enqueued, Preparing, OnTheWay, Cancelled, Returning }
    public enum WalletOrderStatus { OrderPlaced, OnTheWay, Cancelled }

    // Properties
    public OrderTypes OrderType { get; set; }
    public OrderStatuses OrderStatus { get; set; } // How to set a dynamic data type (different enum)?
    public int Id { get; set; }
}
</code>```

What is the best approach to do this?

Using Generic Type?

Using Builder Pattern?

答:
I would implement a Generic Type.</p>
```<code>public class Order<T> where T : Enum
{
    public Enums.OrderTypes OrderType { get; set; }
    public T OrderStatus { get; set; }
    public int Id { get; set; }
}

public class Enums
{
    public enum OrderTypes { Restaurant, Grocery, Wallet }

    public enum RestaurantOrderStatus { OrderPlaced, Pending, Preparing, ReadyForPickup, OnTheWay, Cancelled }
    public enum GroceryOrderStatus { OrderPlaced, Enqueued, Preparing, OnTheWay, Cancelled, Returning }
    public enum WalletOrderStatus { OrderPlaced, OnTheWay, Cancelled }
}

public class UseCase
{
    public static void UseLike()
    {
        Enums.OrderTypes orderType = Enums.OrderTypes.Grocery;

        switch (orderType)
        {
            case Enums.OrderTypes.Restaurant:
                _ = new Order<Enums.RestaurantOrderStatus>();
                break;
            case Enums.OrderTypes.Grocery:
                _ = new Order<Enums.GroceryOrderStatus>();
                break;
            case Enums.OrderTypes.Wallet:
                _ = new Order<Enums.WalletOrderStatus>();
                break;
        }

    }
}

</code>```

ContentLicense: CC BY-SA 4.0

Body:
How to best implement a property with a dynamic data type depending on the value of another property?

I have a class for an Order with two properties OrderType (enum) and OrderStatus (enum)

The problem is that the data type for OrderStatus is different depending on the value OrderType

public class Order
{
    // Enums
    public enum OrderTypes { Restaurant, Grocery, Wallet }

    public enum RestaurantOrderStatus { OrderPlaced, Pending, Preparing, ReadyForPickup OnTheWay, Cancelled }
    public enum GroceryOrderStatus { OrderPlaced, Enqueued, Preparing, OnTheWay, Cancelled, Returning }
    public enum WalletOrderStatus { OrderPlaced, OnTheWay, Cancelled }

    // Properties
    public OrderTypes OrderType { get; set; }
    public OrderStatuses OrderStatus { get; set; } // How to set a dynamic data type (different enum)?
    public int Id { get; set; }
}

What is the best approach to do this?

Using Generic Type?

Using Builder Pattern?

Body:
I would implement a Generic Type.

public class Order<T> where T : Enum
{
    public Enums.OrderTypes OrderType { get; set; }
    public T OrderStatus { get; set; }
    public int Id { get; set; }
}

public class Enums
{
    public enum OrderTypes { Restaurant, Grocery, Wallet }

    public enum RestaurantOrderStatus { OrderPlaced, Pending, Preparing, ReadyForPickup, OnTheWay, Cancelled }
    public enum GroceryOrderStatus { OrderPlaced, Enqueued, Preparing, OnTheWay, Cancelled, Returning }
    public enum WalletOrderStatus { OrderPlaced, OnTheWay, Cancelled }
}

public class UseCase
{
    public static void UseLike()
    {
        Enums.OrderTypes orderType = Enums.OrderTypes.Grocery;

        switch (orderType)
        {
            case Enums.OrderTypes.Restaurant:
                _ = new Order<Enums.RestaurantOrderStatus>();
                break;
            case Enums.OrderTypes.Grocery:
                _ = new Order<Enums.GroceryOrderStatus>();
                break;
            case Enums.OrderTypes.Wallet:
                _ = new Order<Enums.WalletOrderStatus>();
                break;
        }

    }
}


问:
Why does adding extra arrow function parentheses resolve an infinite loop problem?
I'm working on my project using react but I encountered a problem with using setState hook.

Here is my code:

```<code>//state and handle function

const [activeStep, setActiveStep] = React.useState(0);
const handleStep = (index)  => {
        setActiveStep(index);
}

//return component (I'm using mui)

return (
            <Stepper nonLinear activeStep={activeStep}>
                {steps.map((label, index) => (
                    <Step key={label} completed={false}>
                        <StepButton color="inherit" onClick={handleStep(index)}>
                            {label}
                        </StepButton>
                    </Step>
                ))}
            </Stepper>

    );
</code>```

With this code page enters infinite loop and the page doesn't show up. But if I add an extra parentheses to handlestep function:

```<code>//added extra parantheses
const handleStep = (index) => () => {
        setActiveStep(index);
    }
</code>```

It doesn't enter infinite loop and everything seems working.
Does adding parentheses to arrow functions changes functionality or is it a MUI component bug?

答:
You are calling function instead of passing.

Change this

```<code><StepButton color="inherit" onClick={handleStep(index)}>
</code>```

Into this

```<code><StepButton color="inherit" onClick={() => handleStep(index)}>
</code>```

Body:
I'm working on my project using react but I encountered a problem with using setState hook.

Here is my code:

//state and handle function

const [activeStep, setActiveStep] = React.useState(0);
const handleStep = (index)  => {
        setActiveStep(index);
}

//return component (I'm using mui)

return (
            <Stepper nonLinear activeStep={activeStep}>
                {steps.map((label, index) => (
                    <Step key={label} completed={false}>
                        <StepButton color="inherit" onClick={handleStep(index)}>
                            {label}
                        </StepButton>
                    </Step>
                ))}
            </Stepper>

    );

With this code page enters infinite loop and the page doesn't show up. But if I add an extra parentheses to handlestep function:

//added extra parantheses
const handleStep = (index) => () => {
        setActiveStep(index);
    }

It doesn't enter infinite loop and everything seems working.
Does adding parentheses to arrow functions changes functionality or is it a MUI component bug?

Body:
You are calling function instead of passing.

Change this

<StepButton color="inherit" onClick={handleStep(index)}>

Into this

<StepButton color="inherit" onClick={() => handleStep(index)}>


问:
Populate a database with python and Django efficiently
We are trying to populate a database with Python and Django with random numbers, but we have a lot of rows to go through, and it takes like 20 minutes to carry out that task.

This is our code. We have 210000 rows to go through

```<code>def populate(request):

    all_accounts = Account.objects.all()
    count = 0

    for account in all_accounts:
        account.avg_deal_size = round(random.randint(10, 200000), 2)
        account.save()
        print(f"Counter of accounts: {count}")
        count += 1
</code>```

Thank you!

答:
Assuming you don't need any logic in .save(), or signals to be executed or such, just use SQL to have your RDBMS do the heavy lifting. This should execute in seconds if that.

```<code>from django.db import connection

def populate(request):
    with connection.cursor() as cur:
        cur.execute("UPDATE myapp_account SET avg_deal_size = round(10 + random() * 190000, 2)")
        (res,) = cur.fetchone()
        print(f"{res} rows affected.")
</code>```

Body:
We are trying to populate a database with Python and Django with random numbers, but we have a lot of rows to go through, and it takes like 20 minutes to carry out that task.

This is our code. We have 210000 rows to go through

def populate(request):

    all_accounts = Account.objects.all()
    count = 0

    for account in all_accounts:
        account.avg_deal_size = round(random.randint(10, 200000), 2)
        account.save()
        print(f"Counter of accounts: {count}")
        count += 1

Thank you!

Body:
Assuming you don't need any logic in .save(), or signals to be executed or such, just use SQL to have your RDBMS do the heavy lifting. This should execute in seconds if that.

from django.db import connection

def populate(request):
    with connection.cursor() as cur:
        cur.execute("UPDATE myapp_account SET avg_deal_size = round(10 + random() * 190000, 2)")
        (res,) = cur.fetchone()
        print(f"{res} rows affected.")


问:
Split Div Into 2 Columns Using CSS
I have been attempting to split a div into two columns using CSS, but I have not managed to get it working yet.  My basic structure is as follows:

```<code><div id="content">
  <div id="left">
     <div id="object1"></div>
     <div id="object2"></div>
  </div>

  <div id="right">
     <div id="object3"></div>
     <div id="object4"></div>
  </div>
</div>
</code>```

If I attempt to float the right and left divs to their respective positions (right and left), it seems to ignore the content div's background-color.  And other code that I have tried from various websites doesn't seem to be able to translate to my structure.

Thanks for any help!

答:
If you don't care old browser and need a simple way.

#content {
  display: flex;
}

#left,
#right {
  flex: 50%;
}
```

ContentLicense: CC BY-SA 2.5

Title: Split Div Into 2 Columns Using CSS

Body:
I have been attempting to split a div into two columns using CSS, but I have not managed to get it working yet.  My basic structure is as follows:

If I attempt to float the right and left divs to their respective positions (right and left), it seems to ignore the content div's background-color.  And other code that I have tried from various websites doesn't seem to be able to translate to my structure.

Thanks for any help!


问:
Android ScrollView, scroll before visible
how can I set scroll of scrollview to x pixels, before it's even shown?

In ScrollView I have some Views and i know that it will fill screen. Can I scroll to let say second View, so that first View is not visible when activity is started?

Now I have sth like this, but I think it's not perfect, sometimes, I see first View, and then it's scrolled to the second one

```<code>@Override
public void onGlobalLayout() {
    if (mHorizontalScrollView.getChildCount() > 0 && mHorizontalScrollView.getChildAt(0).getWidth() > mScreenWidth) {
            hsv.scrollTo(100, 0);
    }
}
</code>```

EDIT!!

Second attempt was to use http://developer.android.com/reference/android/view/ViewTreeObserver.OnPreDrawListener.html instead of http://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener.html
In OnPreDrawListener we can read that At this point, all views in the tree have been measured and given a frame. Clients can use this to adjust their scroll bounds or even to request a new layout before drawing occurs. so basically at this point we should adjust scrolling. So I created:

```<code>@Override
public boolean onPreDraw() {
    if (hsv.getChildCount() > 0 && hsv.getChildAt(0).getWidth() > mScreenWidth) {
        hsv.scrollTo(100, 0);
        return false;
    }
    return true;
}
</code>```

but now it's never working for me.

答:
Use :

```<code>scrollTo (int x, int y)

It sets the scrolled position of your view. This will cause a call to onScrollChanged
</code>```

For more details : see this

ScrollView ScrollTo

ContentLicense: CC BY-SA 3.0

Body:
how can I set scroll of scrollview to x pixels, before it's even shown?

In ScrollView I have some Views and i know that it will fill screen. Can I scroll to let say second View, so that first View is not visible when activity is started?

Now I have sth like this, but I think it's not perfect, sometimes, I see first View, and then it's scrolled to the second one

@Override
public void onGlobalLayout() {
    if (mHorizontalScrollView.getChildCount() > 0 && mHorizontalScrollView.getChildAt(0).getWidth() > mScreenWidth) {
            hsv.scrollTo(100, 0);
    }
}

EDIT!!

Second attempt was to use http://developer.android.com/reference/android/view/ViewTreeObserver.OnPreDrawListener.html instead of http://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener.html
In OnPreDrawListener we can read that At this point, all views in the tree have been measured and given a frame. Clients can use this to adjust their scroll bounds or even to request a new layout before drawing occurs. so basically at this point we should adjust scrolling. So I created:

@Override
public boolean onPreDraw() {
    if (hsv.getChildCount() > 0 && hsv.getChildAt(0).getWidth() > mScreenWidth) {
        hsv.scrollTo(100, 0);
        return false;
    }
    return true;
}

but now it's never working for me.

Body:
Use :

scrollTo (int x, int y)

It sets the scrolled position of your view. This will cause a call to onScrollChanged

For more details : see this

ScrollView ScrollTo


问:
Tracking Changes in TOP N Products from Year to Year using DAX in PowerBI
Let's say I set my slicer value to N = 3 and Year = 2021, I would like to return a table that shows which products were in the Top 3 in the selected year 2021 but not in the prior year 2020.

So if the TOP 3 products in 2021 were Bananas, Oatmeal and Chocolate, and in 2020 were Bananas, Bread, and Coffee, the result should just be Oatmeal and Chocolate. In general, the results will vary for the user-selected values of N and Year.

I've written a DAX query that does exactly this with no problem. The problem is that I can't dynamically use it in Power BI:

```<code>``` Measure Top N SKU IN =
VAR N = MAX('Popularity Slicer'[Value]) -- get max value on the popularity slicer
VAR YearSlicer = SELECTEDVALUE('L2 Top SKUs'[Year]) -- get sliced year

-- filter table on TOP N and selected Year
VAR SelectedYearTable =
    CALCULATETABLE(
        'L2 Top SKUs',
        FILTER('L2 Top SKUs', 'L2 Top SKUs'[Popularity] <= N),
        FILTER('L2 Top SKUs', 'L2 Top SKUs'[Year] = YearSlicer) -- look at the previous year
    )

-- filter table on TOP N and prior Year
VAR PriorYearTable =
CALCULATETABLE(
        'L2 Top SKUs',
        FILTER('L2 Top SKUs', 'L2 Top SKUs'[Popularity] <= N),
        FILTER('L2 Top SKUs', 'L2 Top SKUs'[Year] = YearSlicer - 1 )
    )

-- get popularity measure
VAR SelectedYear =
    SELECTCOLUMNS(
        SelectedYearTable,
        "Matnr", [Matnr],
        "Year", [Year],
        "Cosine", [Total Cosine Projection],
        "Popularity", RANKX(SelectedYearTable, [Total Cosine Projection])
        )

VAR PriorYear =
SELECTCOLUMNS(
    PriorYearTable,
    "Matnr", [Matnr],
    "Year", [Year],
    "Cosine", [Total Cosine Projection],
    "Popularity", RANKX(PriorYearTable, [Total Cosine Projection])
    )

-- get the intersection
VAR SKUs = EXCEPT(
    SELECTCOLUMNS(
        FILTER(SelectedYear, [Popularity] <= N),
        "SKU",
        [Matnr]
    ),
    SELECTCOLUMNS(
        FILTER(PriorYear, [Popularity] <= N),
        "SKU",
        [Matnr]
    )
)

RETURN
SKUs```
</code>```

The measure won't return the results, SKUs because it contains multiple values. I can't compute a table, however, because SELECTEDVALUE only works in measures . . . Below is a screenshot of what the query should return. Can anyone help?

Screenshot of DAX query which returns new "Most Popular" products in 2021 for N = 20 and Year = 2021

EDIT: I've since tried taking the virtual column, SKUs, and converting this into an actual measure. I did this with the following code in DAX Studio and it worked perfectly (see attached photo).

The code asks the base table 'L2 Top SKUs' if any of it's parts numbers (Matnr) are in the virtual column SKUs and returns 1 if "yes" and 0 if "no". Then, to evaluate the measure, I add it as a column to the base table and filter for [Top] = 1, which gives the correct answer. When I go to do this in PowerBI it gives some 1's and some 0's but it's not correct and it is the same exact code:

```<code>MEASURE 'L2 Top SKUs'[Top] = If(FIRSTNONBLANK('L2 Top SKUs'[Matnr], 0) IN SKUs, 1, 0)

VAR Results = ADDCOLUMNS(
        SELECTCOLUMNS(
            'L2 Top SKUs',
            "Matnr", 'L2 Top SKUs'[Matnr]
        ),
        "Top", [Top]
    )

EVALUATE
DISTINCT(FILTER(Results, [Top] = 1))```

![Screenshot of DAX query which returns new "Most Popular" products in 2021 for N = 20 and Year = 2021][2]

  [1]: https://i.stack.imgur.com/WLAHQ.png
  [2]: https://i.stack.imgur.com/yt0bV.png
```

答:
I found a work around for what I was trying to do, which was to calculate a table that shows the change in a measure from a previous time period. The way to do this is to have two Date tables connected in series to the primary table (or tables) and to make the relationship between them inactive. I then used two different slicers (one corresponding to each of the Date tables) which I was able to use to compare two different periods of time. The two periods are user set in this case, which is not exactly what I was thinking (I wanted the time differential to be automatically set to 1 year), but it does job.

Here's how to build it: https://www.daxpatterns.com/comparing-different-time-periods/

Body:
Let's say I set my slicer value to N = 3 and Year = 2021, I would like to return a table that shows which products were in the Top 3 in the selected year 2021 but not in the prior year 2020.

So if the TOP 3 products in 2021 were Bananas, Oatmeal and Chocolate, and in 2020 were Bananas, Bread, and Coffee, the result should just be Oatmeal and Chocolate. In general, the results will vary for the user-selected values of N and Year.

I've written a DAX query that does exactly this with no problem. The problem is that I can't dynamically use it in Power BI:

``` Measure Top N SKU IN =
VAR N = MAX('Popularity Slicer'[Value]) -- get max value on the popularity slicer
VAR YearSlicer = SELECTEDVALUE('L2 Top SKUs'[Year]) -- get sliced year

-- filter table on TOP N and selected Year
VAR SelectedYearTable =
    CALCULATETABLE(
        'L2 Top SKUs',
        FILTER('L2 Top SKUs', 'L2 Top SKUs'[Popularity] <= N),
        FILTER('L2 Top SKUs', 'L2 Top SKUs'[Year] = YearSlicer) -- look at the previous year
    )

-- filter table on TOP N and prior Year
VAR PriorYearTable =
CALCULATETABLE(
        'L2 Top SKUs',
        FILTER('L2 Top SKUs', 'L2 Top SKUs'[Popularity] <= N),
        FILTER('L2 Top SKUs', 'L2 Top SKUs'[Year] = YearSlicer - 1 )
    )

-- get popularity measure
VAR SelectedYear =
    SELECTCOLUMNS(
        SelectedYearTable,
        "Matnr", [Matnr],
        "Year", [Year],
        "Cosine", [Total Cosine Projection],
        "Popularity", RANKX(SelectedYearTable, [Total Cosine Projection])
        )

VAR PriorYear =
SELECTCOLUMNS(
    PriorYearTable,
    "Matnr", [Matnr],
    "Year", [Year],
    "Cosine", [Total Cosine Projection],
    "Popularity", RANKX(PriorYearTable, [Total Cosine Projection])
    )

-- get the intersection
VAR SKUs = EXCEPT(
    SELECTCOLUMNS(
        FILTER(SelectedYear, [Popularity] <= N),
        "SKU",
        [Matnr]
    ),
    SELECTCOLUMNS(
        FILTER(PriorYear, [Popularity] <= N),
        "SKU",
        [Matnr]
    )
)

RETURN
SKUs```

The measure won't return the results, SKUs because it contains multiple values. I can't compute a table, however, because SELECTEDVALUE only works in measures . . . Below is a screenshot of what the query should return. Can anyone help?

Screenshot of DAX query which returns new "Most Popular" products in 2021 for N = 20 and Year = 2021

EDIT: I've since tried taking the virtual column, SKUs, and converting this into an actual measure. I did this with the following code in DAX Studio and it worked perfectly (see attached photo).

The code asks the base table 'L2 Top SKUs' if any of it's parts numbers (Matnr) are in the virtual column SKUs and returns 1 if "yes" and 0 if "no". Then, to evaluate the measure, I add it as a column to the base table and filter for [Top] = 1, which gives the correct answer. When I go to do this in PowerBI it gives some 1's and some 0's but it's not correct and it is the same exact code:

MEASURE 'L2 Top SKUs'[Top] = If(FIRSTNONBLANK('L2 Top SKUs'[Matnr], 0) IN SKUs, 1, 0)

VAR Results = ADDCOLUMNS(
        SELECTCOLUMNS(
            'L2 Top SKUs',
            "Matnr", 'L2 Top SKUs'[Matnr]
        ),
        "Top", [Top]
    )

EVALUATE
DISTINCT(FILTER(Results, [Top] = 1))```

![Screenshot of DAX query which returns new "Most Popular" products in 2021 for N = 20 and Year = 2021][2]

  [1]: https://i.stack.imgur.com/WLAHQ.png
  [2]: https://i.stack.imgur.com/yt0bV.png


问:
How do I trigger a change event on radio buttons in react-testing-library?
I'm in the process of moving over to react-testing-library, and have no idea how to trigger this event and get the results of the changes.

I've tried using the fireEvent function to trigger the change, and then tried the rerender function, but I can't seem to get it to work.

App.js

```<code>import React, { useState } from "react";
import logo from "./logo.svg";
import "./App.css";

const options = {
  DoTheThing: 'DoTheThing',
  DoOtherThing: 'DoOtherThing',
};

function App() {
  const [action, setAction] = useState(options.DoTheThing);

  return (
    <div className="App">
      <header className="App-header">
        <form>
          <fieldset>
            <label>
              <input
                type="radio"
                name="radio1"
                value={options.DoTheThing}
                checked={action === options.DoTheThing}
                onChange={event => setAction(event.target.value)}
              />
              First
            </label>

            <label>
              <input
                type="radio"
                name="radio1"
                value={options.DoOtherThing}
                checked={action === options.DoOtherThing}
                onChange={event => setAction(event.target.value)}
              />
              Second
            </label>
          </fieldset>
        </form>
      </header>
    </div>
  );
}

export default App;
</code>```

App.test.js

```<code>import React from 'react';
import { render, cleanup, fireEvent } from 'react-testing-library';
import App from './App';

afterEach(cleanup);

it('should change the value ', () => {
  const {getByLabelText, rerender } = render(<App/>);
  const second = getByLabelText(/Second/);

  fireEvent.change(second);
  rerender(<App/>);

  expect(document.forms[0].elements.radio1.value).toEqual("DoOtherThing");

});
</code>```

答:
This worked for me (working with the radio buttons, not the radio groups):</p>
```<code>// some code here to make sure the screen has finished rendering, and I have all radio buttons in the DOM (I am expecting 5 containers):
await waitFor(() => expect(screen.getAllByTestId('some-slow-loading-container')).toHaveLength(5))

// get all "true" labeled radio buttons by test id (or by role + name or whatever):
const allTrueLabelRadioButtons = screen.getAllByTestId('true-label-radio-button');

// loop over the array of HTML elements found:
for (const trueLabelRadioButton of allTrueLabelRadioButtons) {
   // using fireEvent instead of userEvent because of some bugs with the components library I am stuck with. Usually I use userEvent:
   fireEvent.click(trueLabelRadioButton)
}

// check whatever you are expecting to happen after all radio buttons are set to "true".
//...
</code>```

Body:
I'm in the process of moving over to react-testing-library, and have no idea how to trigger this event and get the results of the changes.

I've tried using the fireEvent function to trigger the change, and then tried the rerender function, but I can't seem to get it to work.

App.js

import React, { useState } from "react";
import logo from "./logo.svg";
import "./App.css";

const options = {
  DoTheThing: 'DoTheThing',
  DoOtherThing: 'DoOtherThing',
};

function App() {
  const [action, setAction] = useState(options.DoTheThing);

  return (

        <form>
          <fieldset>

              <input
                type="radio"
                name="radio1"
                value={options.DoTheThing}
                checked={action === options.DoTheThing}
                onChange={event => setAction(event.target.value)}
              />
              First

              <input
                type="radio"
                name="radio1"
                value={options.DoOtherThing}
                checked={action === options.DoOtherThing}
                onChange={event => setAction(event.target.value)}
              />
              Second

          </fieldset>
        </form>

  );
}

export default App;

App.test.js

import React from 'react';
import { render, cleanup, fireEvent } from 'react-testing-library';
import App from './App';

afterEach(cleanup);

it('should change the value ', () => {
  const {getByLabelText, rerender } = render(<App/>);
  const second = getByLabelText(/Second/);

  fireEvent.change(second);
  rerender(<App/>);

  expect(document.forms[0].elements.radio1.value).toEqual("DoOtherThing");

});

Body:
This worked for me (working with the radio buttons, not the radio groups):

// some code here to make sure the screen has finished rendering, and I have all radio buttons in the DOM (I am expecting 5 containers):
await waitFor(() => expect(screen.getAllByTestId('some-slow-loading-container')).toHaveLength(5))

// get all "true" labeled radio buttons by test id (or by role + name or whatever):
const allTrueLabelRadioButtons = screen.getAllByTestId('true-label-radio-button');

// loop over the array of HTML elements found:
for (const trueLabelRadioButton of allTrueLabelRadioButtons) {
   // using fireEvent instead of userEvent because of some bugs with the components library I am stuck with. Usually I use userEvent:
   fireEvent.click(trueLabelRadioButton)
}

// check whatever you are expecting to happen after all radio buttons are set to "true".
//...


问:
Restore unstaged changes lost on branch switch with IntelliJ / PhpStorm
I am using PhpStorm as IDE and did edit some files without commiting them to VCS nor staging them. Unfortunately I switched the branch I was working in to one where the files don't exist. There was a notice popping up, probably telling me I would lose my changes, but by accidentally hitting the keyboard at the same time I confirmed that notice immediately.

Is there a way to restore my lost changes?

答:
For me PhpStorm saved the lost changes in the Shelf. To restore your changes from there, complete these steps:

Open the "Commit" menu (Alt+0)

In the opened window go to the "Shelf" tab. If the window doesn't have enough horizontal space, it could be placed under "Show hidden tabs" button near the tab name, you can find the "Shelf" tab there.

Select a respective line with "Uncommited changes before ..." that you wish to restore and click "Unshelve Silently" button (Ctrl+Alt+U). You can also choose to restore files selectively and do the same process.

Make sure that your changes are restored and commit them if you need to.

If you completed the previous step, you can delete the shelved changes, as they are not needed anymore - select, then right click and "Delete" (or select and press Delete).


问:
Selenium Grid: Unable to start selenium grid hub
after downloading selenium-server-4.0.0.jar from here

```<code>https://www.selenium.dev/downloads/
</code>```

I put this jar file in the c folder and after that
using cmd I tried launching selenium grid hub using this command

```<code>java -jar selenium-server-4.0.0.jar hub
</code>```

I'm unable to run the selenium grid hub it shows the following

```<code>C:\>java -jar selenium-server-4.0.0.jar hub
12:29:21.621 INFO [LogManager$RootLogger.log] - Using the system default encoding
12:29:21.624 INFO [OpenTelemetryTracer.createTracer] - Using OpenTelemetry for tracing
12:29:22.034 INFO [BoundZmqEventBus.<init>] - XPUB binding to [binding to tcp://*:4442,
advertising as tcp://192.168.100.8:4442], XSUB binding to [binding to tcp://*:4443,
advertising as tcp://192.168.100.8:4443]
12:29:22.073 INFO [UnboundZmqEventBus.<init>] - Connecting to tcp://192.168.100.8:4442 and
tcp://192.168.100.8:4443
12:29:22.094 INFO [UnboundZmqEventBus.<init>] - Sockets created
12:29:23.110 INFO [UnboundZmqEventBus.<init>] - Event bus ready
12:29:24.443 INFO [Hub.execute] - Started Selenium Hub 4.0.0 (revision 3a21814679):
http://192.168.100.8:4444
</code>```

I tried putting this URL in chrome browser

```<code>http://192.168.100.8:4444
</code>```

then it shows this

```<code>Unable to find /index.html
</code>```

答: I had similar issue. It turns out it was a java problem . I had some old jdk8 version. After switching to jdk11 it works fine.</p>

Body:
after downloading selenium-server-4.0.0.jar from here

https://www.selenium.dev/downloads/

I put this jar file in the c folder and after that
using cmd I tried launching selenium grid hub using this command

java -jar selenium-server-4.0.0.jar hub

I'm unable to run the selenium grid hub it shows the following

C:\>java -jar selenium-server-4.0.0.jar hub
12:29:21.621 INFO [LogManager$RootLogger.log] - Using the system default encoding
12:29:21.624 INFO [OpenTelemetryTracer.createTracer] - Using OpenTelemetry for tracing
12:29:22.034 INFO [BoundZmqEventBus.<init>] - XPUB binding to [binding to tcp://*:4442,
advertising as tcp://192.168.100.8:4442], XSUB binding to [binding to tcp://*:4443,
advertising as tcp://192.168.100.8:4443]
12:29:22.073 INFO [UnboundZmqEventBus.<init>] - Connecting to tcp://192.168.100.8:4442 and
tcp://192.168.100.8:4443
12:29:22.094 INFO [UnboundZmqEventBus.<init>] - Sockets created
12:29:23.110 INFO [UnboundZmqEventBus.<init>] - Event bus ready
12:29:24.443 INFO [Hub.execute] - Started Selenium Hub 4.0.0 (revision 3a21814679):
http://192.168.100.8:4444

I tried putting this URL in chrome browser

http://192.168.100.8:4444

then it shows this

Unable to find /index.html


问:
User location annotation misplaced when not default
I am showing the user location in an MKMapView. I don't want the default blue circle but instead the red pin.

Therefore I implemented mapView:viewForAnnotation: and made it always return a red pin as the user's location is the only pin I will show on the map view.

When using the default blue circle the location is quite precise but when changing to the red pin it's off quite a lot. It's as if the red pin is dropped precisely and is then moved up so it does not longer show my current position.

This is my code:

```<code>- (MKAnnotationView *)mapView:(MKMapView *)_mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    NSLog(@"MapView: Annotation.");

    MKPinAnnotationView *pin = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:nil];
    [pin setPinColor:MKPinAnnotationColorRed];
    [pin setAnimatesDrop:YES];
    [pin setCanShowCallout:NO];

    return pin;
}
</code>```

I use mapView:didAddAnnotationViews: to center the map view to my current location.

```<code>- (void)mapView:(MKMapView *)_mapView didAddAnnotationViews:(NSArray *)views
{
    for(MKAnnotationView *annotationView in views)
    {
        if(annotationView.annotation == _mapView.userLocation)
        {
            MKCoordinateRegion region;
            MKCoordinateSpan span;

            span.latitudeDelta = 0.20;
            span.longitudeDelta = 0.20;

            CLLocationCoordinate2D location = [[_mapView userLocation] coordinate];

            region.span = span;
            region.center = location;

            [_mapView setRegion:region animated:YES];
            [_mapView regionThatFits:region];
        }
    }
}
</code>```

Does anyone know why my annotation is no longer placed correct when using the red pin instead of the default annotation view?

答: Setting [pin setAnimatesDrop:NO] instead of YES solved this.

Body:
I am showing the user location in an MKMapView. I don't want the default blue circle but instead the red pin.

Therefore I implemented mapView:viewForAnnotation: and made it always return a red pin as the user's location is the only pin I will show on the map view.

When using the default blue circle the location is quite precise but when changing to the red pin it's off quite a lot. It's as if the red pin is dropped precisely and is then moved up so it does not longer show my current position.

This is my code:

- (MKAnnotationView *)mapView:(MKMapView *)_mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    NSLog(@"MapView: Annotation.");

    MKPinAnnotationView *pin = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:nil];
    [pin setPinColor:MKPinAnnotationColorRed];
    [pin setAnimatesDrop:YES];
    [pin setCanShowCallout:NO];

    return pin;
}

I use mapView:didAddAnnotationViews: to center the map view to my current location.

- (void)mapView:(MKMapView *)_mapView didAddAnnotationViews:(NSArray *)views
{
    for(MKAnnotationView *annotationView in views)
    {
        if(annotationView.annotation == _mapView.userLocation)
        {
            MKCoordinateRegion region;
            MKCoordinateSpan span;

            span.latitudeDelta = 0.20;
            span.longitudeDelta = 0.20;

            CLLocationCoordinate2D location = [[_mapView userLocation] coordinate];

            region.span = span;
            region.center = location;

            [_mapView setRegion:region animated:YES];
            [_mapView regionThatFits:region];
        }
    }
}

Does anyone know why my annotation is no longer placed correct when using the red pin instead of the default annotation view?


问:
mutate columns with labels attributes in r
I have imported data from SPSS and I want to transform some variables to factors, without having to list them all. These variables can be distinguished from the others by having the attribute labels, so I want to use the condition length(get_labels(variable.name))>0 to mutate (or, if not possible, to select) them.

Using the following example (despite not being a tbl_df as would be if imported with haven::read_sav)

```<code>dt <- data.table(a = 1:4,
                 b = factor(c(1,2,1,1), levels=1:2, labels=c("Yes","No")),
                 d = c("xxx", "yyy", "zzz", "kkk"),
                 e = factor(c(1,1,3,2), levels=1:4, labels=c("A","B","C","D")))

</code>```

I have tried

dt %>% mutate_at(vars(length(get_labels(.))>0), haven::as_factor)

dt %>% mutate_if((length(get_labels(.))>0), haven::as_factor)

but that didn't work.

How can I achieve the desired result, that is, mutate/select the columns band e?

Thanks!

答:
You can do it like this:

```<code>library(haven)
df = read_sav("iris.sav")

is.havenlab <- function(x) "haven_labelled" %in% class(x)
df %>% mutate(across(where(is.havenlab),haven::as_factor))
</code>```

Input (first three rows of df before mutating the is.havenlab columns)

```<code># A tibble: 150 x 5
   Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
          <dbl>       <dbl>        <dbl>       <dbl>  <dbl+lbl>
 1          5.1         3.5          1.4         0.2 1 [setosa]
 2          4.9         3            1.4         0.2 1 [setosa]
 3          4.7         3.2          1.3         0.2 1 [setosa]
</code>```

Output (first three rows after finding all the 'haven-labelled' columns and converting to factor

```<code># A tibble: 150 x 5
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
          <dbl>       <dbl>        <dbl>       <dbl> <fct>
 1          5.1         3.5          1.4         0.2 setosa
 2          4.9         3            1.4         0.2 setosa
 3          4.7         3.2          1.3         0.2 setosa
</code>```

data.table approach

This shows an alternative function, which I've called has.labels (either this or the above one, is.havenlab) work fine.

```<code>df = setDT(read_sav("iris.sav"))
has.labels <- function(x) !is.null(attr(x,"labels"))
for(c in names(df)[sapply(df,has.labels)]) set(df,j=c, value = haven::as_factor(df[[c]]))
</code>```

Body:
I have imported data from SPSS and I want to transform some variables to factors, without having to list them all. These variables can be distinguished from the others by having the attribute labels, so I want to use the condition length(get_labels(variable.name))>0 to mutate (or, if not possible, to select) them.

Using the following example (despite not being a tbl_df as would be if imported with haven::read_sav)

dt <- data.table(a = 1:4,
                 b = factor(c(1,2,1,1), levels=1:2, labels=c("Yes","No")),
                 d = c("xxx", "yyy", "zzz", "kkk"),
                 e = factor(c(1,1,3,2), levels=1:4, labels=c("A","B","C","D")))

I have tried

dt %>% mutate_at(vars(length(get_labels(.))>0), haven::as_factor)

dt %>% mutate_if((length(get_labels(.))>0), haven::as_factor)

but that didn't work.

How can I achieve the desired result, that is, mutate/select the columns band e?

Thanks!

Body:
You can do it like this:

library(haven)
df = read_sav("iris.sav")

is.havenlab <- function(x) "haven_labelled" %in% class(x)
df %>% mutate(across(where(is.havenlab),haven::as_factor))

Input (first three rows of df before mutating the is.havenlab columns)

# A tibble: 150 x 5
   Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
          <dbl>       <dbl>        <dbl>       <dbl>  <dbl+lbl>
 1          5.1         3.5          1.4         0.2 1 [setosa]
 2          4.9         3            1.4         0.2 1 [setosa]
 3          4.7         3.2          1.3         0.2 1 [setosa]

Output (first three rows after finding all the 'haven-labelled' columns and converting to factor

# A tibble: 150 x 5
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
          <dbl>       <dbl>        <dbl>       <dbl> <fct>
 1          5.1         3.5          1.4         0.2 setosa
 2          4.9         3            1.4         0.2 setosa
 3          4.7         3.2          1.3         0.2 setosa

data.table approach

This shows an alternative function, which I've called has.labels (either this or the above one, is.havenlab) work fine.

df = setDT(read_sav("iris.sav"))
has.labels <- function(x) !is.null(attr(x,"labels"))
for(c in names(df)[sapply(df,has.labels)]) set(df,j=c, value = haven::as_factor(df[[c]]))


问:
Generate dynamic Tab using argonDash (shiny framework) package
I tried to make dynamic Tab using argonDash package. However, I met some trouble with my code.
I guess argonDash seems to get different behavior than native shiny because argonDash uses Bootstrap 4 (instead of 3).

My code is composed of two key features:

The first widget uiOutput(outputId = "new_argonSidebarItem") works well.

The second widget uiOutput(outputId = "new_argonTabItem") doesn't work properly. I expect that the argonBadge() toggle with the second tab.

```<code>library(shiny)
library(argonDash)
library(argonR)

ui <- argonDashPage(
  sidebar = argonDashSidebar(
    id = "sidebar01",
    vertical = FALSE,
    size = "md",
    background = "white",
    argonSidebarMenu(
      style = "display:-webkit-inline-box;",
      argonSidebarItem(
        tabName = "Tab1",
        icon = NULL,
        "Dashboard"
      ),

      # New Tab
      uiOutput(outputId = "new_argonSidebarItem")

    )
  ),
  body = argonDashBody(
    argonTabItems(
      argonTabItem(
        tabName = "Tab1",
        actionButton("add_more", "Add a new btn")
      ),

      # Body
      uiOutput(outputId = "new_argonTabItem")

    )
  )
)

server <- function(input, output, session) {

  observeEvent(input$add_more, {

    tabId <- sample.int(n = 1000000, size = 1)
    tabName <- paste0("Tab_", tabId)

    insertUI(
      selector = "#tab-Tab1",
      where = "afterEnd",
      ui = argonSidebarItem(
        tabName = tabName,
        tabName
      )
    )

    output$new_argonTabItem <- renderUI({
      argonTabItem(
        tabName = tabName,
        argonBadge(
          text = tabName,
          src = "#",
          pill = FALSE,
          status = "success"
        )
      )
    })

  })

}

shinyApp(ui, server)
</code>```

Thank you for your time!

答:
To update your badge you need to track which tab is selected. This is done accordingly to this solution : https://github.com/RinteRface/argonDash/issues/7

But your badge can not be modified, so I replaced it with a button from {shinyWidgets}.

I hope this is what you ask for, I'm not really sure to understand what you want to happen.

```<code>library(shiny)
library(argonDash)
library(argonR)
library(shinyWidgets)

ui <- argonDashPage(
  sidebar = argonDashSidebar(
    id = "sidebar01",
    vertical = FALSE,
    size = "md",
    background = "white",
    argonSidebarMenu(
      style = "display:-webkit-inline-box;",
      argonSidebarItem(
        tabName = "Tab1",
        icon = NULL,
        "Dashboard"
      ),

      # New Tab
      uiOutput(outputId = "new_argonSidebarItem")

    )
  ),
  body = argonDashBody(
    argonTabItems(
      argonTabItem(
        tabName = "Tab1",
        actionButton("add_more", "Add a new btn")
      ),

      # Body
      uiOutput(outputId = "new_argonTabItem")

    ),
    tags$script( "$(document).on('click', function(event) {
              Shiny.onInputChange('activeTab', $('.active').data().value);});")
  )
)

server <- function(input, output, session) {

  x <- reactiveValues(tabs = NULL)

  observeEvent(input$add_more, {

    tabId <- sample.int(n = 1000000, size = 1)
    tabName <- paste0("Tab_", tabId)

    insertUI(
      selector = "#tab-Tab1",
      where = "afterEnd",
      ui = argonSidebarItem(
        tabName = tabName,
        tabName
      )
    )

    output$new_argonTabItem <- renderUI({
      argonTabItem(
        tabName = tabName,
        actionBttn(
          inputId = paste0(input$activeTab,"_b"),
          label = tabName,
          style = "float",
          color = "success"
        )#,
        # argonBadge(
        #   text = tabName,
        #   src = "#",
        #   pill = FALSE,
        #   status = "success"
        # )
      )
    })

  })

  observeEvent(input$activeTab, {
    updateActionButton(session,
                       paste0(input$activeTab,"_b"),
                       input$activeTab)
  })
}

shinyApp(ui, server)
</code>```

Body:
I tried to make dynamic Tab using argonDash package. However, I met some trouble with my code.
I guess argonDash seems to get different behavior than native shiny because argonDash uses Bootstrap 4 (instead of 3).

My code is composed of two key features:

The first widget uiOutput(outputId = "new_argonSidebarItem") works well.

The second widget uiOutput(outputId = "new_argonTabItem") doesn't work properly. I expect that the argonBadge() toggle with the second tab.

library(shiny)
library(argonDash)
library(argonR)

ui <- argonDashPage(
  sidebar = argonDashSidebar(
    id = "sidebar01",
    vertical = FALSE,
    size = "md",
    background = "white",
    argonSidebarMenu(
      style = "display:-webkit-inline-box;",
      argonSidebarItem(
        tabName = "Tab1",
        icon = NULL,
        "Dashboard"
      ),

      # New Tab
      uiOutput(outputId = "new_argonSidebarItem")

    )
  ),
  body = argonDashBody(
    argonTabItems(
      argonTabItem(
        tabName = "Tab1",
        actionButton("add_more", "Add a new btn")
      ),

      # Body
      uiOutput(outputId = "new_argonTabItem")

    )
  )
)

server <- function(input, output, session) {

  observeEvent(input$add_more, {

    tabId <- sample.int(n = 1000000, size = 1)
    tabName <- paste0("Tab_", tabId)

    insertUI(
      selector = "#tab-Tab1",
      where = "afterEnd",
      ui = argonSidebarItem(
        tabName = tabName,
        tabName
      )
    )

    output$new_argonTabItem <- renderUI({
      argonTabItem(
        tabName = tabName,
        argonBadge(
          text = tabName,
          src = "#",
          pill = FALSE,
          status = "success"
        )
      )
    })

  })

}

shinyApp(ui, server)

Thank you for your time!

Body:
To update your badge you need to track which tab is selected. This is done accordingly to this solution : https://github.com/RinteRface/argonDash/issues/7

But your badge can not be modified, so I replaced it with a button from {shinyWidgets}.

I hope this is what you ask for, I'm not really sure to understand what you want to happen.

library(shiny)
library(argonDash)
library(argonR)
library(shinyWidgets)

ui <- argonDashPage(
  sidebar = argonDashSidebar(
    id = "sidebar01",
    vertical = FALSE,
    size = "md",
    background = "white",
    argonSidebarMenu(
      style = "display:-webkit-inline-box;",
      argonSidebarItem(
        tabName = "Tab1",
        icon = NULL,
        "Dashboard"
      ),

      # New Tab
      uiOutput(outputId = "new_argonSidebarItem")

    )
  ),
  body = argonDashBody(
    argonTabItems(
      argonTabItem(
        tabName = "Tab1",
        actionButton("add_more", "Add a new btn")
      ),

      # Body
      uiOutput(outputId = "new_argonTabItem")

    ),
    tags$script( "$(document).on('click', function(event) {
              Shiny.onInputChange('activeTab', $('.active').data().value);});")
  )
)

server <- function(input, output, session) {

  x <- reactiveValues(tabs = NULL)

  observeEvent(input$add_more, {

    tabId <- sample.int(n = 1000000, size = 1)
    tabName <- paste0("Tab_", tabId)

    insertUI(
      selector = "#tab-Tab1",
      where = "afterEnd",
      ui = argonSidebarItem(
        tabName = tabName,
        tabName
      )
    )

    output$new_argonTabItem <- renderUI({
      argonTabItem(
        tabName = tabName,
        actionBttn(
          inputId = paste0(input$activeTab,"_b"),
          label = tabName,
          style = "float",
          color = "success"
        )#,
        # argonBadge(
        #   text = tabName,
        #   src = "#",
        #   pill = FALSE,
        #   status = "success"
        # )
      )
    })

  })

  observeEvent(input$activeTab, {
    updateActionButton(session,
                       paste0(input$activeTab,"_b"),
                       input$activeTab)
  })
}

shinyApp(ui, server)


问:
How to create an array of objects with all objects from multiple arrays?
Given de following arrays:

```<code>const classes = [
  {
    students: [
       Student1,
       Student2,
    ]
  },
  {
    students: [
       Student3,
       Student4,
    ]
  }
]
</code>```

What's the best way performance-wise to generate an array of objects with a similar structure to this:

```<code>const allStudents = [
  Student1,
  Student2,
  Student3,
  Student4
]

</code>```

答:
That's what I did, hope it helped:

const classes = [
  {
    students: [
    'Student1',
    'Student2',
    ]
  },
  {
    students: [
    'Student3',
    'Student4',
    ]
  }
  ];

  var newArray = [];
  for(var i = 0; i < classes.length; i++){
    var tempArray = Object.values(classes[i]);
    for(var j = 0; j < tempArray[0].length; j++){
      newArray.push(tempArray[0][j]);
    }
  }

  console.log(newArray);```

Body:
Given de following arrays:

const classes = [
  {
    students: [
       Student1,
       Student2,
    ]
  },
  {
    students: [
       Student3,
       Student4,
    ]
  }
]

What's the best way performance-wise to generate an array of objects with a similar structure to this:

const allStudents = [
  Student1,
  Student2,
  Student3,
  Student4
]


问:
laravel bulk sms notification sending
hello I'm new for laravel I'm trying to send SMS notification from api.

I'm using 3rd party service for sending sms thy have less documentation for php code integration. and API URL

When I tried in laravel form controller when form submit sms notification will triggers by this
but problem is my API User name and passwords displayed in browser URL and inspect network tab too is was problem I don't want to show my API Credentials to any one

```<code>return redirect()->away("http://api.bulksmsgateway.in/sendmessage.php?user=....&password=.......&mobile=........&message=hello&sender=.......&type=3&template_id=123");
</code>```

** php code integration service provider document**

```<code><?php
error_reporting (E_ALL ^ E_NOTICE);
$username="XXXXXXX";
$password ="XXXXXXX";
$number=$_POST['number'];
$sender="abc";
$message=$_POST['message'];
$template_id='12345';
if($_POST['submitted']=='true')
{
$url="http://api.bulksmsgateway.in/sendmessage.php?user=".urlencode($username)."&password=".urlencode($password)."&mobile=".urlencode($number)."&sender=".urlencode($sender)."&message=".urlencode($message)."&type=".urlencode('3')."&template_id=".urlencode($template_id);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
echo $curl_scraped_page = curl_exec($ch);
curl_close($ch);
}

?>
<html>
<head>
</head>
<body>
<form action="" method="post" name="sms_gate" >
<br />
Number : <br />
<input type="text" name="number" />
<br /><br />
Message:<br/>
<textarea name="message" ></textarea>
<input type="hidden" name="submitted" value="true" />
<br />
<input type="submit" name="submit" value="send" />
</form>
</body>
</html>
</code>```

** API URL code integration service provider document provided this**

```<code>URL : http://api.bulksmsgateway.in/sendmessage.php?user=....&password=.......&mobile=........&message=hello&sender=.......&type=3&template_id=123
</code>```

my controller

```<code>public function Store_Enrollment(Request $request)

    {

      $this->validate($request, [

  'student_name' => 'required|string|max:255',
  'student_phone_no' => 'required|string|max:10',

    ]);

   $input['student_name'] = ucfirst ($request['student_name']);
   $input['student_phone_no'] = $request->student_phone_no;
   $redirect = Student::create($input);

return redirect()->away("http://api.bulksmsgateway.in/sendmessage.php?user=XXX&password=XXX&mobile=$redirect->student_phone_no&message=Dear  $redirect->student_name,  G&sender=ABC&type=3&template_id=112");

}
</code>```

答:
APIs like this are intended to be called server-to-server, not in the browser.

You can use the Laravel HTTP client to make a call to this API from your server; this will not expose the API keys or other sensitive data.

Title: laravel bulk sms notification sending

Body:
hello I'm new for laravel I'm trying to send SMS notification from api.

I'm using 3rd party service for sending sms thy have less documentation for php code integration. and API URL

When I tried in laravel form controller when form submit sms notification will triggers by this
but problem is my API User name and passwords displayed in browser URL and inspect network tab too is was problem I don't want to show my API Credentials to any one

return redirect()->away("http://api.bulksmsgateway.in/sendmessage.php?user=....&password=.......&mobile=........&message=hello&sender=.......&type=3&template_id=123");

** php code integration service provider document**

<?php
error_reporting (E_ALL ^ E_NOTICE);
$username="XXXXXXX";
$password ="XXXXXXX";
$number=$_POST['number'];
$sender="abc";
$message=$_POST['message'];
$template_id='12345';
if($_POST['submitted']=='true')
{
$url="http://api.bulksmsgateway.in/sendmessage.php?user=".urlencode($username)."&password=".urlencode($password)."&mobile=".urlencode($number)."&sender=".urlencode($sender)."&message=".urlencode($message)."&type=".urlencode('3')."&template_id=".urlencode($template_id);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
echo $curl_scraped_page = curl_exec($ch);
curl_close($ch);
}

?>

<form action="" method="post" name="sms_gate" >

Number :

<input type="text" name="number" />

Message:

<textarea name="message" ></textarea>
<input type="hidden" name="submitted" value="true" />

<input type="submit" name="submit" value="send" />
</form>

** API URL code integration service provider document provided this**

URL : http://api.bulksmsgateway.in/sendmessage.php?user=....&password=.......&mobile=........&message=hello&sender=.......&type=3&template_id=123

my controller

public function Store_Enrollment(Request $request)

    {

      $this->validate($request, [

  'student_name' => 'required|string|max:255',
  'student_phone_no' => 'required|string|max:10',

    ]);

   $input['student_name'] = ucfirst ($request['student_name']);
   $input['student_phone_no'] = $request->student_phone_no;
   $redirect = Student::create($input);

return redirect()->away("http://api.bulksmsgateway.in/sendmessage.php?user=XXX&password=XXX&mobile=$redirect->student_phone_no&message=Dear  $redirect->student_name,  G&sender=ABC&type=3&template_id=112");

}


问:
Clickhouse. Get value from json
I use Clickhouse database. There is a table with string column (data). All rows contains data like:

```<code>'[{"a":23, "b":1}]'
'[{"a":7, "b":15}]'
</code>```

I wanna get all values of key "b".

```<code>1
15
</code>```

Next query:

```<code>Select JSONExtractInt('data', 0, 'b') from table
</code>```

return 0 all time. How i can get values of key "b"?

答:
SELECT tupleElement(JSONExtract(j, 'Array(Tuple(a Int64, b Int64))'), 'b')[1] AS res
FROM
(
    SELECT '[{"a":23, "b":1}]' AS j
    UNION ALL
    SELECT '[{"a":7, "b":15}]'
)

┌─res─┐
│   1 │
└─────┘
┌─res─┐
│  15 │
└─────┘
```

Title: Clickhouse. Get value from json

Body:
I use Clickhouse database. There is a table with string column (data). All rows contains data like:

'[{"a":23, "b":1}]'
'[{"a":7, "b":15}]'

I wanna get all values of key "b".

1
15

Next query:

Select JSONExtractInt('data', 0, 'b') from table

return 0 all time. How i can get values of key "b"?


问:
Dictionary from another dictionary
I have a dictionary with IDs and counts:

```<code>  items_count = {
    '1111:271': 111,
    '1111:190': 3,
    '1231:106': 13,
    '1211:104': 111,
    '1111:201': 9
    }
</code>```

Key is "category":"id". I want to separate category and put it in another dictionary like:

```<code>items_count2 = {
    '1111': {'271': 111, '190': 3, '201': 0},
    '1231': {'106': 13},
    '1211': {'104': 111}
    }
</code>```

but when I do this

```<code>items_count2 = {k.split(':')[0]: {k.split(':')[1]: v} for k, v in items_count}
</code>```

I get error
"ValueError: too many values to unpack (expected 2)"

please help to understand, what am I doing wrong?

答:
Setting up a dictionary with the needed keys is a clearer solution. But if you want to avoid looping, splitting and indexing twice you can create the needed keys on the fly with dict.setdefault.

items_count = {
    '1111:271': 111,
    '1111:190': 3,
    '1231:106': 13,
    '1211:104': 111,
    '1111:201': 9
}

items_count2 = {}
for k,v in items_count.items():
    s1, s2 = k.split(':')
    items_count2.setdefault(s1, {})[s2] = v
items_count2
```
<p>Output</p>
```{'1111': {'190': 3, '201': 9, '271': 111},
 '1211': {'104': 111},
 '1231': {'106': 13}}
```

Title: Dictionary from another dictionary

Body:
I have a dictionary with IDs and counts:

  items_count = {
    '1111:271': 111,
    '1111:190': 3,
    '1231:106': 13,
    '1211:104': 111,
    '1111:201': 9
    }

Key is "category":"id". I want to separate category and put it in another dictionary like:

items_count2 = {
    '1111': {'271': 111, '190': 3, '201': 0},
    '1231': {'106': 13},
    '1211': {'104': 111}
    }

but when I do this

items_count2 = {k.split(':')[0]: {k.split(':')[1]: v} for k, v in items_count}

I get error
"ValueError: too many values to unpack (expected 2)"

please help to understand, what am I doing wrong?

Body:
Setting up a dictionary with the needed keys is a clearer solution. But if you want to avoid looping, splitting and indexing twice you can create the needed keys on the fly with dict.setdefault.

items_count = {
    '1111:271': 111,
    '1111:190': 3,
    '1231:106': 13,
    '1211:104': 111,
    '1111:201': 9
}

items_count2 = {}
for k,v in items_count.items():
    s1, s2 = k.split(':')
    items_count2.setdefault(s1, {})[s2] = v
items_count2

Output

{'1111': {'190': 3, '201': 9, '271': 111},
 '1211': {'104': 111},
 '1231': {'106': 13}}


问:
Django batching/bulk update_or_create?
I have data in the database which needs updating periodically. The source of the data returns everything that's available at that point in time, so will include new data that is not already in the database.

As I loop through the source data I don't want to be making 1000s of individual writes if possible.

Is there anything such as update_or_create but works in batches?

One thought was using update_or_create in combination with manual transactions, but I'm not sure if that just queues up the individual writes or if it would combine it all into one SQL insert?

Or similarly could using @commit_on_success() on a function with update_or_create inside a the loop work?

I am not doing anything with the data other than translating it and saving it to a model. Nothing is dependent on that model existing during the loop.

答: There is django-bulk-update-or-create library for Django that can do that.</p>

Title: Django batching/bulk update_or_create?


问:
What's the correct way to use scanf_s in using string arrays?

char array1[10];
scanf_s("%9s", array1, (unsigned)_countof(array1);
```

What's mean of (unsigned)_countof(array1)?

and what's different from use scanf_s("%9s", array1, sizeof(array1);?

both worked, but I want to understand about it more surely

答:
What's the correct way to use scanf_s in using string arrays?

scanf_s() with "%9s" is not for string arrays.  It is for reading text and saving as a single string, which is a character array with a null character.

Its proper use is complicated by MSVC expects a different type in the count argument than C11.  In C11 and later, scanf_s() is an optional function of the standard library and lacks wide acceptance.

```<code>// MSVC - type unsigned expected, hence the cast.
scanf_s("%9s", array1, (unsigned)_countof(array1);

// C11 - type size_t expected
scanf_s("%9s", array1, sizeof array1 / sizeof array1[0]);
</code>```

Proper use of either obliges code to check the return value of scanf_s()

```<code>if (1 == scanf_s("%9s", ...)) Success();
else Fail();
</code>```

What's mean of (unsigned)_countof(array1)?

_countof() is an MSVC macro equivalent to (sizeof(array) / sizeof(array[0])).  When passed an array, it returns the count of elements in the array as type size_t.  Casting to unsigned gets the expected type as with MSVC scanf_s().  The value may truncate due to the cast - a rare issue with huge arrays.

what's different from use scanf_s("%9s", array1, sizeof(array1));?

The expected type of sizeof(array1) is size_t and not unsigned as expected in MSVC - leading to undefined behavior.  When size_t is as unsigned, that is OK, else a real problem.

The conceptual value is wrong.  It should be the array element count, not the byte size of the array.  Either OK here as sizeof(char)==1, yet wrong if code moved to say using wide characters.

both worked

Code is not portable.  It may have "worked" in OP's case, but lacks portability.

Consider alternatives to scanf_s(), scanf() like fgets().

Body:
char array1[10];
scanf_s("%9s", array1, (unsigned)_countof(array1);

What's mean of (unsigned)_countof(array1)?

and what's different from use scanf_s("%9s", array1, sizeof(array1);?

both worked, but I want to understand about it more surely

Body:
What's the correct way to use scanf_s in using string arrays?

scanf_s() with "%9s" is not for string arrays.  It is for reading text and saving as a single string, which is a character array with a null character.

Its proper use is complicated by MSVC expects a different type in the count argument than C11.  In C11 and later, scanf_s() is an optional function of the standard library and lacks wide acceptance.

// MSVC - type unsigned expected, hence the cast.
scanf_s("%9s", array1, (unsigned)_countof(array1);

// C11 - type size_t expected
scanf_s("%9s", array1, sizeof array1 / sizeof array1[0]);

Proper use of either obliges code to check the return value of scanf_s()

if (1 == scanf_s("%9s", ...)) Success();
else Fail();

What's mean of (unsigned)_countof(array1)?

_countof() is an MSVC macro equivalent to (sizeof(array) / sizeof(array[0])).  When passed an array, it returns the count of elements in the array as type size_t.  Casting to unsigned gets the expected type as with MSVC scanf_s().  The value may truncate due to the cast - a rare issue with huge arrays.

what's different from use scanf_s("%9s", array1, sizeof(array1));?

The expected type of sizeof(array1) is size_t and not unsigned as expected in MSVC - leading to undefined behavior.  When size_t is as unsigned, that is OK, else a real problem.

The conceptual value is wrong.  It should be the array element count, not the byte size of the array.  Either OK here as sizeof(char)==1, yet wrong if code moved to say using wide characters.

both worked

Code is not portable.  It may have "worked" in OP's case, but lacks portability.

Consider alternatives to scanf_s(), scanf() like fgets().


问:
How to output formated text but with added values - Python
I am new to Python and I can´t find any way to execute this code.

I am using JSON generator and need to print formated code and add some changes to it. I have variables that have some values and I need to insert them into my code. So the final code will have exact formating but with added values.

hp = 50;
cp = 100;
wp = 40;

{
  "721": {
    "<policy_id>": {
      "<asset_name>": {
        "name": "<display_name>",
        "image": "<ipfs_link>",
        "mediaType": "<mime_type>",
        "description": "<description>",
        "Visual": "<rarity>",
        "Health Points": "<hp (value of hp here)>",
        "Combat Power": "<cp (value of cp here)>",
        "Working Power": "<wp (value of wp here)>",
        "files": [
          {
            "name": "<display_name>",
            "mediaType": "<mime_type>",
            "src": "<ipfs_link>"
          }
        ]
      }```
</div>
</div>
</p>
<p>Final output (I want to generate 100 of this same code with exact formating but with different hp wp and cp values.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>{
  "721": {
    "<policy_id>": {
      "<asset_name>": {
        "name": "<display_name>",
        "image": "<ipfs_link>",
        "mediaType": "<mime_type>",
        "description": "<description>",
        "Visual": "<rarity>",
        "Health Points": "50",
        "Combat Power": "100",
        "Working Power": "40",
        "files": [
          {
            "name": "<display_name>",
            "mediaType": "<mime_type>",
            "src": "<ipfs_link>"
          }
        ]
      }</code>```

答:
You can use f-strings to painlessly wrap variables in strings, and json.dump/s() can produce nice JSONs if an indent argument is supplied:

```<code>import json
hp = 50
whatever = {"721":{"<policy id>":{"<asset name>":{"Health Points":f"{hp}"}}}}
print(json.dumps(whatever, indent=4))
</code>```

will display

```<code>{
    "721": {
        "<policy id>": {
            "<asset name>": {
                "Health Points": "50"
            }
        }
    }
}
</code>```

Body:
I am new to Python and I can´t find any way to execute this code.

I am using JSON generator and need to print formated code and add some changes to it. I have variables that have some values and I need to insert them into my code. So the final code will have exact formating but with added values.

hp = 50;
cp = 100;
wp = 40;

{
  "721": {
    "<policy_id>": {
      "<asset_name>": {
        "name": "<display_name>",
        "image": "<ipfs_link>",
        "mediaType": "<mime_type>",
        "description": "<description>",
        "Visual": "<rarity>",
        "Health Points": "<hp (value of hp here)>",
        "Combat Power": "<cp (value of cp here)>",
        "Working Power": "<wp (value of wp here)>",
        "files": [
          {
            "name": "<display_name>",
            "mediaType": "<mime_type>",
            "src": "<ipfs_link>"
          }
        ]
      }

Final output (I want to generate 100 of this same code with exact formating but with different hp wp and cp values.

{
  "721": {
    "<policy_id>": {
      "<asset_name>": {
        "name": "<display_name>",
        "image": "<ipfs_link>",
        "mediaType": "<mime_type>",
        "description": "<description>",
        "Visual": "<rarity>",
        "Health Points": "50",
        "Combat Power": "100",
        "Working Power": "40",
        "files": [
          {
            "name": "<display_name>",
            "mediaType": "<mime_type>",
            "src": "<ipfs_link>"
          }
        ]
      }

Body:
You can use f-strings to painlessly wrap variables in strings, and json.dump/s() can produce nice JSONs if an indent argument is supplied:

import json
hp = 50
whatever = {"721":{"<policy id>":{"<asset name>":{"Health Points":f"{hp}"}}}}
print(json.dumps(whatever, indent=4))

will display

{
    "721": {
        "<policy id>": {
            "<asset name>": {
                "Health Points": "50"
            }
        }
    }
}


问:
How do I show an uninstaller window with CPack NSIS during re-installation?
I have the following CMakeLists.txt (the only thing in the directory):

```<code>cmake_minimum_required(VERSION 3.0.0)

project(CPackUninstallerTest)

set(CPACK_GENERATOR NSIS)
set(CPACK_NSIS_ENABLE_UNINSTALL_BEFORE_INSTALL ON)
set(CPACK_NSIS_EXTRA_UNINSTALL_COMMANDS
"DetailPrint \\\"Sleeping...\\\"
Sleep 3000"
)

file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test.txt" "Some output\n")
install(FILES "${CMAKE_CURRENT_BINARY_DIR}/test.txt" TYPE DATA)

include(CPack)
</code>```

Running cmake and cpack works fine, and .../build/CPackUninstallerTest-0.1.1-win64.exe is generated.

Running the installer works as expected:

And running the uninstaller (Uninstall.exe in the install directory) also works, where the sleep takes three seconds:

However, this uninstall window does not show up if I try to install on top of an existing installation. After clicking Yes here:

That window goes away for three seconds (as it uninstalls) before the new installer runs.

This is a terrible user experience and results in them re-running the installer while waiting for the hidden uninstaller, causing confusing results.

How do I configure NSIS or CMake/CPack to show the uninstaller progress bar when using CPACK_NSIS_ENABLE_UNINSTALL_BEFORE_INSTALL and re-installing?

答:
Your issue could not be solved with NSIS interfaces of CMake.

I had a similar problem with CPACK_NSIS_ENABLE_UNINSTALL_BEFORE_INSTALL. The user could not install it again when uninstallation run manually.

The problem here is that manually running the uninstaller does not delete the install flag from windows registry keys.

My recommendation is that you can create your NSIS script by using NSIS template script of CMake. And you can add remove command easily to uninstaller section of new script.

And then you can give the new script as template to CMake.

Body:
I have the following CMakeLists.txt (the only thing in the directory):

cmake_minimum_required(VERSION 3.0.0)

project(CPackUninstallerTest)

set(CPACK_GENERATOR NSIS)
set(CPACK_NSIS_ENABLE_UNINSTALL_BEFORE_INSTALL ON)
set(CPACK_NSIS_EXTRA_UNINSTALL_COMMANDS
"DetailPrint \\\"Sleeping...\\\"
Sleep 3000"
)

file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test.txt" "Some output\n")
install(FILES "${CMAKE_CURRENT_BINARY_DIR}/test.txt" TYPE DATA)

include(CPack)

Running cmake and cpack works fine, and .../build/CPackUninstallerTest-0.1.1-win64.exe is generated.

Running the installer works as expected:

And running the uninstaller (Uninstall.exe in the install directory) also works, where the sleep takes three seconds:

However, this uninstall window does not show up if I try to install on top of an existing installation. After clicking Yes here:

That window goes away for three seconds (as it uninstalls) before the new installer runs.

This is a terrible user experience and results in them re-running the installer while waiting for the hidden uninstaller, causing confusing results.

How do I configure NSIS or CMake/CPack to show the uninstaller progress bar when using CPACK_NSIS_ENABLE_UNINSTALL_BEFORE_INSTALL and re-installing?


问:
How to make log10 ONLY first y-axis (not secondary y-axis) in ggplot in R
I would like to plot ONLY y-axis1 DATA (left axis, Var1, dotted line) as a log10 scale. The dotted line would therefore look higher on the y-axis and differences between 1 and 2 would be noticeable.

I have tried several things, but does not work ( I believe I am using them in the wrong order/place) such as:

+coord_trans(y='log10')--> empty plot

scale_y_continuous(trans = log10_trans(),... --> makes both Var1 and Var 2 log10

scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x),labels = trans_format("log10", math_format(10^.x)))--> makes both y axis log10 and removes y-axis2 (Var2)

```<code>data<- data.frame(
      Day=c(1,2,3,1,2,3,1,2,3),
      Name=rep(c(rep("a",3),rep("b",3),rep("c",3))),
      Var1=c(1090,484,64010,1090,484,64010,1090,484,64010),
      Var2= c(4,16,39,2,22,39,41,10,3))

ggplot(data)  +
  geom_bar(aes(fill=Name, y=Var2*1000, x=Day),stat="identity", colour="black", position= position_stack(reverse = TRUE))+
  geom_line(aes(x=Day, y=Var1),stat="identity",color="black", linetype="dotted", size=0.8)+
  geom_point(aes(Day, Var1), shape=8)+
  labs(title= "",
       x="",y=expression('Var1'))+
  scale_y_continuous(
    sec.axis=sec_axis(~./1000, name= expression(paste("Var2"))))+
  theme_classic()+
  scale_fill_grey(start = 1, end=0.1,name = "", labels = c("a", "b", "c"))
</code>```

答:
Here is a custom breaks function:

br <- function(limits) {
  10^(seq(ifelse(limits[1] <= 0,
                 0,
                 trunc(log10(limits[1]))),
          trunc(log10(limits[2])),
          by = 1))}
```
<pre class="lang-r prettyprint-override"><code>ggplot(data)  +
  geom_bar(aes(fill = Name, y = Var2 * 1000, x = Day),
           stat = "identity",
           colour = "black",
           position = position_stack(reverse = TRUE))+
  geom_line(aes(x=Day, y=Var1),
            stat = "identity",
            color = "black",
            linetype = "dotted",
            size = 0.8)+
  geom_point(aes(Day, Var1),
             shape = 8)+
  labs(title = "",
       x = "",
       y = expression('Var1'))+
  scale_y_continuous(
    breaks = br,
    sec.axis = sec_axis(~./1000, name= expression(paste("Var2"))))+
  theme_classic()+
  scale_fill_grey(start = 1,
                  end = 0.1,
                  name = "",
                  labels = c("a", "b", "c"))

</code>```

Results aren't so pretty but you can customize the breaks as you wish.

Body:
I would like to plot ONLY y-axis1 DATA (left axis, Var1, dotted line) as a log10 scale. The dotted line would therefore look higher on the y-axis and differences between 1 and 2 would be noticeable.

I have tried several things, but does not work ( I believe I am using them in the wrong order/place) such as:

+coord_trans(y='log10')--> empty plot

scale_y_continuous(trans = log10_trans(),... --> makes both Var1 and Var 2 log10

scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x),labels = trans_format("log10", math_format(10^.x)))--> makes both y axis log10 and removes y-axis2 (Var2)

data<- data.frame(
      Day=c(1,2,3,1,2,3,1,2,3),
      Name=rep(c(rep("a",3),rep("b",3),rep("c",3))),
      Var1=c(1090,484,64010,1090,484,64010,1090,484,64010),
      Var2= c(4,16,39,2,22,39,41,10,3))

ggplot(data)  +
  geom_bar(aes(fill=Name, y=Var2*1000, x=Day),stat="identity", colour="black", position= position_stack(reverse = TRUE))+
  geom_line(aes(x=Day, y=Var1),stat="identity",color="black", linetype="dotted", size=0.8)+
  geom_point(aes(Day, Var1), shape=8)+
  labs(title= "",
       x="",y=expression('Var1'))+
  scale_y_continuous(
    sec.axis=sec_axis(~./1000, name= expression(paste("Var2"))))+
  theme_classic()+
  scale_fill_grey(start = 1, end=0.1,name = "", labels = c("a", "b", "c"))

Body:
Here is a custom breaks function:

br <- function(limits) {
  10^(seq(ifelse(limits[1] <= 0,
                 0,
                 trunc(log10(limits[1]))),
          trunc(log10(limits[2])),
          by = 1))}

ggplot(data)  +
  geom_bar(aes(fill = Name, y = Var2 * 1000, x = Day),
           stat = "identity",
           colour = "black",
           position = position_stack(reverse = TRUE))+
  geom_line(aes(x=Day, y=Var1),
            stat = "identity",
            color = "black",
            linetype = "dotted",
            size = 0.8)+
  geom_point(aes(Day, Var1),
             shape = 8)+
  labs(title = "",
       x = "",
       y = expression('Var1'))+
  scale_y_continuous(
    breaks = br,
    sec.axis = sec_axis(~./1000, name= expression(paste("Var2"))))+
  theme_classic()+
  scale_fill_grey(start = 1,
                  end = 0.1,
                  name = "",
                  labels = c("a", "b", "c"))

Results aren't so pretty but you can customize the breaks as you wish.


问:
How to refresh result completely by different actionbuttons in shiny
My shiny app works well but there is a small problem that puzzled me.

There are three actionbuttons and all of them can create similar pictures and tables at the same time.

In my view, I hope each actionbutton can refresh the result generated by last button.
I modified my code but it doesn't work. And one or two empty area always appear.

So my question is what I can do to remove the empty areas. I hope each graph and each table could appear together without any space or distance just like the result that the first button generated.

The space like this:

Here is my code:

```<code>options(encoding = "UTF-8")
library(shiny)
library(shinythemes)
library(psych)              ## corr.test
library(DT)
library(pheatmap)
########

data<-structure(list(Name = c("A", "A", "A", "B", "B", "B", "C", "C",
                              "C", "D"), `0610005C13Rik` = c(0.42, 0.28, 0.16, 0.14, 0.23,
                                                             0.12, 0, 0.06, 0.09, 0.27), `0610006L08Rik` = c(0, 0, 0, 0, 0,
                                                                                0, 0, 0, 0, 0), `0610007P14Rik` = c(12.81, 11.44, 13.94, 14.26,
                                                                                14.95, 14.55, 6.61, 8.52, 7.68, 5.13), `0610009B22Rik` = c(7.53,
                                                                                6.55, 7.32, 7.12, 6.33, 7.12, 5.87, 3.57, 3.95, 3.49), `0610009E02Rik` = c(0.19,
                                                                                0.25, 0.23, 0.18, 0.28, 0.3, 0.26, 0.14, 0.11, 0.11), `0610009L18Rik` = c(1.32,
                                                                                1.61, 1.26, 0.78, 1.12, 0.95, 3.45, 1.36, 0.94, 1.31), `0610009O20Rik` = c(18.73,
                                                                                17.38, 18.56, 21.46, 22.64, 21.24, 20.85, 21.85, 17.9, 23.44),
                     `0610010B08Rik` = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), `0610010F05Rik` = c(5.14,
                                                                                4.49, 4.68, 4.63, 4.5, 4.15, 1.74, 2.3, 2.03, 2.28), `0610010K14Rik` = c(34.97,
                                                                                28.72, 32.6, 29.98, 29.93, 30.05, 38.07, 29.76, 28.63, 27.74
                                                                                )), row.names = c(NA, 10L), class = "data.frame")
data
######

ui <- fluidPage(
    mainPanel("666",
#      width = 9,
                  tabPanel("123",
                           hr(),
                           typeaheadInput(
                             "select",
                             "Select",
                             choices = NULL,
                             minLength = 1,
                             value = "0610005C13Rik"
                           ),
                           #####
                           actionButton(inputId = "plot_1", label = "123",width=80,class="btn btn-success"),
                           actionButton(inputId = "plot_2", label = "456",width=80,class="btn btn-light"),
                           actionButton(inputId = "plot_3", label = "789",width=80,class="btn btn-danger"),
                           hr(),
                           uiOutput("all"),
                           dataTableOutput('myTable1'),
                           dataTableOutput('myTable2'),
                           dataTableOutput('myTable3')
                           #####
                  )
      ))
server <- function(input, output, session) {

  updateTypeaheadInput(session, "select", choices = colnames(data[,-1]))
  observeEvent(list(input$plot_1,input$plot_2,input$plot_3), {
    updateTabsetPanel(session, "666",
                      selected = "123"
    )
  })

  #################
  global <- reactiveValues(out = NULL
  )

  ######
  output$all <- renderUI({
    global$out
  })

  observeEvent(input$plot_1,{
    global$out <- plotOutput("myPlot_1")
    myData_2(NULL)
    myData_3(NULL)
  })

  observeEvent(input$plot_2, {

    global$out <- plotOutput("myPlot_2")
    myData_1(NULL)
    myData_3(NULL)
  })

  observeEvent(input$plot_3, {
    global$outtt <- plotOutput("myPlot_3")
    myData_1(NULL)
    myData_2(NULL)
  })

  #########################################
  ##
  myPlot_1 = reactiveVal()
  myPlot_2 = reactiveVal()
  myPlot_3 = reactiveVal()
  #
  myData_1 = reactiveVal()
  myData_2 = reactiveVal()
  myData_3 = reactiveVal()

  ####################################  1
  observeEvent(input$plot_1, {
    validate(need(sum(unique(colnames(data[,-1])) %in% input$select)>0, "The gene is not found."))
    data_cor<-data[,-1]
    tm <- corr.test(data_cor[,input$select,drop=FALSE],
                    y = data_cor, use = "pairwise", "spearman", adjust="none",
                    alpha=0.05, ci=F, minlength=5)
    res <-setNames(as.data.frame(t(do.call(rbind, tm[c("r", "p")]))), c("Correlation", "P_value"))
    res<-res[-which(rownames(res)== input$select),]
    res<-data.frame(Gene=rownames(res),res)
    res<-res[order(res$Correlation,decreasing = T),]
    rownames(res)<-NULL
    res<-na.omit(res)
    res
    ##############
    data_correlation=t(data[, -1])
    data_subset=data_correlation[c(input$select, as.vector(head(res$Gene, 9))), ]
    myPlot_1(

      if(nrow(data_subset)>1){
        pheatmap(log2(data_subset+1), show_colnames = F,fontsize_row =13,
#                 labels_row = as.expression(lapply(rownames(data_subset), function(a) bquote(italic(.(a))))),
                 cluster_rows = F, cluster_cols = F,
                 fontsize = 11,
                 cellwidth=4
        )
      }
    )
    myData_1(res)
  })
  ######################################## 2
  observeEvent(input$plot_2, {
    validate(need(sum(unique(colnames(data[,-1])) %in% input$select)>0, "The gene is not found."))
    data_cor<-data[,-1]
    tm <- corr.test(data_cor[,input$select,drop=FALSE],
                    y = data_cor, use = "pairwise", "spearman", adjust="none",
                    alpha=0.05, ci=F, minlength=5)
    res <-setNames(as.data.frame(t(do.call(rbind, tm[c("r", "p")]))), c("Correlation", "P_value"))
    res<-res[-which(rownames(res)== input$select),]
    res<-data.frame(Gene=rownames(res),res)
    res<-res[order(res$Correlation,decreasing = T),]
    rownames(res)<-NULL
    res<-na.omit(res)
    res
    ##############
    data_correlation=t(data[, -1])
    data_subset=data_correlation[c(input$select, as.vector(head(res$Gene, 9))), ]
    myPlot_2(

      if(nrow(data_subset)>1){
        pheatmap(log2(data_subset+1), show_colnames = F,fontsize_row =13,
                 #                 labels_row = as.expression(lapply(rownames(data_subset), function(a) bquote(italic(.(a))))),
                 cluster_rows = F, cluster_cols = F,
                 fontsize = 11,
                 cellwidth=4
        )
      }
    )
    myData_2(res)
  })
  ########################################  3
  observeEvent(input$plot_3, {
    validate(need(sum(unique(colnames(data[,-1])) %in% input$select)>0, "The gene is not found."))
    data_cor<-data[,-1]
    tm <- corr.test(data_cor[,input$select,drop=FALSE],
                    y = data_cor, use = "pairwise", "spearman", adjust="none",
                    alpha=0.05, ci=F, minlength=5)
    res <-setNames(as.data.frame(t(do.call(rbind, tm[c("r", "p")]))), c("Correlation", "P_value"))
    res<-res[-which(rownames(res)== input$select),]
    res<-data.frame(Gene=rownames(res),res)
    res<-res[order(res$Correlation,decreasing = T),]
    rownames(res)<-NULL
    res<-na.omit(res)
    res
    ##############
    data_correlation=t(data[, -1])
    data_subset=data_correlation[c(input$select, as.vector(head(res$Gene, 9))), ]
    myPlot_3(

      if(nrow(data_subset)>1){
        pheatmap(log2(data_subset+1), show_colnames = F,fontsize_row =13,
                 #                 labels_row = as.expression(lapply(rownames(data_subset), function(a) bquote(italic(.(a))))),
                 cluster_rows = F, cluster_cols = F,
                 fontsize = 11,
                 cellwidth=4
        )
      }
    )
    myData_3(res)
  })
  ###################################  1
  output$myPlot_1 = renderPlot({
    req(myPlot_1())
    myPlot_1()
  })

  output$myTable1 = renderDataTable({
    req(myData_1())

    myData_1()

  })
  #################################  2
  output$myPlot_2 = renderPlot({

    req(myPlot_2())
    myPlot_2()
  })

  output$myTable2 = renderDataTable({

    req(myData_2())

    myData_2()

  })
  #################################  3
  output$myPlot_3 = renderPlot({

    req(myPlot_3())
    myPlot_3()
  })

  output$myTable3 = renderDataTable({

    req(myData_3())

    myData_3()

  })

}

###################

# Create Shiny app ----
shinyApp(ui = ui, server = server)
</code>```

who can help me

答:
Similar to plot, you could to output the tables in a renderUI.  Try this

```<code>ui <- fluidPage(
  mainPanel("666",
            #      width = 9,
            tabPanel("123",
                     hr(),
                     selectInput(
                       "select",
                       "Select",
                       choices = NULL#,
                       # minLength = 1,
                       # value = "0610005C13Rik"
                     ),
                     #####
                     actionButton(inputId = "plot_1", label = "123",width=80,class="btn btn-success"),
                     actionButton(inputId = "plot_2", label = "456",width=80,class="btn btn-light"),
                     actionButton(inputId = "plot_3", label = "789",width=80,class="btn btn-danger"),
                     hr(),
                     uiOutput("all"),
                     uiOutput("mydata")
                     # dataTableOutput('myTable1'),
                     # dataTableOutput('myTable2'),
                     # dataTableOutput('myTable3')
                     #####
            )
  ))
server <- function(input, output, session) {

  updateSelectInput(session, "select", choices = colnames(data[,-1]))
  observeEvent(list(input$plot_1,input$plot_2,input$plot_3), {
    updateTabsetPanel(session, "666",
                      selected = "123"
    )
  })

  #################
  global <- reactiveValues(out = NULL, data = NULL
  )

  ######
  output$all <- renderUI({
    global$out
  })
  output$mydata <- renderUI({
    global$data
  })

  observeEvent(input$plot_1,{
    global$out <- plotOutput("myPlot_1")
    global$data <- DTOutput("myTable1")
    # myData_2(NULL)
    # myData_3(NULL)
  })

  observeEvent(input$plot_2, {

    global$out <- plotOutput("myPlot_2")
    global$data <- DTOutput("myTable2")
    # myData_1(NULL)
    # myData_3(NULL)
  })

  observeEvent(input$plot_3, {
    global$out <- plotOutput("myPlot_3")
    global$data <- DTOutput("myTable3")
    # myData_1(NULL)
    # myData_2(NULL)
  })

</code>```

Body:
My shiny app works well but there is a small problem that puzzled me.

There are three actionbuttons and all of them can create similar pictures and tables at the same time.

In my view, I hope each actionbutton can refresh the result generated by last button.
I modified my code but it doesn't work. And one or two empty area always appear.

So my question is what I can do to remove the empty areas. I hope each graph and each table could appear together without any space or distance just like the result that the first button generated.

The space like this:

Here is my code:

options(encoding = "UTF-8")
library(shiny)
library(shinythemes)
library(psych)              ## corr.test
library(DT)
library(pheatmap)
########

data<-structure(list(Name = c("A", "A", "A", "B", "B", "B", "C", "C",
                              "C", "D"), `0610005C13Rik` = c(0.42, 0.28, 0.16, 0.14, 0.23,
                                                             0.12, 0, 0.06, 0.09, 0.27), `0610006L08Rik` = c(0, 0, 0, 0, 0,
                                                                                0, 0, 0, 0, 0), `0610007P14Rik` = c(12.81, 11.44, 13.94, 14.26,
                                                                                14.95, 14.55, 6.61, 8.52, 7.68, 5.13), `0610009B22Rik` = c(7.53,
                                                                                6.55, 7.32, 7.12, 6.33, 7.12, 5.87, 3.57, 3.95, 3.49), `0610009E02Rik` = c(0.19,
                                                                                0.25, 0.23, 0.18, 0.28, 0.3, 0.26, 0.14, 0.11, 0.11), `0610009L18Rik` = c(1.32,
                                                                                1.61, 1.26, 0.78, 1.12, 0.95, 3.45, 1.36, 0.94, 1.31), `0610009O20Rik` = c(18.73,
                                                                                17.38, 18.56, 21.46, 22.64, 21.24, 20.85, 21.85, 17.9, 23.44),
                     `0610010B08Rik` = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), `0610010F05Rik` = c(5.14,
                                                                                4.49, 4.68, 4.63, 4.5, 4.15, 1.74, 2.3, 2.03, 2.28), `0610010K14Rik` = c(34.97,
                                                                                28.72, 32.6, 29.98, 29.93, 30.05, 38.07, 29.76, 28.63, 27.74
                                                                                )), row.names = c(NA, 10L), class = "data.frame")
data
######

ui <- fluidPage(
    mainPanel("666",
#      width = 9,
                  tabPanel("123",
                           hr(),
                           typeaheadInput(
                             "select",
                             "Select",
                             choices = NULL,
                             minLength = 1,
                             value = "0610005C13Rik"
                           ),
                           #####
                           actionButton(inputId = "plot_1", label = "123",width=80,class="btn btn-success"),
                           actionButton(inputId = "plot_2", label = "456",width=80,class="btn btn-light"),
                           actionButton(inputId = "plot_3", label = "789",width=80,class="btn btn-danger"),
                           hr(),
                           uiOutput("all"),
                           dataTableOutput('myTable1'),
                           dataTableOutput('myTable2'),
                           dataTableOutput('myTable3')
                           #####
                  )
      ))
server <- function(input, output, session) {

  updateTypeaheadInput(session, "select", choices = colnames(data[,-1]))
  observeEvent(list(input$plot_1,input$plot_2,input$plot_3), {
    updateTabsetPanel(session, "666",
                      selected = "123"
    )
  })

  #################
  global <- reactiveValues(out = NULL
  )

  ######
  output$all <- renderUI({
    global$out
  })

  observeEvent(input$plot_1,{
    global$out <- plotOutput("myPlot_1")
    myData_2(NULL)
    myData_3(NULL)
  })

  observeEvent(input$plot_2, {

    global$out <- plotOutput("myPlot_2")
    myData_1(NULL)
    myData_3(NULL)
  })

  observeEvent(input$plot_3, {
    global$outtt <- plotOutput("myPlot_3")
    myData_1(NULL)
    myData_2(NULL)
  })

  #########################################
  ##
  myPlot_1 = reactiveVal()
  myPlot_2 = reactiveVal()
  myPlot_3 = reactiveVal()
  #
  myData_1 = reactiveVal()
  myData_2 = reactiveVal()
  myData_3 = reactiveVal()

  ####################################  1
  observeEvent(input$plot_1, {
    validate(need(sum(unique(colnames(data[,-1])) %in% input$select)>0, "The gene is not found."))
    data_cor<-data[,-1]
    tm <- corr.test(data_cor[,input$select,drop=FALSE],
                    y = data_cor, use = "pairwise", "spearman", adjust="none",
                    alpha=0.05, ci=F, minlength=5)
    res <-setNames(as.data.frame(t(do.call(rbind, tm[c("r", "p")]))), c("Correlation", "P_value"))
    res<-res[-which(rownames(res)== input$select),]
    res<-data.frame(Gene=rownames(res),res)
    res<-res[order(res$Correlation,decreasing = T),]
    rownames(res)<-NULL
    res<-na.omit(res)
    res
    ##############
    data_correlation=t(data[, -1])
    data_subset=data_correlation[c(input$select, as.vector(head(res$Gene, 9))), ]
    myPlot_1(

      if(nrow(data_subset)>1){
        pheatmap(log2(data_subset+1), show_colnames = F,fontsize_row =13,
#                 labels_row = as.expression(lapply(rownames(data_subset), function(a) bquote(italic(.(a))))),
                 cluster_rows = F, cluster_cols = F,
                 fontsize = 11,
                 cellwidth=4
        )
      }
    )
    myData_1(res)
  })
  ######################################## 2
  observeEvent(input$plot_2, {
    validate(need(sum(unique(colnames(data[,-1])) %in% input$select)>0, "The gene is not found."))
    data_cor<-data[,-1]
    tm <- corr.test(data_cor[,input$select,drop=FALSE],
                    y = data_cor, use = "pairwise", "spearman", adjust="none",
                    alpha=0.05, ci=F, minlength=5)
    res <-setNames(as.data.frame(t(do.call(rbind, tm[c("r", "p")]))), c("Correlation", "P_value"))
    res<-res[-which(rownames(res)== input$select),]
    res<-data.frame(Gene=rownames(res),res)
    res<-res[order(res$Correlation,decreasing = T),]
    rownames(res)<-NULL
    res<-na.omit(res)
    res
    ##############
    data_correlation=t(data[, -1])
    data_subset=data_correlation[c(input$select, as.vector(head(res$Gene, 9))), ]
    myPlot_2(

      if(nrow(data_subset)>1){
        pheatmap(log2(data_subset+1), show_colnames = F,fontsize_row =13,
                 #                 labels_row = as.expression(lapply(rownames(data_subset), function(a) bquote(italic(.(a))))),
                 cluster_rows = F, cluster_cols = F,
                 fontsize = 11,
                 cellwidth=4
        )
      }
    )
    myData_2(res)
  })
  ########################################  3
  observeEvent(input$plot_3, {
    validate(need(sum(unique(colnames(data[,-1])) %in% input$select)>0, "The gene is not found."))
    data_cor<-data[,-1]
    tm <- corr.test(data_cor[,input$select,drop=FALSE],
                    y = data_cor, use = "pairwise", "spearman", adjust="none",
                    alpha=0.05, ci=F, minlength=5)
    res <-setNames(as.data.frame(t(do.call(rbind, tm[c("r", "p")]))), c("Correlation", "P_value"))
    res<-res[-which(rownames(res)== input$select),]
    res<-data.frame(Gene=rownames(res),res)
    res<-res[order(res$Correlation,decreasing = T),]
    rownames(res)<-NULL
    res<-na.omit(res)
    res
    ##############
    data_correlation=t(data[, -1])
    data_subset=data_correlation[c(input$select, as.vector(head(res$Gene, 9))), ]
    myPlot_3(

      if(nrow(data_subset)>1){
        pheatmap(log2(data_subset+1), show_colnames = F,fontsize_row =13,
                 #                 labels_row = as.expression(lapply(rownames(data_subset), function(a) bquote(italic(.(a))))),
                 cluster_rows = F, cluster_cols = F,
                 fontsize = 11,
                 cellwidth=4
        )
      }
    )
    myData_3(res)
  })
  ###################################  1
  output$myPlot_1 = renderPlot({
    req(myPlot_1())
    myPlot_1()
  })

  output$myTable1 = renderDataTable({
    req(myData_1())

    myData_1()

  })
  #################################  2
  output$myPlot_2 = renderPlot({

    req(myPlot_2())
    myPlot_2()
  })

  output$myTable2 = renderDataTable({

    req(myData_2())

    myData_2()

  })
  #################################  3
  output$myPlot_3 = renderPlot({

    req(myPlot_3())
    myPlot_3()
  })

  output$myTable3 = renderDataTable({

    req(myData_3())

    myData_3()

  })

}

###################

# Create Shiny app ----
shinyApp(ui = ui, server = server)

who can help me

Body:
Similar to plot, you could to output the tables in a renderUI.  Try this

ui <- fluidPage(
  mainPanel("666",
            #      width = 9,
            tabPanel("123",
                     hr(),
                     selectInput(
                       "select",
                       "Select",
                       choices = NULL#,
                       # minLength = 1,
                       # value = "0610005C13Rik"
                     ),
                     #####
                     actionButton(inputId = "plot_1", label = "123",width=80,class="btn btn-success"),
                     actionButton(inputId = "plot_2", label = "456",width=80,class="btn btn-light"),
                     actionButton(inputId = "plot_3", label = "789",width=80,class="btn btn-danger"),
                     hr(),
                     uiOutput("all"),
                     uiOutput("mydata")
                     # dataTableOutput('myTable1'),
                     # dataTableOutput('myTable2'),
                     # dataTableOutput('myTable3')
                     #####
            )
  ))
server <- function(input, output, session) {

  updateSelectInput(session, "select", choices = colnames(data[,-1]))
  observeEvent(list(input$plot_1,input$plot_2,input$plot_3), {
    updateTabsetPanel(session, "666",
                      selected = "123"
    )
  })

  #################
  global <- reactiveValues(out = NULL, data = NULL
  )

  ######
  output$all <- renderUI({
    global$out
  })
  output$mydata <- renderUI({
    global$data
  })

  observeEvent(input$plot_1,{
    global$out <- plotOutput("myPlot_1")
    global$data <- DTOutput("myTable1")
    # myData_2(NULL)
    # myData_3(NULL)
  })

  observeEvent(input$plot_2, {

    global$out <- plotOutput("myPlot_2")
    global$data <- DTOutput("myTable2")
    # myData_1(NULL)
    # myData_3(NULL)
  })

  observeEvent(input$plot_3, {
    global$out <- plotOutput("myPlot_3")
    global$data <- DTOutput("myTable3")
    # myData_1(NULL)
    # myData_2(NULL)
  })