问:
'make_interp_spline' line dropping between two points
I am plotting some points and to make the plot smoother I'm using 'make_interp_spline'. The problem is that I get a falling line between the first two points. The other points are ok, and they have the same distance. Is there something I can do about it?

Ps: I just have the data from 10 and 30.

My code:

```<code>import matplotlib
import pylab as pl
from pylab import *
import numpy as np
from scipy.interpolate import make_interp_spline

x1, y1 = np.loadtxt('Grafico_I_D_Fe.txt', dtype=float, delimiter=',', unpack=True)

B_spline_coeff1 = make_interp_spline(x1, y1)
X1_Final = np.linspace(x.min(), x.max(), 500)
Y1_Final = B_spline_coeff1(X1_Final)

pl.plot(X1_Final, Y1_Final, color='r', label=r'Iron ($2 \times 10^7$)')
pl.scatter(x1, y1, marker='*', color='r')
</code>```

Data:

```<code>10, 3.187170532786709e-15
30, 1.031832270812154e-13
50, 3.444779276423242e-13
70, 6.316369610195546e-14
</code>```

Plot:

答:
Interpolation functions often have the unintuitive property of wiggling a lot. In your case, the interpolated curve goes below zero, although the data points don't.

Many other interpolation or approximation functions exist, each having their own benefits and drawbacks for specific situations. PchipInterpolator is one such function, that tries to stay inside the range of the data points (but has a less nice second derivative).

The code below uses PchipInterpolator, but also takes the log of the input y-values, and reverses that operation via exp on the result. Without taking the log, the wobbly second derivative is more visible.

from matplotlib import pyplot as plt
import numpy as np
from scipy.interpolate import PchipInterpolator

x1 = [10, 30, 50, 70]
y1 = [3.187170532786709e-15, 1.031832270812154e-13, 3.444779276423242e-13, 6.316369610195546e-14]

B_spline_coeff1 = PchipInterpolator(x1, np.log(y1))
X1_Final = np.linspace(9, 71, 500)
Y1_Final = np.exp(B_spline_coeff1(X1_Final))

plt.plot(X1_Final, Y1_Final, color='r', label=r'Iron ($2 \times 10^7$)')
plt.scatter(x1, y1, marker='*', color='r')
plt.yscale('log')
plt.show()
```
<p><img src="https://i.stack.imgur.com/sFTkp.png" alt="PchipInterpolator" /></p>
<p>PS: It seems that for these specific data points, the original <code>make_interp_spline</code> works even better than <code>PchipInterpolator</code> when using the log conversion.  Often this won't be the case, and you might need to consider other interpolation or approximation functions.</p>
<pre class="lang-py prettyprint-override"><code>B_spline_coeff1 = make_interp_spline(x1, np.log(y1))
X1_Final = np.linspace(9, 71, 500)
Y1_Final = np.exp(B_spline_coeff1(X1_Final))

plt.plot(X1_Final, Y1_Final, color='r', label=r'Iron ($2 \times 10^7$)')
plt.scatter(x1, y1, marker='*', color='r')
plt.yscale('log')
plt.show()
</code>```

Body:
I am plotting some points and to make the plot smoother I'm using 'make_interp_spline'. The problem is that I get a falling line between the first two points. The other points are ok, and they have the same distance. Is there something I can do about it?

Ps: I just have the data from 10 and 30.

My code:

import matplotlib
import pylab as pl
from pylab import *
import numpy as np
from scipy.interpolate import make_interp_spline

x1, y1 = np.loadtxt('Grafico_I_D_Fe.txt', dtype=float, delimiter=',', unpack=True)

B_spline_coeff1 = make_interp_spline(x1, y1)
X1_Final = np.linspace(x.min(), x.max(), 500)
Y1_Final = B_spline_coeff1(X1_Final)

pl.plot(X1_Final, Y1_Final, color='r', label=r'Iron ($2 \times 10^7$)')
pl.scatter(x1, y1, marker='*', color='r')

Data:

10, 3.187170532786709e-15
30, 1.031832270812154e-13
50, 3.444779276423242e-13
70, 6.316369610195546e-14

Plot:

Body:
Interpolation functions often have the unintuitive property of wiggling a lot. In your case, the interpolated curve goes below zero, although the data points don't.

Many other interpolation or approximation functions exist, each having their own benefits and drawbacks for specific situations. PchipInterpolator is one such function, that tries to stay inside the range of the data points (but has a less nice second derivative).

The code below uses PchipInterpolator, but also takes the log of the input y-values, and reverses that operation via exp on the result. Without taking the log, the wobbly second derivative is more visible.

from matplotlib import pyplot as plt
import numpy as np
from scipy.interpolate import PchipInterpolator

x1 = [10, 30, 50, 70]
y1 = [3.187170532786709e-15, 1.031832270812154e-13, 3.444779276423242e-13, 6.316369610195546e-14]

B_spline_coeff1 = PchipInterpolator(x1, np.log(y1))
X1_Final = np.linspace(9, 71, 500)
Y1_Final = np.exp(B_spline_coeff1(X1_Final))

plt.plot(X1_Final, Y1_Final, color='r', label=r'Iron ($2 \times 10^7$)')
plt.scatter(x1, y1, marker='*', color='r')
plt.yscale('log')
plt.show()

PS: It seems that for these specific data points, the original make_interp_spline works even better than PchipInterpolator when using the log conversion.  Often this won't be the case, and you might need to consider other interpolation or approximation functions.

B_spline_coeff1 = make_interp_spline(x1, np.log(y1))
X1_Final = np.linspace(9, 71, 500)
Y1_Final = np.exp(B_spline_coeff1(X1_Final))

plt.plot(X1_Final, Y1_Final, color='r', label=r'Iron ($2 \times 10^7$)')
plt.scatter(x1, y1, marker='*', color='r')
plt.yscale('log')
plt.show()


来源: stackexchange

问:
Selecting minimum value between columns python
I have a DataFrame that looks like the below. "Name" represents a student name and values below each of the Test variables represent the test grade.

```<code>Name Test1 Test2 Test3
Ana  87    93    82
Cole 62    73    84
Sia  64    58    60
Max  93    95    99
Leah 93    90    85
Cam  76    80    83
</code>```

The desired result is the DataFrame below. Where "MinTestGrade" represents that lowest grade each student earned between the 3. "TestNumber" is the Test they got the lowest grade on.

```<code>Name TestNumber MinTestGrade
Ana  3          82
Cole 1          62
Sia  2          58
Max  1          93
Leah 3          85
Cam  1          76
</code>```

How can I do this using python?

答:
```<code>df.set_index("Name").agg(["idxmin", "min"], axis=1).reset_index()
#    Name idxmin  min
# 0   Ana  Test3   82
# 1  Cole  Test1   62
# 2   Sia  Test2   58
# 3   Max  Test1   93
# 4  Leah  Test3   85
# 5   Cam  Test1   76
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a DataFrame that looks like the below. "Name" represents a student name and values below each of the Test variables represent the test grade.

Name Test1 Test2 Test3
Ana  87    93    82
Cole 62    73    84
Sia  64    58    60
Max  93    95    99
Leah 93    90    85
Cam  76    80    83

The desired result is the DataFrame below. Where "MinTestGrade" represents that lowest grade each student earned between the 3. "TestNumber" is the Test they got the lowest grade on.

Name TestNumber MinTestGrade
Ana  3          82
Cole 1          62
Sia  2          58
Max  1          93
Leah 3          85
Cam  1          76

How can I do this using python?


问:
React Parent To Child Component Props Update Issue
Let say i have two components one parent and another child
now i have a prop in child component called active which basically assign {active} class to child if its true now i wanted to change this prop from its parent component while rendering. take a look at some codes below

main code

```<code>import React from 'react';
import { List , Item } from "../Buttons";

export function Sample2() {
    return (
        <List>
            <Item>items</Item>
            <Item>items</Item>
            <Item>items</Item>
        </List>
    )
}
</code>```

component codes

commented line is what i am trying to achieve but its not allowed

```<code>export function List({ children }){
    const [index,setIndex] = useState(0)

    function getOptions(){
        return children.map((each,i)=>{
            //each.props.active = index == i
            return each
        })
    }

    return (
        <div className="list">
            {getOptions()}
        </div>
    )
}

export function Item({ active , children }){
    const classes ="item p-4 border-b" + (active?` active`:"")
    return (
        <div className={classes}>{children}</div>
    )
}
</code>```

now i wanted to know what is the way to achive this or i am not following react flow ? i am old in javascript but very much new to react so please explain what would be the best way to achive this

here's a screenshot of my codes

答:
A React component should never modify it's own props directly. If you think about a component as a function, modifying a parameter being passed to the function by the caller means you cannot run the same function twice and guarantee it will output the same result. This is necessary for React's rendering cycle to behave correctly. Therefor you need to set the props via element attributes like <MyComponent message={foo} /> where foo is a variable declared within the parent. An easy way to accomplish what you want is to provide a prop to the each child in the list:

```<code>export function List({ children }){
    const [index,setIndex] = useState(0)

    return (
        <div className="list">
            {children.map((child, i)=> (
                <Item isActive={index === i}>
                  {child}
                </Item>
               )
            )}
        </div>
    )
}
</code>```

Body:
Let say i have two components one parent and another child
now i have a prop in child component called active which basically assign {active} class to child if its true now i wanted to change this prop from its parent component while rendering. take a look at some codes below

main code

import React from 'react';
import { List , Item } from "../Buttons";

export function Sample2() {
    return (
        <List>
            <Item>items</Item>
            <Item>items</Item>
            <Item>items</Item>
        </List>
    )
}

component codes

commented line is what i am trying to achieve but its not allowed

export function List({ children }){
    const [index,setIndex] = useState(0)

    function getOptions(){
        return children.map((each,i)=>{
            //each.props.active = index == i
            return each
        })
    }

    return (

            {getOptions()}

    )
}

export function Item({ active , children }){
    const classes ="item p-4 border-b" + (active?` active`:"")
    return (

{children}

    )
}

now i wanted to know what is the way to achive this or i am not following react flow ? i am old in javascript but very much new to react so please explain what would be the best way to achive this

here's a screenshot of my codes

Body:
A React component should never modify it's own props directly. If you think about a component as a function, modifying a parameter being passed to the function by the caller means you cannot run the same function twice and guarantee it will output the same result. This is necessary for React's rendering cycle to behave correctly. Therefor you need to set the props via element attributes like <MyComponent message={foo} /> where foo is a variable declared within the parent. An easy way to accomplish what you want is to provide a prop to the each child in the list:

export function List({ children }){
    const [index,setIndex] = useState(0)

    return (
        <div className="list">
            {children.map((child, i)=> (
                <Item isActive={index === i}>
                  {child}
                </Item>
               )
            )}
        </div>
    )
}


问:
Can't work on my project after updating to Visual Studio 2022
I recently updated from Visual Studio 2019 to Visual Studio 2022. Thing is, I can't load previously created projects. IDE pops up a message asking for me to either install .NET Framework 4.7.2 compatibility pack or update the project to .NET Framework 4.8

I've already installed .NET Framework 4.7.2 (as shown below), but it doesn't seem to detect it. The dialog just keeps popping even after rebooting.

Updating the whole thing to 4.8 is out of question since it is a group project where Visual 2019 is still being used.

答:
Make sure you install the optional workload ".NET Framework 4.7.2 Targeting pack" as well as the SDK in case in the Visual Studio 2022 installer:

Similarly, you could install the 4.8 targeting pack into Visual Studios 2019 on your colleagues machines


问:
Can the amount be in USDT on Binanace Api Future Trade?
```<code>import ccxt
import pprint

with open("D:/api.txt") as f:
    lines = f.readlines()
    api_key = lines[0].strip()
    secret  = lines[1].strip()

binance = ccxt.binance({
    'apiKey' : api_key,
    'secret' :  secret,
    'enableRateLimit': True,
    'options': {
        'defaultType': 'future'
    }
    })
markets = binance.fetch_tickers()
print(markets.keys())

order = binance.create_limit_buy_order(
    symbol = 'ENSUSDT',
    amount = 1,
    price = 19.5,
    )

pprint.pprint(order)
</code>```

In this way, I would like to order 10$, but it is inconvenient because the amount is based on the price of one coin. Is there a way to do something like amount=10$ instead of amount = 1 ?

答:
The closest you could do would be to multiply the contractSize by the price and the amount you want to spend

```<code>usdt_amount = 10
market['contractSize'] * price * usdt_amount
</code>```

```<code>with open("D:/api.txt") as f:
    lines = f.readlines()
    api_key = lines[0].strip()
    secret  = lines[1].strip()

binance = ccxt.binance({
    'apiKey' : api_key,
    'secret' :  secret,
    'enableRateLimit': True,
    'options': {
        'defaultType': 'future'
    }
})
tickers = binance.fetch_tickers()

price = 19.5
symbol = 'ENS/USDT'
market = binance.market(symbol)
usdt_amount = 10

order = binance.create_limit_buy_order(
    symbol = symbol,
    amount = market['contractSize'] * price * usdt_amount,
    price = price,
)
</code>```

Body:
import ccxt
import pprint

with open("D:/api.txt") as f:
    lines = f.readlines()
    api_key = lines[0].strip()
    secret  = lines[1].strip()

binance = ccxt.binance({
    'apiKey' : api_key,
    'secret' :  secret,
    'enableRateLimit': True,
    'options': {
        'defaultType': 'future'
    }
    })
markets = binance.fetch_tickers()
print(markets.keys())

order = binance.create_limit_buy_order(
    symbol = 'ENSUSDT',
    amount = 1,
    price = 19.5,
    )

pprint.pprint(order)

In this way, I would like to order 10$, but it is inconvenient because the amount is based on the price of one coin. Is there a way to do something like amount=10$ instead of amount = 1 ?

Body:
The closest you could do would be to multiply the contractSize by the price and the amount you want to spend

usdt_amount = 10
market['contractSize'] * price * usdt_amount

with open("D:/api.txt") as f:
    lines = f.readlines()
    api_key = lines[0].strip()
    secret  = lines[1].strip()

binance = ccxt.binance({
    'apiKey' : api_key,
    'secret' :  secret,
    'enableRateLimit': True,
    'options': {
        'defaultType': 'future'
    }
})
tickers = binance.fetch_tickers()

price = 19.5
symbol = 'ENS/USDT'
market = binance.market(symbol)
usdt_amount = 10

order = binance.create_limit_buy_order(
    symbol = symbol,
    amount = market['contractSize'] * price * usdt_amount,
    price = price,
)


问:
Is it possible to dynamically change resources from XML-file?
I want to easily be able to change the UI apperance (colors & logo) of an app and thought to ask if someone has any suggestions on how best to do it.

What I want is simply to replace an XML-file in the project before compiling it and having the resources (i.e. the color values in colors.xml) set to the values of the XML.
The only problem seems to be that there is no way to change resources at runtime(?)

Is there any way of changing the resources automatically at authortime?

The whole point of simply replacing the XML file for different UI apperances is to save time and minimize the amount of editing different parts of the code.

答:
If I understand your question correctly then I think all you want is Theming for your application, I do not know whether you can change Resources in runtime or not, but you can definitely have separate themes for each of your UI component, which you can apply dynamically.

A good guide on Theming can be found here:

http://brainflush.wordpress.com/2009/03/15/understanding-android-themes-and-styles/

Try the theming and see if it works for you or not.

Thanks

ContentLicense: CC BY-SA 3.0


问:
Uncaught TypeError: Cannot assign to read only property 'amount' of object '#<Object>'
I'm fetching data from an API and then I save an array inside a state. While I'm trying to modify the specific field in object inside an array using input, I'm getting the following error: 'Uncaught TypeError: Cannot assign to read only property 'amount' of object '#''.

States (I'm using RTK Query):

```<code>const { data: Florists_data, refetch } = useGetFloristQuery(Number(sessionStorage.getItem('florist_id')));
const [flowersData, setFlowersData] = useState(Florists_data?.florist[0].flowers);
const [tmpFlowers, setTmpFlowers] = useState(Florists_data?.florist[0].flowers);
</code>```

Update function:

```<code>const updateFieldChanged = (index: number, e: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => {
        let newArr = [...tmpFlowers!];
        newArr[index].amount = Number(e.target.value); //GETTING ERROR HERE
        setTmpFlowers(newArr);
    }
</code>```

Inputs:

```<code>{flowersData?.map((flower, index) => {
  return (
    <>
      <div className={classes.Nested_Flower_Container} key={index}>
        <div className={classes.Nested_Flower_Name}>
          {flower.name}
        </div>
        <div className={classes.Nested_Flower_Input} style={{ marginRight: '0.2em' }}>
          <TextField
            id="Amount"
            label="Amount"
            variant="outlined"
            size="small"
            type="number"
            onChange={(e) => {
              updateFieldChanged(index, e);
            }}
            className={classes_2.root}
            />
        </div>
      </div>
    </>)
})}
</code>```

答: Spread operator normally creates a new object in memory, not just an address pointer. But when using it on an array of objects, it creates a second array like usual, but with all the objects inside being memory pointers. In short, what I believe is happening is the objects cant be changed because they're not copies. Try finding a deep clone code and testing of it works. (This is what's happening https://media.discordapp.net/attachments/335455578921107456/940745267324534825/MMAsMng1.png) which I also suspect is erroring out because you're modifying the state in an unapproved way</p>

Body:
I'm fetching data from an API and then I save an array inside a state. While I'm trying to modify the specific field in object inside an array using input, I'm getting the following error: 'Uncaught TypeError: Cannot assign to read only property 'amount' of object '#''.

States (I'm using RTK Query):

const { data: Florists_data, refetch } = useGetFloristQuery(Number(sessionStorage.getItem('florist_id')));
const [flowersData, setFlowersData] = useState(Florists_data?.florist[0].flowers);
const [tmpFlowers, setTmpFlowers] = useState(Florists_data?.florist[0].flowers);

Update function:

const updateFieldChanged = (index: number, e: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => {
        let newArr = [...tmpFlowers!];
        newArr[index].amount = Number(e.target.value); //GETTING ERROR HERE
        setTmpFlowers(newArr);
    }

Inputs:

{flowersData?.map((flower, index) => {
  return (
    <>

          {flower.name}

          <TextField
            id="Amount"
            label="Amount"
            variant="outlined"
            size="small"
            type="number"
            onChange={(e) => {
              updateFieldChanged(index, e);
            }}
            className={classes_2.root}
            />

    </>)
})}


问:
What's the use of `MutableTransitionState`? Looks like mutableStateOf does all it can equally good
In https://developer.android.com/jetpack/compose/animation, it is mentioned that

We sometimes want to have an initial state different from the first target state. We can use updateTransition with MutableTransitionState to achieve this. For example, it allows us to start animation as soon as the code enters composition.

```<code>// Start in collapsed state and immediately animate to expanded
var currentState = remember { MutableTransitionState(BoxState.Collapsed) }
currentState.targetState = BoxState.Expanded
val transition = updateTransition(currentState)
// ...
</code>```

(For full code, refer to full code example 1. below)

However, the above code is only working for initial animation but not subsequent (i.e. change from Expanded to Collapsed), as whenever the currentState.targetState changes, the composable function will run and retriggered currentState.targetState = BoxState.Expanded.

To fix the problem, I'll have to

```<code>    var currentState by remember { mutableStateOf(BoxState.Collapsed) }
    val transition = updateTransition(currentState, label = "")

    LaunchedEffect(Unit) {
        currentState.targetState = BoxState.Expanded
    }
</code>```

(For full code, refer to full code example 2. below)

This will make the animation start automatically from Collapsed to Expanded. Also subsequently upon change from Expanded to Collapse (e.g. through a button click), it will still work, as the LaunchedEffect is no longer triggered.

With the LaunchedEffect, we can also do it with normal mutableStateOf, i.e. without MutableTransitionState, and still, behave well.

```<code>    var currentState by remember { mutableStateOf(BoxState.Collapsed) }
    val transition = updateTransition(currentState, label = "")

    LaunchedEffect(Unit) {
        currentState = BoxState.Expanded
    }
</code>```

(For full code, refer to full code example 3. below)

So I cannot see any extra benefit using MutableTransitionState compare to the normal mutableStateOf. Anything I miss?

Full Code that describes the situation above

1. MutableTransitionState code follow document example that doesn't work

The code that doesn't works with just MutableTransitionState (i.e. no effect on button click, only having initial animation)

```<code>@Composable
fun Greeting() {
    val currentState = remember { MutableTransitionState(BoxState.Collapsed) }
    currentState.targetState = BoxState.Expanded
    val transition = updateTransition(currentState, label = "")

    val rect by transition.animateRect(label = "") { state ->
        when (state) {
            BoxState.Collapsed -> Rect(0f, 0f, 100f, 100f)
            BoxState.Expanded -> Rect(100f, 100f, 300f, 300f)
        }
    }

    Column {
        Canvas(
            modifier = Modifier.fillMaxWidth().height(500.dp)
                .border(BorderStroke(1.dp, Color.Green))
        ) {
            drawPath(Path().apply { addRect(rect) }, Color.Red)
        }
        Button(onClick = {
            currentState.targetState =
                if (currentState.targetState == BoxState.Expanded) BoxState.Collapsed
                else BoxState.Expanded
        }) {
            Text("Click Me")
        }
    }
}
</code>```

2. MutableTransitionState code with launched effect that works

The code that works with just MutableTransitionState (i.e. have effect on button click, and having initial animation)

```<code>@Composable
fun Greeting() {
    val currentState = remember { MutableTransitionState(BoxState.Collapsed) }
    val transition = updateTransition(currentState, label = "")

    val rect by transition.animateRect(label = "") { state ->
        when (state) {
            BoxState.Collapsed -> Rect(0f, 0f, 100f, 100f)
            BoxState.Expanded -> Rect(100f, 100f, 300f, 300f)
        }
    }

    Column {
        Canvas(
            modifier = Modifier.fillMaxWidth().height(500.dp)
                .border(BorderStroke(1.dp, Color.Green))
        ) {
            drawPath(Path().apply { addRect(rect) }, Color.Red)
        }
        Button(onClick = {
            currentState.targetState =
                if (currentState.targetState == BoxState.Expanded) BoxState.Collapsed
                else BoxState.Expanded
        }) {
            Text("Click Me")
        }
    }

    LaunchedEffect(Unit) {
        currentState.targetState = BoxState.Expanded
    }
}
</code>```

3. Just mutableStateOf code with launched effect that still works

The code that works with just mutableStateOf (i.e. have effect on button click, and having initial animation)

```<code>@Composable
fun Greeting() {
    var currentState by remember { mutableStateOf(BoxState.Collapsed) }
    val transition = updateTransition(currentState, label = "")

    val rect by transition.animateRect(label = "") { state ->
        when (state) {
            BoxState.Collapsed -> Rect(0f, 0f, 100f, 100f)
            BoxState.Expanded -> Rect(100f, 100f, 300f, 300f)
        }
    }

    Column {
        Canvas(
            modifier = Modifier.fillMaxWidth().height(500.dp)
                .border(BorderStroke(1.dp, Color.Green))
        ) {
            drawPath(Path().apply { addRect(rect) }, Color.Red)
        }
        Button(onClick = {
            currentState =
                if (currentState == BoxState.Expanded) BoxState.Collapsed
                else BoxState.Expanded
        }) {
            Text("Click Me")
        }
    }

    LaunchedEffect(Unit) {
        currentState = BoxState.Expanded
    }
}
</code>```

答:
MutableTransitionState allows you to specify a different targetState than the initial state. Note it is not a MutableState.

If you do something like this:

```<code>    val currentState = remember {
        MutableTransitionState(BoxState.Collapsed).apply {targetState = BoxState.Expanded}
    }

</code>```

You can expect the Transition to start an animation going from BoxState.Collapsed to BoxState.Expanded as soon as the updateTransition is composed for the first time.

MutableTransitionState is designed to 1) trigger animations when a composable gets added to the tree (i.e. enter animations), and 2) allow observation of currentState vs targetState through the MutableTransitionState object like this: https://android.googlesource.com/platform/frameworks/support/+/e6095adbb8ffba6aede464fd06ef7302eac61860/compose/animation/animation/integration-tests/animation-demos/src/main/java/androidx/compose/animation/demos/AnimatedVisiblilityLazyColumnDemo.kt#127

Body:
In https://developer.android.com/jetpack/compose/animation, it is mentioned that

We sometimes want to have an initial state different from the first target state. We can use updateTransition with MutableTransitionState to achieve this. For example, it allows us to start animation as soon as the code enters composition.

// Start in collapsed state and immediately animate to expanded
var currentState = remember { MutableTransitionState(BoxState.Collapsed) }
currentState.targetState = BoxState.Expanded
val transition = updateTransition(currentState)
// ...

(For full code, refer to full code example 1. below)

However, the above code is only working for initial animation but not subsequent (i.e. change from Expanded to Collapsed), as whenever the currentState.targetState changes, the composable function will run and retriggered currentState.targetState = BoxState.Expanded.

To fix the problem, I'll have to

    var currentState by remember { mutableStateOf(BoxState.Collapsed) }
    val transition = updateTransition(currentState, label = "")

    LaunchedEffect(Unit) {
        currentState.targetState = BoxState.Expanded
    }

(For full code, refer to full code example 2. below)

This will make the animation start automatically from Collapsed to Expanded. Also subsequently upon change from Expanded to Collapse (e.g. through a button click), it will still work, as the LaunchedEffect is no longer triggered.

With the LaunchedEffect, we can also do it with normal mutableStateOf, i.e. without MutableTransitionState, and still, behave well.

    var currentState by remember { mutableStateOf(BoxState.Collapsed) }
    val transition = updateTransition(currentState, label = "")

    LaunchedEffect(Unit) {
        currentState = BoxState.Expanded
    }

(For full code, refer to full code example 3. below)

So I cannot see any extra benefit using MutableTransitionState compare to the normal mutableStateOf. Anything I miss?

Full Code that describes the situation above

1. MutableTransitionState code follow document example that doesn't work

The code that doesn't works with just MutableTransitionState (i.e. no effect on button click, only having initial animation)

@Composable
fun Greeting() {
    val currentState = remember { MutableTransitionState(BoxState.Collapsed) }
    currentState.targetState = BoxState.Expanded
    val transition = updateTransition(currentState, label = "")

    val rect by transition.animateRect(label = "") { state ->
        when (state) {
            BoxState.Collapsed -> Rect(0f, 0f, 100f, 100f)
            BoxState.Expanded -> Rect(100f, 100f, 300f, 300f)
        }
    }

    Column {
        Canvas(
            modifier = Modifier.fillMaxWidth().height(500.dp)
                .border(BorderStroke(1.dp, Color.Green))
        ) {
            drawPath(Path().apply { addRect(rect) }, Color.Red)
        }
        Button(onClick = {
            currentState.targetState =
                if (currentState.targetState == BoxState.Expanded) BoxState.Collapsed
                else BoxState.Expanded
        }) {
            Text("Click Me")
        }
    }
}

2. MutableTransitionState code with launched effect that works

The code that works with just MutableTransitionState (i.e. have effect on button click, and having initial animation)

@Composable
fun Greeting() {
    val currentState = remember { MutableTransitionState(BoxState.Collapsed) }
    val transition = updateTransition(currentState, label = "")

    val rect by transition.animateRect(label = "") { state ->
        when (state) {
            BoxState.Collapsed -> Rect(0f, 0f, 100f, 100f)
            BoxState.Expanded -> Rect(100f, 100f, 300f, 300f)
        }
    }

    Column {
        Canvas(
            modifier = Modifier.fillMaxWidth().height(500.dp)
                .border(BorderStroke(1.dp, Color.Green))
        ) {
            drawPath(Path().apply { addRect(rect) }, Color.Red)
        }
        Button(onClick = {
            currentState.targetState =
                if (currentState.targetState == BoxState.Expanded) BoxState.Collapsed
                else BoxState.Expanded
        }) {
            Text("Click Me")
        }
    }

    LaunchedEffect(Unit) {
        currentState.targetState = BoxState.Expanded
    }
}

3. Just mutableStateOf code with launched effect that still works

The code that works with just mutableStateOf (i.e. have effect on button click, and having initial animation)

@Composable
fun Greeting() {
    var currentState by remember { mutableStateOf(BoxState.Collapsed) }
    val transition = updateTransition(currentState, label = "")

    val rect by transition.animateRect(label = "") { state ->
        when (state) {
            BoxState.Collapsed -> Rect(0f, 0f, 100f, 100f)
            BoxState.Expanded -> Rect(100f, 100f, 300f, 300f)
        }
    }

    Column {
        Canvas(
            modifier = Modifier.fillMaxWidth().height(500.dp)
                .border(BorderStroke(1.dp, Color.Green))
        ) {
            drawPath(Path().apply { addRect(rect) }, Color.Red)
        }
        Button(onClick = {
            currentState =
                if (currentState == BoxState.Expanded) BoxState.Collapsed
                else BoxState.Expanded
        }) {
            Text("Click Me")
        }
    }

    LaunchedEffect(Unit) {
        currentState = BoxState.Expanded
    }
}

Body:
MutableTransitionState allows you to specify a different targetState than the initial state. Note it is not a MutableState.

If you do something like this:

    val currentState = remember {
        MutableTransitionState(BoxState.Collapsed).apply {targetState = BoxState.Expanded}
    }

You can expect the Transition to start an animation going from BoxState.Collapsed to BoxState.Expanded as soon as the updateTransition is composed for the first time.

MutableTransitionState is designed to 1) trigger animations when a composable gets added to the tree (i.e. enter animations), and 2) allow observation of currentState vs targetState through the MutableTransitionState object like this: https://android.googlesource.com/platform/frameworks/support/+/e6095adbb8ffba6aede464fd06ef7302eac61860/compose/animation/animation/integration-tests/animation-demos/src/main/java/androidx/compose/animation/demos/AnimatedVisiblilityLazyColumnDemo.kt#127


问:
Purview Collection - Move Entities To Collection
How can we move purview entities between collections using API's?</p>

答:
Please refer to this Azure Purview REST API documentation which has description with sample: Collection - Move Entities To Collection

Moving existing entities to a target collection:

POST {Endpoint}/catalog/api/collections/{collection}/entity/moveHere?api-version=2021-05-01-preview


问:
Appending floats to empty pandas DataFrame
I am trying to build a recursive function that will take data from a specific dataframe, do a little math with it, and append that result to a new dataframe. My current code looks as follows

```<code>div1, div2, div3 = [pd.DataFrame(index = range(1), columns = ['g']) for i in range(3)]

# THIS IS NOT WORKING FOR SOME REASON
def stats(div, obp):
    loop = 1
    while loop <= 3:
        games = obp['g'].sum() / 2
        div = div.append(games)
        loop += 1
    if loop == 2:
        stats(div2, dii_obp, dii_hr)
    elif loop == 3:
        stats(div3, diii_obp, diii_hr)
    else:
        print('Invalid')

stats(div1, di_obp)
</code>```

I get an error that reads:

```<code>TypeError: cannot concatenate object of type '<class 'numpy.float64'>'; only Series and DataFrame objs are valid
</code>```

div1, and di_obp are dataframes and ['g'] is a column in the di_obp dataframe.

I have tried making the variable games into an empty list, and a series and got different errors. I am not sure what I should try next. Any help is much appreciated!!

here is the head of the di_obp dataframe, the dii_obp and the diii_obp dataframes are the same but with different values.

```<code>print(di_obp.head())
      rank  team     g      ab      h     bb   hbp    sf    sh
608  213.0  None  56.0  1947.0  526.0  182.0  55.0  19.0  22.0
609  214.0  None  36.0  1099.0  287.0  124.0  25.0  11.0  24.0
610  215.0  None  35.0  1099.0  247.0  159.0  51.0  11.0  24.0
611  216.0  None  36.0  1258.0  317.0  157.0  30.0  11.0   7.0
612  217.0  None  38.0  1136.0  281.0  138.0  41.0  14.0  10.0
</code>```

CURRENT PROBLEM:

```<code>div1, div2, div3 = [pd.DataFrame(index= range(1), columns = ['g']) for i in range(3)]

def stats(div, obp):
    loop = 1
    while loop <= 3:
        while loop <= 3:
            games = obp['g'].sum() / 2
            div[0] = div[0].append({'g': games}, ignore_index=True)
            loop += 1
        if loop == 2:
            stats([div2], dii_obp)
        elif loop == 3:
            stats([div3], diii_obp)
        else:
            print('Done')

stats([div1], di_obp)
</code>```

this does not return an error, but my dataframes are still empty

答:
Appending to a dataframe is generally not recommended. Instead, you should accumulate your data in lists and then create dataframes from those lists:</p>
```<code>div1, div2, div3 = [[] for _ in range(3)]

def stats(div, obp):
    loop = 1
    while loop <= 3:
        while loop <= 3:
            games = obp['g'].sum() / 2
            div.append(games)
            loop += 1
        if loop == 2:
            stats(div2, dii_obp)
        elif loop == 3:
            stats(div3, diii_obp)
        else:
            print('Done')

stats(div1, di_obp)

div1_df, div2_df, div2_df = [pd.DataFrame({'g': div}) for div in [div1, div2, div3]]
</code>```

Body:
I am trying to build a recursive function that will take data from a specific dataframe, do a little math with it, and append that result to a new dataframe. My current code looks as follows

div1, div2, div3 = [pd.DataFrame(index = range(1), columns = ['g']) for i in range(3)]

# THIS IS NOT WORKING FOR SOME REASON
def stats(div, obp):
    loop = 1
    while loop <= 3:
        games = obp['g'].sum() / 2
        div = div.append(games)
        loop += 1
    if loop == 2:
        stats(div2, dii_obp, dii_hr)
    elif loop == 3:
        stats(div3, diii_obp, diii_hr)
    else:
        print('Invalid')

stats(div1, di_obp)

I get an error that reads:

TypeError: cannot concatenate object of type '<class 'numpy.float64'>'; only Series and DataFrame objs are valid

div1, and di_obp are dataframes and ['g'] is a column in the di_obp dataframe.

I have tried making the variable games into an empty list, and a series and got different errors. I am not sure what I should try next. Any help is much appreciated!!

here is the head of the di_obp dataframe, the dii_obp and the diii_obp dataframes are the same but with different values.

print(di_obp.head())
      rank  team     g      ab      h     bb   hbp    sf    sh
608  213.0  None  56.0  1947.0  526.0  182.0  55.0  19.0  22.0
609  214.0  None  36.0  1099.0  287.0  124.0  25.0  11.0  24.0
610  215.0  None  35.0  1099.0  247.0  159.0  51.0  11.0  24.0
611  216.0  None  36.0  1258.0  317.0  157.0  30.0  11.0   7.0
612  217.0  None  38.0  1136.0  281.0  138.0  41.0  14.0  10.0

CURRENT PROBLEM:

div1, div2, div3 = [pd.DataFrame(index= range(1), columns = ['g']) for i in range(3)]

def stats(div, obp):
    loop = 1
    while loop <= 3:
        while loop <= 3:
            games = obp['g'].sum() / 2
            div[0] = div[0].append({'g': games}, ignore_index=True)
            loop += 1
        if loop == 2:
            stats([div2], dii_obp)
        elif loop == 3:
            stats([div3], diii_obp)
        else:
            print('Done')

stats([div1], di_obp)

this does not return an error, but my dataframes are still empty

Body:
Appending to a dataframe is generally not recommended. Instead, you should accumulate your data in lists and then create dataframes from those lists:

div1, div2, div3 = [[] for _ in range(3)]

def stats(div, obp):
    loop = 1
    while loop <= 3:
        while loop <= 3:
            games = obp['g'].sum() / 2
            div.append(games)
            loop += 1
        if loop == 2:
            stats(div2, dii_obp)
        elif loop == 3:
            stats(div3, diii_obp)
        else:
            print('Done')

stats(div1, di_obp)

div1_df, div2_df, div2_df = [pd.DataFrame({'g': div}) for div in [div1, div2, div3]]


问:
Function for filling in values to adjacent cells
I have a Google sheet (Form Connector) that uses a form for users to input data into. From there, another sheet (Summary) gives a summary of all the data that is put into it via the form. Another sheet gives a breakdown of all the data (Daily RT). The Daily RT sheet is shown below

Within the cells that say "No RT" is the following formula, with respect to their row.

```<code>=IFNA(ARRAY_CONSTRAIN(FILTER('Form Connector'!$D$2:$F,'Form Connector'!$C$2:$C=$B$1,'Form Connector'!$B$2:$B=$A3),1,20),IF($A3<TODAY(),"No RT",""))
</code>```

Column A is the dates, B:D is data as well as E:G. I've been focusing on the IF($A3<TODAY(),"No RT","") in the formula to be able to replace the "No RT" part of it.

Question:
Is there any way, instead of "No RT", to fill in 0's in columns B:D using the one formula which is in column B via an array?

答:
try in B3 after you remove everything from B3:D range:

```<code>=ARRAYFORMULA(IFNA(VLOOKUP($A3:$A,
 FILTER('Form Connector'!$B2:$F, 'Form Connector'!$C2:$C=B$1),
 {3,4,5}, 0))*1)
</code>```

update:

```<code>=ARRAYFORMULA(IF($A3:$A>=TODAY(),,IFNA(VLOOKUP($A3:$A,
 FILTER('Form Connector'!$B2:$F, 'Form Connector'!$C2:$C=B$1),
 {3,4,5}, 0))*1))
</code>```

Body:
I have a Google sheet (Form Connector) that uses a form for users to input data into. From there, another sheet (Summary) gives a summary of all the data that is put into it via the form. Another sheet gives a breakdown of all the data (Daily RT). The Daily RT sheet is shown below

Within the cells that say "No RT" is the following formula, with respect to their row.

=IFNA(ARRAY_CONSTRAIN(FILTER('Form Connector'!$D$2:$F,'Form Connector'!$C$2:$C=$B$1,'Form Connector'!$B$2:$B=$A3),1,20),IF($A3<TODAY(),"No RT",""))

Column A is the dates, B:D is data as well as E:G. I've been focusing on the IF($A3<TODAY(),"No RT","") in the formula to be able to replace the "No RT" part of it.

Question:
Is there any way, instead of "No RT", to fill in 0's in columns B:D using the one formula which is in column B via an array?

Body:
try in B3 after you remove everything from B3:D range:

=ARRAYFORMULA(IFNA(VLOOKUP($A3:$A,
 FILTER('Form Connector'!$B2:$F, 'Form Connector'!$C2:$C=B$1),
 {3,4,5}, 0))*1)

update:

=ARRAYFORMULA(IF($A3:$A>=TODAY(),,IFNA(VLOOKUP($A3:$A,
 FILTER('Form Connector'!$B2:$F, 'Form Connector'!$C2:$C=B$1),
 {3,4,5}, 0))*1))


问:
Removing decimal places after second number
I have some raw data exported from my ERP. Most of the data has two decimals, but there are a few lines contain numbers with three or more decimal places... When summing up all data with powershell I have a 0,01€ discrepancy between my ERP PDF report and sum of exported data. I tracked the discrepancy to a single number - 2.205. Powershell rounds this number to 2.2 not 2.21 as expected. If I try any other number - 2.215, 2.225 they all get rounded to 2.22, 2.23..

Why is 2.205 not treated the same???

答:
.NET's default mid-point rounding strategy is ToEven, meaning that .5 values are rounded to the closest even integer.

Important: The following example use [decimal] numbers - as implied by number-literal suffix d - not [double]s , so as to avoid problems that stem from [double] values, which internally use a binary representation that typically does not have an exact decimal equivalent, so that a number that may appear to have a 5 in the relevant decimal place may actually be just above or below that exact decimal value,[1] which means that mid-point rounding may not apply - see Rounding and precision.

In the case at hand, rounding -2.205 to 2 decimal places means that 0 is the closest even integer, and [Math]::Round(-2.205d, 2) therefore yields -2.20.[2]

It sounds like you want AwayFromZero as the mid-point rounding strategy, which rounds to the next higher integer in absolute terms:

PS> [Math]::Round(-2.205d, 2, 'AwayFromZero')
-2.21
```

[1] To see if a given fractional value has an exact decimal representation, you can use something like the following:

$num = [double] -2.205; '{0:F28}' -f $num

Unless the input number is echoed with trailing zeros only, the given value has no exact decimal representation; [double] value -2.205 does not, but 0.5 does, for instance.

[2] Note that [Math]::Round(2.225d, 2) therefore yields 2.22, not 2.23, as you state in your question.

Body:
.NET's default mid-point rounding strategy is ToEven, meaning that .5 values are rounded to the closest even integer.

Important: The following example use [decimal] numbers - as implied by number-literal suffix d - not [double]s , so as to avoid problems that stem from [double] values, which internally use a binary representation that typically does not have an exact decimal equivalent, so that a number that may appear to have a 5 in the relevant decimal place may actually be just above or below that exact decimal value,[1] which means that mid-point rounding may not apply - see Rounding and precision.

In the case at hand, rounding -2.205 to 2 decimal places means that 0 is the closest even integer, and [Math]::Round(-2.205d, 2) therefore yields -2.20.[2]

It sounds like you want AwayFromZero as the mid-point rounding strategy, which rounds to the next higher integer in absolute terms:

PS> [Math]::Round(-2.205d, 2, 'AwayFromZero')
-2.21

[1] To see if a given fractional value has an exact decimal representation, you can use something like the following:

$num = [double] -2.205; '{0:F28}' -f $num

Unless the input number is echoed with trailing zeros only, the given value has no exact decimal representation; [double] value -2.205 does not, but 0.5 does, for instance.

[2] Note that [Math]::Round(2.225d, 2) therefore yields 2.22, not 2.23, as you state in your question.


问:
Querying Hashtable key LINQ expression C#
I have a hashtable that has key/value pairs as follows,

```<code>Hashtable h1 = new Hashtable();
h1.Add("@USD_Type","123");

        public class USDParameters
        {
            public const string USDType = "@USD_Type";
            public const string USDId = "@USD_ID";
            public const string USDName = "@USD_Name";
        }

</code>```

Sometimes, I might also have "@USD_ID", "@USD_Name" keys in the hashtable.

I would like to query all the keys in the hashtable which start with @STD_ and match against the names in USDParameters. If the name is not found in hashtable then I need to build a string that has the key(minus @) from the hashtable.

For e.g. "The following key(s) missing from the hashtable - USD_ID, USD_Name"

答:
The challenging part is to query on the keys:

var keys = h1.Keys.Cast<string>()
  .Where(x => x.StartsWith("@STD_"));
```

Once you have the list in this enumerable type it is much easier to look for missing keys.

Body:
I have a hashtable that has key/value pairs as follows,

Hashtable h1 = new Hashtable();
h1.Add("@USD_Type","123");

        public class USDParameters
        {
            public const string USDType = "@USD_Type";
            public const string USDId = "@USD_ID";
            public const string USDName = "@USD_Name";
        }

Sometimes, I might also have "@USD_ID", "@USD_Name" keys in the hashtable.

I would like to query all the keys in the hashtable which start with @STD_ and match against the names in USDParameters. If the name is not found in hashtable then I need to build a string that has the key(minus @) from the hashtable.

For e.g. "The following key(s) missing from the hashtable - USD_ID, USD_Name"

Body:
The challenging part is to query on the keys:

var keys = h1.Keys.Cast<string>()
  .Where(x => x.StartsWith("@STD_"));

Once you have the list in this enumerable type it is much easier to look for missing keys.


问:
Sendinblue API V3 using autoload.php without composer
I try to send transactional emails with Sendinblue, using API V3 and php.

I've tried to follow the documentation https://github.com/sendinblue/APIv3-php-library and I've read a lot of posts on Stackoverflow, like this one : How do I set transactional email attributes in Sendinblue api v3?.

I don't know how to generate vendor/autoload.php with composer, so I've downloaded
sendinblue/api-v3-sdk (Official SendinBlue provided RESTFul API V3 php library) on https://php-download.com.

I've tested these lines :

```<code><?php
require_once('/vendor/autoload.php');

$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'xkeysib-my-key');

$apiInstance = new SendinBlue\Client\Api\TransactionalEmailsApi(
    new GuzzleHttp\Client(),
    $config
);
$sendSmtpEmail = new \SendinBlue\Client\Model\SendSmtpEmail();
$sendSmtpEmail['subject'] = 'Le sujet';
$sendSmtpEmail['htmlContent'] = '<html><body><h1>This is a transactional email </h1></body></html>';
$sendSmtpEmail['sender'] = array('name' => 'John Doe', 'email' => 'contact@domain.com');
$sendSmtpEmail['to'] = array(
    array('email' => 'autre@domain2fr', 'name' => 'Jane Doe')
);
$sendSmtpEmail['replyTo'] = array('email' => 'replyto@domain.com', 'name' => 'John Doe');
$sendSmtpEmail['headers'] = array('Some-Custom-Name' => 'unique-id-1234');
$sendSmtpEmail['params'] = array('parameter' => 'My param value', 'subject' => 'New Subject');

try {
    $result = $apiInstance->sendTransacEmail($sendSmtpEmail);
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling TransactionalEmailsApi->sendTransacEmail: ', $e->getMessage(), PHP_EOL;
}
?>
</code>```

And I've got the following error :

Parse error: syntax error, unexpected '?', expecting variable (T_VARIABLE) in D:...\sendinblueV3\vendor\guzzlehttp\guzzle\src\Client.php on line 203

because of this line

```<code>$apiInstance = ....
</code>```

So I've removed the "?" on line 203 of Client.php :

```<code>public function getConfig(?string $option = null)
</code>```

and then, I've another mistake :

Parse error: syntax error, unexpected 'const' (T_CONST), expecting variable (T_VARIABLE) in D:\Dropbox\www\ifrb\IFRBTP77\sendinblueV3\vendor\guzzlehttp\guzzle\src\ClientInterface.php on line 19

If someone understand where is the problem ....

Thank you,
Olivier.

Edit :

I've installed composer as @David Wolf suggested to me.
But when running

C:\Windows\System32>composer require sendinblue/api-v3-sdk "8.x.x"

I've an error due to my php version :

```<code>./composer.json has been created Running composer update
sendinblue/api-v3-sdk Loading composer repositories with package
information Updating dependencies Your requirements could not be
resolved to an installable set of packages.
  Problem 1
    - guzzlehttp/guzzle[7.4.0, ..., 7.4.1] require php ^7.2.5 || ^8.0 -> your php version (5.6.18) does not satisfy that requirement.
    - sendinblue/api-v3-sdk v8.0.0 requires guzzlehttp/guzzle ^7.4.0 -> satisfiable by guzzlehttp/guzzle[7.4.0, 7.4.1].
    - Root composer.json requires sendinblue/api-v3-sdk 8.x.x -> satisfiable by sendinblue/api-v3-sdk[v8.0.0].
</code>```

That's curious because API v3 Php Library requires PHP 5.6 and later.

And I can't upgrade py php version on my server.

答:
Downloading the API Wrapper won't work, since itself has dependencies (other code it depends on), which you haven't installed.

The easiest and best practice way to archive what you are trying to do is using  composer.

Download and Install composer

Run composer require sendinblue/api-v3-sdk "8.x.x"

The last command will automatically install all dependencies for you and generate the needed autoloaders.

If you are new to composer I would suggest you checking out the getting started section on the composer website.

Body:
I try to send transactional emails with Sendinblue, using API V3 and php.

I've tried to follow the documentation https://github.com/sendinblue/APIv3-php-library and I've read a lot of posts on Stackoverflow, like this one : How do I set transactional email attributes in Sendinblue api v3?.

I don't know how to generate vendor/autoload.php with composer, so I've downloaded
sendinblue/api-v3-sdk (Official SendinBlue provided RESTFul API V3 php library) on https://php-download.com.

I've tested these lines :

<?php
require_once('/vendor/autoload.php');

$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'xkeysib-my-key');

$apiInstance = new SendinBlue\Client\Api\TransactionalEmailsApi(
    new GuzzleHttp\Client(),
    $config
);
$sendSmtpEmail = new \SendinBlue\Client\Model\SendSmtpEmail();
$sendSmtpEmail['subject'] = 'Le sujet';
$sendSmtpEmail['htmlContent'] = '
This is a transactional email
';
$sendSmtpEmail['sender'] = array('name' => 'John Doe', 'email' => 'contact@domain.com');
$sendSmtpEmail['to'] = array(
    array('email' => 'autre@domain2fr', 'name' => 'Jane Doe')
);
$sendSmtpEmail['replyTo'] = array('email' => 'replyto@domain.com', 'name' => 'John Doe');
$sendSmtpEmail['headers'] = array('Some-Custom-Name' => 'unique-id-1234');
$sendSmtpEmail['params'] = array('parameter' => 'My param value', 'subject' => 'New Subject');

try {
    $result = $apiInstance->sendTransacEmail($sendSmtpEmail);
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling TransactionalEmailsApi->sendTransacEmail: ', $e->getMessage(), PHP_EOL;
}
?>

And I've got the following error :

Parse error: syntax error, unexpected '?', expecting variable (T_VARIABLE) in D:...\sendinblueV3\vendor\guzzlehttp\guzzle\src\Client.php on line 203

because of this line

$apiInstance = ....

So I've removed the "?" on line 203 of Client.php :

public function getConfig(?string $option = null)

and then, I've another mistake :

Parse error: syntax error, unexpected 'const' (T_CONST), expecting variable (T_VARIABLE) in D:\Dropbox\www\ifrb\IFRBTP77\sendinblueV3\vendor\guzzlehttp\guzzle\src\ClientInterface.php on line 19

If someone understand where is the problem ....

Thank you,
Olivier.

Edit :

I've installed composer as @David Wolf suggested to me.
But when running

C:\Windows\System32>composer require sendinblue/api-v3-sdk "8.x.x"

I've an error due to my php version :

./composer.json has been created Running composer update
sendinblue/api-v3-sdk Loading composer repositories with package
information Updating dependencies Your requirements could not be
resolved to an installable set of packages.
  Problem 1
    - guzzlehttp/guzzle[7.4.0, ..., 7.4.1] require php ^7.2.5 || ^8.0 -> your php version (5.6.18) does not satisfy that requirement.
    - sendinblue/api-v3-sdk v8.0.0 requires guzzlehttp/guzzle ^7.4.0 -> satisfiable by guzzlehttp/guzzle[7.4.0, 7.4.1].
    - Root composer.json requires sendinblue/api-v3-sdk 8.x.x -> satisfiable by sendinblue/api-v3-sdk[v8.0.0].

That's curious because API v3 Php Library requires PHP 5.6 and later.

And I can't upgrade py php version on my server.


问:
gVim: How to load multiple files in buffer?
Im in windows and is new in using gvim. I am using the Nerdtree plugin for project navigations. Right now I open files from the nerd tree, vim will then load this opened files in the buffer. I find it easier to switch throug multiple files using the :b command, it gets more convenient after opening more files as more is loaded in the buffer.

But I think it will be more convenient if there is a way to load all files in a directory in the buffer at the same time instead of loading one by one when opening them.

答:
If you use the project plugin for Vim, you could open all files under the currently selected entry.

Note that an entry is not only limited to be a folder, you could e.g. place all your needed includes in one entry and then open them in one go.

The plugin gives you also more project-relevant features like grepping through all files of the currently selected entry and many more.

Setting up your project is a little effort, but once you've done that, it's really comfortable.


问:
Confusion about this pointer and callback functions
Let's say I have the following scenario where I define a callback function m_deleter.

```<code>
class B {
public:
    B() = default;
    ~B(){
        if (m_deleter) {
            m_deleter();
        }
    }

    std::function<void()> m_deleter = nullptr;
};

class A {
public:
    void createB(B& b) {
        auto func = [this]() {
            this->printMessage();
        };

        b.m_deleter = func;
    }

    void printMessage() {
        std::cout << "Here is the message!" << std::endl;
    }
};
</code>```

And here is our main function:

```<code>int main() {
    B b;

    {
        A a;
        a.createB(b);
    } // a falls out of scope.

}
</code>```

Here is my confusion. When the stack instance a falls out of scope, is the memory not deallocated? How can the this pointer, used here in the callback: this->printMessage(); still point to a valid object?

When I run the above program, it prints:
Here is the message!

Edit:
Follow up question, is there any way for b to know that a has fallen out of scope and is no longer a valid object, and therefore should not call the callback?

答:
It doesn't. But due to the fact that in the method printMessage you don't reference any fields from the class A, there is no crush. This is an UB however.

Here is the code that avoids this issue but demonstrates the correct behavior:

class A {
public:
    void createB(B& b) {
        auto func = []() {
            A::printMessage();
        };

        b.m_deleter = func;
    }

    static void printMessage() {
        std::cout << "Here is the message!" << std::endl;
    }
};
```

No pointer, no references to any field, no need to track whether the instance is valid, no UB. If you need to access the data from A, you need a valid instance.

Body:
Let's say I have the following scenario where I define a callback function m_deleter.

class B {
public:
    B() = default;
    ~B(){
        if (m_deleter) {
            m_deleter();
        }
    }

    std::function<void()> m_deleter = nullptr;
};

class A {
public:
    void createB(B& b) {
        auto func = [this]() {
            this->printMessage();
        };

        b.m_deleter = func;
    }

    void printMessage() {
        std::cout << "Here is the message!" << std::endl;
    }
};

And here is our main function:

int main() {
    B b;

    {
        A a;
        a.createB(b);
    } // a falls out of scope.

}

Here is my confusion. When the stack instance a falls out of scope, is the memory not deallocated? How can the this pointer, used here in the callback: this->printMessage(); still point to a valid object?

When I run the above program, it prints:
Here is the message!

Edit:
Follow up question, is there any way for b to know that a has fallen out of scope and is no longer a valid object, and therefore should not call the callback?

Body:
It doesn't. But due to the fact that in the method printMessage you don't reference any fields from the class A, there is no crush. This is an UB however.

Here is the code that avoids this issue but demonstrates the correct behavior:

class A {
public:
    void createB(B& b) {
        auto func = []() {
            A::printMessage();
        };

        b.m_deleter = func;
    }

    static void printMessage() {
        std::cout << "Here is the message!" << std::endl;
    }
};

No pointer, no references to any field, no need to track whether the instance is valid, no UB. If you need to access the data from A, you need a valid instance.


问:
How I turn these classes to override or how I give this final tag to values?
I' ve downloaded this plugin recently and I tried to open example file. However I was getting these errors

*This class (or a class that this class inherits from) is marked as '@immutable', but one or more of its instance fields aren't final: StartMeetingWidget.zoomOptions, StartMeetingWidget.meetingOptions, StartMeetingWidget.timer

```<code>    class StartMeetingWidget extends StatelessWidget {
  ZoomOptions zoomOptions;
  ZoomMeetingOptions meetingOptions;

  Timer timer;

  StartMeetingWidget({Key key, meetingId}) : super(key: key) {
    this.zoomOptions = new ZoomOptions(
      domain: "zoom.us",
      appKey: "appKey",
      appSecret: "appSecret",
    );
    this.meetingOptions = new ZoomMeetingOptions(
        userId: '<zoom_user_id>',
        displayName: 'Example display Name',
        meetingId: meetingId,
        zoomAccessToken: "<User zak>",
        zoomToken: "<user_token>",
        disableDialIn: "true",
        disableDrive: "true",
        disableInvite: "true",
        disableShare: "true",
        noAudio: "false",
        noDisconnectAudio: "false");
  }

  bool _isMeetingEnded(String status) {
    var result = false;

    if (Platform.isAndroid)
      result = status == "MEETING_STATUS_DISCONNECTING" ||
          status == "MEETING_STATUS_FAILED";
    else
      result = status == "MEETING_STATUS_IDLE";

    return result;
  }

  @override
  Widget build(BuildContext context) {
    // Use the Todo to create the UI.
    return Scaffold(
      appBar: AppBar(
        title: Text('Loading meeting '),
      ),
      body: Padding(
          padding: EdgeInsets.all(16.0),
          child: ZoomView(onViewCreated: (controller) {
            print("Created the view");

            controller.initZoom(this.zoomOptions).then((results) {
              print("initialised");
              print(results);

              if (results[0] == 0) {
                controller.zoomStatusEvents.listen((status) {
                  print("Meeting Status Stream: " +
                      status[0] +
                      " - " +
                      status[1]);
                  if (_isMeetingEnded(status[0])) {
                    Navigator.pop(context);
                    timer?.cancel();
                  }
                });

                print("listen on event channel");

                controller
                    .startMeeting(this.meetingOptions)
                    .then((joinMeetingResult) {
                  timer = Timer.periodic(new Duration(seconds: 2), (timer) {
                    controller
                        .meetingStatus(this.meetingOptions.meetingId)
                        .then((status) {
                      print("Meeting Status Polling: " +
                          status[0] +
                          " - " +
                          status[1]);
                    });
                  });
                });
              }
            }).catchError((error) {
              print("Error");
              print(error);
            });
          })),
    );
  }
}
</code>```

答:
A final field is a field that can't be reassigned; this means you have to give it a value and never change that value again.

To make a field final, use the final keyword:

class StartMeetingWidget extends StatelessWidget {
  final ZoomOptions zoomOptions;
  final ZoomMeetingOptions meetingOptions;

  final Timer timer;
```
<p>This poses a problem, because you assign these variables on different points.</p>
<p>Both the <code>ZoomOptions</code> and <code>ZoomMeetingOptions</code> variables get assigned when you create the object, this isn't wrong per se, but you are doing it on the body, which you shouldn't do, instead, use the space before the body (sorry, don't know what to call it):</p>
```StartMeetingWidget({Key key, meetingId})
  : zoomOptions = new ZoomOptions(
    domain: "zoom.us",
    appKey: "appKey",
    appSecret: "appSecret",
  ),
  meetingOptions = new ZoomMeetingOptions(
      userId: '<zoom_user_id>',
      displayName: 'Example display Name',
      meetingId: meetingId,
      zoomAccessToken: "<User zak>",
      zoomToken: "<user_token>",
      disableDialIn: "true",
      disableDrive: "true",
      disableInvite: "true",
      disableShare: "true",
      noAudio: "false",
      noDisconnectAudio: "false"),
  super(key: key);
```
<p>The real problem is <code>timer</code>. You assign timer on some callback into your class, I am not terribly sure what purpose it serves, but it doesn't seem like you can move this assignment to some other place. This means you are going to have to either live with the warning you are getting, or use a <code>StatefulWidget</code>:</p>
```class StartMeetingWidget extends StatefulWidget {
  final ZoomOptions zoomOptions;
  final ZoomMeetingOptions meetingOptions;

StartMeetingWidget({Key key, meetingId})
  : zoomOptions = new ZoomOptions(
    domain: "zoom.us",
    appKey: "appKey",
    appSecret: "appSecret",
  ),
  meetingOptions = new ZoomMeetingOptions(
      userId: '<zoom_user_id>',
      displayName: 'Example display Name',
      meetingId: meetingId,
      zoomAccessToken: "<User zak>",
      zoomToken: "<user_token>",
      disableDialIn: "true",
      disableDrive: "true",
      disableInvite: "true",
      disableShare: "true",
      noAudio: "false",
      noDisconnectAudio: "false"),
  super(key: key);

  @override
  _StartMeetingWidgetState createState() => _StartMeetingWidgetState();
}

class _StartMeetingWidgetState extends State<StartMeetingWidget> {
  Timer timer;

  @override
  Widget build(BuildContext context) {
    ...
  }
}
```

If you make the above changes, you will also have to change every reference to this.zoomOptions and this.meetingOptions into widget.zoomOptions and widget.meetingOptions.

Body:
I' ve downloaded this plugin recently and I tried to open example file. However I was getting these errors

*This class (or a class that this class inherits from) is marked as '@immutable', but one or more of its instance fields aren't final: StartMeetingWidget.zoomOptions, StartMeetingWidget.meetingOptions, StartMeetingWidget.timer

    class StartMeetingWidget extends StatelessWidget {
  ZoomOptions zoomOptions;
  ZoomMeetingOptions meetingOptions;

  Timer timer;

  StartMeetingWidget({Key key, meetingId}) : super(key: key) {
    this.zoomOptions = new ZoomOptions(
      domain: "zoom.us",
      appKey: "appKey",
      appSecret: "appSecret",
    );
    this.meetingOptions = new ZoomMeetingOptions(
        userId: '<zoom_user_id>',
        displayName: 'Example display Name',
        meetingId: meetingId,
        zoomAccessToken: "<User zak>",
        zoomToken: "<user_token>",
        disableDialIn: "true",
        disableDrive: "true",
        disableInvite: "true",
        disableShare: "true",
        noAudio: "false",
        noDisconnectAudio: "false");
  }

  bool _isMeetingEnded(String status) {
    var result = false;

    if (Platform.isAndroid)
      result = status == "MEETING_STATUS_DISCONNECTING" ||
          status == "MEETING_STATUS_FAILED";
    else
      result = status == "MEETING_STATUS_IDLE";

    return result;
  }

  @override
  Widget build(BuildContext context) {
    // Use the Todo to create the UI.
    return Scaffold(
      appBar: AppBar(
        title: Text('Loading meeting '),
      ),
      body: Padding(
          padding: EdgeInsets.all(16.0),
          child: ZoomView(onViewCreated: (controller) {
            print("Created the view");

            controller.initZoom(this.zoomOptions).then((results) {
              print("initialised");
              print(results);

              if (results[0] == 0) {
                controller.zoomStatusEvents.listen((status) {
                  print("Meeting Status Stream: " +
                      status[0] +
                      " - " +
                      status[1]);
                  if (_isMeetingEnded(status[0])) {
                    Navigator.pop(context);
                    timer?.cancel();
                  }
                });

                print("listen on event channel");

                controller
                    .startMeeting(this.meetingOptions)
                    .then((joinMeetingResult) {
                  timer = Timer.periodic(new Duration(seconds: 2), (timer) {
                    controller
                        .meetingStatus(this.meetingOptions.meetingId)
                        .then((status) {
                      print("Meeting Status Polling: " +
                          status[0] +
                          " - " +
                          status[1]);
                    });
                  });
                });
              }
            }).catchError((error) {
              print("Error");
              print(error);
            });
          })),
    );
  }
}

Body:
A final field is a field that can't be reassigned; this means you have to give it a value and never change that value again.

To make a field final, use the final keyword:

class StartMeetingWidget extends StatelessWidget {
  final ZoomOptions zoomOptions;
  final ZoomMeetingOptions meetingOptions;

  final Timer timer;

This poses a problem, because you assign these variables on different points.

Both the ZoomOptions and ZoomMeetingOptions variables get assigned when you create the object, this isn't wrong per se, but you are doing it on the body, which you shouldn't do, instead, use the space before the body (sorry, don't know what to call it):

StartMeetingWidget({Key key, meetingId})
  : zoomOptions = new ZoomOptions(
    domain: "zoom.us",
    appKey: "appKey",
    appSecret: "appSecret",
  ),
  meetingOptions = new ZoomMeetingOptions(
      userId: '<zoom_user_id>',
      displayName: 'Example display Name',
      meetingId: meetingId,
      zoomAccessToken: "<User zak>",
      zoomToken: "<user_token>",
      disableDialIn: "true",
      disableDrive: "true",
      disableInvite: "true",
      disableShare: "true",
      noAudio: "false",
      noDisconnectAudio: "false"),
  super(key: key);

The real problem is timer. You assign timer on some callback into your class, I am not terribly sure what purpose it serves, but it doesn't seem like you can move this assignment to some other place. This means you are going to have to either live with the warning you are getting, or use a StatefulWidget:

class StartMeetingWidget extends StatefulWidget {
  final ZoomOptions zoomOptions;
  final ZoomMeetingOptions meetingOptions;

StartMeetingWidget({Key key, meetingId})
  : zoomOptions = new ZoomOptions(
    domain: "zoom.us",
    appKey: "appKey",
    appSecret: "appSecret",
  ),
  meetingOptions = new ZoomMeetingOptions(
      userId: '<zoom_user_id>',
      displayName: 'Example display Name',
      meetingId: meetingId,
      zoomAccessToken: "<User zak>",
      zoomToken: "<user_token>",
      disableDialIn: "true",
      disableDrive: "true",
      disableInvite: "true",
      disableShare: "true",
      noAudio: "false",
      noDisconnectAudio: "false"),
  super(key: key);

  @override
  _StartMeetingWidgetState createState() => _StartMeetingWidgetState();
}

class _StartMeetingWidgetState extends State<StartMeetingWidget> {
  Timer timer;

  @override
  Widget build(BuildContext context) {
    ...
  }
}

If you make the above changes, you will also have to change every reference to this.zoomOptions and this.meetingOptions into widget.zoomOptions and widget.meetingOptions.


问:
Playbook 'hangs' when running a Python script that launches another Windows process
I'm having an issue when running a Python script using the win_command module. The playbook execution hangs indefinitely when the Python script starts a Tomcat process which is supposed to keep running even once the script completes. If I were to manually kill the Tomcat process, the Ansible playbook completes.

---
- name: Restore product
  win_command: 'python restore-product.py'
  args:
    chdir: C:\temp
```
<p>I have tried the following within the Python script hoping that Ansible would not be able to track the launched process, but have had no luck:</p>
<pre class="lang-py prettyprint-override"><code>subprocess.Popen('start /cmd /c service.bat startup', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

sys.exit(0)
</code>```

答:
Do not use Python's popen function and rather go for spawn() as described here:
https://stackoverflow.com/a/1196122/4222206</p>

Body:
I'm having an issue when running a Python script using the win_command module. The playbook execution hangs indefinitely when the Python script starts a Tomcat process which is supposed to keep running even once the script completes. If I were to manually kill the Tomcat process, the Ansible playbook completes.

---
- name: Restore product
  win_command: 'python restore-product.py'
  args:
    chdir: C:\temp

I have tried the following within the Python script hoping that Ansible would not be able to track the launched process, but have had no luck:

subprocess.Popen('start /cmd /c service.bat startup', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

sys.exit(0)


问:
how to use discord.py to put a custom prescense on a users account?
I want to make a program that shows the current song playing on a users (mine) apple music app on MacOS and display the info in the users' discord presence (not on a bot account), similar to the Spotify integration. However, all of the docs I'm reading for how to use discord.py, it only talks about using it with a bot, and I cannot find how to just use it for the user. I may not be looking in the right place but I'm not sure. Is there a way to just use it with a user, or do you need a bot to use discord.py?

I'm kinda dumb so sorry in advance and please help.

答:
Do it how you would normally with a bot, but replace the bot's token with your own. Make sure you're using discord.py and not a fork, as not all forks support selfbots.

```<code>client.run("Your Token, not a bots")
</code>```

Body:
Do it how you would normally with a bot, but replace the bot's token with your own. Make sure you're using discord.py and not a fork, as not all forks support selfbots.

client.run("Your Token, not a bots")


问:
how to use dcc.Store() for dictionary of dataframe
I have been struggling for one day already. Can anyone help me?

I have a dictionary to store lots of dataframes, ie. dict1={'key1':df1,'key2':df2,'key3':df3}

Now I am using dcc.Store() to share these dictionary data between callbacks.

firstly, I store the dictionary into dcc.Store() using json.dumps(dict1), then I got an error of TypeError: Object of type DataFrame is not JSON serializable.

so how do I store dictionary of dataframe into dcc.Store()? do I have to convert all the dataframe before putting them into the dictionary? It will re-work all my codes. Is it possible to do it without converting each dataframe to json and just work on the dictionary?

Thank you so much for your help. I really appreciate it.

```<code>
@app.callback(
    [
    Output('stored-shared-data-time-dict','data'),
    [
    Input('load-area-data','n_clicks'),
    ],

    prevent_initial_call=True,   # disable output in the first load
)
def change_area_data(n_clicks):  #radio_value,range_slider_values

    s1=json.dumps(dict1)
    return s1

</code>```

then, I am loading the dictionary from dcc.Store().

```<code>
@app.callback(
    [
        Output("timeplot-graph", "figure"),
        Output("timeplot-markdown", "children"),
    ],
    [
        Input("plot-well-prod", "n_clicks"),
    ],
    [
        State('stored-shared-data-time-dict','data'),
    ],

    prevent_initial_call=True,   # disable output in the first load
)

def change_well_time_graphs(n_clicks,well_cell, well_data,json_dict):

    df = json.loads(json_dict)

    (fig,markdown_text)=make_graph(df)

    print('Done Creating Graphes')

    return (fig,markdown_text)

</code>```

答:
The error TypeError: Object of type DataFrame is not JSON serializable means you need to convert your dataframe into something that is JSON-compatible (e.g. a dictionary). Then, you will need to pass into dcc.Store() a tuple or a list of that json-serializable object (e.g. a list of a dict). Once you want to read that dataframe in another callback, you just convert the dcc.Store object back into a dataframe. Here is an example of how you could do this in your code:

@app.callback(
    [Output('stored-shared-data-time-dict','data')],
    [Input('load-area-data','n_clicks')]
    , prevent_initial_call=True,   # disable output in the first load

)
def change_area_data(n_clicks):  #radio_value,range_slider_values
    s1 = [df.to_dict()]
    return s1

@app.callback(
    [
        Output("timeplot-graph", "figure"),
        Output("timeplot-markdown", "children"),
    ],
    [
        Input("plot-well-prod", "n_clicks"),
    ],
    [
        State('stored-shared-data-time-dict','data'),
    ], prevent_initial_call=True,   # disable output in the first load
)
def change_well_time_graphs(n_clicks,well_cell, well_data,json_dict):
    df = pd.DataFrame.from_dict(json_dict, orient='index')
    (fig,markdown_text)=make_graph(df)
    print('Done Creating Graphes')

    return (fig,markdown_text)
```
<p>EDIT:
In the case of having a dictionary of dataframes that you wish to store in a <code>dcc.Store</code>, then the same approach applies but by doing this for each dataframe in the dictionary, then sending the dict to the store, then iterating through each dictionary in the callback and converting that back into a dataframe, here's an example of that for your code:</p>
<pre class="lang-py prettyprint-override"><code>@app.callback(
    [Output('stored-shared-data-time-dict','data')],
    [Input('load-area-data','n_clicks')]
    , prevent_initial_call=True,   # disable output in the first load

)
def change_area_data(n_clicks):  #radio_value,range_slider_values
    temp_dict = dict1
    for key, df in temp_dict.items():
        temp_dict[key] = df.to_dict()
    return [temp_dict]

@app.callback(
    [
        Output("timeplot-graph", "figure"),
        Output("timeplot-markdown", "children"),
    ],
    [
        Input("plot-well-prod", "n_clicks"),
    ],
    [
        State('stored-shared-data-time-dict','data'),
    ], prevent_initial_call=True,   # disable output in the first load
)
def change_well_time_graphs(n_clicks,well_cell, well_data,json_dict):
    df_list = []
    for _, dic in json_dict.items():
        df_list.append(pd.DataFrame.from_dict(dic, orient='index'))
    # the rest of your logic using the list of df's "df_list"
    .
    .
    .
    return (fig,markdown_text)
</code>```

Body:
I have been struggling for one day already. Can anyone help me?

I have a dictionary to store lots of dataframes, ie. dict1={'key1':df1,'key2':df2,'key3':df3}

Now I am using dcc.Store() to share these dictionary data between callbacks.

firstly, I store the dictionary into dcc.Store() using json.dumps(dict1), then I got an error of TypeError: Object of type DataFrame is not JSON serializable.

so how do I store dictionary of dataframe into dcc.Store()? do I have to convert all the dataframe before putting them into the dictionary? It will re-work all my codes. Is it possible to do it without converting each dataframe to json and just work on the dictionary?

Thank you so much for your help. I really appreciate it.

@app.callback(
    [
    Output('stored-shared-data-time-dict','data'),
    [
    Input('load-area-data','n_clicks'),
    ],

    prevent_initial_call=True,   # disable output in the first load
)
def change_area_data(n_clicks):  #radio_value,range_slider_values

    s1=json.dumps(dict1)
    return s1

then, I am loading the dictionary from dcc.Store().

@app.callback(
    [
        Output("timeplot-graph", "figure"),
        Output("timeplot-markdown", "children"),
    ],
    [
        Input("plot-well-prod", "n_clicks"),
    ],
    [
        State('stored-shared-data-time-dict','data'),
    ],

    prevent_initial_call=True,   # disable output in the first load
)

def change_well_time_graphs(n_clicks,well_cell, well_data,json_dict):

    df = json.loads(json_dict)

    (fig,markdown_text)=make_graph(df)

    print('Done Creating Graphes')

    return (fig,markdown_text)

Body:
The error TypeError: Object of type DataFrame is not JSON serializable means you need to convert your dataframe into something that is JSON-compatible (e.g. a dictionary). Then, you will need to pass into dcc.Store() a tuple or a list of that json-serializable object (e.g. a list of a dict). Once you want to read that dataframe in another callback, you just convert the dcc.Store object back into a dataframe. Here is an example of how you could do this in your code:

@app.callback(
    [Output('stored-shared-data-time-dict','data')],
    [Input('load-area-data','n_clicks')]
    , prevent_initial_call=True,   # disable output in the first load

)
def change_area_data(n_clicks):  #radio_value,range_slider_values
    s1 = [df.to_dict()]
    return s1

@app.callback(
    [
        Output("timeplot-graph", "figure"),
        Output("timeplot-markdown", "children"),
    ],
    [
        Input("plot-well-prod", "n_clicks"),
    ],
    [
        State('stored-shared-data-time-dict','data'),
    ], prevent_initial_call=True,   # disable output in the first load
)
def change_well_time_graphs(n_clicks,well_cell, well_data,json_dict):
    df = pd.DataFrame.from_dict(json_dict, orient='index')
    (fig,markdown_text)=make_graph(df)
    print('Done Creating Graphes')

    return (fig,markdown_text)

EDIT:
In the case of having a dictionary of dataframes that you wish to store in a dcc.Store, then the same approach applies but by doing this for each dataframe in the dictionary, then sending the dict to the store, then iterating through each dictionary in the callback and converting that back into a dataframe, here's an example of that for your code:

@app.callback(
    [Output('stored-shared-data-time-dict','data')],
    [Input('load-area-data','n_clicks')]
    , prevent_initial_call=True,   # disable output in the first load

)
def change_area_data(n_clicks):  #radio_value,range_slider_values
    temp_dict = dict1
    for key, df in temp_dict.items():
        temp_dict[key] = df.to_dict()
    return [temp_dict]

@app.callback(
    [
        Output("timeplot-graph", "figure"),
        Output("timeplot-markdown", "children"),
    ],
    [
        Input("plot-well-prod", "n_clicks"),
    ],
    [
        State('stored-shared-data-time-dict','data'),
    ], prevent_initial_call=True,   # disable output in the first load
)
def change_well_time_graphs(n_clicks,well_cell, well_data,json_dict):
    df_list = []
    for _, dic in json_dict.items():
        df_list.append(pd.DataFrame.from_dict(dic, orient='index'))
    # the rest of your logic using the list of df's "df_list"
    .
    .
    .
    return (fig,markdown_text)


问:
What are practical uses of applicative style?
I am a Scala programmer, learning Haskell now. It's easy to find practical use cases and real world examples for OO concepts, such as decorators, strategy pattern etc. Books and interwebs are filled with it.

I came to the realization that this somehow is not the case for functional concepts. Case in point: applicatives.

I am struggling to find practical use cases for applicatives. Almost all of the tutorials and books I have come across so far provide the examples of [] and Maybe. I expected applicatives to be more applicable than that, seeing all the attention they get in the FP community.

I think I understand the conceptual basis for applicatives (maybe I am wrong), and I have waited long for my moment of enlightenment. But it doesn't seem to be happening. Never while programming, have I had a moment when I would shout with a joy, "Eureka! I can use applicative here!" (except again, for [] and Maybe).

Can someone please guide me how applicatives can be used in a day-to-day programming? How do I start spotting the pattern? Thanks!

答:
Applicatives are great when you've got a plain old function of several variables, and you have the arguments but they're wrapped up in some kind of context. For instance, you have the plain old concatenate function (++) but you want to apply it to 2 strings which were acquired through I/O. Then the fact that IO is an applicative functor comes to the rescue:

Prelude Control.Applicative> (++) <$> getLine <*> getLine
hi
there
"hithere"
```

<p>Even though you explicitly asked for non-<code>Maybe</code> examples, it seems like a great use case to me, so I'll give an example. You have a regular function of several variables, but you don't know if you have all the values you need (some of them may have failed to compute, yielding <code>Nothing</code>). So essentially because you have "partial values", you want to turn your function into a partial function, which is undefined if any of its inputs is undefined. Then</p>

<pre class="lang-hs prettyprint-override"><code>Prelude Control.Applicative> (+) <$> Just 3 <*> Just 5
Just 8
</code>```

but

Prelude Control.Applicative> (+) <$> Just 3 <*> Nothing
Nothing
```

which is exactly what you want.

The basic idea is that you're "lifting" a regular function into a context where it can be applied to as many arguments as you like. The extra power of Applicative over just a basic Functor is that it can lift functions of arbitrary arity, whereas fmap can only lift a unary function.

Body:
Applicatives are great when you've got a plain old function of several variables, and you have the arguments but they're wrapped up in some kind of context. For instance, you have the plain old concatenate function (++) but you want to apply it to 2 strings which were acquired through I/O. Then the fact that IO is an applicative functor comes to the rescue:

Prelude Control.Applicative> (++) <$> getLine <*> getLine
hi
there
"hithere"

Even though you explicitly asked for non-Maybe examples, it seems like a great use case to me, so I'll give an example. You have a regular function of several variables, but you don't know if you have all the values you need (some of them may have failed to compute, yielding Nothing). So essentially because you have "partial values", you want to turn your function into a partial function, which is undefined if any of its inputs is undefined. Then

Prelude Control.Applicative> (+) <$> Just 3 <*> Just 5
Just 8

but

Prelude Control.Applicative> (+) <$> Just 3 <*> Nothing
Nothing

which is exactly what you want.

The basic idea is that you're "lifting" a regular function into a context where it can be applied to as many arguments as you like. The extra power of Applicative over just a basic Functor is that it can lift functions of arbitrary arity, whereas fmap can only lift a unary function.


问:
Powershell Code from Script Runs Within a PowerShell ISE Session - The Script myscript.ps1 does not run from PS>myscript.ps1
When I launch a powershell session via powershell.exe and at the PS> prompt enter myscript.ps1 it errors with -
PS D:\TEST> D:\TEST\testrun.ps1

Missing ')' in method call.

At D:\TEST\testrun.ps1:1 char:65

$factory = [System.Data.Common.DbProviderFactories]::GetFactory( <<<< â?oIBM.
Data.DB2â??)

CategoryInfo          : ParserError: (CloseParenToken:TokenId) [], Parse
Exception

FullyQualifiedErrorId : MissingEndParenthesisInMethodCall

What is the reason for it working when running the lines of code individually via CutNPaste into ISE and launching?  I receive the email with a nice table from the db extraction when I run it via ISE. This error is probably why it doesn't run in TaskScheduler as well.

```<code>
$factory = [System.Data.Common.DbProviderFactories]::GetFactory(“IBM.Data.DB2”)
$cstrbld = $factory.CreateConnectionStringBuilder()
$cstrbld.Database = 'dbname'
$cstrbld.UserID = 'USER'
$cstrbld.Password = 'password'
$cstrbld.Server = 'server:50001'
$dbconn = $factory.CreateConnection()
$dbconn.ConnectionString = $cstrbld.ConnectionString
$dbconn.Open()
$dbcmd = $factory.CreateCommand()
$dbcmd.Connection = $dbconn
########################################################################################################################################
$dbcmd.CommandText = 'SELECT PFIWORKUNIT,ACTOR,FLOWDEFINITION,WORKTITLE,STATUS FROM APPLICATION.PFIWORKUNIT WHERE STATUS BETWEEN 0 AND 3'
########################################################################################################################################

$dbcmd.CommandType = [System.Data.CommandType]::Text
$da = $factory.CreateDataAdapter()
$da.SelectCommand = $dbcmd
$ds = New-Object System.Data.DataSet
$da.Fill($ds) | Out-Null

$dbconn.Close()

     ForEach ($row in $ds.Tables[0].Rows) {

        $ExciterObject = New-Object PSObject
        $ExciterObject | Add-Member -MemberType NoteProperty -Name "PFIWORKUNIT" -Value $row.PFIWORKUNIT
        $ExciterObject | Add-Member -MemberType NoteProperty -Name "ACTOR" -Value $row.ACTOR
        $ExciterObject | Add-Member -MemberType NoteProperty -Name "FLOWDEFINITION" -Value $row.FLOWDEFINITION
        $ExciterObject | Add-Member -MemberType NoteProperty -Name "WORKTITLE" -Value $row.WORKTITLE
        $ExciterObject | Add-Member -MemberType NoteProperty -Name "STATUS" -Value $row.STATUS
        $exportObject += $ExciterObject

        }

        function ConvertTo-HTMLTable ($obj) {
    # Accepts a System.Data.DataTable object or an array of PSObjects and converts to styled HTML table

    # add type needed to replace HTML special characters into entities
    Add-Type -AssemblyName System.Web

    $sb = New-Object -TypeName System.Text.StringBuilder
    [void]$sb.AppendLine('<table>')
    if ($null -ne $obj) {
        if (([object]$obj).GetType().FullName -eq 'System.Data.DataTable'){
            # it is a DataTable; convert to array of PSObjects
            $obj = $obj | Select-Object * -ExcludeProperty ItemArray, Table, RowError, RowState, HasErrors
        }
        $headers = $obj[0].PSObject.Properties | Select -ExpandProperty Name
        [void]$sb.AppendLine('<thead><tr>')
        foreach ($column in $headers) {
            [void]$sb.AppendLine(('<th>{0}</th>' -f [System.Web.HttpUtility]::HtmlEncode($column)))
        }
        [void]$sb.AppendLine('</tr></thead><tbody>')
        $row = 0
        $obj | ForEach-Object {
            # add inline style for zebra color rows
            if ($row++ -band 1) {
                $tr = '<tr style="background-color: {0};">' -f $oddRowBackColor
            }
            else {
                $tr = '<tr>'
            }
            [void]$sb.AppendLine($tr)
            foreach ($column in $headers) {
                [string]$val = $($_.$column)
                #If($NameAd -ne "")
                if ($val -notmatch "\S") {
                    $td = '<td> </td>'
                }

                else {
                    $td = '<td>{0}</td>' -f [System.Web.HttpUtility]::HtmlEncode($val)
                }
                [void]$sb.Append($td)
            }
            [void]$sb.AppendLine('</tr>')
        }

        [void]$sb.AppendLine('</tbody>')
    }
    [void]$sb.AppendLine('</table>')

    return $sb.ToString()
}

$headerBackColor = '#4F81BD'  # backgroundcolor for column headers
$oddRowBackColor = '#DCE6F1'  # background color for odd rows

$style = @"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Report</title>
    <meta name="generator" content="PowerShell" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style type="text/css">
    body {
        font-family: Verdana, Arial, Geneva, Helvetica, sans-serif;
        font-size: 12px;
        color: black;
    }

    table, td, th {
        border-color: black;
        border-style: solid;
        font-family: Verdana, Arial, Geneva, Helvetica, sans-serif;
        font-size: 11px;
    }
    table {
        border-width: 0 0 1px 1px;
        border-spacing: 0;
        border-collapse: collapse;
    }

    td, th {
        margin: 0;
        padding: 4px;
        border-width: 1px 1px 0 0;
        text-align: left;
    }
    th {
        color: white;
        background-color: $headerBackColor;
        font-weight: bold;
    }
    </style>

<p><span style="color: #0000ff;"><strong>I'm only pulling only 1 thru 3 for a short email list</strong></span></p>
<p><span style="color: #0000ff;"><strong>WORK UNIT STATUS LEVELS BELOW:</strong></span></p>
<ol>
<li>01 = (<span style="color: #3366ff;"><strong>Ready for processing</strong></span>) using your SA account.</li>
<li>02 = (<span style="color: #3366ff;"><strong>Processing in progresst</strong></span>) using your SA account.</li>
<li>03 = (<span style="color: #3366ff;"><strong>Processing failed</strong></span>) using your SA account.</li>
<li>04 = (<span style="color: #3366ff;"><strong>Processing completed</strong></span>) using your SA account.</li>
<li>05 = (<span style="color: #3366ff;"><strong>Cancellation requested</strong></span>) using your SA account.</li>
<li>06 = (<span style="color: #3366ff;"><strong>Cancellation in progress</strong></span>) using your SA account.</li>
<li>07 = (<span style="color: #3366ff;"><strong>Cancellation failed</strong></span>) using your SA account.</li>
<li>08 = (<span style="color: #3366ff;"><strong>Cancellation completed</strong></span>) using your SA account.</li>
</ol>
"@
####SET EMAIL VALUES####
$bodyA = '{0}</head><body>{1}</body></html>' -f $style, (ConvertTo-HTMLTable $exportObject)
$EmailTo = "you@you.org"
$EmailFrom = "me@me.org"
$Subject = "Failed Work Unit Issue - High Priority"
$Body = $bodyA
$SMTPServer = "mail.server.org"

####EMAIL PROCESS ####
$anonUsername = "anonymous"
$anonPassword = ConvertTo-SecureString -String "anonymous" -AsPlainText -Force
$anonCredentials = New-Object System.Management.Automation.PSCredential($anonUsername,$anonPassword)
Send-MailMessage -smtpserver "$SMTPServer" -from "$EmailFrom" -to "$EmailTo" -subject "$Subject" -bodyAsHtml "$Body" -credential $anonCredentials
Exit

</code>```

答:
The quotes in the below section aren't standard, so the compiler is interpreting them as other characters.

```<code>$factory = [System.Data.Common.DbProviderFactories]::GetFactory(“IBM.Data.DB2”)
</code>```

Note a regular ascii double quote is "034", but if you copy and paste one of the quote symbols from above into an ascii converter you'll get "226 128 156" as the ascii code instead.

TL;DR watch out for symbols that look a lot like the one you think you're using but aren't.

Body:
When I launch a powershell session via powershell.exe and at the PS> prompt enter myscript.ps1 it errors with -
PS D:\TEST> D:\TEST\testrun.ps1

Missing ')' in method call.

At D:\TEST\testrun.ps1:1 char:65

$factory = [System.Data.Common.DbProviderFactories]::GetFactory( <<<< â?oIBM.
Data.DB2â??)

CategoryInfo          : ParserError: (CloseParenToken:TokenId) [], Parse
Exception

FullyQualifiedErrorId : MissingEndParenthesisInMethodCall

What is the reason for it working when running the lines of code individually via CutNPaste into ISE and launching?  I receive the email with a nice table from the db extraction when I run it via ISE. This error is probably why it doesn't run in TaskScheduler as well.

$factory = [System.Data.Common.DbProviderFactories]::GetFactory(“IBM.Data.DB2”)
$cstrbld = $factory.CreateConnectionStringBuilder()
$cstrbld.Database = 'dbname'
$cstrbld.UserID = 'USER'
$cstrbld.Password = 'password'
$cstrbld.Server = 'server:50001'
$dbconn = $factory.CreateConnection()
$dbconn.ConnectionString = $cstrbld.ConnectionString
$dbconn.Open()
$dbcmd = $factory.CreateCommand()
$dbcmd.Connection = $dbconn
########################################################################################################################################
$dbcmd.CommandText = 'SELECT PFIWORKUNIT,ACTOR,FLOWDEFINITION,WORKTITLE,STATUS FROM APPLICATION.PFIWORKUNIT WHERE STATUS BETWEEN 0 AND 3'
########################################################################################################################################

$dbcmd.CommandType = [System.Data.CommandType]::Text
$da = $factory.CreateDataAdapter()
$da.SelectCommand = $dbcmd
$ds = New-Object System.Data.DataSet
$da.Fill($ds) | Out-Null

$dbconn.Close()

     ForEach ($row in $ds.Tables[0].Rows) {

        $ExciterObject = New-Object PSObject
        $ExciterObject | Add-Member -MemberType NoteProperty -Name "PFIWORKUNIT" -Value $row.PFIWORKUNIT
        $ExciterObject | Add-Member -MemberType NoteProperty -Name "ACTOR" -Value $row.ACTOR
        $ExciterObject | Add-Member -MemberType NoteProperty -Name "FLOWDEFINITION" -Value $row.FLOWDEFINITION
        $ExciterObject | Add-Member -MemberType NoteProperty -Name "WORKTITLE" -Value $row.WORKTITLE
        $ExciterObject | Add-Member -MemberType NoteProperty -Name "STATUS" -Value $row.STATUS
        $exportObject += $ExciterObject

        }

        function ConvertTo-HTMLTable ($obj) {
    # Accepts a System.Data.DataTable object or an array of PSObjects and converts to styled HTML table

    # add type needed to replace HTML special characters into entities
    Add-Type -AssemblyName System.Web

    $sb = New-Object -TypeName System.Text.StringBuilder
    [void]$sb.AppendLine('
')
    if ($null -ne $obj) {
        if (([object]$obj).GetType().FullName -eq 'System.Data.DataTable'){
            # it is a DataTable; convert to array of PSObjects
            $obj = $obj | Select-Object * -ExcludeProperty ItemArray, Table, RowError, RowState, HasErrors
        }
        $headers = $obj[0].PSObject.Properties | Select -ExpandProperty Name
        [void]$sb.AppendLine('

')
        foreach ($column in $headers) {
            [void]$sb.AppendLine(('{0}	' -f [System.Web.HttpUtility]::HtmlEncode($column)))
        }
        [void]$sb.AppendLine('

')
        $row = 0
        $obj | ForEach-Object {
            # add inline style for zebra color rows
            if ($row++ -band 1) {
                $tr = '
' -f $oddRowBackColor
            }
            else {
                $tr = '
'
            }
            [void]$sb.AppendLine($tr)
            foreach ($column in $headers) {
                [string]$val = $($_.$column)
                #If($NameAd -ne "")
                if ($val -notmatch "\S") {
                    $td = ' 	'
                }

                else {
                    $td = '{0}	' -f [System.Web.HttpUtility]::HtmlEncode($val)
                }
                [void]$sb.Append($td)
            }
            [void]$sb.AppendLine('
')
        }

        [void]$sb.AppendLine('
')
    }
    [void]$sb.AppendLine('
')

    return $sb.ToString()
}

$headerBackColor = '#4F81BD'  # backgroundcolor for column headers
$oddRowBackColor = '#DCE6F1'  # background color for odd rows

$style = @"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Report</title>
    <meta name="generator" content="PowerShell" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

I'm only pulling only 1 thru 3 for a short email list

WORK UNIT STATUS LEVELS BELOW:

01 = (Ready for processing) using your SA account.

02 = (Processing in progresst) using your SA account.

03 = (Processing failed) using your SA account.

04 = (Processing completed) using your SA account.

05 = (Cancellation requested) using your SA account.

06 = (Cancellation in progress) using your SA account.

07 = (Cancellation failed) using your SA account.

08 = (Cancellation completed) using your SA account.

"@
####SET EMAIL VALUES####
$bodyA = '{0}{1}' -f $style, (ConvertTo-HTMLTable $exportObject)
$EmailTo = "you@you.org"
$EmailFrom = "me@me.org"
$Subject = "Failed Work Unit Issue - High Priority"
$Body = $bodyA
$SMTPServer = "mail.server.org"

####EMAIL PROCESS ####
$anonUsername = "anonymous"
$anonPassword = ConvertTo-SecureString -String "anonymous" -AsPlainText -Force
$anonCredentials = New-Object System.Management.Automation.PSCredential($anonUsername,$anonPassword)
Send-MailMessage -smtpserver "$SMTPServer" -from "$EmailFrom" -to "$EmailTo" -subject "$Subject" -bodyAsHtml "$Body" -credential $anonCredentials
Exit

Body:
The quotes in the below section aren't standard, so the compiler is interpreting them as other characters.

$factory = [System.Data.Common.DbProviderFactories]::GetFactory(“IBM.Data.DB2”)

Note a regular ascii double quote is "034", but if you copy and paste one of the quote symbols from above into an ascii converter you'll get "226 128 156" as the ascii code instead.

TL;DR watch out for symbols that look a lot like the one you think you're using but aren't.